BitcoinCore JSONRPC Java使用,创建账号,获取余额,转账等等...

1、首先要安装好bitcoin core服务 上一篇有怎么安装

下面代码支持多钱包多地址动态调用,但让我没用使用多地址,根据自己的需要然后封装方法就好

2、引入jar  JavaBitcoinRpcClient

<!-- https://mvnrepository.com/artifact/wf.bitcoin/JavaBitcoindRpcClient -->
<dependency>
    <groupId>wf.bitcoin</groupId>
    <artifactId>JavaBitcoindRpcClient</artifactId>
    <version>1.0.0</version>
</dependency>

 

3、 BitcoinRPC 接口

package com.lpz.btc.api;

import com.lpz.btc.model.TransferModel;

public interface BitcoinRPC {

    /**
     * 创建BTC钱包地址(钱包、地址都是新创建)
     * @param walletName 钱包名称
     * @param walletPassword 钱包密码
     * @param addressName 地址显示名称
     * @return 地址
     */
    String createBtcAddress(String walletName,String walletPassword,String addressName);

    /**
     * 获取BTC余额
     * @param walletName 钱包名称
     * @param address 地址
     * @return 余额
     */
    double getBtcBalance(String walletName,String address);

    /**
     * BTC转账
     * @param walletName 钱包名称
     * @param walletPassword 钱包密码
     * @param toAddress 接收地址
     * @param quantity 转账数量
     * @return 转账状态消息
     */
    TransferModel transfetBtc(String walletName,String walletPassword,String toAddress,double quantity);

    /**
     * 获取地址私钥
     * @param walletName 钱包名称
     * @param walletPassword 钱包密码
     * @param address 地址
     * @return 私钥
     */
    String getBtcPrivateKey(String walletName,String walletPassword,String address);

    /**
     * 导入BTC私钥(导入地址到钱包)
     * @param walletName 钱包名称
     * @param walletPassword 钱包密码
     * @param privateKey 私钥
     * @return 是否成功
     */
    boolean importBtcPrivateKey(String walletName,String walletPassword,String privateKey);

}

4、BitcoinRPCImpl 实现类

