stage) {
+ stage.set("VALIDATE_EXPIRY");
if (command.validUntil < System.currentTimeMillis()) throw new CustomException("执行请求已过期");
+ stage.set("VALIDATE_CONFIGURATION");
UsdtConfig config = configs.selectFirst();
if (config == null || !config.getVersion().equals(command.envelopeVersion)
|| !config.getTronNetType().equals(command.network)) {
throw new CustomException("钱包配置或网络已变化,请重新发起操作");
}
+ stage.set("VALIDATE_BROADCAST_PERMISSION");
if (command.operation == null || !Boolean.TRUE.equals(command.operation.getBroadcast())) {
throw new CustomException("本次操作未确认广播");
}
+ stage.set("VALIDATE_WALLET");
WalletAddressPlus wallet = new WalletAddressPlus();
wallet.setId(command.walletId);
wallet.setToken(command.address);
@@ -174,6 +195,7 @@ public class ChainCommandExecutor {
throw new CustomException("钱包已禁用或派生地址不一致");
}
}
+ stage.set("VALIDATE_BUSINESS_RECORD");
validateBusiness(command);
return wallet;
}
@@ -218,6 +240,10 @@ public class ChainCommandExecutor {
private void requireBudget(ChainCommand command, WalletAddressPlus wallet, ITronService tron, ApiWrapper api) throws Exception {
WalletOperationRequest request = command.operation;
WalletResourceEstimateVo estimate = estimates.estimate(command.type, wallet, request);
+ log.info("链上任务资源估算完成,businessKey={},safeEnergy={},energyGap={},safeBandwidth={},"
+ + "bandwidthGap={},burnRequired={}", command.businessKey,
+ estimate.getSafeEnergy(), estimate.getEnergyGap(), estimate.getSafeBandwidth(),
+ estimate.getBandwidthGap(), estimate.isBurnRequired());
if (Boolean.TRUE.equals(request.getResourceOnly()) && estimate.isBurnRequired()) {
throw new CustomException("当前资源不足,禁止燃烧 TRX");
}
@@ -235,12 +261,19 @@ public class ChainCommandExecutor {
.add(BigDecimal.valueOf(estimate.getBandwidthGap()).multiply(BigDecimal.valueOf(bandwidthFee))).movePointLeft(6);
BigDecimal needed = burn.add(reserve);
if ("trx".equals(command.type) || "stake".equals(command.type)) needed = needed.add(request.getAmount());
- if (tron.getTRxBalance(api, wallet.getToken()).compareTo(needed) < 0) {
+ BigDecimal trxBalance = tron.getTRxBalance(api, wallet.getToken());
+ log.info("链上任务TRX预算复核完成,businessKey={},energyFeeSun={},bandwidthFeeSun={},"
+ + "burnTrx={},reserveTrx={},neededTrx={},availableTrx={}", command.businessKey,
+ energyFee, bandwidthFee, burn.toPlainString(), reserve.toPlainString(), needed.toPlainString(),
+ trxBalance.toPlainString());
+ if (trxBalance.compareTo(needed) < 0) {
throw new CustomException("TRX 余额不足以支付本次操作及资源预算");
}
- if ("usdt".equals(command.type)
- && tron.getUsdtBalance(api, wallet.getToken()).compareTo(request.getAmount()) < 0) {
- throw new CustomException("USDT 余额不足");
+ if ("usdt".equals(command.type)) {
+ BigDecimal usdtBalance = tron.getUsdtBalance(api, wallet.getToken());
+ log.info("链上任务USDT余额复核完成,businessKey={},neededUsdt={},availableUsdt={}",
+ command.businessKey, request.getAmount().toPlainString(), usdtBalance.toPlainString());
+ if (usdtBalance.compareTo(request.getAmount()) < 0) throw new CustomException("USDT 余额不足");
}
}
diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutionStore.java b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutionStore.java
index 8766773..8dde7a2 100644
--- a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutionStore.java
+++ b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutionStore.java
@@ -58,6 +58,22 @@ public class ChainExecutionStore {
+ "where execution_id=? and status='QUEUED'", id) == 1;
}
+ /**
+ * 执行器重启后恢复尚未产生任何签名痕迹的远程任务。
+ *
+ * 交易广播前必须先通过 {@link #signed(String, String, byte[])} 将状态从 RUNNING 原子更新为
+ * SIGNED。即使旧进程仍在退出,只要本方法先将状态改回 QUEUED,旧进程便无法持久化签名并广播;
+ * 若旧进程先写入 SIGNED,本条件也不会命中。因此该恢复不会产生两笔链上交易。
+ *
+ * @return 恢复为 QUEUED 的任务数量
+ */
+ public int requeueUnsignedRemoteExecutions() {
+ return jdbc.update("update usdt_chain_execution set status='QUEUED',"
+ + "error_message='执行器重启,未签名远程任务已重新排队',updated_at=CURRENT_TIMESTAMP "
+ + "where status='RUNNING' and execution_mode='REMOTE' "
+ + "and transaction_id is null and signed_transaction is null");
+ }
+
public void signed(String id, String hash, byte[] transaction) {
if (jdbc.update("update usdt_chain_execution set status='SIGNED',transaction_id=?,signed_transaction=?,"
+ "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='RUNNING'",
@@ -72,9 +88,17 @@ public class ChainExecutionStore {
}
public void failBeforeSigning(String id) {
- // 节点、SDK 异常可能携带敏感上下文,只记录固定文案;SIGNED 永远不改成可重试失败。
- jdbc.update("update usdt_chain_execution set status='FAILED',error_message='执行前校验或签名失败,请检查配置、余额和资源',"
- + "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='RUNNING'", id);
+ failBeforeSigning(id, "UNKNOWN", "UnknownException");
+ }
+
+ /**
+ * 仅记录受控阶段和异常类型,不落库 SDK 异常消息,避免节点响应或钱包上下文泄露。
+ * SIGNED 状态永远不会被此方法改成可重新执行的失败状态。
+ */
+ public void failBeforeSigning(String id, String stage, String errorType) {
+ String diagnostic = "执行前失败,阶段=" + safeDiagnostic(stage) + ",异常类型=" + safeDiagnostic(errorType);
+ jdbc.update("update usdt_chain_execution set status='FAILED',error_message=?,"
+ + "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='RUNNING'", diagnostic, id);
}
/** 仅供原代付链上确认流程调用;已确认失败的交易允许下一次人工执行尝试。 */
@@ -110,4 +134,9 @@ public class ChainExecutionStore {
throw new CustomException("执行指令序列化失败");
}
}
+
+ private String safeDiagnostic(String value) {
+ if (value == null || !value.matches("[A-Za-z0-9_.$-]{1,80}")) return "UNKNOWN";
+ return value;
+ }
}
diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java
index 7d38386..7951762 100644
--- a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java
+++ b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainExecutorClient.java
@@ -10,17 +10,20 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.annotation.Scheduled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
import javax.net.ssl.HttpsURLConnection;
import java.net.URI;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
/** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */
@Component
@@ -36,6 +39,10 @@ public class ChainExecutorClient {
private String tlsCertificateLocation;
@Value("${chain.executor.health-failure-threshold:3}")
private int healthFailureThreshold;
+ @Value("${chain.executor.health-check-interval-ms:10000}")
+ private long healthCheckIntervalMs;
+ @Value("${chain.executor.health-check-initial-delay-ms:10000}")
+ private long healthCheckInitialDelayMs;
@Autowired(required = false)
private ChainExecutorRuntimeState runtimeState;
private RestTemplate http;
@@ -45,6 +52,7 @@ public class ChainExecutorClient {
private volatile int consecutiveFailures;
private volatile long checkedAt;
private volatile String lastDiagnostic = "NOT_CHECKED";
+ private ScheduledExecutorService healthScheduler;
public ChainExecutorClient() {
http = createHttp(null);
@@ -104,6 +112,7 @@ public class ChainExecutorClient {
log.error("内网链上执行器启动验证未通过,支付系统继续启动,远程链上操作暂不可用,诊断={}",
unavailable.getMessage());
}
+ startHealthMonitor();
}
public boolean isEnabled() { return enabled; }
@@ -126,16 +135,24 @@ public class ChainExecutorClient {
}
/** 后台持续探测,即使已自动停用也继续更新“已恢复、待管理员启用”状态。 */
- @Scheduled(fixedDelayString = "${chain.executor.health-check-interval-ms:10000}", initialDelayString = "${chain.executor.health-check-initial-delay-ms:10000}")
public void monitor() {
if (!enabled || !checking.compareAndSet(false, true)) return;
try {
probeNow();
+ } catch (Exception failure) {
+ // 避免状态持久化等外围异常终止后续固定延迟探测。
+ log.error("内网链上执行器后台探测异常,后续仍将继续检查,异常类型={}", rootType(failure));
} finally {
checking.set(false);
}
}
+ /** 页面状态读取同时触发实时探测,“立即检查”不得只返回进程内旧缓存。 */
+ public Map refreshAvailability() {
+ monitor();
+ return availability();
+ }
+
/** 只有实时探测可用时才允许管理员重新打开,避免误启用后立即接受远程任务。 */
public void enableRuntime(String operator) {
if (!probeNow()) throw new com.ruoyi.common.exception.CustomException("执行器尚未恢复,无法启用");
@@ -227,6 +244,30 @@ public class ChainExecutorClient {
}
}
+ /**
+ * 使用独立守护线程执行健康检查,不依赖资源租赁模块是否启用Spring全局调度。
+ */
+ private synchronized void startHealthMonitor() {
+ if (!enabled || healthScheduler != null) return;
+ healthScheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
+ Thread thread = new Thread(runnable, "chain-executor-health-monitor");
+ thread.setDaemon(true);
+ return thread;
+ });
+ healthScheduler.scheduleWithFixedDelay(this::monitor, Math.max(0L, healthCheckInitialDelayMs),
+ Math.max(1000L, healthCheckIntervalMs), TimeUnit.MILLISECONDS);
+ log.info("内网链上执行器后台健康检查已启动,首次延迟={}ms,检查间隔={}ms",
+ Math.max(0L, healthCheckInitialDelayMs), Math.max(1000L, healthCheckIntervalMs));
+ }
+
+ @PreDestroy
+ public synchronized void closeHealthMonitor() {
+ if (healthScheduler == null) return;
+ healthScheduler.shutdownNow();
+ healthScheduler = null;
+ log.info("内网链上执行器后台健康检查已停止");
+ }
+
private static String rootType(Throwable failure) {
Throwable cause = failure;
while (cause.getCause() != null && cause.getCause() != cause) cause = cause.getCause();
diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java
index b73dd8e..4549da5 100644
--- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java
+++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/ChainExecutorController.java
@@ -32,7 +32,8 @@ public class ChainExecutorController {
+ "or @ss.hasPermi('system:usdtTaskItem:edit') or @ss.hasPermi('system:usdtPayoutOrder:execute')")
@GetMapping("/status")
public AjaxResult status() {
- Map result = new LinkedHashMap<>(client.availability());
+ // 页面轮询和“立即检查”都执行实时探测,不能只返回进程内缓存状态。
+ Map result = new LinkedHashMap<>(client.refreshAvailability());
// 明确列出公开字段,禁止 SELECT * 结果进入 HTTP 响应。
boolean rentalEnabled = rentalProperties != null && rentalProperties.isEnabled();
result.put("executions", client.isEnabled() ? store.jdbc().queryForList(rentalEnabled
diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainCommandExecutorTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainCommandExecutorTest.java
index a3e26c5..cafb933 100644
--- a/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainCommandExecutorTest.java
+++ b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainCommandExecutorTest.java
@@ -36,6 +36,7 @@ public class ChainCommandExecutorTest {
private int signedCount;
private int broadcasts;
private boolean acceptBroadcast;
+ private boolean failEstimateWithLinkageError;
private byte[] firstTransaction;
@Before
@@ -70,6 +71,7 @@ public class ChainCommandExecutorTest {
};
WalletOperationEstimateService estimates = new WalletOperationEstimateService(networks) {
@Override public WalletResourceEstimateVo estimate(String type, WalletAddressPlus wallet, WalletOperationRequest request) {
+ if (failEstimateWithLinkageError) throw new NoSuchMethodError("simulated protobuf conflict");
WalletResourceEstimateVo estimate = new WalletResourceEstimateVo();
estimate.setEstimatedBurnTrx(BigDecimal.ZERO);
return estimate;
@@ -108,6 +110,7 @@ public class ChainCommandExecutorTest {
assertEquals(0, signedCount);
assertEquals(0, broadcasts);
assertEquals("FAILED", store.get(id).get("status"));
+ assertTrue(String.valueOf(store.get(id).get("error_message")).contains("阶段=VALIDATE_EXPIRY"));
}
@Test
@@ -141,6 +144,18 @@ public class ChainCommandExecutorTest {
assertEquals(0, broadcasts);
}
+ @Test
+ public void linkageErrorBeforeSigningMarksExecutionFailed() {
+ failEstimateWithLinkageError = true;
+ executor.execute(executionId, "test-only-password");
+ Map result = store.get(executionId);
+ assertEquals("FAILED", result.get("status"));
+ assertTrue(String.valueOf(result.get("error_message")).contains("阶段=ESTIMATE_RESOURCES"));
+ assertTrue(String.valueOf(result.get("error_message")).contains("异常类型=NoSuchMethodError"));
+ assertEquals(0, signedCount);
+ assertEquals(0, broadcasts);
+ }
+
private ChainCommand command() {
ChainCommand command = new ChainCommand();
command.businessKey = "WALLET:test";
diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutionStoreTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutionStoreTest.java
index fe2ff25..e57a1e8 100644
--- a/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutionStoreTest.java
+++ b/ruoyi-system/src/test/java/com/ruoyi/system/chain/ChainExecutionStoreTest.java
@@ -69,6 +69,23 @@ public class ChainExecutionStoreTest {
assertEquals("BROADCASTED", store.get(id).get("status"));
}
+ @Test
+ public void restartRequeuesOnlyUnsignedRemoteRunningExecution() {
+ String unsignedRemote = (String) store.create(command("PAYOUT:unsigned"), true).get("execution_id");
+ String password = (String) store.create(command("PAYOUT:password"), false).get("execution_id");
+ String signedRemote = (String) store.create(command("PAYOUT:signed"), true).get("execution_id");
+ assertTrue(store.claim(unsignedRemote));
+ assertTrue(store.claim(password));
+ assertTrue(store.claim(signedRemote));
+ store.signed(signedRemote, "known-hash", new byte[] {1});
+
+ assertEquals(1, store.requeueUnsignedRemoteExecutions());
+ assertEquals("QUEUED", store.get(unsignedRemote).get("status"));
+ assertEquals("RUNNING", store.get(password).get("status"));
+ assertEquals("SIGNED", store.get(signedRemote).get("status"));
+ assertArrayEquals(new byte[] {1}, (byte[]) store.get(signedRemote).get("signed_transaction"));
+ }
+
@Test
public void failureBeforeSigningCanBeArchivedWithoutLosingAudit() {
String id = (String) store.create(command(), false).get("execution_id");
@@ -105,8 +122,12 @@ public class ChainExecutionStoreTest {
}
private ChainCommand command() {
+ return command("PAYOUT:123");
+ }
+
+ private ChainCommand command(String businessKey) {
ChainCommand command = new ChainCommand();
- command.businessKey = "PAYOUT:123";
+ command.businessKey = businessKey;
command.operatorId = 1L;
command.type = "usdt";
command.operation = new WalletOperationRequest();
diff --git a/usdt-chain-executor/pom.xml b/usdt-chain-executor/pom.xml
index 5db1709..721f103 100644
--- a/usdt-chain-executor/pom.xml
+++ b/usdt-chain-executor/pom.xml
@@ -6,7 +6,20 @@
usdt-chain-executor
仅内网调用的独立链上执行进程
- com.ruoyiruoyi-system
+
+ com.ruoyi
+ ruoyi-system
+
+
+
+ com.google.protobuf
+ protobuf-javalite
+
+
+
com.baomidoumybatis-plus-boot-starter3.4.0
mysqlmysql-connector-java8.0.30
org.springframework.bootspring-boot-starter-jdbc
diff --git a/usdt-chain-executor/src/main/java/com/ruoyi/executor/ChainExecutorApplication.java b/usdt-chain-executor/src/main/java/com/ruoyi/executor/ChainExecutorApplication.java
index 102d9b7..72f353a 100644
--- a/usdt-chain-executor/src/main/java/com/ruoyi/executor/ChainExecutorApplication.java
+++ b/usdt-chain-executor/src/main/java/com/ruoyi/executor/ChainExecutorApplication.java
@@ -43,11 +43,12 @@ public class ChainExecutorApplication {
// 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。
try {
log.info("USDT链上执行器正在启动,运行模式=独立内网执行进程");
+ ProtobufRuntimeValidator.validate();
new SpringApplicationBuilder(ChainExecutorApplication.class).web(WebApplicationType.NONE)
.properties("spring.config.name=executor").run(args);
log.info("USDT链上执行器启动完成");
} catch (Exception ex) {
- log.error("USDT链上执行器启动失败,异常类型={}", ex.getClass().getSimpleName());
+ log.error("USDT链上执行器启动失败,异常类型={},msg {}", ex.getClass().getSimpleName(), ex.getMessage());
System.err.println("内网执行服务启动失败,请检查内网监听、白名单、环境变量、数据库及钱包密码配置");
System.exit(1);
}
diff --git a/usdt-chain-executor/src/main/java/com/ruoyi/executor/IntranetExecutionServer.java b/usdt-chain-executor/src/main/java/com/ruoyi/executor/IntranetExecutionServer.java
index a20ad1f..f907938 100644
--- a/usdt-chain-executor/src/main/java/com/ruoyi/executor/IntranetExecutionServer.java
+++ b/usdt-chain-executor/src/main/java/com/ruoyi/executor/IntranetExecutionServer.java
@@ -89,6 +89,12 @@ public class IntranetExecutionServer {
// 启动校验表结构和解密能力,不执行任何链上广播。
store.jdbc().queryForObject("select count(*) from usdt_chain_execution where 1=0", Long.class);
checkReady();
+ int requeued = store.requeueUnsignedRemoteExecutions();
+ if (requeued > 0) {
+ notified = true;
+ log.warn("执行器启动时恢复未签名远程任务,重新排队数量={};任务将重新校验有效期、余额和资源", requeued);
+ }
+ warnUnfinishedRunningTasks();
log.info("启动检查通过,网络={},允许来源数量={},广播已启用", network, allowed.size());
InetSocketAddress address = new InetSocketAddress(bind, Integer.parseInt(required("CHAIN_EXECUTOR_PORT")));
// 执行器只提供HTTP。需要HTTPS时由同机Nginx终止TLS并转发到回环监听端口。
@@ -160,6 +166,23 @@ public class IntranetExecutionServer {
signing.validateConfigurationPassword(password);
}
+ /**
+ * RUNNING 不允许自动重领,因为旧进程可能已完成签名但尚未来得及更新状态。
+ * 启动时输出受控诊断,便于管理员结合交易哈希和签名字节判断是否可以人工置为失败。
+ */
+ private void warnUnfinishedRunningTasks() {
+ List