Module: Nano::Base32

Extended by:
Base32
Included in:
Base32
Defined in:
lib/nano/base32.rb

Overview

This module performs encoding and decoding of Base32 as specified by the Nano protocol.

Constant Summary collapse

ALPHABET =

The Base32 alphabet of characters.

"13456789abcdefghijkmnopqrstuwxyz".freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.read_char(chr) ⇒ Object

Raises:

  • (ArgumentError)


79
80
81
82
83
# File 'lib/nano/base32.rb', line 79

def read_char(chr)
  idx = ALPHABET.index(chr)
  raise ArgumentError, "Character #{chr} not base32 compliant" if idx.nil? 
  idx
end

Instance Method Details

#decode(str) ⇒ Object

Decodes a Base32 encoded string into a hex string

Parameters:

  • str (String)

    The base32 encoded string



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/nano/base32.rb', line 51

def decode(str)
  length = str.length
  leftover = (length * 5) % 8
  offset = leftover == 0 ? 0 : 8 - leftover

  bits = 0
  value = 0

  output = Array.new

  length.times do |i|
    value = (value << 5) | read_char(str[i])
    bits += 5

    if bits >= 8
      output.push((value >> (bits + offset - 8)) & 255)
      bits -= 8
    end
  end

  if bits > 0
    output.push((value << (bits + offset - 8)) & 255)
  end

  output = output.drop(1) unless leftover == 0
  Nano::Utils.bytes_to_hex(output)
end

#encode(bytes) ⇒ String

Encode an array of bytes into Base32 string.

Parameters:

  • bytes (Array<Int8>)

    The byte array to encode.

Returns:

  • (String)

    The base32 encoded representation of the bytes



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/nano/base32.rb', line 20

def encode(bytes)
  length = bytes.length
  leftover = (length * 8) % 5
  offset = leftover == 0 ? 0 : 5 - leftover
  value = 0
  output = ""
  bits = 0

  length.times do |i|
    value = (value << 8) | bytes[i]
    bits += 8

    while bits >= 5
      output += ALPHABET[(value >> bits + offset - 5) & 31]
      bits -= 5
    end
  end

  if bits > 0
    output += ALPHABET[(value << (5 - (bits + offset))) & 31]
  end

  output
end