区块链钱包之创建以太坊离线交易(ETH交易)
Posted 陳英傑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了区块链钱包之创建以太坊离线交易(ETH交易)相关的知识,希望对你有一定的参考价值。
(一)区块链钱包之生成助记词
(二)区块链钱包之创建钱包地址
(三)区块链钱包之加密算法简介
(四)区块链钱包之创建比特离线交易(BTC交易)
(五)区块链钱包之创建以太坊交易(ETH交易)
导入Gralde依赖:
org.web3j:core:4.6.0-android
我们做BTC和ETH都需要导入库,最终导入如下:
api 'org.bouncycastle:bcpkix-jdk15to18:1.68'
// bouncycastle:bcprov-xxx在web3j和bitcoinj中都有
// api 'org.bouncycastle:bcprov-jdk15to18:1.68'
api group: 'org.bitcoinj', name: 'bitcoinj-core', version: '0.15.10' // 包含org.bouncycastle:bcprov-jdk15to18:1.68
api('org.web3j:core:4.6.0-android') {
// 剔除 org.bouncycastle:bcprov-jdk15on:1.60
exclude group: 'org.bouncycastle', module: 'bcprov-jdk15on'
}
创建以太交易如下:
// 首先需要创建凭证:
public Credentials getCredentials(List<String> keywords) {
Credentials credentials = null;
WalletAddressModel model = FaxMsnPlugin.getMF().getModel(WalletAddressModel.class);
List<WalletAddressModel.Item> items = model.findByType(CoinType.ETH.type);
if (!ArrayUtils.isEmpty(items)) {
WalletAddressModel.Item item = items.get(0);
if (item != null) {
DeterministicKey key = FaxWalletUtils.generateKeyByPath(keywords, item.realPath);
String privateKeyAsHex = key.getPrivateKeyAsHex();
credentials = Credentials.create(privateKeyAsHex);
}
}
return credentials;
}
// 创建一般交易
public String createTransaction(List<String> keywords, String destinationAddress, long nonce, long gasPrice, long gasLimit, BigDecimal value) {
String hexStr = "";
try {
if (credentials != null) {
BigInteger nonceBig = BigInteger.valueOf(nonce);
BigInteger gasPriceBig = BigInteger.valueOf(gasPrice);
BigInteger gasLimitBig = BigInteger.valueOf(gasLimit);
RawTransaction transaction = RawTransaction.createEtherTransaction(nonceBig, gasPriceBig, gasLimitBig, destinationAddress, value.toBigInteger());
byte[] bytes = TransactionEncoder.signMessage(transaction, credentials);
hexStr = Numeric.toHexStringNoPrefix(bytes);
}
} catch (Exception e) {
e.printStackTrace();
}
return hexStr;
}
// 根据合约地址创建交易
public String createContractTransaction(List<String> keywords, String destinationAddress, long nonce, long gasPrice, long gasLimit, BigDecimal value, String contractAddress) {
String result = "";
try {
if (credentials != null) {
BigInteger nonceBig = BigInteger.valueOf(nonce);
BigInteger gasPriceBig = BigInteger.valueOf(gasPrice);
BigInteger gasLimitBig = BigInteger.valueOf(gasLimit);
String data = "0xa9059cbb" +
Numeric.toHexStringNoPrefixZeroPadded(Numeric.toBigInt(destinationAddress), 64) +
Numeric.toHexStringNoPrefixZeroPadded(value.toBigInteger(), 64);
RawTransaction transaction = RawTransaction.createTransaction(nonceBig, gasPriceBig, gasLimitBig, contractAddress, data);
byte[] bytes = TransactionEncoder.signMessage(transaction, credentials);
result = Numeric.toHexStringNoPrefix(bytes);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
希望我的分享能帮助到大家
以上是关于区块链钱包之创建以太坊离线交易(ETH交易)的主要内容,如果未能解决你的问题,请参考以下文章