Module: Crypto::Base32

Defined in:
lib/wallet_validator/crypto/base32.rb

Constant Summary collapse

TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".freeze
HEX_ENCODE_ARRAY =
%w[0 1 2 3 4 5 6 7 8 9 a b c d e f].freeze

Class Method Summary collapse

Class Method Details

.chunk_decode(ori_bytes) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/wallet_validator/crypto/base32.rb', line 7

def self.chunk_decode(ori_bytes)
  bytes = []
  ori_bytes.each do |c| # strip padding
    break if c == 61

    bytes << c
  end

  n = (bytes.length * 5.0 / 8.0).floor
  p = bytes.length < 8 ? 5 - (n * 8) % 5 : 0
  t = 0

  bytes.each do |o|
    i = TABLE.index(o.chr)
    raise ArgumentError, "invalid character '#{o.chr}'" if i.nil?

    t = (t << 5) + i
  end
  c = t >> p
  ans = []
  (0..n - 1).each do |i|
    ans << i
  end
  ans = ans.reverse
  ans.each_with_index do |i, index|
    ans[index] = ((c >> i * 8) & 0xff).chr
  end
  ans
end

.chunks(str, size) ⇒ Object



37
38
39
40
41
42
# File 'lib/wallet_validator/crypto/base32.rb', line 37

def self.chunks(str, size)
  result = []
  bytes = str.bytes
  result << bytes.shift(size) while bytes.length > 0
  result
end

.decode(str) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/wallet_validator/crypto/base32.rb', line 44

def self.decode(str)
  ans = []
  chunked = chunks(str, 8)
  chunked.each do |ori_bytes|
    temp = chunk_decode(ori_bytes)
    ans << temp
  end
  ans.flatten.join
end

.ua2hex(ua) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/wallet_validator/crypto/base32.rb', line 54

def self.ua2hex(ua)
  memo = ""
  ua.each do |el|
    memo += "#{HEX_ENCODE_ARRAY[el >> 4]}#{HEX_ENCODE_ARRAY[el & 0x0f]}"
  end
  memo
end

.valid?(address, _is_testnet) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
65
66
67
68
69
70
71
# File 'lib/wallet_validator/crypto/base32.rb', line 62

def self.valid?(address, _is_testnet)
  address = address.upcase.delete("-")
  addressHex = ua2hex(Base32.decode(address).bytes)

  version_prefixed_ripemd160_hash = addressHex[0..41]

  computed = Digest::SHA3.hexdigest([version_prefixed_ripemd160_hash].pack("H*"), 256)[0..7]
  checksum = addressHex[42..-1]
  computed == checksum
end