Module: Bitcoin::P2P::Handler
- Defined in:
- lib/bitcoin/p2p/handler.rb
Instance Method Summary collapse
- #parse(message) ⇒ Object
- #parse_header ⇒ Object
- #post_init ⇒ Object
- #receive_data(data) ⇒ Object
- #unbind ⇒ Object
Instance Method Details
#parse(message) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/bitcoin/p2p/handler.rb', line 18 def parse() @message ||= '' @message += command, payload, rest = parse_header return unless command msg = Bitcoin::Message.decode(command, payload.bth) puts puts " => receive #{command}. #{msg.to_h}" @message = "" parse(rest) if rest && rest.bytesize > 0 end |
#parse_header ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/bitcoin/p2p/handler.rb', line 30 def parse_header head_magic = Bitcoin.chain_params.magic_head return if @message.nil? || @message.size < Bitcoin::MESSAGE_HEADER_SIZE magic, command, length, checksum = @message.unpack('a4A12Va4') raise Bitcoin::Message::Error, "invalid header magic. #{magic.bth}" unless magic.bth == head_magic payload = @message[Bitcoin::MESSAGE_HEADER_SIZE...(Bitcoin::MESSAGE_HEADER_SIZE + length)] return if payload.size < length raise Bitcoin::Message::Error, "header checksum mismatch. #{checksum.bth}" unless Bitcoin.double_sha256(payload)[0...4] == checksum rest = @message[(Bitcoin::MESSAGE_HEADER_SIZE + length)..-1] [command, payload, rest] end |
#post_init ⇒ Object
6 7 8 |
# File 'lib/bitcoin/p2p/handler.rb', line 6 def post_init puts "> connected! You can send version message." end |
#receive_data(data) ⇒ Object
10 11 12 13 14 15 16 |
# File 'lib/bitcoin/p2p/handler.rb', line 10 def receive_data(data) begin parse(data) rescue Bitcoin::Message::Error => e puts "invalid header magic. #{e.}" end end |
#unbind ⇒ Object
45 46 47 |
# File 'lib/bitcoin/p2p/handler.rb', line 45 def unbind puts "\n => connection is closed. please stop." end |