Class: BitcoinNode::Protocol::Message

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin_node/protocol.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(payload) ⇒ Message

Returns a new instance of Message.

Raises:

  • (ArgumentError)


50
51
52
53
54
# File 'lib/bitcoin_node/protocol.rb', line 50

def initialize(payload)
  raise ArgumentError, 'Expected Payload type' unless Payload === payload
  @payload = payload
  @command = payload.name
end

Instance Attribute Details

#commandObject (readonly)

Returns the value of attribute command.



48
49
50
# File 'lib/bitcoin_node/protocol.rb', line 48

def command
  @command
end

Class Method Details

.validate(raw_message) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/bitcoin_node/protocol.rb', line 68

def self.validate(raw_message)
  network, command, expected_length, checksum = Header.unpack(raw_message)
  raw_payload = raw_message[Header::SIZE...(Header::SIZE + expected_length)]
  if (actual = raw_payload.bytesize) < expected_length
    raise BN::P::IncompleteMessageError.new("Incomplete message (missing #{expected_length - actual} bytes)")
  elsif checksum != BN::Protocol.digest(raw_payload)[0...4]
    raise BN::P::InvalidChecksumError.new("Invalid checksum on command #{command}")
  else
    [raw_payload, command]
  end
end

Instance Method Details

#bytesizeObject



64
65
66
# File 'lib/bitcoin_node/protocol.rb', line 64

def bytesize
  raw.bytesize
end

#rawObject



56
57
58
59
60
61
62
# File 'lib/bitcoin_node/protocol.rb', line 56

def raw
  @raw ||= begin
    [Header.build_from(@payload).raw, @payload.raw]
      .join
      .force_encoding('binary')
  end
end