以太坊 java开发依赖
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.5.0</version>
</dependency>
连接到以太坊同步节点
private String gethURL = "http://localhost:8545";
private void connectGeth() {
// --rpcport value HTTP-RPC服务器监听端口(默认值:8545)
this.web3j = Admin.build(new HttpService(gethURL));
if(null==web3j) {
System.out.println("connectGeth error");
}
}
创建账户,需要输入密码,返回账户地址 0x00000...
public String addAccount(String password) {
// walletId:$|chainId:$|account:$
if (web3j == null)
connectGeth();
String account = "";
try {
String fileName = WalletUtils.generateNewWalletFile(password, new File(keystorePath));
Credentials credentials = WalletUtils.loadCredentials(password, keystorePath + "/" + fileName);
account = credentials.getAddress();
} catch (InvalidAlgorithmParameterException e1) {
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (NoSuchProviderException e1) {
e1.printStackTrace();
} catch (CipherException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
addCredentials(account, password);
return account;
}
以太币(矿币)转账
private void transfer_ETH(String _from, String password, String _to, BigInteger value, Long logId) {
Credentials credentials = loadCredentials(_from, password);
try {
//获取nonce
EthGetTransactionCount count=web3j.ethGetTransactionCount(_from, DefaultBlockParameterName.LATEST).send();
BigInteger nonce=count.getTransactionCount();
//创建交易
//BigInteger val=Convert.toWei(new BigDecimal(value), Unit.ETHER).toBigInteger();
RawTransaction rawTransaction=RawTransaction.createEtherTransaction(nonce, GAS_PRICE, GAS_LIMIT, _to, value);
//验证签名
byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue=Numeric.toHexString(signMessage);
//发送交易
CompletableFuture<EthSendTransaction> sendAsync &#