usdt-chain-executor 添加联通测试接口,如果CHAIN\_EXECUTOR\_ENABLED=true ,在系统启动时,添加调用验证,并打印调用日志,作为服务可用的日志

This commit is contained in:
lu7213 committed 2026-11-06 20:24:08 -05:00
1 parent 5ca2cc5202
commit ee9b209e3d
10 files changed
+166 -24

No files matched your search

+14
View File
@@ -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
Binary file not shown.
@@ -17,6 +17,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 独立启动入口。仅显式导入执行所需组件,禁止扫描 com.ruoyi,
@@ -35,12 +37,17 @@ import org.springframework.scheduling.annotation.EnableScheduling;
com.ruoyi.system.chain.resource.ResourceExecutionGate.class,
IntranetExecutionServer.class})
public class ChainExecutorApplication {
private static final Logger log = LoggerFactory.getLogger(ChainExecutorApplication.class);
public static void main(String[] args) {
// 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。
try {
log.info("USDT链上执行器正在启动,运行模式=独立内网执行进程");
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());
System.err.println("内网执行服务启动失败,请检查内网监听、白名单、环境变量、数据库及钱包密码配置");
System.exit(1);
}
@@ -12,6 +12,8 @@ import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import org.springframework.scheduling.annotation.Scheduled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@@ -41,6 +43,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
* POST 仅唤醒数据库任务扫描,不能通过 HTTP 注入钱包、金额、密码或原始交易。
*/
public class IntranetExecutionServer {
private static final Logger log = LoggerFactory.getLogger(IntranetExecutionServer.class);
private final ChainExecutionStore store;
private final ChainCommandExecutor executor;
private final WalletSigningService signing;
@@ -79,6 +82,7 @@ public class IntranetExecutionServer {
@PostConstruct
public void start() throws Exception {
log.info("开始校验链上执行器启动配置");
InetAddress bind = IntranetAddress.parse(required("CHAIN_EXECUTOR_BIND_ADDRESS"));
if (NetworkInterface.getByInetAddress(bind) == null) throw new IllegalArgumentException("监听地址必须属于本机");
for (String ip : required("CHAIN_EXECUTOR_ALLOWED_IPS").split(",")) allowed.add(IntranetAddress.parse(ip.trim()));
@@ -93,6 +97,7 @@ public class IntranetExecutionServer {
// 启动校验表结构和解密能力,不执行任何链上广播。
store.jdbc().queryForObject("select count(*) from usdt_chain_execution where 1=0", Long.class);
checkReady();
log.info("启动检查通过,网络={},允许来源数量={},广播已启用", network, allowed.size());
InetSocketAddress address = new InetSocketAddress(bind, Integer.parseInt(required("CHAIN_EXECUTOR_PORT")));
if (bind.isLoopbackAddress() && environment.get("CHAIN_EXECUTOR_TLS_KEYSTORE") == null) {
server = HttpServer.create(address, 32);
@@ -104,6 +109,8 @@ public class IntranetExecutionServer {
server.createContext("/", this::handle);
server.setExecutor(httpThreads);
server.start();
log.info("内网执行服务已监听,地址={},端口={},传输协议={}", bind.getHostAddress(),
server.getAddress().getPort(), server instanceof HttpsServer ? "HTTPS" : "HTTP-LOOPBACK");
}
private void handle(HttpExchange exchange) throws java.io.IOException {
@@ -112,16 +119,24 @@ public class IntranetExecutionServer {
String received = exchange.getRequestHeaders().getFirst("Authorization");
if (!allowed.contains(peer) || received == null || !MessageDigest.isEqual(authorization,
received.getBytes(StandardCharsets.UTF_8))) {
log.warn("拒绝未授权内网请求,来源={},方法={},路径={}", peer.getHostAddress(),
exchange.getRequestMethod(), exchange.getRequestURI().getPath());
respond(exchange, 403, "FORBIDDEN");
return;
}
if (exchange.getRequestURI().getRawQuery() != null) {
log.warn("拒绝带查询参数的内网请求,来源={},路径={}", peer.getHostAddress(), path(exchange));
respond(exchange, 400, "INVALID_REQUEST");
return;
}
String path = exchange.getRequestURI().getPath();
if ("/internal/v1/readiness".equals(path) && "GET".equals(exchange.getRequestMethod())) {
if ("/internal/v1/connectivity".equals(path) && "GET".equals(exchange.getRequestMethod())) {
// 联通测试只证明网络、TLS、来源白名单和服务令牌可用;业务就绪由 readiness 继续校验。
log.info("执行器联通测试通过,来源={}", peer.getHostAddress());
respond(exchange, 200, "CONNECTED");
} else if ("/internal/v1/readiness".equals(path) && "GET".equals(exchange.getRequestMethod())) {
checkReady();
log.debug("执行器就绪检查通过,来源={}", peer.getHostAddress());
respond(exchange, 200, "READY");
} else if ("/internal/v1/executions".equals(path) && "POST".equals(exchange.getRequestMethod())) {
// 请求体不参与任务执行;只接受空正文,避免引入无界解析和敏感参数日志。
@@ -133,9 +148,16 @@ public class IntranetExecutionServer {
}
checkReady();
notified = true;
log.info("收到任务扫描唤醒请求,来源={}", peer.getHostAddress());
respond(exchange, 202, "ACCEPTED");
} else respond(exchange, 404, "NOT_FOUND");
} catch (Exception ignored) {
} else {
log.warn("拒绝未知内网请求,来源={},方法={},路径={}", peer.getHostAddress(),
exchange.getRequestMethod(), path);
respond(exchange, 404, "NOT_FOUND");
}
} catch (Exception failure) {
log.warn("内网请求处理失败,方法={},路径={},异常类型={}", exchange.getRequestMethod(),
path(exchange), failure.getClass().getSimpleName());
respond(exchange, 503, "NOT_READY");
} finally {
exchange.close();
@@ -156,17 +178,41 @@ public class IntranetExecutionServer {
if (!notified && System.currentTimeMillis() < nextScanAt) return;
if (!processing.compareAndSet(false, true)) return;
try {
long startedAt = System.currentTimeMillis();
checkReady();
notified = false;
nextScanAt = System.currentTimeMillis() + 2000;
for (Map<String, Object> row : store.recoverable()) {
List<Map<String, Object>> rows = store.recoverable();
if (!rows.isEmpty()) log.info("开始处理链上任务批次,待检查数量={}", rows.size());
int executed = 0;
int recovered = 0;
int skipped = 0;
for (Map<String, Object> 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链上执行器已停止");
}
}
@@ -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
@@ -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));
}