Module: Bech32

Defined in:
lib/bech32.rb,
lib/bech32/version.rb,
lib/bech32/segwit_addr.rb

Defined Under Namespace

Classes: SegwitAddr

Constant Summary collapse

SEPARATOR =
'1'
CHARSET =
%w(q p z r y 9 x 8 g f 2 t v d w 0 s 3 j n 5 4 k h c e 6 m u a 7 l)
VERSION =
"1.0.3"

Class Method Summary collapse

Class Method Details

.create_checksum(hrp, data) ⇒ Object

Returns computed checksum values of hrp and data



57
58
59
60
61
# File 'lib/bech32.rb', line 57

def create_checksum(hrp, data)
  values = expand_hrp(hrp) + data
  polymod = polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
  (0..5).map{|i|(polymod >> 5 * (5 - i)) & 31}
end

.decode(bech) ⇒ Object

Returns the Bach32 decoded hrp and data.

require 'bech32'

addr = 'BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4'
hrp, data = Bech32.decode(addr)

<i>Generates:</i>
'bc' # hrp
[0, 14, 20, 15, 7, 13, 26, 0, 25, 18, 6, 11, 13, 8, 21, 4, 20, 3, 17, 2, 29, 3, 12, 29, 3, 4, 15, 24, 20, 6, 14, 30, 22] # data


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bech32.rb', line 36

def decode(bech)
  # check invalid bytes
  return nil if bech.scrub('?').include?('?')
  # check uppercase/lowercase
  return nil if (bech.downcase != bech && bech.upcase != bech)
  bech.each_char{|c|return nil if c.ord < 33 || c.ord > 126}
  bech = bech.downcase
  # check data length
  pos = bech.rindex(SEPARATOR)
  return nil if pos.nil? || pos + 7 > bech.length || bech.length > 90
  # check valid charset
  bech[pos+1..-1].each_char{|c|return nil unless CHARSET.include?(c)}
  # split hrp and data
  hrp = bech[0..pos-1]
  data = bech[pos+1..-1].each_char.map{|c|CHARSET.index(c)}
  # check checksum
  return nil unless verify_checksum(hrp, data)
  [hrp, data[0..-7]]
end

.encode(hrp, data) ⇒ Object

Returns the encoded Bech32 string.

require 'bech32'

bech = Bech32.encode('bc', [])

<i>Generates:</i>
'BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4' # bech


20
21
22
23
# File 'lib/bech32.rb', line 20

def encode(hrp, data)
  checksummed = data + create_checksum(hrp, data)
  hrp + SEPARATOR + checksummed.map{|i|CHARSET[i]}.join
end

.verify_checksum(hrp, data) ⇒ Object

Verify a checksum given Bech32 string



64
65
66
# File 'lib/bech32.rb', line 64

def verify_checksum(hrp, data)
  polymod(expand_hrp(hrp) + data) == 1
end