在ruby中创建比特币地址

时间:2016-05-14 12:48:45

标签: ruby sha256 bitcoin

我正在尝试根据比特币维基(bitcoin creation according bitcoin wiki)的文档在ruby中创建比特币地址。 起点只是一些模拟ripmed160输出的随机字符串。 不幸的是,我没有成功这样做,这是我的代码:

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 个答案:

答案 0 :(得分: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