diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java index b449b24..7e835e1 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletAddressController.java @@ -12,6 +12,7 @@ import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.system.domain.WalletAddress; import com.ruoyi.system.domain.WalletAddressPlus; import com.ruoyi.system.service.IWalletAddressService; +import com.ruoyi.system.service.WalletSigningService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; @@ -36,16 +37,18 @@ public class WalletAddressController extends BaseController { private IWalletAddressService walletAddressService; @Autowired private TronServiceProvider tronServiceProvider; + @Autowired + private WalletSigningService walletSigningService; /** 查询链上账户快照。私钥只从服务端读取,响应永远不包含 tokenKey。 */ - @PreAuthorize("@ss.hasPermi('system:address:query')") + @PreAuthorize("@ss.hasPermi('system:address:query') or @ss.hasPermi('system:address:user-query')") @GetMapping("/{id}/chain") public AjaxResult chain(@PathVariable("id") Long id) { WalletAddressPlus wallet = walletAddressService.getById(id); if (wallet == null) { return AjaxResult.error("钱包不存在"); } - if (wallet.getUserId() != null && !SecurityUtils.isAdmin(getUserId()) && !wallet.getUserId().equals(getUserId())) { + if (!SecurityUtils.isAdmin(getUserId()) && !getUserId().equals(wallet.getUserId())) { return AjaxResult.error("无权访问该钱包"); } ApiWrapper api = null; @@ -65,38 +68,136 @@ public class WalletAddressController extends BaseController { } } - @PreAuthorize("@ss.hasPermi('system:address:operate')") - @PostMapping("/operate/{type}") - public AjaxResult operate(@PathVariable("type") String type, @RequestBody WalletOperationRequest request) { - if (request == null || request.getWalletId() == null) return AjaxResult.error("钱包不能为空"); - WalletAddressPlus wallet = walletAddressService.getById(request.getWalletId()); - if (wallet == null || (wallet.getUserId() != null && !SecurityUtils.isAdmin(getUserId()) && !wallet.getUserId().equals(getUserId()))) return AjaxResult.error("无权访问该钱包"); - if (type == null || !type.matches("(?i)trx|usdt|stake|unstake|delegate|undelegate|cancel-unstake")) return AjaxResult.error("不支持的操作类型"); - if (!"cancel-unstake".equalsIgnoreCase(type) && (request.getAmount() == null || request.getAmount().signum() <= 0)) return AjaxResult.error("金额必须大于 0"); - if (("trx".equalsIgnoreCase(type) || "usdt".equalsIgnoreCase(type) || "delegate".equalsIgnoreCase(type) || "undelegate".equalsIgnoreCase(type)) && (request.getToAddress() == null || request.getToAddress().trim().isEmpty())) return AjaxResult.error("目标地址不能为空"); - if (!Boolean.TRUE.equals(request.getBroadcast())) return AjaxResult.success("预演模式:已通过参数校验,未广播交易"); - ApiWrapper api = null; - try { - ITronService tronService = tronServiceProvider.getCurrentService(); - api = tronService.buildApiWrapper(); - String tx; - BigDecimal amount = request.getAmount(); - if ("trx".equalsIgnoreCase(type)) tx = tronService.trxTrans(api, wallet.getToken(), request.getToAddress(), amount); - else if ("usdt".equalsIgnoreCase(type)) tx = tronService.usdtTrans(api, wallet.getToken(), request.getToAddress(), amount.toPlainString()); - else if ("stake".equalsIgnoreCase(type)) tx = String.valueOf(tronService.stakeTrxBalance(api, wallet.getToken(), amount, resource(request))); - else if ("unstake".equalsIgnoreCase(type)) tx = String.valueOf(tronService.unstakeTrxBalance(api, wallet.getToken(), amount, resource(request))); - else if ("delegate".equalsIgnoreCase(type)) tx = tronService.delegateResourceV2(api, wallet.getToken(), request.getToAddress(), amount, resource(request)); - else if ("undelegate".equalsIgnoreCase(type)) tx = tronService.unDelegateResourceV2(api, wallet.getToken(), request.getToAddress(), amount, resource(request)); - else if ("cancel-unstake".equalsIgnoreCase(type)) tx = String.valueOf(tronService.cancleUnstakeTrxBalance(api, wallet.getToken())); - else return AjaxResult.error("不支持的操作类型"); - return AjaxResult.success(tx); - } catch (Exception ex) { - return AjaxResult.error("链上操作失败,请检查余额、资源和地址"); - } finally { if (api != null) api.close(); } + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/transfer-trx") + public AjaxResult transferTrx(@RequestBody WalletOperationRequest request) { + final WalletAddressPlus wallet = requireWallet(request); + validateAmount(request); + validateTarget(request); + if (isPreview(request)) return previewSuccess(); + return signedResult(wallet, request, (tron, api, current) -> + tron.trxTrans(api, current.getToken(), request.getToAddress().trim(), request.getAmount())); } - private int resource(WalletOperationRequest request) { - return request.getResourceCode() == null ? 1 : request.getResourceCode(); + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/transfer-usdt") + public AjaxResult transferUsdt(@RequestBody WalletOperationRequest request) { + final WalletAddressPlus wallet = requireWallet(request); + validateAmount(request); + validateTarget(request); + if (isPreview(request)) return previewSuccess(); + return signedResult(wallet, request, (tron, api, current) -> + tron.usdtTrans(api, current.getToken(), request.getToAddress().trim(), + request.getAmount().toPlainString())); + } + + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/stake") + public AjaxResult stake(@RequestBody WalletOperationRequest request) { + final WalletAddressPlus wallet = requireWallet(request); + validateAmount(request); + validateResource(request); + if (isPreview(request)) return previewSuccess(); + return signedResult(wallet, request, (tron, api, current) -> + tron.stakeTrxBalance(api, current.getToken(), request.getAmount(), request.getResourceCode())); + } + + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/unstake") + public AjaxResult unstake(@RequestBody WalletOperationRequest request) { + final WalletAddressPlus wallet = requireWallet(request); + validateAmount(request); + validateResource(request); + if (isPreview(request)) return previewSuccess(); + return signedResult(wallet, request, (tron, api, current) -> + tron.unstakeTrxBalance(api, current.getToken(), request.getAmount(), request.getResourceCode())); + } + + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/delegate") + public AjaxResult delegate(@RequestBody WalletOperationRequest request) { + final WalletAddressPlus wallet = requireWallet(request); + validateAmount(request); + validateTarget(request); + validateResource(request); + if (isPreview(request)) return previewSuccess(); + return signedResult(wallet, request, (tron, api, current) -> + tron.delegateResourceV2(api, current.getToken(), request.getToAddress().trim(), + request.getAmount(), request.getResourceCode())); + } + + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/undelegate") + public AjaxResult undelegate(@RequestBody WalletOperationRequest request) { + final WalletAddressPlus wallet = requireWallet(request); + validateAmount(request); + validateTarget(request); + validateResource(request); + if (isPreview(request)) return previewSuccess(); + return signedResult(wallet, request, (tron, api, current) -> + tron.unDelegateResourceV2(api, current.getToken(), request.getToAddress().trim(), + request.getAmount(), request.getResourceCode())); + } + + @PreAuthorize("@ss.hasPermi('system:address:operate') or @ss.hasPermi('system:address:user-query')") + @PostMapping("/operations/cancel-unstake") + public AjaxResult cancelUnstake(@RequestBody WalletOperationRequest request) { + final WalletAddressPlus wallet = requireWallet(request); + if (isPreview(request)) return previewSuccess(); + return signedResult(wallet, request, (tron, api, current) -> + tron.cancleUnstakeTrxBalance(api, current.getToken())); + } + + private AjaxResult signedResult(WalletAddressPlus wallet, WalletOperationRequest request, + WalletSigningService.SignedOperation operation) { + try { + Object result = walletSigningService.execute(wallet, request.getConfigurationPassword(), operation); + return AjaxResult.success(result); + } finally { + // 尽快解除请求对象对密码字符串的引用,且禁止在日志中输出整个请求对象。 + request.setConfigurationPassword(null); + } + } + + private WalletAddressPlus requireWallet(WalletOperationRequest request) { + if (request == null || request.getWalletId() == null) { + throw new com.ruoyi.common.exception.CustomException("钱包不能为空"); + } + WalletAddressPlus wallet = walletAddressService.getById(request.getWalletId()); + if (wallet == null) { + throw new com.ruoyi.common.exception.CustomException("钱包不存在"); + } + if (!SecurityUtils.isAdmin(getUserId()) && !getUserId().equals(wallet.getUserId())) { + throw new com.ruoyi.common.exception.CustomException("无权访问该钱包"); + } + return wallet; + } + + private void validateAmount(WalletOperationRequest request) { + if (request.getAmount() == null || request.getAmount().signum() <= 0) { + throw new com.ruoyi.common.exception.CustomException("金额必须大于 0"); + } + } + + private void validateTarget(WalletOperationRequest request) { + if (request.getToAddress() == null || request.getToAddress().trim().isEmpty()) { + throw new com.ruoyi.common.exception.CustomException("目标地址不能为空"); + } + } + + private void validateResource(WalletOperationRequest request) { + if (request.getResourceCode() == null + || (request.getResourceCode().intValue() != 0 && request.getResourceCode().intValue() != 1)) { + throw new com.ruoyi.common.exception.CustomException("资源类型只能为 0(带宽)或 1(能量)"); + } + } + + private boolean isPreview(WalletOperationRequest request) { + return !Boolean.TRUE.equals(request.getBroadcast()); + } + + private AjaxResult previewSuccess() { + return AjaxResult.success("预演模式:已通过参数校验,未解密钱包且未广播交易"); } @PreAuthorize("@ss.hasPermi('system:address:getByIds')" ) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java index 58a04f5..589cd58 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletOperationRequest.java @@ -1,5 +1,6 @@ package com.ruoyi.system.domain.vo; +import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; /** 管理端钱包操作请求;私钥不允许从请求传入。 */ @@ -9,6 +10,9 @@ public class WalletOperationRequest { private BigDecimal amount; private Integer resourceCode; private Boolean broadcast; + /** 配置密码仅用于本次请求解锁助记词,禁止持久化或输出日志。 */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + private String configurationPassword; public Long getWalletId() { return walletId; } public void setWalletId(Long walletId) { this.walletId = walletId; } @@ -20,4 +24,6 @@ public class WalletOperationRequest { public void setResourceCode(Integer resourceCode) { this.resourceCode = resourceCode; } public Boolean getBroadcast() { return broadcast; } public void setBroadcast(Boolean broadcast) { this.broadcast = broadcast; } + public String getConfigurationPassword() { return configurationPassword; } + public void setConfigurationPassword(String configurationPassword) { this.configurationPassword = configurationPassword; } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletSigningService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletSigningService.java new file mode 100644 index 0000000..033d3da --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletSigningService.java @@ -0,0 +1,145 @@ +package com.ruoyi.system.service; + +import com.ruoyi.common.exception.CustomException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.demo.WalletEnvelopeEncryptionDemo; +import com.ruoyi.system.domain.UsdtConfig; +import com.ruoyi.system.domain.WalletAddressPlus; +import com.ruoyi.system.mapper.UsdtConfigMapper; +import org.bitcoinj.crypto.ChildNumber; +import org.bitcoinj.crypto.DeterministicKey; +import org.bitcoinj.crypto.HDPath; +import org.bitcoinj.crypto.MnemonicCode; +import org.bitcoinj.wallet.DeterministicKeyChain; +import org.bitcoinj.wallet.DeterministicSeed; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.tron.common.crypto.ECKey; +import org.tron.trident.core.ApiWrapper; +import org.tron.trident.utils.Base58Check; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; + +/** 使用配置密码在内存中解锁指定 HD 钱包,并执行需要签名的链上操作。 */ +@Service +public class WalletSigningService { + @Autowired + private UsdtConfigMapper usdtConfigMapper; + @Autowired + private TronServiceProvider tronServiceProvider; + + public T execute(WalletAddressPlus wallet, String configurationPassword, + SignedOperation operation) { + validate(wallet, configurationPassword, operation); + List configs = usdtConfigMapper.selectUsdtConfigList(new UsdtConfig()); + if (configs == null || configs.isEmpty()) { + throw new CustomException("全局钱包配置不存在"); + } + + char[] password = configurationPassword.toCharArray(); + char[] mnemonic = null; + byte[] privateKey = null; + ApiWrapper api = null; + try { + UsdtConfig config = configs.get(0); + mnemonic = WalletEnvelopeEncryptionDemo.unlock(toEnvelope(config), password); + DerivedKey derived = derive(new String(mnemonic), parseIndex(wallet.getTokenIndex())); + privateKey = derived.privateKey; + if (!wallet.getToken().equals(derived.address)) { + throw new CustomException("钱包地址与派生索引不匹配,已拒绝签名"); + } + ITronService tronService = tronServiceProvider.getCurrentService(); + api = tronService.buildApiWrapper(toHex(privateKey)); + return operation.execute(tronService, api, wallet); + } catch (SecurityException e) { + throw new CustomException("配置密码错误"); + } catch (CustomException e) { + throw e; + } catch (Exception e) { + throw new CustomException("钱包解密或链上签名操作失败", e); + } finally { + if (api != null) { + api.close(); + } + Arrays.fill(password, '\0'); + if (mnemonic != null) { + Arrays.fill(mnemonic, '\0'); + } + if (privateKey != null) { + Arrays.fill(privateKey, (byte) 0); + } + } + } + + private void validate(WalletAddressPlus wallet, String password, SignedOperation operation) { + if (wallet == null || StringUtils.isBlank(wallet.getToken())) { + throw new CustomException("钱包不存在"); + } + if (StringUtils.isBlank(password)) { + throw new CustomException("配置密码不能为空"); + } + if (operation == null) { + throw new CustomException("签名操作不能为空"); + } + } + + private int parseIndex(String tokenIndex) { + try { + int index = Integer.parseInt(tokenIndex); + if (index < 0 || index > 10000) { + throw new NumberFormatException(); + } + return index; + } catch (Exception e) { + throw new CustomException("钱包派生索引无效"); + } + } + + private WalletEnvelopeEncryptionDemo.EncryptedEnvelope toEnvelope(UsdtConfig config) { + if (config.getVersion() == null || config.getIterations() == null) { + throw new CustomException("钱包加密信封数据不完整"); + } + return new WalletEnvelopeEncryptionDemo.EncryptedEnvelope( + config.getVersion().intValue(), config.getEncryptionAlgorithm(), config.getPasswordKdf(), + config.getIterations().intValue(), config.getEncryptedMnemonic(), config.getMnemonicNonce(), + config.getEncryptedDek(), config.getDekNonce(), config.getKeySalt(), + config.getPasswordSalt(), config.getPasswordHash()); + } + + private DerivedKey derive(String mnemonic, int index) throws Exception { + List words = Arrays.asList(mnemonic.trim().toLowerCase().split("\\s+")); + MnemonicCode.INSTANCE.check(words); + DeterministicSeed seed = DeterministicSeed.ofMnemonic(words, ""); + DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed).build(); + HDPath base = HDPath.M().extend(new ChildNumber(44, true), new ChildNumber(195, true), + new ChildNumber(0, true), ChildNumber.ZERO); + DeterministicKey key = chain.getKeyByPath(base.extend(new ChildNumber(index, false)), true); + byte[] bytes = key.getPrivKeyBytes(); + String address = Base58Check.bytesToBase58(ECKey.fromPrivate(new BigInteger(1, bytes)).getAddress()); + return new DerivedKey(bytes, address); + } + + private String toHex(byte[] bytes) { + StringBuilder result = new StringBuilder(bytes.length * 2); + for (byte value : bytes) { + result.append(String.format("%02x", value)); + } + return result.toString(); + } + + public interface SignedOperation { + T execute(ITronService tronService, ApiWrapper api, WalletAddressPlus wallet) throws Exception; + } + + private static final class DerivedKey { + private final byte[] privateKey; + private final String address; + + private DerivedKey(byte[] privateKey, String address) { + this.privateKey = privateKey; + this.address = address; + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java index 512864c..12cd76a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java @@ -36,6 +36,7 @@ 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.core.NodeType; +import org.tron.trident.core.key.KeyPair; import org.tron.trident.core.contract.Contract; import org.tron.trident.core.contract.Trc20Contract; import org.tron.trident.core.exceptions.IllegalException; @@ -85,8 +86,12 @@ public class TronNileServiceImpl implements ITronService { @Override public ApiWrapper buildApiWrapper() { - ApiWrapper apiWrapper = ApiWrapper.ofNile(null); - return apiWrapper; + /* + * Trident 0.10.0 的 ApiWrapper 即使只执行查询,也会在构造时解析私钥。 + * 因此不能向 ofNile 传 null。这里使用一次性随机密钥初始化客户端; + * 密钥只存在于当前 ApiWrapper 内存中,不保存、不输出,也不用于业务交易签名。 + */ + return ApiWrapper.ofNile(KeyPair.generate().toPrivateKey()); } @Override diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java index ee7ba31..e35e7d3 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java @@ -37,6 +37,7 @@ import org.tron.trident.core.NodeType; import org.tron.trident.core.contract.Contract; import org.tron.trident.core.contract.Trc20Contract; import org.tron.trident.core.exceptions.IllegalException; +import org.tron.trident.core.key.KeyPair; import org.tron.trident.proto.Chain; import org.tron.trident.proto.Common; import org.tron.trident.proto.Response; @@ -80,13 +81,18 @@ public class TronProServiceImpl implements ITronService { @Override public ApiWrapper buildApiWrapper(String privateKey) { return ApiWrapper.ofMainnet(privateKey, - TronServiceSupport.requiredEnvironment("TRON_PRO_API_KEY")); + tronscanApiKey()); } @Override public ApiWrapper buildApiWrapper() { - return ApiWrapper.ofMainnet(null, - TronServiceSupport.requiredEnvironment("TRON_PRO_API_KEY")); + /* + * Trident 0.10.0 的 ApiWrapper 即使只执行查询,也会在构造时解析私钥。 + * 因此不能向 ofNile 传 null。这里使用一次性随机密钥初始化客户端; + * 密钥只存在于当前 ApiWrapper 内存中,不保存、不输出,也不用于业务交易签名。 + */ + return ApiWrapper.ofMainnet(KeyPair.generate().toPrivateKey(), + tronscanApiKey()); } private static byte[] keccak256(byte[] input) {