执行器检查逻辑修改

This commit is contained in:
lu7213 committed 2026-11-07 03:23:30 -05:00
1 parent f3f4a306e5
commit f55f4c2961
14 files changed
+298 -26

No files matched your search

+9
View File
@@ -103,6 +103,15 @@
<groupId>com.google.protobuf</groupId> <groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId> <artifactId>protobuf-java</artifactId>
</exclusion> </exclusion>
<!--
bitcoinj 0.17 使用 protobuf-javalite,而 TRON Trident 使用完整 protobuf-java。
两个制品包含 com.google.protobuf.Any 等同名类,同时进入执行器会因加载顺序
产生 NoSuchMethodError,因此支付系统统一使用上方受控版本的 protobuf-java。
-->
<exclusion>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-javalite</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
@@ -26,6 +26,7 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
/** /**
* 两个进程复用的受控执行引擎:核对业务、实时预算、解锁、构造一次、落盘、广播。 * 两个进程复用的受控执行引擎:核对业务、实时预算、解锁、构造一次、落盘、广播。
@@ -53,6 +54,7 @@ public class ChainCommandExecutor {
public void execute(String id, String password) { public void execute(String id, String password) {
long startedAt = System.currentTimeMillis(); long startedAt = System.currentTimeMillis();
AtomicReference<String> stage = new AtomicReference<>("LOAD_COMMAND");
// 等待租赁到账不是签名失败,必须在领取RUNNING之前返回,让资源Worker异步推进。 // 等待租赁到账不是签名失败,必须在领取RUNNING之前返回,让资源Worker异步推进。
ChainCommand pending = store.command(store.get(id)); ChainCommand pending = store.command(store.get(id));
if (pending.rentalRequired && pending.validUntil >= System.currentTimeMillis()) { if (pending.rentalRequired && pending.validUntil >= System.currentTimeMillis()) {
@@ -74,22 +76,36 @@ public class ChainCommandExecutor {
} }
try { try {
ChainCommand command = store.command(store.get(id)); ChainCommand command = store.command(store.get(id));
log.info("链上任务已领取,executionId={},businessKey={},operation={},network={}", id, log.info("链上任务已领取,executionId={},businessKey={},operation={},network={},授权剩余={}ms", id,
command.businessKey, command.type, command.network); command.businessKey, command.type, command.network,
WalletAddressPlus wallet = validate(command); Math.max(0L, command.validUntil - System.currentTimeMillis()));
WalletAddressPlus wallet = validate(command, stage);
log.info("链上任务业务校验通过,executionId={},businessKey={}", id, command.businessKey); log.info("链上任务业务校验通过,executionId={},businessKey={}", id, command.businessKey);
stage.set("UNLOCK_WALLET");
signing.execute(wallet, password, (tron, api, current) -> { signing.execute(wallet, password, (tron, api, current) -> {
if (!networkName(command.network).equals(tron.type())) { if (!networkName(command.network).equals(tron.type())) {
throw new CustomException("执行期间网络发生变化,已拒绝签名"); throw new CustomException("执行期间网络发生变化,已拒绝签名");
} }
log.info("链上任务钱包解锁及网络复核通过,executionId={},businessKey={},network={}",
id, command.businessKey, command.network);
// 使用实时余额和资源,不能信任页面估算或旧数据库快照。 // 使用实时余额和资源,不能信任页面估算或旧数据库快照。
stage.set("ESTIMATE_RESOURCES");
requireBudget(command, wallet, tron, api); requireBudget(command, wallet, tron, api);
if (command.rentalRequired) resourceGate.require(command); if (command.rentalRequired) {
stage.set("VERIFY_RENTED_RESOURCES");
resourceGate.require(command);
log.info("链上任务租赁资源到账复核通过,executionId={},businessKey={}", id, command.businessKey);
}
stage.set("BUILD_TRANSACTION");
Chain.Transaction unsigned = build(command, tron, api); Chain.Transaction unsigned = build(command, tron, api);
if (!unsigned.hasRawData() || unsigned.getRawData().getContractCount() != 1) { if (!unsigned.hasRawData() || unsigned.getRawData().getContractCount() != 1) {
throw new CustomException("节点未构造有效交易"); throw new CustomException("节点未构造有效交易");
} }
log.info("链上交易构造完成,executionId={},businessKey={},contractCount={}", id,
command.businessKey, unsigned.getRawData().getContractCount());
stage.set("SIGN_TRANSACTION");
Chain.Transaction signed = api.signTransaction(unsigned); Chain.Transaction signed = api.signTransaction(unsigned);
stage.set("PERSIST_SIGNED_TRANSACTION");
store.signed(id, transactionId(signed), signed.toByteArray()); store.signed(id, transactionId(signed), signed.toByteArray());
log.info("链上交易已签名并持久化,executionId={},businessKey={},transactionId={}", id, log.info("链上交易已签名并持久化,executionId={},businessKey={},transactionId={}", id,
command.businessKey, transactionId(signed)); command.businessKey, transactionId(signed));
@@ -100,11 +116,12 @@ public class ChainCommandExecutor {
command.businessKey, System.currentTimeMillis() - startedAt); command.businessKey, System.currentTimeMillis() - startedAt);
return null; return null;
}); });
} catch (Exception ex) { } catch (Exception | LinkageError failure) {
store.failBeforeSigning(id); store.failBeforeSigning(id, stage.get(), failure.getClass().getSimpleName());
// LinkageError(例如Protobuf NoSuchMethodError)同样发生在签名前,必须结束RUNNING状态。
// 不打印 SDK 异常对象或消息,避免私钥客户端的内部上下文进入日志。 // 不打印 SDK 异常对象或消息,避免私钥客户端的内部上下文进入日志。
log.error("链上任务签名前执行失败,executionId={},异常类型={},耗时={}ms", id, log.error("链上任务签名前执行失败,executionId={},阶段={},异常类型={},耗时={}ms", id,
ex.getClass().getSimpleName(), System.currentTimeMillis() - startedAt); stage.get(), failure.getClass().getSimpleName(), System.currentTimeMillis() - startedAt);
} }
} }
@@ -147,16 +164,20 @@ public class ChainCommandExecutor {
} }
} }
private WalletAddressPlus validate(ChainCommand command) { private WalletAddressPlus validate(ChainCommand command, AtomicReference<String> stage) {
stage.set("VALIDATE_EXPIRY");
if (command.validUntil < System.currentTimeMillis()) throw new CustomException("执行请求已过期"); if (command.validUntil < System.currentTimeMillis()) throw new CustomException("执行请求已过期");
stage.set("VALIDATE_CONFIGURATION");
UsdtConfig config = configs.selectFirst(); UsdtConfig config = configs.selectFirst();
if (config == null || !config.getVersion().equals(command.envelopeVersion) if (config == null || !config.getVersion().equals(command.envelopeVersion)
|| !config.getTronNetType().equals(command.network)) { || !config.getTronNetType().equals(command.network)) {
throw new CustomException("钱包配置或网络已变化,请重新发起操作"); throw new CustomException("钱包配置或网络已变化,请重新发起操作");
} }
stage.set("VALIDATE_BROADCAST_PERMISSION");
if (command.operation == null || !Boolean.TRUE.equals(command.operation.getBroadcast())) { if (command.operation == null || !Boolean.TRUE.equals(command.operation.getBroadcast())) {
throw new CustomException("本次操作未确认广播"); throw new CustomException("本次操作未确认广播");
} }
stage.set("VALIDATE_WALLET");
WalletAddressPlus wallet = new WalletAddressPlus(); WalletAddressPlus wallet = new WalletAddressPlus();
wallet.setId(command.walletId); wallet.setId(command.walletId);
wallet.setToken(command.address); wallet.setToken(command.address);
@@ -174,6 +195,7 @@ public class ChainCommandExecutor {
throw new CustomException("钱包已禁用或派生地址不一致"); throw new CustomException("钱包已禁用或派生地址不一致");
} }
} }
stage.set("VALIDATE_BUSINESS_RECORD");
validateBusiness(command); validateBusiness(command);
return wallet; return wallet;
} }
@@ -218,6 +240,10 @@ public class ChainCommandExecutor {
private void requireBudget(ChainCommand command, WalletAddressPlus wallet, ITronService tron, ApiWrapper api) throws Exception { private void requireBudget(ChainCommand command, WalletAddressPlus wallet, ITronService tron, ApiWrapper api) throws Exception {
WalletOperationRequest request = command.operation; WalletOperationRequest request = command.operation;
WalletResourceEstimateVo estimate = estimates.estimate(command.type, wallet, request); 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()) { if (Boolean.TRUE.equals(request.getResourceOnly()) && estimate.isBurnRequired()) {
throw new CustomException("当前资源不足,禁止燃烧 TRX"); throw new CustomException("当前资源不足,禁止燃烧 TRX");
} }
@@ -235,12 +261,19 @@ public class ChainCommandExecutor {
.add(BigDecimal.valueOf(estimate.getBandwidthGap()).multiply(BigDecimal.valueOf(bandwidthFee))).movePointLeft(6); .add(BigDecimal.valueOf(estimate.getBandwidthGap()).multiply(BigDecimal.valueOf(bandwidthFee))).movePointLeft(6);
BigDecimal needed = burn.add(reserve); BigDecimal needed = burn.add(reserve);
if ("trx".equals(command.type) || "stake".equals(command.type)) needed = needed.add(request.getAmount()); 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 余额不足以支付本次操作及资源预算"); throw new CustomException("TRX 余额不足以支付本次操作及资源预算");
} }
if ("usdt".equals(command.type) if ("usdt".equals(command.type)) {
&& tron.getUsdtBalance(api, wallet.getToken()).compareTo(request.getAmount()) < 0) { BigDecimal usdtBalance = tron.getUsdtBalance(api, wallet.getToken());
throw new CustomException("USDT 余额不足"); log.info("链上任务USDT余额复核完成,businessKey={},neededUsdt={},availableUsdt={}",
command.businessKey, request.getAmount().toPlainString(), usdtBalance.toPlainString());
if (usdtBalance.compareTo(request.getAmount()) < 0) throw new CustomException("USDT 余额不足");
} }
} }
@@ -58,6 +58,22 @@ public class ChainExecutionStore {
+ "where execution_id=? and status='QUEUED'", id) == 1; + "where execution_id=? and status='QUEUED'", id) == 1;
} }
/**
* 执行器重启后恢复尚未产生任何签名痕迹的远程任务。
*
* <p>交易广播前必须先通过 {@link #signed(String, String, byte[])} 将状态从 RUNNING 原子更新为
* SIGNED。即使旧进程仍在退出,只要本方法先将状态改回 QUEUED,旧进程便无法持久化签名并广播;
* 若旧进程先写入 SIGNED,本条件也不会命中。因此该恢复不会产生两笔链上交易。</p>
*
* @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) { public void signed(String id, String hash, byte[] transaction) {
if (jdbc.update("update usdt_chain_execution set status='SIGNED',transaction_id=?,signed_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'", + "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='RUNNING'",
@@ -72,9 +88,17 @@ public class ChainExecutionStore {
} }
public void failBeforeSigning(String id) { public void failBeforeSigning(String id) {
// 节点、SDK 异常可能携带敏感上下文,只记录固定文案;SIGNED 永远不改成可重试失败。 failBeforeSigning(id, "UNKNOWN", "UnknownException");
jdbc.update("update usdt_chain_execution set status='FAILED',error_message='执行前校验或签名失败,请检查配置、余额和资源'," }
+ "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='RUNNING'", id);
/**
* 仅记录受控阶段和异常类型,不落库 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("执行指令序列化失败"); throw new CustomException("执行指令序列化失败");
} }
} }
private String safeDiagnostic(String value) {
if (value == null || !value.matches("[A-Za-z0-9_.$-]{1,80}")) return "UNKNOWN";
return value;
}
} }
@@ -10,17 +10,20 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.RestClientResponseException; import org.springframework.web.client.RestClientResponseException;
import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import java.net.URI; import java.net.URI;
import java.time.Instant; import java.time.Instant;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */ /** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */
@Component @Component
@@ -36,6 +39,10 @@ public class ChainExecutorClient {
private String tlsCertificateLocation; private String tlsCertificateLocation;
@Value("${chain.executor.health-failure-threshold:3}") @Value("${chain.executor.health-failure-threshold:3}")
private int healthFailureThreshold; 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) @Autowired(required = false)
private ChainExecutorRuntimeState runtimeState; private ChainExecutorRuntimeState runtimeState;
private RestTemplate http; private RestTemplate http;
@@ -45,6 +52,7 @@ public class ChainExecutorClient {
private volatile int consecutiveFailures; private volatile int consecutiveFailures;
private volatile long checkedAt; private volatile long checkedAt;
private volatile String lastDiagnostic = "NOT_CHECKED"; private volatile String lastDiagnostic = "NOT_CHECKED";
private ScheduledExecutorService healthScheduler;
public ChainExecutorClient() { public ChainExecutorClient() {
http = createHttp(null); http = createHttp(null);
@@ -104,6 +112,7 @@ public class ChainExecutorClient {
log.error("内网链上执行器启动验证未通过,支付系统继续启动,远程链上操作暂不可用,诊断={}", log.error("内网链上执行器启动验证未通过,支付系统继续启动,远程链上操作暂不可用,诊断={}",
unavailable.getMessage()); unavailable.getMessage());
} }
startHealthMonitor();
} }
public boolean isEnabled() { return enabled; } 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() { public void monitor() {
if (!enabled || !checking.compareAndSet(false, true)) return; if (!enabled || !checking.compareAndSet(false, true)) return;
try { try {
probeNow(); probeNow();
} catch (Exception failure) {
// 避免状态持久化等外围异常终止后续固定延迟探测。
log.error("内网链上执行器后台探测异常,后续仍将继续检查,异常类型={}", rootType(failure));
} finally { } finally {
checking.set(false); checking.set(false);
} }
} }
/** 页面状态读取同时触发实时探测,“立即检查”不得只返回进程内旧缓存。 */
public Map<String, Object> refreshAvailability() {
monitor();
return availability();
}
/** 只有实时探测可用时才允许管理员重新打开,避免误启用后立即接受远程任务。 */ /** 只有实时探测可用时才允许管理员重新打开,避免误启用后立即接受远程任务。 */
public void enableRuntime(String operator) { public void enableRuntime(String operator) {
if (!probeNow()) throw new com.ruoyi.common.exception.CustomException("执行器尚未恢复,无法启用"); 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) { private static String rootType(Throwable failure) {
Throwable cause = failure; Throwable cause = failure;
while (cause.getCause() != null && cause.getCause() != cause) cause = cause.getCause(); while (cause.getCause() != null && cause.getCause() != cause) cause = cause.getCause();
@@ -32,7 +32,8 @@ public class ChainExecutorController {
+ "or @ss.hasPermi('system:usdtTaskItem:edit') or @ss.hasPermi('system:usdtPayoutOrder:execute')") + "or @ss.hasPermi('system:usdtTaskItem:edit') or @ss.hasPermi('system:usdtPayoutOrder:execute')")
@GetMapping("/status") @GetMapping("/status")
public AjaxResult status() { public AjaxResult status() {
Map<String, Object> result = new LinkedHashMap<>(client.availability()); // 页面轮询和“立即检查”都执行实时探测,不能只返回进程内缓存状态。
Map<String, Object> result = new LinkedHashMap<>(client.refreshAvailability());
// 明确列出公开字段,禁止 SELECT * 结果进入 HTTP 响应。 // 明确列出公开字段,禁止 SELECT * 结果进入 HTTP 响应。
boolean rentalEnabled = rentalProperties != null && rentalProperties.isEnabled(); boolean rentalEnabled = rentalProperties != null && rentalProperties.isEnabled();
result.put("executions", client.isEnabled() ? store.jdbc().queryForList(rentalEnabled result.put("executions", client.isEnabled() ? store.jdbc().queryForList(rentalEnabled
@@ -36,6 +36,7 @@ public class ChainCommandExecutorTest {
private int signedCount; private int signedCount;
private int broadcasts; private int broadcasts;
private boolean acceptBroadcast; private boolean acceptBroadcast;
private boolean failEstimateWithLinkageError;
private byte[] firstTransaction; private byte[] firstTransaction;
@Before @Before
@@ -70,6 +71,7 @@ public class ChainCommandExecutorTest {
}; };
WalletOperationEstimateService estimates = new WalletOperationEstimateService(networks) { WalletOperationEstimateService estimates = new WalletOperationEstimateService(networks) {
@Override public WalletResourceEstimateVo estimate(String type, WalletAddressPlus wallet, WalletOperationRequest request) { @Override public WalletResourceEstimateVo estimate(String type, WalletAddressPlus wallet, WalletOperationRequest request) {
if (failEstimateWithLinkageError) throw new NoSuchMethodError("simulated protobuf conflict");
WalletResourceEstimateVo estimate = new WalletResourceEstimateVo(); WalletResourceEstimateVo estimate = new WalletResourceEstimateVo();
estimate.setEstimatedBurnTrx(BigDecimal.ZERO); estimate.setEstimatedBurnTrx(BigDecimal.ZERO);
return estimate; return estimate;
@@ -108,6 +110,7 @@ public class ChainCommandExecutorTest {
assertEquals(0, signedCount); assertEquals(0, signedCount);
assertEquals(0, broadcasts); assertEquals(0, broadcasts);
assertEquals("FAILED", store.get(id).get("status")); assertEquals("FAILED", store.get(id).get("status"));
assertTrue(String.valueOf(store.get(id).get("error_message")).contains("阶段=VALIDATE_EXPIRY"));
} }
@Test @Test
@@ -141,6 +144,18 @@ public class ChainCommandExecutorTest {
assertEquals(0, broadcasts); assertEquals(0, broadcasts);
} }
@Test
public void linkageErrorBeforeSigningMarksExecutionFailed() {
failEstimateWithLinkageError = true;
executor.execute(executionId, "test-only-password");
Map<String, Object> 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() { private ChainCommand command() {
ChainCommand command = new ChainCommand(); ChainCommand command = new ChainCommand();
command.businessKey = "WALLET:test"; command.businessKey = "WALLET:test";
@@ -69,6 +69,23 @@ public class ChainExecutionStoreTest {
assertEquals("BROADCASTED", store.get(id).get("status")); 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 @Test
public void failureBeforeSigningCanBeArchivedWithoutLosingAudit() { public void failureBeforeSigningCanBeArchivedWithoutLosingAudit() {
String id = (String) store.create(command(), false).get("execution_id"); String id = (String) store.create(command(), false).get("execution_id");
@@ -105,8 +122,12 @@ public class ChainExecutionStoreTest {
} }
private ChainCommand command() { private ChainCommand command() {
return command("PAYOUT:123");
}
private ChainCommand command(String businessKey) {
ChainCommand command = new ChainCommand(); ChainCommand command = new ChainCommand();
command.businessKey = "PAYOUT:123"; command.businessKey = businessKey;
command.operatorId = 1L; command.operatorId = 1L;
command.type = "usdt"; command.type = "usdt";
command.operation = new WalletOperationRequest(); command.operation = new WalletOperationRequest();
+14 -1
View File
@@ -6,7 +6,20 @@
<artifactId>usdt-chain-executor</artifactId> <artifactId>usdt-chain-executor</artifactId>
<description>仅内网调用的独立链上执行进程</description> <description>仅内网调用的独立链上执行进程</description>
<dependencies> <dependencies>
<dependency><groupId>com.ruoyi</groupId><artifactId>ruoyi-system</artifactId></dependency> <dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
<!--
执行器可能在服务器上单模块构建,此时 Maven 会读取本地仓库中的旧版
ruoyi-system POM。这里再次排除 javalite,确保不依赖多模块构建顺序。
-->
<exclusions>
<exclusion>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-javalite</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.0</version></dependency> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.0</version></dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
@@ -43,11 +43,12 @@ public class ChainExecutorApplication {
// 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。 // 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。
try { try {
log.info("USDT链上执行器正在启动,运行模式=独立内网执行进程"); log.info("USDT链上执行器正在启动,运行模式=独立内网执行进程");
ProtobufRuntimeValidator.validate();
new SpringApplicationBuilder(ChainExecutorApplication.class).web(WebApplicationType.NONE) new SpringApplicationBuilder(ChainExecutorApplication.class).web(WebApplicationType.NONE)
.properties("spring.config.name=executor").run(args); .properties("spring.config.name=executor").run(args);
log.info("USDT链上执行器启动完成"); log.info("USDT链上执行器启动完成");
} catch (Exception ex) { } catch (Exception ex) {
log.error("USDT链上执行器启动失败,异常类型={}", ex.getClass().getSimpleName()); log.error("USDT链上执行器启动失败,异常类型={},msg {}", ex.getClass().getSimpleName(), ex.getMessage());
System.err.println("内网执行服务启动失败,请检查内网监听、白名单、环境变量、数据库及钱包密码配置"); System.err.println("内网执行服务启动失败,请检查内网监听、白名单、环境变量、数据库及钱包密码配置");
System.exit(1); System.exit(1);
} }
@@ -89,6 +89,12 @@ public class IntranetExecutionServer {
// 启动校验表结构和解密能力,不执行任何链上广播。 // 启动校验表结构和解密能力,不执行任何链上广播。
store.jdbc().queryForObject("select count(*) from usdt_chain_execution where 1=0", Long.class); store.jdbc().queryForObject("select count(*) from usdt_chain_execution where 1=0", Long.class);
checkReady(); checkReady();
int requeued = store.requeueUnsignedRemoteExecutions();
if (requeued > 0) {
notified = true;
log.warn("执行器启动时恢复未签名远程任务,重新排队数量={};任务将重新校验有效期、余额和资源", requeued);
}
warnUnfinishedRunningTasks();
log.info("启动检查通过,网络={},允许来源数量={},广播已启用", network, allowed.size()); log.info("启动检查通过,网络={},允许来源数量={},广播已启用", network, allowed.size());
InetSocketAddress address = new InetSocketAddress(bind, Integer.parseInt(required("CHAIN_EXECUTOR_PORT"))); InetSocketAddress address = new InetSocketAddress(bind, Integer.parseInt(required("CHAIN_EXECUTOR_PORT")));
// 执行器只提供HTTP。需要HTTPS时由同机Nginx终止TLS并转发到回环监听端口。 // 执行器只提供HTTP。需要HTTPS时由同机Nginx终止TLS并转发到回环监听端口。
@@ -160,6 +166,23 @@ public class IntranetExecutionServer {
signing.validateConfigurationPassword(password); signing.validateConfigurationPassword(password);
} }
/**
* RUNNING 不允许自动重领,因为旧进程可能已完成签名但尚未来得及更新状态。
* 启动时输出受控诊断,便于管理员结合交易哈希和签名字节判断是否可以人工置为失败。
*/
private void warnUnfinishedRunningTasks() {
List<Map<String, Object>> rows = store.jdbc().queryForList(
"select execution_id,business_key,transaction_id,signed_transaction,updated_at "
+ "from usdt_chain_execution where status='RUNNING' order by updated_at limit 20");
if (rows.isEmpty()) return;
log.warn("发现未完成的RUNNING链上任务,数量={};系统不会自动重领,请人工核验是否已签名或广播", rows.size());
for (Map<String, Object> row : rows) {
log.warn("未完成链上任务,executionId={},businessKey={},updatedAt={},hasTransactionId={},hasSignedTransaction={}",
row.get("execution_id"), row.get("business_key"), row.get("updated_at"),
row.get("transaction_id") != null, row.get("signed_transaction") != null);
}
}
@Scheduled(fixedDelay = 200, initialDelay = 2000) @Scheduled(fixedDelay = 200, initialDelay = 2000)
public void process() { public void process() {
if (!notified && System.currentTimeMillis() < nextScanAt) return; if (!notified && System.currentTimeMillis() < nextScanAt) return;
@@ -197,9 +220,10 @@ public class IntranetExecutionServer {
} }
if (!rows.isEmpty()) log.info("链上任务批次处理结束,执行数量={},恢复数量={},跳过数量={},耗时={}ms", if (!rows.isEmpty()) log.info("链上任务批次处理结束,执行数量={},恢复数量={},跳过数量={},耗时={}ms",
executed, recovered, skipped, System.currentTimeMillis() - startedAt); executed, recovered, skipped, System.currentTimeMillis() - startedAt);
} catch (Exception failure) { } catch (Exception | LinkageError failure) {
// 固定延迟补扫;不输出密码、信封或 SDK 异常。恢复后继续已有任务。 // 固定延迟补扫;不输出密码、信封或 SDK 异常。恢复后继续已有任务。
log.error("链上任务扫描失败,将按固定延迟重试,异常类型={}", failure.getClass().getSimpleName()); log.error("链上任务扫描失败,将按固定延迟重试,异常类型={},已处理任务由任务级状态机记录结果",
failure.getClass().getSimpleName());
} finally { } finally {
processing.set(false); processing.set(false);
} }
@@ -0,0 +1,62 @@
package com.ruoyi.executor;
import com.google.protobuf.Any;
import com.google.protobuf.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.net.URL;
/**
* 校验执行器实际加载的 Protobuf 运行时是否兼容 TRON Trident。
*
* <p>protobuf-java 与 protobuf-javalite 包含若干完全相同的类名,但方法签名不同。
* 若部署包或外部 classpath 同时包含两者,应用可以正常启动,却会在首次构造交易时
* 抛出 {@link NoSuchMethodError}。因此必须在接收链上任务之前完成 ABI 校验。</p>
*/
final class ProtobufRuntimeValidator {
private static final Logger LOG = LoggerFactory.getLogger(ProtobufRuntimeValidator.class);
private ProtobufRuntimeValidator() {
}
/**
* Trident 0.10.0 调用 Any.pack(Message),该方法仅由完整 protobuf-java 提供。
*/
static void validate() {
try {
Any.class.getMethod("pack", Message.class);
} catch (NoSuchMethodException ex) {
throw new IllegalStateException("Protobuf运行时与TRON Trident不兼容,请移除protobuf-javalite或旧版protobuf-java;"
+ "Any类加载位置=" + sourceLocation() + ";检测到的pack签名=" + packSignatures(), ex);
}
Package runtimePackage = Any.class.getPackage();
String implementationVersion = runtimePackage == null ? null : runtimePackage.getImplementationVersion();
LOG.info("Protobuf运行时兼容性检查通过,版本={},加载位置={}",
implementationVersion == null ? "unknown" : implementationVersion,
sourceLocation());
}
private static String sourceLocation() {
URL source = Any.class.getProtectionDomain() == null
|| Any.class.getProtectionDomain().getCodeSource() == null
? null : Any.class.getProtectionDomain().getCodeSource().getLocation();
return source == null ? "unknown" : source.toExternalForm();
}
private static String packSignatures() {
StringBuilder signatures = new StringBuilder();
for (Method method : Any.class.getMethods()) {
if (!"pack".equals(method.getName())) {
continue;
}
if (signatures.length() > 0) {
signatures.append(',');
}
signatures.append(method.toGenericString());
}
return signatures.length() == 0 ? "none" : signatures.toString();
}
}
@@ -75,7 +75,9 @@ public class ExecutorBootstrapTest {
public static class Probe { public static class Probe {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource(JDBC, "sa", "")); JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource(JDBC, "sa", ""));
jdbc.execute("create table usdt_chain_execution (execution_id varchar(36), status varchar(16), execution_mode varchar(16), created_at timestamp)"); jdbc.execute("create table usdt_chain_execution (execution_id varchar(36),business_key varchar(160),"
+ "status varchar(16),execution_mode varchar(16),transaction_id varchar(128),"
+ "signed_transaction blob,error_message varchar(512),created_at timestamp,updated_at timestamp)");
jdbc.execute("create table usdt_config (id bigint, pay_usdt_num decimal, receive_usdt_num decimal, tron_net_type int, " jdbc.execute("create table usdt_config (id bigint, pay_usdt_num decimal, receive_usdt_num decimal, tron_net_type int, "
+ "version bigint, encryption_algorithm varchar, password_kdf varchar, iterations bigint, encrypted_mnemonic varchar, " + "version bigint, encryption_algorithm varchar, password_kdf varchar, iterations bigint, encrypted_mnemonic varchar, "
+ "mnemonic_nonce varchar, encrypted_dek varchar, dek_nonce varchar, key_salt varchar, password_salt varchar, " + "mnemonic_nonce varchar, encrypted_dek varchar, dek_nonce varchar, key_salt varchar, password_salt varchar, "
@@ -79,7 +79,9 @@ public class IntranetExecutionServerTest {
environment.put("CHAIN_EXECUTOR_BROADCAST_ENABLED", "true"); environment.put("CHAIN_EXECUTOR_BROADCAST_ENABLED", "true");
ChainExecutionStore store = new ChainExecutionStore(new DriverManagerDataSource( ChainExecutionStore store = new ChainExecutionStore(new DriverManagerDataSource(
"jdbc:h2:mem:server" + System.nanoTime() + ";DB_CLOSE_DELAY=-1", "sa", "")); "jdbc:h2:mem:server" + System.nanoTime() + ";DB_CLOSE_DELAY=-1", "sa", ""));
store.jdbc().execute("create table usdt_chain_execution(id int)"); store.jdbc().execute("create table usdt_chain_execution(id int,execution_id varchar(36),business_key varchar(160),"
+ "status varchar(16),execution_mode varchar(16),transaction_id varchar(128),signed_transaction blob,"
+ "error_message varchar(512),updated_at timestamp)");
UsdtConfig config = new UsdtConfig(); UsdtConfig config = new UsdtConfig();
config.setTronNetType(0); config.setTronNetType(0);
UsdtConfigMapper configs = (UsdtConfigMapper) Proxy.newProxyInstance(getClass().getClassLoader(), UsdtConfigMapper configs = (UsdtConfigMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
@@ -0,0 +1,19 @@
package com.ruoyi.executor;
import com.google.protobuf.Any;
import com.google.protobuf.Message;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* 防止执行器依赖调整时再次混入 protobuf-javalite,导致 Trident 构造交易失败。
*/
public class ProtobufRuntimeValidatorTest {
@Test
public void runtimeProvidesFullProtobufApiRequiredByTrident() throws Exception {
ProtobufRuntimeValidator.validate();
assertNotNull(Any.class.getMethod("pack", Message.class));
}
}