【问题标题】:How to export the output of bitcoind JSON-RPC calls using bitcoin-ruby interface to a text file in tab-delimited format如何使用 bitcoin-ruby 接口将 bitcoind JSON-RPC 调用的输出导出到制表符分隔格式的文本文件
【发布时间】:2018-09-05 12:56:29
【问题描述】:

我在 Ubuntu 16.04 中运行 bitcoind 服务器。同样使用bitcoin-ruby连接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变量里面的key如下:

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

我想从块号 514641 中解析 "hash" 、 "tx" 、 "time" 、 "difficulty" 的键值,使用 ruby​​ 编程计算回块号 1 并将输出解析为文本文件制表符分隔的以下格式:

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

在这里,“hash”和“time”对于同一个块将是相同的值。我是红宝石编程的新手。任何指南都将受到高度赞赏。

提前致谢。

【问题讨论】:

    标签: ruby bitcoin json-rpc bitcoind


    【解决方案1】:

    我假设您的 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
    

    【讨论】:

    • 出现错误:Traceback(最近一次调用最后一次):6:来自/root/.rbenv/versions/2.5.0/bin/irb:11:in &lt;main&gt;' 5: from (irb):52 4: from /root/.rbenv/versions/2.5.0/lib/ruby/2.5.0/csv.rb:1289:in open' 3: from (irb):54:in block in irb_binding' 2: from (irb):54:in each' 1: from (irb):54:in block (2 levels) in irb_binding' NoMethodError (undefined method 你的意思是?
    • @Rubz 是的,我有一个错字,错误甚至告诉了它是什么。我修复了它,请参阅更新的答案。谢谢。