简单使用以太坊Web3j
1、创建钱包
- 生成助记词
import org.web3j.crypto.MnemonicUtils; import static org.web3j.crypto.SecureRandomUtils.secureRandom; private String generateMnemonics() { byte[] initialEntropy = new byte[16]; secureRandom().nextBytes(initialEntropy); String mnemonic = MnemonicUtils.generateMnemonic(initialEntropy); }
- 生成种子
//如果使用密码可能与大部分钱包不兼容 byte[] seed = MnemonicUtils.generateSeed(mnemonic, password)
- 生成密钥对和地址
import org.web3j.utils.Numeric; import static org.web3j.crypto.Hash.sha256; import org.web3j.crypto.Keys; ECKeyPair ecKeyPair = ECKeyPair.create(sha256(seed)); String priKeyWithPrefix = Numeric.toHexStringWithPrefix(ecKeyPair.getPrivateKey()); String pubKeyWithPrefix = Numeric.toHexStringWithPrefix(ecKeyPair.getPublicKey()); //根据公钥或者ECKeyPair获取钱包地址 String address = Keys.getAddress(ecKeyPair); String address = Keys.getAddress(pubKeyWithPrefix);
- 生成钱包文件
WalletFile walletFile = Wallet.createLight(password, keyPair);
以上所有流程,在 Web3j 最新版本中被整合进一个方法中
Bip39Wallet wallet = WalletUtils.generateBip39Wallet(password, destinationDirectory)
Bip39Wallet
是一个纯 POJO 对象,包含了钱包文件和助记词。
在 BIP39 基础上,Web3j 同时提供了对 BIP44 的支持
Bip39Wallet wallet = Bip44WalletUtils.generateBip44Wallet(password, destinationDirectory)
2、恢复钱包
- 私钥恢复
ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(mPrivateKey,16));
- 助记词恢复通过助记词得到种子 然后再得到公私钥,可参考前面 2-3步
- 钱包文件恢复
ECKeyPair ecKeyPair = Wallet.decrypt("密码", WalletFile );
3、交易
//Web3j web3b = Web3j.build(new HttpService("https://api.myetherapi.com/eth"));
Web3j web3b = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
//Credentials credentials = WalletUtils.loadCredentials(password, "/path/to/walletfile");
Credentials credentials = WalletUtils.loadBip39Credentials(password, mnemonic)
TransactionReceipt transactionReceipt = Transfer.sendFunds(web3b, credentials, "0x<address>|<ensName>",BigDecimal.valueOf(1.0), Convert.Unit.ETHER).send();
推荐专栏
热门币种
更多
币种
价格
24H涨跌幅
热搜币种
更多
币种
价格
24H涨跌幅
最新快讯
更多
2023-11-28 19:06:57
2023-11-28 19:03:57
2023-11-28 18:59:52
2023-11-28 18:53:43
2023-11-28 18:53:38
2023-11-28 18:52:07
2023-11-28 18:47:58