Class: Bitcoin::Connection

Inherits:
EM::Connection
  • Object
show all
Includes:
ConnectionHandler
Defined in:
lib/bitcoin/connection.rb

Overview

Establish connection to node

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ConnectionHandler

#on_addr, #on_block, #on_get_block, #on_get_transaction, #on_handshake_begin, #on_handshake_complete, #on_inv_block, #on_inv_transaction, #on_tx, #on_verack, #on_version, #query_blocks

Constructor Details

#initialize(host, port, connections) ⇒ Connection

Returns a new instance of Connection.



84
85
86
87
88
# File 'lib/bitcoin/connection.rb', line 84

def initialize(host, port, connections)
  @sockaddr = [port, host]
  @connections = connections
  @parser = Bitcoin::Protocol::Parser.new(self)
end

Class Method Details

.connect(host, port, connections) ⇒ Object



104
105
106
# File 'lib/bitcoin/connection.rb', line 104

def self.connect(host, port, connections)
  EM.connect(host, port, self, host, port, connections)
end

.connect_random_from_dns(connections) ⇒ Object



108
109
110
111
112
113
114
115
116
# File 'lib/bitcoin/connection.rb', line 108

def self.connect_random_from_dns(connections)
  seeds = Bitcoin.network[:dns_seeds]
  if seeds.empty?
    raise 'No DNS seeds available. Provide IP, configure seeds, or use different network.'
  end

  host = Resolv::DNS.new.getaddresses(seeds.sample).map(&:to_s).sample
  connect(host, Bitcoin.network[:default_port], connections)
end

Instance Method Details

#post_initObject



90
91
92
93
# File 'lib/bitcoin/connection.rb', line 90

def post_init
  p ['connected', @sockaddr]
  EM.schedule { on_handshake_begin }
end

#receive_data(data) ⇒ Object



95
96
97
# File 'lib/bitcoin/connection.rb', line 95

def receive_data(data)
  @parser.parse(data)
end

#unbindObject



99
100
101
102
# File 'lib/bitcoin/connection.rb', line 99

def unbind
  p ['disconnected', @sockaddr]
  self.class.connect_random_from_dns(@connections)
end