Class: Ciri::DevP2P::Peer

Inherits:
Object
  • Object
show all
Includes:
Actor
Defined in:
lib/ciri/devp2p/peer.rb

Overview

represent a connected remote node

Defined Under Namespace

Classes: DiscoverError, UnknownMessageCodeError

Constant Summary

Constants included from Actor

Actor::LOGGER

Instance Attribute Summary collapse

Attributes included from Actor

#executor

Instance Method Summary collapse

Methods included from Actor

#<<, #call, #enqueue, #loop_callback, #raise_error, #send_stop, #start_loop, #wait

Constructor Details

#initialize(connection, handshake, protocols) ⇒ Peer

Returns a new instance of Peer.


44
45
46
47
48
49
50
# File 'lib/ciri/devp2p/peer.rb', line 44

def initialize(connection, handshake, protocols)
  @connection = connection
  @handshake = handshake
  @protocols = protocols
  @protocol_io_hash = make_protocol_io_hash(protocols, handshake.caps, connection)
  super()
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection


42
43
44
# File 'lib/ciri/devp2p/peer.rb', line 42

def connection
  @connection
end

Instance Method Details

#handle(msg) ⇒ Object


81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/ciri/devp2p/peer.rb', line 81

def handle(msg)
  if msg.code == RLPX::MESSAGES[:ping]    #TODO send pong

  elsif msg.code == RLPX::MESSAGES[:discover]
    reason = RLP.decode_with_type(msg.payload, Integer)
    raise DiscoverError.new("receive error discovery message, reason: #{reason}")
  else
    # send msg to sub protocol
    if (protocol_io = find_protocol_io_by_msg_code(msg.code)).nil?
      raise UnknownMessageCodeError.new("can't find protocol with msg code #{msg.code}")
    end
    protocol_io.msg_queue << msg
  end
end

#node_idObject


52
53
54
# File 'lib/ciri/devp2p/peer.rb', line 52

def node_id
  @node_id ||= RLPX::NodeID.from_raw_id(@handshake.id)
end

#read_loopObject

read and handle msg


65
66
67
68
69
70
71
72
73
# File 'lib/ciri/devp2p/peer.rb', line 65

def read_loop
  loop do
    msg = connection.read_msg
    msg.received_at = Time.now
    handle(msg)
  end
rescue StandardError => e
  self << [:raise_error, e]
end

#startObject

start peer handle msg, handle sub protocols


58
59
60
61
62
# File 'lib/ciri/devp2p/peer.rb', line 58

def start
  executor.post {read_loop}
  start_protocols
  super
end

#start_protocolsObject


75
76
77
78
79
# File 'lib/ciri/devp2p/peer.rb', line 75

def start_protocols
  @protocols.each do |protocol|
    protocol.start.(self, @protocol_io_hash[protocol.name])
  end
end