Module: Bech32
- Defined in:
- lib/platon/bech32.rb
Defined Under Namespace
Modules: Encoding
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)
- BECH32M_CONST =
0x2bc830a3
Class Method Summary collapse
-
.create_checksum(hrp, data, spec) ⇒ Object
Returns computed checksum values of
hrp
anddata
. -
.decode(bech, max_length = 90) ⇒ Object
Returns the Bech32 decoded hrp and data.
-
.encode(hrp, data, spec) ⇒ Object
Returns the encoded Bech32 string.
-
.verify_checksum(hrp, data) ⇒ Integer
Verify a checksum given Bech32 string.
Class Method Details
.create_checksum(hrp, data, spec) ⇒ Object
Returns computed checksum values of hrp
and data
42 43 44 45 46 47 |
# File 'lib/platon/bech32.rb', line 42 def create_checksum(hrp, data, spec) values = (hrp) + data const = (spec == Bech32::Encoding::BECH32M ? Bech32::BECH32M_CONST : 1) polymod = polymod(values + [0, 0, 0, 0, 0, 0]) ^ const (0..5).map{|i|(polymod >> 5 * (5 - i)) & 31} end |
.decode(bech, max_length = 90) ⇒ Object
Returns the Bech32 decoded hrp and data.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/platon/bech32.rb', line 23 def decode(bech, max_length = 90) # check uppercase/lowercase return nil if bech.bytes.index{|x| x < 33 || x > 126} return nil if (bech.downcase != bech && bech.upcase != bech) bech = bech.downcase # check data length pos = bech.rindex(SEPARATOR) return nil if pos.nil? || pos + 7 > bech.length || bech.length > max_length # 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 spec = verify_checksum(hrp, data) spec ? [hrp, data[0..-7], spec] : nil end |
.encode(hrp, data, spec) ⇒ Object
Returns the encoded Bech32 string.
17 18 19 20 |
# File 'lib/platon/bech32.rb', line 17 def encode(hrp, data, spec) checksummed = data + create_checksum(hrp, data, spec) hrp + SEPARATOR + checksummed.map{|i|CHARSET[i]}.join end |
.verify_checksum(hrp, data) ⇒ Integer
Verify a checksum given Bech32 string
53 54 55 56 57 58 59 60 61 |
# File 'lib/platon/bech32.rb', line 53 def verify_checksum(hrp, data) const = polymod((hrp) + data) case const when 1 Encoding::BECH32 when BECH32M_CONST Encoding::BECH32M end end |