归集任务逻辑

This commit is contained in:
lu7213 committed 2026-10-12 11:51:52 -04:00
1 parent 18e3eb8ff0
commit 38d038115a
8 files changed
+488 -126

No files matched your search

@@ -7,17 +7,12 @@ import com.ruoyi.system.service.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
/** /**
* 后台逐地址执行归集任务;每个明细独立失败并继续后续地址。 * 后台逐地址执行归集任务;每个明细独立失败并继续后续地址。
*/ */
@Component
@EnableScheduling
public class UsdtAggregationExecutorTask { public class UsdtAggregationExecutorTask {
private static final Logger log = LoggerFactory.getLogger(UsdtAggregationExecutorTask.class); private static final Logger log = LoggerFactory.getLogger(UsdtAggregationExecutorTask.class);
@Autowired @Autowired
@@ -29,7 +24,6 @@ public class UsdtAggregationExecutorTask {
@Autowired @Autowired
private TronServiceProvider tronServiceProvider; private TronServiceProvider tronServiceProvider;
@Scheduled(fixedDelay = 30000L)
public void executePending() { public void executePending() {
ITronService tronService; ITronService tronService;
try { try {
@@ -11,6 +11,9 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.UsdtAggregationTask; import com.ruoyi.system.domain.UsdtAggregationTask;
import com.ruoyi.system.domain.UsdtAggregationTaskPlus; import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
import com.ruoyi.system.service.IUsdtAggregationTaskService; import com.ruoyi.system.service.IUsdtAggregationTaskService;
import com.ruoyi.system.service.UsdtAggregationWorkflowService;
import com.ruoyi.system.domain.vo.AggregationExecuteRequest;
import com.ruoyi.system.domain.vo.AggregationTaskCreateRequest;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -28,17 +31,53 @@ import java.util.List;
public class UsdtAggregationTaskController extends BaseController { public class UsdtAggregationTaskController extends BaseController {
@Autowired @Autowired
private IUsdtAggregationTaskService usdtAggregationTaskService; private IUsdtAggregationTaskService usdtAggregationTaskService;
/** 触发归集任务;实际明细执行由后台任务处理,避免阻塞 HTTP 请求。 */ @Autowired
private UsdtAggregationWorkflowService aggregationWorkflowService;
/** 创建应用下全部子钱包的 USDT 归集任务。 */
@PreAuthorize("@ss.hasPermi('system:usdtTask:add')")
@PostMapping("/create")
public AjaxResult create(@RequestBody AggregationTaskCreateRequest request) {
return AjaxResult.success(aggregationWorkflowService.create(request, false));
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-add')")
@PostMapping("/user/create")
public AjaxResult userCreate(@RequestBody AggregationTaskCreateRequest request) {
return AjaxResult.success(aggregationWorkflowService.create(request, true));
}
/** 管理员审核归集任务:approved=true 通过,false 拒绝。 */
@PreAuthorize("@ss.hasPermi('system:usdtTask:edit')")
@PostMapping("/{id}/review")
public AjaxResult review(@PathVariable("id") Long id, @RequestParam boolean approved) {
aggregationWorkflowService.approve(id, approved);
return AjaxResult.success(approved ? "审核通过" : "审核拒绝");
}
/** 审核通过后,使用配置密码同步签名并执行所有待执行或失败明细。 */
@PreAuthorize("@ss.hasPermi('system:usdtTask:execute')") @PreAuthorize("@ss.hasPermi('system:usdtTask:execute')")
@PostMapping("/{id}/execute") @PostMapping("/{id}/execute")
public AjaxResult execute(@PathVariable("id") Long id) { public AjaxResult execute(@PathVariable("id") Long id,
UsdtAggregationTask task = usdtAggregationTaskService.selectUsdtAggregationTaskById(id, false); @RequestBody AggregationExecuteRequest request) {
if (task == null) return AjaxResult.error("任务不存在"); try {
if (task.getStatus() != null && task.getStatus() == 1) return AjaxResult.error("任务正在执行"); aggregationWorkflowService.executeTask(id, request.getConfigurationPassword(), false);
task.setStatus(1); return AjaxResult.success("归集任务执行完成");
task.setExeTime(new java.util.Date()); } finally {
usdtAggregationTaskService.updateUsdtAggregationTask(task, false); request.setConfigurationPassword(null);
return AjaxResult.success("任务已进入执行队列"); }
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-edit')")
@PostMapping("/user/{id}/execute")
public AjaxResult userExecute(@PathVariable("id") Long id,
@RequestBody AggregationExecuteRequest request) {
try {
aggregationWorkflowService.executeTask(id, request.getConfigurationPassword(), true);
return AjaxResult.success("归集任务执行完成");
} finally {
request.setConfigurationPassword(null);
}
} }
@PreAuthorize("@ss.hasPermi('system:usdtTask:getByIds')") @PreAuthorize("@ss.hasPermi('system:usdtTask:getByIds')")
@@ -121,60 +160,8 @@ public class UsdtAggregationTaskController extends BaseController {
return AjaxResult.success(usdtAggregationTaskService.selectUsdtAggregationTaskById(id, true)); return AjaxResult.success(usdtAggregationTaskService.selectUsdtAggregationTaskById(id, true));
} }
/** /*
* 新增归集任务 * 归集任务的状态、审核结果、目标地址和执行时间必须由工作流维护。
* 不暴露代码生成器的通用新增、编辑和删除接口,防止绕过审核流程。
*/ */
@PreAuthorize("@ss.hasPermi('system:usdtTask:add')")
@Log(title = "归集任务", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.insertUsdtAggregationTask(usdtAggregationTask, false));
}
/**
* 新增归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-add')")
@Log(title = "归集任务", businessType = BusinessType.INSERT)
@PostMapping("/user")
public AjaxResult userAdd(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.insertUsdtAggregationTask(usdtAggregationTask, true));
}
/**
* 修改归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:edit')")
@Log(title = "归集任务", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.updateUsdtAggregationTask(usdtAggregationTask, false));
}
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-edit')")
@Log(title = "归集任务", businessType = BusinessType.UPDATE)
@PutMapping("/user")
public AjaxResult userEdit(@RequestBody UsdtAggregationTask usdtAggregationTask) {
return toAjax(usdtAggregationTaskService.updateUsdtAggregationTask(usdtAggregationTask, true));
}
/**
* 删除归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:remove')")
@Log(title = "归集任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(usdtAggregationTaskService.deleteUsdtAggregationTaskByIds(ids, false));
}
/**
* 删除归集任务
*/
@PreAuthorize("@ss.hasPermi('system:usdtTask:user-remove')")
@Log(title = "归集任务", businessType = BusinessType.DELETE)
@DeleteMapping("/user/{ids}")
public AjaxResult userRemove(@PathVariable Long[] ids) {
return toAjax(usdtAggregationTaskService.deleteUsdtAggregationTaskByIds(ids, true));
}
} }
@@ -11,6 +11,8 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.UsdtAggregationTaskItem; import com.ruoyi.system.domain.UsdtAggregationTaskItem;
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus; import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
import com.ruoyi.system.service.IUsdtAggregationTaskItemService; import com.ruoyi.system.service.IUsdtAggregationTaskItemService;
import com.ruoyi.system.service.UsdtAggregationWorkflowService;
import com.ruoyi.system.domain.vo.AggregationExecuteRequest;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -29,6 +31,33 @@ public class UsdtAggregationTaskItemController extends BaseController
{ {
@Autowired @Autowired
private IUsdtAggregationTaskItemService usdtAggregationTaskItemService; private IUsdtAggregationTaskItemService usdtAggregationTaskItemService;
@Autowired
private UsdtAggregationWorkflowService aggregationWorkflowService;
/** 手动重新执行单个失败明细,仍要求配置密码。 */
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:edit')")
@PostMapping("/{id}/retry")
public AjaxResult retry(@PathVariable("id") Long id,
@RequestBody AggregationExecuteRequest request) {
try {
aggregationWorkflowService.retryItem(id, request.getConfigurationPassword(), false);
return AjaxResult.success("归集明细重试完成");
} finally {
request.setConfigurationPassword(null);
}
}
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-edit')")
@PostMapping("/user/{id}/retry")
public AjaxResult userRetry(@PathVariable("id") Long id,
@RequestBody AggregationExecuteRequest request) {
try {
aggregationWorkflowService.retryItem(id, request.getConfigurationPassword(), true);
return AjaxResult.success("归集明细重试完成");
} finally {
request.setConfigurationPassword(null);
}
}
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:getByIds')") @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:getByIds')")
@PostMapping("/getByIds") @PostMapping("/getByIds")
public AjaxResult getByIds(@RequestBody Ids ids) public AjaxResult getByIds(@RequestBody Ids ids)
@@ -110,61 +139,8 @@ public class UsdtAggregationTaskItemController extends BaseController
{ {
return AjaxResult.success(usdtAggregationTaskItemService.selectUsdtAggregationTaskItemById(id,true)); return AjaxResult.success(usdtAggregationTaskItemService.selectUsdtAggregationTaskItemById(id,true));
} }
/** /*
* 新增归集任务明细 * 明细金额、来源地址、目标地址和执行状态均由归集工作流维护。
* 对外只保留查询与失败项重试接口,禁止任意增删改明细。
*/ */
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:add')")
@Log(title = "归集任务明细", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.insertUsdtAggregationTaskItem(usdtAggregationTaskItem,false));
}
/**
* 新增归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-add')")
@Log(title = "归集任务明细", businessType = BusinessType.INSERT)
@PostMapping("/user")
public AjaxResult userAdd(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.insertUsdtAggregationTaskItem(usdtAggregationTaskItem,true));
}
/**
* 修改归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:edit')")
@Log(title = "归集任务明细", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.updateUsdtAggregationTaskItem(usdtAggregationTaskItem,false));
}
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-edit')")
@Log(title = "归集任务明细", businessType = BusinessType.UPDATE)
@PutMapping("/user")
public AjaxResult userEdit(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem)
{
return toAjax(usdtAggregationTaskItemService.updateUsdtAggregationTaskItem(usdtAggregationTaskItem,true));
}
/**
* 删除归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:remove')")
@Log(title = "归集任务明细", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(usdtAggregationTaskItemService.deleteUsdtAggregationTaskItemByIds(ids,false));
}
/**
* 删除归集任务明细
*/
@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-remove')")
@Log(title = "归集任务明细", businessType = BusinessType.DELETE)
@DeleteMapping("/user/{ids}")
public AjaxResult userRemove(@PathVariable Long[] ids)
{
return toAjax(usdtAggregationTaskItemService.deleteUsdtAggregationTaskItemByIds(ids,true));
}
} }
@@ -0,0 +1,17 @@
package com.ruoyi.system.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
/** 归集执行请求,配置密码仅用于当前请求内解锁钱包。 */
public class AggregationExecuteRequest implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String configurationPassword;
public String getConfigurationPassword() { return configurationPassword; }
public void setConfigurationPassword(String configurationPassword) {
this.configurationPassword = configurationPassword;
}
}
@@ -0,0 +1,21 @@
package com.ruoyi.system.domain.vo;
import java.io.Serializable;
/** 按应用或用户生成 USDT 归集任务。 */
public class AggregationTaskCreateRequest implements Serializable {
private static final long serialVersionUID = 1L;
private Long appId;
private Long userId;
private String taskName;
private String remark;
public Long getAppId() { return appId; }
public void setAppId(Long appId) { this.appId = appId; }
public Long getUserId() { return userId; }
public void setUserId(Long userId) { this.userId = userId; }
public String getTaskName() { return taskName; }
public void setTaskName(String taskName) { this.taskName = taskName; }
public String getRemark() { return remark; }
public void setRemark(String remark) { this.remark = remark; }
}
@@ -5,10 +5,16 @@ import com.ruoyi.system.domain.vo.TronAccount;
import com.ruoyi.system.domain.vo.TronAccountItem; import com.ruoyi.system.domain.vo.TronAccountItem;
import org.tron.trident.core.ApiWrapper; import org.tron.trident.core.ApiWrapper;
import org.tron.trident.core.exceptions.IllegalException; import org.tron.trident.core.exceptions.IllegalException;
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.proto.Chain;
import org.tron.trident.proto.Response; import org.tron.trident.proto.Response;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
import com.google.protobuf.ByteString; import com.google.protobuf.ByteString;
import com.ruoyi.system.domain.vo.DelegatedResourceDetailVo; import com.ruoyi.system.domain.vo.DelegatedResourceDetailVo;
@@ -32,6 +38,63 @@ public interface ITronService {
String usdtTrans(ApiWrapper api,String fromAddress, String toAddress, String amount); String usdtTrans(ApiWrapper api,String fromAddress, String toAddress, String amount);
/**
* 构造并签名一次 USDT 转账交易,广播失败时仅重播同一笔签名交易。
*
* <p>该方法用于归集等需要自动重试的场景。绝不能在重试循环中重新构造交易,
* 否则节点已经接收交易但客户端响应超时时,可能产生多笔有效转账。</p>
*
* @param api 带来源钱包私钥的客户端
* @param fromAddress 来源地址
* @param toAddress 目标地址
* @param amount USDT 数量,最多 6 位小数
* @param maxBroadcastAttempts 最大广播次数,包含首次广播
* @return 链上交易哈希
*/
default String usdtTransWithBroadcastRetry(ApiWrapper api, String fromAddress,
String toAddress, BigDecimal amount, int maxBroadcastAttempts) throws IllegalException {
if (api == null || fromAddress == null || toAddress == null) {
throw new IllegalArgumentException("USDT 转账参数不完整");
}
if (amount == null || amount.signum() <= 0) {
throw new IllegalArgumentException("归集金额必须大于 0");
}
if (maxBroadcastAttempts <= 0) {
throw new IllegalArgumentException("广播次数必须大于 0");
}
final long tokenAmount;
try {
tokenAmount = amount.movePointRight(6).longValueExact();
} catch (ArithmeticException ex) {
throw new IllegalArgumentException("USDT 金额最多支持 6 位小数且不能超出范围", ex);
}
Function function = new Function("transfer",
Arrays.asList(new Address(toAddress), new Uint256(tokenAmount)),
Collections.emptyList());
Chain.Transaction unsignedTransaction = api.triggerCall(
fromAddress,
ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())),
function).setFeeLimit(10_000_000L).build();
Chain.Transaction signedTransaction = api.signTransaction(unsignedTransaction);
RuntimeException lastFailure = null;
for (int attempt = 1; attempt <= maxBroadcastAttempts; attempt++) {
try {
String transactionHash = api.broadcastTransaction(signedTransaction);
if (transactionHash != null && !transactionHash.trim().isEmpty()
&& !transactionHash.startsWith("error")) {
return transactionHash;
}
lastFailure = new IllegalStateException("TRON 节点未返回有效交易哈希");
} catch (RuntimeException ex) {
lastFailure = ex;
}
}
throw new IllegalStateException("TRON 交易广播失败,已重播同一签名交易 "
+ maxBroadcastAttempts + " 次", lastFailure);
}
String trxTrans(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount); String trxTrans(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount);
/** /**
@@ -0,0 +1,278 @@
package com.ruoyi.system.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AppsPlus;
import com.ruoyi.system.domain.UsdtAggregationTask;
import com.ruoyi.system.domain.UsdtAggregationTaskItem;
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.domain.vo.AggregationTaskCreateRequest;
import com.ruoyi.system.domain.vo.WalletOperationRequest;
import com.ruoyi.system.domain.vo.WalletResourceEstimateVo;
import com.ruoyi.system.mapper.UsdtAggregationTaskItemMapper;
import com.ruoyi.system.mapper.UsdtAggregationTaskMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
/** USDT 归集任务的生成、审核和受控签名执行流程。 */
@Service
public class UsdtAggregationWorkflowService {
private static final int MAX_ATTEMPTS = 4;
private final IAppsService appsService;
private final IWalletAddressService walletService;
private final IUsdtAggregationTaskService taskService;
private final IUsdtAggregationTaskItemService itemService;
private final UsdtAggregationTaskMapper taskMapper;
private final UsdtAggregationTaskItemMapper itemMapper;
private final WalletOperationEstimateService estimateService;
private final WalletSigningService walletSigningService;
public UsdtAggregationWorkflowService(IAppsService appsService,
IWalletAddressService walletService,
IUsdtAggregationTaskService taskService,
IUsdtAggregationTaskItemService itemService,
UsdtAggregationTaskMapper taskMapper,
UsdtAggregationTaskItemMapper itemMapper,
WalletOperationEstimateService estimateService,
WalletSigningService walletSigningService) {
this.appsService = appsService;
this.walletService = walletService;
this.taskService = taskService;
this.itemService = itemService;
this.taskMapper = taskMapper;
this.itemMapper = itemMapper;
this.estimateService = estimateService;
this.walletSigningService = walletSigningService;
}
@Transactional(rollbackFor = Exception.class)
public Long create(AggregationTaskCreateRequest request, boolean userMode) {
AppsPlus app = resolveApp(request, userMode);
if (StringUtils.isBlank(app.getDistTokenAddress())) {
throw new CustomException("应用未配置主账号归集地址");
}
List<WalletAddressPlus> wallets = walletService.getListByAppId(app.getId());
Date now = DateUtils.getNowDate();
UsdtAggregationTask task = new UsdtAggregationTask();
task.setTaskName(StringUtils.isBlank(request.getTaskName())
? "USDT归集-" + app.getName() + "-" + now.getTime() : request.getTaskName().trim());
task.setAppId(app.getId());
task.setUserId(app.getUserId());
task.setRemark(request.getRemark());
task.setStatus(0);
task.setVerifyStatus(0);
task.setDistTokenAddress(app.getDistTokenAddress());
task.setCreatedAt(now);
task.setUpdatedAt(now);
int eligible = 0;
for (WalletAddressPlus wallet : wallets) {
if (!isEligible(wallet, app.getDistTokenAddress())) {
continue;
}
eligible++;
}
if (eligible == 0) {
throw new CustomException("当前应用没有可归集的子钱包");
}
taskMapper.insertUsdtAggregationTask(task);
for (WalletAddressPlus wallet : wallets) {
if (!isEligible(wallet, app.getDistTokenAddress())) {
continue;
}
UsdtAggregationTaskItem item = buildItem(task, wallet, now);
itemMapper.insertUsdtAggregationTaskItem(item);
}
return task.getId();
}
public void approve(Long taskId, boolean approved) {
UsdtAggregationTaskPlus task = requireTask(taskId, false);
if (task.getStatus() != null && task.getStatus() != 0) {
throw new CustomException("任务已开始执行,不能重复审核");
}
task.setVerifyStatus(approved ? 1 : 2);
task.setUpdatedAt(DateUtils.getNowDate());
task.setRemark(approved ? "审核通过" : "审核拒绝");
taskService.updateById(task);
}
public void executeTask(Long taskId, String password, boolean userMode) {
UsdtAggregationTaskPlus task = requireTask(taskId, userMode);
if (!Integer.valueOf(1).equals(task.getVerifyStatus())) {
throw new CustomException("归集任务尚未审核通过");
}
if (Integer.valueOf(1).equals(task.getStatus())) {
throw new CustomException("归集任务正在执行");
}
walletSigningService.validateConfigurationPassword(password);
task.setStatus(1);
task.setExeTime(DateUtils.getNowDate());
task.setUpdatedAt(DateUtils.getNowDate());
taskService.updateById(task);
List<UsdtAggregationTaskItemPlus> items = itemService.list(
new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
.eq(UsdtAggregationTaskItemPlus::getParentId, taskId)
.in(UsdtAggregationTaskItemPlus::getStatus, 0L, 2L));
boolean failed = false;
for (UsdtAggregationTaskItemPlus item : items) {
if (!executeItemInternal(item, password)) {
failed = true;
}
}
finishTask(task, failed);
}
public void retryItem(Long itemId, String password, boolean userMode) {
UsdtAggregationTaskItemPlus item = itemService.getById(itemId);
if (item == null) {
throw new CustomException("归集明细不存在");
}
UsdtAggregationTaskPlus task = requireTask(item.getParentId(), userMode);
if (!Integer.valueOf(1).equals(task.getVerifyStatus())) {
throw new CustomException("归集任务尚未审核通过");
}
if (Integer.valueOf(1).equals(task.getStatus())) {
throw new CustomException("归集任务正在执行,不能单独重试明细");
}
if (!Long.valueOf(2L).equals(item.getStatus())) {
throw new CustomException("只有失败的归集明细可以手动重试");
}
walletSigningService.validateConfigurationPassword(password);
executeItemInternal(item, password);
boolean remainsFailed = itemService.count(new LambdaQueryWrapper<UsdtAggregationTaskItemPlus>()
.eq(UsdtAggregationTaskItemPlus::getParentId, task.getId())
.eq(UsdtAggregationTaskItemPlus::getStatus, 2L)) > 0;
finishTask(task, remainsFailed);
}
private UsdtAggregationTaskItem buildItem(UsdtAggregationTask task,
WalletAddressPlus wallet, Date now) {
WalletOperationRequest operation = new WalletOperationRequest();
operation.setWalletId(wallet.getId());
operation.setToAddress(task.getDistTokenAddress());
operation.setAmount(wallet.getUsdtBalance());
WalletResourceEstimateVo estimate = estimateService.estimate("usdt", wallet, operation);
UsdtAggregationTaskItem item = new UsdtAggregationTaskItem();
item.setTokenAddress(wallet.getToken());
item.setStatus(0L);
item.setRemark("等待执行");
item.setOpeAmount(wallet.getUsdtBalance());
item.setCreatedAt(now);
item.setUpdatedAt(now);
item.setNeedEnergyNum(estimate.getSafeEnergy());
item.setNeedBandwidthNum(estimate.getSafeBandwidth());
item.setGapEnergyNum(estimate.getEnergyGap());
item.setGapBandwidthNum(estimate.getBandwidthGap());
item.setWillUseTrxNum(estimate.getEstimatedBurnTrx().setScale(0, RoundingMode.UP).longValue());
item.setUserId(task.getUserId());
item.setAppId(task.getAppId());
item.setParentId(task.getId());
item.setDistTokenAddress(task.getDistTokenAddress());
return item;
}
private boolean executeItemInternal(UsdtAggregationTaskItemPlus item, String password) {
WalletAddressPlus wallet = walletService.getByTokenAndAppId(item.getTokenAddress(), item.getAppId());
if (wallet == null) {
markFailed(item, "钱包不存在或已不属于当前应用");
return false;
}
try {
String tx = walletSigningService.execute(wallet, password, (tron, api, current) ->
tron.usdtTransWithBroadcastRetry(api, current.getToken(),
item.getDistTokenAddress(), item.getOpeAmount(), MAX_ATTEMPTS));
item.setStatus(1L);
item.setRemark("执行成功;同一签名交易最多广播 " + MAX_ATTEMPTS
+ " 次;交易哈希:" + tx);
item.setUpdatedAt(DateUtils.getNowDate());
itemService.updateById(item);
return true;
} catch (Exception ex) {
markFailed(item, "执行失败;同一签名交易已最多广播 " + MAX_ATTEMPTS
+ " 次;原因:" + safeMessage(ex));
return false;
}
}
private void markFailed(UsdtAggregationTaskItemPlus item, String reason) {
item.setStatus(2L);
item.setRemark(reason);
item.setUpdatedAt(DateUtils.getNowDate());
itemService.updateById(item);
}
private void finishTask(UsdtAggregationTaskPlus task, boolean failed) {
task.setStatus(failed ? 3 : 2);
task.setUpdatedAt(DateUtils.getNowDate());
task.setRemark(failed ? "执行完成,存在失败明细" : "全部归集成功");
taskService.updateById(task);
}
private AppsPlus resolveApp(AggregationTaskCreateRequest request, boolean userMode) {
if (request == null) {
throw new CustomException("创建参数不能为空");
}
Long currentUserId = SecurityUtils.getUserId();
Long userId = userMode ? currentUserId : request.getUserId();
AppsPlus app = null;
if (request.getAppId() != null) {
app = appsService.getById(request.getAppId());
} else if (userId != null) {
app = appsService.getOne(new LambdaQueryWrapper<AppsPlus>()
.eq(AppsPlus::getUserId, userId)
.eq(AppsPlus::getStatus, 1)
.isNull(AppsPlus::getDeletedAt));
}
if (app == null || !Integer.valueOf(1).equals(app.getStatus())) {
throw new CustomException("未找到启用的商户应用");
}
if (userId != null && !userId.equals(app.getUserId())) {
throw new CustomException("应用与所属用户不匹配");
}
if (userMode && !currentUserId.equals(app.getUserId())) {
throw new CustomException("无权为该应用创建归集任务");
}
return app;
}
private UsdtAggregationTaskPlus requireTask(Long taskId, boolean userMode) {
UsdtAggregationTaskPlus task = taskService.getById(taskId);
if (task == null) {
throw new CustomException("归集任务不存在");
}
if (userMode && !SecurityUtils.getUserId().equals(task.getUserId())) {
throw new CustomException("无权操作该归集任务");
}
return task;
}
private boolean isEligible(WalletAddressPlus wallet, String destination) {
return wallet != null && Integer.valueOf(1).equals(wallet.getStatus())
&& wallet.getDeletedAt() == null && StringUtils.isNotBlank(wallet.getWalletUserName())
&& StringUtils.isNotBlank(wallet.getToken()) && !wallet.getToken().equals(destination)
&& wallet.getUsdtBalance() != null && wallet.getUsdtBalance().compareTo(BigDecimal.ZERO) > 0;
}
private String safeMessage(Exception exception) {
if (exception == null || StringUtils.isBlank(exception.getMessage())) {
return "未知错误";
}
String message = exception.getMessage().replace('\n', ' ').replace('\r', ' ');
return message.length() > 700 ? message.substring(0, 700) : message;
}
}
@@ -32,6 +32,32 @@ public class WalletSigningService {
@Autowired @Autowired
private TronServiceProvider tronServiceProvider; private TronServiceProvider tronServiceProvider;
/** 仅校验配置密码,不派生私钥、不签名也不广播交易。 */
public void validateConfigurationPassword(String configurationPassword) {
if (StringUtils.isBlank(configurationPassword)) {
throw new CustomException("配置密码不能为空");
}
List<UsdtConfig> configs = usdtConfigMapper.selectUsdtConfigList(new UsdtConfig());
if (configs == null || configs.isEmpty()) {
throw new CustomException("全局钱包配置不存在");
}
char[] password = configurationPassword.toCharArray();
char[] mnemonic = null;
try {
mnemonic = WalletEnvelopeEncryptionDemo.unlock(toEnvelope(configs.get(0)), password);
} catch (SecurityException ex) {
throw new CustomException("配置密码错误");
} catch (Exception ex) {
log.error("全局钱包配置解密失败", ex);
throw new CustomException("全局钱包配置解密失败", ex);
} finally {
Arrays.fill(password, '\0');
if (mnemonic != null) {
Arrays.fill(mnemonic, '\0');
}
}
}
public <T> T execute(WalletAddressPlus wallet, String configurationPassword, public <T> T execute(WalletAddressPlus wallet, String configurationPassword,
SignedOperation<T> operation) { SignedOperation<T> operation) {
validate(wallet, configurationPassword, operation); validate(wallet, configurationPassword, operation);