【以太坊开发】Web3j对以太坊钱包功能的实现

EthService.java

public class EthService {

// private static String URL="http://192.168.1.213:8545";
private static String URL="http://47.88.230.234:18759";
private static HttpService httpService;
/**
     * 初始化web3j普通api调用
     *
     * @return web3j
     */
    public static Web3j initWeb3j() {
        return Web3j.build(getService());
    }


    /**
     * 初始化personal级别的操作对象
     * @return Geth
     */
    public static Geth initGeth(){
        return Geth.build(getService());
    }


    /**
     * 初始化admin级别操作的对象
     * @return Admin
     */
    public static Admin initAdmin(){
        return Admin.build(getService());
    }


    /**
     * 通过http连接到geth节点
     * @return
     */
    private static HttpService getService(){
     if(httpService==null){
     httpService=new HttpService(URL);
     }
        return httpService;
    }
    
    /**
     * 输入密码创建地址
     *
     * @param password 密码(建议同一个平台的地址使用一个相同的,且复杂度较高的密码)
     * @return 地址hash
     * @throws IOException
     */
    public static String newAccount(String password) throws IOException {
        Admin admin = initAdmin();
        Request request = admin.personalNewAccount(password);
        NewAccountIdentifier result = request.send();
        return result.getAccountId();
    }
    
    /**
     * 获得当前区块高度
     *
     * @return 当前区块高度
     * @throws IOException
     */
    public static BigInteger getCurrentBlockNumber() throws IOException {
        Web3j web3j = initWeb3j();
        Request request = web3j.ethBlockNumber();
        return request.send().getBlockNumber();
    }
    
    /**
     * 解锁账户,发送交易前需要对账户进行解锁
     *
     * @param address  地址
     * @param password 密码
     * @param duration 解锁有效时间,单位秒
     * @return
     * @throws IOException
     */
    public static Boolean unlockAccount(String address, String password, BigInteger duration) throws IOException {
        Admin admin = initAdmin();
        Request request = admin.personalUnlockAccount(address, password, duration);
        PersonalUnlockAccount account = request.send();
        return account.accountUnlocked();
    }
    
    /**
     * 账户解锁,使用完成之后需要锁定
     *
     * @param address
     * @return
     * @throws IOException
     */
    public static Boolean lockAccount(String address) throws IOException {
        Geth geth = initGeth();
        Request request = geth.personalLockAccount(address);
        BooleanResponse response = request.send();
        return response.success();
    }
    
    /**
     * 根据hash值获取交易
     *
     * @param hash
     * @return
     * @throws IOException
     */
    public static EthTransaction getTransactionByHash(String hash) throws IOException {
        Web3j web3j = initWeb3j();
        Request request = web3j.ethGetTransactionByHash(hash);
        return request.send();
    }
    
    /**
     * 获得ethblock
     *
     * @param blockNumber 根据区块编号
     * @return
     * @throws IOException
     */
    public static EthBlock getBlockEthBlock(Integer blockNumber) throws IOException {
        Web3j web3j = initWeb3j();


        DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(blockNumber);
        Request request = web3j.ethGetBlockByNumber(defaultBlockParameter, true);
        EthBlock ethBlock = request.send();
        return ethBlock;
    }
    
    /**
     * 发送交易并获得交易hash值
     *
     * @param transaction
     * @param password
     * @return
     * @throws IOException
     */
    public static String sendTransaction(Transaction transaction, String password) throws IOException {
        Admin admin = initAdmin();
        Request request = admin.personalSendTransaction(transaction, password);
        EthSendTransaction ethSendTransaction = request.send();
        return ethSendTransaction.getTransactionHash();
    }
    
    /**
     * 指定地址发送交易所需nonce获取
     *
     * @param address 待发送交易地址
     * @return
     * @throws IOException
     */
    public static BigInteger getNonce(String address) throws IOException {
        Web3j web3j = initWeb3j();
        Request request = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.LATEST);
        return request.send().getTransactionCount();
    }

}


App.java

public class App {

    // GAS价格  
    public static BigInteger GAS_PRICE = BigInteger.valueOf(20_000_000_000L);  
    // GAS上限  
    public static BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000L);  
  
    // 交易费用  
    public static BigInteger GAS_VALUE = BigInteger.valueOf(1300_000L);;  
    
