Class: CryptoconditionsRuby::Utils::Base58

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

Constant Summary collapse

CHARS =
%w(123456789 ABCDEFGHJKLMNPQRSTUVWXYZ abcdefghijkmnopqrstuvwxyz).freeze

Class Method Summary collapse

Class Method Details

.decode(data_string) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/cryptoconditions_ruby/utils/base58.rb', line 35

def self.decode(data_string)
  vlong = data_string.each_byte.inject(0) do |store, b|
    store = decoding_table[b.chr] + (58 * store)
    store
  end
  result = ''
  while vlong > 0
    result += (vlong % 256).chr
    vlong /= 256
  end
  while data_string[0] == '1'
    result += "\x00"
    data_string = data_string[1..-1]
  end
  result.reverse
end

.decoding_tableObject



6
7
8
# File 'lib/cryptoconditions_ruby/utils/base58.rb', line 6

def self.decoding_table
  @decoding_table ||= generate_decoding_table
end

.encode(data) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cryptoconditions_ruby/utils/base58.rb', line 20

def self.encode(data)
  cdata = data.unpack('C*')
  vlong = cdata.inject(0) { |store, v| v + store * 256 }
  result = ''
  while vlong > 0
    result += encoding_table[vlong % 58]
    vlong /= 58
  end
  while cdata.first.zero?
    result += '1'
    cdata = cdata[1..-1]
  end
  result.reverse
end

.encoding_tableObject



16
17
18
# File 'lib/cryptoconditions_ruby/utils/base58.rb', line 16

def self.encoding_table
  @encoding_table ||= decoding_table.invert
end

.generate_decoding_tableObject



10
11
12
13
14
# File 'lib/cryptoconditions_ruby/utils/base58.rb', line 10

def self.generate_decoding_table
  CHARS.join.split('').each_with_index.each_with_object({}) do |(c, i), store|
    store[c] = i
  end
end