Module: AdequateCryptoAddress::Utils::Bch

Included in:
Bch
Defined in:
lib/adequate_crypto_address/utils/bch.rb

Constant Summary collapse

CHARSET =
'qpzry9x8gf2tvdw0s3jn54khce6mua7l'

Class Method Summary collapse

Class Method Details

.b32decode(inputs) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/adequate_crypto_address/utils/bch.rb', line 14

def b32decode(inputs)
  out = []
  return out unless inputs

  inputs.chars.each do |letter|
    out.push(CHARSET.index(letter))
  end
  out
end

.b32encode(inputs) ⇒ Object



70
71
72
73
74
75
76
# File 'lib/adequate_crypto_address/utils/bch.rb', line 70

def b32encode(inputs)
  out = ''
  inputs.each do |char_code|
    out += CHARSET[char_code].to_s
  end
  out
end

.calculate_cash_checksum(payload) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/adequate_crypto_address/utils/bch.rb', line 55

def calculate_cash_checksum(payload)
  poly = polymod(expanded_prefix + payload + [0, 0, 0, 0, 0, 0, 0, 0])
  out = []
  8.times do |i|
    out.push((poly >> (5 * (7 - i))) & 0x1f)
  end
  out
end

.code_list_to_string(code_list) ⇒ Object



10
11
12
# File 'lib/adequate_crypto_address/utils/bch.rb', line 10

def code_list_to_string(code_list)
  code_list.map { |i| Array(i).pack('C*') }.join
end

.convertbits(data, frombits, tobits, pad: true) ⇒ Object



78
79
80
# File 'lib/adequate_crypto_address/utils/bch.rb', line 78

def convertbits(data, frombits, tobits, pad: true)
  Bech32.convert_bits(data, from_bits: frombits, to_bits: tobits, pad: pad)
end

.expanded_prefix ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/adequate_crypto_address/utils/bch.rb', line 43

def expanded_prefix
  val = if prefix
          prefix.to_s.chars.map do |i|
            i.ord & 0x1f
          end
        else
          []
        end

  val + [0]
end

.polymod(values) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/adequate_crypto_address/utils/bch.rb', line 24

def polymod(values)
  chk = 1
  generator = [
    [0x01, 0x98f2bc8e61],
    [0x02, 0x79b76d99e2],
    [0x04, 0xf33e5fb3c4],
    [0x08, 0xae2eabe2a8],
    [0x10, 0x1e4f43e470]
  ]
  values.each do |value|
    top = chk >> 35
    chk = ((chk & 0x07ffffffff) << 5) ^ value
    generator.each do |i|
      chk ^= i[1] if top.anybits?(i[0])
    end
  end
  chk ^ 1
end

.verify_cash_checksum(payload) ⇒ Object



64
65
66
67
68
# File 'lib/adequate_crypto_address/utils/bch.rb', line 64

def verify_cash_checksum(payload)
  polymod(expanded_prefix + payload).zero?
rescue TypeError
  raise AdequateCryptoAddress::InvalidAddress
end