Reputation: 95
I am running the bitcoind server in Ubuntu 16.04. Also using a method of connecting to bitcoind's RPC using bitcoin-ruby:
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"]
end
The following RPC commands shows the parsed data of block number 514641 :
bhash= 514641
bid= bitcoinRPC('getblockhash',[bhash])
bid="0000000000000000003b34a5f6cb571435b71449c38e54bf2cbafb7ca3800501"
blk= bitcoinRPC("getblock",[bid])
And the keys inside the blk variables are as follows:
blk.keys
["hash", "confirmations", "strippedsize", "size", "weight", "height",
"version", "versionHex", "merkleroot", "tx", "time", "mediantime", "nonce",
"bits", "difficulty", "chainwork", "previousblockhash", "nextblockhash"]
I want to parse the key values of "hash" , "tx", "time", "difficulty" from inside the block number 514641 calculating back to block number 1 using ruby programming and parse the output to a text file in tab-delimited following format:
hash tx time difficulty
000... 12X.... 2344556 5455345
-- 13X... -- 5678899
-- 14X... -- 6454545
Here, the "hash" and "time" will be same values for the same block. I am new to ruby programming. Any guideline will be highly appreciated.
Thanks in advance.
Upvotes: 0
Views: 355
Reputation: 11226
I assume your blk
object is just a ruby hash at this point so you should be able to just do:
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
Upvotes: 0