Class: Bitcoin::Message::Base

Inherits:
Object
  • Object
show all
Extended by:
Util
Includes:
HexConverter, Util
Defined in:
lib/bitcoin/message/base.rb

Overview

Base message class

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util

byte_to_bit, calc_checksum, decode_base58_address, double_sha256, encode_base58_address, hash160, hkdf_sha256, hmac_sha256, pack_boolean, pack_var_int, pack_var_string, padding_zero, sha256, tagged_hash, unpack_boolean, unpack_var_int, unpack_var_int_from_io, unpack_var_string, valid_address?

Methods included from HexConverter

#to_hex

Class Method Details

.from_pkt(message) ⇒ Bitcoin::Message::XXX

Decode message data to message object.

Parameters:

  • message (String)

    with binary format.

Returns:

  • (Bitcoin::Message::XXX)

    An instance of a class that inherits Bitcoin::Message::Base

Raises:

  • (ArgumentError)

    Occurs for data that cannot be decoded.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/bitcoin/message/base.rb', line 30

def self.from_pkt(message)
  buf = StringIO.new(message)
  magic = buf.read(4)
  raise ArgumentError, 'Invalid magic.' unless magic == Bitcoin.chain_params.magic_head.htb
  command = buf.read(12).delete("\x00")
  length = buf.read(4).unpack1('V')
  checksum = buf.read(4)
  payload = buf.read(length)
  raise ArgumentError, 'Checksum do not match.' unless checksum == Bitcoin.double_sha256(payload)[0...4]
  Bitcoin::Message.decode(command, payload&.bth)
end

Instance Method Details

#to_payloadObject

abstract method



22
23
24
# File 'lib/bitcoin/message/base.rb', line 22

def to_payload
  raise 'to_payload must be implemented in a child class.'
end

#to_pktObject

generate message header (binary format) bitcoin.org/en/developer-reference#message-headers



12
13
14
15
16
17
18
19
# File 'lib/bitcoin/message/base.rb', line 12

def to_pkt
  payload = to_payload
  magic = Bitcoin.chain_params.magic_head.htb
  command_name = self.class.const_get(:COMMAND, false).ljust(12, "\x00")
  payload_size = [payload.bytesize].pack('V')
  checksum = Bitcoin.double_sha256(payload)[0...4]
  magic << command_name << payload_size << checksum << payload
end