Class: BitcoinNode::P2p::Client

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

Defined Under Namespace

Classes: CommandHandler, Parser

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port = 8333, probe = LoggingProbe.new("client-#{host}")) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
17
18
# File 'lib/bitcoin_node/p2p/client.rb', line 12

def initialize(host, port = 8333, probe = LoggingProbe.new("client-#{host}"))
  @host, @buffer, @probe = host, String.new, probe
  @socket = TCPSocket.new(host, port)
  @handshaked = false
  @version = BN::Protocol::VERSION
  @probe << { connected: host }
end

Instance Attribute Details

#handshakedObject Also known as: handshaked?

Returns the value of attribute handshaked.



10
11
12
# File 'lib/bitcoin_node/p2p/client.rb', line 10

def handshaked
  @handshaked
end

#versionObject

Returns the value of attribute version.



10
11
12
# File 'lib/bitcoin_node/p2p/client.rb', line 10

def version
  @version
end

Class Method Details

.connect(host, port = 8333, probe = LoggingProbe.new("client-#{host}")) ⇒ Object



6
7
8
# File 'lib/bitcoin_node/p2p/client.rb', line 6

def self.connect(host, port = 8333, probe = LoggingProbe.new("client-#{host}"))
  new(host, port, probe)
end

Instance Method Details

#close!Object



40
41
42
43
# File 'lib/bitcoin_node/p2p/client.rb', line 40

def close!
  @socket.close
  @probe << { closed: @host }
end

#send(message) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/bitcoin_node/p2p/client.rb', line 22

def send(message)
  raise ArgumentError unless BN::Protocol::Message === message

  @probe << { sending: message.command }
  @socket.write(message.raw)

  loop {
    @buffer << @socket.readpartial(1024)
    handler = CommandHandler.new(self, @buffer, @probe)
    if handler.valid_message?
      handler.parse
      break
    end
  }
rescue IOError => e
  BN::ClientLogger.error(e.message)
end