package com.lpz.btc.api.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lpz.btc.api.BitcoinRPC;
import com.lpz.btc.wf.bitcoin.javabitcoindrpcclient.BitcoinJSONRPCClient;
import com.lpz.btc.model.exchange.TransferModel;
import com.lpz.setting.DefaultBtc;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class BitcoinRPCImpl implements BitcoinRPC {
    private Logger logger=Logger.getLogger(BitcoinRPCImpl.class);
    private DefaultBtc defaultBtc=new DefaultBtc();
    private String user=defaultBtc.BTCRPCUSER;//lpz
    private String password=defaultBtc.BTCRPPASSWORD;//lpz
    private String port=defaultBtc.BTCRPCPORT;//18332 因为测试网是18332  主网是8332
    private String host=defaultBtc.BTCRPCALLOWIP;//127.0.0.1
    private final int WALLET_PASS_PHRASE_TIME_OUT=60;

    @Override
    public String createBtcAddress(String walletName, String walletPassword, String addressName) {
        try{
            //获取BTC客户端默认钱包
            BitcoinJSONRPCClient bitcoinClient=getBitcoinClient("");
            //创建钱包
            String walletResult=bitcoinClient.query("createwallet",walletName).toString();
            logger.info("钱包("+walletName+")创建成功返回==>"+walletResult+"");
            //获取当前BTC客户端钱包
            bitcoinClient=getBitcoinClient(walletName);
            //设置钱包密码
            bitcoinClient.encryptWallet(walletPassword);
            //创建地址
            return bitcoinClient.getNewAddress(addressName);
        }catch (Exception e){
            logger.error("创建钱包地址异常==>"+e.getMessage());
        }
        return null;
    }

    @Override
    public double getBtcBalance(String walletName, String address) {
        try {
            List<JSONArray> jsonArrayList=getListAddressInfo(walletName);
            for(JSONArray jsonArray:jsonArrayList){
                if(jsonArray.getString(0).equals(address)){
                    return jsonArray.getDoubleValue(1);
                }
            }
        }catch (Exception e){
           logger.error("钱包("+walletName+")地址("+address+")获取余额异常==>"+e.getMessage());
        }
        return 0;
    }

    @Override
    public TransferModel transfetBtc(String walletName, String walletPassword, String toAddress, double quantity) {
        TransferModel transferModel=new TransferModel();
        transferModel.status=transferModel.status_101;
        try {
           BitcoinJSONRPCClient bitcoinClient=getBitcoinClient(walletName);
           //获取钱包余额
            double balance = bitcoinClient.getBalance().doubleValue();
            if(balance<quantity){
                transferModel.message="余额不足";
                transferModel.status=transferModel.status_103;
            }else{
                //输入钱包密码
                bitcoinClient.walletPassPhrase(walletPassword,WALLET_PASS_PHRASE_TIME_OUT);
                //开始转账
                String result=bitcoinClient.sendToAddress(toAddress, BigDecimal.valueOf(quantity));
                logger.info("钱包("+walletName+")成功转账"+quantity+"个btc到"+toAddress+"交易hash==>"+result);
                transferModel.message="转账成功";
                transferModel.status=transferModel.status_100;
            }
       }catch (Exception e){
            transferModel.message="BTC转账异常";
            logger.error("钱包("+walletName+")转账"+quantity+"个btc到"+toAddress+"异常==>"+e.getMessage());
       }
        return transferModel;
    }

    @Override
    public String getBtcPrivateKey(String walletName, String walletPassword, String address) {
        try {
            BitcoinJSONRPCClient bitcoinClient=getBitcoinClient(walletName);
            bitcoinClient.walletPassPhrase(walletPassword,WALLET_PASS_PHRASE_TIME_OUT);
            Object addressPrivate=bitcoinClient.query("dumpprivkey",address);
            return addressPrivate.toString();
        }catch (Exception e){
            logger.error("获取地址("+address+")私钥异常==>"+e.getMessage());
        }
        return null;
    }

    @Override
    public boolean importBtcPrivateKey(String walletName, String walletPassword, String privateKey) {
        try {
            BitcoinJSONRPCClient bitcoinClient=getBitcoinClient(walletName);
            bitcoinClient.walletPassPhrase(walletPassword,WALLET_PASS_PHRASE_TIME_OUT);
            bitcoinClient.importPrivKey(privateKey);
            return true;
        }catch (Exception e){
            logger.error("导入地址私钥("+privateKey.substring(10)+"******)到钱包("+walletName+")异常==>"+e.getMessage());
        }
        return false;
    }

    /**
     * 获取BTC客户端
     * @param walletName 钱包名称
     * @return BTC客户端
     */
    private BitcoinJSONRPCClient getBitcoinClient(String walletName){
        BitcoinJSONRPCClient bitcoinClient=null;
        try {
            URL url = new URL("http://" + user + ':' + password + "@" + host + ":" + port + "/wallet/"+walletName+"");
            bitcoinClient = new BitcoinJSONRPCClient(url);
        } catch (MalformedURLException e) {
           logger.error("获取BTC RPC错误==>"+e.getMessage());
        }
        return bitcoinClient;
    }
    /**
     * 获取所有钱包地址信息
     * @param walletName 钱包名称
     * @return 所有地址信息
     */
    private  List<JSONArray> getListAddressInfo(String walletName){
        BitcoinJSONRPCClient bitcoinClient=getBitcoinClient(walletName);
        List<JSONArray> resultList=new ArrayList<JSONArray>();
        try {
            Object walletAddressAll=bitcoinClient.query("listaddressgroupings");
            JSONArray jsonArrayAll= JSON.parseArray(JSON.toJSONString(walletAddressAll));
            for(int i=0;i<jsonArrayAll.size();i++){
                JSONArray walletArray=JSON.parseArray(jsonArrayAll.get(i).toString());
                for(int j=0;j<walletArray.size();j++){
                    JSONArray jsonArray= JSON.parseArray(walletArray.getString(j));
                    resultList.add(jsonArray);
                }
            }
        }catch (Exception e){
            logger.error("钱包("+walletName+")获取所有地址信息异常==>"+e.getMessage());
        }
        return resultList;
    }
}

5、测试调用 BitcoinRPCTest


package com.lpz;

import com.lpz.btc.api.BitcoinRPC;
import com.lpz.btc.api.impl.BitcoinRPCImpl;
import org.apache.log4j.Logger;
import org.junit.Test;

