Created
October 16, 2016 08:42
-
-
Save wenweih/4be59c0c79315c203de0c00e67087ee3 to your computer and use it in GitHub Desktop.
Bitcoin/address validation http://rosettacode.org/wiki/Bitcoin/address_validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'digest/sha2' | |
module BitcoinAddress | |
extend self | |
N = [0,1,2,3,4,5,6,7,8,nil,nil,nil,nil,nil,nil,nil,9,10,11,12,13,14,15,16,nil,17,18,19,20,21,nil,22,23,24,25,26,27,28,29,30,31,32,nil,nil,nil,nil,nil,nil,33,34,35,36,37,38,39,40,41,42,43,nil,44,45,46,47,48,49,50,51,52,53,54,55,56,57] | |
def validate? address | |
g = address.bytes.inject(0){|g,n| g*58+N[n-49]}.to_s(16) | |
n = g.slice!(0..-9) | |
(n.length...42).each{n.insert(0,'0')} | |
caculate = Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8] | |
g == caculate ? true : false | |
end | |
private | |
def convert g | |
i,e = '',[] | |
(0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'} | |
e.pack(i) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment