1. 程式人生 > >區塊鏈開發(四)web3j和web3.js對以太坊錢包功能的實現

區塊鏈開發(四)web3j和web3.js對以太坊錢包功能的實現

經過前面的環境搭建,現在開始通過web3j和web3.js來簡單呼叫以太坊的api

web3j的使用

首先是新建一個maven工程

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
<modelVersion>4.0.0</modelVersion> <groupId>com.cayden.ethereum</groupId> <artifactId>ethsample</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.web3j</groupId
>
<artifactId>core</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>
1.7.2</version> </dependency> </dependencies> </project>

然後新建Web3JClient.java

package com.cayden.ethereum.client;

import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;

/**
 * Created by cuiran on 18/7/6.
 */
public class Web3JClient {

    private static String ip = "http://127.0.0.1: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;
    }
}

在新建ParityClient.java

package com.cayden.ethereum.client;

import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.parity.Parity;

/**
 * Created by cuiran on 18/7/6.
 */
public class ParityClient {
    private static String ip = "http://127.0.0.1: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;
    }
}

然後建立一個AccountInfo類

package com.cayden.ethereum.pojo;

/**
 * Created by cuiran on 18/7/6.
 */
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;
    }
}

新建一個賬戶類Account

package com.cayden.ethereum;

import com.cayden.ethereum.client.ParityClient;
import com.cayden.ethereum.client.Web3JClient;
import com.cayden.ethereum.pojo.AccountInfo;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.parity.Parity;
import org.web3j.protocol.parity.methods.response.NewAccountIdentifier;
import org.web3j.protocol.parity.methods.response.PersonalAccountsInfo;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cuiran on 18/7/6.
 */
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 cuiran
     *
     */
    public List<String> 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<String,Object> account = new HashMap<String,Object>();
                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;
    }
}

新建一個交易轉賬類

package com.cayden.ethereum;

import com.cayden.ethereum.client.ParityClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.parity.Parity;

import java.math.BigDecimal;
import java.math.BigInteger;


/**
 * Created by cuiran on 18/7/6.
 */
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;
    }
}

最後測試類如下

package com.cayden.ethereum;

import com.cayden.ethereum.pojo.AccountInfo;
import org.web3j.protocol.parity.methods.response.PersonalAccountsInfo;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

/**
 * Created by cuiran on 18/7/6.
 */
public class AccountTest {
    public static void main(String args[]) {
//        createAccount();

        getBalance();

//        queryAccount();
//        trade();

//        getAccountInfo();
    }

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



    }

    public static void getAccountInfo(){
        Account account = new Account();
        PersonalAccountsInfo.AccountsInfo accountsInfo = account.getAccountInfo("0x5bd2328251e8abd5bc39393a9549586634785938");
        System.out.println(accountsInfo.toString());


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

    public static void trade(){
        Trade trade = new Trade();
        boolean result=trade.trasfer("0x1a95f4df6dbf7511b8ec820833df628ea743c458","123456","0x91140c3170f4aa959f09aff9b5393e9d0cd2a54c",new BigDecimal(5));
        System.out.println("trade:"+result);

    }
    public static void createAccount(){
        Account account = new Account();
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setPhone("12345678901");
        accountInfo.setAddress("北街家園");
        accountInfo.setSchool("清華大學");
        accountInfo.setUserName("cayden");
        String accountId = account.createAccount("cayden","123456",accountInfo);
        System.out.println("註冊賬戶成功:"+accountId);
//        PersonalAccountsInfo.AccountsInfo accountsInfo = account.getAccountInfo("0xad7bbca86e02e503076b06931e05938e51e49fb9");
//        System.out.println(accountsInfo.toString());
    }
}

這裡寫圖片描述

web3.js的使用

先引入web3.js檔案
然後新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="js/web3.js"></script>
<input type="button" value="獲取賬號">

<input type="button" value="建立賬號">
<input type="button" value="解鎖賬號">
<input type="button" value="獲取餘額">
<script>
        var web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));
        document.querySelectorAll("input")[0].onclick=function(){
             //使用web3 的api 去操作節點。jsonrpc

            web3.eth.getAccounts(function(error,result){
                console.log(result);
                var res="查詢賬號資訊:<br>";
                for (var i=0;i<result.length;i++){
                    res+="賬號"+(i+1)+":"+result[i]+"<br>";
                }
                document.getElementById("result").innerHTML=res;
            });

        }
        document.querySelectorAll("input")[1].onclick=function(){
            console.log("www");
            web3.personal.newAccount("123456",function(error,result){
                console.log(result);
            });
        }
        document.querySelectorAll("input")[2].onclick=function(){
            web3.personal.unlockAccount("0x89ed26fe35814f839b8b62e5de09521280247cfd","123456",function(error,result){
                console.log(result);
                console.log("解綁成功");
            });
        }

        document.querySelectorAll("input")[3].onclick=function(){
            web3.eth.getBalance("0xb258e5b1b30215b112881c13f22ab5a47a624b81",function(error,result){
                console.log(result);

                document.getElementById("result").innerHTML="餘額:"+result.c[0];
                console.log("獲取餘額成功");
            });
        }


</script>
<div id="result"></div>
</body>
</html>

這裡寫圖片描述