接入租赁平台

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

@@ -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,
@RequestBody AggregationExecuteRequest request) {
try {
aggregationWorkflowService.executeTask(id, request.getConfigurationPassword(), false);
aggregationWorkflowService.executeTask(id, request.getConfigurationPassword(), false, request.getResourceOnly());
return AjaxResult.success("归集任务执行完成");
} finally {
request.setConfigurationPassword(null);
@@ -57,7 +57,7 @@ public class UsdtAggregationTaskItemController extends BaseController {
public AjaxResult retry(@PathVariable("id") Long id,
@RequestBody AggregationExecuteRequest request) {
try {
aggregationWorkflowService.retryItem(id, request.getConfigurationPassword(), false);
aggregationWorkflowService.retryItem(id, request.getConfigurationPassword(), false, request.getResourceOnly());
return AjaxResult.success("归集明细重试完成");
} finally {
request.setConfigurationPassword(null);
@@ -1,4 +1,6 @@
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.SelectItem;
import java.util.List;
@@ -51,6 +53,8 @@ public class UsdtConfigController extends BaseController
private WalletOperationEstimateService walletOperationEstimateService;
@Autowired
private WalletSigningService walletSigningService;
@Autowired
private ChainExecutionRouter chainExecutionRouter;
/** 实时查询主账号链上快照;主账号不写入 wallet_address。 */
@PreAuthorize("@ss.hasPermi('system:usdtConfig:query')")
@@ -84,12 +88,25 @@ public class UsdtConfigController extends BaseController
WalletAddressPlus wallet = walletAddressService.queryTronInfo(mainWallet());
validateOperation(type, request);
try {
if (!Boolean.TRUE.equals(request.getBroadcast())) {
return AjaxResult.success("预演模式:未解密钱包、未广播交易");
}
if (Boolean.TRUE.equals(request.getResourceOnly())) {
walletOperationEstimateService.requireNoBurn(type, wallet, request);
}
Object result = walletSigningService.execute(wallet, request.getConfigurationPassword(),
(tron, api, current) -> executeOperation(type, tron, api, current, request));
return AjaxResult.success(result);
String requestId = request.getExecutionRequestId();
if (chainExecutionRouter.isEnabled() && (requestId == null
|| !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 {
request.setConfigurationPassword(null);
}
@@ -86,7 +86,7 @@ public class UsdtPayoutOrderController extends BaseController {
@PostMapping("/{id}/execute")
public AjaxResult execute(@PathVariable Long id, @RequestBody PayoutExecuteRequest request) {
try {
return AjaxResult.success(processingService.execute(id, request.getConfigurationPassword()));
return AjaxResult.success(processingService.execute(id, request.getConfigurationPassword(), request.getResourceOnly()));
} finally {
request.setConfigurationPassword(null);
}
@@ -1,5 +1,8 @@
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.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
@@ -61,6 +64,8 @@ public class WalletAddressController extends BaseController {
@Autowired
private WalletSigningService walletSigningService;
@Autowired
private ChainExecutionRouter chainExecutionRouter;
@Autowired
private WalletOperationEstimateService walletOperationEstimateService;
@Autowired
private IUsdtProxyToOtherService usdtProxyToOtherService;
@@ -222,8 +227,18 @@ public class WalletAddressController extends BaseController {
if (Boolean.TRUE.equals(request.getResourceOnly())) {
walletOperationEstimateService.requireNoBurn(operationType, wallet, request);
}
Object result = walletSigningService.execute(wallet, request.getConfigurationPassword(), operation);
return AjaxResult.success(result);
String requestId = request.getExecutionRequestId();
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 {
// 尽快解除请求对象对密码字符串的引用,且禁止在日志中输出整个请求对象。
request.setConfigurationPassword(null);
@@ -2,6 +2,11 @@ package com.ruoyi.system.domain.dto;
/** 管理员执行代付时提交的配置密码。 */
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;
public String getConfigurationPassword(){return configurationPassword;}
public void setConfigurationPassword(String value){configurationPassword=value;}
@@ -6,6 +6,9 @@ import java.io.Serializable;
/** 归集执行请求,配置密码仅用于当前请求内解锁钱包。 */
public class AggregationExecuteRequest implements Serializable {
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)
private String configurationPassword;
@@ -5,6 +5,10 @@ import java.math.BigDecimal;
/** 管理端钱包操作请求;私钥不允许从请求传入。 */
public class WalletOperationRequest {
/** 页面为一次用户操作生成 UUID;超时重试必须复用,防止生成第二笔交易。 */
private String executionRequestId;
public String getExecutionRequestId() { return executionRequestId; }
public void setExecutionRequestId(String value) { executionRequestId = value; }
private Long walletId;
private String toAddress;
private BigDecimal amount;
@@ -1,5 +1,9 @@
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.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.*;
@@ -42,11 +46,21 @@ public class PayoutProcessingService {
private TronServiceProvider tronProvider;
@Autowired
private TransactionTemplate transactionTemplate;
@Autowired
private ChainExecutionRouter chainExecutionRouter;
@Autowired
private com.ruoyi.system.chain.ChainExecutionStore chainExecutionStore;
/**
* 配置密码仅用于本次内存解锁,广播成功后订单进入待链上确认状态。
*/
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,
PayoutOrderService.EXECUTE_FAILED, EXECUTING) != 1) {
throw new CustomException("仅待执行或执行失败的订单可以广播,请勿重复操作");
@@ -57,17 +71,28 @@ public class PayoutProcessingService {
WalletAddressPlus mainWallet = new WalletAddressPlus();
mainWallet.setToken(config.getTokenAddress());
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())
? tron.usdtTransWithBroadcastRetry(api, wallet.getToken(),
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 -> {
markBroadcasted(id, hash);
return null;
});
return hash;
} catch (Exception exception) {
if (exception instanceof ChainExecutionPendingException) {
// 远程任务已持久化或交易已签名;保留 EXECUTING,后台负责同步结果。
return exception.getMessage();
}
transactionTemplate.execute(status -> {
markFailed(id, safe(exception));
return null;
@@ -80,6 +105,9 @@ public class PayoutProcessingService {
@Transactional(rollbackFor = Exception.class)
public void markBroadcasted(Long id, String hash) {
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()))
throw new CustomException("代付订单状态已变化");
o.setStatus(PayoutOrderService.BROADCASTED);
@@ -130,6 +158,10 @@ public class PayoutProcessingService {
o.setExecuteError(error);
o.setUpdatedAt(new Date());
payoutMapper.updateById(o);
if (chainExecutionRouter.isEnabled()) {
// 只有节点明确确认链上失败才允许归档原幂等记录,广播超时不能走这里。
chainExecutionStore.chainFailed("PAYOUT:" + id, o.getBlockTransactionId());
}
}
return null;
});
@@ -1,5 +1,10 @@
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.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
@@ -42,6 +47,14 @@ public class UsdtAggregationWorkflowService {
private final WalletSigningService walletSigningService;
private final WalletLedgerPostingService ledgerPostingService;
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,
IWalletAddressService walletService,
@@ -184,6 +197,10 @@ public class UsdtAggregationWorkflowService {
}
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);
if (Integer.valueOf(4).equals(task.getStatus())) {
throw new CustomException("归集任务已关闭,不能执行");
@@ -198,6 +215,25 @@ public class UsdtAggregationWorkflowService {
new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
.eq(UsdtAggregationTaskItemPlus::getParentId, taskId)
.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 -> {
if (taskMapper.startExecutableTask(taskId) != 1) {
throw new CustomException("任务状态已变化,可能已关闭或正在执行,请刷新后重试");
@@ -205,7 +241,7 @@ public class UsdtAggregationWorkflowService {
boolean hasFailure = false;
for (UsdtAggregationTaskItemPlus item : items) {
if (!executeItemInternal(item, session)) {
if (!executeItemInternal(item, session, resourceOnly)) {
hasFailure = true;
}
}
@@ -215,6 +251,10 @@ public class UsdtAggregationWorkflowService {
}
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);
if (item == null) {
throw new CustomException("归集明细不存在");
@@ -229,7 +269,14 @@ public class UsdtAggregationWorkflowService {
if (!Long.valueOf(2L).equals(item.getStatus())) {
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>()
.eq(UsdtAggregationTaskItemPlus::getParentId, task.getId())
.eq(UsdtAggregationTaskItemPlus::getStatus, 2L)) > 0;
@@ -263,8 +310,41 @@ public class UsdtAggregationWorkflowService {
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,
WalletSigningService.UnlockedWalletSession session) {
WalletSigningService.UnlockedWalletSession session, Boolean resourceOnly) {
// 使用数据库状态而非列表快照决定是否允许广播,取消与执行只能有一方成功。
if (itemMapper.claimItemForExecution(item.getId()) != 1) {
UsdtAggregationTaskItem current = itemMapper.selectUsdtAggregationTaskItemById(item.getId());
@@ -278,9 +358,13 @@ public class UsdtAggregationWorkflowService {
markFailed(item, "钱包不存在或已不属于当前应用");
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) ->
tron.usdtTransWithBroadcastRetry(api, current.getToken(),
item.getDistTokenAddress(), item.getOpeAmount(), MAX_ATTEMPTS));
if (resourceCommand != null) resourceExecutionGate.transferred(resourceCommand.businessKey, tx);
String successRemark = "执行成功;同一签名交易最多广播 " + MAX_ATTEMPTS
+ " 次;交易哈希:" + tx;
ledgerPostingService.completeAggregationItem(item, wallet, tx, successRemark);
@@ -299,6 +383,20 @@ public class UsdtAggregationWorkflowService {
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) {
task.setStatus(failed ? 3 : 2);
task.setUpdatedAt(DateUtils.getNowDate());
@@ -95,7 +95,8 @@ public class WalletSigningService {
} catch (CustomException e) {
throw e;
} catch (Exception e) {
log.error(e.getMessage(),e);
// 私钥客户端异常可能带有签名上下文,禁止输出原始异常消息和堆栈。
log.error("钱包解密或链上签名操作失败");
throw new CustomException("钱包解密或链上签名操作失败", e);
} finally {
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"; }
}
}