public static void main(String[] args) {
// 获取余额
try {
System.out.println("Hello World!");


Admin admin = EthService.initAdmin();
System.out.println(admin.personalListAccounts().send().getAccountIds());
//// ShhAddToGroup group = admin.shhAddToGroup("enode://6d1819c68ad4bb4928f349d8fecb14223087b4ea0740dd3ffee55b95d975c2123d230e12e13a40083fc902440d83f0aa17e0a925616110c14273e6b2d7f59635@192.168.1.64:30303").send();
//// System.out.println(group);
//
// NetPeerCount count=admin.netPeerCount().send();
// System.out.println(count.getResult());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/**
* 开始挖矿
*/
@Test
public void startMining(){

}

/**
* 新建用户
*/
@Test
public void CreateNewAccounts() {
String account = "";
try {
account = EthService.newAccount("123456");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(account);
}


/**
* 获取钱包里的所有用户
*/
@Test
public void getAllAccounts() {
try {
Geth geth = EthService.initGeth();
Request request = geth.ethAccounts();
List list = request.send().getAccounts();
System.out.println(list.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/**
* 获取用户余额
*/
@Test
public void getAccountBalance() {
try {
String address="0xdbaea9b9d0b4d9dfff546466c89de34c9711a942";//0x8b7483ea3c7a545dbf93bf07764b479e0469e821 0xdbaea9b9d0b4d9dfff546466c89de34c9711a942
Web3j web3 = EthService.initWeb3j();
EthGetBalance ethGetBalance1 = web3.ethGetBalance(address, DefaultBlockParameter.valueOf("latest")).send();
System.out.println(ethGetBalance1.getBalance());
System.out.println(address+"的余额:" + Convert.fromWei(ethGetBalance1.getBalance().toString(), Convert.Unit.ETHER));  //.new BigDecimal(ethGetBalance1.getBalance() + "").divide(BigDecimal.valueOf(Math.pow(10, 18))).setScale(6)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 转账
*/
@Test
public void transferBalance(){
try {
boolean flag = EthService.unlockAccount("0xdbaea9b9d0b4d9dfff546466c89de34c9711a942", "123456", new BigInteger(1800 + ""));
System.out.println(flag);


BigInteger value = Convert.toWei("12", Convert.Unit.ETHER).toBigInteger(); 

Web3j web3j=EthService.initWeb3j();
Credentials credentials = WalletUtils.loadCredentials("123456", "F:\\Ethereum\\blockchain\\keystore\\UTC--2018-04-26T06-04-02.691651400Z--dbaea9b9d0b4d9dfff546466c89de34c9711a942");


// get the next available nonce
BigInteger nonce = EthService.getNonce("0xdbaea9b9d0b4d9dfff546466c89de34c9711a942");

// create our transaction
RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(
            nonce, GAS_PRICE, GAS_LIMIT, "0x8b7483ea3c7a545dbf93bf07764b479e0469e821", value);


// sign & send our transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();

System.out.println(ethSendTransaction.getResult());
System.out.println(ethSendTransaction.getTransactionHash());


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 监听新区块
*/
@Test
public void observableBlockChain(){
Web3j web3j=EthService.initWeb3j();
Subscription subscription = web3j.blockObservable(false).subscribe(block -> {
Block blk=block.getResult();
System.out.println("当前区块高度:"+blk.getNumber()+",上一个区块:"+blk.getParentHash()+blk.getHash());
});
System.out.println("订阅的"+subscription.hashCode());
}

}


MyBlockObserve.java

public class MyBlockObserve {


private static Web3j web3j=EthService.initWeb3j();

/**
* 监听区块数据
*/
public static void observableBlockChain(){
Subscription subscription = web3j.blockObservable(false).subscribe(block -> {
Block blk=block.getResult();
System.out.println("当前区块高度:"+blk.getNumber()+",上一个区块:"+blk.getParentHash()+blk.getHash());
});
System.out.println("订阅的"+subscription.hashCode());
}

}

你可能感兴趣的:(区块链/以太坊/比特币)