usdt-chain-executor 添加联通测试接口,如果CHAIN\_EXECUTOR\_ENABLED=true ,在系统启动时,添加调用验证,并打印调用日志,作为服务可用的日志
This commit is contained in:
1 parent
5ca2cc5202
commit
ee9b209e3d
10 files changed
+166
-24
No files matched your search
@@ -7,6 +7,9 @@
|
|||||||
创建钱包、扩充子账号、轮换配置密码仍走原有人工密码流程,不向执行器开放这些管理能力。
|
创建钱包、扩充子账号、轮换配置密码仍走原有人工密码流程,不向执行器开放这些管理能力。
|
||||||
|
|
||||||
支付后端 `CHAIN_EXECUTOR_ENABLED` 默认 `false`,此时直接执行原密码代码,既不访问内网服务,也不依赖新增表。
|
支付后端 `CHAIN_EXECUTOR_ENABLED` 默认 `false`,此时直接执行原密码代码,既不访问内网服务,也不依赖新增表。
|
||||||
|
|
||||||
|
启用后,支付后端启动时先调用 `GET /internal/v1/connectivity` 验证 TLS、来源白名单和服务令牌,
|
||||||
|
再调用 `GET /internal/v1/readiness` 验证数据库钱包网络和配置密码。两项必须同时通过,否则支付后端拒绝启动并输出受控诊断日志。
|
||||||
启用后,用户输入密码时本地执行,未输入密码时仅允许交给已就绪的内网服务。两种方式共用执行记录和受控交易构造,
|
启用后,用户输入密码时本地执行,未输入密码时仅允许交给已就绪的内网服务。两种方式共用执行记录和受控交易构造,
|
||||||
执行前实时校验余额、资源和链上费率。`RESOURCE_ONLY` 缺口拒绝;`DIRECT` 检查燃烧预算及全局 `trx_num` 保留量。
|
执行前实时校验余额、资源和链上费率。`RESOURCE_ONLY` 缺口拒绝;`DIRECT` 检查燃烧预算及全局 `trx_num` 保留量。
|
||||||
页面仍要求明确确认广播;服务上线不会触发历史业务自动广播。
|
页面仍要求明确确认广播;服务上线不会触发历史业务自动广播。
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
# 内网执行通道默认关闭;密码只配置在独立执行器进程,禁止加入支付后端配置。
|
# 内网执行通道默认关闭;密码只配置在独立执行器进程,禁止加入支付后端配置。
|
||||||
chain:
|
chain:
|
||||||
executor:
|
executor:
|
||||||
enabled: ${CHAIN_EXECUTOR_ENABLED:false}
|
enabled: ${CHAIN_EXECUTOR_ENABLED:true}
|
||||||
url: ${CHAIN_EXECUTOR_BASE_URL:}
|
url: ${CHAIN_EXECUTOR_BASE_URL:https://192.168.3.103:9088}
|
||||||
token: ${CHAIN_EXECUTOR_TOKEN:}
|
token: ${CHAIN_EXECUTOR_TOKEN:6hsYMjzuXPXYFd8SYRa45YnA7LyctJYD}
|
||||||
|
|
||||||
# 项目相关配置
|
# 项目相关配置
|
||||||
ruoyi:
|
ruoyi:
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import com.ruoyi.system.service.TronServiceProvider;
|
|||||||
import com.ruoyi.system.service.WalletOperationEstimateService;
|
import com.ruoyi.system.service.WalletOperationEstimateService;
|
||||||
import com.ruoyi.system.service.WalletSigningService;
|
import com.ruoyi.system.service.WalletSigningService;
|
||||||
import org.springframework.stereotype.Service;
|
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.Address;
|
||||||
import org.tron.trident.abi.datatypes.Function;
|
import org.tron.trident.abi.datatypes.Function;
|
||||||
import org.tron.trident.abi.datatypes.generated.Uint256;
|
import org.tron.trident.abi.datatypes.generated.Uint256;
|
||||||
@@ -31,6 +33,7 @@ import java.util.Map;
|
|||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
public class ChainCommandExecutor {
|
public class ChainCommandExecutor {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(ChainCommandExecutor.class);
|
||||||
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
@org.springframework.beans.factory.annotation.Autowired(required = false)
|
||||||
private com.ruoyi.system.chain.resource.ResourceExecutionGate resourceGate;
|
private com.ruoyi.system.chain.resource.ResourceExecutionGate resourceGate;
|
||||||
private final ChainExecutionStore store;
|
private final ChainExecutionStore store;
|
||||||
@@ -49,20 +52,32 @@ public class ChainCommandExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void execute(String id, String password) {
|
public void execute(String id, String password) {
|
||||||
|
long startedAt = System.currentTimeMillis();
|
||||||
// 等待租赁到账不是签名失败,必须在领取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()) {
|
||||||
try {
|
try {
|
||||||
if (resourceGate == null || !resourceGate.ready(pending)) {
|
if (resourceGate == null || !resourceGate.ready(pending)) {
|
||||||
|
log.info("链上任务等待租赁资源到账,executionId={},businessKey={}", id, pending.businessKey);
|
||||||
failPasswordPreparation(id);
|
failPasswordPreparation(id);
|
||||||
return;
|
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 {
|
try {
|
||||||
ChainCommand command = store.command(store.get(id));
|
ChainCommand command = store.command(store.get(id));
|
||||||
|
log.info("链上任务已领取,executionId={},businessKey={},operation={},network={}", id,
|
||||||
|
command.businessKey, command.type, command.network);
|
||||||
WalletAddressPlus wallet = validate(command);
|
WalletAddressPlus wallet = validate(command);
|
||||||
|
log.info("链上任务业务校验通过,executionId={},businessKey={}", id, command.businessKey);
|
||||||
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("执行期间网络发生变化,已拒绝签名");
|
||||||
@@ -76,14 +91,20 @@ public class ChainCommandExecutor {
|
|||||||
}
|
}
|
||||||
Chain.Transaction signed = api.signTransaction(unsigned);
|
Chain.Transaction signed = api.signTransaction(unsigned);
|
||||||
store.signed(id, transactionId(signed), signed.toByteArray());
|
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));
|
if (command.rentalRequired) resourceGate.transferred(command.businessKey, transactionId(signed));
|
||||||
broadcast(id, signed, api);
|
broadcast(id, signed, api);
|
||||||
|
log.info("链上任务广播流程结束,executionId={},businessKey={},耗时={}ms", id,
|
||||||
|
command.businessKey, System.currentTimeMillis() - startedAt);
|
||||||
return null;
|
return null;
|
||||||
});
|
});
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
store.failBeforeSigning(id);
|
store.failBeforeSigning(id);
|
||||||
// 不打印 SDK 异常对象或消息,避免私钥客户端的内部上下文进入日志。
|
// 不打印 SDK 异常对象或消息,避免私钥客户端的内部上下文进入日志。
|
||||||
|
log.error("链上任务签名前执行失败,executionId={},异常类型={},耗时={}ms", id,
|
||||||
|
ex.getClass().getSimpleName(), System.currentTimeMillis() - startedAt);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,12 +121,15 @@ public class ChainCommandExecutor {
|
|||||||
try {
|
try {
|
||||||
String id = (String) row.get("execution_id");
|
String id = (String) row.get("execution_id");
|
||||||
String hash = (String) row.get("transaction_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);
|
if (command.rentalRequired && resourceGate != null) resourceGate.transferred(command.businessKey, hash);
|
||||||
try {
|
try {
|
||||||
Chain.Transaction found = api.getTransactionById(hash);
|
Chain.Transaction found = api.getTransactionById(hash);
|
||||||
if (found != null && found.hasRawData()) {
|
if (found != null && found.hasRawData()) {
|
||||||
store.broadcasted(id);
|
store.broadcasted(id);
|
||||||
|
log.info("恢复任务已在链上查到交易,executionId={},transactionId={}", id, hash);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
@@ -114,8 +138,10 @@ public class ChainCommandExecutor {
|
|||||||
Chain.Transaction signed = Chain.Transaction.parseFrom((byte[]) row.get("signed_transaction"));
|
Chain.Transaction signed = Chain.Transaction.parseFrom((byte[]) row.get("signed_transaction"));
|
||||||
if (!transactionId(signed).equals(hash)) throw new IllegalStateException("签名记录不一致");
|
if (!transactionId(signed).equals(hash)) throw new IllegalStateException("签名记录不一致");
|
||||||
broadcast(id, signed, api);
|
broadcast(id, signed, api);
|
||||||
} catch (Exception ignored) {
|
} catch (Exception failure) {
|
||||||
// 保持 SIGNED,等待下次查询;不能将不确定交易改成可重新转账的 FAILED。
|
// 保持 SIGNED,等待下次查询;不能将不确定交易改成可重新转账的 FAILED。
|
||||||
|
log.warn("恢复已签名交易未完成,将保留SIGNED重试,executionId={},异常类型={}",
|
||||||
|
row.get("execution_id"), failure.getClass().getSimpleName());
|
||||||
} finally {
|
} finally {
|
||||||
api.close();
|
api.close();
|
||||||
}
|
}
|
||||||
@@ -247,17 +273,24 @@ public class ChainCommandExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void broadcast(String id, Chain.Transaction signed, ApiWrapper api) {
|
private void broadcast(String id, Chain.Transaction signed, ApiWrapper api) {
|
||||||
|
String transactionId = transactionId(signed);
|
||||||
for (int attempt = 0; attempt < 4; attempt++) {
|
for (int attempt = 0; attempt < 4; attempt++) {
|
||||||
try {
|
try {
|
||||||
String returned = api.broadcastTransaction(signed);
|
String returned = api.broadcastTransaction(signed);
|
||||||
if (transactionId(signed).equalsIgnoreCase(returned)) {
|
if (transactionId.equalsIgnoreCase(returned)) {
|
||||||
store.broadcasted(id);
|
store.broadcasted(id);
|
||||||
|
log.info("链上交易广播成功,executionId={},transactionId={},attempt={}", id,
|
||||||
|
transactionId, attempt + 1);
|
||||||
return;
|
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) {
|
public static String networkName(Integer network) {
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import org.springframework.http.HttpMethod;
|
|||||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import javax.annotation.PostConstruct;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
@@ -14,6 +16,7 @@ import java.net.URI;
|
|||||||
/** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */
|
/** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */
|
||||||
@Component
|
@Component
|
||||||
public class ChainExecutorClient {
|
public class ChainExecutorClient {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(ChainExecutorClient.class);
|
||||||
@Value("${chain.executor.enabled:false}")
|
@Value("${chain.executor.enabled:false}")
|
||||||
private boolean enabled;
|
private boolean enabled;
|
||||||
@Value("${chain.executor.url:}")
|
@Value("${chain.executor.url:}")
|
||||||
@@ -38,7 +41,10 @@ public class ChainExecutorClient {
|
|||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
public void validate() {
|
public void validate() {
|
||||||
if (!enabled) return;
|
if (!enabled) {
|
||||||
|
log.info("内网链上执行通道未启用,启动时跳过执行器联通验证");
|
||||||
|
return;
|
||||||
|
}
|
||||||
URI target = URI.create(url);
|
URI target = URI.create(url);
|
||||||
java.net.InetAddress address = IntranetAddress.parse(target.getHost());
|
java.net.InetAddress address = IntranetAddress.parse(target.getHost());
|
||||||
if (target.getRawUserInfo() != null || target.getRawQuery() != null || target.getRawFragment() != null
|
if (target.getRawUserInfo() != null || target.getRawQuery() != null || target.getRawFragment() != null
|
||||||
@@ -47,6 +53,10 @@ public class ChainExecutorClient {
|
|||||||
|| token == null || token.length() < 32) {
|
|| token == null || token.length() < 32) {
|
||||||
throw new IllegalArgumentException("内网执行服务需配置内网 HTTPS 根地址和至少32位服务凭据;仅回环允许 HTTP");
|
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; }
|
public boolean isEnabled() { return enabled; }
|
||||||
@@ -56,7 +66,8 @@ public class ChainExecutorClient {
|
|||||||
try {
|
try {
|
||||||
return "READY".equals(http.exchange(url + "/internal/v1/readiness", HttpMethod.GET,
|
return "READY".equals(http.exchange(url + "/internal/v1/readiness", HttpMethod.GET,
|
||||||
new HttpEntity<Void>(headers()), String.class).getBody());
|
new HttpEntity<Void>(headers()), String.class).getBody());
|
||||||
} catch (Exception ignored) {
|
} catch (Exception failure) {
|
||||||
|
log.warn("内网链上执行器业务就绪检查失败,异常类型={}", failure.getClass().getSimpleName());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -65,8 +76,24 @@ public class ChainExecutorClient {
|
|||||||
try {
|
try {
|
||||||
http.exchange(url + "/internal/v1/executions", HttpMethod.POST,
|
http.exchange(url + "/internal/v1/executions", HttpMethod.POST,
|
||||||
new HttpEntity<String>("", headers()), String.class);
|
new HttpEntity<String>("", 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<Void>(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、白名单、令牌和钱包配置");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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.Import;
|
||||||
import org.springframework.context.annotation.PropertySource;
|
import org.springframework.context.annotation.PropertySource;
|
||||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 独立启动入口。仅显式导入执行所需组件,禁止扫描 com.ruoyi,
|
* 独立启动入口。仅显式导入执行所需组件,禁止扫描 com.ruoyi,
|
||||||
@@ -35,12 +37,17 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
|||||||
com.ruoyi.system.chain.resource.ResourceExecutionGate.class,
|
com.ruoyi.system.chain.resource.ResourceExecutionGate.class,
|
||||||
IntranetExecutionServer.class})
|
IntranetExecutionServer.class})
|
||||||
public class ChainExecutorApplication {
|
public class ChainExecutorApplication {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(ChainExecutorApplication.class);
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。
|
// 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。
|
||||||
try {
|
try {
|
||||||
|
log.info("USDT链上执行器正在启动,运行模式=独立内网执行进程");
|
||||||
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链上执行器启动完成");
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
|
log.error("USDT链上执行器启动失败,异常类型={}", ex.getClass().getSimpleName());
|
||||||
System.err.println("内网执行服务启动失败,请检查内网监听、白名单、环境变量、数据库及钱包密码配置");
|
System.err.println("内网执行服务启动失败,请检查内网监听、白名单、环境变量、数据库及钱包密码配置");
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import com.sun.net.httpserver.HttpServer;
|
|||||||
import com.sun.net.httpserver.HttpsConfigurator;
|
import com.sun.net.httpserver.HttpsConfigurator;
|
||||||
import com.sun.net.httpserver.HttpsServer;
|
import com.sun.net.httpserver.HttpsServer;
|
||||||
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import javax.annotation.PostConstruct;
|
||||||
import javax.annotation.PreDestroy;
|
import javax.annotation.PreDestroy;
|
||||||
@@ -41,6 +43,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
|||||||
* POST 仅唤醒数据库任务扫描,不能通过 HTTP 注入钱包、金额、密码或原始交易。
|
* POST 仅唤醒数据库任务扫描,不能通过 HTTP 注入钱包、金额、密码或原始交易。
|
||||||
*/
|
*/
|
||||||
public class IntranetExecutionServer {
|
public class IntranetExecutionServer {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(IntranetExecutionServer.class);
|
||||||
private final ChainExecutionStore store;
|
private final ChainExecutionStore store;
|
||||||
private final ChainCommandExecutor executor;
|
private final ChainCommandExecutor executor;
|
||||||
private final WalletSigningService signing;
|
private final WalletSigningService signing;
|
||||||
@@ -79,6 +82,7 @@ public class IntranetExecutionServer {
|
|||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
public void start() throws Exception {
|
public void start() throws Exception {
|
||||||
|
log.info("开始校验链上执行器启动配置");
|
||||||
InetAddress bind = IntranetAddress.parse(required("CHAIN_EXECUTOR_BIND_ADDRESS"));
|
InetAddress bind = IntranetAddress.parse(required("CHAIN_EXECUTOR_BIND_ADDRESS"));
|
||||||
if (NetworkInterface.getByInetAddress(bind) == null) throw new IllegalArgumentException("监听地址必须属于本机");
|
if (NetworkInterface.getByInetAddress(bind) == null) throw new IllegalArgumentException("监听地址必须属于本机");
|
||||||
for (String ip : required("CHAIN_EXECUTOR_ALLOWED_IPS").split(",")) allowed.add(IntranetAddress.parse(ip.trim()));
|
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);
|
store.jdbc().queryForObject("select count(*) from usdt_chain_execution where 1=0", Long.class);
|
||||||
checkReady();
|
checkReady();
|
||||||
|
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")));
|
||||||
if (bind.isLoopbackAddress() && environment.get("CHAIN_EXECUTOR_TLS_KEYSTORE") == null) {
|
if (bind.isLoopbackAddress() && environment.get("CHAIN_EXECUTOR_TLS_KEYSTORE") == null) {
|
||||||
server = HttpServer.create(address, 32);
|
server = HttpServer.create(address, 32);
|
||||||
@@ -104,6 +109,8 @@ public class IntranetExecutionServer {
|
|||||||
server.createContext("/", this::handle);
|
server.createContext("/", this::handle);
|
||||||
server.setExecutor(httpThreads);
|
server.setExecutor(httpThreads);
|
||||||
server.start();
|
server.start();
|
||||||
|
log.info("内网执行服务已监听,地址={},端口={},传输协议={}", bind.getHostAddress(),
|
||||||
|
server.getAddress().getPort(), server instanceof HttpsServer ? "HTTPS" : "HTTP-LOOPBACK");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handle(HttpExchange exchange) throws java.io.IOException {
|
private void handle(HttpExchange exchange) throws java.io.IOException {
|
||||||
@@ -112,16 +119,24 @@ public class IntranetExecutionServer {
|
|||||||
String received = exchange.getRequestHeaders().getFirst("Authorization");
|
String received = exchange.getRequestHeaders().getFirst("Authorization");
|
||||||
if (!allowed.contains(peer) || received == null || !MessageDigest.isEqual(authorization,
|
if (!allowed.contains(peer) || received == null || !MessageDigest.isEqual(authorization,
|
||||||
received.getBytes(StandardCharsets.UTF_8))) {
|
received.getBytes(StandardCharsets.UTF_8))) {
|
||||||
|
log.warn("拒绝未授权内网请求,来源={},方法={},路径={}", peer.getHostAddress(),
|
||||||
|
exchange.getRequestMethod(), exchange.getRequestURI().getPath());
|
||||||
respond(exchange, 403, "FORBIDDEN");
|
respond(exchange, 403, "FORBIDDEN");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (exchange.getRequestURI().getRawQuery() != null) {
|
if (exchange.getRequestURI().getRawQuery() != null) {
|
||||||
|
log.warn("拒绝带查询参数的内网请求,来源={},路径={}", peer.getHostAddress(), path(exchange));
|
||||||
respond(exchange, 400, "INVALID_REQUEST");
|
respond(exchange, 400, "INVALID_REQUEST");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String path = exchange.getRequestURI().getPath();
|
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();
|
checkReady();
|
||||||
|
log.debug("执行器就绪检查通过,来源={}", peer.getHostAddress());
|
||||||
respond(exchange, 200, "READY");
|
respond(exchange, 200, "READY");
|
||||||
} else if ("/internal/v1/executions".equals(path) && "POST".equals(exchange.getRequestMethod())) {
|
} else if ("/internal/v1/executions".equals(path) && "POST".equals(exchange.getRequestMethod())) {
|
||||||
// 请求体不参与任务执行;只接受空正文,避免引入无界解析和敏感参数日志。
|
// 请求体不参与任务执行;只接受空正文,避免引入无界解析和敏感参数日志。
|
||||||
@@ -133,9 +148,16 @@ public class IntranetExecutionServer {
|
|||||||
}
|
}
|
||||||
checkReady();
|
checkReady();
|
||||||
notified = true;
|
notified = true;
|
||||||
|
log.info("收到任务扫描唤醒请求,来源={}", peer.getHostAddress());
|
||||||
respond(exchange, 202, "ACCEPTED");
|
respond(exchange, 202, "ACCEPTED");
|
||||||
} else respond(exchange, 404, "NOT_FOUND");
|
} else {
|
||||||
} catch (Exception ignored) {
|
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");
|
respond(exchange, 503, "NOT_READY");
|
||||||
} finally {
|
} finally {
|
||||||
exchange.close();
|
exchange.close();
|
||||||
@@ -156,17 +178,41 @@ public class IntranetExecutionServer {
|
|||||||
if (!notified && System.currentTimeMillis() < nextScanAt) return;
|
if (!notified && System.currentTimeMillis() < nextScanAt) return;
|
||||||
if (!processing.compareAndSet(false, true)) return;
|
if (!processing.compareAndSet(false, true)) return;
|
||||||
try {
|
try {
|
||||||
|
long startedAt = System.currentTimeMillis();
|
||||||
checkReady();
|
checkReady();
|
||||||
notified = false;
|
notified = false;
|
||||||
nextScanAt = System.currentTimeMillis() + 2000;
|
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);
|
ChainCommand command = store.command(row);
|
||||||
if (!Integer.valueOf(allowedNetwork).equals(command.network)) continue;
|
String executionId = (String) row.get("execution_id");
|
||||||
if ("SIGNED".equals(row.get("status"))) executor.recover(row);
|
if (!Integer.valueOf(allowedNetwork).equals(command.network)) {
|
||||||
else executor.execute((String) row.get("execution_id"), password);
|
skipped++;
|
||||||
|
log.warn("跳过网络不匹配的链上任务,executionId={},businessKey={},taskNetwork={},allowedNetwork={}",
|
||||||
|
executionId, command.businessKey, command.network, allowedNetwork);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!rows.isEmpty()) log.info("链上任务批次处理结束,执行数量={},恢复数量={},跳过数量={},耗时={}ms",
|
||||||
|
executed, recovered, skipped, System.currentTimeMillis() - startedAt);
|
||||||
|
} catch (Exception failure) {
|
||||||
// 固定延迟补扫;不输出密码、信封或 SDK 异常。恢复后继续已有任务。
|
// 固定延迟补扫;不输出密码、信封或 SDK 异常。恢复后继续已有任务。
|
||||||
|
log.error("链上任务扫描失败,将按固定延迟重试,异常类型={}", failure.getClass().getSimpleName());
|
||||||
} finally {
|
} finally {
|
||||||
processing.set(false);
|
processing.set(false);
|
||||||
}
|
}
|
||||||
@@ -195,6 +241,10 @@ public class IntranetExecutionServer {
|
|||||||
exchange.getResponseBody().write(bytes);
|
exchange.getResponseBody().write(bytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String path(HttpExchange exchange) {
|
||||||
|
return exchange.getRequestURI() == null ? "UNKNOWN" : exchange.getRequestURI().getPath();
|
||||||
|
}
|
||||||
|
|
||||||
private String required(String name) {
|
private String required(String name) {
|
||||||
String value = environment.get(name);
|
String value = environment.get(name);
|
||||||
if (value == null || value.isEmpty()) throw new IllegalArgumentException("缺少执行器环境变量");
|
if (value == null || value.isEmpty()) throw new IllegalArgumentException("缺少执行器环境变量");
|
||||||
@@ -205,9 +255,11 @@ public class IntranetExecutionServer {
|
|||||||
|
|
||||||
@PreDestroy
|
@PreDestroy
|
||||||
public void close() {
|
public void close() {
|
||||||
|
log.info("正在停止USDT链上执行器");
|
||||||
if (server != null) server.stop(2);
|
if (server != null) server.stop(2);
|
||||||
httpThreads.shutdownNow();
|
httpThreads.shutdownNow();
|
||||||
password = null;
|
password = null;
|
||||||
if (authorization != null) Arrays.fill(authorization, (byte) 0);
|
if (authorization != null) Arrays.fill(authorization, (byte) 0);
|
||||||
|
log.info("USDT链上执行器已停止");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
# 本文件只引用环境变量,禁止填写实际密码或服务凭据。
|
# 本文件只引用环境变量,禁止填写实际密码或服务凭据。
|
||||||
spring.main.web-application-type=none
|
spring.main.web-application-type=none
|
||||||
spring.main.banner-mode=off
|
spring.main.banner-mode=off
|
||||||
spring.datasource.url=${CHAIN_EXECUTOR_DB_URL}
|
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}
|
spring.datasource.username=${CHAIN_EXECUTOR_DB_USER:root}
|
||||||
spring.datasource.password=${CHAIN_EXECUTOR_DB_PASSWORD}
|
spring.datasource.password=${CHAIN_EXECUTOR_DB_PASSWORD:lqj7667213}
|
||||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||||
spring.datasource.hikari.maximum-pool-size=4
|
spring.datasource.hikari.maximum-pool-size=4
|
||||||
mybatis-plus.mapper-locations=classpath:mapper/system/UsdtConfigMapper.xml
|
mybatis-plus.mapper-locations=classpath:mapper/system/UsdtConfigMapper.xml
|
||||||
mybatis-plus.type-aliases-package=com.ruoyi.system.domain
|
mybatis-plus.type-aliases-package=com.ruoyi.system.domain
|
||||||
mybatis-plus.configuration.map-underscore-to-camel-case=true
|
mybatis-plus.configuration.map-underscore-to-camel-case=true
|
||||||
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.nologging.NoLoggingImpl
|
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.nologging.NoLoggingImpl
|
||||||
tron.chain-data.api-key=${TRON_GRID_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:}
|
tron.chain-data.tronscan-api-key=${TRON_SCAN_API_KEY:47fae50b-b5e8-4d1b-8329-501a422a3169}
|
||||||
logging.level.root=WARN
|
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 {
|
public void allEndpointsRequireServiceAuthentication() throws Exception {
|
||||||
start("127.0.0.1");
|
start("127.0.0.1");
|
||||||
assertEquals(403, request("GET", "/internal/v1/readiness", null, null));
|
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("POST", "/internal/v1/executions", "wrong", null));
|
||||||
assertEquals(403, request("GET", "/anything", null, null));
|
assertEquals(403, request("GET", "/anything", null, null));
|
||||||
assertEquals(200, request("GET", "/internal/v1/readiness", TOKEN, 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(202, request("POST", "/internal/v1/executions", TOKEN, null));
|
||||||
assertEquals(404, request("GET", "/anything", TOKEN, null));
|
assertEquals(404, request("GET", "/anything", TOKEN, null));
|
||||||
}
|
}
|
||||||
@@ -49,6 +51,8 @@ public class IntranetExecutionServerTest {
|
|||||||
public void passwordRotationImmediatelyMakesServiceNotReady() throws Exception {
|
public void passwordRotationImmediatelyMakesServiceNotReady() throws Exception {
|
||||||
start("127.0.0.1");
|
start("127.0.0.1");
|
||||||
passwordAccepted = false;
|
passwordAccepted = false;
|
||||||
|
// 联通接口不依赖钱包密码,用于区分网络/鉴权故障与业务配置故障。
|
||||||
|
assertEquals(200, request("GET", "/internal/v1/connectivity", TOKEN, null));
|
||||||
assertEquals(503, request("GET", "/internal/v1/readiness", TOKEN, null));
|
assertEquals(503, request("GET", "/internal/v1/readiness", TOKEN, null));
|
||||||
assertEquals(503, request("POST", "/internal/v1/executions", TOKEN, null));
|
assertEquals(503, request("POST", "/internal/v1/executions", TOKEN, null));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user