2016-05-14 49 views
1

我试图根据比特币wiki文档(bitcoin creation according bitcoin wiki)在ruby中创建一个比特币地址。 起始点只是一些模拟ripmed160输出的随机字符串。 可惜我不太有这样的人,这里是我的代码:在ruby中创建比特币地址

require 'base58_gmp' 
tx_hash = "a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5" 

ripmed160 = tx_hash[0..39] 
ripmed160_with_pre = "00" + ripmed160 

sha1 = Digest::SHA256.hexdigest ripmed160_with_pre 
sha2 = Digest::SHA256.hexdigest sha1 

bin_address = Integer("0x" + ripmed160_with_pre + sha2[0..7]) 

bitcoin_address = "1" + Base58GMP.encode(bin_address, 'bitcoin') # => "1GPcbTYDBwJ42MfKkedxjmJ3nrgoaNd2Sf" 

我得到的东西看起来像一个比特币地址,但它不是由blockchain.info认可,所以我想这是无效的。 你能帮我做这个工作吗?

+1

有一个在代码中的其他错误;你尝试转换为一个整数(使用Integer(“0x”+ xx)'_twice_,这会导致错误。我认为这只是一个错字或复制/粘贴错误,因为它使代码失败,而不是给一个不正确的地址。 – matt

+0

此外,代替'Integer(“0x”+ hex)','hex.to_i(16)'。 –

+0

你是对的。我编辑了代码,现在它不再失败。 – user3866773

回答

1

当你计算SHA256校验,确保在前面的步骤,而不是那些字节的十六进制编码的实际字节来计算的话:你已经证明

# First convert to actual bytes. 
bytes = [ripmed160_with_pre].pack('H*') 

# Now calculate the first hash over the raw bytes, and 
# return the raw bytes again for the next hash 
# (note: digest not hexdigest). 
sha1 = Digest::SHA256.digest bytes 

# Second SHA256, using the raw bytes from the previous step 
# but this time we can use hexdigest as the rest of the code 
# assumes hex encoded strings 
sha2 = Digest::SHA256.hexdigest sha1 
+0

Works!Thanks very much – user3866773