2016-05-14 50 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