Module: Bitcoin::Base58
- Defined in:
- lib/bitcoin/base58.rb
Overview
Base58Check encoding https://en.bitcoin.it/wiki/Base58Check_encoding
Constant Summary collapse
- ALPHABET =
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'- SIZE =
ALPHABET.size
- MAX_LENGTH =
Upper bound for #decode. Decoding is quadratic in the length of the input, and the longest value Bitcoin encodes with Base58 is an extended key, at 111 characters.
256
Class Method Summary collapse
-
.decode(base58_val) ⇒ String
decode base58 string to hex value.
-
.encode(hex) ⇒ Object
encode hex value to base58 string.
Class Method Details
.decode(base58_val) ⇒ String
decode base58 string to hex value. which is not in the alphabet.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/bitcoin/base58.rb', line 32 def decode(base58_val) if base58_val.length > MAX_LENGTH raise ArgumentError, "Base58 string must not be longer than #{MAX_LENGTH} characters." end int_val = 0 base58_val.each_char do |char| char_index = ALPHABET.index(char) raise ArgumentError, 'Value passed not a valid Base58 String.' if char_index.nil? int_val = int_val * SIZE + char_index end s = int_val.to_even_length_hex s = '' if s == '00' leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size s = ('00' * leading_zero_bytes) + s if leading_zero_bytes > 0 s end |
.encode(hex) ⇒ Object
encode hex value to base58 string.
16 17 18 19 20 21 22 23 24 25 |
# File 'lib/bitcoin/base58.rb', line 16 def encode(hex) leading_zero_bytes = (hex.match(/^([0]+)/) ? $1 : '').size / 2 int_val = hex.to_i(16) base58_val = '' while int_val > 0 int_val, remainder = int_val.divmod(SIZE) base58_val = ALPHABET[remainder] + base58_val end ('1' * leading_zero_bytes) + base58_val end |