Class: BitcoinCigs::Base58

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin_cigs/base_58.rb

Constant Summary collapse

CHARS =
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
CHAR_SIZE =
CHARS.size

Class Method Summary collapse

Class Method Details

.decode(s) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/bitcoin_cigs/base_58.rb', line 6

def self.decode(s)
  int_val = 0
  s.reverse.split('').each_with_index do |char, index|
    char_index = CHARS.index(char)
    return nil if char_index.nil?
    int_val += char_index * (CHAR_SIZE ** index)
  end
  
  leading_zeros = /^#{CHARS[0]}*/.match(s).to_s.size
  
  ["#{"00" * leading_zeros}#{int_val.to_s(16)}"].pack('H*')
end

.encode(s) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/bitcoin_cigs/base_58.rb', line 19

def self.encode(s)
  int_val = s.unpack('H*').first.to_i(16)
  
  base58_val = ''
  while int_val >= CHAR_SIZE
    mod = int_val % CHAR_SIZE
    base58_val = CHARS[mod,1] + base58_val
    int_val = (int_val - mod) / CHAR_SIZE
  end
  
  result = CHARS[int_val, 1] + base58_val
  
  s.chars.each do |char|
    if char == "\x00"
      result = CHARS[0] + result
    else
      break
    end
  end
  
  result
end