Class: Sibit::Base58

Inherits:
Object
  • Object
show all
Defined in:
lib/sibit/base58.rb

Overview

Base58 encoding for Bitcoin addresses.

Encapsulates hex data and provides encoding/decoding functionality.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright (c) 2019-2026 Yegor Bugayenko

License

MIT

Constant Summary collapse

ALPHABET =
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Base58

Returns a new instance of Base58.



21
22
23
# File 'lib/sibit/base58.rb', line 21

def initialize(data)
  @data = data
end

Instance Method Details

#checkObject



47
48
49
# File 'lib/sibit/base58.rb', line 47

def check
  Digest::SHA256.hexdigest(Digest::SHA256.digest([@data].pack('H*')))[0...8]
end

#decodeObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/sibit/base58.rb', line 35

def decode
  num = 0
  @data.each_char do |c|
    idx = ALPHABET.index(c)
    raise(Sibit::Error, "Invalid Base58 character '#{c}' in address '#{@data}'") if idx.nil?
    num = (num * 58) + idx
  end
  hex = num.zero? ? '' : num.to_s(16)
  hex = "0#{hex}" if hex.length.odd?
  ('00' * @data.match(/^1*/)[0].length) + hex
end

#encodeObject



25
26
27
28
29
30
31
32
33
# File 'lib/sibit/base58.rb', line 25

def encode
  num = @data.to_i(16)
  result = ''
  while num.positive?
    num, remainder = num.divmod(58)
    result = ALPHABET[remainder] + result
  end
  ('1' * [@data].pack('H*').match(/^\x00*/)[0].length) + result
end