class Faker::Bitcoin

Constants

PROTOCOL_VERSIONS

Public Class Methods

address() click to toggle source
# File lib/faker/bitcoin.rb, line 13
def address
  address_for(:main)
end
testnet_address() click to toggle source
# File lib/faker/bitcoin.rb, line 17
def testnet_address
  address_for(:testnet)
end

Protected Class Methods

address_for(network) click to toggle source
# File lib/faker/bitcoin.rb, line 40
def address_for(network)
  version = PROTOCOL_VERSIONS.fetch(network)
  hash = SecureRandom.hex(20)
  packed = version.chr + [hash].pack("H*")
  checksum = Digest::SHA2.digest(Digest::SHA2.digest(packed))[0..3]
  base58(packed + checksum)
end
base58(str) click to toggle source
# File lib/faker/bitcoin.rb, line 23
def base58(str)
  alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  base = alphabet.size

  lv = 0
  str.split('').reverse.each_with_index { |v,i| lv += v.unpack('C')[0] * 256**i }

  ret = ''
  while lv > 0 do
    lv, mod = lv.divmod(base)
    ret << alphabet[mod]
  end

  npad = str.match(/^#{0.chr}*/)[0].to_s.size
  '1'*npad + ret.reverse
end