当前位置:   article > 正文

以太坊搭建私链(5)——使用java连接私链、发起交易和查询交易_用java写一个跟以太币一样的程序

用java写一个跟以太币一样的程序

新建maven项目并添加依赖

在pom.xml中添加依赖,需要添加的依赖如下所示:

<dependencies>
        <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>core</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.24</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.2</version>
        </dependency>
    </dependencies>
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

java连接私链

import java.io.IOException;
import java.math.BigInteger;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.core.methods.response.*;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;
public class main {
	public static void main(String[] args) {
        // TODO Auto-generated method stub
        //连接到私链
        //因为我把端口映射到了本机的8545端口,所以使用这一地址:端口形式
        Web3j web3 = Web3j.build(new HttpService("http://127.0.0.1:8545"));
        //获取一些区块链信息
        try {
            //查看区块链中的区块数量
            EthBlockNumber blockNumber = web3.ethBlockNumber().send();
            //查看节点中的账户
            EthAccounts accounts = web3.ethAccounts().send();
            // 查看网络中的节点数目
            NetPeerCount peerCount = web3.netPeerCount().send();
            //查看挖矿速度
            EthHashrate ethHashrate = web3.ethHashrate().send();
            //获取交易信息
            EthTransaction trans = web3.ethGetTransactionByHash(transHash).send();
            //查看账户余额
            EthGetBalance ethbalance = web3.ethGetBalance(ownerAddress,DefaultBlockParameterName.LATEST).send();
			//打印信息
            System.out.println("网络中的区块数量: " + blockNumber.getBlockNumber());
            System.out.println("节点中的账户: " + accounts.getAccounts());
            System.out.println("网络中的节点数目: " + peerCount.getQuantity());
            System.out.println("挖矿速度:"+ethHashrate.getHashrate());
            System.out.println("账户<"+ownerAddress+">的余额:"+ethbalance.getBalance());
            System.out.println("交易<"+transHash+">的细节:"+trans.getResult().getInput());
        } catch (IOException ex) {
            throw new RuntimeException("Error whilst sending json-rpc requests", ex);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

java发布交易

首先需要在main类中加入如下成员属性:

	//发送者地址
    private static String ownerAddress ="发送者账户地址";
	//发送者私钥(加0x前缀)
    private static String privateKey ="发送者账户的私钥";
	//接收者地址
    private static String toAddress ="接收者账户地址";
	//交易的附加信息
    private static String data = "交易的附加信息";
    //这笔交易的gas价格
    private static BigInteger price = BigInteger.valueOf(0);
    //这笔交易的gas上限
    private static BigInteger limit = BigInteger.valueOf(800000000);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

需要注意的是,如果使用之前的方法搭建私链的话,账户的私钥我们是不知道的。geth直接将私钥加密存放在了生成的keystore文件中。需要使用metamask钱包来导出账户的私钥。具体可以参考我另一篇文章:使用metamask获取账户私钥。

public void sendtrans(Web3j web3){
        try{ 
            //获取nonce
            BigInteger nonce = web3.ethGetTransactionCount(ownerAddress,DefaultBlockParameterName.PENDING).send().getTransactionCount();
            //设置你的转账金额
            BigInteger value = Convert.toWei("0", Convert.Unit.ETHER).toBigInteger();
            //签名交易  
            RawTransaction rawTransaction =RawTransaction.createTransaction(nonce, price, limit, toAddress, value, data);
            Credentials credentials = Credentials.create(privateKey);
            byte[] signedMessage =TransactionEncoder.signMessage(rawTransaction, credentials);
            //广播交易
            String hash =  web3.ethSendRawTransaction(Numeric.toHexString(signedMessage)).sendAsync().get().getTransactionHash();
            //获取交易的哈希值,之后可以根据交易的哈希值查询交易细节
            System.out.println("hash:"+hash);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

java查询交易信息

在连接到java私链后,便可以查询交易信息,如下代码所示:

try{
//使用transHash获取交易信息,也有其它方式,具体可以ctrl点击ethGetTransactionByHash进入ethereum.class查看
EthTransaction trans = web3.ethGetTransactionByHash(transHash).send();
//打印你想查询的信息
System.out.println("交易<"+transHash+">的附加信息:"+trans.getResult().getInput());
}catch(IOException ex){
            throw new RuntimeException("Error whilst sending json-rpc requests", ex);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

可以查询每一笔交易的细节,如下图所示,按照自己的需要进行查询。
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/768822
推荐阅读
相关标签
  

闽ICP备14008679号