接入租赁平台
This commit is contained in:
1 parent
c035263bc6
commit
1c2d15b2a9
51 files changed
+3631
-15
No files matched your search
@@ -0,0 +1,14 @@
|
||||
export CHAIN_EXECUTOR_TOKEN=6hsYMjzuXPXYFd8SYRa45YnA7LyctJYD
|
||||
export CHAIN_EXECUTOR_DB_URL=jdbc:mysql://gitlab.chatshop.com.cn:3309/epusdt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&connectionTimeZone=LOCAL&forceConnectionTimeZoneToSession=true
|
||||
export CHAIN_EXECUTOR_DB_USER=root
|
||||
export CHAIN_EXECUTOR_DB_PASSWORD=lqj7667213
|
||||
export TRON_GRID_API_KEY=719b2ba2-dedd-48ad-99a6-df1caa6f08ae
|
||||
export TRON_SCAN_API_KEY=47fae50b-b5e8-4d1b-8329-501a422a3169
|
||||
export CHAIN_EXECUTOR_BIND_ADDRESS=192.168.3.103
|
||||
export CHAIN_EXECUTOR_PORT=9088
|
||||
export CHAIN_EXECUTOR_ALLOWED_IPS=192.168.3.103,192.168.3.106
|
||||
export CHAIN_EXECUTOR_CONFIGURATION_PASSWORD=lqj7667213.520
|
||||
export CHAIN_EXECUTOR_ALLOWED_NETWORK=NILE
|
||||
export CHAIN_EXECUTOR_BROADCAST_ENABLED=true
|
||||
export CHAIN_EXECUTOR_TLS_KEYSTORE=/etc/nginx/certs/rent-truststore.p12
|
||||
export CHAIN_EXECUTOR_TLS_PASSWORD=lqj7667213
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent><groupId>com.ruoyi</groupId><artifactId>ruoyi</artifactId><version>3.4.0</version></parent>
|
||||
<artifactId>usdt-chain-executor</artifactId>
|
||||
<description>仅内网调用的独立链上执行进程</description>
|
||||
<dependencies>
|
||||
<dependency><groupId>com.ruoyi</groupId><artifactId>ruoyi-system</artifactId></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>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
|
||||
<!-- 与 ruoyi-system 的 Trident 运行时统一,不能被其他传递依赖降级。 -->
|
||||
<dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>3.25.5</version></dependency>
|
||||
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency>
|
||||
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>1.4.199</version><scope>test</scope></dependency>
|
||||
</dependencies>
|
||||
<build><plugins>
|
||||
<plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.2.13.RELEASE</version>
|
||||
<configuration><mainClass>com.ruoyi.executor.ChainExecutorApplication</mainClass></configuration>
|
||||
<executions><execution><goals><goal>repackage</goal></goals></execution></executions>
|
||||
</plugin>
|
||||
</plugins></build>
|
||||
</project>
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.ruoyi.executor;
|
||||
|
||||
import com.ruoyi.system.chain.ChainCommandExecutor;
|
||||
import com.ruoyi.system.chain.ChainExecutionStore;
|
||||
import com.ruoyi.system.mapper.UsdtConfigMapper;
|
||||
import com.ruoyi.system.service.TronChainDataClient;
|
||||
import com.ruoyi.system.service.TronServiceProvider;
|
||||
import com.ruoyi.system.service.WalletOperationEstimateService;
|
||||
import com.ruoyi.system.service.WalletSigningService;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.mybatis.spring.mapper.MapperFactoryBean;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* 独立启动入口。仅显式导入执行所需组件,禁止扫描 com.ruoyi,
|
||||
* 防止启动支付 HTTP API、Telegram、订单扫描、回调和账务结算任务。
|
||||
*/
|
||||
@Configuration
|
||||
@EnableAutoConfiguration(excludeName = {
|
||||
"org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration",
|
||||
"org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration"})
|
||||
@EnableScheduling
|
||||
@PropertySource("classpath:executor.properties")
|
||||
@Import({ChainExecutionStore.class, ChainCommandExecutor.class, WalletSigningService.class,
|
||||
TronServiceProvider.class, TronChainDataClient.class, WalletOperationEstimateService.class,
|
||||
com.ruoyi.system.chain.resource.ResourceLeaseStore.class,
|
||||
com.ruoyi.system.chain.resource.ResourceProbe.class,
|
||||
com.ruoyi.system.chain.resource.ResourceExecutionGate.class,
|
||||
IntranetExecutionServer.class})
|
||||
public class ChainExecutorApplication {
|
||||
public static void main(String[] args) {
|
||||
// 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。
|
||||
try {
|
||||
new SpringApplicationBuilder(ChainExecutorApplication.class).web(WebApplicationType.NONE)
|
||||
.properties("spring.config.name=executor").run(args);
|
||||
} catch (Exception ex) {
|
||||
System.err.println("内网执行服务启动失败,请检查内网监听、白名单、环境变量、数据库及钱包密码配置");
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MapperFactoryBean<UsdtConfigMapper> usdtConfigMapper(SqlSessionFactory factory) {
|
||||
MapperFactoryBean<UsdtConfigMapper> mapper = new MapperFactoryBean<>(UsdtConfigMapper.class);
|
||||
mapper.setSqlSessionFactory(factory);
|
||||
return mapper;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.ruoyi.executor;
|
||||
|
||||
import com.ruoyi.system.chain.ChainCommand;
|
||||
import com.ruoyi.system.chain.ChainCommandExecutor;
|
||||
import com.ruoyi.system.chain.ChainExecutionStore;
|
||||
import com.ruoyi.system.chain.IntranetAddress;
|
||||
import com.ruoyi.system.domain.UsdtConfig;
|
||||
import com.ruoyi.system.mapper.UsdtConfigMapper;
|
||||
import com.ruoyi.system.service.WalletSigningService;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
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 javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.KeyStore;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* 唯一网络入口:实际 TCP 对端 IP 白名单 + 独立 Bearer 凭据,所有路径统一鉴权。
|
||||
* 不读取 X-Forwarded-For,不提供公网健康检查或任意交易签名接口。
|
||||
* POST 仅唤醒数据库任务扫描,不能通过 HTTP 注入钱包、金额、密码或原始交易。
|
||||
*/
|
||||
public class IntranetExecutionServer {
|
||||
private final ChainExecutionStore store;
|
||||
private final ChainCommandExecutor executor;
|
||||
private final WalletSigningService signing;
|
||||
private final UsdtConfigMapper configs;
|
||||
private final Map<String, String> environment;
|
||||
private final AtomicBoolean processing = new AtomicBoolean();
|
||||
private final List<InetAddress> allowed = new ArrayList<>();
|
||||
private final ThreadPoolExecutor httpThreads = new ThreadPoolExecutor(2, 4, 30, TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<Runnable>(32), runnable -> {
|
||||
Thread thread = new Thread(runnable, "intranet-executor-http");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}, new ThreadPoolExecutor.AbortPolicy());
|
||||
private HttpServer server;
|
||||
private String password;
|
||||
private byte[] authorization;
|
||||
private int allowedNetwork;
|
||||
private volatile boolean notified;
|
||||
private volatile long nextScanAt;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
public IntranetExecutionServer(ChainExecutionStore store, ChainCommandExecutor executor,
|
||||
WalletSigningService signing, UsdtConfigMapper configs) {
|
||||
this(store, executor, signing, configs, System.getenv());
|
||||
}
|
||||
|
||||
/** 测试可注入独立环境,生产构造器只读取进程环境变量,不从 HTTP 接收密码。 */
|
||||
IntranetExecutionServer(ChainExecutionStore store, ChainCommandExecutor executor,
|
||||
WalletSigningService signing, UsdtConfigMapper configs, Map<String, String> environment) {
|
||||
this.store = store;
|
||||
this.executor = executor;
|
||||
this.signing = signing;
|
||||
this.configs = configs;
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void start() throws Exception {
|
||||
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()));
|
||||
String token = required("CHAIN_EXECUTOR_TOKEN");
|
||||
if (token.length() < 32) throw new IllegalArgumentException("服务凭据至少32位");
|
||||
authorization = ("Bearer " + token).getBytes(StandardCharsets.UTF_8);
|
||||
password = required("CHAIN_EXECUTOR_CONFIGURATION_PASSWORD");
|
||||
String network = required("CHAIN_EXECUTOR_ALLOWED_NETWORK");
|
||||
if (!"NILE".equals(network) && !"MAINNET".equals(network)) throw new IllegalArgumentException("网络配置无效");
|
||||
allowedNetwork = "NILE".equals(network) ? 0 : 1;
|
||||
if (!"true".equals(required("CHAIN_EXECUTOR_BROADCAST_ENABLED"))) throw new IllegalArgumentException("未允许广播");
|
||||
// 启动校验表结构和解密能力,不执行任何链上广播。
|
||||
store.jdbc().queryForObject("select count(*) from usdt_chain_execution where 1=0", Long.class);
|
||||
checkReady();
|
||||
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);
|
||||
} else {
|
||||
HttpsServer https = HttpsServer.create(address, 32);
|
||||
https.setHttpsConfigurator(new HttpsConfigurator(tlsContext()));
|
||||
server = https;
|
||||
}
|
||||
server.createContext("/", this::handle);
|
||||
server.setExecutor(httpThreads);
|
||||
server.start();
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) throws java.io.IOException {
|
||||
try {
|
||||
InetAddress peer = exchange.getRemoteAddress().getAddress();
|
||||
String received = exchange.getRequestHeaders().getFirst("Authorization");
|
||||
if (!allowed.contains(peer) || received == null || !MessageDigest.isEqual(authorization,
|
||||
received.getBytes(StandardCharsets.UTF_8))) {
|
||||
respond(exchange, 403, "FORBIDDEN");
|
||||
return;
|
||||
}
|
||||
if (exchange.getRequestURI().getRawQuery() != null) {
|
||||
respond(exchange, 400, "INVALID_REQUEST");
|
||||
return;
|
||||
}
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
if ("/internal/v1/readiness".equals(path) && "GET".equals(exchange.getRequestMethod())) {
|
||||
checkReady();
|
||||
respond(exchange, 200, "READY");
|
||||
} else if ("/internal/v1/executions".equals(path) && "POST".equals(exchange.getRequestMethod())) {
|
||||
// 请求体不参与任务执行;只接受空正文,避免引入无界解析和敏感参数日志。
|
||||
if (exchange.getRequestHeaders().getFirst("Transfer-Encoding") != null
|
||||
|| exchange.getRequestHeaders().getFirst("Content-Length") != null
|
||||
&& !"0".equals(exchange.getRequestHeaders().getFirst("Content-Length"))) {
|
||||
respond(exchange, 400, "EMPTY_BODY_REQUIRED");
|
||||
return;
|
||||
}
|
||||
checkReady();
|
||||
notified = true;
|
||||
respond(exchange, 202, "ACCEPTED");
|
||||
} else respond(exchange, 404, "NOT_FOUND");
|
||||
} catch (Exception ignored) {
|
||||
respond(exchange, 503, "NOT_READY");
|
||||
} finally {
|
||||
exchange.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void checkReady() {
|
||||
UsdtConfig config = configs.selectFirst();
|
||||
if (config == null || config.getTronNetType() == null || config.getTronNetType() != allowedNetwork) {
|
||||
throw new IllegalStateException("网络不匹配");
|
||||
}
|
||||
// 每次就绪检查验证当前信封,密码轮换后立即停止接收新任务。
|
||||
signing.validateConfigurationPassword(password);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 200, initialDelay = 2000)
|
||||
public void process() {
|
||||
if (!notified && System.currentTimeMillis() < nextScanAt) return;
|
||||
if (!processing.compareAndSet(false, true)) return;
|
||||
try {
|
||||
checkReady();
|
||||
notified = false;
|
||||
nextScanAt = System.currentTimeMillis() + 2000;
|
||||
for (Map<String, Object> row : store.recoverable()) {
|
||||
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);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 固定延迟补扫;不输出密码、信封或 SDK 异常。恢复后继续已有任务。
|
||||
} finally {
|
||||
processing.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
private SSLContext tlsContext() throws Exception {
|
||||
char[] secret = required("CHAIN_EXECUTOR_TLS_PASSWORD").toCharArray();
|
||||
try (InputStream stream = Files.newInputStream(Paths.get(required("CHAIN_EXECUTOR_TLS_KEYSTORE")))) {
|
||||
KeyStore keys = KeyStore.getInstance("PKCS12");
|
||||
keys.load(stream, secret);
|
||||
KeyManagerFactory managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
|
||||
managers.init(keys, secret);
|
||||
SSLContext context = SSLContext.getInstance("TLSv1.2");
|
||||
context.init(managers.getKeyManagers(), null, null);
|
||||
return context;
|
||||
} finally {
|
||||
Arrays.fill(secret, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
private static void respond(HttpExchange exchange, int status, String message) throws java.io.IOException {
|
||||
byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
|
||||
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
}
|
||||
|
||||
private String required(String name) {
|
||||
String value = environment.get(name);
|
||||
if (value == null || value.isEmpty()) throw new IllegalArgumentException("缺少执行器环境变量");
|
||||
return value;
|
||||
}
|
||||
|
||||
int listeningPort() { return server.getAddress().getPort(); }
|
||||
|
||||
@PreDestroy
|
||||
public void close() {
|
||||
if (server != null) server.stop(2);
|
||||
httpThreads.shutdownNow();
|
||||
password = null;
|
||||
if (authorization != null) Arrays.fill(authorization, (byte) 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# 本文件只引用环境变量,禁止填写实际密码或服务凭据。
|
||||
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.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:}
|
||||
logging.level.root=WARN
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.ruoyi.executor;
|
||||
|
||||
import com.ruoyi.system.chain.ChainCommandExecutor;
|
||||
import com.ruoyi.system.demo.WalletEnvelopeEncryptionDemo;
|
||||
import com.ruoyi.system.demo.WalletEnvelopeEncryptionDemo.EncryptedEnvelope;
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* 独立子进程启动真实 Spring 配置、MyBatis Mapper 和解密服务。
|
||||
* 使用独立 H2 与一次性测试信封;通过真实环境变量注入密码,不读本机 .env,不访问外部网络。
|
||||
*/
|
||||
public class ExecutorBootstrapTest {
|
||||
private static final String JDBC = "jdbc:h2:mem:executorSmoke;MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1";
|
||||
private static final String PASSWORD = "test-only-bootstrap-password";
|
||||
private static final String TOKEN = "test-only-bootstrap-token-01234567890123456789";
|
||||
|
||||
@Test
|
||||
public void isolatedApplicationStartsWithoutPaymentControllersOrSchedulers() throws Exception {
|
||||
String java = System.getProperty("java.home") + "/bin/java";
|
||||
String classpath = System.getProperty("surefire.test.class.path", System.getProperty("java.class.path"));
|
||||
ProcessBuilder builder = new ProcessBuilder(java, "-cp", classpath, Probe.class.getName()).redirectErrorStream(true);
|
||||
Map<String, String> env = builder.environment();
|
||||
// 覆盖全部测试所需变量,避免继承真实执行器配置;跨机 TLS 配置也必须移除。
|
||||
env.keySet().removeIf(name -> name.startsWith("CHAIN_EXECUTOR_"));
|
||||
env.put("CHAIN_EXECUTOR_BIND_ADDRESS", "127.0.0.1");
|
||||
env.put("CHAIN_EXECUTOR_PORT", "0");
|
||||
env.put("CHAIN_EXECUTOR_ALLOWED_IPS", "127.0.0.1");
|
||||
env.put("CHAIN_EXECUTOR_ALLOWED_NETWORK", "NILE");
|
||||
env.put("CHAIN_EXECUTOR_BROADCAST_ENABLED", "true");
|
||||
env.put("CHAIN_EXECUTOR_CONFIGURATION_PASSWORD", PASSWORD);
|
||||
env.put("CHAIN_EXECUTOR_TOKEN", TOKEN);
|
||||
env.put("CHAIN_EXECUTOR_DB_URL", JDBC);
|
||||
env.put("CHAIN_EXECUTOR_DB_USER", "sa");
|
||||
env.put("CHAIN_EXECUTOR_DB_PASSWORD", "");
|
||||
Process process = builder.start();
|
||||
ExecutorService reader = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<String> captured = reader.submit(() -> {
|
||||
StringBuilder text = new StringBuilder();
|
||||
try (BufferedReader lines = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = lines.readLine()) != null) text.append(line).append('\n');
|
||||
}
|
||||
return text.toString();
|
||||
});
|
||||
assertTrue("独立服务启动超时", process.waitFor(60, TimeUnit.SECONDS));
|
||||
String output = captured.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(output, 0, process.exitValue());
|
||||
assertTrue(output, output.contains("EXECUTOR_BOOTSTRAP_OK"));
|
||||
assertFalse("密码不得进入启动输出", output.contains(PASSWORD));
|
||||
} finally {
|
||||
process.destroyForcibly();
|
||||
reader.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
public static class Probe {
|
||||
public static void main(String[] args) throws Exception {
|
||||
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_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, "
|
||||
+ "mnemonic_nonce varchar, encrypted_dek varchar, dek_nonce varchar, key_salt varchar, password_salt varchar, "
|
||||
+ "password_hash varchar, rotated_at timestamp, trx_num decimal, token_address varchar, usdt_balance decimal, trx_balance decimal)");
|
||||
EncryptedEnvelope envelope = WalletEnvelopeEncryptionDemo.create(PASSWORD.toCharArray(), 1).envelope;
|
||||
jdbc.update("insert into usdt_config (id,tron_net_type,version,encryption_algorithm,password_kdf,iterations,encrypted_mnemonic,"
|
||||
+ "mnemonic_nonce,encrypted_dek,dek_nonce,key_salt,password_salt,password_hash) values (1,0,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
envelope.version, envelope.encryptionAlgorithm, envelope.passwordKdf, envelope.iterations,
|
||||
envelope.encryptedMnemonic, envelope.mnemonicNonce, envelope.encryptedDek, envelope.dekNonce,
|
||||
envelope.keySalt, envelope.passwordSalt, envelope.passwordHash);
|
||||
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(ChainExecutorApplication.class)
|
||||
.web(WebApplicationType.NONE).properties("spring.config.name=executor")
|
||||
.run("--spring.datasource.driver-class-name=org.h2.Driver", "--logging.level.root=OFF")) {
|
||||
assertNotNull(context.getBean(ChainCommandExecutor.class));
|
||||
assertEquals(0, context.getBeanNamesForType(com.ruoyi.system.controller.WalletAddressController.class).length);
|
||||
assertEquals(0, context.getBeanNamesForType(com.ruoyi.system.chain.ChainExecutionReconciler.class).length);
|
||||
assertEquals(0, context.getBeanNamesForType(com.ruoyi.system.service.PayoutProcessingService.class).length);
|
||||
IntranetExecutionServer server = context.getBean(IntranetExecutionServer.class);
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL("http://127.0.0.1:" + server.listeningPort()
|
||||
+ "/internal/v1/readiness").openConnection();
|
||||
connection.setRequestProperty("Authorization", "Bearer " + TOKEN);
|
||||
connection.setReadTimeout(2000);
|
||||
try { assertEquals(200, connection.getResponseCode()); }
|
||||
finally { connection.disconnect(); }
|
||||
System.out.println("EXECUTOR_BOOTSTRAP_OK");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package com.ruoyi.executor;
|
||||
|
||||
import com.ruoyi.system.chain.ChainExecutionStore;
|
||||
import com.ruoyi.system.chain.IntranetAddress;
|
||||
import com.ruoyi.system.domain.UsdtConfig;
|
||||
import com.ruoyi.system.mapper.UsdtConfigMapper;
|
||||
import com.ruoyi.system.service.WalletSigningService;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/** 真实回环 HTTP 集成测试;用可控解锁替身,绝不访问 TRON 或使用真实钱包密码。 */
|
||||
public class IntranetExecutionServerTest {
|
||||
private static final String TOKEN = "test-only-service-token-01234567890123456789";
|
||||
private IntranetExecutionServer server;
|
||||
private boolean passwordAccepted = true;
|
||||
private final Map<String, String> environment = new HashMap<>();
|
||||
|
||||
@After
|
||||
public void cleanup() { if (server != null) server.close(); }
|
||||
|
||||
@Test
|
||||
public void allEndpointsRequireServiceAuthentication() throws Exception {
|
||||
start("127.0.0.1");
|
||||
assertEquals(403, request("GET", "/internal/v1/readiness", 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(202, request("POST", "/internal/v1/executions", TOKEN, null));
|
||||
assertEquals(404, request("GET", "/anything", TOKEN, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forwardedHeaderCannotBypassActualPeerWhitelist() throws Exception {
|
||||
start("127.0.0.2");
|
||||
assertEquals(403, request("GET", "/internal/v1/readiness", TOKEN, "127.0.0.2"));
|
||||
assertEquals(403, request("POST", "/internal/v1/executions", TOKEN, "127.0.0.2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void passwordRotationImmediatelyMakesServiceNotReady() throws Exception {
|
||||
start("127.0.0.1");
|
||||
passwordAccepted = false;
|
||||
assertEquals(503, request("GET", "/internal/v1/readiness", TOKEN, null));
|
||||
assertEquals(503, request("POST", "/internal/v1/executions", TOKEN, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsPublicWildcardDnsAndAmbiguousAddresses() {
|
||||
for (String address : new String[] {"0.0.0.0", "8.8.8.8", "localhost", "169.254.1.1", "172.32.0.1",
|
||||
"192.168.001.2", "::", "::1", "10.0.0.256"}) {
|
||||
try { IntranetAddress.parse(address); fail(address); }
|
||||
catch (IllegalArgumentException expected) { /* fail closed */ }
|
||||
}
|
||||
for (String address : new String[] {"10.0.0.1", "172.16.0.1", "172.31.255.254", "192.168.0.1", "127.0.0.1"}) {
|
||||
assertNotNull(IntranetAddress.parse(address));
|
||||
}
|
||||
}
|
||||
|
||||
private void start(String allowed) throws Exception {
|
||||
environment.put("CHAIN_EXECUTOR_BIND_ADDRESS", "127.0.0.1");
|
||||
environment.put("CHAIN_EXECUTOR_PORT", "0");
|
||||
environment.put("CHAIN_EXECUTOR_ALLOWED_IPS", allowed);
|
||||
environment.put("CHAIN_EXECUTOR_TOKEN", TOKEN);
|
||||
environment.put("CHAIN_EXECUTOR_CONFIGURATION_PASSWORD", "test-only-password");
|
||||
environment.put("CHAIN_EXECUTOR_ALLOWED_NETWORK", "NILE");
|
||||
environment.put("CHAIN_EXECUTOR_BROADCAST_ENABLED", "true");
|
||||
ChainExecutionStore store = new ChainExecutionStore(new DriverManagerDataSource(
|
||||
"jdbc:h2:mem:server" + System.nanoTime() + ";DB_CLOSE_DELAY=-1", "sa", ""));
|
||||
store.jdbc().execute("create table usdt_chain_execution(id int)");
|
||||
UsdtConfig config = new UsdtConfig();
|
||||
config.setTronNetType(0);
|
||||
UsdtConfigMapper configs = (UsdtConfigMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
|
||||
new Class<?>[] {UsdtConfigMapper.class}, (proxy, method, arguments) -> config);
|
||||
WalletSigningService signing = new WalletSigningService() {
|
||||
@Override public void validateConfigurationPassword(String password) {
|
||||
if (!passwordAccepted) throw new IllegalStateException("test rejection");
|
||||
}
|
||||
};
|
||||
server = new IntranetExecutionServer(store, null, signing, configs, environment);
|
||||
server.start();
|
||||
}
|
||||
|
||||
private int request(String method, String path, String token, String forwarded) throws Exception {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL("http://127.0.0.1:" + server.listeningPort() + path).openConnection();
|
||||
connection.setConnectTimeout(2000);
|
||||
connection.setReadTimeout(2000);
|
||||
connection.setRequestMethod(method);
|
||||
if (token != null) connection.setRequestProperty("Authorization", "Bearer " + token);
|
||||
if (forwarded != null) connection.setRequestProperty("X-Forwarded-For", forwarded);
|
||||
if ("POST".equals(method)) { connection.setDoOutput(true); connection.getOutputStream().close(); }
|
||||
try { return connection.getResponseCode(); }
|
||||
finally { connection.disconnect(); }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user