class DEVp2p::Command

Attributes

receive_callbacks[R]

Public Class Methods

decode_payload(rlp_data) click to toggle source
# File lib/devp2p/command.rb, line 31
def decode_payload(rlp_data)
  case structure
  when RLP::Sedes::CountableList
    decoder = structure
  when Hash
    decoder = RLP::Sedes::List.new(elements: sedes, strict: decode_strict)
  else
    raise InvalidCommandStructure
  end

  data = RLP.decode rlp_data, sedes: decoder
  data = structure.keys.zip(data).to_h if structure.is_a?(Hash)
  data
rescue
  puts "error in decode: #{$!}"
  puts "rlp:"
  puts RLP.decode(rlp_data)
  raise $!
end
encode_payload(data) click to toggle source
# File lib/devp2p/command.rb, line 14
def encode_payload(data)
  if data.is_a?(Hash)
    raise ArgumentError, 'structure must be hash of arg names and sedes' unless structure.instance_of?(Hash)
    data = structure.keys.map {|k| data[k] }
  end

  case structure
  when RLP::Sedes::CountableList
    RLP.encode data, sedes: structure
  when Hash
    raise ArgumentError, 'structure and data length mismatch' unless data.size == structure.size
    RLP.encode data, sedes: RLP::Sedes::List.new(elements: sedes)
  else
    raise InvalidCommandStructure
  end
end
new() click to toggle source
# File lib/devp2p/command.rb, line 58
def initialize
  raise InvalidCommandStructure unless [Hash, RLP::Sedes::CountableList].any? {|c| structure.is_a?(c) }
  @receive_callbacks = []
end
sedes() click to toggle source
# File lib/devp2p/command.rb, line 51
def sedes
  @sedes ||= structure.values
end

Public Instance Methods

create(proto, *args) click to toggle source

optionally implement create

# File lib/devp2p/command.rb, line 64
def create(proto, *args)
  options = args.last.is_a?(Hash) ? args.pop : {}
  raise ArgumentError, "proto #{proto} must be protocol" unless proto.is_a?(Protocol)
  raise ArgumentError, "command structure mismatch" if !options.empty? && structure.instance_of?(RLP::Sedes::CountableList)
  options.empty? ? args : options
end
receive(proto, data) click to toggle source

optionally implement receive

# File lib/devp2p/command.rb, line 72
def receive(proto, data)
  if structure.instance_of?(RLP::Sedes::CountableList)
    receive_callbacks.each {|cb| cb.call(proto, data) }
  else
    receive_callbacks.each {|cb| cb.call(proto, **data) }
  end
end