新增tron加密逻辑
This commit is contained in:
1 parent
009955d560
commit
00a4a08c70
18 files changed
+1071
-55
No files matched your search
+2
-11
@@ -50,18 +50,14 @@ public class WalletAddressController extends BaseController {
|
||||
if (wallet.getUserId() != null && !SecurityUtils.isAdmin(getUserId()) && !wallet.getUserId().equals(getUserId())) {
|
||||
return AjaxResult.error("无权访问该钱包");
|
||||
}
|
||||
if (wallet.getTokenKey() == null || wallet.getTokenKey().trim().isEmpty()) {
|
||||
return AjaxResult.error("钱包未配置受控私钥");
|
||||
}
|
||||
ApiWrapper api = null;
|
||||
try {
|
||||
api = tronService.buildApiWrapper(wallet.getTokenKey());
|
||||
api = tronService.buildApiWrapper();
|
||||
wallet.setTrxBalance(tronService.getTRxBalance(api, wallet.getToken()));
|
||||
wallet.setUsdtBalance(tronService.getUsdtBalance(api, wallet.getToken()));
|
||||
com.ruoyi.system.domain.vo.EnergyAndBandwidthVo resource = tronService.energyAndBandwidth(wallet.getToken());
|
||||
wallet.setEnergyNum(resource.getEnergy().max(BigDecimal.ZERO).longValue());
|
||||
wallet.setBandwidthNum(resource.getBandwidth().max(BigDecimal.ZERO).longValue());
|
||||
wallet.setTokenKey(null);
|
||||
return AjaxResult.success(wallet);
|
||||
} catch (Exception ex) {
|
||||
return AjaxResult.error("链上查询失败,请稍后重试");
|
||||
@@ -76,18 +72,13 @@ public class WalletAddressController extends BaseController {
|
||||
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 (wallet.getTokenKey() == null || wallet.getTokenKey().trim().isEmpty()) return AjaxResult.error("钱包未配置受控私钥");
|
||||
try {
|
||||
String derived = Base58Check.bytesToBase58(ECKey.fromPrivate(new BigInteger(wallet.getTokenKey().trim(), 16)).getAddress());
|
||||
if (!derived.equals(wallet.getToken())) return AjaxResult.error("钱包私钥与地址不匹配");
|
||||
} catch (Exception ex) { 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 {
|
||||
api = tronService.buildApiWrapper(wallet.getTokenKey());
|
||||
api = tronService.buildApiWrapper();
|
||||
String tx;
|
||||
BigDecimal amount = request.getAmount();
|
||||
if ("trx".equalsIgnoreCase(type)) tx = tronService.trxTrans(api, wallet.getToken(), request.getToAddress(), amount);
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Signature;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Ed25519 使用示例。
|
||||
*
|
||||
* Ed25519 只能签名和验签,不能直接加密/解密;这里用 AES-256-GCM 演示加密解密。
|
||||
* 真正的公钥加密应使用 X25519 协商共享密钥,再使用 AES-GCM 加密业务数据。
|
||||
* 本示例显式使用 Bouncy Castle provider,因此可兼容 JDK 8。
|
||||
*/
|
||||
public final class Ed25519CryptoDemo {
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private Ed25519CryptoDemo() { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// JDK 8 does not provide Ed25519; register Bouncy Castle explicitly.
|
||||
if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
|
||||
String message = "TRON payment payload";
|
||||
|
||||
KeyPairGenerator edGenerator = KeyPairGenerator.getInstance("Ed25519", "BC");
|
||||
KeyPair signingKeys = edGenerator.generateKeyPair();
|
||||
byte[] signature = sign(message.getBytes(StandardCharsets.UTF_8), signingKeys);
|
||||
boolean verified = verify(message.getBytes(StandardCharsets.UTF_8), signature, signingKeys);
|
||||
|
||||
System.out.println("Ed25519 public key: " + Base64.getEncoder().encodeToString(signingKeys.getPublic().getEncoded()));
|
||||
System.out.println("Ed25519 private key: " + Base64.getEncoder().encodeToString(signingKeys.getPrivate().getEncoded()));
|
||||
System.out.println("Signature: " + Base64.getEncoder().encodeToString(signature));
|
||||
System.out.println("Signature valid: " + verified);
|
||||
|
||||
AesEnvelope encrypted = encrypt(message.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] decrypted = decrypt(encrypted);
|
||||
System.out.println("AES-GCM ciphertext: " + Base64.getEncoder().encodeToString(encrypted.ciphertext));
|
||||
System.out.println("AES-GCM plaintext: " + new String(decrypted, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static byte[] sign(byte[] message, KeyPair keyPair) throws Exception {
|
||||
Signature signer = Signature.getInstance("Ed25519", "BC");
|
||||
signer.initSign(keyPair.getPrivate());
|
||||
signer.update(message);
|
||||
return signer.sign();
|
||||
}
|
||||
|
||||
public static boolean verify(byte[] message, byte[] signature, KeyPair keyPair) throws Exception {
|
||||
Signature verifier = Signature.getInstance("Ed25519", "BC");
|
||||
verifier.initVerify(keyPair.getPublic());
|
||||
verifier.update(message);
|
||||
return verifier.verify(signature);
|
||||
}
|
||||
|
||||
public static AesEnvelope encrypt(byte[] plaintext) throws Exception {
|
||||
KeyGenerator generator = KeyGenerator.getInstance("AES");
|
||||
generator.init(256);
|
||||
SecretKey key = generator.generateKey();
|
||||
byte[] nonce = new byte[12];
|
||||
RANDOM.nextBytes(nonce);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce));
|
||||
return new AesEnvelope(key, nonce, cipher.doFinal(plaintext));
|
||||
}
|
||||
|
||||
public static byte[] decrypt(AesEnvelope envelope) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, envelope.key, new GCMParameterSpec(128, envelope.nonce));
|
||||
return cipher.doFinal(envelope.ciphertext);
|
||||
}
|
||||
|
||||
public static final class AesEnvelope {
|
||||
private final SecretKey key;
|
||||
private final byte[] nonce;
|
||||
private final byte[] ciphertext;
|
||||
|
||||
private AesEnvelope(SecretKey key, byte[] nonce, byte[] ciphertext) {
|
||||
this.key = key;
|
||||
this.nonce = nonce;
|
||||
this.ciphertext = ciphertext;
|
||||
}
|
||||
|
||||
public byte[] getEncodedKey() { return key.getEncoded().clone(); }
|
||||
public byte[] getNonce() { return nonce.clone(); }
|
||||
public byte[] getCiphertext() { return ciphertext.clone(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* RSA 非对称加密示例,兼容 JDK 8。
|
||||
*
|
||||
* 使用 RSA-OAEP-SHA256,避免 RSA/ECB/PKCS1Padding 的旧式填充。
|
||||
* RSA 只能加密有限长度数据;生产环境建议 RSA 加密随机 AES 密钥,AES-GCM 加密正文。
|
||||
*/
|
||||
public final class RsaEncryptionDemo {
|
||||
private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
|
||||
|
||||
private RsaEncryptionDemo() { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String plaintext = "myEpusdt RSA encryption demo";
|
||||
KeyPair keyPair = generateKeyPair(2048);
|
||||
|
||||
String publicKey = encodePublicKey(keyPair.getPublic());
|
||||
String privateKey = encodePrivateKey(keyPair.getPrivate());
|
||||
String ciphertext = encrypt(plaintext, publicKey);
|
||||
String decrypted = decrypt(ciphertext, privateKey);
|
||||
|
||||
System.out.println("Public key (X.509/Base64): " + publicKey);
|
||||
System.out.println("Private key (PKCS#8/Base64): " + privateKey);
|
||||
System.out.println("Ciphertext (Base64): " + ciphertext);
|
||||
System.out.println("Plaintext: " + decrypted);
|
||||
}
|
||||
|
||||
public static KeyPair generateKeyPair(int keySize) throws Exception {
|
||||
if (keySize < 2048) throw new IllegalArgumentException("RSA 密钥长度不能小于 2048 位");
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(keySize);
|
||||
return generator.generateKeyPair();
|
||||
}
|
||||
|
||||
public static String encrypt(String plaintext, String publicKeyBase64) throws Exception {
|
||||
PublicKey publicKey = readPublicKey(publicKeyBase64);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
public static String decrypt(String ciphertextBase64, String privateKeyBase64) throws Exception {
|
||||
PrivateKey privateKey = readPrivateKey(privateKeyBase64);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
byte[] plaintext = cipher.doFinal(Base64.getDecoder().decode(ciphertextBase64));
|
||||
return new String(plaintext, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static String encodePublicKey(PublicKey key) {
|
||||
return Base64.getEncoder().encodeToString(key.getEncoded());
|
||||
}
|
||||
|
||||
public static String encodePrivateKey(PrivateKey key) {
|
||||
return Base64.getEncoder().encodeToString(key.getEncoded());
|
||||
}
|
||||
|
||||
public static PublicKey readPublicKey(String base64) throws Exception {
|
||||
KeyFactory factory = KeyFactory.getInstance("RSA");
|
||||
return factory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(base64)));
|
||||
}
|
||||
|
||||
public static PrivateKey readPrivateKey(String base64) throws Exception {
|
||||
KeyFactory factory = KeyFactory.getInstance("RSA");
|
||||
return factory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
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.bouncycastle.jcajce.provider.digest.Keccak;
|
||||
import org.bouncycastle.math.ec.ECPoint;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* TRON 钱包信封加密演示。
|
||||
* <p>
|
||||
* 助记词由随机 DEK 使用 AES-256-GCM 加密;DEK 再由配置密码派生的 KEK 加密。
|
||||
* 配置密码验证哈希单独使用一组 salt。此类仅用于演示,不负责数据库持久化或业务授权。
|
||||
*/
|
||||
public final class WalletEnvelopeEncryptionDemo {
|
||||
private static final int KEY_BYTES = 32;
|
||||
private static final int SALT_BYTES = 16;
|
||||
private static final int NONCE_BYTES = 12;
|
||||
/** Demo default; production should benchmark and normally use a much higher value. */
|
||||
private static final int ITERATIONS = readIterations();
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static final BigInteger BASE58 = BigInteger.valueOf(58);
|
||||
private static final char[] BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
|
||||
private WalletEnvelopeEncryptionDemo() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建钱包主密钥。
|
||||
*
|
||||
* 流程:
|
||||
* 1. 生成 128 位随机熵并转换为 12 个助记词。
|
||||
* 2. 生成随机 DEK(Data Encryption Key)。
|
||||
* 3. DEK 使用 AES-256-GCM 加密助记词,得到 encryptedMnemonic。
|
||||
* 4. 配置密码通过 PBKDF2 派生 KEK(Key Encryption Key)。
|
||||
* 5. KEK 使用 AES-256-GCM 加密 DEK,得到 encryptedDek。
|
||||
* 6. 同一助记词按 m/44'/195'/0'/0/i 派生主钱包和子钱包地址。
|
||||
*
|
||||
* 数据库只应保存返回对象中的 envelope 字段和钱包地址/索引,不能保存 mnemonic。
|
||||
*/
|
||||
public static DemoBundle create(char[] configurationPassword, int childCount) throws Exception {
|
||||
requirePassword(configurationPassword);
|
||||
if (childCount < 0 || childCount > 10000)
|
||||
throw new IllegalArgumentException("子钱包数量必须在 0 到 10000 之间");
|
||||
byte[] entropy = random(16);
|
||||
List<String> words = MnemonicCode.INSTANCE.toMnemonic(entropy);
|
||||
Arrays.fill(entropy, (byte) 0);
|
||||
String mnemonic = join(words);
|
||||
EncryptedEnvelope envelope = encrypt(mnemonic, configurationPassword);
|
||||
List<DerivedWallet> wallets = deriveWallets(mnemonic, childCount + 1);
|
||||
return new DemoBundle(mnemonic, envelope, wallets);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解锁信封。
|
||||
*
|
||||
* 先用 passwordSalt 验证密码,再用 keySalt 派生 KEK,解开 encryptedDek,
|
||||
* 最后用 DEK 解开 encryptedMnemonic。AES-GCM 会同时校验密文完整性。
|
||||
* 返回的助记词只允许短时间存在于内存,调用方使用后必须清零 char[]。
|
||||
*/
|
||||
public static char[] unlock(EncryptedEnvelope envelope, char[] configurationPassword) throws Exception {
|
||||
requirePassword(configurationPassword);
|
||||
verifyPassword(envelope, configurationPassword);
|
||||
byte[] kek = deriveKey(configurationPassword, decode(envelope.keySalt), envelope.iterations);
|
||||
byte[] dek = null;
|
||||
byte[] plaintext = null;
|
||||
try {
|
||||
dek = crypt(Cipher.DECRYPT_MODE, decode(envelope.encryptedDek), kek, decode(envelope.dekNonce));
|
||||
plaintext = crypt(Cipher.DECRYPT_MODE, decode(envelope.encryptedMnemonic), dek, decode(envelope.mnemonicNonce));
|
||||
return new String(plaintext, StandardCharsets.UTF_8).toCharArray();
|
||||
} finally {
|
||||
Arrays.fill(kek, (byte) 0);
|
||||
if (dek != null) Arrays.fill(dek, (byte) 0);
|
||||
if (plaintext != null) Arrays.fill(plaintext, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮换配置密码。
|
||||
*
|
||||
* 这是“密码轮换”,不是“助记词轮换”:
|
||||
* 旧密码解开 DEK 后,用新密码派生的新 KEK 重新加密 DEK;助记词密文不变,
|
||||
* 因此主钱包、子钱包地址和历史订单映射保持不变。每次使用新的 salt 和 nonce,
|
||||
* 并将 version 加一。生产环境应在数据库事务中配合旧 version 做乐观锁更新。
|
||||
*/
|
||||
public static EncryptedEnvelope rotateConfigurationPassword(EncryptedEnvelope oldEnvelope,
|
||||
char[] oldPassword,
|
||||
char[] newPassword) throws Exception {
|
||||
requirePassword(oldPassword);
|
||||
requirePassword(newPassword);
|
||||
verifyPassword(oldEnvelope, oldPassword);
|
||||
byte[] oldKek = deriveKey(oldPassword, decode(oldEnvelope.keySalt), oldEnvelope.iterations);
|
||||
byte[] dek = null;
|
||||
try {
|
||||
dek = crypt(Cipher.DECRYPT_MODE, decode(oldEnvelope.encryptedDek), oldKek, decode(oldEnvelope.dekNonce));
|
||||
byte[] newSalt = random(SALT_BYTES);
|
||||
byte[] newNonce = random(NONCE_BYTES);
|
||||
byte[] newPasswordSalt = random(SALT_BYTES);
|
||||
byte[] newKek = deriveKey(newPassword, newSalt, ITERATIONS);
|
||||
byte[] wrappedDek;
|
||||
try {
|
||||
wrappedDek = crypt(Cipher.ENCRYPT_MODE, dek, newKek, newNonce);
|
||||
} finally {
|
||||
Arrays.fill(newKek, (byte) 0);
|
||||
}
|
||||
byte[] passwordHash = deriveKey(newPassword, newPasswordSalt, ITERATIONS);
|
||||
return new EncryptedEnvelope(oldEnvelope.version + 1, "AES-256-GCM", "PBKDF2-HMAC-SHA256", ITERATIONS,
|
||||
encode(oldEnvelope.encryptedMnemonicBytes()), encode(oldEnvelope.mnemonicNonceBytes()),
|
||||
encode(wrappedDek), encode(newNonce), encode(newSalt), encode(newPasswordSalt), encode(passwordHash));
|
||||
} finally {
|
||||
Arrays.fill(oldKek, (byte) 0);
|
||||
if (dek != null) Arrays.fill(dek, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整演示设置密码、旧密码解锁、密码轮换和新密码解锁。
|
||||
* 返回的演示结果会包含新生成的助记词以便离线备份,但不包含密码、DEK 或 KEK;生产代码不要暴露该结果。
|
||||
*/
|
||||
public static RotationDemoResult runPasswordRotationDemo(char[] oldPassword, char[] newPassword) throws Exception {
|
||||
requirePassword(oldPassword);
|
||||
requirePassword(newPassword);
|
||||
DemoBundle created = create(oldPassword, 5);
|
||||
List<DerivedWallet> beforeRotation = created.wallets;
|
||||
|
||||
char[] oldUnlockedMnemonic = unlock(created.envelope, oldPassword);
|
||||
List<DerivedWallet> addressesBefore = deriveWallets(new String(oldUnlockedMnemonic), beforeRotation.size());
|
||||
Arrays.fill(oldUnlockedMnemonic, '\0');
|
||||
|
||||
EncryptedEnvelope rotatedEnvelope = rotateConfigurationPassword(created.envelope, oldPassword, newPassword);
|
||||
boolean oldPasswordRejected;
|
||||
try {
|
||||
char[] shouldNotUnlock = unlock(rotatedEnvelope, oldPassword);
|
||||
Arrays.fill(shouldNotUnlock, '\0');
|
||||
oldPasswordRejected = false;
|
||||
} catch (SecurityException expected) {
|
||||
oldPasswordRejected = true;
|
||||
}
|
||||
|
||||
char[] newUnlockedMnemonic = unlock(rotatedEnvelope, newPassword);
|
||||
List<DerivedWallet> addressesAfter = deriveWallets(new String(newUnlockedMnemonic), beforeRotation.size());
|
||||
Arrays.fill(newUnlockedMnemonic, '\0');
|
||||
boolean addressesUnchanged = sameAddresses(addressesBefore, addressesAfter)
|
||||
&& sameAddresses(beforeRotation, addressesAfter);
|
||||
return new RotationDemoResult(created.envelope.version, rotatedEnvelope.version,
|
||||
oldPasswordRejected, true, addressesUnchanged, created.mnemonic, rotatedEnvelope, addressesAfter);
|
||||
}
|
||||
|
||||
private static boolean sameAddresses(List<DerivedWallet> left, List<DerivedWallet> right) {
|
||||
if (left.size() != right.size()) return false;
|
||||
for (int i = 0; i < left.size(); i++) {
|
||||
if (left.get(i).index != right.get(i).index || !left.get(i).address.equals(right.get(i).address))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从同一助记词派生主钱包及子钱包,索引 0 为主钱包。
|
||||
* token_index 必须与此处的 index 一致,路径固定为 m/44'/195'/0'/0/i。
|
||||
* 这里只返回地址和派生路径,私钥不进入结果对象,避免误传到前端或日志。
|
||||
*/
|
||||
public static List<DerivedWallet> deriveWallets(String mnemonic, int walletCount) throws Exception {
|
||||
if (walletCount < 1 || walletCount > 10001)
|
||||
throw new IllegalArgumentException("钱包数量必须在 1 到 10001 之间");
|
||||
List<String> words = Arrays.asList(mnemonic.trim().toLowerCase().split("\\s+"));
|
||||
MnemonicCode.INSTANCE.check(words);
|
||||
DeterministicSeed seed = DeterministicSeed.ofMnemonic(words, "");
|
||||
DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
|
||||
HDPath basePath = HDPath.M().extend(new ChildNumber(44, true), new ChildNumber(195, true),
|
||||
new ChildNumber(0, true), ChildNumber.ZERO);
|
||||
List<DerivedWallet> wallets = new ArrayList<DerivedWallet>(walletCount);
|
||||
for (int index = 0; index < walletCount; index++) {
|
||||
HDPath path = basePath.extend(new ChildNumber(index, false));
|
||||
DeterministicKey key = keyChain.getKeyByPath(path, true);
|
||||
ECPoint publicPoint = key.getPubKeyPoint();
|
||||
byte[] uncompressed = publicPoint.getEncoded(false);
|
||||
byte[] publicKey = Arrays.copyOfRange(uncompressed, 1, uncompressed.length);
|
||||
byte[] hash = new Keccak.Digest256().digest(publicKey);
|
||||
byte[] address = new byte[21];
|
||||
address[0] = 0x41;
|
||||
System.arraycopy(hash, 12, address, 1, 20);
|
||||
wallets.add(new DerivedWallet(index, "m/44'/195'/0'/0/" + index, base58Check(address)));
|
||||
Arrays.fill(uncompressed, (byte) 0);
|
||||
Arrays.fill(publicKey, (byte) 0);
|
||||
Arrays.fill(hash, (byte) 0);
|
||||
Arrays.fill(address, (byte) 0);
|
||||
}
|
||||
return wallets;
|
||||
}
|
||||
|
||||
/** 执行信封加密;password 只在本方法调用期间使用,不写入任何持久化对象。 */
|
||||
private static EncryptedEnvelope encrypt(String mnemonic, char[] password) throws Exception {
|
||||
byte[] dek = random(KEY_BYTES), keySalt = random(SALT_BYTES), dekNonce = random(NONCE_BYTES);
|
||||
byte[] mnemonicNonce = random(NONCE_BYTES), passwordSalt = random(SALT_BYTES);
|
||||
byte[] kek = deriveKey(password, keySalt, ITERATIONS);
|
||||
try {
|
||||
byte[] encryptedMnemonic = crypt(Cipher.ENCRYPT_MODE, mnemonic.getBytes(StandardCharsets.UTF_8), dek, mnemonicNonce);
|
||||
byte[] encryptedDek = crypt(Cipher.ENCRYPT_MODE, dek, kek, dekNonce);
|
||||
byte[] passwordHash = deriveKey(password, passwordSalt, ITERATIONS);
|
||||
return new EncryptedEnvelope(1, "AES-256-GCM", "PBKDF2-HMAC-SHA256", ITERATIONS,
|
||||
encode(encryptedMnemonic), encode(mnemonicNonce), encode(encryptedDek), encode(dekNonce),
|
||||
encode(keySalt), encode(passwordSalt), encode(passwordHash));
|
||||
} finally {
|
||||
Arrays.fill(dek, (byte) 0);
|
||||
Arrays.fill(kek, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void verifyPassword(EncryptedEnvelope envelope, char[] password) throws Exception {
|
||||
byte[] candidate = deriveKey(password, decode(envelope.passwordSalt), envelope.iterations);
|
||||
byte[] expected = decode(envelope.passwordHash);
|
||||
try {
|
||||
if (!MessageDigest.isEqual(candidate, expected)) throw new SecurityException("配置密码错误");
|
||||
} finally {
|
||||
Arrays.fill(candidate, (byte) 0);
|
||||
Arrays.fill(expected, (byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** PBKDF2 派生 256 位 KEK 或密码验证值;salt 和 iterations 必须随密文保存。 */
|
||||
private static byte[] deriveKey(char[] password, byte[] salt, int iterations) throws Exception {
|
||||
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, KEY_BYTES * 8);
|
||||
try {
|
||||
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
|
||||
} finally {
|
||||
spec.clearPassword();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] crypt(int mode, byte[] input, byte[] key, byte[] nonce) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(mode, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, nonce));
|
||||
return cipher.doFinal(input);
|
||||
}
|
||||
|
||||
private static String base58Check(byte[] payload) throws Exception {
|
||||
byte[] first = MessageDigest.getInstance("SHA-256").digest(payload);
|
||||
byte[] second = MessageDigest.getInstance("SHA-256").digest(first);
|
||||
byte[] checked = Arrays.copyOf(payload, payload.length + 4);
|
||||
System.arraycopy(second, 0, checked, payload.length, 4);
|
||||
BigInteger value = new BigInteger(1, checked);
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (value.signum() > 0) {
|
||||
BigInteger[] div = value.divideAndRemainder(BASE58);
|
||||
out.append(BASE58_ALPHABET[div[1].intValue()]);
|
||||
value = div[0];
|
||||
}
|
||||
for (byte b : checked) {
|
||||
if (b == 0) out.append(BASE58_ALPHABET[0]);
|
||||
else break;
|
||||
}
|
||||
Arrays.fill(first, (byte) 0);
|
||||
Arrays.fill(second, (byte) 0);
|
||||
Arrays.fill(checked, (byte) 0);
|
||||
return out.reverse().toString();
|
||||
}
|
||||
|
||||
private static byte[] random(int size) {
|
||||
byte[] bytes = new byte[size];
|
||||
RANDOM.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static String encode(byte[] bytes) {
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private static byte[] decode(String text) {
|
||||
return Base64.getDecoder().decode(text);
|
||||
}
|
||||
|
||||
private static String join(List<String> words) {
|
||||
StringBuilder value = new StringBuilder();
|
||||
for (String word : words) {
|
||||
if (value.length() > 0) value.append(' ');
|
||||
value.append(word);
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static void requirePassword(char[] password) {
|
||||
if (password == null || password.length < 10) throw new IllegalArgumentException("配置密码至少 10 位");
|
||||
}
|
||||
|
||||
private static int readIterations() {
|
||||
String configured = System.getProperty("wallet.demo.pbkdf2.iterations");
|
||||
int value = 10000;
|
||||
if (configured != null) {
|
||||
try { value = Integer.parseInt(configured); } catch (NumberFormatException ignored) { }
|
||||
}
|
||||
if (value < 10000 || value > 1000000) throw new IllegalArgumentException("PBKDF2 迭代次数必须在 10000 到 1000000 之间");
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 交互式演示:输入旧密码和新密码,验证轮换前后地址不变。
|
||||
* 仅在隔离的本机终端运行;生产服务绝不能打印 mnemonic、密码或私钥。
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
java.io.Console console = System.console();
|
||||
if (console == null) throw new IllegalStateException("请在交互式本机终端运行");
|
||||
char[] oldPassword = console.readPassword("Initial configuration password (10+ chars): ");
|
||||
char[] newPassword = console.readPassword("New configuration password (10+ chars): ");
|
||||
char[] confirmPassword = console.readPassword("Confirm new configuration password: ");
|
||||
if (newPassword == null || confirmPassword == null || !Arrays.equals(newPassword, confirmPassword)) {
|
||||
clear(oldPassword, newPassword, confirmPassword);
|
||||
throw new IllegalArgumentException("两次新密码不一致");
|
||||
}
|
||||
Arrays.fill(confirmPassword, '\0');
|
||||
try {
|
||||
RotationDemoResult result = runPasswordRotationDemo(oldPassword, newPassword);
|
||||
System.out.println("Mnemonic (write it down offline; never share or paste into support requests): " + result.mnemonic);
|
||||
System.out.println("Derived wallets (addresses only):");
|
||||
for (DerivedWallet wallet : result.wallets) System.out.println(wallet.path + " " + wallet.address);
|
||||
System.out.println("Password rotation: version " + result.oldVersion + " -> " + result.newVersion);
|
||||
System.out.println("Old password rejected: " + result.oldPasswordRejected);
|
||||
System.out.println("New password unlock succeeded: " + result.newPasswordUnlockSucceeded);
|
||||
System.out.println("Derived addresses unchanged: " + result.addressesUnchanged);
|
||||
System.out.println("Mnemonic encryption: " + result.envelope.encryptionAlgorithm
|
||||
+ ", KDF=" + result.envelope.passwordKdf + ", iterations=" + result.envelope.iterations);
|
||||
} finally {
|
||||
clear(oldPassword, newPassword);
|
||||
}
|
||||
}
|
||||
|
||||
private static void clear(char[]... values) {
|
||||
if (values == null) return;
|
||||
for (char[] value : values) if (value != null) Arrays.fill(value, '\0');
|
||||
}
|
||||
|
||||
public static final class DemoBundle {
|
||||
public final String mnemonic;
|
||||
public final EncryptedEnvelope envelope;
|
||||
public final List<DerivedWallet> wallets;
|
||||
|
||||
private DemoBundle(String mnemonic, EncryptedEnvelope envelope, List<DerivedWallet> wallets) {
|
||||
this.mnemonic = mnemonic;
|
||||
this.envelope = envelope;
|
||||
this.wallets = wallets;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class DerivedWallet {
|
||||
public final int index;
|
||||
public final String path;
|
||||
public final String address;
|
||||
|
||||
private DerivedWallet(int index, String path, String address) {
|
||||
this.index = index;
|
||||
this.path = path;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return path + " " + address;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class RotationDemoResult {
|
||||
public final int oldVersion;
|
||||
public final int newVersion;
|
||||
public final boolean oldPasswordRejected;
|
||||
public final boolean newPasswordUnlockSucceeded;
|
||||
public final boolean addressesUnchanged;
|
||||
/**
|
||||
* Sensitive: expose only in this local demo, never serialize or log in production.
|
||||
*/
|
||||
public final String mnemonic;
|
||||
public final EncryptedEnvelope envelope;
|
||||
public final List<DerivedWallet> wallets;
|
||||
|
||||
private RotationDemoResult(int oldVersion, int newVersion, boolean oldPasswordRejected,
|
||||
boolean newPasswordUnlockSucceeded, boolean addressesUnchanged,
|
||||
String mnemonic, EncryptedEnvelope envelope, List<DerivedWallet> wallets) {
|
||||
this.oldVersion = oldVersion;
|
||||
this.newVersion = newVersion;
|
||||
this.oldPasswordRejected = oldPasswordRejected;
|
||||
this.newPasswordUnlockSucceeded = newPasswordUnlockSucceeded;
|
||||
this.addressesUnchanged = addressesUnchanged;
|
||||
this.mnemonic = mnemonic;
|
||||
this.envelope = envelope;
|
||||
this.wallets = wallets;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 可持久化的密文 DTO;不包含明文助记词、DEK 或 KEK。
|
||||
*/
|
||||
public static final class EncryptedEnvelope {
|
||||
public final int version;
|
||||
public final String encryptionAlgorithm;
|
||||
public final String passwordKdf;
|
||||
public final int iterations;
|
||||
public final String encryptedMnemonic;
|
||||
public final String mnemonicNonce;
|
||||
public final String encryptedDek;
|
||||
public final String dekNonce;
|
||||
public final String keySalt;
|
||||
public final String passwordSalt;
|
||||
public final String passwordHash;
|
||||
|
||||
/**
|
||||
* 用于从数据库反序列化已持久化的信封字段。
|
||||
* 调用方只能传入密文、salt、nonce 等字段,绝不能把明文助记词放入此对象。
|
||||
*/
|
||||
public EncryptedEnvelope(int version, String encryptionAlgorithm, String passwordKdf, int iterations,
|
||||
String encryptedMnemonic, String mnemonicNonce, String encryptedDek,
|
||||
String dekNonce, String keySalt, String passwordSalt, String passwordHash) {
|
||||
this.version = version;
|
||||
this.encryptionAlgorithm = encryptionAlgorithm;
|
||||
this.passwordKdf = passwordKdf;
|
||||
this.iterations = iterations;
|
||||
this.encryptedMnemonic = encryptedMnemonic;
|
||||
this.mnemonicNonce = mnemonicNonce;
|
||||
this.encryptedDek = encryptedDek;
|
||||
this.dekNonce = dekNonce;
|
||||
this.keySalt = keySalt;
|
||||
this.passwordSalt = passwordSalt;
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
private byte[] encryptedMnemonicBytes() {
|
||||
return decode(encryptedMnemonic);
|
||||
}
|
||||
|
||||
private byte[] mnemonicNonceBytes() {
|
||||
return decode(mnemonicNonce);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.ruoyi.system.demo;
|
||||
|
||||
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.tron.common.crypto.ECKey;
|
||||
import org.tron.trident.core.ApiWrapper;
|
||||
import org.tron.trident.proto.Chain;
|
||||
import org.tron.trident.proto.Response;
|
||||
import org.tron.trident.utils.Base58Check;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 信封解密后使用 Trident 完成 TRX 转账的最小示例。
|
||||
*
|
||||
* <p>生产流程:数据库读取 EncryptedEnvelope -> 配置密码解锁助记词 ->
|
||||
* 按钱包索引派生私钥 -> 校验派生地址 -> 构造、签名并广播交易。</p>
|
||||
* <p>本示例只连接 Nile 测试网,严禁将测试代码改为主网后直接使用生产私钥。</p>
|
||||
*/
|
||||
public final class WalletEnvelopeTronTransferDemo {
|
||||
private WalletEnvelopeTronTransferDemo() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String passwordText = required("WALLET_CONFIG_PASSWORD");
|
||||
String privateKeyEnvelope = required("WALLET_ENVELOPE_JSON");
|
||||
String targetAddress = required("TRON_TEST_TO_ADDRESS");
|
||||
BigDecimal amountTrx = new BigDecimal(required("TRON_TEST_TRX_AMOUNT"));
|
||||
|
||||
// 实际项目中应使用 JSON 反序列化器将数据库字段映射为 EncryptedEnvelope。
|
||||
// 为避免示例伪造数据库格式,这里要求调用方在代码中加载 envelope 对象。
|
||||
throw new IllegalStateException("请在业务代码中反序列化 EncryptedEnvelope 后调用 transferOnNile()");
|
||||
}
|
||||
|
||||
/** 使用主钱包 index=0 转账;调用方负责从数据库加载 envelope。 */
|
||||
public static String transferOnNile(WalletEnvelopeEncryptionDemo.EncryptedEnvelope envelope,
|
||||
char[] configurationPassword,
|
||||
String targetAddress,
|
||||
BigDecimal amountTrx) throws Exception {
|
||||
if (envelope == null || targetAddress == null || amountTrx == null || amountTrx.signum() <= 0) {
|
||||
throw new IllegalArgumentException("信封、目标地址和金额不能为空,金额必须大于 0");
|
||||
}
|
||||
char[] mnemonic = WalletEnvelopeEncryptionDemo.unlock(envelope, configurationPassword);
|
||||
byte[] privateBytes = null;
|
||||
ApiWrapper api = null;
|
||||
try {
|
||||
DerivedPrivateKey derived = derivePrivateKey(new String(mnemonic), 0);
|
||||
privateBytes = derived.privateKey;
|
||||
String fromAddress = derived.address;
|
||||
api = ApiWrapper.ofNile(toHex(privateBytes));
|
||||
|
||||
long sun = amountTrx.movePointRight(6).longValueExact();
|
||||
Response.TransactionExtention extension = api.transfer(fromAddress, targetAddress.trim(), sun);
|
||||
Chain.Transaction signed = api.signTransaction(extension);
|
||||
return api.broadcastTransaction(signed);
|
||||
} finally {
|
||||
if (api != null) api.close();
|
||||
if (privateBytes != null) Arrays.fill(privateBytes, (byte) 0);
|
||||
Arrays.fill(mnemonic, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
/** 按 TRON BIP44 路径派生索引对应的私钥,仅供服务端内存使用。 */
|
||||
private static DerivedPrivateKey derivePrivateKey(String mnemonic, int index) throws Exception {
|
||||
List<String> 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[] privateKey = key.getPrivKeyBytes();
|
||||
String address = Base58Check.bytesToBase58(ECKey.fromPrivate(new BigInteger(1, privateKey)).getAddress());
|
||||
return new DerivedPrivateKey(privateKey, address);
|
||||
}
|
||||
|
||||
private static String toHex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder(bytes.length * 2);
|
||||
for (byte value : bytes) result.append(String.format("%02x", value));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private static String required(String name) {
|
||||
String value = System.getenv(name);
|
||||
if (value == null || value.trim().isEmpty()) throw new IllegalArgumentException(name + " 未配置");
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private static final class DerivedPrivateKey {
|
||||
private final byte[] privateKey;
|
||||
private final String address;
|
||||
|
||||
private DerivedPrivateKey(byte[] privateKey, String address) {
|
||||
this.privateKey = privateKey;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,10 +61,6 @@ public class WalletAddress extends BaseEntity
|
||||
@Excel(name = "子账号对应的索引位置")
|
||||
private String tokenIndex;
|
||||
|
||||
@Excel(name = "token key")
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
private String tokenKey;
|
||||
|
||||
/** usdt余额 */
|
||||
@Excel(name = "usdt余额")
|
||||
private BigDecimal usdtBalance;
|
||||
@@ -157,14 +153,6 @@ public class WalletAddress extends BaseEntity
|
||||
@Excel(name = "免费带宽总额")
|
||||
private Long bandwidthFreeAllNum;
|
||||
|
||||
public String getTokenKey() {
|
||||
return tokenKey;
|
||||
}
|
||||
|
||||
public void setTokenKey(String tokenKey) {
|
||||
this.tokenKey = tokenKey;
|
||||
}
|
||||
|
||||
public void setId(Long id)
|
||||
{
|
||||
this.id = id;
|
||||
|
||||
@@ -112,10 +112,6 @@ public class WalletAddressPlus implements Serializable
|
||||
@Excel(name = "已经投票数量")
|
||||
private Long votedNum;
|
||||
|
||||
@Excel(name = "token key")
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
private String tokenKey;
|
||||
|
||||
/** 质押还剩能用的带宽 */
|
||||
@Excel(name = "质押还剩能用的带宽")
|
||||
private Long bandwidthStakedNum;
|
||||
@@ -133,24 +129,16 @@ public class WalletAddressPlus implements Serializable
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTokenKey() {
|
||||
return tokenKey;
|
||||
}
|
||||
|
||||
public void setTokenKey(String tokenKey) {
|
||||
this.tokenKey = tokenKey;
|
||||
}
|
||||
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public void setToken(String token)
|
||||
public void setToken(String token)
|
||||
{
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public String getToken()
|
||||
public String getToken()
|
||||
{
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ public interface ITronService {
|
||||
String type();
|
||||
ApiWrapper buildApiWrapper(String privateKey);
|
||||
|
||||
ApiWrapper buildApiWrapper();
|
||||
|
||||
|
||||
String contractAddress();
|
||||
|
||||
String tronscanApiUrl();
|
||||
|
||||
@@ -84,6 +84,12 @@ public class TronNileServiceImpl implements ITronService {
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper() {
|
||||
ApiWrapper apiWrapper = ApiWrapper.ofNile(null);
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String contractAddress() {
|
||||
return "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";
|
||||
|
||||
@@ -11,15 +11,20 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Date;
|
||||
|
||||
/** 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。 */
|
||||
/**
|
||||
* 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。
|
||||
*/
|
||||
@Component
|
||||
public class TronPaymentScanner {
|
||||
@Autowired private IUsdtOrdersService orders;
|
||||
@Autowired private ITronService tron;
|
||||
@Autowired
|
||||
private IUsdtOrdersService orders;
|
||||
@Autowired
|
||||
private ITronService tron;
|
||||
private final RestTemplate http = new RestTemplate();
|
||||
|
||||
@Scheduled(fixedDelay = 30000L)
|
||||
@@ -28,18 +33,26 @@ public class TronPaymentScanner {
|
||||
if (order.getToken() == null || order.getActualAmount() == null) continue;
|
||||
try {
|
||||
String url = tron.tronscanApiUrl() + "/v1/accounts/" + order.getToken() + "/transactions/trc20?limit=200&only_confirmed=true&contract_address=" + tron.contractAddress();
|
||||
JSONObject root = JSON.parseObject(http.getForObject(url, String.class)); JSONArray data = root == null ? null : root.getJSONArray("data");
|
||||
JSONObject root = JSON.parseObject(http.getForObject(url, String.class));
|
||||
JSONArray data = root == null ? null : root.getJSONArray("data");
|
||||
if (data == null) continue;
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
JSONObject tx = data.getJSONObject(i);
|
||||
if (!order.getToken().equals(tx.getString("to"))) continue;
|
||||
BigDecimal value = new BigDecimal(tx.getString("value")).movePointLeft(6).setScale(6, RoundingMode.DOWN);
|
||||
if (value.compareTo(order.getActualAmount().setScale(6, RoundingMode.DOWN)) != 0) continue;
|
||||
String hash = tx.getString("transaction_id"); if (hash == null || hash.trim().isEmpty()) continue;
|
||||
if (orders.count(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getBlockTransactionId, hash)) > 0) continue;
|
||||
order.setBlockTransactionId(hash); order.setStatus(2L); order.setUpdatedAt(new Date()); orders.updateById(order); break;
|
||||
String hash = tx.getString("transaction_id");
|
||||
if (hash == null || hash.trim().isEmpty()) continue;
|
||||
if (orders.count(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getBlockTransactionId, hash)) > 0)
|
||||
continue;
|
||||
order.setBlockTransactionId(hash);
|
||||
order.setStatus(2L);
|
||||
order.setUpdatedAt(new Date());
|
||||
orders.updateById(order);
|
||||
break;
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,11 @@ public class TronProServiceImpl implements ITronService {
|
||||
return ApiWrapper.ofMainnet(privateKey, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper() {
|
||||
return ApiWrapper.ofMainnet(null, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae");
|
||||
}
|
||||
|
||||
private static byte[] keccak256(byte[] input) {
|
||||
Keccak.Digest256 digest = new Keccak.Digest256();
|
||||
return digest.digest(input);
|
||||
|
||||
@@ -167,6 +167,12 @@ public class TronShastaServiceImpl implements ITronService {
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiWrapper buildApiWrapper() {
|
||||
ApiWrapper apiWrapper = ApiWrapper.ofShasta(null);
|
||||
return apiWrapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String contractAddress() {
|
||||
return "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs";
|
||||
|
||||
+1
-2
@@ -35,12 +35,11 @@ public class UsdtAggregationExecutor {
|
||||
boolean failed = false;
|
||||
for (UsdtAggregationTaskItemPlus item : items) {
|
||||
WalletAddressPlus wallet = walletService.getByTokenAndAppId(item.getTokenAddress(), item.getAppId());
|
||||
if (wallet == null || wallet.getTokenKey() == null) { fail(item, "来源钱包不存在或未配置私钥"); failed = true; continue; }
|
||||
String tx = null;
|
||||
Exception last = null;
|
||||
for (int attempt = 0; attempt < 4 && tx == null; attempt++) {
|
||||
org.tron.trident.core.ApiWrapper api = null;
|
||||
try { api = tronService.buildApiWrapper(wallet.getTokenKey()); tx = tronService.usdtTrans(api, wallet.getToken(), item.getDistTokenAddress(), item.getOpeAmount().toPlainString()); }
|
||||
try { api = tronService.buildApiWrapper(); tx = tronService.usdtTrans(api, wallet.getToken(), item.getDistTokenAddress(), item.getOpeAmount().toPlainString()); }
|
||||
catch (Exception ex) { last = ex; }
|
||||
finally { if (api != null) api.close(); }
|
||||
}
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
|
||||
|
||||
@Override
|
||||
public boolean updateTronInfo(WalletAddressPlus walletAddressPlus) {
|
||||
ApiWrapper api = tronService.buildApiWrapper(walletAddressPlus.getTokenKey());
|
||||
ApiWrapper api = tronService.buildApiWrapper();
|
||||
BigDecimal amout = tronService.getUsdtBalance(api,walletAddressPlus.getToken());
|
||||
walletAddressPlus.setUsdtBalance(amout);
|
||||
amout = tronService.getTRxBalance(api,walletAddressPlus.getToken());
|
||||
|
||||
@@ -38,11 +38,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<result property="bandwidthStakedAllNum" column="bandwidth_staked_all_num" />
|
||||
<result property="bandwidthFreeNum" column="bandwidth_free_num" />
|
||||
<result property="bandwidthFreeAllNum" column="bandwidth_free_all_num" />
|
||||
<result property="tokenKey" column="token_key" />
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectWalletAddressVo">
|
||||
select id, token, status, created_at,token_key, updated_at, deleted_at, app_id, user_id, wallet_user_name, token_index, usdt_balance, trx_balance, energy_num, energy_all_num, energy_used_num, bandwidth_num, delegated_energy_trx_num, delegated_energy_value, acquired_delegated_energy_trx_num, acquired_delegated_energy_value, delegated_bandwidth_trx_num, delegated_bandwidth_value, acquired_delegated_bandwidth_trx_num, acquired_delegated_bandwidth_value, staked_trx_num, energy_staked_trx_num, bandwidth_staked_trx_num, vote_num, voted_num, bandwidth_staked_num, bandwidth_staked_all_num, bandwidth_free_num, bandwidth_free_all_num from wallet_address
|
||||
select id, token, status, created_at, updated_at, deleted_at, app_id, user_id, wallet_user_name, token_index, usdt_balance, trx_balance, energy_num, energy_all_num, energy_used_num, bandwidth_num, delegated_energy_trx_num, delegated_energy_value, acquired_delegated_energy_trx_num, acquired_delegated_energy_value, delegated_bandwidth_trx_num, delegated_bandwidth_value, acquired_delegated_bandwidth_trx_num, acquired_delegated_bandwidth_value, staked_trx_num, energy_staked_trx_num, bandwidth_staked_trx_num, vote_num, voted_num, bandwidth_staked_num, bandwidth_staked_all_num, bandwidth_free_num, bandwidth_free_all_num from wallet_address
|
||||
</sql>
|
||||
|
||||
<select id="selectWalletAddressList" parameterType="WalletAddress" resultMap="WalletAddressResult">
|
||||
@@ -80,7 +79,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null "> and bandwidth_staked_all_num = #{bandwidthStakedAllNum}</if>
|
||||
<if test="bandwidthFreeNum != null "> and bandwidth_free_num = #{bandwidthFreeNum}</if>
|
||||
<if test="bandwidthFreeAllNum != null "> and bandwidth_free_all_num = #{bandwidthFreeAllNum}</if>
|
||||
<if test="tokenKey != null "> and token_key = #{tokenKey}</if>
|
||||
</where>
|
||||
</select>
|
||||
|
||||
@@ -124,7 +122,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null">bandwidth_staked_all_num,</if>
|
||||
<if test="bandwidthFreeNum != null">bandwidth_free_num,</if>
|
||||
<if test="bandwidthFreeAllNum != null">bandwidth_free_all_num,</if>
|
||||
<if test="tokenKey != null">token_key,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="token != null and token != ''">#{token},</if>
|
||||
@@ -159,7 +156,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null">#{bandwidthStakedAllNum},</if>
|
||||
<if test="bandwidthFreeNum != null">#{bandwidthFreeNum},</if>
|
||||
<if test="bandwidthFreeAllNum != null">#{bandwidthFreeAllNum},</if>
|
||||
<if test="tokenKey != null">#{tokenKey},</if>
|
||||
</trim>
|
||||
</insert>
|
||||
|
||||
@@ -198,7 +194,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="bandwidthStakedAllNum != null">bandwidth_staked_all_num = #{bandwidthStakedAllNum},</if>
|
||||
<if test="bandwidthFreeNum != null">bandwidth_free_num = #{bandwidthFreeNum},</if>
|
||||
<if test="bandwidthFreeAllNum != null">bandwidth_free_all_num = #{bandwidthFreeAllNum},</if>
|
||||
<if test="tokenKey != null">token_key = #{tokenKey},</if>
|
||||
</trim>
|
||||
where id = #{id}
|
||||
</update>
|
||||
|
||||
Reference in new issue
Block a user