jokulfox

导航

 

开发环境和工具

1. window 10 64
2. 比特核心钱包:bitcoin core 64
配置过程
1. 下载比特币核心钱包,下载链接https://bitcoin.org/en/download
2. 安装完不要运行。启动测试网络,这个需要下的数据比较少,大概10G。如图,第二个启动项
3. 启动后会弹出如图页面:
 选择数据存放的位置(正式环境需要100G,随着时间而增加),这个地址下面还需要使用,请记住。
4. 同步数据,如下图所示
 下边进度条消失就是同步完了。
5. 配置rpc。在数据存放位置新建一个文件名称是bitcoin.conf,内容如下
testnet=0
server=1            
rpcuser=wang        
rpcpassword=123456  
rpctimeout=30       
rpcport=18332       
rpcconnect=127.0.0.1
testnet=0是测试网络,正式环境去掉这一行,并把rpcport=18332改为rpcport=8332
6. 代码使用了jsonrpc4j,maven依赖如下
<dependency>
    <groupId>com.github.briandilley.jsonrpc4j</groupId>
    <artifactId>jsonrpc4j</artifactId>
   <version>1.1</version>
</dependency>
6.1. 简单公用类
public class ClientUtil {

    public static JsonRpcHttpClient getClient() {
        JsonRpcHttpClient client = null;
        try {
            String cred = Base64.encodeBytes(("wang" + ":" +"123456").getBytes());
            Map<String, String> headers = new HashMap<String, String>(1);
            //身份认证
            headers.put("Authorization", "Basic " + cred);
            client = new JsonRpcHttpClient(new URL("http://127.0.0.1:18332"),headers);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return client;
    }

    public static Object result(String command, Object[] objects) {
        JsonRpcHttpClient client = ClientUtil.getClient();
        Object result = null;
        if(client != null) {
            try {
                result = client.invoke(command, objects,Object.class);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
        return result;
    }
}
6.2. 发送比特币
   @Test
    public void sendfrom() {
        String result = (String) ClientUtil.result("sendfrom", new Object[]{"","2MzFix1Fnndi1wAvg9B7dLfRgL25FuC4J7x","0.0001"});
        System.out.println(result);
    }
第二个参数是对方的地址,第三个参数是金额。
6.3. 生成一个地址,并监测对方是否发送
    /**
     * 生成一个收款地址,等待接收
     */
    @Test
    public void newAddressAndReceived() {
        String result = (String) ClientUtil.result("getnewaddress", new Object[]{""});
        System.out.println(result);

        while (true) {
            Double received = (Double) ClientUtil.result("getreceivedbyaddress", new Object[] {result});
            if(received > 0) {
                System.out.println(received);
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
7. 免费领取测试网络比特币地址:https://testnet.coinfaucet.eu/en/
    api:https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list
 





posted on 2016-11-24 16:02  jokulfox  阅读(1929)  评论(1)    收藏  举报