Sha256: c9858ae70c9da4414222f5580f8b8345cd67170b318dd4e5c528badf892f16e3

Contents?: true

Size: 1.37 KB

Versions: 11

Compression:

Stored size: 1.37 KB

Contents

# frozen_string_literal: true

module OpenAssets

  MARKER = "\x4f\x41"
  VERSION = "\x01\x00"

  # the open assets payload
  class Payload

    attr_accessor :quantities
    attr_accessor :metadata

    def initialize(quantities = [], metadata = '')
      @quantities = quantities
      @metadata = metadata
    end

    # parse open assets payload
    # @return [Payload] a open assets payload object, if payload is invalid, return nil.
    def self.parse_from_payload(payload)
      buf = StringIO.new(payload)
      marker = buf.read(2)
      version = buf.read(2)
      return nil if marker != MARKER || version != VERSION
      count = Bitcoin.unpack_var_int_from_io(buf)
      quantities = []
      count.times do
        quantities << LEB128.decode_unsigned(buf, buf.pos)
      end
      metadata_length = Bitcoin.unpack_var_int_from_io(buf)
      return nil if buf.length < metadata_length + buf.pos
      metadata = buf.read(metadata_length).each_byte.map(&:chr).join
      new(quantities, metadata)
    end

    # generate binary payload
    def to_payload
      payload = String.new
      payload << MARKER
      payload << VERSION
      payload << Bitcoin.pack_var_int(quantities.size) << quantities.map{|q| LEB128.encode_unsigned(q).read }.join
      payload << Bitcoin.pack_var_int(metadata.length) << metadata.bytes.map{|b| sprintf("%02x", b)}.join.htb
      payload
    end

  end

end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
bitcoinrb-0.2.5 lib/openassets/payload.rb
bitcoinrb-0.2.4 lib/openassets/payload.rb
bitcoinrb-0.2.2 lib/openassets/payload.rb
bitcoinrb-0.2.1 lib/openassets/payload.rb
bitcoinrb-0.2.0 lib/openassets/payload.rb
bitcoinrb-0.1.9 lib/openassets/payload.rb
bitcoinrb-0.1.8 lib/openassets/payload.rb
bitcoinrb-0.1.7 lib/openassets/payload.rb
bitcoinrb-0.1.6 lib/openassets/payload.rb
bitcoinrb-0.1.5 lib/openassets/payload.rb
bitcoinrb-0.1.4 lib/openassets/payload.rb