Class: AddressCodec::Codec
- Inherits:
-
Object
- Object
- AddressCodec::Codec
- Defined in:
- lib/address-codec/codec.rb
Direct Known Subclasses
Instance Method Summary collapse
-
#decode(base58string, opts) ⇒ Hash
Decodes a base58 string and verifies its version and checksum.
-
#decode_checked(base58string) ⇒ Array<Integer>
Decodes a base58 string and verifies its checksum.
-
#encode(bytes, opts) ⇒ String
Encodes a byte array into a base58 string with a version prefix and checksum.
-
#encode_checked(bytes) ⇒ String
Encodes a byte array into a base58 string with a checksum.
-
#initialize ⇒ Codec
constructor
A new instance of Codec.
Constructor Details
#initialize ⇒ Codec
Returns a new instance of Codec.
8 9 10 |
# File 'lib/address-codec/codec.rb', line 8 def initialize @codec = Core::Base58XRP.new end |
Instance Method Details
#decode(base58string, opts) ⇒ Hash
Decodes a base58 string and verifies its version and checksum.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/address-codec/codec.rb', line 25 def decode(base58string, opts) versions = opts[:versions] types = opts[:version_types] without_sum = decode_checked(base58string) if versions.length > 1 && !opts[:expected_length] raise 'expected_length is required because there are >= 2 possible versions' end version_length_guess = versions[0].is_a?(Numeric) ? 1 : versions[0].length payload_length = opts[:expected_length] || without_sum.length - version_length_guess version_bytes = without_sum[0...-payload_length] payload = without_sum[-payload_length..-1] versions.each_with_index do |version, i| version = Array(version) if version_bytes == version return { version: version, bytes: payload, type: types ? types[i] : nil } end end raise 'version_invalid: version bytes do not match any of the provided version(s)' end |
#decode_checked(base58string) ⇒ Array<Integer>
Decodes a base58 string and verifies its checksum.
65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/address-codec/codec.rb', line 65 def decode_checked(base58string) bytes = decode_raw(base58string) if bytes.length < 5 raise 'invalid_input_size: decoded data must have length >= 5' end unless verify_check_sum(bytes) raise 'checksum_invalid' end bytes[0...-4] end |
#encode(bytes, opts) ⇒ String
Encodes a byte array into a base58 string with a version prefix and checksum.
16 17 18 19 |
# File 'lib/address-codec/codec.rb', line 16 def encode(bytes, opts) versions = opts[:versions] encode_versioned(bytes, versions, opts[:expected_length]) end |
#encode_checked(bytes) ⇒ String
Encodes a byte array into a base58 string with a checksum.
57 58 59 60 |
# File 'lib/address-codec/codec.rb', line 57 def encode_checked(bytes) check = sha256(sha256(bytes))[0, 4] encode_raw(bytes + check) end |