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(); } }