user3866773 user3866773 - 2 years ago 168
Ruby Question

create bitcoin address in ruby

I am trying to create a bitcoin address in ruby according to the documentation of bitcoin wiki (bitcoin creation according bitcoin wiki).
Starting point is just some random string which emulates the output of ripmed160.
Unfortunately I don't quite succeed in doing so, here is my code:

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(Integer(bin_address), 'bitcoin') # => "1GPcbTYDBwJ42MfKkedxjmJ3nrgoaNd2Sf"

I get something that looks like a bitcoin address but it is not recognised by so I guess it is invalid.
Can you please help me to make that work.

Answer Source

When you calculate the SHA256 checksum, make sure to calculate it over the actual bytes of the previous step, not the hex encoding of those bytes:

# 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download