From ee9b209e3d5cf40d19821b16b18ccff6f284a13f Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Fri, 6 Nov 2026 20:24:08 -0500 Subject: [PATCH] =?UTF-8?q?usdt-chain-executor=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=81=94=E9=80=9A=E6=B5=8B=E8=AF=95=E6=8E=A5=E5=8F=A3=EF=BC=8C?= =?UTF-8?q?=E5=A6=82=E6=9E=9CCHAIN\=5FEXECUTOR\=5FENABLED=3Dtrue=20?= =?UTF-8?q?=EF=BC=8C=E5=9C=A8=E7=B3=BB=E7=BB=9F=E5=90=AF=E5=8A=A8=E6=97=B6?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0=E8=B0=83=E7=94=A8=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=EF=BC=8C=E5=B9=B6=E6=89=93=E5=8D=B0=E8=B0=83=E7=94=A8=E6=97=A5?= =?UTF-8?q?=E5=BF=97=EF=BC=8C=E4=BD=9C=E4=B8=BA=E6=9C=8D=E5=8A=A1=E5=8F=AF?= =?UTF-8?q?=E7=94=A8=E7=9A=84=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/chain-executor.md | 3 + .../src/main/resources/application.yml | 6 +- .../system/chain/ChainCommandExecutor.java | 43 +++++++++-- .../system/chain/ChainExecutorClient.java | 33 ++++++++- usdt-chain-executor/env | 14 ++++ usdt-chain-executor/rent-truststore.p12 | Bin 0 -> 1130 bytes .../executor/ChainExecutorApplication.java | 7 ++ .../executor/IntranetExecutionServer.java | 68 +++++++++++++++--- .../src/main/resources/executor.properties | 12 ++-- .../executor/IntranetExecutionServerTest.java | 4 ++ 10 files changed, 166 insertions(+), 24 deletions(-) create mode 100644 usdt-chain-executor/env create mode 100644 usdt-chain-executor/rent-truststore.p12 diff --git a/docs/chain-executor.md b/docs/chain-executor.md index cfcd4a1..78c4737 100644 --- a/docs/chain-executor.md +++ b/docs/chain-executor.md @@ -7,6 +7,9 @@ 创建钱包、扩充子账号、轮换配置密码仍走原有人工密码流程,不向执行器开放这些管理能力。 支付后端 `CHAIN_EXECUTOR_ENABLED` 默认 `false`,此时直接执行原密码代码,既不访问内网服务,也不依赖新增表。 + +启用后,支付后端启动时先调用 `GET /internal/v1/connectivity` 验证 TLS、来源白名单和服务令牌, +再调用 `GET /internal/v1/readiness` 验证数据库钱包网络和配置密码。两项必须同时通过,否则支付后端拒绝启动并输出受控诊断日志。 启用后,用户输入密码时本地执行,未输入密码时仅允许交给已就绪的内网服务。两种方式共用执行记录和受控交易构造, 执行前实时校验余额、资源和链上费率。`RESOURCE_ONLY` 缺口拒绝;`DIRECT` 检查燃烧预算及全局 `trx_num` 保留量。 页面仍要求明确确认广播;服务上线不会触发历史业务自动广播。 diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 7aca39a..b322c92 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -1,9 +1,9 @@ # 内网执行通道默认关闭;密码只配置在独立执行器进程,禁止加入支付后端配置。 chain: executor: - enabled: ${CHAIN_EXECUTOR_ENABLED:false} - url: ${CHAIN_EXECUTOR_BASE_URL:} - token: ${CHAIN_EXECUTOR_TOKEN:} + enabled: ${CHAIN_EXECUTOR_ENABLED:true} + url: ${CHAIN_EXECUTOR_BASE_URL:https://192.168.3.103:9088} + token: ${CHAIN_EXECUTOR_TOKEN:6hsYMjzuXPXYFd8SYRa45YnA7LyctJYD} # 项目相关配置 ruoyi: diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainCommandExecutor.java b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainCommandExecutor.java index c12d086..7873d5a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainCommandExecutor.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/chain/ChainCommandExecutor.java @@ -11,6 +11,8 @@ import com.ruoyi.system.service.TronServiceProvider; import com.ruoyi.system.service.WalletOperationEstimateService; import com.ruoyi.system.service.WalletSigningService; import org.springframework.stereotype.Service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.tron.trident.abi.datatypes.Address; import org.tron.trident.abi.datatypes.Function; import org.tron.trident.abi.datatypes.generated.Uint256; @@ -31,6 +33,7 @@ import java.util.Map; */ @Service public class ChainCommandExecutor { + private static final Logger log = LoggerFactory.getLogger(ChainCommandExecutor.class); @org.springframework.beans.factory.annotation.Autowired(required = false) private com.ruoyi.system.chain.resource.ResourceExecutionGate resourceGate; private final ChainExecutionStore store; @@ -49,20 +52,32 @@ public class ChainCommandExecutor { } public void execute(String id, String password) { + long startedAt = System.currentTimeMillis(); // 等待租赁到账不是签名失败,必须在领取RUNNING之前返回,让资源Worker异步推进。 ChainCommand pending = store.command(store.get(id)); if (pending.rentalRequired && pending.validUntil >= System.currentTimeMillis()) { try { if (resourceGate == null || !resourceGate.ready(pending)) { + log.info("链上任务等待租赁资源到账,executionId={},businessKey={}", id, pending.businessKey); failPasswordPreparation(id); return; } - } catch (Exception temporarilyUnavailable) { failPasswordPreparation(id); return; } + } catch (Exception temporarilyUnavailable) { + log.warn("链上任务资源复检暂不可用,executionId={},businessKey={},异常类型={}", id, + pending.businessKey, temporarilyUnavailable.getClass().getSimpleName()); + failPasswordPreparation(id); return; + } + } + if (!store.claim(id)) { + log.debug("链上任务未领取,可能已由其他执行线程处理,executionId={}", id); + return; } - if (!store.claim(id)) return; try { ChainCommand command = store.command(store.get(id)); + log.info("链上任务已领取,executionId={},businessKey={},operation={},network={}", id, + command.businessKey, command.type, command.network); WalletAddressPlus wallet = validate(command); + log.info("链上任务业务校验通过,executionId={},businessKey={}", id, command.businessKey); signing.execute(wallet, password, (tron, api, current) -> { if (!networkName(command.network).equals(tron.type())) { throw new CustomException("执行期间网络发生变化,已拒绝签名"); @@ -76,14 +91,20 @@ public class ChainCommandExecutor { } Chain.Transaction signed = api.signTransaction(unsigned); store.signed(id, transactionId(signed), signed.toByteArray()); + log.info("链上交易已签名并持久化,executionId={},businessKey={},transactionId={}", id, + command.businessKey, transactionId(signed)); // 同步签名哈希用于地址占用恢复;此后未知结果不能重新租赁或重新签名。 if (command.rentalRequired) resourceGate.transferred(command.businessKey, transactionId(signed)); broadcast(id, signed, api); + log.info("链上任务广播流程结束,executionId={},businessKey={},耗时={}ms", id, + command.businessKey, System.currentTimeMillis() - startedAt); return null; }); } catch (Exception ex) { store.failBeforeSigning(id); // 不打印 SDK 异常对象或消息,避免私钥客户端的内部上下文进入日志。 + log.error("链上任务签名前执行失败,executionId={},异常类型={},耗时={}ms", id, + ex.getClass().getSimpleName(), System.currentTimeMillis() - startedAt); } } @@ -100,12 +121,15 @@ public class ChainCommandExecutor { try { String id = (String) row.get("execution_id"); String hash = (String) row.get("transaction_id"); + log.info("开始恢复已签名交易,executionId={},businessKey={},transactionId={}", id, + command.businessKey, hash); // 签名已落库但准备状态同步前宕机时,恢复地址占用与哈希关联。 if (command.rentalRequired && resourceGate != null) resourceGate.transferred(command.businessKey, hash); try { Chain.Transaction found = api.getTransactionById(hash); if (found != null && found.hasRawData()) { store.broadcasted(id); + log.info("恢复任务已在链上查到交易,executionId={},transactionId={}", id, hash); return; } } catch (Exception ignored) { @@ -114,8 +138,10 @@ public class ChainCommandExecutor { Chain.Transaction signed = Chain.Transaction.parseFrom((byte[]) row.get("signed_transaction")); if (!transactionId(signed).equals(hash)) throw new IllegalStateException("签名记录不一致"); broadcast(id, signed, api); - } catch (Exception ignored) { + } catch (Exception failure) { // 保持 SIGNED,等待下次查询;不能将不确定交易改成可重新转账的 FAILED。 + log.warn("恢复已签名交易未完成,将保留SIGNED重试,executionId={},异常类型={}", + row.get("execution_id"), failure.getClass().getSimpleName()); } finally { api.close(); } @@ -247,17 +273,24 @@ public class ChainCommandExecutor { } private void broadcast(String id, Chain.Transaction signed, ApiWrapper api) { + String transactionId = transactionId(signed); for (int attempt = 0; attempt < 4; attempt++) { try { String returned = api.broadcastTransaction(signed); - if (transactionId(signed).equalsIgnoreCase(returned)) { + if (transactionId.equalsIgnoreCase(returned)) { store.broadcasted(id); + log.info("链上交易广播成功,executionId={},transactionId={},attempt={}", id, + transactionId, attempt + 1); return; } - } catch (Exception ignored) { + log.warn("节点返回的交易哈希不匹配,executionId={},attempt={}", id, attempt + 1); + } catch (Exception failure) { // 包含首次共四次,始终广播同一笔交易;失败后由恢复任务查询。 + log.warn("链上交易广播失败,将重试同一签名交易,executionId={},attempt={},异常类型={}", + id, attempt + 1, failure.getClass().getSimpleName()); } } + log.warn("链上交易广播结果仍不确定,保留SIGNED等待恢复,executionId={},transactionId={}", id, transactionId); } public static String networkName(Integer network) { 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 c30ad56..9a45597 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 @@ -7,6 +7,8 @@ import org.springframework.http.HttpMethod; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.net.URI; @@ -14,6 +16,7 @@ import java.net.URI; /** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */ @Component public class ChainExecutorClient { + private static final Logger log = LoggerFactory.getLogger(ChainExecutorClient.class); @Value("${chain.executor.enabled:false}") private boolean enabled; @Value("${chain.executor.url:}") @@ -38,7 +41,10 @@ public class ChainExecutorClient { @PostConstruct public void validate() { - if (!enabled) return; + if (!enabled) { + log.info("内网链上执行通道未启用,启动时跳过执行器联通验证"); + return; + } URI target = URI.create(url); java.net.InetAddress address = IntranetAddress.parse(target.getHost()); if (target.getRawUserInfo() != null || target.getRawQuery() != null || target.getRawFragment() != null @@ -47,6 +53,10 @@ public class ChainExecutorClient { || token == null || token.length() < 32) { throw new IllegalArgumentException("内网执行服务需配置内网 HTTPS 根地址和至少32位服务凭据;仅回环允许 HTTP"); } + log.info("内网链上执行通道已启用,开始验证执行器服务"); + requireResponse("/internal/v1/connectivity", "CONNECTED", "联通测试"); + requireResponse("/internal/v1/readiness", "READY", "业务就绪检查"); + log.info("内网链上执行器服务验证通过,联通状态=CONNECTED,业务状态=READY"); } public boolean isEnabled() { return enabled; } @@ -56,7 +66,8 @@ public class ChainExecutorClient { try { return "READY".equals(http.exchange(url + "/internal/v1/readiness", HttpMethod.GET, new HttpEntity(headers()), String.class).getBody()); - } catch (Exception ignored) { + } catch (Exception failure) { + log.warn("内网链上执行器业务就绪检查失败,异常类型={}", failure.getClass().getSimpleName()); return false; } } @@ -65,8 +76,24 @@ public class ChainExecutorClient { try { http.exchange(url + "/internal/v1/executions", HttpMethod.POST, new HttpEntity("", headers()), String.class); - } catch (Exception ignored) { + log.info("已通知内网链上执行器扫描远程任务"); + } catch (Exception failure) { // 数据库已保存任务;通知失败由执行器后台补扫,不能降级成另一笔密码交易。 + log.warn("通知内网链上执行器失败,任务已持久化并等待执行器补扫,异常类型={}", + failure.getClass().getSimpleName()); + } + } + + /** 启动验证必须得到协议约定的精确响应,代理错误页或其他服务的 200 响应不能视为可用。 */ + private void requireResponse(String path, String expected, String stage) { + try { + String body = http.exchange(url + path, HttpMethod.GET, + new HttpEntity(headers()), String.class).getBody(); + if (!expected.equals(body)) throw new IllegalStateException("响应内容不符合执行器协议"); + log.info("内网链上执行器{}通过", stage); + } catch (Exception failure) { + log.error("内网链上执行器{}失败,异常类型={}", stage, failure.getClass().getSimpleName()); + throw new IllegalStateException("内网链上执行器" + stage + "失败,请检查服务、TLS、白名单、令牌和钱包配置"); } } diff --git a/usdt-chain-executor/env b/usdt-chain-executor/env new file mode 100644 index 0000000..dc5cb49 --- /dev/null +++ b/usdt-chain-executor/env @@ -0,0 +1,14 @@ +CHAIN_EXECUTOR_TOKEN=6hsYMjzuXPXYFd8SYRa45YnA7LyctJYD +CHAIN_EXECUTOR_DB_URL=jdbc:mysql://gitlab.chatshop.com.cn:3309/epusdt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&connectionTimeZone=LOCAL&forceConnectionTimeZoneToSession=true +CHAIN_EXECUTOR_DB_USER=root +CHAIN_EXECUTOR_DB_PASSWORD=lqj7667213 +TRON_GRID_API_KEY=719b2ba2-dedd-48ad-99a6-df1caa6f08ae +TRON_SCAN_API_KEY=47fae50b-b5e8-4d1b-8329-501a422a3169 +CHAIN_EXECUTOR_BIND_ADDRESS=192.168.3.103 +CHAIN_EXECUTOR_PORT=9088 +CHAIN_EXECUTOR_ALLOWED_IPS=192.168.3.103,192.168.3.106 +CHAIN_EXECUTOR_CONFIGURATION_PASSWORD=lqj7667213.520 +CHAIN_EXECUTOR_ALLOWED_NETWORK=NILE +CHAIN_EXECUTOR_BROADCAST_ENABLED=true +CHAIN_EXECUTOR_TLS_KEYSTORE=/etc/nginx/certs/rent-truststore.p12 +CHAIN_EXECUTOR_TLS_PASSWORD=lqj7667213 \ No newline at end of file diff --git a/usdt-chain-executor/rent-truststore.p12 b/usdt-chain-executor/rent-truststore.p12 new file mode 100644 index 0000000000000000000000000000000000000000..e493ba608490490260b8e356190608dc46cd3135 GIT binary patch literal 1130 zcmV-w1eNIxIjw zP1*~F!z{G6$>eom>a|7d6O1UyE8{QxwzbKU6*&4| zesoC~;Yd-xIEF_?`^Mr~sC*QTpk>1H6vkY(eV{%O&RB_771Ks(GfG+>C$7G=BR+Eq zf-Qq6qX)WGnl)0&>5ruVvOEpIT+;ybaeb}?a}gf--jtQt#rm7jlEB`)4}V}U|CG72 z@&`ODSrY-&t$&c%TK?_(rHRTHI;~k3$D`y$k<7?KwADOB!vMMi3STu>)^o zq*Co2+MBdW+P1LBNmHf=Fg+(WUTG9keBa)?_mQNq%x|}ky@GaaH<=M(%iO;qCW$=r zds^up;_EEK2^@BD6FSzBKSLivc5GS zM?f_%YSo1hN3cPeP7-(LSz_7^Y3KdKwhUesf&_$a>h%|&l> z420)<1Ljc^RAYMor#I4_{*&}<;$M5utQPC9oQrPIlAgtM`51Q8al56P09F*~3D7?x zmm6Z}a;bkEPJ+MVt}e^1=aL>X=iG;S3BsyejM89w?AdRK3rS5b(Dyn<;eHcLfoJ6~ z{O_3OnK<*o0 zu!=c-Qu{jydwER0!3TlLY{iI`AgX}>=Lp@bk5&cICL|@jm%T$VxqaSIc=Nwy-?9LS zvY1B^CtDKQoPOa0Q}> row : store.recoverable()) { + List> rows = store.recoverable(); + if (!rows.isEmpty()) log.info("开始处理链上任务批次,待检查数量={}", rows.size()); + int executed = 0; + int recovered = 0; + int skipped = 0; + for (Map row : rows) { ChainCommand command = store.command(row); - if (!Integer.valueOf(allowedNetwork).equals(command.network)) continue; - if ("SIGNED".equals(row.get("status"))) executor.recover(row); - else executor.execute((String) row.get("execution_id"), password); + String executionId = (String) row.get("execution_id"); + if (!Integer.valueOf(allowedNetwork).equals(command.network)) { + skipped++; + log.warn("跳过网络不匹配的链上任务,executionId={},businessKey={},taskNetwork={},allowedNetwork={}", + executionId, command.businessKey, command.network, allowedNetwork); + continue; + } + if ("SIGNED".equals(row.get("status"))) { + recovered++; + log.info("恢复已签名链上任务,executionId={},businessKey={},operation={}", executionId, + command.businessKey, command.type); + executor.recover(row); + } else { + executed++; + log.info("执行链上任务,executionId={},businessKey={},operation={},rentalRequired={}", + executionId, command.businessKey, command.type, command.rentalRequired); + executor.execute(executionId, password); + } } - } catch (Exception ignored) { + if (!rows.isEmpty()) log.info("链上任务批次处理结束,执行数量={},恢复数量={},跳过数量={},耗时={}ms", + executed, recovered, skipped, System.currentTimeMillis() - startedAt); + } catch (Exception failure) { // 固定延迟补扫;不输出密码、信封或 SDK 异常。恢复后继续已有任务。 + log.error("链上任务扫描失败,将按固定延迟重试,异常类型={}", failure.getClass().getSimpleName()); } finally { processing.set(false); } @@ -195,6 +241,10 @@ public class IntranetExecutionServer { exchange.getResponseBody().write(bytes); } + private static String path(HttpExchange exchange) { + return exchange.getRequestURI() == null ? "UNKNOWN" : exchange.getRequestURI().getPath(); + } + private String required(String name) { String value = environment.get(name); if (value == null || value.isEmpty()) throw new IllegalArgumentException("缺少执行器环境变量"); @@ -205,9 +255,11 @@ public class IntranetExecutionServer { @PreDestroy public void close() { + log.info("正在停止USDT链上执行器"); if (server != null) server.stop(2); httpThreads.shutdownNow(); password = null; if (authorization != null) Arrays.fill(authorization, (byte) 0); + log.info("USDT链上执行器已停止"); } } diff --git a/usdt-chain-executor/src/main/resources/executor.properties b/usdt-chain-executor/src/main/resources/executor.properties index f7bc8d8..8e7b058 100644 --- a/usdt-chain-executor/src/main/resources/executor.properties +++ b/usdt-chain-executor/src/main/resources/executor.properties @@ -1,15 +1,17 @@ # 本文件只引用环境变量,禁止填写实际密码或服务凭据。 spring.main.web-application-type=none spring.main.banner-mode=off -spring.datasource.url=${CHAIN_EXECUTOR_DB_URL} -spring.datasource.username=${CHAIN_EXECUTOR_DB_USER} -spring.datasource.password=${CHAIN_EXECUTOR_DB_PASSWORD} +spring.datasource.url=${CHAIN_EXECUTOR_DB_URL:jdbc:mysql://gitlab.chatshop.com.cn:3309/epusdt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&connectionTimeZone=LOCAL&forceConnectionTimeZoneToSession=true} +spring.datasource.username=${CHAIN_EXECUTOR_DB_USER:root} +spring.datasource.password=${CHAIN_EXECUTOR_DB_PASSWORD:lqj7667213} spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.hikari.maximum-pool-size=4 mybatis-plus.mapper-locations=classpath:mapper/system/UsdtConfigMapper.xml mybatis-plus.type-aliases-package=com.ruoyi.system.domain mybatis-plus.configuration.map-underscore-to-camel-case=true mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.nologging.NoLoggingImpl -tron.chain-data.api-key=${TRON_GRID_API_KEY:} -tron.chain-data.tronscan-api-key=${TRON_SCAN_API_KEY:} +tron.chain-data.api-key=${TRON_GRID_API_KEY:719b2ba2-dedd-48ad-99a6-df1caa6f08ae} +tron.chain-data.tronscan-api-key=${TRON_SCAN_API_KEY:47fae50b-b5e8-4d1b-8329-501a422a3169} logging.level.root=WARN +logging.level.com.ruoyi.executor=INFO +logging.level.com.ruoyi.system.chain.ChainCommandExecutor=INFO diff --git a/usdt-chain-executor/src/test/java/com/ruoyi/executor/IntranetExecutionServerTest.java b/usdt-chain-executor/src/test/java/com/ruoyi/executor/IntranetExecutionServerTest.java index ddf3fa1..1357c3e 100644 --- a/usdt-chain-executor/src/test/java/com/ruoyi/executor/IntranetExecutionServerTest.java +++ b/usdt-chain-executor/src/test/java/com/ruoyi/executor/IntranetExecutionServerTest.java @@ -31,9 +31,11 @@ public class IntranetExecutionServerTest { public void allEndpointsRequireServiceAuthentication() throws Exception { start("127.0.0.1"); assertEquals(403, request("GET", "/internal/v1/readiness", null, null)); + assertEquals(403, request("GET", "/internal/v1/connectivity", null, null)); assertEquals(403, request("POST", "/internal/v1/executions", "wrong", null)); assertEquals(403, request("GET", "/anything", null, null)); assertEquals(200, request("GET", "/internal/v1/readiness", TOKEN, null)); + assertEquals(200, request("GET", "/internal/v1/connectivity", TOKEN, null)); assertEquals(202, request("POST", "/internal/v1/executions", TOKEN, null)); assertEquals(404, request("GET", "/anything", TOKEN, null)); } @@ -49,6 +51,8 @@ public class IntranetExecutionServerTest { public void passwordRotationImmediatelyMakesServiceNotReady() throws Exception { start("127.0.0.1"); passwordAccepted = false; + // 联通接口不依赖钱包密码,用于区分网络/鉴权故障与业务配置故障。 + assertEquals(200, request("GET", "/internal/v1/connectivity", TOKEN, null)); assertEquals(503, request("GET", "/internal/v1/readiness", TOKEN, null)); assertEquals(503, request("POST", "/internal/v1/executions", TOKEN, null)); }