module CryptoAddress

Constants

ADDRESS_TYPES
VERSION

Public Class Methods

base58_to_int(base58_val) click to toggle source
# File lib/crypto-address.rb, line 41
def base58_to_int(base58_val)
  alpha = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
  int_val, base = 0, alpha.size
  base58_val.reverse.each_char.with_index do |char,index|
    raise ArgumentError, 'Value not a valid Base58 String.' unless char_index = alpha.index(char)
    int_val += char_index*(base**index)
  end
  int_val
end
checksum(hex) click to toggle source
# File lib/crypto-address.rb, line 55
def checksum(hex)
  b = [hex].pack("H*") # unpack hex
  Digest::SHA256.hexdigest( Digest::SHA256.digest(b) )[0...8]
end
checksum_valid?(hex) click to toggle source
# File lib/crypto-address.rb, line 51
def checksum_valid?(hex)
  checksum( hex[0...42] ) == hex[-8..-1]
end
decode_base58(base58_val) click to toggle source
# File lib/crypto-address.rb, line 33
def decode_base58(base58_val)
  s = base58_to_int(base58_val).to_s(16); s = (s.bytesize.odd? ? '0'+s : s)
  s = '' if s == '00'
  leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size
  s = ("00"*leading_zero_bytes) + s  if leading_zero_bytes > 0
  s
end
valid?(address, type = :BTC) click to toggle source
# File lib/crypto-address.rb, line 25
def valid?(address, type = :BTC)
  raise "Unknown currency" unless ADDRESS_TYPES.has_key?(type)
  hex = decode_base58(address) rescue false
  return false unless hex && hex.bytesize == 50
  return false unless ADDRESS_TYPES[type].include?(hex[0...2].to_i(16))
  checksum_valid?(hex)
end