go语言依靠bitcoind的JSON-RPC实现bitcoind-cli功能详解

首先我们看一下bitcoin对JSON-RPC的解释:

3.2.5首次运行比特币核心

当你第一次运行bitcoind时,它会提醒你用一个安全密码给JSON-RPC接口创建一个配置文件。该密码控制对Bitcoin Core提供的应用程序编程接口(API)的访问。

文章地址:http://book.8btc.com/books/6/masterbitcoin2cn/_book/ch03.html

我们了解到bitcoind提供一个API接口  可以通过HTTP直接对bitcoin函数进行调用

API接口定义:https://baike.baidu.com/item/api/10154

接下来我们知道bitcoin-cli实际是官方提供的http客户端 同样实现bitcoind的接口

那么我们可不可以自己做一个客户端 实现类似bitcond-cli的功能呢

答案是可以的

精通bitcoin一书对rpc的解释为:

3.3.3使用比特币核心的编程接口

bitcoin-cli helper对于探索Bitcoin Core API和测试功能非常有用。 但是应用编程接口的全部要点是以编程方式访问功能。 在本节中,我们将演示从另一个程序访问Bitcoin Core。

Bitcoin Core的API是一个JSON-RPC接口。 JSON代表JavaScript对象符号,它是一种非常方便的方式来呈现人类和程序可以轻松阅读的数据。 RPC代表远程过程调用,这意味着我们通过网络协议调用远程(位于比特币核心节点)的过程(函数)。 在这种情况下,网络协议是HTTP或HTTPS(用于加密连接)。

文章地址:http://book.8btc.com/books/6/masterbitcoin2cn/_book/ch03.html

下面是我用go语言实现web服务 访问bitcoind-rpc接口的实验图

查询余额

查询钱包信息

查询哈希值

通过哈希值查询块的信息

类似的功能可以一直添加

源码如下:

bitcoincode函数是整个交互的核心

//通过变量与bitcoind进行交互
func bitcoincode(s string) string {
	str := strings.Fields(s)
	url := "http://user:[email protected]:18332"
	curl1 := `{"jsonrpc":"1.0","id":"curltest","method":"`
	curl2 := `","params":[`
	curl3 := `]}`

	var quest string
	switch len(str) {
	case 1:
		quest = fmt.Sprintln(curl1+str[0]+curl2+curl3)
	case 2:
		quest = fmt.Sprintln(curl1+str[0]+curl2+"\""+str[1]+"\""+curl3)
	}

	fmt.Println(quest)
	var jsonStr = []byte(quest)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("X-Custom-Header", "myvalue")
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))

	return string(body)
}

业务模块 

//实现web命令及暴露端口
func run() {
	http.HandleFunc("/block_chain/getbalance", blockChainGetBalance)
	http.HandleFunc("/block_chain/getwalletinfo", blockChainGetWalletInfo)
	http.HandleFunc("/block_chain/getbestblockhash", blockChainGetBestBlockHash)
	http.HandleFunc("/block_chain/getblock", blockChainGetBlock)
	http.ListenAndServe(":8332", nil)
}

//实现getbalance
func blockChainGetBalance(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, bitcoincode("getbalance"))
}


//实现getwalletinfo
func blockChainGetWalletInfo(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, bitcoincode("getwalletinfo"))
}

//实现GetBestBlockHash
func blockChainGetBestBlockHash(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, bitcoincode("getbestblockhash"))
}

//实现GetBlock
func blockChainGetBlock(w http.ResponseWriter, r *http.Request) {
	blockData := r.URL.Query().Get("data")
	io.WriteString(w, bitcoincode(blockData))
}

func main() {
	run()
}

根据上面源代码可以实现一个自己定制的钱包客户端

附上bitcoind-rpc命令大全 https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list

猜你喜欢

转载自blog.csdn.net/weixin_42654444/article/details/84025012
今日推荐