public class BitcoinRPCTest {
private Logger logger=Logger.getLogger(BitcoinRPCTest.class);
BitcoinRPC bitcoinRPC=new BitcoinRPCImpl();

@Test
public void getBalance(){
String walletName="lpz";
String address="2N1UMYA6poo3JFFnV3kGC5T5yrw81nRBQP4";
double balance=bitcoinRPC.getBtcBalance(walletName,address);
logger.info("钱包("+walletName+")的余额是==>"+balance);
}
@Test
public void createBtcAddress(){
String walletName="lpz_tld";
String walletPassword="lpz_tld";
String addressName="lpz_tld";
String newAddress=bitcoinRPC.createBtcAddress(walletName,walletPassword,addressName);
logger.info("钱包("+walletName+")地址==>"+newAddress);
}
}
 

效果如下:

还有一点就是我代码里面没有使用BitcoinJSONRPCClient 这个jar 用的是源码

copy代码使用的时候,引包哪里改成使用jar就好了,

然后就是jar里面包含了老版本的方法,有些方法在bitcoin core控制台不能使用的话,在java里面也会抛异常 "找不到此方法"的

eq:上一篇里面move(转账)方法 java里面使用此方法就会抛异常

###最后一点是我自己测试使用的

package com.lpz.exchange.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import wf.bitcoin.javabitcoindrpcclient.BitcoinJSONRPCClient;
import wf.bitcoin.javabitcoindrpcclient.BitcoindRpcClient;

import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class TestBitcoinCore {
    private static Logger logger= Logger.getLogger(TestBitcoinCore.class);
    private static void javaBitcoin(){
        String user = "lpz";
        String password = "lpz";
        String host = "127.0.0.1";
//        String host = "192.168.86.1";
        String port = "18332";
        try {
            URL url = new URL("http://" + user + ':' + password + "@" + host + ":" + port + "/wallet/");
            BitcoinJSONRPCClient bitcoinClient = new BitcoinJSONRPCClient(url);
//            //创建钱包
//            String walletName="longpizi5";
//            String returnWallet=bitcoinClient.query("createwallet",walletName).toString();
//            System.out.println(returnWallet);
            //设置钱包密码
//            bitcoinClient.encryptWallet("TLD6_1zns");
            //修改钱包密码 walletpassphrasechange
//            bitcoinClient.query("TLD6_1zns","原密码","新密码");//未测试
            //获取钱包信息
            System.out.println("钱包信息:"+JSON.toJSONString(bitcoinClient.getWalletInfo()));
            //导入钱包
//            bitcoinClient.dumpWallet("C:\\Users\\THIS_ODK\\Desktop\\lpz.dat");
//            System.out.println(JSON.toJSONString());
//            System.out.println(bitcoinClient.backupWallet(););

            //创建账号
//            String addressName="longlin1";
//            String account=bitcoinClient.getNewAddress(addressName);
//            System.out.println("账号地址:"+account);
            BigDecimal balance = bitcoinClient.getBalance();
            System.out.println(balance);
            //获取账号信息 listaddressgroupings
            List<BitcoindRpcClient.ReceivedAddress> receivedAddressList=bitcoinClient.listReceivedByAddress();
            System.out.println("钱包地址信息1:"+JSON.toJSONString(receivedAddressList));
            Object o_listAddress=bitcoinClient.query("listaddressgroupings");
            System.out.println("钱包地址信息2:"+ JSON.toJSONString(o_listAddress));
            //获取地址私钥 dumpprivkey
            //输入钱包密码
//            bitcoinClient.walletPassPhrase("TLD6_1zns",60);
//            Object o_getAddressPrivate=bitcoinClient.query("dumpprivkey","2N1y1DGtXUbajM5SWyo9yRgiWAqQcPUyVEA");
//            System.out.println("获取地址私钥:"+ JSON.toJSONString(o_getAddressPrivate));
            /*
            //转账 sendtoaddress 错误: Please enter the wallet passphrase with walletpassphrase first."
            //输入钱包密码
            bitcoinClient.walletPassPhrase("TLD6_1zns",5000);
            //开始转账
            String result=bitcoinClient.sendToAddress("2N1y1DGtXUbajM5SWyo9yRgiWAqQcPUyVEA", BigDecimal.valueOf(0.01));
            System.out.println("交易ID:"+result);
            */
            //锁定钱包:walletlock   钱包解锁:walletpassphrase
            //*
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

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

 

posted @ 2019-05-21 16:02  iviv  阅读(5352)  评论(1编辑  收藏  举报