以太坊的Java客户端使用

准备工作

  1. 已经安装好以太坊客户端或是以太坊集群
  2. 安装jdk8开发环境,web3j需要在java 8的环境才能运行

引入jar包

<dependency>
  <groupId>org.web3jgroupId>
  <artifactId>coreartifactId>
  <version>2.2.1version>
dependency>

连接以太坊客户端

使用web3j的api连接

public class Web3JClient {

    private static String ip = "http://ip地址:8545/";

    private Web3JClient(){}

    private volatile static Web3j web3j;

    public static Web3j getClient(){
        if(web3j==null){
            synchronized (Web3JClient.class){
                if(web3j==null){
                    web3j = Web3j.build(new HttpService(ip));
                }
            }
        }
        return web3j;
    }
}

使用Parity的api连接

public class ParityClient {

    private static String ip = "http://ip地址:8545/";

    private ParityClient(){}

    private static class ClientHolder{
        private static final Parity parity = Parity.build(new HttpService(ip));
    }

    public static final  Parity getParity(){
        return ClientHolder.parity;
    }
}

账户操作

1.创建账户POJO

public class AccountInfo {

    private String userName;

    private String phone;

    private String address;

    private String school;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }
}

2.账户相关操作

public class Account {

    private static  Parity parity = ParityClient.getParity();

    private static Web3j web3j = Web3JClient.getClient();

    /**
     * Life
     * Like this
     * Like that
     * Also
     * It's not the same with you think
     * @Author lzh
     *
     */
    public List getAccountlist(){

        try{
            return  parity.personalListAccounts().send().getAccountIds();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public String createAccount(String accountName,String password,AccountInfo accountInfo){
        try {
            NewAccountIdentifier newAccountIdentifier = parity.personalNewAccount(password).send();
            if(newAccountIdentifier!=null){
                String accountId = newAccountIdentifier.getAccountId();
                parity.personalSetAccountName(accountId,accountName);

                Map account = new HashMap();
                account.put(accountId,accountInfo);
                parity.personalSetAccountMeta(accountId,account);

                return  accountId;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public PersonalAccountsInfo.AccountsInfo getAccountInfo(String accountId){

        try{
            PersonalAccountsInfo personalAccountsInfo = parity.personalAccountsInfo().send();

            return  personalAccountsInfo.getAccountsInfo().get(accountId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public BigInteger getBalance(String accountId){
        try {
            DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(58);
            EthGetBalance ethGetBalance =  parity.ethGetBalance(accountId,defaultBlockParameter).send();
            if(ethGetBalance!=null){
                return ethGetBalance.getBalance();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

账户测试

public class AccountTest {

    public static void main(String args[]) {
        getBalance();
    }

    public static void getBalance(){
        Account account = new Account();
        BigInteger ba = account.getBalance("0xcee1086eabd4cac10f6658eeffcdc66ad7565450");
        System.out.print(ba);
    }

    public static  void queryAccount(){
        Account account = new Account();
        List accounts = account.getAccountlist();
        for(String accountId:accounts){
            System.out.println(accountId);
        }

    }

    public void createAccount(){
            Account account = new Account();
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setPhone("229787499");
            accountInfo.setAddress("世宁大厦");
            accountInfo.setSchool("buaa");
            accountInfo.setUserName("lzh");
            String accountId = account.createAccount("lzh","123456",accountInfo);
            System.out.println("注册账户成功:"+accountId);
//        PersonalAccountsInfo.AccountsInfo accountsInfo = account.getAccountInfo("0xad7bbca86e02e503076b06931e05938e51e49fb9");
//        System.out.println(accountsInfo.toString());
    }
}

交易操作

public class Trade {

    private static final Logger logger = LoggerFactory.getLogger(Trade.class);

    private static BigInteger nonce = new BigInteger("0");

    private static BigInteger gasPrice = new BigInteger("1");

    private static BigInteger gasLimit = new BigInteger("50");

    private Parity parity = ParityClient.getParity();

    public boolean trasfer(String accountId,String passsword,String toAccountId, BigDecimal amount)  {

        Transaction transaction = Transaction.createEtherTransaction(accountId,null,null,null,toAccountId,amount.toBigInteger());
        try{
            EthSendTransaction ethSendTransaction =parity.personalSignAndSendTransaction(transaction,passsword).send();
            if(ethSendTransaction!=null){
                String tradeHash = ethSendTransaction.getTransactionHash();
                logger.info("账户:[{}]转账到账户:[{}],交易hash:[{}]",accountId,toAccountId,tradeHash);
            }
        }catch (Exception e){
            logger.error("账户:[{}]交易失败!",accountId,e);
        }
        return false;
    }

}

交易测试

public class TradeTest {

    public static void main(String args[]){
        Trade trade = new Trade();
        trade.trasfer("账户a的hash码","abc123","账户b的hash码",new BigDecimal(100));
    }
}

其他

有问题,或者想了解更多区块链的信息,请留言。

你可能感兴趣的:(区块链)