赞
踩
与普通交易由节点负责签名不同,裸交易需要外部应用进行离线签名。 因此在使用裸交易之前,需要首先载入账户凭证,利用私钥进行签名。
从账户一向账户九转账1个以太币,流程如下:首先创建账户一的凭证对象,然后创建交易请求,再用账户一的凭证对该请求进行签名,签名结束最后提交该交易请求即完成一次裸交易。
@Test public void submitRawTransaction() throws IOException, CipherException, ExecutionException, InterruptedException { Web3j web3j = Web3j.build(new HttpService("http://localhost:8545")); Credentials credentials = Credentials.create("0x355321e6df9ae014b0e19d2d49db10508e3b717326a925cd282896114ad26922");//通过账户1的私钥创建凭证对象 List<String> accounts = web3j.ethAccounts().send().getAccounts(); String to = accounts.get(8); BigInteger gasPrice = BigInteger.valueOf(22000000000L); BigInteger gasLimit = BigInteger.valueOf(670000); BigInteger value = Convert.toWei("1",Convert.Unit.ETHER).toBigInteger(); String data = ""; BigInteger nonce = web3j.ethGetTransactionCount(credentials.getAddress(),DefaultBlockParameterName.LATEST).send().getTransactionCount(); RawTransaction transaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, to,value,data);//准备好transaction对象 byte[] signMessage = TransactionEncoder.signMessage(transaction, credentials);//利用账户凭证进行签名,得到字节流签名信息 String hexMessage = Numeric.toHexString(signMessage); //将字节流转换为十六进制字符串 String transactionHash = web3j.ethSendRawTransaction(hexMessage).send().getTransactionHash();//请求交易 System.out.println("nonce:"+nonce); System.out.println("transactionHash:"+transactionHash); System.out.println("transaction:"+transaction); System.out.println("hexMessage:"+hexMessage); BigInteger toBalance = web3j.ethGetBalance(to,DefaultBlockParameterName.LATEST).send().getBalance(); System.out.println("账户9余额:"+toBalance); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。