添加子账号逻辑

This commit is contained in:
lu7213 committed 2026-10-10 05:22:05 -04:00
1 parent 35c7bcc8aa
commit 658e6ccf1e
8 files changed
+196 -2

No files matched your search

@@ -24,6 +24,7 @@ import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.dto.UsdtConfigCreateRequest;
import com.ruoyi.system.domain.dto.UsdtConfigRotateRequest;
import com.ruoyi.system.domain.dto.UsdtConfigAddWalletsRequest;
/**
* 全局配置Controller
@@ -63,6 +64,25 @@ public class UsdtConfigController extends BaseController
{
return AjaxResult.success(usdtConfigService.rotateConfigurationPassword(id, request));
}
/** 查询当前全局子账号池数量。 */
@PreAuthorize("@ss.hasPermi('system:usdtConfig:list')")
@GetMapping("/child-accounts/stats")
public AjaxResult childAccountStats()
{
return AjaxResult.success(usdtConfigService.getChildAccountStats());
}
/** 使用当前配置密码解锁助记词并增加未分配子账号。 */
@PreAuthorize("@ss.hasPermi('system:usdtConfig:edit')")
@Log(title = "增加全局钱包子账号", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
@PostMapping("/{id}/child-accounts")
public AjaxResult addChildAccounts(@PathVariable("id") Long id,
@RequestBody UsdtConfigAddWalletsRequest request)
{
return AjaxResult.success(usdtConfigService.addChildAccounts(id, request));
}
@PreAuthorize("@ss.hasPermi('system:usdtConfig:getByIds')")
@PostMapping("/getByIds")
public AjaxResult getByIds(@RequestBody Ids ids)
@@ -0,0 +1,16 @@
package com.ruoyi.system.domain.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
/** 增加全局子账号请求。 */
public class UsdtConfigAddWalletsRequest {
private Integer count;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String configurationPassword;
public Integer getCount() { return count; }
public void setCount(Integer count) { this.count = count; }
public String getConfigurationPassword() { return configurationPassword; }
public void setConfigurationPassword(String configurationPassword) { this.configurationPassword = configurationPassword; }
}
@@ -14,6 +14,8 @@ public class UsdtConfigCreateRequest {
private BigDecimal receiveUsdtNum;
private Integer tronNetType;
private BigDecimal trxNum;
/** 初始化时生成的子账号数量,不包含索引 0 主钱包。 */
private Integer childAccountCount;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String configurationPassword;
@@ -29,6 +31,8 @@ public class UsdtConfigCreateRequest {
public void setTronNetType(Integer tronNetType) { this.tronNetType = tronNetType; }
public BigDecimal getTrxNum() { return trxNum; }
public void setTrxNum(BigDecimal trxNum) { this.trxNum = trxNum; }
public Integer getChildAccountCount() { return childAccountCount; }
public void setChildAccountCount(Integer childAccountCount) { this.childAccountCount = childAccountCount; }
public String getConfigurationPassword() { return configurationPassword; }
public void setConfigurationPassword(String configurationPassword) { this.configurationPassword = configurationPassword; }
public String getConfirmPassword() { return confirmPassword; }
@@ -0,0 +1,18 @@
package com.ruoyi.system.domain.vo;
/** 全局子账号池操作结果,不包含地址或私钥。 */
public class UsdtConfigWalletPoolResult {
private final int totalCount;
private final int createdCount;
private final int skippedCount;
public UsdtConfigWalletPoolResult(int totalCount, int createdCount, int skippedCount) {
this.totalCount = totalCount;
this.createdCount = createdCount;
this.skippedCount = skippedCount;
}
public int getTotalCount() { return totalCount; }
public int getCreatedCount() { return createdCount; }
public int getSkippedCount() { return skippedCount; }
}
@@ -39,6 +39,12 @@ public interface WalletAddressMapper extends BaseMapper<WalletAddressPlus>
*/
public int insertWalletAddress(WalletAddress walletAddress);
/** 查询已占用的派生索引,供全局子账号池幂等生成。 */
List<String> selectExistingTokenIndexes();
/** 统计未分配给应用和用户的全局子账号。 */
int countGlobalChildAccounts();
/**
* 修改钱包
*
@@ -8,8 +8,10 @@ import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.ruoyi.common.select.SelectItem;
import com.ruoyi.system.domain.dto.UsdtConfigCreateRequest;
import com.ruoyi.system.domain.dto.UsdtConfigRotateRequest;
import com.ruoyi.system.domain.dto.UsdtConfigAddWalletsRequest;
import com.ruoyi.system.domain.vo.UsdtConfigCreateResult;
import com.ruoyi.system.domain.vo.UsdtConfigRotateResult;
import com.ruoyi.system.domain.vo.UsdtConfigWalletPoolResult;
/**
* 全局配置Service接口
*
@@ -25,6 +27,12 @@ public interface IUsdtConfigService extends IService<UsdtConfigPlus>
/** 轮换配置密码,不改变助记词、派生地址及历史订单映射。 */
UsdtConfigRotateResult rotateConfigurationPassword(Long id, UsdtConfigRotateRequest request);
/** 增加全局未分配子账号,已存在的 token_index 自动跳过。 */
UsdtConfigWalletPoolResult addChildAccounts(Long id, UsdtConfigAddWalletsRequest request);
/** 查询当前全局未分配子账号数量。 */
UsdtConfigWalletPoolResult getChildAccountStats();
/**
* 查询全局配置
*
@@ -12,6 +12,8 @@ import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.UsdtConfigMapper;
import com.ruoyi.system.mapper.WalletAddressMapper;
import com.ruoyi.system.domain.WalletAddress;
import com.ruoyi.system.domain.UsdtConfig;
import com.ruoyi.system.domain.UsdtConfigPlus;
import com.ruoyi.system.service.IUsdtConfigService;
@@ -22,12 +24,18 @@ import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.demo.WalletEnvelopeEncryptionDemo;
import com.ruoyi.system.domain.dto.UsdtConfigCreateRequest;
import com.ruoyi.system.domain.dto.UsdtConfigRotateRequest;
import com.ruoyi.system.domain.dto.UsdtConfigAddWalletsRequest;
import com.ruoyi.system.domain.vo.UsdtConfigCreateResult;
import com.ruoyi.system.domain.vo.UsdtConfigRotateResult;
import com.ruoyi.system.domain.vo.UsdtConfigWalletPoolResult;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Date;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* 全局配置Service业务层处理
*
@@ -41,6 +49,8 @@ public class UsdtConfigServiceImpl extends ServiceImpl<UsdtConfigMapper, UsdtCon
private UsdtConfigMapper usdtConfigMapper;
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private WalletAddressMapper walletAddressMapper;
/**
* 首次创建全局配置。
@@ -59,7 +69,7 @@ public class UsdtConfigServiceImpl extends ServiceImpl<UsdtConfigMapper, UsdtCon
char[] password = request.getConfigurationPassword().toCharArray();
try {
WalletEnvelopeEncryptionDemo.DemoBundle bundle =
WalletEnvelopeEncryptionDemo.create(password, 0);
WalletEnvelopeEncryptionDemo.create(password, request.getChildAccountCount());
WalletEnvelopeEncryptionDemo.EncryptedEnvelope envelope = bundle.envelope;
UsdtConfig config = new UsdtConfig();
config.setPayUsdtNum(request.getPayUsdtNum());
@@ -71,6 +81,9 @@ public class UsdtConfigServiceImpl extends ServiceImpl<UsdtConfigMapper, UsdtCon
if (usdtConfigMapper.insertUsdtConfig(config) != 1) {
throw new CustomException("全局配置创建失败");
}
Set<Integer> initialIndexes = indexesFromOneTo(request.getChildAccountCount());
initialIndexes.removeAll(existingIndexes());
persistWallets(bundle.wallets, initialIndexes);
return new UsdtConfigCreateResult(config.getId(), config.getVersion(),
config.getTokenAddress(), bundle.mnemonic);
} catch (CustomException e) {
@@ -120,6 +133,100 @@ public class UsdtConfigServiceImpl extends ServiceImpl<UsdtConfigMapper, UsdtCon
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public UsdtConfigWalletPoolResult addChildAccounts(Long id, UsdtConfigAddWalletsRequest request) {
if (id == null) throw new CustomException("配置 ID 不能为空");
if (request == null || request.getCount() == null || request.getCount() < 1 || request.getCount() > 10000) {
throw new CustomException("增加数量必须在 1 到 10000 之间");
}
validatePassword(request.getConfigurationPassword(), "配置密码");
UsdtConfig current = usdtConfigMapper.selectFirstForUpdate();
if (current == null || !id.equals(current.getId())) throw new CustomException("全局配置不存在");
Set<Integer> existingIndexes = existingIndexes();
Set<Integer> targetIndexes = new HashSet<Integer>();
int skipped = 0;
for (int index = 1; index <= 10000 && targetIndexes.size() < request.getCount(); index++) {
if (existingIndexes.contains(index)) {
skipped++;
} else {
targetIndexes.add(index);
}
}
if (targetIndexes.size() < request.getCount()) throw new CustomException("子账号索引已达到 10000 上限");
int maxIndex = 0;
for (Integer index : targetIndexes) maxIndex = Math.max(maxIndex, index);
char[] password = request.getConfigurationPassword().toCharArray();
char[] mnemonic = null;
try {
mnemonic = WalletEnvelopeEncryptionDemo.unlock(toEnvelope(current), password);
List<WalletEnvelopeEncryptionDemo.DerivedWallet> wallets =
WalletEnvelopeEncryptionDemo.deriveWallets(new String(mnemonic), maxIndex + 1);
int created = persistWallets(wallets, targetIndexes);
return new UsdtConfigWalletPoolResult(walletAddressMapper.countGlobalChildAccounts(), created, skipped);
} catch (SecurityException e) {
throw new CustomException("配置密码错误");
} catch (CustomException e) {
throw e;
} catch (Exception e) {
throw new CustomException("增加钱包子账号失败", e);
} finally {
Arrays.fill(password, '\0');
if (mnemonic != null) Arrays.fill(mnemonic, '\0');
}
}
@Override
public UsdtConfigWalletPoolResult getChildAccountStats() {
return new UsdtConfigWalletPoolResult(walletAddressMapper.countGlobalChildAccounts(), 0, 0);
}
private Set<Integer> indexesFromOneTo(int count) {
Set<Integer> indexes = new HashSet<Integer>();
for (int index = 1; index <= count; index++) indexes.add(index);
return indexes;
}
private Set<Integer> existingIndexes() {
Set<Integer> indexes = new HashSet<Integer>();
for (String value : walletAddressMapper.selectExistingTokenIndexes()) {
try {
int index = Integer.parseInt(value);
if (index >= 0 && index <= 10000) indexes.add(index);
} catch (NumberFormatException ignored) {
// 历史非数字索引不属于当前 HD 派生索引空间。
}
}
return indexes;
}
private int persistWallets(List<WalletEnvelopeEncryptionDemo.DerivedWallet> wallets,
Set<Integer> targetIndexes) {
int created = 0;
Date now = DateUtils.getNowDate();
for (WalletEnvelopeEncryptionDemo.DerivedWallet wallet : wallets) {
if (!targetIndexes.contains(wallet.index)) continue;
WalletAddress entity = new WalletAddress();
entity.setToken(wallet.address);
entity.setTokenIndex(String.valueOf(wallet.index));
entity.setStatus(1L);
entity.setCreatedAt(now);
entity.setUpdatedAt(now);
entity.setAppId(null);
entity.setUserId(null);
entity.setWalletUserName(null);
entity.setUsdtBalance(BigDecimal.ZERO);
entity.setTrxBalance(BigDecimal.ZERO);
if (walletAddressMapper.insertWalletAddress(entity) != 1) {
throw new CustomException("子账号索引 " + wallet.index + " 保存失败");
}
created++;
}
return created;
}
private void validateCreateRequest(UsdtConfigCreateRequest request) {
if (request == null) throw new CustomException("请求参数不能为空");
validatePassword(request.getConfigurationPassword(), "配置密码");
@@ -135,6 +242,10 @@ public class UsdtConfigServiceImpl extends ServiceImpl<UsdtConfigMapper, UsdtCon
|| request.getTrxNum() == null || request.getTrxNum().signum() < 0) {
throw new CustomException("手续费和 TRX 数量不能为空且不能小于 0");
}
if (request.getChildAccountCount() == null || request.getChildAccountCount() < 0
|| request.getChildAccountCount() > 10000) {
throw new CustomException("子账号数量必须在 0 到 10000 之间");
}
}
private void validateRotateRequest(Long id, UsdtConfigRotateRequest request) {
@@ -86,6 +86,17 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<include refid="selectWalletAddressVo"/>
where id = #{id}
</select>
<select id="selectExistingTokenIndexes" resultType="String">
select token_index from wallet_address
where deleted_at is null and token_index is not null and token_index != ''
</select>
<select id="countGlobalChildAccounts" resultType="int">
select count(1) from wallet_address
where deleted_at is null and app_id is null and user_id is null and wallet_user_name is null
and cast(token_index as unsigned) &gt; 0
</select>
<insert id="insertWalletAddress" parameterType="WalletAddress" useGeneratedKeys="true" keyProperty="id">
insert into wallet_address
@@ -208,4 +219,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
#{id}
</foreach>
</delete>
</mapper>
</mapper>