接入租赁平台

This commit is contained in:
lu7213 committed 2026-11-05 09:20:29 -05:00
1 parent c035263bc6
commit 1c2d15b2a9
51 files changed
+3631 -15

No files matched your search

+4
View File
@@ -1,5 +1,9 @@
## 平台简介 ## 平台简介
归集、代付支持可选的[双平台资源租赁](docs/resource-rental.md):人工确认租赁后等待链上资源到账,再输入密码广播;独立执行器自动异步准备资源。默认关闭,启用前执行增量SQL并配置加密的平台凭据。
新增可选的独立[内网链上执行服务](docs/chain-executor.md):默认关闭,保留原配置密码方式;启用前执行 `sql/chain_executor.sql`,并按文档配置仅内网监听、来源白名单、TLS、服务凭据及执行器环境密码。
归集任务全部有效明细取消后,取消事务自动将主任务标记为 `status=4(已关闭)`,保留审核状态和历史记录。部分取消不会关闭任务;已关闭任务不能再次执行或审核,且不再占用待执行任务名额。执行开始及结束采用条件更新,防止旧执行快照覆盖关闭状态。无需修改数据库表结构。 归集任务全部有效明细取消后,取消事务自动将主任务标记为 `status=4(已关闭)`,保留审核状态和历史记录。部分取消不会关闭任务;已关闭任务不能再次执行或审核,且不再占用待执行任务名额。执行开始及结束采用条件更新,防止旧执行快照覆盖关闭状态。无需修改数据库表结构。
归集明细支持管理端及用户端取消:`POST /system/usdtTaskItem/{id}/cancel`、`POST /system/usdtTaskItem/user/{id}/cancel`,分别复用明细 edit/user-edit 权限,用户端校验任务及明细归属。仅待执行明细可取消,取消保留审计记录且不可恢复。明细状态为 `0=待执行、1=成功、2=失败、3=已取消、4=执行中`;执行前以条件更新抢占明细,取消成功后不会广播。无需变更表结构。 归集明细支持管理端及用户端取消:`POST /system/usdtTaskItem/{id}/cancel`、`POST /system/usdtTaskItem/user/{id}/cancel`,分别复用明细 edit/user-edit 权限,用户端校验任务及明细归属。仅待执行明细可取消,取消保留审计记录且不可恢复。明细状态为 `0=待执行、1=成功、2=失败、3=已取消、4=执行中`;执行前以条件更新抢占明细,取消成功后不会广播。无需变更表结构。
+111
View File
@@ -0,0 +1,111 @@
# 内网链上执行服务
## 功能与兼容边界
`usdt-chain-executor` 是独立 JDK 8 进程,复用当前钱包信封解密、HD 派生、TRON 网络选择和资源估算。
支持主钱包/子钱包 TRX 与 USDT 转账、Stake 2.0 质押/取消质押、代理/取消代理、取消全部待解冻、归集、代付。
创建钱包、扩充子账号、轮换配置密码仍走原有人工密码流程,不向执行器开放这些管理能力。
支付后端 `CHAIN_EXECUTOR_ENABLED` 默认 `false`,此时直接执行原密码代码,既不访问内网服务,也不依赖新增表。
启用后,用户输入密码时本地执行,未输入密码时仅允许交给已就绪的内网服务。两种方式共用执行记录和受控交易构造,
执行前实时校验余额、资源和链上费率。`RESOURCE_ONLY` 缺口拒绝;`DIRECT` 检查燃烧预算及全局 `trx_num` 保留量。
页面仍要求明确确认广播;服务上线不会触发历史业务自动广播。
## 部署顺序
1. 备份并执行 `sql/chain_executor.sql`,只新增执行记录表,不重建原表。
2. 使用 JDK 8 构建:`mvn -pl usdt-chain-executor -am package -DskipTests`。
3. 给独立执行器配置下表环境变量,再启动 `java -jar usdt-chain-executor/target/usdt-chain-executor-3.4.0.jar`。
4. 验证监听地址、来源白名单、TLS 和服务认证后,再配置支付后端环境变量并部署前端。
5. 首次在 NILE 验证。没有执行过真实交易的构建/隔离测试不能替代实际部署验收。
禁止把真实配置密码写在脚本、命令行参数、Git 文件或支付后端配置中。通过进程管理器的受控环境注入。
### 执行器环境变量
| 变量 | 含义 |
| --- | --- |
| `CHAIN_EXECUTOR_BIND_ADDRESS` | 必填,本机明确 IPv4;只接受 `10/8`、`172.16/12`、`192.168/16` 或 `127/8` |
| `CHAIN_EXECUTOR_PORT` | 必填,独立监听端口,例如 `9088` |
| `CHAIN_EXECUTOR_ALLOWED_IPS` | 必填,支付后端实际 TCP 来源 IPv4,逗号分隔,逐个精确匹配;不支持通配/CIDR |
| `CHAIN_EXECUTOR_TOKEN` | 必填,至少 32 位的独立随机服务凭据;与后端配置相同,不是钱包密码 |
| `CHAIN_EXECUTOR_CONFIGURATION_PASSWORD` | 必填,当前全局钱包配置密码,仅在执行器进程内存中使用 |
| `CHAIN_EXECUTOR_ALLOWED_NETWORK` | 必填,`NILE` 或 `MAINNET`;与数据库全局配置不同则未就绪 |
| `CHAIN_EXECUTOR_BROADCAST_ENABLED` | 必填,只有明确为 `true` 才启动 |
| `CHAIN_EXECUTOR_DB_URL` | 与支付后端相同数据库;使用 `connectionTimeZone=LOCAL&forceConnectionTimeZoneToSession=true` |
| `CHAIN_EXECUTOR_DB_USER` / `CHAIN_EXECUTOR_DB_PASSWORD` | 独立最小权限数据库账号及密码 |
| `CHAIN_EXECUTOR_TLS_KEYSTORE` | 非回环监听必填,PKCS12 证书库的绝对路径 |
| `CHAIN_EXECUTOR_TLS_PASSWORD` | 证书库密码 |
| `TRON_GRID_API_KEY` / `TRON_SCAN_API_KEY` | 按实际节点配置,沿用共享 TRON 客户端 |
独立执行器数据库权限:`usdt_config`、`wallet_address`、`usdt_payout_order`、
`usdt_aggregation_task`、`usdt_aggregation_task_item` 只需 SELECT;`usdt_chain_execution` 需 SELECT/UPDATE。
执行器不需要创建表、删除表、写业务状态或修改商户余额的权限。
### 支付后端环境变量
| 变量 | 含义 |
| --- | --- |
| `CHAIN_EXECUTOR_ENABLED` | 启用双通道时设 `true` |
| `CHAIN_EXECUTOR_BASE_URL` | 无尾斜杠/路径的根地址,例如 `https://192.168.10.20:9088` |
| `CHAIN_EXECUTOR_TOKEN` | 独立服务凭据,与执行器一致 |
仅回环地址允许 HTTP;跨机器强制 HTTPS。证书 SAN 必须包含配置的内网 IP,支付后端 JVM 需信任签发 CA。
使用 JVM trustStore 配置受信 CA,禁止关闭证书校验。只支持 IPv4 字面地址,不接受域名,避免 DNS 重绑定和意外公网解析。
## 仅内网访问
- 服务拒绝 `0.0.0.0`、公网、域名、IPv6 和未配置白名单的启动方式。
- 所有 HTTP 路径统一检查真实 TCP 对端 IP 和独立 Bearer 凭据;健康检查也不例外。
- 不信任 `X-Forwarded-For` 或其他代理头。默认直接从支付后端调用,不经过反向代理。
- 防火墙/安全组仅允许支付后端指定内网 IP 访问执行端口,其他来源全部拒绝。
- 禁止配置公网 NAT、端口转发、公网反向代理和公网 Ingress;容器部署只发布到宿主机指定内网地址。
- 前端只访问现有支付后端;执行器地址、凭据、密码、信封和签名交易不返回浏览器。
应用只能校验本机监听与实际来源,无法代替基础设施防火墙,也无法检测外部设备上的 NAT/公网转发规则。
## 协议与执行流程
- `GET /internal/v1/readiness`:鉴权后验证当前配置密码和网络,成功返回纯文本 `READY`,未就绪返回 503。
- `POST /internal/v1/executions`:鉴权后接收空正文通知,返回 202;只唤醒数据库扫描,不接收任意交易参数。
- `GET /system/chainExecutor/status`:现有后端登录鉴权入口,返回可用性和当前操作人最近 5 条公开执行记录。
业务指令先写数据库,通知只是加速信号;通知丢失时每 2 秒补扫。队列指令 10 分钟内未开始则拒绝执行。
就绪校验会解密信封但不签名;实际执行再次核对信封版本、网络、钱包启用状态、地址与索引、代付/归集业务状态及金额。
私钥仍由 `WalletSigningService` 在内存中派生,派生地址不匹配时拒绝。
| 状态 | 语义与恢复 |
| --- | --- |
| `QUEUED` | 持久化待执行;REMOTE 可以补扫;PASSWORD 不会在无人输入密码时自动解锁 |
| `RUNNING` | 已原子领取,正在校验/签名;不凭超时自动释放,防止多进程同时签名 |
| `SIGNED` | 签名交易与哈希已落库,广播前的持久化屏障;只查询或重播原字节,不重新构造 |
| `BROADCASTED` | 节点确认接收或按哈希查到原交易;不等同于链上执行成功 |
| `FAILED` | 明确在签名前失败,可以重新输入密码或重试远程执行;旧记录归档保留 |
| `CHAIN_FAILED` | 原代付链上确认任务已确认原哈希执行失败,允许下一次人工尝试;保留旧交易审计 |
广播包含首次最多尝试 4 次,使用同一笔签名交易。`SIGNED` 后响应丢失或数据库断连不改为可重新广播的失败。
恢复任务查原哈希或重播同一交易,不能因交易过期/未查到就自动创建新交易。
代付保留状态 6 直到结果明确;后端每 5 秒同步为已广播,再由原链上确认和账务结算完成。
归集明细保留状态 4,逐明细同步交易哈希与幂等支出流水;全部明细结束后同步主任务。
执行器只写执行记录,不能代替支付系统做审核或结算。
## 维护与异常恢复
- 密码轮换后,旧环境密码无法解密,服务就绪状态立即失败。更新执行器环境变量并重启;不要通过 HTTP 发送新密码。
- 切换全局网络时,必须同步调整执行器允许网络。旧网络 `SIGNED` 记录未处理完前不要切换。
- 存在 QUEUED/RUNNING/SIGNED 未决记录时,不要关闭后端功能开关后改走不受新表约束的旧通道。
- `SIGNED` 长期未确认:核对网络、交易哈希、交易过期时间与链上结果。禁止清空签名记录或直接重新转账。
- `RUNNING` 在进程异常退出后可能保留:先停止所有本地和远程执行进程,确认该记录没有 `signed_transaction`、没有交易哈希,
且签名前持久化屏障确实未通过,再由维护人员将其标记为 FAILED。禁止运行中按时间强制抢占。
- 后端分发归集期间异常退出时,主任务可能保留“正在分发链上执行任务”。先核对已创建指令与未提交明细,
不要直接重跑主任务。明确已提交结果后再恢复业务状态;该保守占位用于避免重复归集。
需要停机维护时先停止新提交,等待已签名交易和业务同步完成,再停执行器、关闭功能开关。
`signed_transaction` 不包含私钥,但具有广播能力,必须限制数据库读取和备份访问,不得公开或写日志。
## 验证
隔离测试覆盖:同业务并发提交/领取只成功一次、签名后不可标记为可重试失败、密码不入库、
广播响应丢失时同一字节重播与恢复不重新签名、真实回环 HTTP 的 IP 白名单/凭据校验、伪造转发头拒绝、密码轮换未就绪。
部署仍须验证公网无法连接、非白名单内网来源拒绝、错误服务凭据拒绝、TLS 验证和实际 NILE 链上确认。
+73
View File
@@ -0,0 +1,73 @@
# 归集与代付资源租赁
## 启用与兼容
默认关闭:`USDT_RESOURCE_RENTAL_ENABLED=false`。关闭时保留原转账通道、燃烧预算、审核和账务结算行为,不查询新增资源表。此功能仅用于归集、代付,普通钱包操作不自动购买资源。
部署前备份数据库,依次执行 `sql/chain_executor.sql`、`sql/resource_rental.sql`。均为增量建表,不删除旧数据。后端与执行器必须共享同一数据库;远程模式还需按 [执行器说明](chain-executor.md) 部署执行器。不要在生产数据库上运行测试脚本。
支付后端外部配置:
```yaml
usdt:
resource-rental:
enabled: true
provider: INTERNAL # INTERNAL 或 DUIYA,仅影响尚未授权的新准备记录
arrival-timeout-seconds: 300
rental:
master-key: ${RENT_MASTER_KEY} # 外部注入的Base64编码32字节随机密钥
```
也可使用已接入的环境变量 `USDT_RESOURCE_RENTAL_ENABLED`、`USDT_RESOURCE_RENTAL_PROVIDER`、`USDT_RESOURCE_ARRIVAL_TIMEOUT_SECONDS`。所有支付实例的密钥必须一致;不要随意更换,原订单查询仍需要解密原配置。执行器只核验资源和签名,不需要平台API密钥或租赁加密密钥。
## 保存平台配置
使用已登录管理员的 `system:usdtConfig:edit` 权限调用 `POST /system/chain-resources/config`。凭据为只写字段,后端加密入库;每次保存新增配置版本,原订单始终使用其 `config_id`,切换平台不会重购原单。不要把实际密钥写入文档、命令行或日志。
自有平台请求示例(占位符须在受控配置客户端中替换):
```json
{
"provider": "INTERNAL",
"network": "NILE",
"baseUrl": "https://rental.example.com",
"apiKey": "<API Key>",
"apiSecret": "<API Secret>",
"durationSeconds": 3600,
"energyStep": 30000,
"bandwidthStep": 100,
"maxOrderCost": 10,
"maxExecutionCost": 20
}
```
`baseUrl` 为HTTPS站点根地址,自有平台适配器自动拼接 `/api/rental/v1`。自有租赁账户需要启用应用及API凭据、绑定当前网络的能量/带宽默认套餐并准备可用余额。`energyStep`、`bandwidthStep`、`durationSeconds` 必须匹配对应默认套餐的数量和周期倍数;不传 `package_id`。费用单位为USDT。
兑呀使用 `provider=DUIYA`、`network=MAINNET`、`baseUrl=https://weidubot.cc/api/v2`,按需设置 `energyPeriod`(默认`1h`)、`bandwidthPeriod`(默认`1day`)。费用单位为TRX;能量最低30000、带宽最低100,按配置步长向上取整。使用资源订单 `buy_energy/buy_net`,不调用速充接口。公开文档未确认测试网支持,DUIYA的NILE请求会被拒绝。
每类资源检查 `maxOrderCost`,每个业务准备检查 `maxExecutionCost`;人工额外受页面确认的报价上限限制。归集各地址独立计费。这里没有每日总费用额度,部署时按业务量设置单笔上限和平台余额。兑呀创建接口未提供锁价字段,预估费用无法替代平台最终扣费,首次上线需小额核对实际计价。
## 操作流程
人工执行:在归集/代付页面选择“手动输入配置密码”,点击执行后先展示实时资源和报价。可选择租赁,或沿用原转账规则。确认租赁仅购买缺口;页面只读轮询,支付后端独立查询链上,必须能量、带宽均足额才显示密码输入。输入密码并确认广播后,签名前再次核验。资源已足额时不购买。密码不持久化、不交给资源Worker,关闭弹窗不会自动转账。
远程执行:提交业务后保持原执行中状态;支付后端资源Worker为远程排队指令自动准备资源。执行器资源未就绪时仍保持QUEUED,不解锁钱包,不签名;就绪后复检、构造并签名一次,持久化后广播。等待期间的状态和错误显示在“最近执行记录”中。原转账授权有效期仍为10分钟,资源等待不会无限延长授权。
链上查询失败不是资源为零,不会因此付费。租赁平台返回成功或交付成功均不能证明可用资源满足,只有支付系统读取指定网络的实时 `limit-used` 并重新估算本次操作,才会置为READY。估算失败拒绝购买,不使用页面的默认能量兜底值。
## 防重复与恢复
- 同一业务唯一准备记录;同一次准备每类资源唯一订单。本地CREATED→SUBMITTING的数据库CAS是实际付费调用屏障,浏览器、多个后端实例、进程重启均复用原单。
- 创建请求禁止HTTP自动重试和重定向。超时/响应丢失/进程中断保留SUBMIT_UNKNOWN,不回到CREATED。自有平台可按原商户单号只读核对;兑呀未文档化商户幂等号,结果未知必须人工核对平台账单,不能自动重下。
- 等待超时显示TIMEOUT,可点“继续检查原单”;此操作只延长到账检测,不新建租赁订单、不更换平台、不延长转账授权。关闭页面后服务仍继续检查,重新打开复用原记录。
- REVIEW阻止转账,即使地址后来资源足额也不会绕过未知/失败租赁订单;需运维核实原单。当前版本不提供自动补租第二轮或清除未知订单的按钮,避免重复扣费。已确定交付但资源仍不足时,可继续原单检测或由管理员从其他渠道补充资源,不自动再购买。
- 同网络同发送钱包独占准备,主钱包代付按地址串行。签名后占用不按超时回收,只有链上收据确认资源已消耗才释放。已明确链上失败的原交易可复用原租赁资源重新预检,不自动重租。
- 已租赁但尚未执行的准备保留地址占用,关闭弹窗不释放,也不撤销已付费订单。管理员应完成原操作或核对异常后处理;不要直接删除准备/订单/地址占用表记录。
业务审核、代付冻结与最终链上确认结算沿用原实现。租赁费用由平台账户支付,不混入商户USDT本金结算。一个归集地址失败不终止其他地址的后端准备,但人工批次需全部资源就绪才允许输入密码;可先取消尚未执行且无需继续的明细,再预检剩余明细。
## 验证范围
隔离H2测试使用真实增量SQL和可控链上/平台替身,覆盖并发唯一订单、延迟到账、两类资源分别到账、签名前回落、未知结果不重下、超时续查、原平台配置引用、费用上限和同地址互斥。既有链上执行与独立执行器启动测试继续运行。前端使用实际Vue/Element组件的模拟接口检查桌面1200px和窄屏390px,验证刷新不重复购买、到账前不展示密码、确认后才执行。
未进行真实钱包签名、真实平台扣费或生产数据库升级。上线需先配置自有平台NILE环境进行受控联调;DUIYA需在主网小额核对凭据、周期、扣费和代理到账。
+2 -1
View File
@@ -228,6 +228,7 @@
<modules> <modules>
<module>ruoyi-admin</module> <module>ruoyi-admin</module>
<module>ruoyi-system</module> <module>ruoyi-system</module>
<module>usdt-chain-executor</module>
</modules> </modules>
<packaging>pom</packaging> <packaging>pom</packaging>
@@ -277,4 +278,4 @@
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
</project> </project>
@@ -1,3 +1,10 @@
# 内网执行通道默认关闭;密码只配置在独立执行器进程,禁止加入支付后端配置。
chain:
executor:
enabled: ${CHAIN_EXECUTOR_ENABLED:false}
url: ${CHAIN_EXECUTOR_BASE_URL:}
token: ${CHAIN_EXECUTOR_TOKEN:}
# 项目相关配置 # 项目相关配置
ruoyi: ruoyi:
whiteList: whiteList:
@@ -225,6 +232,14 @@ luqj:
dir: dir:
prefix: lu7213/images/ # 上传文件夹路径前缀 prefix: lu7213/images/ # 上传文件夹路径前缀
# 归集/代付资源租赁,平台连接凭据加密存储在数据库。
usdt:
resource-rental:
# 启用前执行sql/resource_rental.sql及sql/chain_executor.sql,并保存平台配置。
enabled: ${USDT_RESOURCE_RENTAL_ENABLED:false}
provider: ${USDT_RESOURCE_RENTAL_PROVIDER:INTERNAL}
arrival-timeout-seconds: ${USDT_RESOURCE_ARRIVAL_TIMEOUT_SECONDS:300}
# Authenticator 凭据使用独立的 32 字节随机 AES 密钥(Base64),所有实例必须一致。 # Authenticator 凭据使用独立的 32 字节随机 AES 密钥(Base64),所有实例必须一致。
# 留空时禁止新建绑定;不要随意更换,已有凭据需要原密钥才能解密。 # 留空时禁止新建绑定;不要随意更换,已有凭据需要原密钥才能解密。
auth: auth:
@@ -0,0 +1,23 @@
package com.ruoyi.system.chain;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
/**
* 可持久化的链上业务指令。只包含公开地址和业务参数,绝不包含配置密码或私钥。
* 字段由支付后端从已鉴权的业务记录构造,执行器仍须重新核对数据库。
*/
public class ChainCommand {
public String businessKey;
public Long operatorId;
public Long walletId;
public String address;
public String tokenIndex;
public Integer network;
public Long envelopeVersion;
/** 新任务允许开始执行的截止时间;已签名任务不受此截止时间影响。 */
public long validUntil;
public String type;
/** 为true时必须经租赁准备及严格链上复检;执行器不能回退为燃烧TRX。 */
public boolean rentalRequired;
public WalletOperationRequest operation;
}
@@ -0,0 +1,276 @@
package com.ruoyi.system.chain;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.domain.vo.WalletResourceEstimateVo;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.service.ITronService;
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.tron.trident.abi.datatypes.Address;
import org.tron.trident.abi.datatypes.Function;
import org.tron.trident.abi.datatypes.generated.Uint256;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.proto.Chain;
import org.tron.trident.proto.Response;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* 两个进程复用的受控执行引擎:核对业务、实时预算、解锁、构造一次、落盘、广播。
* 不接受调用方提供的原始交易或私钥。广播结果未知时保留 SIGNED,绝不重新构造。
*/
@Service
public class ChainCommandExecutor {
@org.springframework.beans.factory.annotation.Autowired(required = false)
private com.ruoyi.system.chain.resource.ResourceExecutionGate resourceGate;
private final ChainExecutionStore store;
private final WalletSigningService signing;
private final WalletOperationEstimateService estimates;
private final UsdtConfigMapper configs;
private final TronServiceProvider networks;
public ChainCommandExecutor(ChainExecutionStore store, WalletSigningService signing,
WalletOperationEstimateService estimates, UsdtConfigMapper configs, TronServiceProvider networks) {
this.store = store;
this.signing = signing;
this.estimates = estimates;
this.configs = configs;
this.networks = networks;
}
public void execute(String id, String password) {
// 等待租赁到账不是签名失败,必须在领取RUNNING之前返回,让资源Worker异步推进。
ChainCommand pending = store.command(store.get(id));
if (pending.rentalRequired && pending.validUntil >= System.currentTimeMillis()) {
try {
if (resourceGate == null || !resourceGate.ready(pending)) {
failPasswordPreparation(id);
return;
}
} catch (Exception temporarilyUnavailable) { failPasswordPreparation(id); return; }
}
if (!store.claim(id)) return;
try {
ChainCommand command = store.command(store.get(id));
WalletAddressPlus wallet = validate(command);
signing.execute(wallet, password, (tron, api, current) -> {
if (!networkName(command.network).equals(tron.type())) {
throw new CustomException("执行期间网络发生变化,已拒绝签名");
}
// 使用实时余额和资源,不能信任页面估算或旧数据库快照。
requireBudget(command, wallet, tron, api);
if (command.rentalRequired) resourceGate.require(command);
Chain.Transaction unsigned = build(command, tron, api);
if (!unsigned.hasRawData() || unsigned.getRawData().getContractCount() != 1) {
throw new CustomException("节点未构造有效交易");
}
Chain.Transaction signed = api.signTransaction(unsigned);
store.signed(id, transactionId(signed), signed.toByteArray());
// 同步签名哈希用于地址占用恢复;此后未知结果不能重新租赁或重新签名。
if (command.rentalRequired) resourceGate.transferred(command.businessKey, transactionId(signed));
broadcast(id, signed, api);
return null;
});
} catch (Exception ex) {
store.failBeforeSigning(id);
// 不打印 SDK 异常对象或消息,避免私钥客户端的内部上下文进入日志。
}
}
/** 人工请求没有后台保存的密码,资源回落时必须明确失败后回到页面,不能永远占用PASSWORD队列。 */
private void failPasswordPreparation(String id) {
if ("PASSWORD".equals(store.get(id).get("execution_mode")) && store.claim(id)) store.failBeforeSigning(id);
}
/** 恢复仅使用数据库中的同一签名交易;过期或结果未知也不生成第二笔交易。 */
public void recover(Map<String, Object> row) {
ChainCommand command = store.command(row);
ITronService tron = networks.getServiceForNetwork(Integer.valueOf(0).equals(command.network) ? "NILE" : "MAINNET");
ApiWrapper api = tron.buildApiWrapper();
try {
String id = (String) row.get("execution_id");
String hash = (String) row.get("transaction_id");
// 签名已落库但准备状态同步前宕机时,恢复地址占用与哈希关联。
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);
return;
}
} catch (Exception ignored) {
// 查询失败不能证明交易不存在;下方只能重播同一字节内容。
}
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) {
// 保持 SIGNED,等待下次查询;不能将不确定交易改成可重新转账的 FAILED。
} finally {
api.close();
}
}
private WalletAddressPlus validate(ChainCommand command) {
if (command.validUntil < System.currentTimeMillis()) throw new CustomException("执行请求已过期");
UsdtConfig config = configs.selectFirst();
if (config == null || !config.getVersion().equals(command.envelopeVersion)
|| !config.getTronNetType().equals(command.network)) {
throw new CustomException("钱包配置或网络已变化,请重新发起操作");
}
if (command.operation == null || !Boolean.TRUE.equals(command.operation.getBroadcast())) {
throw new CustomException("本次操作未确认广播");
}
WalletAddressPlus wallet = new WalletAddressPlus();
wallet.setId(command.walletId);
wallet.setToken(command.address);
wallet.setTokenIndex(command.tokenIndex);
if (command.walletId == null) {
if (!"0".equals(command.tokenIndex) || !config.getTokenAddress().equals(command.address)) {
throw new CustomException("主钱包地址不匹配");
}
} else {
List<Map<String, Object>> rows = store.jdbc().queryForList(
"select token,token_index from wallet_address where id=? and status=1 and deleted_at is null",
command.walletId);
if (rows.size() != 1 || !command.address.equals(rows.get(0).get("token"))
|| !command.tokenIndex.equals(rows.get(0).get("token_index"))) {
throw new CustomException("钱包已禁用或派生地址不一致");
}
}
validateBusiness(command);
return wallet;
}
private void validateBusiness(ChainCommand command) {
if (command.businessKey.startsWith("PAYOUT:")) {
Long id = Long.valueOf(command.businessKey.substring(7));
List<Map<String, Object>> rows = store.jdbc().queryForList(
"select to_address,amount,currency from usdt_payout_order where id=? and status=6 and deleted_at is null", id);
if (rows.size() != 1 || command.walletId != null) throw new CustomException("代付订单不可执行");
Map<String, Object> order = rows.get(0);
if (!command.type.equals("USDT".equals(order.get("currency")) ? "usdt" : "trx")) {
throw new CustomException("代付币种不一致");
}
requireTransferMatches(command, order, "to_address", "amount");
} else if (command.businessKey.startsWith("AGGREGATION:")) {
Long id = Long.valueOf(command.businessKey.substring(12));
List<Map<String, Object>> rows = store.jdbc().queryForList(
"select i.dist_token_address,i.ope_amount,i.token_address from usdt_aggregation_task_item i "
+ "join usdt_aggregation_task t on t.id=i.parent_id "
+ "join wallet_address w on w.token=i.token_address and w.app_id=i.app_id "
+ "where i.id=? and i.status=4 and i.deleted_at is null and t.verify_status=1 "
+ "and t.deleted_at is null and w.id=? and w.deleted_at is null", id, command.walletId);
if (rows.size() != 1 || !"usdt".equals(command.type)
|| !command.address.equals(rows.get(0).get("token_address"))) {
throw new CustomException("归集明细不可执行");
}
requireTransferMatches(command, rows.get(0), "dist_token_address", "ope_amount");
} else if (!command.businessKey.startsWith("WALLET:")) {
throw new CustomException("不支持的业务类型");
}
}
private void requireTransferMatches(ChainCommand command, Map<String, Object> row,
String target, String amount) {
if (!row.get(target).equals(command.operation.getToAddress())
|| ((BigDecimal) row.get(amount)).compareTo(command.operation.getAmount()) != 0) {
throw new CustomException("业务金额或目标地址不一致");
}
}
private void requireBudget(ChainCommand command, WalletAddressPlus wallet, ITronService tron, ApiWrapper api) throws Exception {
WalletOperationRequest request = command.operation;
WalletResourceEstimateVo estimate = estimates.estimate(command.type, wallet, request);
if (Boolean.TRUE.equals(request.getResourceOnly()) && estimate.isBurnRequired()) {
throw new CustomException("当前资源不足,禁止燃烧 TRX");
}
UsdtConfig config = configs.selectFirst();
BigDecimal reserve = config.getTrxNum() == null ? BigDecimal.ONE : config.getTrxNum().max(BigDecimal.ZERO);
// 页面估算允许保守提示;实际广播必须读到当前链上费率,禁止使用默认费率兜底。
long energyFee = 0L;
long bandwidthFee = 0L;
for (Response.ChainParameters.ChainParameter fee : api.getChainParameters().getChainParameterList()) {
if ("getEnergyFee".equals(fee.getKey())) energyFee = fee.getValue();
if ("getTransactionFee".equals(fee.getKey())) bandwidthFee = fee.getValue();
}
if (energyFee <= 0 || bandwidthFee <= 0) throw new CustomException("无法读取当前链上资源费率,已拒绝广播");
BigDecimal burn = BigDecimal.valueOf(estimate.getEnergyGap()).multiply(BigDecimal.valueOf(energyFee))
.add(BigDecimal.valueOf(estimate.getBandwidthGap()).multiply(BigDecimal.valueOf(bandwidthFee))).movePointLeft(6);
BigDecimal needed = burn.add(reserve);
if ("trx".equals(command.type) || "stake".equals(command.type)) needed = needed.add(request.getAmount());
if (tron.getTRxBalance(api, wallet.getToken()).compareTo(needed) < 0) {
throw new CustomException("TRX 余额不足以支付本次操作及资源预算");
}
if ("usdt".equals(command.type)
&& tron.getUsdtBalance(api, wallet.getToken()).compareTo(request.getAmount()) < 0) {
throw new CustomException("USDT 余额不足");
}
}
private Chain.Transaction build(ChainCommand command, ITronService tron, ApiWrapper api) throws Exception {
WalletOperationRequest request = command.operation;
String owner = command.address;
String target = request.getToAddress();
if ("cancel-unstake".equals(command.type)) return api.cancelAllUnfreezeV2(owner).getTransaction();
long amount = request.getAmount().movePointRight(6).longValueExact();
if (amount <= 0) throw new CustomException("金额必须大于 0");
switch (command.type) {
case "trx": return api.transfer(owner, target, amount).getTransaction();
case "usdt":
Function transfer = new Function("transfer", Arrays.asList(new Address(target), new Uint256(amount)),
Collections.emptyList());
return api.triggerCall(owner, ApiWrapper.toHex(ApiWrapper.parseAddress(tron.contractAddress())),
transfer).setFeeLimit(100_000_000L).build();
case "stake": return api.freezeBalanceV2(owner, amount, resource(request)).getTransaction();
case "unstake": return api.unfreezeBalanceV2(owner, amount, resource(request)).getTransaction();
case "delegate": return api.delegateResourceV2(owner, amount, resource(request), target, true, 86400).getTransaction();
case "undelegate": return api.undelegateResource(owner, amount, resource(request), target).getTransaction();
default: throw new CustomException("不支持的钱包操作");
}
}
private int resource(WalletOperationRequest request) {
Integer code = request.getResourceCode();
if (code == null || code != 0 && code != 1) throw new CustomException("资源类型无效");
return code;
}
private void broadcast(String id, Chain.Transaction signed, ApiWrapper api) {
for (int attempt = 0; attempt < 4; attempt++) {
try {
String returned = api.broadcastTransaction(signed);
if (transactionId(signed).equalsIgnoreCase(returned)) {
store.broadcasted(id);
return;
}
} catch (Exception ignored) {
// 包含首次共四次,始终广播同一笔交易;失败后由恢复任务查询。
}
}
}
public static String networkName(Integer network) {
if (Integer.valueOf(0).equals(network)) return "nile";
if (Integer.valueOf(1).equals(network)) return "pro";
throw new IllegalArgumentException("TRON 网络无效");
}
private static String transactionId(Chain.Transaction signed) {
try {
return ApiWrapper.toHex(MessageDigest.getInstance("SHA-256").digest(signed.getRawData().toByteArray()));
} catch (Exception ex) {
throw new IllegalStateException("交易哈希计算失败");
}
}
}
@@ -0,0 +1,10 @@
package com.ruoyi.system.chain;
import com.ruoyi.common.exception.CustomException;
/** 已提交或广播结果未知,不得按普通失败释放业务占位或切换执行通道。 */
public class ChainExecutionPendingException extends CustomException {
public ChainExecutionPendingException() {
super("链上执行已提交,结果确认中,请在执行记录中查看进度,勿重复提交");
}
}
@@ -0,0 +1,105 @@
package com.ruoyi.system.chain;
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.service.IUsdtAggregationTaskItemService;
import com.ruoyi.system.service.IWalletAddressService;
import com.ruoyi.system.service.PayoutProcessingService;
import com.ruoyi.system.service.WalletLedgerPostingService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.List;
import java.util.Map;
/**
* 支付后端同步最终广播结果。执行器不修改商户余额,不绕过已有代付链上确认和结算流程。
* 结果同步和 reconciled 标记同一事务提交;后台重启后可继续,业务行锁防止并发落账。
*/
@Component
public class ChainExecutionReconciler {
private final ChainExecutorClient client;
private final ChainExecutionStore store;
private final PayoutProcessingService payouts;
private final IUsdtAggregationTaskItemService items;
private final IWalletAddressService wallets;
private final WalletLedgerPostingService ledger;
private final TransactionTemplate transactions;
public ChainExecutionReconciler(ChainExecutorClient client, ChainExecutionStore store,
PayoutProcessingService payouts, IUsdtAggregationTaskItemService items,
IWalletAddressService wallets, WalletLedgerPostingService ledger, TransactionTemplate transactions) {
this.client = client;
this.store = store;
this.payouts = payouts;
this.items = items;
this.wallets = wallets;
this.ledger = ledger;
this.transactions = transactions;
}
@Scheduled(fixedDelay = 5000)
public void reconcile() {
if (!client.isEnabled()) return;
List<Map<String, Object>> rows = store.jdbc().queryForList("select execution_id from usdt_chain_execution "
+ "where reconciled=0 and status in ('BROADCASTED','FAILED') order by created_at limit 50");
for (Map<String, Object> row : rows) {
try {
transactions.execute(status -> {
apply((String) row.get("execution_id"));
return null;
});
} catch (Exception ignored) {
// 业务事务失败下次继续,禁止因此重新广播。
}
}
finishAggregationTasks();
}
private void apply(String id) {
Map<String, Object> row = store.jdbc().queryForMap(
"select * from usdt_chain_execution where execution_id=? for update", id);
if (((Number) row.get("reconciled")).intValue() != 0) return;
ChainCommand command = store.command(row);
boolean success = "BROADCASTED".equals(row.get("status"));
String hash = (String) row.get("transaction_id");
if (command.businessKey.startsWith("PAYOUT:")) {
Long orderId = Long.valueOf(command.businessKey.substring(7));
Integer current = store.jdbc().queryForObject(
"select status from usdt_payout_order where id=? for update", Integer.class, orderId);
if (Integer.valueOf(PayoutProcessingService.EXECUTING).equals(current)) {
if (success) payouts.markBroadcasted(orderId, hash);
else payouts.markFailed(orderId, (String) row.get("error_message"));
}
} else if (command.businessKey.startsWith("AGGREGATION:")) {
Long itemId = Long.valueOf(command.businessKey.substring(12));
Integer current = store.jdbc().queryForObject(
"select status from usdt_aggregation_task_item where id=? for update", Integer.class, itemId);
if (Integer.valueOf(4).equals(current)) {
UsdtAggregationTaskItemPlus item = items.getById(itemId);
if (success) {
WalletAddressPlus wallet = wallets.getById(command.walletId);
ledger.completeAggregationItem(item, wallet, hash, "执行成功;交易哈希:" + hash);
} else {
item.setStatus(2L);
item.setRemark((String) row.get("error_message"));
item.setUpdatedAt(new java.util.Date());
items.updateById(item);
}
}
}
store.jdbc().update("update usdt_chain_execution set reconciled=1 where execution_id=?", id);
}
private void finishAggregationTasks() {
// 仅关闭使用新通道且已无待执行/执行中明细的任务,避免干扰原密码批处理。
store.jdbc().update("update usdt_aggregation_task t set status=case when exists "
+ "(select 1 from usdt_aggregation_task_item i where i.parent_id=t.id and i.status=2 and i.deleted_at is null) "
+ "then 3 else 2 end,remark='链上执行结果已同步',updated_at=CURRENT_TIMESTAMP "
+ "where t.status=1 and t.remark<>'正在分发链上执行任务' and exists (select 1 from usdt_aggregation_task_item i "
+ "join usdt_chain_execution e on e.business_key=concat('AGGREGATION:',i.id) where i.parent_id=t.id) "
+ "and not exists (select 1 from usdt_aggregation_task_item i where i.parent_id=t.id "
+ "and i.status in (0,4) and i.deleted_at is null)");
}
}
@@ -0,0 +1,138 @@
package com.ruoyi.system.chain;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.service.WalletSigningService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* 执行通道的唯一选择点。显式密码沿用本地解锁;未携带密码才允许内网执行。
* 未启用功能时直接调用原逻辑,不依赖新增表,也不改变现有接口返回值。
*/
@Service
public class ChainExecutionRouter {
@org.springframework.beans.factory.annotation.Autowired(required = false)
private com.ruoyi.system.chain.resource.ResourceRentalProperties rentalProperties;
@org.springframework.beans.factory.annotation.Autowired(required = false)
private com.ruoyi.system.chain.resource.ResourceExecutionGate resourceGate;
private final ChainExecutorClient client;
private final ChainExecutionStore store;
private final ChainCommandExecutor executor;
private final WalletSigningService signing;
private final UsdtConfigMapper configs;
public ChainExecutionRouter(ChainExecutorClient client, ChainExecutionStore store,
ChainCommandExecutor executor, WalletSigningService signing, UsdtConfigMapper configs) {
this.client = client;
this.store = store;
this.executor = executor;
this.signing = signing;
this.configs = configs;
}
public boolean isEnabled() { return client.isEnabled(); }
/** 在占用业务状态前检查通道;检查失败不创建任务,也不要求用户重复审核。 */
public void requireChannel(String password) {
if (StringUtils.hasText(password)) {
signing.validateConfigurationPassword(password);
} else if (!client.ready()) {
throw new CustomException("内网执行服务不可用,请使用配置密码执行");
}
}
public Object execute(String type, WalletAddressPlus wallet, WalletOperationRequest request,
String businessKey, WalletSigningService.SignedOperation<?> legacy) {
String password = request.getConfigurationPassword();
boolean remote = !StringUtils.hasText(password);
boolean rentalEnabled = rentalProperties != null && rentalProperties.isEnabled()
&& (businessKey.startsWith("PAYOUT:") || businessKey.startsWith("AGGREGATION:"));
if (!isEnabled()) {
// 兼容原本地通道;只有明确确认租赁的业务才增加严格资源复检。
if (rentalEnabled) {
ChainCommand local = command(type, wallet, request, businessKey);
if (Boolean.TRUE.equals(request.getResourceOnly()) || resourceGate.required(local)) resourceGate.require(local);
Object result = signing.execute(wallet, password, legacy);
resourceGate.transferred(businessKey, String.valueOf(result));
return result;
}
return signing.execute(wallet, password, legacy);
}
ChainCommand command = command(type, wallet, request, businessKey);
command.rentalRequired = rentalEnabled && (remote || Boolean.TRUE.equals(request.getResourceOnly()) || resourceGate.required(command));
if (command.rentalRequired) command.operation.setResourceOnly(true);
if (!remote && command.rentalRequired) resourceGate.require(command);
Map<String, Object> row = store.byBusinessKey(businessKey);
if (row != null && !sameCommand(store.command(row), command)) {
throw new CustomException("执行编号已被其他操作使用");
}
if (row != null && ("FAILED".equals(row.get("status")) || "CHAIN_FAILED".equals(row.get("status")))) {
requireChannel(password);
store.archiveFailure(businessKey);
row = null;
}
if (row == null) {
requireChannel(password);
row = store.create(command, remote);
}
// 即使 INSERT 与其他请求发生唯一键冲突,也必须再次核对最终取得的原任务。
if (!sameCommand(store.command(row), command)) throw new CustomException("执行编号已被其他操作使用");
String id = (String) row.get("execution_id");
if (remote && "REMOTE".equals(row.get("execution_mode"))) client.notifyExecutor();
try {
if (!remote && "PASSWORD".equals(row.get("execution_mode"))) executor.execute(id, password);
row = store.get(id);
} catch (Exception uncertain) {
// 已有持久化任务后,数据库断连也属于结果未知,不能释放业务执行占位。
throw new ChainExecutionPendingException();
}
if ("BROADCASTED".equals(row.get("status"))) return row.get("transaction_id");
if ("FAILED".equals(row.get("status"))) throw new CustomException((String) row.get("error_message"));
throw new ChainExecutionPendingException();
}
private ChainCommand command(String type, WalletAddressPlus wallet, WalletOperationRequest request, String key) {
UsdtConfig config = configs.selectFirst();
if (config == null) throw new CustomException("全局钱包配置不存在");
ChainCommand command = new ChainCommand();
command.businessKey = key;
command.operatorId = SecurityUtils.getUserId();
command.walletId = wallet.getId();
command.address = wallet.getToken();
command.tokenIndex = wallet.getTokenIndex();
command.network = config.getTronNetType();
command.envelopeVersion = config.getVersion();
command.validUntil = System.currentTimeMillis() + 10 * 60 * 1000L;
command.type = type;
// 显式复制公开字段。不能序列化原请求,避免未来更换 JSON 库导致密码意外入库。
WalletOperationRequest copy = new WalletOperationRequest();
copy.setAmount(request.getAmount());
copy.setToAddress(request.getToAddress() == null ? null : request.getToAddress().trim());
copy.setResourceCode(request.getResourceCode());
copy.setResourceOnly(request.getResourceOnly());
copy.setBroadcast(request.getBroadcast());
command.operation = copy;
return command;
}
private boolean sameCommand(ChainCommand left, ChainCommand right) {
return (!left.businessKey.startsWith("WALLET:") || java.util.Objects.equals(left.operatorId, right.operatorId))
&& java.util.Objects.equals(left.walletId, right.walletId)
&& java.util.Objects.equals(left.tokenIndex, right.tokenIndex)
&& java.util.Objects.equals(left.address, right.address)
&& java.util.Objects.equals(left.network, right.network)
&& java.util.Objects.equals(left.type, right.type)
&& java.util.Objects.equals(left.operation.getToAddress(), right.operation.getToAddress())
&& java.util.Objects.equals(left.operation.getResourceCode(), right.operation.getResourceCode())
&& java.util.Objects.equals(left.operation.getResourceOnly(), right.operation.getResourceOnly())
&& (left.operation.getAmount() == null ? right.operation.getAmount() == null
: right.operation.getAmount() != null && left.operation.getAmount().compareTo(right.operation.getAmount()) == 0);
}
}
@@ -0,0 +1,113 @@
package com.ruoyi.system.chain;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.CustomException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* 双通道共用的执行日志。业务键唯一约束是最终并发屏障,不能用 JVM 锁替代。
* SIGNED 状态必须在首次广播之前提交;数据库不可用时禁止广播。
* 不自动回收 RUNNING:进程可能仍在签名,不能仅凭租约过期再次构造交易。
*/
@Repository
public class ChainExecutionStore {
private final JdbcTemplate jdbc;
private final ObjectMapper json = new ObjectMapper();
public ChainExecutionStore(DataSource dataSource) {
jdbc = new JdbcTemplate(dataSource);
}
public JdbcTemplate jdbc() { return jdbc; }
public Map<String, Object> create(ChainCommand command, boolean remote) {
String id = UUID.randomUUID().toString();
try {
jdbc.update("insert into usdt_chain_execution (execution_id,business_key,operator_id,"
+ "execution_mode,command_json,status,created_at,updated_at) values (?,?,?,?,?,'QUEUED',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
id, command.businessKey, command.operatorId, remote ? "REMOTE" : "PASSWORD", encode(command));
} catch (DuplicateKeyException duplicate) {
// 重复业务请求只能引用原任务;禁止覆盖原金额、地址或已签名交易。
return byBusinessKey(command.businessKey);
}
return get(id);
}
public Map<String, Object> get(String id) {
List<Map<String, Object>> rows = jdbc.queryForList(
"select * from usdt_chain_execution where execution_id=?", id);
if (rows.isEmpty()) throw new CustomException("执行记录不存在");
return rows.get(0);
}
public Map<String, Object> byBusinessKey(String key) {
List<Map<String, Object>> rows = jdbc.queryForList(
"select * from usdt_chain_execution where business_key=?", key);
return rows.isEmpty() ? null : rows.get(0);
}
public boolean claim(String id) {
return jdbc.update("update usdt_chain_execution set status='RUNNING',updated_at=CURRENT_TIMESTAMP "
+ "where execution_id=? and status='QUEUED'", id) == 1;
}
public void signed(String id, String hash, byte[] transaction) {
if (jdbc.update("update usdt_chain_execution set status='SIGNED',transaction_id=?,signed_transaction=?,"
+ "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='RUNNING'",
hash, transaction, id) != 1) {
throw new CustomException("执行状态变化,已拒绝广播");
}
}
public void broadcasted(String id) {
jdbc.update("update usdt_chain_execution set status='BROADCASTED',error_message=null,"
+ "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='SIGNED'", id);
}
public void failBeforeSigning(String id) {
// 节点、SDK 异常可能携带敏感上下文,只记录固定文案;SIGNED 永远不改成可重试失败。
jdbc.update("update usdt_chain_execution set status='FAILED',error_message='执行前校验或签名失败,请检查配置、余额和资源',"
+ "updated_at=CURRENT_TIMESTAMP where execution_id=? and status='RUNNING'", id);
}
/** 仅供原代付链上确认流程调用;已确认失败的交易允许下一次人工执行尝试。 */
public void chainFailed(String businessKey, String hash) {
jdbc.update("update usdt_chain_execution set status='CHAIN_FAILED',reconciled=1,"
+ "error_message='原交易已由链上确认失败,可人工重新执行',updated_at=CURRENT_TIMESTAMP "
+ "where business_key=? and transaction_id=? and status='BROADCASTED'", businessKey, hash);
}
public ChainCommand command(Map<String, Object> row) {
try {
return json.readValue((String) row.get("command_json"), ChainCommand.class);
} catch (Exception ex) {
throw new CustomException("执行指令格式无效");
}
}
/** 只有签名前失败或链上已明确确认失败允许新尝试;保留旧签名及哈希用于审计。 */
public void archiveFailure(String businessKey) {
jdbc.update("update usdt_chain_execution set business_key=execution_id,reconciled=1 where business_key=? and status in ('FAILED','CHAIN_FAILED')",
businessKey);
}
public List<Map<String, Object>> recoverable() {
return jdbc.queryForList("select * from usdt_chain_execution where "
+ "(status='QUEUED' and execution_mode='REMOTE') or status='SIGNED' order by created_at limit 50");
}
private String encode(ChainCommand command) {
try {
return json.writeValueAsString(command);
} catch (Exception ex) {
throw new CustomException("执行指令序列化失败");
}
}
}
@@ -0,0 +1,78 @@
package com.ruoyi.system.chain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
import java.net.URI;
/** 内网调用客户端。仅允许内网字面 IP;禁用 HTTP 重定向,避免凭据被转发到其他主机。 */
@Component
public class ChainExecutorClient {
@Value("${chain.executor.enabled:false}")
private boolean enabled;
@Value("${chain.executor.url:}")
private String url;
@Value("${chain.executor.token:}")
private String token;
private final RestTemplate http;
public ChainExecutorClient() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(java.net.HttpURLConnection connection, String method)
throws java.io.IOException {
super.prepareConnection(connection, method);
connection.setInstanceFollowRedirects(false);
}
};
factory.setConnectTimeout(1500);
factory.setReadTimeout(2500);
http = new RestTemplate(factory);
}
@PostConstruct
public void validate() {
if (!enabled) return;
URI target = URI.create(url);
java.net.InetAddress address = IntranetAddress.parse(target.getHost());
if (target.getRawUserInfo() != null || target.getRawQuery() != null || target.getRawFragment() != null
|| target.getPath() != null && !target.getPath().isEmpty()
|| !("https".equals(target.getScheme()) || address.isLoopbackAddress() && "http".equals(target.getScheme()))
|| token == null || token.length() < 32) {
throw new IllegalArgumentException("内网执行服务需配置内网 HTTPS 根地址和至少32位服务凭据;仅回环允许 HTTP");
}
}
public boolean isEnabled() { return enabled; }
public boolean ready() {
if (!enabled) return false;
try {
return "READY".equals(http.exchange(url + "/internal/v1/readiness", HttpMethod.GET,
new HttpEntity<Void>(headers()), String.class).getBody());
} catch (Exception ignored) {
return false;
}
}
public void notifyExecutor() {
try {
http.exchange(url + "/internal/v1/executions", HttpMethod.POST,
new HttpEntity<String>("", headers()), String.class);
} catch (Exception ignored) {
// 数据库已保存任务;通知失败由执行器后台补扫,不能降级成另一笔密码交易。
}
}
private HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
return headers;
}
}
@@ -0,0 +1,42 @@
package com.ruoyi.system.chain;
import java.net.InetAddress;
import java.util.Arrays;
/**
* 执行服务仅接受明确的 RFC1918 IPv4 或回环地址。
* 禁止域名解析、通配监听、链路本地地址和转发头,避免配置意外开放公网。
*/
public final class IntranetAddress {
private IntranetAddress() { }
public static InetAddress parse(String literal) {
if (literal == null || !literal.matches("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+")) {
throw new IllegalArgumentException("必须配置明确的内网 IPv4 地址");
}
String[] parts = literal.split("\\.");
byte[] bytes = new byte[4];
for (int i = 0; i < parts.length; i++) {
int value = Integer.parseInt(parts[i]);
if (value > 255 || !Integer.toString(value).equals(parts[i])) {
throw new IllegalArgumentException("内网 IPv4 地址格式无效");
}
bytes[i] = (byte) value;
}
int first = bytes[0] & 255;
int second = bytes[1] & 255;
if (!(first == 10 || first == 127 || first == 172 && second >= 16 && second <= 31
|| first == 192 && second == 168)) {
throw new IllegalArgumentException("执行服务禁止使用公网或通配地址");
}
try {
return InetAddress.getByAddress(bytes);
} catch (java.net.UnknownHostException ex) {
throw new IllegalArgumentException("内网 IPv4 地址格式无效");
}
}
public static boolean matches(InetAddress peer, String literal) {
return peer != null && Arrays.equals(peer.getAddress(), parse(literal).getAddress());
}
}
@@ -0,0 +1,66 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.common.exception.CustomException;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;
/** 兑呀资源订单适配,使用buy_energy/buy_net,绝不混用速充接口。 */
@Component
public class DuiyaResourceRentalProvider implements ResourceRentalProvider {
private final ResourceProviderHttp http;
public DuiyaResourceRentalProvider(ResourceProviderHttp http) { this.http = http; }
public String code() { return "DUIYA"; }
public Quote quote(Map<String, Object> config, String network, String address, String resource, long quantity) {
if (!"MAINNET".equals(network)) throw new CustomException("兑呀资源订单尚未确认测试网支持,已拒绝下单");
String period = String.valueOf(config.get("ENERGY".equals(resource) ? "energy_period" : "bandwidth_period"));
String type = "ENERGY".equals(resource) ? "energy" : "net";
HttpUrl url = ResourceProviderHttp.url(config, "/query_price").newBuilder()
.addQueryParameter("type", type).addQueryParameter("count", Long.toString(quantity))
.addQueryParameter("period", period).build();
Map<String, Object> price = data(http.send(auth(config, url).get().build()));
Quote quote = new Quote();
quote.quantity = quantity;
quote.amount = new BigDecimal(String.valueOf(price.get("amount")));
quote.currency = "TRX";
quote.request = new LinkedHashMap<>();
quote.request.put("count", quantity);
quote.request.put("period", period);
quote.request.put("address", address);
quote.request.put("resource", resource);
return quote;
}
public Submission create(Map<String, Object> config, String merchantOrderNo, Quote quote) {
String path = "ENERGY".equals(quote.request.get("resource")) ? "/buy_energy" : "/buy_net";
FormBody.Builder form = new FormBody.Builder();
for (String field : new String[] {"count", "period", "address"}) form.add(field, String.valueOf(quote.request.get(field)));
Map<String, Object> data = data(http.send(auth(config, ResourceProviderHttp.url(config, path))
.post(form.build()).build()));
Object order = data.get("order_sn");
if (order == null || order.toString().isEmpty()) throw new CustomException("兑呀未返回订单号,请核对原订单");
return new Submission(order.toString(), "ACCEPTED");
}
public String query(Map<String, Object> config, String merchantOrderNo, String providerOrderNo) {
if (providerOrderNo == null) return "UNKNOWN";
HttpUrl url = ResourceProviderHttp.url(config, "/query_result").newBuilder()
.addQueryParameter("order_sn", providerOrderNo).build();
return String.valueOf(data(http.send(auth(config, url).get().build())).get("status"));
}
private Map<String, Object> data(Map<String, Object> response) {
if (!"1".equals(String.valueOf(response.get("code")))) throw new CustomException("兑呀未确认请求成功,请核对原单及平台配置");
return ResourceProviderHttp.data(response);
}
private Request.Builder auth(Map<String, Object> config, HttpUrl url) {
String key = http.key(config);
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
return new Request.Builder().url(url).header("x-api-key", key).header("x-timestamp", timestamp)
.header("x-signature", ResourceProviderHttp.hmac(http.secret(config), key + timestamp));
}
}
@@ -0,0 +1,64 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.rental.RentalCrypto;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
/** 自有平台商户API适配:使用原始UTF-8 JSON签名,固定商户单号保证创建幂等。 */
@Component
public class InternalResourceRentalProvider implements ResourceRentalProvider {
private final ResourceProviderHttp http;
public InternalResourceRentalProvider(ResourceProviderHttp http) { this.http = http; }
public String code() { return "INTERNAL"; }
public Quote quote(Map<String, Object> config, String network, String address, String resource, long quantity) {
Map<String, Object> request = new LinkedHashMap<>();
request.put("network", network);
request.put("resource_type", resource);
request.put("receiver_address", address);
request.put("resource_quantity", quantity);
request.put("duration_seconds", config.get("duration_seconds"));
Map<String, Object> price = call(config, "/quote", request);
Quote quote = new Quote();
quote.quantity = quantity;
quote.amount = new BigDecimal(String.valueOf(price.get("amount")));
quote.currency = "USDT";
request.put("expected_amount", quote.amount.toPlainString());
quote.request = request;
return quote;
}
public Submission create(Map<String, Object> config, String merchantOrderNo, Quote quote) {
Map<String, Object> request = new LinkedHashMap<>(quote.request);
request.put("merchant_order_no", merchantOrderNo);
Map<String, Object> order = call(config, "/create", request);
if (order.get("order_no") == null) throw new CustomException("租赁平台未返回订单号");
return new Submission(order.get("order_no").toString(), String.valueOf(order.get("status")));
}
public String query(Map<String, Object> config, String merchantOrderNo, String providerOrderNo) {
Map<String, Object> request = new LinkedHashMap<>();
request.put("merchant_order_no", merchantOrderNo);
return String.valueOf(call(config, "/query", request).get("status"));
}
private Map<String, Object> call(Map<String, Object> config, String operation, Map<String, Object> request) {
HttpUrl url = ResourceProviderHttp.url(config, "/api/rental/v1" + operation);
String body = http.encode(request);
String key = http.key(config);
long time = System.currentTimeMillis();
String nonce = UUID.randomUUID().toString().replace("-", "");
String signature = RentalCrypto.sign(http.secret(config), "API", key, time, nonce, "POST", url.encodedPath(), body);
Map<String, Object> response = http.send(new Request.Builder().url(url)
.header("X-Rent-Key", key).header("X-Rent-Timestamp", Long.toString(time))
.header("X-Rent-Nonce", nonce).header("X-Rent-Signature", signature)
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body)).build());
if (!"200".equals(String.valueOf(response.get("code")))) throw new CustomException("自有租赁平台拒绝请求,请检查配置和租赁账户");
return ResourceProviderHttp.data(response);
}
}
@@ -0,0 +1,93 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.chain.ChainCommand;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** 从可信业务记录构造租赁目标,页面不允许提交任意地址、金额或钱包派生索引。 */
@Component
public class ResourceBusinessResolver {
private final ResourceLeaseStore store;
private final UsdtConfigMapper configs;
public ResourceBusinessResolver(ResourceLeaseStore store, UsdtConfigMapper configs) { this.store = store; this.configs = configs; }
public List<ChainCommand> resolve(String kind, Long id) {
return resolve(kind, id, false);
}
/** 后台付费前重新读取真实业务;执行中状态只允许远程队列使用,页面不能越过审核。 */
public void validateQueued(ChainCommand queued) {
if (queued.validUntil < System.currentTimeMillis() || queued.operation == null
|| !Boolean.TRUE.equals(queued.operation.getBroadcast())) {
throw new CustomException("原链上执行授权已过期或未确认广播,停止租赁");
}
String[] key = queued.businessKey.split(":");
if (key.length != 2) throw new CustomException("资源业务编号无效");
List<ChainCommand> current = resolve(key[0], Long.valueOf(key[1]), true);
if (current.size() != 1 || !ResourceLeaseStore.same(current.get(0), queued)
|| !java.util.Objects.equals(current.get(0).tokenIndex, queued.tokenIndex)) {
throw new CustomException("业务或钱包配置已变化,已停止租赁");
}
}
/** 人工恢复可处理尚在排队的远程业务,但不能延长执行指令的转账授权有效期。 */
public List<ChainCommand> resolveForResume(String kind, Long id) {
if (!"PAYOUT".equals(kind) && !"AGGREGATION".equals(kind)) return resolve(kind, id);
Map<String, Object> execution = store.one("select * from usdt_chain_execution where business_key=? and status='QUEUED' and execution_mode='REMOTE'", kind + ":" + id);
if (execution == null) return resolve(kind, id);
Map<String, Object> holder = new java.util.HashMap<>();
holder.put("command_json", execution.get("command_json"));
ChainCommand queued = store.command(holder);
if (queued.validUntil < System.currentTimeMillis()) throw new CustomException("原执行授权已过期,请待原任务标记失败后重新执行");
validateQueued(queued);
return java.util.Collections.singletonList(queued);
}
private List<ChainCommand> resolve(String kind, Long id, boolean queued) {
UsdtConfig config = configs.selectFirst();
if (config == null) throw new CustomException("主钱包未配置");
List<ChainCommand> commands = new ArrayList<>();
if ("PAYOUT".equals(kind)) {
Map<String, Object> order = store.one("select * from usdt_payout_order where id=? and deleted_at is null and status in "
+ (queued ? "(6)" : "(1,5)"), id);
if (order == null) throw new CustomException("代付订单尚未通过审核或已开始执行");
commands.add(command(config, "PAYOUT:" + id, null, config.getTokenAddress(), "0",
"USDT".equals(order.get("currency")) ? "usdt" : "trx", order.get("to_address"), order.get("amount")));
} else if ("TASK".equals(kind) || "AGGREGATION".equals(kind)) {
String where = "TASK".equals(kind) ? "i.parent_id=?" : "i.id=?";
List<Map<String, Object>> items = store.jdbc().queryForList("select i.*,w.id as wallet_id,w.token_index from usdt_aggregation_task_item i "
+ "join usdt_aggregation_task t on t.id=i.parent_id join wallet_address w on w.token=i.token_address and w.app_id=i.app_id "
+ "where " + where + (queued ? " and i.status=4 and t.verify_status=1 "
: " and i.status in (0,2) and t.verify_status=1 and t.status in (0,3) ")
+ "and i.deleted_at is null and t.deleted_at is null and w.status=1 and w.deleted_at is null order by i.id", id);
if (items.isEmpty()) throw new CustomException("没有审核通过且可执行的归集明细");
for (Map<String, Object> item : items) commands.add(command(config, "AGGREGATION:" + item.get("id"),
((Number) item.get("wallet_id")).longValue(), String.valueOf(item.get("token_address")),
String.valueOf(item.get("token_index")), "usdt", item.get("dist_token_address"), item.get("ope_amount")));
} else { throw new CustomException("不支持的资源业务类型"); }
return commands;
}
private ChainCommand command(UsdtConfig config, String key, Long walletId, String address, String index,
String type, Object target, Object amount) {
ChainCommand command = new ChainCommand();
command.businessKey = key;
command.walletId = walletId;
command.address = address;
command.tokenIndex = index;
command.network = config.getTronNetType();
command.envelopeVersion = config.getVersion();
command.type = type;
command.operation = new WalletOperationRequest();
command.operation.setToAddress(String.valueOf(target));
command.operation.setAmount(new BigDecimal(String.valueOf(amount)));
return command;
}
}
@@ -0,0 +1,33 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.chain.ChainCommand;
import org.springframework.stereotype.Component;
import java.util.Map;
/** 签名侧只做资源/业务绑定复检,不调用任何租赁创建接口。执行器也复用此组件。 */
@Component
public class ResourceExecutionGate {
private final ResourceLeaseStore store;
private final ResourceProbe probe;
public ResourceExecutionGate(ResourceLeaseStore store, ResourceProbe probe) { this.store = store; this.probe = probe; }
public boolean required(ChainCommand command) {
Map<String, Object> prep = store.byBusiness(command.businessKey);
return command.rentalRequired || prep != null && ((Number) prep.get("rental_authorized")).intValue() == 1;
}
/** 返回false表示仍需准备,调用方保持排队,禁止误记签名失败。 */
public boolean ready(ChainCommand command) {
Map<String, Object> prep = store.byBusiness(command.businessKey);
if (prep == null || !ResourceLeaseStore.same(store.command(prep), command)) return false;
if (!"READY".equals(prep.get("stage")) || !store.acquire(prep)) return false;
ResourceProbe.Observation current = probe.inspect(command);
store.observe(String.valueOf(prep.get("id")), current);
return current.ready();
}
public void require(ChainCommand command) {
if (!ready(command)) throw new CustomException("资源尚未满足,请继续核对原租赁订单,勿重复租赁");
}
public void transferred(String key, String hash) { store.transferred(key, hash); }
}
@@ -0,0 +1,116 @@
package com.ruoyi.system.chain.resource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.chain.ChainCommand;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import javax.sql.DataSource;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* 资源准备持久化及地址占用。唯一键防重复,短事务只操作数据库,不包含HTTP/RPC。
* 地址占用不能按超时自动回收:先签名后宕机时,交易可能仍会进入链上。
*/
@Repository
public class ResourceLeaseStore {
private final JdbcTemplate jdbc;
private final TransactionTemplate transactions;
private final ObjectMapper json = new ObjectMapper();
public ResourceLeaseStore(DataSource source, PlatformTransactionManager manager) {
jdbc = new JdbcTemplate(source);
transactions = new TransactionTemplate(manager);
}
public JdbcTemplate jdbc() { return jdbc; }
public Map<String, Object> one(String sql, Object... args) {
List<Map<String, Object>> rows = jdbc.queryForList(sql, args);
return rows.isEmpty() ? null : rows.get(0);
}
public Map<String, Object> byBusiness(String key) {
return one("select * from usdt_resource_preparation where business_key=?", key);
}
public Map<String, Object> get(String id) {
Map<String, Object> row = one("select * from usdt_resource_preparation where id=?", id);
if (row == null) throw new CustomException("资源准备记录不存在");
return row;
}
public ChainCommand command(Map<String, Object> row) {
try { return json.readValue(String.valueOf(row.get("command_json")), ChainCommand.class); }
catch (Exception ex) { throw new CustomException("资源准备参数无效"); }
}
public String encode(Object value) {
try { return json.writeValueAsString(value); }
catch (Exception ex) { throw new CustomException("资源准备参数编码失败"); }
}
public Map<String, Object> ensure(ChainCommand command, int seconds) {
String id = UUID.randomUUID().toString();
try {
jdbc.update("insert into usdt_resource_preparation(id,business_key,network,address,command_json,deadline_at) values(?,?,?,?,?,?)",
id, command.businessKey, ResourceProbe.network(command), command.address, encode(command),
new Timestamp(System.currentTimeMillis() + seconds * 1000L));
} catch (DuplicateKeyException existing) {
// 重复预检/页面刷新复用原准备记录,不创建新轮次,不重置付费订单。
}
Map<String, Object> row = byBusiness(command.businessKey);
ChainCommand original = command(row);
if (!same(original, command)) throw new CustomException("业务或钱包配置已变化,请核对原资源订单");
// 尚未授权且没有付费记录的过期预检可重新开始;已授权记录必须显式恢复原单检测。
jdbc.update("update usdt_resource_preparation set deadline_at=? where id=? and rental_authorized=0 and deadline_at<CURRENT_TIMESTAMP "
+ "and not exists(select 1 from usdt_resource_rental_order where preparation_id=?)",
new Timestamp(System.currentTimeMillis() + seconds * 1000L), row.get("id"), row.get("id"));
row = get(String.valueOf(row.get("id")));
return row;
}
public static boolean same(ChainCommand a, ChainCommand b) {
return java.util.Objects.equals(a.address, b.address) && java.util.Objects.equals(a.network, b.network)
&& java.util.Objects.equals(a.tokenIndex, b.tokenIndex)
&& java.util.Objects.equals(a.envelopeVersion, b.envelopeVersion)
&& java.util.Objects.equals(a.type, b.type) && java.util.Objects.equals(a.walletId, b.walletId)
&& java.util.Objects.equals(a.operation.getToAddress(), b.operation.getToAddress())
&& a.operation.getAmount().compareTo(b.operation.getAmount()) == 0;
}
public boolean acquire(Map<String, Object> prep) {
try { jdbc.update("insert into usdt_resource_address_guard(network,address) values(?,?)", prep.get("network"), prep.get("address")); }
catch (DuplicateKeyException exists) { /* 地址只有一行,多进程共享。 */ }
return transactions.execute(status -> {
Map<String, Object> guard = one("select * from usdt_resource_address_guard where network=? and address=? for update",
prep.get("network"), prep.get("address"));
if (guard.get("owner_id") != null && !prep.get("id").equals(guard.get("owner_id"))) return false;
jdbc.update("update usdt_resource_address_guard set owner_id=? where network=? and address=?",
prep.get("id"), prep.get("network"), prep.get("address"));
return true;
});
}
public void release(Map<String, Object> prep) {
jdbc.update("update usdt_resource_address_guard set owner_id=null where network=? and address=? and owner_id=?",
prep.get("network"), prep.get("address"), prep.get("id"));
}
public void observe(String id, ResourceProbe.Observation value) {
jdbc.update("update usdt_resource_preparation set required_energy=?,required_bandwidth=?,available_energy=?,available_bandwidth=?,"
+ "checked_at=CURRENT_TIMESTAMP,stage=?,error_message=null,updated_at=CURRENT_TIMESTAMP where id=? and stage<>'TRANSFERRED'",
value.requiredEnergy, value.requiredBandwidth, value.availableEnergy, value.availableBandwidth,
value.ready() ? "READY" : "WAITING", id);
}
public void stage(String id, String stage, String message) {
jdbc.update("update usdt_resource_preparation set stage=?,error_message=?,updated_at=CURRENT_TIMESTAMP where id=? and stage<>'TRANSFERRED'",
stage, message, id);
}
public void transferred(String businessKey, String hash) {
jdbc.update("update usdt_resource_preparation set stage='TRANSFERRED',transaction_id=?,updated_at=CURRENT_TIMESTAMP where business_key=?",
hash, businessKey);
}
/** 本地唯一键+CAS是实际付费调用屏障。HTTP超时后保留SUBMIT_UNKNOWN,绝不回到CREATED。 */
public boolean claimOrder(String id) {
return jdbc.update("update usdt_resource_rental_order set status='SUBMITTING',updated_at=CURRENT_TIMESTAMP where id=? and status='CREATED'", id) == 1;
}
}
@@ -0,0 +1,93 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.chain.ChainCommand;
import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.TronServiceProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.proto.Response;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 付费租赁专用的严格链上读取。与页面快照分开:节点异常必须抛错,不能按零资源补租。
* 指定指令网络,查询实际发送钱包;不读取平台返回的“资源已到账”作为执行依据。
*/
@Component
public class ResourceProbe {
private final TronServiceProvider networks;
@Value("${tron.operation-resource-redundancy-percent:20}")
private int redundancy;
public ResourceProbe(TronServiceProvider networks) { this.networks = networks; }
public Observation inspect(ChainCommand command) {
ITronService tron = networks.getServiceForNetwork(network(command));
ApiWrapper api = tron.buildApiWrapper();
try {
if (api.getAccount(command.address).getAddress().isEmpty()) {
throw new CustomException("发送钱包尚未激活,不能接收代理资源");
}
Response.AccountResourceMessage resource = api.getAccountResource(command.address);
long energy = "usdt".equals(command.type)
? tron.estimateEnergy(api, command.address, command.operation.getToAddress(), command.operation.getAmount()) : 0;
if ("usdt".equals(command.type) && energy <= 0) {
throw new CustomException("未取得有效能量估算,请检查节点");
}
long bandwidth = "trx".equals(command.type)
? tron.estimateBandwidth(api, command.address, command.operation.getToAddress(), command.operation.getAmount())
: tron.defaultEstimateBandwidth();
if (bandwidth <= 0) throw new CustomException("未取得有效带宽估算");
Observation value = new Observation();
value.requiredEnergy = safe(energy);
value.requiredBandwidth = safe(Math.addExact(bandwidth, 100));
value.availableEnergy = Math.max(0, resource.getEnergyLimit() - resource.getEnergyUsed());
long staked = Math.max(0, resource.getNetLimit() - resource.getNetUsed());
long free = Math.max(0, resource.getFreeNetLimit() - resource.getFreeNetUsed());
// TRC20 合约调用只按质押/收到代理带宽预算;普通转账可使用免费额度。
// 协议按单种额度支付整笔交易,不能把两份不足的额度简单相加冒充足额。
value.availableBandwidth = "trx".equals(command.type) ? Math.max(staked, free) : staked;
if ("usdt".equals(command.type)
&& tron.getUsdtBalance(api, command.address).compareTo(command.operation.getAmount()) < 0) {
throw new CustomException("USDT余额不足,不能准备本次转账");
}
if ("trx".equals(command.type)
&& tron.getTRxBalance(api, command.address).compareTo(command.operation.getAmount()) < 0) {
throw new CustomException("TRX本金不足,不能准备本次转账");
}
return value;
} finally { api.close(); }
}
/** 只在节点已给出交易收据后释放地址占用,不能仅凭广播接口成功就复用资源。 */
public boolean consumed(ChainCommand command, String hash) {
ApiWrapper api = networks.getServiceForNetwork(network(command)).buildApiWrapper();
try { return api.getTransactionInfoById(hash).getBlockNumber() > 0; }
catch (Exception unknown) { return false; }
finally { api.close(); }
}
private long safe(long value) {
return BigDecimal.valueOf(value).multiply(BigDecimal.valueOf(100L + Math.max(0, redundancy)))
.divide(BigDecimal.valueOf(100), 0, RoundingMode.UP).longValueExact();
}
public static String network(ChainCommand command) {
if (Integer.valueOf(0).equals(command.network)) return "NILE";
if (Integer.valueOf(1).equals(command.network)) return "MAINNET";
throw new CustomException("资源租赁仅支持NILE和MAINNET");
}
public static class Observation {
public long requiredEnergy;
public long requiredBandwidth;
public long availableEnergy;
public long availableBandwidth;
public long energyGap() { return Math.max(0, requiredEnergy - availableEnergy); }
public long bandwidthGap() { return Math.max(0, requiredBandwidth - availableBandwidth); }
public boolean ready() { return energyGap() == 0 && bandwidthGap() == 0; }
}
}
@@ -0,0 +1,69 @@
package com.ruoyi.system.chain.resource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.rental.RentalCrypto;
import okhttp3.*;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/** 租赁出站客户端:禁止重定向和连接自动重试,防止有副作用的创建请求被重复发送。 */
@Component
public class ResourceProviderHttp {
private final RentalCrypto crypto;
private final ObjectMapper json = new ObjectMapper();
private final OkHttpClient client = new OkHttpClient.Builder().retryOnConnectionFailure(false)
.followRedirects(false).followSslRedirects(false).connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS).callTimeout(15, TimeUnit.SECONDS).build();
public ResourceProviderHttp(RentalCrypto crypto) { this.crypto = crypto; }
public String key(Map<String, Object> config) { return crypto.decrypt(String.valueOf(config.get("api_key_cipher"))); }
public String secret(Map<String, Object> config) { return crypto.decrypt(String.valueOf(config.get("api_secret_cipher"))); }
public String encode(Object value) {
try { return json.writeValueAsString(value); }
catch (Exception ex) { throw new CustomException("资源订单参数编码失败"); }
}
public Map<String, Object> send(Request request) {
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful() || response.body() == null) throw new IllegalStateException();
// 平台正文可能包含敏感上下文,异常原文和完整正文均不输出。
// 先限制读取字节,再解码,避免异常平台一次返回巨大正文占满内存。
okio.BufferedSource source = response.body().source();
source.request(262145);
if (source.buffer().size() > 262144) throw new IllegalStateException();
String body = source.readUtf8();
return json.readValue(body, new TypeReference<Map<String, Object>>() { });
} catch (Exception ex) { throw new CustomException("资源平台响应未能确认,请核对原订单,勿重复下单"); }
}
public static String hmac(String secret, String plain) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
StringBuilder hex = new StringBuilder();
for (byte b : mac.doFinal(plain.getBytes(StandardCharsets.UTF_8))) hex.append(String.format("%02x", b & 255));
return hex.toString();
} catch (Exception ex) { throw new CustomException("资源平台签名失败"); }
}
public static HttpUrl url(Map<String, Object> config, String path) {
HttpUrl base = HttpUrl.parse(String.valueOf(config.get("base_url")));
if (base == null || !base.isHttps() || !base.username().isEmpty() || !base.password().isEmpty()
|| base.query() != null || base.fragment() != null) throw new CustomException("资源平台地址必须为HTTPS且不含认证信息或查询串");
return HttpUrl.parse(base.toString().replaceAll("/+$", "") + path);
}
@SuppressWarnings("unchecked")
public static Map<String, Object> data(Map<String, Object> response) {
if (!(response.get("data") instanceof Map)) throw new CustomException("资源平台未返回有效订单数据");
return (Map<String, Object>) response.get("data");
}
}
@@ -0,0 +1,19 @@
package com.ruoyi.system.chain.resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/** 平台选择来自部署配置;连接凭证和计价策略来自数据库。默认关闭以兼容旧部署。 */
@Component
public class ResourceRentalProperties {
@Value("${usdt.resource-rental.enabled:false}")
private boolean enabled;
@Value("${usdt.resource-rental.provider:INTERNAL}")
private String provider;
@Value("${usdt.resource-rental.arrival-timeout-seconds:300}")
private int timeoutSeconds;
public boolean isEnabled() { return enabled; }
public String getProvider() { return provider; }
public int getTimeoutSeconds() { return Math.max(30, timeoutSeconds); }
}
@@ -0,0 +1,26 @@
package com.ruoyi.system.chain.resource;
import java.math.BigDecimal;
import java.util.Map;
/** 公共资源订单接口。所有参数都是公开业务数据,禁止传递钱包密码和私钥。 */
public interface ResourceRentalProvider {
String code();
Quote quote(Map<String, Object> config, String network, String address, String resource, long quantity);
Submission create(Map<String, Object> config, String merchantOrderNo, Quote quote);
String query(Map<String, Object> config, String merchantOrderNo, String providerOrderNo);
final class Quote {
public long quantity;
public BigDecimal amount;
public String currency;
/** 下单参数快照,重放时不能重新报价改变原订单。 */
public Map<String, Object> request;
}
final class Submission {
public final String orderNo;
public final String status;
public Submission(String orderNo, String status) { this.orderNo = orderNo; this.status = status; }
}
}
@@ -0,0 +1,303 @@
package com.ruoyi.system.chain.resource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.chain.ChainCommand;
import com.ruoyi.system.chain.ChainExecutionStore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
/**
* 资源准备编排。租赁受理和资源到账独立;本类绝不持有钱包密码,也不调用转账签名。
* 人工只有prepare入口能授权新订单;定时检测只能续查原单,不能偷偷购买第二轮资源。
*/
@Service
public class ResourceRentalService {
@org.springframework.beans.factory.annotation.Autowired
private ResourceBusinessResolver businessResolver;
private final ResourceRentalProperties properties;
private final ResourceLeaseStore store;
private final ResourceProbe probe;
private final Map<String, ResourceRentalProvider> providers = new HashMap<>();
private final TransactionTemplate tx;
private final ObjectMapper json = new ObjectMapper();
public ResourceRentalService(ResourceRentalProperties properties, ResourceLeaseStore store, ResourceProbe probe,
List<ResourceRentalProvider> adapters, PlatformTransactionManager manager) {
this.properties = properties;
this.store = store;
this.probe = probe;
this.tx = new TransactionTemplate(manager);
for (ResourceRentalProvider adapter : adapters) providers.put(adapter.code(), adapter);
}
public boolean enabled() { return properties.isEnabled(); }
/** 预检可以报价但不会创建平台付费订单;刷新始终复用业务唯一准备记录。 */
public Map<String, Object> preview(ChainCommand command) {
Map<String, Object> prep = store.ensure(command, properties.getTimeoutSeconds());
prep = reuseConfirmedFailure(prep);
if (((Number) prep.get("rental_authorized")).intValue() == 1) {
check(prep);
// 已授权订单只能展示原订单,不受当前平台切换或新报价影响。
return view(store.get(String.valueOf(prep.get("id"))));
}
if ("TRANSFERRED".equals(prep.get("stage"))) return view(prep);
ResourceProbe.Observation current = probe.inspect(command);
if (((Number) prep.get("rental_authorized")).intValue() == 0) store.observe(String.valueOf(prep.get("id")), current);
Map<String, Object> view = view(store.get(String.valueOf(prep.get("id"))));
if (current.ready() && orders(prep).isEmpty()) {
view.put("quoteAmount", "0");
return view;
}
Map<String, Object> config = config(ResourceProbe.network(command));
BigDecimal total = BigDecimal.ZERO;
for (String resource : Arrays.asList("ENERGY", "BANDWIDTH")) {
long gap = "ENERGY".equals(resource) ? current.energyGap() : current.bandwidthGap();
Map<String, Object> order = order(prep, resource);
if (order != null) total = total.add(amount(order.get("quote_amount")));
else if (gap > 0) total = total.add(quote(config, command, resource, gap).amount);
}
view.put("quoteAmount", total.toPlainString());
view.put("currency", config.get("currency"));
view.put("provider", config.get("provider_code"));
return view;
}
/** 用户明确确认的报价上限只作用于本准备记录;远程使用数据库上限。 */
public void prepare(ChainCommand command, BigDecimal confirmedMaximum) {
Map<String, Object> prep = store.ensure(command, properties.getTimeoutSeconds());
if ("TRANSFERRED".equals(prep.get("stage"))) return;
if (((Number) prep.get("rental_authorized")).intValue() == 1) {
// 重复点击和远程轮询仅检查原单,不能补购另一类资源或覆盖REVIEW状态。
check(prep);
return;
}
if (expired(prep)) throw new CustomException("资源等待已超时,请核对原租赁单,不能重复购买");
if (!store.acquire(prep)) {
store.stage(String.valueOf(prep.get("id")), "ADDRESS_BUSY", "该发送钱包已有资源准备或转账,请等待原任务");
return;
}
ResourceProbe.Observation current = probe.inspect(command);
if (current.ready() && orders(prep).isEmpty()) {
tx.execute(status -> {
store.one("select id from usdt_resource_preparation where id=? for update", prep.get("id"));
store.jdbc().update("update usdt_resource_preparation set rental_authorized=1 where id=?", prep.get("id"));
return null;
});
check(store.get(String.valueOf(prep.get("id"))));
return;
}
Map<String, Object> config = config(ResourceProbe.network(command));
Map<String, ResourceRentalProvider.Quote> plans = new LinkedHashMap<>();
for (String resource : Arrays.asList("ENERGY", "BANDWIDTH")) {
long gap = "ENERGY".equals(resource) ? current.energyGap() : current.bandwidthGap();
if (gap > 0 && order(prep, resource) == null) plans.put(resource, quote(config, command, resource, gap));
}
// 两类资源先统一校验费用并落库,再发请求,避免第一类购买后第二类报价超限。
tx.execute(status -> {
Map<String, Object> locked = store.one("select * from usdt_resource_preparation where id=? for update", prep.get("id"));
if (((Number) locked.get("rental_authorized")).intValue() == 1) return null;
BigDecimal total = BigDecimal.ZERO;
for (Map<String, Object> existing : orders(prep)) total = total.add(amount(existing.get("quote_amount")));
for (Map.Entry<String, ResourceRentalProvider.Quote> entry : plans.entrySet()) {
if (order(prep, entry.getKey()) == null) total = total.add(entry.getValue().amount);
}
BigDecimal cap = amount(config.get("max_execution_cost"));
if (confirmedMaximum != null) cap = cap.min(confirmedMaximum);
if (cap.signum() <= 0 || total.compareTo(cap) > 0) throw new CustomException("租赁报价超过已确认上限,请重新确认费用");
for (Map.Entry<String, ResourceRentalProvider.Quote> entry : plans.entrySet()) {
ResourceRentalProvider.Quote quote = entry.getValue();
if (order(prep, entry.getKey()) != null) continue;
store.jdbc().update("insert into usdt_resource_rental_order(id,preparation_id,resource_type,config_id,quantity,request_json,quote_amount,currency) values(?,?,?,?,?,?,?,?)",
UUID.randomUUID().toString(), prep.get("id"), entry.getKey(), config.get("id"), quote.quantity,
store.encode(quote.request), quote.amount, quote.currency);
}
store.jdbc().update("update usdt_resource_preparation set rental_authorized=1 where id=?", prep.get("id"));
return null;
});
submitExisting(prep);
check(store.get(String.valueOf(prep.get("id"))));
}
private ResourceRentalProvider.Quote quote(Map<String, Object> config, ChainCommand command, String resource, long gap) {
long step = ((Number) config.get("ENERGY".equals(resource) ? "energy_step" : "bandwidth_step")).longValue();
if (step <= 0) throw new CustomException("租赁起租量配置不正确");
if ("DUIYA".equals(config.get("provider_code"))) step = Math.max(step, "ENERGY".equals(resource) ? 30000 : 100);
long quantity = Math.multiplyExact(Math.addExact(gap, step - 1) / step, step);
ResourceRentalProvider.Quote quote = provider(config).quote(config, ResourceProbe.network(command), command.address, resource, quantity);
if (quote.amount == null || quote.amount.signum() < 0 || quote.amount.compareTo(amount(config.get("max_order_cost"))) > 0
|| !quote.currency.equals(config.get("currency"))) throw new CustomException("租赁报价超限或计价币种不匹配");
return quote;
}
/** 只发送已持久化且已授权的CREATED订单;CAS失败的并发请求只返回原状态。 */
public void submitExisting(Map<String, Object> prep) {
for (Map<String, Object> order : orders(prep)) {
String id = String.valueOf(order.get("id"));
if (!"CREATED".equals(order.get("status"))) continue;
// 进程重启后CREATED也必须重验业务,不能为已取消或已换钱包的业务付款。
ChainCommand original = store.command(prep);
Map<String, Object> queued = store.one("select * from usdt_chain_execution where business_key=? and status='QUEUED' and execution_mode='REMOTE'", original.businessKey);
if (queued != null) {
try { businessResolver.validateQueued(json.readValue(String.valueOf(queued.get("command_json")), ChainCommand.class)); }
catch (Exception invalid) { throw new CustomException("业务已变化,停止提交资源租赁订单"); }
} else {
String[] key = original.businessKey.split(":");
List<ChainCommand> current = businessResolver.resolve(key[0], Long.valueOf(key[1]));
if (current.size() != 1 || !ResourceLeaseStore.same(original, current.get(0))) throw new CustomException("业务已变化,停止提交资源租赁订单");
}
if (!store.claimOrder(id)) continue;
try {
Map<String, Object> config = configById(order.get("config_id"));
ResourceRentalProvider.Quote quote = new ResourceRentalProvider.Quote();
quote.quantity = ((Number) order.get("quantity")).longValue();
quote.amount = amount(order.get("quote_amount"));
quote.currency = String.valueOf(order.get("currency"));
quote.request = json.readValue(String.valueOf(order.get("request_json")), new TypeReference<Map<String, Object>>() { });
ResourceRentalProvider.Submission result = provider(config).create(config, id, quote);
store.jdbc().update("update usdt_resource_rental_order set status='ACCEPTED',provider_order_no=?,provider_status=?,updated_at=CURRENT_TIMESTAMP where id=? and status='SUBMITTING'",
result.orderNo, result.status, id);
} catch (Exception uncertain) {
// 即使实际调用尚未发生,也保守待核对;没有平台幂等证明时不自动付费重试。
store.jdbc().update("update usdt_resource_rental_order set status='SUBMIT_UNKNOWN',error_message='受理结果未确认,请核对原单,禁止重复购买',updated_at=CURRENT_TIMESTAMP where id=? and status='SUBMITTING'", id);
store.stage(String.valueOf(prep.get("id")), "REVIEW", "租赁受理结果未知,请核对原订单");
}
}
}
/** 平台查询只维护平台结果,READY只能由probe.inspect得出。 */
public void check(Map<String, Object> prep) {
String id = String.valueOf(prep.get("id"));
if ("TRANSFERRED".equals(prep.get("stage"))) return;
// 宕机可能发生在CAS之后、响应入库之前;超过单次HTTP最长调用时间后只转为未知,绝不重发。
store.jdbc().update("update usdt_resource_rental_order set status='SUBMIT_UNKNOWN',error_message='进程中断或受理结果未知,禁止重复购买' "
+ "where preparation_id=? and status='SUBMITTING' and updated_at<?", id,
new Timestamp(System.currentTimeMillis() - 60000));
for (Map<String, Object> order : orders(prep)) {
String state = String.valueOf(order.get("status"));
if (!"CREATED".equals(state) && !"SUBMITTING".equals(state) && !"DELIVERED".equals(state) && !"FAILED".equals(state)) {
try {
Map<String, Object> config = configById(order.get("config_id"));
String providerState = provider(config).query(config, String.valueOf(order.get("id")),
order.get("provider_order_no") == null ? null : order.get("provider_order_no").toString());
// 自有平台状态契约明确;兑呀保留原状态,不猜测未知数字枚举。
String local = "SUCCESS".equalsIgnoreCase(providerState) ? "DELIVERED"
: "FAILED".equalsIgnoreCase(providerState) || "CANCELLED".equalsIgnoreCase(providerState) ? "FAILED"
: "INTERNAL".equals(config.get("provider_code")) && providerState != null
&& Arrays.asList("PENDING", "PROCESSING", "PAID", "QUEUED", "DISPATCHING", "ACTIVE").contains(providerState.toUpperCase(java.util.Locale.ROOT))
? "ACCEPTED" : state;
store.jdbc().update("update usdt_resource_rental_order set status=?,provider_status=?,updated_at=CURRENT_TIMESTAMP where id=? and status<>'SUBMITTING'",
local, providerState, order.get("id"));
} catch (Exception queryUnavailable) { /* 平台查询失败仍独立查询链上,不能伪造失败或新建订单。 */ }
}
}
boolean uncertain = orders(prep).stream().anyMatch(order -> Arrays.asList("CREATED", "SUBMITTING", "SUBMIT_UNKNOWN", "FAILED").contains(order.get("status")));
if (uncertain) { store.stage(id, "REVIEW", "原租赁订单需核对,未重复购买"); return; }
if (expired(prep)) { store.stage(id, "TIMEOUT", "资源等待超时,请核对原单;未重新购买"); return; }
if (!store.acquire(prep)) { store.stage(id, "ADDRESS_BUSY", "等待同地址前序资源任务完成"); return; }
try { store.observe(id, probe.inspect(store.command(prep))); }
catch (Exception unavailable) { store.stage(id, "CHECK_ERROR", "暂时无法确认链上资源,正在重试;未重复购买"); }
}
public Map<String, Object> view(Map<String, Object> prep) {
Map<String, Object> safe = new LinkedHashMap<>(prep);
safe.remove("command_json");
List<Map<String, Object>> safeOrders = new ArrayList<>();
for (Map<String, Object> order : orders(prep)) {
Map<String, Object> copy = new LinkedHashMap<>(order);
copy.remove("request_json");
safeOrders.add(copy);
}
safe.put("orders", safeOrders);
return safe;
}
public List<Map<String, Object>> orders(Map<String, Object> prep) {
return store.jdbc().queryForList("select * from usdt_resource_rental_order where preparation_id=? order by resource_type", prep.get("id"));
}
private Map<String, Object> order(Map<String, Object> prep, String resource) {
return store.one("select * from usdt_resource_rental_order where preparation_id=? and resource_type=?", prep.get("id"), resource);
}
private boolean expired(Map<String, Object> prep) {
return ((java.util.Date) prep.get("deadline_at")).getTime() < System.currentTimeMillis();
}
private Map<String, Object> config(String network) {
Map<String, Object> row = store.one("select * from usdt_resource_rental_config where provider_code=? and network=? and enabled=1 order by id desc limit 1", properties.getProvider(), network);
if (row == null) throw new CustomException("当前网络未配置可用的资源租赁平台");
return row;
}
private Map<String, Object> configById(Object id) {
Map<String, Object> config = store.one("select * from usdt_resource_rental_config where id=?", id);
if (config == null) throw new CustomException("原租赁配置不存在,请核对原订单");
return config;
}
private ResourceRentalProvider provider(Map<String, Object> config) {
ResourceRentalProvider provider = providers.get(String.valueOf(config.get("provider_code")));
if (provider == null) throw new CustomException("不支持的资源租赁平台");
return provider;
}
private static BigDecimal amount(Object value) { return new BigDecimal(String.valueOf(value)); }
/** 每轮有限推进,异常隔离到订单。此方法由独立后台Worker调用,不依赖浏览器存活。 */
public void tick(ChainExecutionStore executions) {
if (!enabled()) return;
// 先释放节点已返回收据的地址占用;SIGNED结果未知时绝不回收。
for (Map<String, Object> prep : store.jdbc().queryForList("select p.* from usdt_resource_preparation p join usdt_resource_address_guard g on g.owner_id=p.id where p.stage='TRANSFERRED' limit 50")) {
try { if (probe.consumed(store.command(prep), String.valueOf(prep.get("transaction_id")))) store.release(prep); }
catch (Exception unavailable) { /* 单个地址的RPC错误不能阻塞后续订单。 */ }
}
for (Map<String, Object> row : store.jdbc().queryForList("select * from usdt_chain_execution where status='QUEUED' and execution_mode='REMOTE' order by created_at limit 50")) {
ChainCommand command = executions.command(row);
if (!command.rentalRequired || command.validUntil < System.currentTimeMillis()) continue;
try { businessResolver.validateQueued(command); prepare(command, null); }
catch (Exception ex) { /* 当前地址失败不能阻塞其他归集/代付,下面保留可见诊断。 */
Map<String, Object> prep = store.byBusiness(command.businessKey);
if (prep != null) diagnostic(prep, "资源准备未完成,请检查业务、平台配置和原租赁订单");
}
}
for (Map<String, Object> prep : store.jdbc().queryForList("select * from usdt_resource_preparation where rental_authorized=1 and stage<>'TRANSFERRED' order by updated_at limit 50")) {
try {
if (((Number) prep.get("rental_authorized")).intValue() == 1 && !expired(prep)) submitExisting(prep);
check(prep);
} catch (Exception isolated) { diagnostic(prep, "资源核对暂未完成,未重复购买"); }
}
}
private void diagnostic(Map<String, Object> prep, String message) {
Map<String, Object> latest = store.get(String.valueOf(prep.get("id")));
if (!Arrays.asList("REVIEW", "TIMEOUT", "TRANSFERRED").contains(latest.get("stage"))) {
store.stage(String.valueOf(prep.get("id")), "CHECK_ERROR", message);
}
}
/** 超时后的恢复只延长检测窗口并续查原单,不调用create,也不改变平台及数量。 */
public void resume(ChainCommand command) {
Map<String, Object> prep = store.byBusiness(command.businessKey);
if (prep == null || !ResourceLeaseStore.same(store.command(prep), command)) throw new CustomException("原资源准备记录不存在或已变化");
prep = reuseConfirmedFailure(prep);
if ("TRANSFERRED".equals(prep.get("stage"))) throw new CustomException("已有转账结果,请先核对链上交易");
store.jdbc().update("update usdt_resource_preparation set deadline_at=?,updated_at=CURRENT_TIMESTAMP where id=?",
new Timestamp(System.currentTimeMillis() + properties.getTimeoutSeconds() * 1000L), prep.get("id"));
check(store.get(String.valueOf(prep.get("id"))));
}
/** 只有原哈希已被既有确认流程判定链上失败,才允许复用剩余资源;旧签名仍留在执行审计表。 */
private Map<String, Object> reuseConfirmedFailure(Map<String, Object> prep) {
if (!"TRANSFERRED".equals(prep.get("stage"))) return prep;
Map<String, Object> execution = store.one("select status,transaction_id from usdt_chain_execution where business_key=?", prep.get("business_key"));
if (execution != null && "CHAIN_FAILED".equals(execution.get("status"))
&& Objects.equals(prep.get("transaction_id"), execution.get("transaction_id"))
&& probe.consumed(store.command(prep), String.valueOf(prep.get("transaction_id")))) {
store.jdbc().update("update usdt_resource_preparation set stage='CHECKING',transaction_id=null,deadline_at=?,updated_at=CURRENT_TIMESTAMP "
+ "where id=? and stage='TRANSFERRED' and transaction_id=?",
new Timestamp(System.currentTimeMillis() + properties.getTimeoutSeconds() * 1000L), prep.get("id"), prep.get("transaction_id"));
return store.get(String.valueOf(prep.get("id")));
}
return prep;
}
}
@@ -0,0 +1,26 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.system.chain.ChainExecutionStore;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PreDestroy;
/** RPC/HTTP运行于独立daemon线程,不能阻塞支付扫描和回调调度器;重启从持久化记录恢复。 */
@Component
public class ResourceRentalWorker {
private final ResourceRentalService service;
private final ChainExecutionStore executions;
private final AtomicBoolean working = new AtomicBoolean();
private final ExecutorService worker = Executors.newSingleThreadExecutor(r -> {
Thread thread = new Thread(r, "payment-resource-rental"); thread.setDaemon(true); return thread;
});
public ResourceRentalWorker(ResourceRentalService service, ChainExecutionStore executions) { this.service = service; this.executions = executions; }
@Scheduled(fixedDelay = 3000, initialDelay = 5000)
public void poll() {
if (!service.enabled() || !working.compareAndSet(false, true)) return;
worker.execute(() -> { try { service.tick(executions); } finally { working.set(false); } });
}
@PreDestroy public void close() { worker.shutdownNow(); }
}
@@ -0,0 +1,48 @@
package com.ruoyi.system.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.chain.ChainExecutorClient;
import com.ruoyi.system.chain.ChainExecutionStore;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
/** 管理页面只访问此支付后端入口,执行服务地址和认证凭据不会发送到浏览器。 */
@RestController
@RequestMapping("/system/chainExecutor")
public class ChainExecutorController {
@org.springframework.beans.factory.annotation.Autowired(required = false)
private com.ruoyi.system.chain.resource.ResourceRentalProperties rentalProperties;
private final ChainExecutorClient client;
private final ChainExecutionStore store;
public ChainExecutorController(ChainExecutorClient client, ChainExecutionStore store) {
this.client = client;
this.store = store;
}
@PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:usdtConfig:edit') "
+ "or @ss.hasPermi('system:usdtTask:execute') or @ss.hasPermi('system:usdtTask:user-edit') "
+ "or @ss.hasPermi('system:usdtTaskItem:edit') or @ss.hasPermi('system:usdtPayoutOrder:execute')")
@GetMapping("/status")
public AjaxResult status() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("enabled", client.isEnabled());
result.put("ready", client.ready());
// 明确列出公开字段,禁止 SELECT * 结果进入 HTTP 响应。
boolean rentalEnabled = rentalProperties != null && rentalProperties.isEnabled();
result.put("executions", client.isEnabled() ? store.jdbc().queryForList(rentalEnabled
? "select e.execution_id,e.business_key,e.status,e.transaction_id,e.error_message,e.created_at,"
+ "p.stage as resource_stage,p.error_message as resource_message from usdt_chain_execution e "
+ "left join usdt_resource_preparation p on p.business_key=e.business_key where e.operator_id=? order by e.created_at desc limit 5"
: "select execution_id,status,transaction_id,error_message,created_at from usdt_chain_execution "
+ "where operator_id=? order by created_at desc limit 5", SecurityUtils.getUserId())
: java.util.Collections.emptyList());
return AjaxResult.success(result);
}
}
@@ -0,0 +1,152 @@
package com.ruoyi.system.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.chain.ChainCommand;
import com.ruoyi.system.chain.resource.*;
import com.ruoyi.system.rental.RentalCrypto;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.*;
/** 管理端资源准备入口。无密码、不签名,不返回平台凭据;权限沿用对应业务执行权限。 */
@RestController
@RequestMapping("/system/chain-resources")
public class ResourceRentalController {
private final ResourceRentalService service;
private final ResourceBusinessResolver resolver;
private final ResourceLeaseStore store;
private final RentalCrypto crypto;
public ResourceRentalController(ResourceRentalService service, ResourceBusinessResolver resolver,
ResourceLeaseStore store, RentalCrypto crypto) {
this.service = service; this.resolver = resolver; this.store = store; this.crypto = crypto;
}
@PreAuthorize("@ss.hasAnyPermi('system:usdtPayoutOrder:execute,system:usdtTask:execute,system:usdtTaskItem:edit')")
@GetMapping("/status")
public AjaxResult status() { return AjaxResult.success(Collections.singletonMap("enabled", service.enabled())); }
@PreAuthorize("@ss.hasAnyPermi('system:usdtPayoutOrder:execute,system:usdtTask:execute,system:usdtTaskItem:edit')")
@PostMapping("/{kind}/{id}/preview")
public AjaxResult preview(@PathVariable String kind, @PathVariable Long id) {
permission(kind);
requireEnabled();
List<Map<String, Object>> rows = new ArrayList<>();
for (ChainCommand command : resolver.resolve(kind, id)) {
try { rows.add(service.preview(command)); }
catch (Exception unavailable) {
Map<String, Object> prep = store.byBusiness(command.businessKey);
if (prep == null) throw new CustomException("资源准备记录不可用,请稍后重试");
if (!Arrays.asList("REVIEW", "TIMEOUT", "TRANSFERRED").contains(prep.get("stage"))) {
store.stage(String.valueOf(prep.get("id")), "CHECK_ERROR", "无法确认链上资源或平台报价,请检查配置后重新预检");
}
rows.add(service.view(store.get(String.valueOf(prep.get("id")))));
}
}
return AjaxResult.success(rows);
}
@PreAuthorize("@ss.hasAnyPermi('system:usdtPayoutOrder:execute,system:usdtTask:execute,system:usdtTaskItem:edit')")
@PostMapping("/{kind}/{id}/prepare")
public AjaxResult prepare(@PathVariable String kind, @PathVariable Long id, @RequestBody PrepareRequest request) {
permission(kind);
requireEnabled();
// 使用预检时每条业务绑定的上限。不能用浏览器提交的地址/数量替代数据库业务。
List<ChainCommand> commands = resolver.resolve(kind, id);
if (request.maximums == null || request.maximums.size() > 10000) throw new CustomException("请先预检并确认租赁费用");
for (ChainCommand command : commands) {
BigDecimal maximum = request.maximums.get(command.businessKey);
if (maximum == null || maximum.signum() < 0) throw new CustomException("缺少该业务的租赁费用确认");
}
for (ChainCommand command : commands) {
try { service.prepare(command, request.maximums.get(command.businessKey)); }
catch (Exception isolated) {
// 按地址隔离:一个钱包报价/余额/节点失败,不能中断其余归集明细。
Map<String, Object> prep = store.byBusiness(command.businessKey);
if (prep != null && !Arrays.asList("REVIEW", "TIMEOUT", "TRANSFERRED").contains(prep.get("stage"))) {
store.stage(String.valueOf(prep.get("id")), "CHECK_ERROR", "资源准备未完成,请核对费用上限、余额、业务状态和平台配置");
}
}
}
return progress(kind, id);
}
@PreAuthorize("@ss.hasAnyPermi('system:usdtPayoutOrder:execute,system:usdtTask:execute,system:usdtTaskItem:edit')")
@PostMapping("/{kind}/{id}/resume")
public AjaxResult resume(@PathVariable String kind, @PathVariable Long id) {
permission(kind);
requireEnabled();
List<Map<String, Object>> rows = new ArrayList<>();
for (ChainCommand command : resolver.resolveForResume(kind, id)) {
service.resume(command);
rows.add(service.view(store.byBusiness(command.businessKey)));
}
return AjaxResult.success(rows);
}
@PreAuthorize("@ss.hasAnyPermi('system:usdtPayoutOrder:execute,system:usdtTask:execute,system:usdtTaskItem:edit')")
@GetMapping("/{kind}/{id}/progress")
public AjaxResult progress(@PathVariable String kind, @PathVariable Long id) {
permission(kind);
requireEnabled();
List<Map<String, Object>> rows = new ArrayList<>();
for (ChainCommand command : resolver.resolve(kind, id)) {
Map<String, Object> prep = store.byBusiness(command.businessKey);
if (prep != null) {
if (!ResourceLeaseStore.same(store.command(prep), command)) throw new CustomException("业务或钱包配置已变化,请核对原租赁单");
rows.add(service.view(prep));
}
}
return AjaxResult.success(rows);
}
/** 每种业务独立检查权限,不能凭代付执行权限购买任意归集资源。 */
private void permission(String kind) {
String permission = "PAYOUT".equals(kind) ? "system:usdtPayoutOrder:execute"
: "TASK".equals(kind) ? "system:usdtTask:execute" : "AGGREGATION".equals(kind) ? "system:usdtTaskItem:edit" : null;
Set<String> permissions = SecurityUtils.getLoginUser().getPermissions();
if (permission == null || permissions == null || !(permissions.contains("*:*:*") || permissions.contains(permission))) {
throw new CustomException("无权准备该业务资源");
}
}
private void requireEnabled() { if (!service.enabled()) throw new CustomException("资源租赁尚未启用"); }
/** 配置采用新增版本,原订单始终引用原config_id。没有日志注解,避免记录明文凭证请求。 */
@PreAuthorize("@ss.hasPermi('system:usdtConfig:edit')")
@PostMapping("/config")
public AjaxResult configure(@RequestBody ConfigRequest request) {
if (!Arrays.asList("INTERNAL", "DUIYA").contains(request.provider)
|| !Arrays.asList("NILE", "MAINNET").contains(request.network)
|| request.apiKey == null || request.apiKey.isEmpty() || request.apiSecret == null || request.apiSecret.isEmpty()
|| request.energyStep <= 0 || request.bandwidthStep <= 0 || request.durationSeconds <= 0
|| request.maxOrderCost == null || request.maxOrderCost.signum() <= 0
|| request.maxExecutionCost == null || request.maxExecutionCost.compareTo(request.maxOrderCost) < 0) {
throw new CustomException("资源平台配置不完整或费用上限无效");
}
Map<String, Object> target = new HashMap<>(); target.put("base_url", request.baseUrl);
ResourceProviderHttp.url(target, "");
String currency = "INTERNAL".equals(request.provider) ? "USDT" : "TRX";
try {
store.jdbc().update("insert into usdt_resource_rental_config(provider_code,network,base_url,api_key_cipher,api_secret_cipher,energy_period,bandwidth_period,duration_seconds,energy_step,bandwidth_step,max_order_cost,max_execution_cost,currency) values(?,?,?,?,?,?,?,?,?,?,?,?,?)",
request.provider, request.network, request.baseUrl, crypto.encrypt(request.apiKey), crypto.encrypt(request.apiSecret),
request.energyPeriod, request.bandwidthPeriod, request.durationSeconds, request.energyStep, request.bandwidthStep,
request.maxOrderCost, request.maxExecutionCost, currency);
return AjaxResult.success("资源平台配置已保存为新版本");
} finally { request.apiKey = null; request.apiSecret = null; }
}
public static class PrepareRequest { public Map<String, BigDecimal> maximums; }
public static class ConfigRequest {
public String provider, network, baseUrl;
@com.fasterxml.jackson.annotation.JsonProperty(access = com.fasterxml.jackson.annotation.JsonProperty.Access.WRITE_ONLY)
public String apiKey;
@com.fasterxml.jackson.annotation.JsonProperty(access = com.fasterxml.jackson.annotation.JsonProperty.Access.WRITE_ONLY)
public String apiSecret;
public String energyPeriod = "1h", bandwidthPeriod = "1day";
public long durationSeconds = 3600, energyStep = 30000, bandwidthStep = 100;
public BigDecimal maxOrderCost, maxExecutionCost;
}
}
@@ -70,7 +70,7 @@ public class UsdtAggregationTaskController extends BaseController {
public AjaxResult execute(@PathVariable("id") Long id, public AjaxResult execute(@PathVariable("id") Long id,
@RequestBody AggregationExecuteRequest request) { @RequestBody AggregationExecuteRequest request) {
try { try {
aggregationWorkflowService.executeTask(id, request.getConfigurationPassword(), false); aggregationWorkflowService.executeTask(id, request.getConfigurationPassword(), false, request.getResourceOnly());
return AjaxResult.success("归集任务执行完成"); return AjaxResult.success("归集任务执行完成");
} finally { } finally {
request.setConfigurationPassword(null); request.setConfigurationPassword(null);
@@ -57,7 +57,7 @@ public class UsdtAggregationTaskItemController extends BaseController {
public AjaxResult retry(@PathVariable("id") Long id, public AjaxResult retry(@PathVariable("id") Long id,
@RequestBody AggregationExecuteRequest request) { @RequestBody AggregationExecuteRequest request) {
try { try {
aggregationWorkflowService.retryItem(id, request.getConfigurationPassword(), false); aggregationWorkflowService.retryItem(id, request.getConfigurationPassword(), false, request.getResourceOnly());
return AjaxResult.success("归集明细重试完成"); return AjaxResult.success("归集明细重试完成");
} finally { } finally {
request.setConfigurationPassword(null); request.setConfigurationPassword(null);
@@ -1,4 +1,6 @@
package com.ruoyi.system.controller; package com.ruoyi.system.controller;
import com.ruoyi.system.chain.ChainExecutionRouter;
import com.ruoyi.system.chain.ChainExecutionPendingException;
import com.ruoyi.common.select.Ids; import com.ruoyi.common.select.Ids;
import com.ruoyi.common.select.SelectItem; import com.ruoyi.common.select.SelectItem;
import java.util.List; import java.util.List;
@@ -51,6 +53,8 @@ public class UsdtConfigController extends BaseController
private WalletOperationEstimateService walletOperationEstimateService; private WalletOperationEstimateService walletOperationEstimateService;
@Autowired @Autowired
private WalletSigningService walletSigningService; private WalletSigningService walletSigningService;
@Autowired
private ChainExecutionRouter chainExecutionRouter;
/** 实时查询主账号链上快照;主账号不写入 wallet_address。 */ /** 实时查询主账号链上快照;主账号不写入 wallet_address。 */
@PreAuthorize("@ss.hasPermi('system:usdtConfig:query')") @PreAuthorize("@ss.hasPermi('system:usdtConfig:query')")
@@ -84,12 +88,25 @@ public class UsdtConfigController extends BaseController
WalletAddressPlus wallet = walletAddressService.queryTronInfo(mainWallet()); WalletAddressPlus wallet = walletAddressService.queryTronInfo(mainWallet());
validateOperation(type, request); validateOperation(type, request);
try { try {
if (!Boolean.TRUE.equals(request.getBroadcast())) {
return AjaxResult.success("预演模式:未解密钱包、未广播交易");
}
if (Boolean.TRUE.equals(request.getResourceOnly())) { if (Boolean.TRUE.equals(request.getResourceOnly())) {
walletOperationEstimateService.requireNoBurn(type, wallet, request); walletOperationEstimateService.requireNoBurn(type, wallet, request);
} }
Object result = walletSigningService.execute(wallet, request.getConfigurationPassword(), String requestId = request.getExecutionRequestId();
(tron, api, current) -> executeOperation(type, tron, api, current, request)); if (chainExecutionRouter.isEnabled() && (requestId == null
return AjaxResult.success(result); || !requestId.matches("[a-zA-Z0-9-]{16,64}"))) {
throw new CustomException("请提供本次操作的唯一执行编号");
}
try {
Object result = chainExecutionRouter.execute(type, wallet, request,
"WALLET:" + getUserId() + ":" + requestId,
(tron, api, current) -> executeOperation(type, tron, api, current, request));
return AjaxResult.success(result);
} catch (ChainExecutionPendingException pending) {
return AjaxResult.success(pending.getMessage());
}
} finally { } finally {
request.setConfigurationPassword(null); request.setConfigurationPassword(null);
} }
@@ -86,7 +86,7 @@ public class UsdtPayoutOrderController extends BaseController {
@PostMapping("/{id}/execute") @PostMapping("/{id}/execute")
public AjaxResult execute(@PathVariable Long id, @RequestBody PayoutExecuteRequest request) { public AjaxResult execute(@PathVariable Long id, @RequestBody PayoutExecuteRequest request) {
try { try {
return AjaxResult.success(processingService.execute(id, request.getConfigurationPassword())); return AjaxResult.success(processingService.execute(id, request.getConfigurationPassword(), request.getResourceOnly()));
} finally { } finally {
request.setConfigurationPassword(null); request.setConfigurationPassword(null);
} }
@@ -1,5 +1,8 @@
package com.ruoyi.system.controller; package com.ruoyi.system.controller;
import com.ruoyi.system.chain.ChainExecutionRouter;
import com.ruoyi.system.chain.ChainExecutionPendingException;
import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
@@ -61,6 +64,8 @@ public class WalletAddressController extends BaseController {
@Autowired @Autowired
private WalletSigningService walletSigningService; private WalletSigningService walletSigningService;
@Autowired @Autowired
private ChainExecutionRouter chainExecutionRouter;
@Autowired
private WalletOperationEstimateService walletOperationEstimateService; private WalletOperationEstimateService walletOperationEstimateService;
@Autowired @Autowired
private IUsdtProxyToOtherService usdtProxyToOtherService; private IUsdtProxyToOtherService usdtProxyToOtherService;
@@ -222,8 +227,18 @@ public class WalletAddressController extends BaseController {
if (Boolean.TRUE.equals(request.getResourceOnly())) { if (Boolean.TRUE.equals(request.getResourceOnly())) {
walletOperationEstimateService.requireNoBurn(operationType, wallet, request); walletOperationEstimateService.requireNoBurn(operationType, wallet, request);
} }
Object result = walletSigningService.execute(wallet, request.getConfigurationPassword(), operation); String requestId = request.getExecutionRequestId();
return AjaxResult.success(result); if (chainExecutionRouter.isEnabled() && (requestId == null
|| !requestId.matches("[a-zA-Z0-9-]{16,64}"))) {
throw new com.ruoyi.common.exception.CustomException("请提供本次操作的唯一执行编号");
}
try {
Object result = chainExecutionRouter.execute(operationType, wallet, request,
"WALLET:" + getUserId() + ":" + requestId, operation);
return AjaxResult.success(result);
} catch (ChainExecutionPendingException pending) {
return AjaxResult.success(pending.getMessage());
}
} finally { } finally {
// 尽快解除请求对象对密码字符串的引用,且禁止在日志中输出整个请求对象。 // 尽快解除请求对象对密码字符串的引用,且禁止在日志中输出整个请求对象。
request.setConfigurationPassword(null); request.setConfigurationPassword(null);
@@ -2,6 +2,11 @@ package com.ruoyi.system.domain.dto;
/** 管理员执行代付时提交的配置密码。 */ /** 管理员执行代付时提交的配置密码。 */
public class PayoutExecuteRequest { public class PayoutExecuteRequest {
/** 页面明确选择资源模式;null保留旧客户端行为。 */
private Boolean resourceOnly;
public Boolean getResourceOnly() { return resourceOnly; }
public void setResourceOnly(Boolean value) { resourceOnly = value; }
@com.fasterxml.jackson.annotation.JsonProperty(access = com.fasterxml.jackson.annotation.JsonProperty.Access.WRITE_ONLY)
private String configurationPassword; private String configurationPassword;
public String getConfigurationPassword(){return configurationPassword;} public String getConfigurationPassword(){return configurationPassword;}
public void setConfigurationPassword(String value){configurationPassword=value;} public void setConfigurationPassword(String value){configurationPassword=value;}
@@ -6,6 +6,9 @@ import java.io.Serializable;
/** 归集执行请求,配置密码仅用于当前请求内解锁钱包。 */ /** 归集执行请求,配置密码仅用于当前请求内解锁钱包。 */
public class AggregationExecuteRequest implements Serializable { public class AggregationExecuteRequest implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Boolean resourceOnly;
public Boolean getResourceOnly() { return resourceOnly; }
public void setResourceOnly(Boolean value) { resourceOnly = value; }
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String configurationPassword; private String configurationPassword;
@@ -5,6 +5,10 @@ import java.math.BigDecimal;
/** 管理端钱包操作请求;私钥不允许从请求传入。 */ /** 管理端钱包操作请求;私钥不允许从请求传入。 */
public class WalletOperationRequest { public class WalletOperationRequest {
/** 页面为一次用户操作生成 UUID;超时重试必须复用,防止生成第二笔交易。 */
private String executionRequestId;
public String getExecutionRequestId() { return executionRequestId; }
public void setExecutionRequestId(String value) { executionRequestId = value; }
private Long walletId; private Long walletId;
private String toAddress; private String toAddress;
private BigDecimal amount; private BigDecimal amount;
@@ -1,5 +1,9 @@
package com.ruoyi.system.service; package com.ruoyi.system.service;
import com.ruoyi.system.chain.ChainExecutionRouter;
import com.ruoyi.system.chain.ChainExecutionPendingException;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.CustomException; import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.*; import com.ruoyi.system.domain.*;
@@ -42,11 +46,21 @@ public class PayoutProcessingService {
private TronServiceProvider tronProvider; private TronServiceProvider tronProvider;
@Autowired @Autowired
private TransactionTemplate transactionTemplate; private TransactionTemplate transactionTemplate;
@Autowired
private ChainExecutionRouter chainExecutionRouter;
@Autowired
private com.ruoyi.system.chain.ChainExecutionStore chainExecutionStore;
/** /**
* 配置密码仅用于本次内存解锁,广播成功后订单进入待链上确认状态。 * 配置密码仅用于本次内存解锁,广播成功后订单进入待链上确认状态。
*/ */
public String execute(Long id, String password) { public String execute(Long id, String password) {
return execute(id, password, null);
}
/** resourceOnly只影响本次明确选择的资源模式,旧调用方传null保持原行为。 */
public String execute(Long id, String password, Boolean resourceOnly) {
if (chainExecutionRouter.isEnabled()) chainExecutionRouter.requireChannel(password);
if (payoutMapper.claimForExecution(id, PayoutOrderService.PENDING_EXECUTE, if (payoutMapper.claimForExecution(id, PayoutOrderService.PENDING_EXECUTE,
PayoutOrderService.EXECUTE_FAILED, EXECUTING) != 1) { PayoutOrderService.EXECUTE_FAILED, EXECUTING) != 1) {
throw new CustomException("仅待执行或执行失败的订单可以广播,请勿重复操作"); throw new CustomException("仅待执行或执行失败的订单可以广播,请勿重复操作");
@@ -57,17 +71,28 @@ public class PayoutProcessingService {
WalletAddressPlus mainWallet = new WalletAddressPlus(); WalletAddressPlus mainWallet = new WalletAddressPlus();
mainWallet.setToken(config.getTokenAddress()); mainWallet.setToken(config.getTokenAddress());
mainWallet.setTokenIndex("0"); mainWallet.setTokenIndex("0");
String hash = signingService.execute(mainWallet, password, (tron, api, wallet) -> WalletOperationRequest operation = new WalletOperationRequest();
operation.setAmount(order.getAmount());
operation.setToAddress(order.getToAddress());
operation.setBroadcast(true);
operation.setResourceOnly(resourceOnly);
operation.setConfigurationPassword(password);
String hash = String.valueOf(chainExecutionRouter.execute("USDT".equals(order.getCurrency()) ? "usdt" : "trx",
mainWallet, operation, "PAYOUT:" + id, (tron, api, wallet) ->
"USDT".equals(order.getCurrency()) "USDT".equals(order.getCurrency())
? tron.usdtTransWithBroadcastRetry(api, wallet.getToken(), ? tron.usdtTransWithBroadcastRetry(api, wallet.getToken(),
order.getToAddress(), order.getAmount(), 3) order.getToAddress(), order.getAmount(), 3)
: tron.trxTrans(api, wallet.getToken(), order.getToAddress(), order.getAmount())); : tron.trxTrans(api, wallet.getToken(), order.getToAddress(), order.getAmount())));
transactionTemplate.execute(status -> { transactionTemplate.execute(status -> {
markBroadcasted(id, hash); markBroadcasted(id, hash);
return null; return null;
}); });
return hash; return hash;
} catch (Exception exception) { } catch (Exception exception) {
if (exception instanceof ChainExecutionPendingException) {
// 远程任务已持久化或交易已签名;保留 EXECUTING,后台负责同步结果。
return exception.getMessage();
}
transactionTemplate.execute(status -> { transactionTemplate.execute(status -> {
markFailed(id, safe(exception)); markFailed(id, safe(exception));
return null; return null;
@@ -80,6 +105,9 @@ public class PayoutProcessingService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void markBroadcasted(Long id, String hash) { public void markBroadcasted(Long id, String hash) {
UsdtPayoutOrderPlus o = payoutMapper.selectByIdForUpdate(id); UsdtPayoutOrderPlus o = payoutMapper.selectByIdForUpdate(id);
// 同步请求与后台结果同步可能同时到达,同一交易的重复同步视为成功。
if (o != null && Integer.valueOf(PayoutOrderService.BROADCASTED).equals(o.getStatus())
&& hash.equals(o.getBlockTransactionId())) return;
if (o == null || !Integer.valueOf(EXECUTING).equals(o.getStatus())) if (o == null || !Integer.valueOf(EXECUTING).equals(o.getStatus()))
throw new CustomException("代付订单状态已变化"); throw new CustomException("代付订单状态已变化");
o.setStatus(PayoutOrderService.BROADCASTED); o.setStatus(PayoutOrderService.BROADCASTED);
@@ -130,6 +158,10 @@ public class PayoutProcessingService {
o.setExecuteError(error); o.setExecuteError(error);
o.setUpdatedAt(new Date()); o.setUpdatedAt(new Date());
payoutMapper.updateById(o); payoutMapper.updateById(o);
if (chainExecutionRouter.isEnabled()) {
// 只有节点明确确认链上失败才允许归档原幂等记录,广播超时不能走这里。
chainExecutionStore.chainFailed("PAYOUT:" + id, o.getBlockTransactionId());
}
} }
return null; return null;
}); });
@@ -1,5 +1,10 @@
package com.ruoyi.system.service; package com.ruoyi.system.service;
import com.ruoyi.system.chain.ChainExecutionRouter;
import com.ruoyi.system.chain.ChainExecutionPendingException;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.CustomException; import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.DateUtils;
@@ -42,6 +47,14 @@ public class UsdtAggregationWorkflowService {
private final WalletSigningService walletSigningService; private final WalletSigningService walletSigningService;
private final WalletLedgerPostingService ledgerPostingService; private final WalletLedgerPostingService ledgerPostingService;
private final ApplicationEventPublisher eventPublisher; private final ApplicationEventPublisher eventPublisher;
@Autowired
private ChainExecutionRouter chainExecutionRouter;
@Autowired(required = false)
private com.ruoyi.system.chain.resource.ResourceRentalProperties resourceRentalProperties;
@Autowired(required = false)
private com.ruoyi.system.chain.resource.ResourceExecutionGate resourceExecutionGate;
@Autowired(required = false)
private com.ruoyi.system.mapper.UsdtConfigMapper resourceConfigMapper;
public UsdtAggregationWorkflowService(IAppsService appsService, public UsdtAggregationWorkflowService(IAppsService appsService,
IWalletAddressService walletService, IWalletAddressService walletService,
@@ -184,6 +197,10 @@ public class UsdtAggregationWorkflowService {
} }
public void executeTask(Long taskId, String password, boolean userMode) { public void executeTask(Long taskId, String password, boolean userMode) {
executeTask(taskId, password, userMode, null);
}
public void executeTask(Long taskId, String password, boolean userMode, Boolean resourceOnly) {
UsdtAggregationTaskPlus task = requireTask(taskId, userMode); UsdtAggregationTaskPlus task = requireTask(taskId, userMode);
if (Integer.valueOf(4).equals(task.getStatus())) { if (Integer.valueOf(4).equals(task.getStatus())) {
throw new CustomException("归集任务已关闭,不能执行"); throw new CustomException("归集任务已关闭,不能执行");
@@ -198,6 +215,25 @@ public class UsdtAggregationWorkflowService {
new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>() new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
.eq(UsdtAggregationTaskItemPlus::getParentId, taskId) .eq(UsdtAggregationTaskItemPlus::getParentId, taskId)
.in(UsdtAggregationTaskItemPlus::getStatus, 0L, 2L)); .in(UsdtAggregationTaskItemPlus::getStatus, 0L, 2L));
if (chainExecutionRouter.isEnabled()) {
chainExecutionRouter.requireChannel(password);
if (taskMapper.startExecutableTask(taskId) != 1) {
throw new CustomException("任务状态已变化,请刷新后重试");
}
taskService.update(new LambdaUpdateWrapper<UsdtAggregationTaskPlus>()
.eq(UsdtAggregationTaskPlus::getId, taskId).eq(UsdtAggregationTaskPlus::getStatus, 1)
.set(UsdtAggregationTaskPlus::getRemark, "正在分发链上执行任务"));
boolean failed = false;
for (UsdtAggregationTaskItemPlus item : items) {
if (!executeItemRouted(item, password, resourceOnly)) failed = true;
}
taskService.update(new LambdaUpdateWrapper<UsdtAggregationTaskPlus>()
.eq(UsdtAggregationTaskPlus::getId, taskId).eq(UsdtAggregationTaskPlus::getStatus, 1)
.set(UsdtAggregationTaskPlus::getRemark, "链上执行中"));
// 只要有远程执行中的明细,就保留主任务执行中,由结果同步任务最终关闭。
if (!hasRunningItems(taskId)) finishTask(task, failed);
return;
}
boolean failed = walletSigningService.executeUnlocked(password, session -> { boolean failed = walletSigningService.executeUnlocked(password, session -> {
if (taskMapper.startExecutableTask(taskId) != 1) { if (taskMapper.startExecutableTask(taskId) != 1) {
throw new CustomException("任务状态已变化,可能已关闭或正在执行,请刷新后重试"); throw new CustomException("任务状态已变化,可能已关闭或正在执行,请刷新后重试");
@@ -205,7 +241,7 @@ public class UsdtAggregationWorkflowService {
boolean hasFailure = false; boolean hasFailure = false;
for (UsdtAggregationTaskItemPlus item : items) { for (UsdtAggregationTaskItemPlus item : items) {
if (!executeItemInternal(item, session)) { if (!executeItemInternal(item, session, resourceOnly)) {
hasFailure = true; hasFailure = true;
} }
} }
@@ -215,6 +251,10 @@ public class UsdtAggregationWorkflowService {
} }
public void retryItem(Long itemId, String password, boolean userMode) { public void retryItem(Long itemId, String password, boolean userMode) {
retryItem(itemId, password, userMode, null);
}
public void retryItem(Long itemId, String password, boolean userMode, Boolean resourceOnly) {
UsdtAggregationTaskItemPlus item = itemService.getById(itemId); UsdtAggregationTaskItemPlus item = itemService.getById(itemId);
if (item == null) { if (item == null) {
throw new CustomException("归集明细不存在"); throw new CustomException("归集明细不存在");
@@ -229,7 +269,14 @@ public class UsdtAggregationWorkflowService {
if (!Long.valueOf(2L).equals(item.getStatus())) { if (!Long.valueOf(2L).equals(item.getStatus())) {
throw new CustomException("只有失败的归集明细可以手动重试"); throw new CustomException("只有失败的归集明细可以手动重试");
} }
walletSigningService.executeUnlocked(password, session -> executeItemInternal(item, session)); if (chainExecutionRouter.isEnabled()) {
chainExecutionRouter.requireChannel(password);
if (taskMapper.startExecutableTask(task.getId()) != 1) throw new CustomException("任务状态已变化");
executeItemRouted(item, password, resourceOnly);
if (hasRunningItems(task.getId())) return;
} else {
walletSigningService.executeUnlocked(password, session -> executeItemInternal(item, session, resourceOnly));
}
boolean remainsFailed = itemService.count(new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>() boolean remainsFailed = itemService.count(new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
.eq(UsdtAggregationTaskItemPlus::getParentId, task.getId()) .eq(UsdtAggregationTaskItemPlus::getParentId, task.getId())
.eq(UsdtAggregationTaskItemPlus::getStatus, 2L)) > 0; .eq(UsdtAggregationTaskItemPlus::getStatus, 2L)) > 0;
@@ -263,8 +310,41 @@ public class UsdtAggregationWorkflowService {
return item; return item;
} }
private boolean hasRunningItems(Long taskId) {
return itemService.count(new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
.eq(UsdtAggregationTaskItemPlus::getParentId, taskId)
.eq(UsdtAggregationTaskItemPlus::getStatus, 4L)) > 0;
}
/** 新通道按明细独立提交,失败不阻断后续地址;不确定结果始终保留执行占位。 */
private boolean executeItemRouted(UsdtAggregationTaskItemPlus item, String password, Boolean resourceOnly) {
if (itemMapper.claimItemForExecution(item.getId()) != 1) return false;
item.setStatus(4L);
try {
WalletAddressPlus wallet = walletService.getByTokenAndAppId(item.getTokenAddress(), item.getAppId());
if (wallet == null) throw new CustomException("钱包不存在或已不属于当前应用");
WalletOperationRequest request = new WalletOperationRequest();
request.setAmount(item.getOpeAmount());
request.setToAddress(item.getDistTokenAddress());
request.setBroadcast(true);
request.setResourceOnly(resourceOnly);
request.setConfigurationPassword(password);
String hash = String.valueOf(chainExecutionRouter.execute("usdt", wallet, request,
"AGGREGATION:" + item.getId(), (tron, api, current) ->
tron.usdtTransWithBroadcastRetry(api, current.getToken(),
item.getDistTokenAddress(), item.getOpeAmount(), MAX_ATTEMPTS)));
ledgerPostingService.completeAggregationItem(item, wallet, hash, "执行成功;交易哈希:" + hash);
return true;
} catch (ChainExecutionPendingException pending) {
return true;
} catch (Exception ex) {
markFailed(item, "执行前校验或签名失败,请检查执行记录");
return false;
}
}
private boolean executeItemInternal(UsdtAggregationTaskItemPlus item, private boolean executeItemInternal(UsdtAggregationTaskItemPlus item,
WalletSigningService.UnlockedWalletSession session) { WalletSigningService.UnlockedWalletSession session, Boolean resourceOnly) {
// 使用数据库状态而非列表快照决定是否允许广播,取消与执行只能有一方成功。 // 使用数据库状态而非列表快照决定是否允许广播,取消与执行只能有一方成功。
if (itemMapper.claimItemForExecution(item.getId()) != 1) { if (itemMapper.claimItemForExecution(item.getId()) != 1) {
UsdtAggregationTaskItem current = itemMapper.selectUsdtAggregationTaskItemById(item.getId()); UsdtAggregationTaskItem current = itemMapper.selectUsdtAggregationTaskItemById(item.getId());
@@ -278,9 +358,13 @@ public class UsdtAggregationWorkflowService {
markFailed(item, "钱包不存在或已不属于当前应用"); markFailed(item, "钱包不存在或已不属于当前应用");
return false; return false;
} }
// 旧本地解锁通道也复用严格复检;不改变未启用租赁时的转账行为。
com.ruoyi.system.chain.ChainCommand resourceCommand = resourceCommand(item, wallet);
if (resourceCommand != null && (Boolean.TRUE.equals(resourceOnly) || resourceExecutionGate.required(resourceCommand))) resourceExecutionGate.require(resourceCommand);
String tx = session.execute(wallet, (tron, api, current) -> String tx = session.execute(wallet, (tron, api, current) ->
tron.usdtTransWithBroadcastRetry(api, current.getToken(), tron.usdtTransWithBroadcastRetry(api, current.getToken(),
item.getDistTokenAddress(), item.getOpeAmount(), MAX_ATTEMPTS)); item.getDistTokenAddress(), item.getOpeAmount(), MAX_ATTEMPTS));
if (resourceCommand != null) resourceExecutionGate.transferred(resourceCommand.businessKey, tx);
String successRemark = "执行成功;同一签名交易最多广播 " + MAX_ATTEMPTS String successRemark = "执行成功;同一签名交易最多广播 " + MAX_ATTEMPTS
+ " 次;交易哈希:" + tx; + " 次;交易哈希:" + tx;
ledgerPostingService.completeAggregationItem(item, wallet, tx, successRemark); ledgerPostingService.completeAggregationItem(item, wallet, tx, successRemark);
@@ -299,6 +383,20 @@ public class UsdtAggregationWorkflowService {
itemService.updateById(item); itemService.updateById(item);
} }
/** 仅复制公开参数,不能把解锁会话或密码放入准备记录。 */
private com.ruoyi.system.chain.ChainCommand resourceCommand(UsdtAggregationTaskItemPlus item, WalletAddressPlus wallet) {
if (resourceRentalProperties == null || !resourceRentalProperties.isEnabled()) return null;
com.ruoyi.system.domain.UsdtConfig config = resourceConfigMapper.selectFirst();
com.ruoyi.system.chain.ChainCommand command = new com.ruoyi.system.chain.ChainCommand();
command.businessKey = "AGGREGATION:" + item.getId();
command.address = wallet.getToken(); command.walletId = wallet.getId(); command.type = "usdt";
command.tokenIndex = wallet.getTokenIndex();
command.network = config.getTronNetType(); command.envelopeVersion = config.getVersion();
command.operation = new WalletOperationRequest(); command.operation.setToAddress(item.getDistTokenAddress());
command.operation.setAmount(item.getOpeAmount());
return command;
}
private void finishTask(UsdtAggregationTaskPlus task, boolean failed) { private void finishTask(UsdtAggregationTaskPlus task, boolean failed) {
task.setStatus(failed ? 3 : 2); task.setStatus(failed ? 3 : 2);
task.setUpdatedAt(DateUtils.getNowDate()); task.setUpdatedAt(DateUtils.getNowDate());
@@ -95,7 +95,8 @@ public class WalletSigningService {
} catch (CustomException e) { } catch (CustomException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(),e); // 私钥客户端异常可能带有签名上下文,禁止输出原始异常消息和堆栈。
log.error("钱包解密或链上签名操作失败");
throw new CustomException("钱包解密或链上签名操作失败", e); throw new CustomException("钱包解密或链上签名操作失败", e);
} finally { } finally {
Arrays.fill(password, '\0'); Arrays.fill(password, '\0');
@@ -0,0 +1,198 @@
package com.ruoyi.system.chain;
import com.google.protobuf.ByteString;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.domain.vo.WalletResourceEstimateVo;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.TronServiceProvider;
import com.ruoyi.system.service.WalletOperationEstimateService;
import com.ruoyi.system.service.WalletSigningService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.proto.Chain;
import org.tron.trident.proto.Response;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import static org.junit.Assert.*;
/** 可控节点替身验证广播先持久化、同交易重播和重启恢复;没有真实 RPC 或真实私钥。 */
public class ChainCommandExecutorTest {
private ChainExecutionStore store;
private ChainCommandExecutor executor;
private TestApi api;
private String executionId;
private int signedCount;
private int broadcasts;
private boolean acceptBroadcast;
private byte[] firstTransaction;
@Before
public void setup() throws Exception {
store = new ChainExecutionStore(new DriverManagerDataSource("jdbc:h2:mem:engine" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", ""));
String schema = new String(Files.readAllBytes(Paths.get("../sql/chain_executor.sql")), StandardCharsets.UTF_8);
store.jdbc().execute(schema.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
api = new TestApi();
ITronService tron = (ITronService) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] {ITronService.class},
(proxy, method, args) -> {
if ("type".equals(method.getName())) return "nile";
if ("buildApiWrapper".equals(method.getName())) return api;
if ("getTRxBalance".equals(method.getName())) return new BigDecimal("100");
throw new UnsupportedOperationException(method.getName());
});
UsdtConfig config = new UsdtConfig();
config.setVersion(1L);
config.setTronNetType(0);
config.setTrxNum(BigDecimal.ONE);
config.setTokenAddress("test-main-wallet");
UsdtConfigMapper configs = (UsdtConfigMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] {UsdtConfigMapper.class}, (proxy, method, args) -> config);
TronServiceProvider networks = new TronServiceProvider(configs, null) {
@Override public ITronService getServiceForNetwork(String network) { return tron; }
};
WalletSigningService signing = new WalletSigningService() {
@Override public <T> T execute(WalletAddressPlus wallet, String password, SignedOperation<T> operation) {
try { return operation.execute(tron, api, wallet); }
catch (Exception ex) { throw new IllegalStateException(ex); }
}
};
WalletOperationEstimateService estimates = new WalletOperationEstimateService(networks) {
@Override public WalletResourceEstimateVo estimate(String type, WalletAddressPlus wallet, WalletOperationRequest request) {
WalletResourceEstimateVo estimate = new WalletResourceEstimateVo();
estimate.setEstimatedBurnTrx(BigDecimal.ZERO);
return estimate;
}
};
executor = new ChainCommandExecutor(store, signing, estimates, configs, networks);
executionId = (String) store.create(command(), true).get("execution_id");
}
@After public void cleanup() { if (api != null) api.close(); }
@Test
public void responseLossRetriesIdenticalTransactionAndRecoveryDoesNotResign() {
executor.execute(executionId, "test-only-password");
assertEquals(1, signedCount);
assertEquals(4, broadcasts);
assertEquals("SIGNED", store.get(executionId).get("status"));
// 模拟重启后节点恢复:从持久化记录重播,不再解锁钱包,不再次构造/签名。
acceptBroadcast = true;
executor.recover(store.get(executionId));
assertEquals(1, signedCount);
assertEquals(5, broadcasts);
assertEquals("BROADCASTED", store.get(executionId).get("status"));
executor.execute(executionId, "test-only-password");
assertEquals(1, signedCount);
assertEquals(5, broadcasts);
}
@Test
public void expiredQueueEntryDoesNotSignOrBroadcast() {
ChainCommand expired = command();
expired.businessKey = "WALLET:expired";
expired.validUntil = 1L;
String id = (String) store.create(expired, true).get("execution_id");
executor.execute(id, "test-only-password");
assertEquals(0, signedCount);
assertEquals(0, broadcasts);
assertEquals("FAILED", store.get(id).get("status"));
}
@Test
public void rentalWaitingLeavesRemoteQueuedWithoutSigning() throws Exception {
ChainCommand waiting = command();
waiting.businessKey = "WALLET:resource-wait";
waiting.rentalRequired = true;
executionId = (String) store.create(waiting, true).get("execution_id");
java.lang.reflect.Field gate = ChainCommandExecutor.class.getDeclaredField("resourceGate");
gate.setAccessible(true);
gate.set(executor, new com.ruoyi.system.chain.resource.ResourceExecutionGate(null, null) {
@Override public boolean ready(ChainCommand command) { return false; }
});
executor.execute(executionId, "test-only-password");
executor.execute(executionId, "test-only-password");
assertEquals("QUEUED", store.get(executionId).get("status"));
assertEquals(0, signedCount);
assertEquals(0, broadcasts);
}
@Test
public void passwordRequestDoesNotRemainQueuedWhenResourcesFallBack() throws Exception {
ChainCommand waiting = command();
waiting.businessKey = "WALLET:password-resource-wait";
waiting.rentalRequired = true;
executionId = (String) store.create(waiting, false).get("execution_id");
// 未注入gate也必须安全失败;密码没有后台副本,不能留成永久等待任务。
executor.execute(executionId, "test-only-password");
assertEquals("FAILED", store.get(executionId).get("status"));
assertEquals(0, signedCount);
assertEquals(0, broadcasts);
}
private ChainCommand command() {
ChainCommand command = new ChainCommand();
command.businessKey = "WALLET:test";
command.operatorId = 1L;
command.address = "test-main-wallet";
command.tokenIndex = "0";
command.network = 0;
command.envelopeVersion = 1L;
command.validUntil = System.currentTimeMillis() + 60_000L;
command.type = "trx";
command.operation = new WalletOperationRequest();
command.operation.setToAddress("test-target");
command.operation.setAmount(BigDecimal.ONE);
command.operation.setBroadcast(true);
return command;
}
private final class TestApi extends ApiWrapper {
TestApi() { super("127.0.0.1:1", "127.0.0.1:1", "0000000000000000000000000000000000000000000000000000000000000001"); }
@Override public Response.TransactionExtention transfer(String from, String to, long amount) {
Chain.Transaction transaction = Chain.Transaction.newBuilder().setRawData(
Chain.Transaction.raw.newBuilder().setExpiration(System.currentTimeMillis() + 60_000)
.addContract(Chain.Transaction.Contract.newBuilder()
.setType(Chain.Transaction.Contract.ContractType.TransferContract))).build();
return Response.TransactionExtention.newBuilder().setTransaction(transaction).build();
}
@Override public Chain.Transaction signTransaction(Chain.Transaction transaction) {
signedCount++;
return transaction.toBuilder().addSignature(ByteString.copyFromUtf8("test-signature")).build();
}
@Override public String broadcastTransaction(Chain.Transaction transaction) {
Map<String, Object> stored = store.get(executionId);
assertEquals("SIGNED", stored.get("status"));
assertArrayEquals(transaction.toByteArray(), (byte[]) stored.get("signed_transaction"));
if (firstTransaction == null) firstTransaction = transaction.toByteArray();
else assertArrayEquals(firstTransaction, transaction.toByteArray());
broadcasts++;
if (!acceptBroadcast) throw new IllegalStateException("simulated response loss");
return (String) stored.get("transaction_id");
}
@Override public Chain.Transaction getTransactionById(String hash, org.tron.trident.core.NodeType... nodes) {
throw new IllegalStateException("simulated query unavailable");
}
@Override public Response.ChainParameters getChainParameters() {
return Response.ChainParameters.newBuilder()
.addChainParameter(Response.ChainParameters.ChainParameter.newBuilder().setKey("getEnergyFee").setValue(100))
.addChainParameter(Response.ChainParameters.ChainParameter.newBuilder().setKey("getTransactionFee").setValue(1000)).build();
}
}
}
@@ -0,0 +1,130 @@
package com.ruoyi.system.chain;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.service.WalletSigningService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.*;
/** 双通道路由边界:关闭时完全兼容;离线不建任务;提交后禁止转为本地新交易。 */
public class ChainExecutionRouterTest {
private ChainExecutionStore store;
private ChainExecutionRouter router;
private boolean enabled = true;
private boolean ready = true;
private int localExecutions;
private int notifications;
@Before
public void setup() throws Exception {
store = new ChainExecutionStore(new DriverManagerDataSource("jdbc:h2:mem:router" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", ""));
String sql = new String(Files.readAllBytes(Paths.get("../sql/chain_executor.sql")), StandardCharsets.UTF_8);
store.jdbc().execute(sql.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
SysUser user = new SysUser();
user.setUserId(1L);
LoginUser login = new LoginUser();
login.setUser(user);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login, null));
UsdtConfig config = new UsdtConfig();
config.setVersion(1L);
config.setTronNetType(0);
UsdtConfigMapper configs = (UsdtConfigMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] {UsdtConfigMapper.class}, (proxy, method, args) -> config);
ChainExecutorClient client = new ChainExecutorClient() {
@Override public boolean isEnabled() { return enabled; }
@Override public boolean ready() { return ready; }
@Override public void notifyExecutor() { notifications++; /* 模拟通知响应丢失 */ }
};
WalletSigningService signing = new WalletSigningService() {
@Override public <T> T execute(WalletAddressPlus wallet, String password, SignedOperation<T> operation) {
localExecutions++;
try { return operation.execute(null, null, wallet); }
catch (Exception ex) { throw new IllegalStateException(ex); }
}
@Override public void validateConfigurationPassword(String password) { }
};
ChainCommandExecutor executor = new ChainCommandExecutor(store, signing, null, configs, null) {
@Override public void execute(String id, String password) { localExecutions++; }
};
router = new ChainExecutionRouter(client, store, executor, signing, configs);
}
@After public void clearContext() { SecurityContextHolder.clearContext(); }
@Test
public void disabledFeatureUsesOriginalPasswordCallbackWithoutNewTable() {
enabled = false;
store.jdbc().execute("drop table usdt_chain_execution");
assertEquals("legacy-result", router.execute("trx", wallet(), request("password"), "WALLET:test",
(tron, api, wallet) -> "legacy-result"));
assertEquals(1, localExecutions);
assertEquals(0, notifications);
}
@Test
public void offlineBeforeSubmissionRequiresPasswordAndCreatesNoExecution() {
ready = false;
try {
router.execute("trx", wallet(), request(null), "WALLET:test", null);
fail("离线不得创建远程任务");
} catch (CustomException expected) {
assertFalse(expected instanceof ChainExecutionPendingException);
}
assertNull(store.byBusinessKey("WALLET:test"));
assertEquals(0, localExecutions);
}
@Test
public void remotePendingDoesNotFallbackEvenWhenUserSubmitsPassword() {
expectPending(request(null));
String original = (String) store.byBusinessKey("WALLET:test").get("execution_id");
ready = false;
expectPending(request("password"));
assertEquals(original, store.byBusinessKey("WALLET:test").get("execution_id"));
assertEquals(0, localExecutions);
WalletOperationRequest changed = request("password");
changed.setAmount(BigDecimal.TEN);
try { router.execute("trx", wallet(), changed, "WALLET:test", null); fail("同编号不能改变金额"); }
catch (CustomException expected) { assertFalse(expected instanceof ChainExecutionPendingException); }
assertEquals(0, localExecutions);
}
private void expectPending(WalletOperationRequest request) {
try { router.execute("trx", wallet(), request, "WALLET:test", null); fail("应查询原任务"); }
catch (ChainExecutionPendingException expected) { /* 正确保留执行占位 */ }
}
private WalletOperationRequest request(String password) {
WalletOperationRequest request = new WalletOperationRequest();
request.setAmount(BigDecimal.ONE);
request.setToAddress("test-target");
request.setBroadcast(true);
request.setConfigurationPassword(password);
return request;
}
private WalletAddressPlus wallet() {
WalletAddressPlus wallet = new WalletAddressPlus();
wallet.setToken("test-main");
wallet.setTokenIndex("0");
return wallet;
}
}
@@ -0,0 +1,117 @@
package com.ruoyi.system.chain;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.*;
/** 隔离 H2 集成测试:使用实际增量脚本,覆盖唯一约束、抢占和签名后失败保护。 */
public class ChainExecutionStoreTest {
private ChainExecutionStore store;
@Before
public void setup() throws Exception {
DriverManagerDataSource data = new DriverManagerDataSource("jdbc:h2:mem:" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", "");
store = new ChainExecutionStore(data);
String sql = new String(Files.readAllBytes(Paths.get("../sql/chain_executor.sql")), StandardCharsets.UTF_8);
// H2 不支持 MySQL 表级 COMMENT=;仅去除存储引擎/字符集/表备注,保留全部列与索引。
store.jdbc().execute(sql.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
}
@Test
public void concurrentDeliveryCreatesAndClaimsOnlyOneExecution() throws Exception {
ExecutorService threads = Executors.newFixedThreadPool(8);
try {
List<Callable<String>> attempts = new ArrayList<>();
for (int i = 0; i < 16; i++) attempts.add(() -> (String) store.create(command(), true).get("execution_id"));
List<Future<String>> results = threads.invokeAll(attempts);
String id = results.get(0).get();
for (Future<String> result : results) assertEquals(id, result.get());
List<Callable<Boolean>> claims = new ArrayList<>();
for (int i = 0; i < 16; i++) claims.add(() -> store.claim(id));
int winners = 0;
for (Future<Boolean> result : threads.invokeAll(claims)) if (result.get()) winners++;
assertEquals(1, winners);
} finally {
threads.shutdownNow();
}
}
@Test
public void signedTransactionCannotBecomeRetryableFailure() {
String id = (String) store.create(command(), true).get("execution_id");
assertTrue(store.claim(id));
byte[] signed = new byte[] {1, 2, 3};
store.signed(id, "fixed-transaction-hash", signed);
store.failBeforeSigning(id);
store.archiveFailure(command().businessKey);
assertEquals("SIGNED", store.get(id).get("status"));
assertArrayEquals(signed, (byte[]) store.get(id).get("signed_transaction"));
assertEquals(id, store.byBusinessKey(command().businessKey).get("execution_id"));
assertFalse(store.claim(id));
store.broadcasted(id);
store.failBeforeSigning(id);
assertEquals("BROADCASTED", store.get(id).get("status"));
}
@Test
public void failureBeforeSigningCanBeArchivedWithoutLosingAudit() {
String id = (String) store.create(command(), false).get("execution_id");
store.claim(id);
store.failBeforeSigning(id);
store.archiveFailure(command().businessKey);
String next = (String) store.create(command(), true).get("execution_id");
assertNotEquals(id, next);
assertEquals("FAILED", store.get(id).get("status"));
assertEquals(1, ((Number) store.get(id).get("reconciled")).intValue());
}
@Test
public void passwordIsNeverPersistedEvenIfCallerSetsIt() {
ChainCommand command = command();
command.operation.setConfigurationPassword("never-persist-this-password");
Map<String, Object> row = store.create(command, true);
assertFalse(((String) row.get("command_json")).contains("never-persist"));
}
@Test
public void onlyConfirmedFailureOfSameHashAllowsPayoutRetry() {
String id = (String) store.create(command(), true).get("execution_id");
store.claim(id);
store.signed(id, "known-hash", new byte[] {1});
store.broadcasted(id);
store.chainFailed(command().businessKey, "other-hash");
assertEquals("BROADCASTED", store.get(id).get("status"));
store.chainFailed(command().businessKey, "known-hash");
assertEquals("CHAIN_FAILED", store.get(id).get("status"));
store.archiveFailure(command().businessKey);
assertNotEquals(id, store.create(command(), false).get("execution_id"));
assertEquals("known-hash", store.get(id).get("transaction_id"));
}
private ChainCommand command() {
ChainCommand command = new ChainCommand();
command.businessKey = "PAYOUT:123";
command.operatorId = 1L;
command.type = "usdt";
command.operation = new WalletOperationRequest();
command.operation.setAmount(new BigDecimal("1.000001"));
command.operation.setBroadcast(true);
return command;
}
}
@@ -0,0 +1,89 @@
package com.ruoyi.system.chain.resource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.rental.RentalCrypto;
import okhttp3.FormBody;
import okhttp3.Request;
import okio.Buffer;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.*;
/** 使用内存HTTP替身检查两种不同认证/编码协议,绝不访问租赁平台。 */
public class ResourceRentalProviderTest {
private final ObjectMapper json = new ObjectMapper();
@Test
public void duiyaUsesResourceOrdersAndDocumentedAuthentication() throws Exception {
FakeHttp http = new FakeHttp();
DuiyaResourceRentalProvider adapter = new DuiyaResourceRentalProvider(http);
Map<String, Object> config = config("https://weidubot.cc/api/v2");
ResourceRentalProvider.Quote quote = adapter.quote(config, "MAINNET", "receiver", "BANDWIDTH", 500);
assertEquals("net", http.request.url().queryParameter("type"));
assertEquals("/api/v2/query_price", http.request.url().encodedPath());
String timestamp = http.request.header("x-timestamp");
assertEquals(ResourceProviderHttp.hmac("test-secret", "test-key" + timestamp), http.request.header("x-signature"));
http.payload = "{\"code\":1,\"data\":{\"order_sn\":\"net-order\"}}";
assertEquals("net-order", adapter.create(config, "local-id", quote).orderNo);
assertEquals("/api/v2/buy_net", http.request.url().encodedPath());
FormBody form = (FormBody) http.request.body();
assertEquals("count", form.name(0));
assertEquals("500", form.value(0));
assertEquals("address", form.name(2));
assertEquals("receiver", form.value(2));
}
@Test
public void internalUsesStableMerchantNumberAndSignsExactJson() throws Exception {
FakeHttp http = new FakeHttp();
http.payload = "{\"code\":200,\"data\":{\"amount\":\"1.2\"}}";
InternalResourceRentalProvider adapter = new InternalResourceRentalProvider(http);
Map<String, Object> config = config("https://rental.example.invalid");
ResourceRentalProvider.Quote quote = adapter.quote(config, "NILE", "receiver", "ENERGY", 60000);
http.payload = "{\"code\":200,\"data\":{\"order_no\":\"internal-order\",\"status\":\"PENDING\"}}";
adapter.create(config, "fixed-id", quote);
Buffer buffer = new Buffer(); http.request.body().writeTo(buffer);
String body = buffer.readUtf8();
Map<String, Object> request = json.readValue(body, new TypeReference<Map<String, Object>>() { });
assertEquals("fixed-id", request.get("merchant_order_no"));
assertFalse(request.containsKey("package_id"));
assertEquals("NILE", request.get("network"));
assertEquals("1.2", request.get("expected_amount"));
assertEquals(RentalCrypto.sign("test-secret", "API", "test-key",
Long.parseLong(http.request.header("X-Rent-Timestamp")), http.request.header("X-Rent-Nonce"),
"POST", "/api/rental/v1/create", body), http.request.header("X-Rent-Signature"));
}
@Test
public void duiyaRejectsBusinessErrorEvenIfHttpSuccess() {
FakeHttp http = new FakeHttp();
http.payload = "{\"code\":0,\"data\":{\"amount\":\"1.2\"}}";
try {
new DuiyaResourceRentalProvider(http).quote(config("https://example.invalid"), "MAINNET", "receiver", "ENERGY", 30000);
fail("business error must not become a usable quote");
} catch (com.ruoyi.common.exception.CustomException expected) { }
}
private Map<String, Object> config(String url) {
Map<String, Object> config = new LinkedHashMap<>();
config.put("base_url", url); config.put("energy_period", "1h");
config.put("bandwidth_period", "1day"); config.put("duration_seconds", 3600);
return config;
}
private class FakeHttp extends ResourceProviderHttp {
Request request;
String payload = "{\"code\":1,\"data\":{\"amount\":\"1.2\"}}";
FakeHttp() { super(null); }
public String key(Map<String, Object> config) { return "test-key"; }
public String secret(Map<String, Object> config) { return "test-secret"; }
public Map<String, Object> send(Request value) {
request = value;
try { return json.readValue(payload, new TypeReference<Map<String, Object>>() { }); }
catch (Exception impossible) { throw new IllegalStateException(impossible); }
}
}
}
@@ -0,0 +1,192 @@
package com.ruoyi.system.chain.resource;
import com.ruoyi.system.chain.ChainCommand;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
/**
* 实际增量SQL + H2事务隔离测试。平台和链上查询均为可控替身,不访问外网、不付费、不签名。
* 特别覆盖“租赁受理成功并不等于到账”以及并发/超时不能重复付费的行为契约。
*/
public class ResourceRentalServiceTest {
private ResourceLeaseStore store;
private ResourceRentalService service;
private FakeProbe probe;
private FakeProvider provider;
private ChainCommand command;
@Before
public void setup() throws Exception {
DriverManagerDataSource data = new DriverManagerDataSource("jdbc:h2:mem:resource" + System.nanoTime()
+ ";MODE=MySQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1", "sa", "");
DataSourceTransactionManager manager = new DataSourceTransactionManager(data);
store = new ResourceLeaseStore(data, manager);
for (String file : Arrays.asList("resource_rental.sql", "chain_executor.sql")) {
String sql = new String(Files.readAllBytes(Paths.get("../sql/" + file)), StandardCharsets.UTF_8);
store.jdbc().execute(sql.replaceAll("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='[^']*'", ""));
}
store.jdbc().update("insert into usdt_resource_rental_config(provider_code,network,base_url,api_key_cipher,api_secret_cipher,currency) values('INTERNAL','NILE','https://example.invalid','cipher','cipher','USDT')");
command = command("PAYOUT:1", "sender");
probe = new FakeProbe();
provider = new FakeProvider();
service = new ResourceRentalService(new ResourceRentalProperties() {
public boolean isEnabled() { return true; }
public String getProvider() { return "INTERNAL"; }
public int getTimeoutSeconds() { return 300; }
}, store, probe, Collections.singletonList(provider), manager);
ResourceBusinessResolver resolver = new ResourceBusinessResolver(store, null) {
public List<ChainCommand> resolve(String kind, Long id) {
return Collections.singletonList(command(kind + ":" + id, "sender"));
}
public void validateQueued(ChainCommand ignored) { }
};
Field field = ResourceRentalService.class.getDeclaredField("businessResolver");
field.setAccessible(true);
field.set(service, resolver);
}
@Test
public void previewNeverBuysAndBothResourcesMustArrive() {
service.preview(command);
assertEquals(0, provider.creates.get());
service.prepare(command, new BigDecimal("2"));
assertEquals(2, provider.creates.get());
assertEquals("WAITING", preparation().get("stage"));
probe.energy = 100;
service.check(preparation());
assertEquals("WAITING", preparation().get("stage"));
probe.bandwidth = 100;
service.check(preparation());
assertEquals("READY", preparation().get("stage"));
assertTrue(new ResourceExecutionGate(store, probe).ready(command));
probe.energy = 0;
assertFalse(new ResourceExecutionGate(store, probe).ready(command));
assertEquals(2, provider.creates.get());
}
@Test
public void concurrentPreparePaysOncePerResource() throws Exception {
ExecutorService threads = Executors.newFixedThreadPool(8);
try {
List<Callable<Void>> calls = new ArrayList<>();
for (int i = 0; i < 16; i++) calls.add(() -> { service.prepare(command, new BigDecimal("2")); return null; });
for (Future<Void> call : threads.invokeAll(calls)) call.get();
assertEquals(2, provider.creates.get());
assertEquals(2, service.orders(preparation()).size());
} finally { threads.shutdownNow(); }
}
@Test
public void unknownCreateResultBlocksEvenWhenResourcesLaterAppear() {
provider.uncertain = true;
service.prepare(command, new BigDecimal("2"));
probe.energy = 100; probe.bandwidth = 100;
service.prepare(command, new BigDecimal("2"));
service.preview(command);
service.resume(command);
assertEquals("REVIEW", preparation().get("stage"));
assertFalse(new ResourceExecutionGate(store, probe).ready(command));
assertEquals(2, provider.creates.get());
}
@Test
public void timeoutResumeAndConfigSwitchReuseOriginalOrders() {
service.prepare(command, new BigDecimal("2"));
store.jdbc().update("update usdt_resource_rental_config set enabled=0");
store.jdbc().update("update usdt_resource_preparation set deadline_at=?", new Timestamp(1));
service.check(preparation());
assertEquals("TIMEOUT", preparation().get("stage"));
probe.energy = 100; probe.bandwidth = 100;
service.resume(command);
assertEquals("READY", preparation().get("stage"));
service.preview(command);
assertEquals(2, provider.creates.get());
}
@Test
public void rpcFailureAndFeeLimitNeverCreatePaidOrder() {
probe.unavailable = true;
try { service.prepare(command, BigDecimal.TEN); fail(); } catch (IllegalStateException expected) { }
probe.unavailable = false;
try { service.prepare(command, BigDecimal.ONE); fail(); } catch (RuntimeException expected) { }
assertEquals(0, provider.creates.get());
assertTrue(service.orders(preparation()).isEmpty());
}
@Test
public void addressIsExclusiveAndPublicViewContainsNoCommandOrRequests() {
service.prepare(command, new BigDecimal("2"));
ChainCommand other = command("PAYOUT:2", "sender");
service.prepare(other, new BigDecimal("2"));
assertEquals("ADDRESS_BUSY", store.byBusiness(other.businessKey).get("stage"));
assertEquals(2, provider.creates.get());
Map<String, Object> view = service.view(preparation());
assertFalse(view.containsKey("command_json"));
for (Map<String, Object> row : service.orders(preparation())) assertNotNull(row.get("request_json"));
assertFalse(store.encode(view).contains("request_json"));
}
@Test
public void abandonedSubmittingIsNeverResent() {
service.prepare(command, new BigDecimal("2"));
provider.uncertain = true;
store.jdbc().update("update usdt_resource_rental_order set status='SUBMITTING',updated_at=?", new Timestamp(1));
service.check(preparation());
assertEquals("REVIEW", preparation().get("stage"));
service.prepare(command, new BigDecimal("2"));
assertEquals(2, provider.creates.get());
}
private Map<String, Object> preparation() { return store.byBusiness(command.businessKey); }
private ChainCommand command(String key, String address) {
ChainCommand value = new ChainCommand();
value.businessKey = key; value.address = address; value.tokenIndex = "0";
value.network = 0; value.envelopeVersion = 1L; value.type = "usdt";
value.operation = new WalletOperationRequest();
value.operation.setToAddress("receiver"); value.operation.setAmount(BigDecimal.ONE);
return value;
}
private static class FakeProbe extends ResourceProbe {
volatile long energy, bandwidth;
volatile boolean unavailable;
FakeProbe() { super(null); }
public Observation inspect(ChainCommand ignored) {
if (unavailable) throw new IllegalStateException("mock RPC unavailable");
Observation value = new Observation();
value.requiredEnergy = 100; value.requiredBandwidth = 100;
value.availableEnergy = energy; value.availableBandwidth = bandwidth;
return value;
}
}
private static class FakeProvider implements ResourceRentalProvider {
final AtomicInteger creates = new AtomicInteger();
volatile boolean uncertain;
public String code() { return "INTERNAL"; }
public Quote quote(Map<String, Object> config, String network, String address, String resource, long quantity) {
Quote value = new Quote(); value.quantity = quantity; value.amount = BigDecimal.ONE;
value.currency = "USDT"; value.request = Collections.singletonMap("receiver_address", address);
return value;
}
public Submission create(Map<String, Object> config, String key, Quote quote) {
creates.incrementAndGet();
if (uncertain) throw new IllegalStateException("mock response lost after purchase");
return new Submission(key, "PENDING");
}
public String query(Map<String, Object> config, String key, String order) { return uncertain ? "UNKNOWN" : "SUCCESS"; }
}
}
+19
View File
@@ -0,0 +1,19 @@
-- 增量脚本:不修改、清空或重建任何已有业务表。支付后端和执行服务共用此表。
CREATE TABLE IF NOT EXISTS usdt_chain_execution (
execution_id VARCHAR(36) NOT NULL COMMENT '全局执行编号',
business_key VARCHAR(128) NOT NULL COMMENT '当前业务幂等键;签名前明确失败后可归档为执行编号',
operator_id BIGINT NOT NULL COMMENT '提交操作的管理员',
execution_mode VARCHAR(16) NOT NULL COMMENT 'REMOTE 或 PASSWORD',
command_json TEXT NOT NULL COMMENT '公开业务参数;禁止保存密码、助记词或私钥',
status VARCHAR(16) NOT NULL COMMENT 'QUEUED/RUNNING/SIGNED/BROADCASTED/FAILED/CHAIN_FAILED',
transaction_id VARCHAR(128) DEFAULT NULL,
signed_transaction MEDIUMBLOB COMMENT '受控签名交易;只用于同一交易重播,不对外返回',
error_message VARCHAR(255) DEFAULT NULL COMMENT '固定脱敏错误',
reconciled TINYINT NOT NULL DEFAULT 0 COMMENT '业务结果是否已同步',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (execution_id),
UNIQUE KEY uk_chain_business (business_key),
KEY idx_chain_recovery (status,execution_mode,created_at),
KEY idx_chain_operator (operator_id,created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='双通道链上执行记录';
+68
View File
@@ -0,0 +1,68 @@
-- 资源租赁增量表。先执行本脚本再启用 usdt.resource-rental.enabled;不改写旧订单及钱包。
CREATE TABLE IF NOT EXISTS usdt_resource_rental_config (
id BIGINT NOT NULL AUTO_INCREMENT,
provider_code VARCHAR(16) NOT NULL,
network VARCHAR(16) NOT NULL,
base_url VARCHAR(255) NOT NULL,
api_key_cipher TEXT NOT NULL COMMENT 'AES-GCM密文,由配置管理接口写入',
api_secret_cipher TEXT NOT NULL,
energy_period VARCHAR(32) NOT NULL DEFAULT '1h',
bandwidth_period VARCHAR(32) NOT NULL DEFAULT '1day',
duration_seconds BIGINT NOT NULL DEFAULT 3600,
energy_step BIGINT NOT NULL DEFAULT 30000,
bandwidth_step BIGINT NOT NULL DEFAULT 100,
max_order_cost DECIMAL(20,6) NOT NULL DEFAULT 10,
max_execution_cost DECIMAL(20,6) NOT NULL DEFAULT 20,
currency VARCHAR(8) NOT NULL,
enabled TINYINT NOT NULL DEFAULT 1,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id), KEY idx_resource_profile(provider_code,network,enabled,id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='支付资源平台连接配置;凭证禁止明文';
CREATE TABLE IF NOT EXISTS usdt_resource_preparation (
id VARCHAR(36) NOT NULL,
business_key VARCHAR(128) NOT NULL,
network VARCHAR(16) NOT NULL,
address VARCHAR(64) NOT NULL,
command_json TEXT NOT NULL COMMENT '公开业务参数,不含密码或私钥',
stage VARCHAR(24) NOT NULL DEFAULT 'CHECKING',
rental_authorized TINYINT NOT NULL DEFAULT 0,
required_energy BIGINT NOT NULL DEFAULT 0,
required_bandwidth BIGINT NOT NULL DEFAULT 0,
available_energy BIGINT NOT NULL DEFAULT 0,
available_bandwidth BIGINT NOT NULL DEFAULT 0,
checked_at TIMESTAMP NULL,
deadline_at TIMESTAMP NULL,
transaction_id VARCHAR(128) NULL,
error_message VARCHAR(255) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id), UNIQUE KEY uk_resource_business(business_key),
KEY idx_resource_wait(stage,updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='人工/自动资源准备,独立于转账授权';
CREATE TABLE IF NOT EXISTS usdt_resource_rental_order (
id VARCHAR(36) NOT NULL,
preparation_id VARCHAR(36) NOT NULL,
resource_type VARCHAR(16) NOT NULL,
config_id BIGINT NOT NULL,
quantity BIGINT NOT NULL,
request_json TEXT NOT NULL COMMENT '固化下单参数,幂等重放禁止改变',
quote_amount DECIMAL(20,6) NOT NULL,
currency VARCHAR(8) NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'CREATED',
provider_order_no VARCHAR(128) NULL,
provider_status VARCHAR(64) NULL,
error_message VARCHAR(255) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id), UNIQUE KEY uk_resource_once(preparation_id,resource_type),
KEY idx_resource_order_status(status,updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='一次准备每类资源只下单一次,未知结果禁止重下';
CREATE TABLE IF NOT EXISTS usdt_resource_address_guard (
network VARCHAR(16) NOT NULL,
address VARCHAR(64) NOT NULL,
owner_id VARCHAR(36) NULL,
PRIMARY KEY(network,address)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='跨实例同发送钱包资源协调,不按时间自动释放已签名占用';
+14
View File
@@ -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
+24
View File
@@ -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");
}
}
}
}
@@ -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(); }
}
}