如何使用bitcoin-ruby接口将bitcoind JSON-RPC调用的输出导出为制表符分隔格式的文本文件

时间:2018-03-27 08:01:15

标签: ruby bitcoin json-rpc bitcoind

我在Ubuntu 16.04中运行bitcoind服务器。还使用了使用比特币 - 红宝石连接到比特币RPC的方法:

require 'bitcoin'
require 'net/http'
require 'json'
RPCUSER = "**"
RPCPASSWORD = "**"
HOST = "localhost"
PORT= 8332

def bitcoinRPC(method,param)
    http = Net::HTTP.new(HOST,PORT)
    request = Net::HTTP::Post.new('/')
    request.basic_auth(RPCUSER,RPCPASSWORD)
    request.content_type = 'application/json'
    request.body = {method:method,params:param,id:'jsonrpc'}.to_json
    JSON.parse(http.request(request).body)["result"]

结束

以下RPC命令显示块编号514641的解析数据:

bhash= 514641
bid= bitcoinRPC('getblockhash',[bhash])
bid="0000000000000000003b34a5f6cb571435b71449c38e54bf2cbafb7ca3800501"
blk= bitcoinRPC("getblock",[bid])

blk变量中的键如下:

blk.keys
["hash", "confirmations", "strippedsize", "size", "weight", "height", 
"version", "versionHex", "merkleroot", "tx", "time", "mediantime", "nonce", 
"bits", "difficulty", "chainwork", "previousblockhash", "nextblockhash"]

我想解析" hash"的关键值," tx","时间","难度"从块编号514641内部使用ruby编程计算回块编号1,并以制表符分隔的格式将输出解析为文本文件:

hash     tx      time     difficulty
000...  12X....  2344556   5455345
 --     13X...      --     5678899
 --     14X...      --     6454545

这里,"哈希"和"时间"将是同一块的相同值。我是ruby编程的新手。任何指南都将受到高度赞赏。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为你的blk对象此时只是一个ruby哈希,所以你应该能够做到:

keys = %w[hash tx time difficulty]  # array of strings (keys you want)
data = keys.map{|key| blk[key]} # array of data from the keys

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << keys # keys will be header row of csv
  data.each{|d| csv << d} # loop over data and push into new row of csv
end