Class: Bitcoin::Network::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin/network/node.rb

Constant Summary collapse

DEFAULT_CONFIG =
{
  :network => :bitcoin,
  :listen => ["0.0.0.0", nil],
  :connect => [],
  :command => ["127.0.0.1", 9999],
  :storage => "utxo::sqlite://~/.bitcoin-ruby/<network>/blocks.db",
  :announce => false,
  :external_port => nil,
  :mode => :full,
  :cache_head => true,
  :index_nhash => false,
  :index_p2sh_type => false,
  :dns => true,
  :epoll_limit => 10000,
  :epoll_user => nil,
  :addr_file => "~/.bitcoin-ruby/<network>/peers.json",
  :log => {
    :network => :info,
    :storage => :info,
  },
  :max => {
    :connections_out => 8,
    :connections_in => 32,
    :connections => 8,
    :addr => 256,
    :queue => 501,
    :inv => 501,
    :inv_cache => 0,
    :unconfirmed => 100,
  },
  :intervals => {
    :queue => 1,
    :inv_queue => 1,
    :addrs => 5,
    :connect => 5,
    :relay => 0,
  },
  :import => nil,
  :skip_validation => false,
  :check_blocks => 1000,
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Node

Returns a new instance of Node.



93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/bitcoin/network/node.rb', line 93

def initialize config = {}
  @config = DEFAULT_CONFIG.deep_merge(config)
  @log = Bitcoin::Logger.create(:network, @config[:log][:network])
  @connections, @command_connections = [], []
  @queue, @queue_thread, @inv_queue, @inv_queue_thread = [], nil, [], nil
  set_store
  load_addrs
  @timers = {}
  @inv_cache = []
  @notifiers = {}
  @relay_propagation, @last_block_time, @external_ips = {}, Time.now, []
  @unconfirmed, @relay_tx = {}, {}
end

Instance Attribute Details

#addrsObject (readonly)

peer addrs (Array of Bitcoin::Protocol::Addr)



36
37
38
# File 'lib/bitcoin/network/node.rb', line 36

def addrs
  @addrs
end

#command_connectionsObject (readonly)

command connections (Array of CommandHandler)



21
22
23
# File 'lib/bitcoin/network/node.rb', line 21

def command_connections
  @command_connections
end

#configObject (readonly)

configuration hash



12
13
14
# File 'lib/bitcoin/network/node.rb', line 12

def config
  @config
end

#connectionsObject (readonly)

connections to other peers (Array of ConnectionHandler)



18
19
20
# File 'lib/bitcoin/network/node.rb', line 18

def connections
  @connections
end

#external_ipsObject

our external ip addresses we got told by peers



42
43
44
# File 'lib/bitcoin/network/node.rb', line 42

def external_ips
  @external_ips
end

#inv_cacheObject (readonly)

inventory cache (blocks/tx recently downloaded)



30
31
32
# File 'lib/bitcoin/network/node.rb', line 30

def inv_cache
  @inv_cache
end

#inv_queueObject (readonly)

inventory queue (blocks/tx waiting to be downloaded)



27
28
29
# File 'lib/bitcoin/network/node.rb', line 27

def inv_queue
  @inv_queue
end

#last_block_timeObject (readonly)

time when the last main chain block was added



45
46
47
# File 'lib/bitcoin/network/node.rb', line 45

def last_block_time
  @last_block_time
end

#logObject (readonly)

logger



15
16
17
# File 'lib/bitcoin/network/node.rb', line 15

def log
  @log
end

#notifiersObject (readonly)

clients to be notified for new block/tx events



39
40
41
# File 'lib/bitcoin/network/node.rb', line 39

def notifiers
  @notifiers
end

#queueObject (readonly)

storage queue (blocks/tx waiting to be stored)



24
25
26
# File 'lib/bitcoin/network/node.rb', line 24

def queue
  @queue
end

#relay_propagationObject

Returns the value of attribute relay_propagation.



48
49
50
# File 'lib/bitcoin/network/node.rb', line 48

def relay_propagation
  @relay_propagation
end

#relay_txObject

Returns the value of attribute relay_tx.



47
48
49
# File 'lib/bitcoin/network/node.rb', line 47

def relay_tx
  @relay_tx
end

#storeObject (readonly)

Bitcoin::Storage backend



33
34
35
# File 'lib/bitcoin/network/node.rb', line 33

def store
  @store
end

Instance Method Details

#accept_connections?Boolean

should the node accept new incoming connections?

Returns:

  • (Boolean)


506
507
508
# File 'lib/bitcoin/network/node.rb', line 506

def accept_connections?
  connections.select(&:incoming?).size < config[:max][:connections_in]
end

#addrObject

get Addr object for our own server



511
512
513
514
515
516
# File 'lib/bitcoin/network/node.rb', line 511

def addr
  @addr = Bitcoin::P::Addr.new
  @addr.time, @addr.service, @addr.ip, @addr.port =
    Time.now.tv_sec, (1 << 0), external_ip, external_port
  @addr
end

#connect_dnsObject

query addrs from dns seed and connect



299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/bitcoin/network/node.rb', line 299

def connect_dns
  unless Bitcoin.network[:dns_seeds].any?
    log.warn { "No DNS seed nodes available" }
    return connect_known_peers
  end
  connect_dns_resolver(Bitcoin.network[:dns_seeds].sample) do |addrs|
    log.debug { "DNS returned addrs: #{addrs.inspect}" }
    addrs.sample(@config[:max][:connections_out] / 2).uniq.each do |addr|
      connect_peer(addr, Bitcoin.network[:default_port])
    end
  end
end

#connect_dns_nslookup(seed) {|addrs| ... } ⇒ Object

get peers from dns via nslookup

Yields:



338
339
340
341
342
343
# File 'lib/bitcoin/network/node.rb', line 338

def connect_dns_nslookup(seed)
  log.info { "Querying addresses from DNS seed: #{seed}" }
  addrs = `nslookup #{seed}`.scan(/Address\: (.+)$/).flatten
  #  exit  if @config[:dns] && hosts.size == 0
  yield(addrs)
end

#connect_dns_resolver(seed) ⇒ Object

get peer addrs from given dns seed using em/dns_resolver. fallback to using ‘nslookup` if it is not installed or fails.



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/bitcoin/network/node.rb', line 321

def connect_dns_resolver(seed)
  if Bitcoin.require_dependency "em/dns_resolver", gem: "em-dns", exit: false
    log.info { "Querying addresses from DNS seed: #{seed}" }

    dns = EM::DnsResolver.resolve(seed)
    dns.callback {|addrs| yield(addrs) }
    dns.errback do |*a|
      log.error { "Cannot resolve DNS seed #{seed}: #{a.inspect}" }
      connect_dns_nslookup(Bitcoin.network[:dns_seeds].sample) {|a| yield(a) }
    end
  else
    log.info { "Falling back to nslookup resolver." }
    connect_dns_nslookup(seed) {|a| yield(a) }
  end
end

#connect_known_peersObject



312
313
314
315
316
317
# File 'lib/bitcoin/network/node.rb', line 312

def connect_known_peers
  log.debug { "Attempting to connecting to known nodes" }
  Bitcoin.network[:known_nodes].shuffle[0..3].each do |node|
    connect_peer node, Bitcoin.network[:default_port]
  end
end

#connect_peer(host, port) ⇒ Object

connect to peer at given host / port



289
290
291
292
293
294
295
296
# File 'lib/bitcoin/network/node.rb', line 289

def connect_peer host, port
  return  if @connections.map{|c| c.host }.include?(host)
  log.debug { "Attempting to connect to #{host}:#{port}" }
  EM.connect(host, port.to_i, ConnectionHandler, self, host, port.to_i, :out)
rescue
  log.debug { "Error connecting to #{host}:#{port}" }
  log.debug { $!.inspect }
end

#epoll_initObject

initiate epoll with given file descriptor and set effective user



192
193
194
195
196
197
198
199
200
# File 'lib/bitcoin/network/node.rb', line 192

def epoll_init
  log.info { "EPOLL: Available file descriptors: " +
    EM.set_descriptor_table_size(@config[:epoll_limit]).to_s }
  if @config[:epoll_user]
    EM.set_effective_user(@config[:epoll_user])
    log.info { "EPOLL: Effective user set to: #{@config[:epoll_user]}" }
  end
  EM.epoll = true
end

#external_ipObject

get the external ip that was suggested in version messages from other peers most often.



470
471
472
473
474
# File 'lib/bitcoin/network/node.rb', line 470

def external_ip
  @external_ips.group_by(&:dup).values.max_by(&:size).first
rescue
  @config[:listen][0]
end

#external_portObject

get the external port assume the same as local port if config option :external_port isn’t given explicitly



478
479
480
# File 'lib/bitcoin/network/node.rb', line 478

def external_port
  @config[:external_port] || @config[:listen][1] || Bitcoin.network[:default_port]
end

#getblocks(locator = store.get_locator) ⇒ Object

query blocks from random peer



366
367
368
369
370
371
372
373
374
375
376
# File 'lib/bitcoin/network/node.rb', line 366

def getblocks locator = store.get_locator
  peer = @connections.select(&:connected?).sample
  return  unless peer
  log.info { "querying blocks from #{peer.host}:#{peer.port}" }
  case @config[:mode]
  when /lite/
    peer.send_getheaders locator  unless @queue.size >= @config[:max][:queue]
  when /full|pruned/
    peer.send_getblocks locator  unless @inv_queue.size >= @config[:max][:inv]
  end
end

#load_addrsObject



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/bitcoin/network/node.rb', line 133

def load_addrs
  file = @config[:addr_file].sub("~", ENV["HOME"])
    .sub("<network>", Bitcoin.network_name.to_s)
  unless File.exist?(file)
    @addrs = []
    FileUtils.mkdir_p(File.dirname(file))
    return
  end
  @addrs = JSON.load(File.read(file)).map do |a|
    addr = Bitcoin::P::Addr.new
    addr.time, addr.service, addr.ip, addr.port =
      a['time'], a['service'], a['ip'], a['port']
    addr
  end
  log.info { "Initialized #{@addrs.size} addrs from #{file}." }
rescue
  @addrs = []
  log.warn { "Error loading addrs from #{file}." }
end

#push_notification(channel, message) ⇒ Object

push notification message to channel



483
484
485
# File 'lib/bitcoin/network/node.rb', line 483

def push_notification channel, message
  @notifiers[channel.to_sym].push(message)  if @notifiers[channel.to_sym]
end

#queue_inv(inv) ⇒ Object

queue inv, caching the most current ones



447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/bitcoin/network/node.rb', line 447

def queue_inv inv
  hash = inv[1].unpack("H*")[0]
  return  if @inv_queue.include?(inv) || @queue.select {|i| i[1].hash == hash }.any?

  return  if @store.send("has_#{inv[0]}", hash)

#      @inv_cache.shift(128)  if @inv_cache.size > @config[:max][:inv_cache]
#      return  if @inv_cache.include?([inv[0], inv[1]]) ||
#        @inv_queue.size >= @config[:max][:inv] ||
#        ([email protected]_sync? && inv[0] == :tx)
#      @inv_cache << [inv[0], inv[1]]
  @inv_queue << inv
end

#runObject



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/bitcoin/network/node.rb', line 202

def run
  @started = Time.now

  EM.add_shutdown_hook do
    store_addrs
    log.info { "Bye" }
  end

  # enable kqueue (BSD, OS X)
  if EM.kqueue?
    log.info { 'Using BSD kqueue' }
    EM.kqueue = true
  end

  # enable epoll (Linux)
  if EM.epoll?
    log.info { 'Using Linux epoll' }
    epoll_init
  end

  EM.run do

    start_timers

    host, port = *@config[:command]
    port ||= Bitcoin.network[:default_port]
    if host
      log.debug { "Trying to bind command socket to #{host}:#{port}" }
      EM.start_server(host, port, CommandHandler, self)
      log.info { "Command socket listening on #{host}:#{port}" }
    end

    host, port = *@config[:listen]
    port ||= Bitcoin.network[:default_port]
    if host
      log.debug { "Trying to bind server socket to #{host}:#{port}" }
      EM.start_server(host, port.to_i, ConnectionHandler, self, host, port.to_i, :in)
      log.info { "Server socket listening on #{host}:#{port}" }
    end

    @config[:connect].each do |host, port|
      port ||= Bitcoin.network[:default_port]
      connect_peer(host, port)
      log.info { "Connecting to #{host}:#{port}" }
    end

    work_connect if @addrs.any?
    connect_dns  if @config[:dns]

    Signal.trap("INT") do
      puts "Shutting down. You can force-quit by pressing Ctrl-C again, but it might corrupt your database!"
      Signal.trap("INT") do
        puts "Force Quit"
        exit 1
      end
      self.stop
    end

    subscribe(:block) do |blk, depth|
      next  unless @store.in_sync?
      @log.debug { "Relaying block #{blk.hash}" }
      @connections.each do |conn|
        next  unless conn.connected?
        conn.send_inv(:block, blk.hash)
      end
    end

    @store.subscribe(:block) do |blk, depth, chain|
      if chain == 0 && blk.hash == @store.get_head.hash
        @last_block_time = Time.now
        push_notification(:block, [blk, depth])
        blk.tx.each {|tx| @unconfirmed.delete(tx.hash) }
      end
      getblocks  if chain == 2 && @store.in_sync?
    end

    @store.subscribe(:reorg) do |new_main, new_side|
      @log.warn { "Reorg of #{new_side.size} blocks." }
      new_main.each {|b| @log.debug { "new main: #{b}" } }
      new_side.each {|b| @log.debug { "new side: #{b}" } }
      push_notification(:reorg, [new_main, new_side])
    end

  end
end

#set_storeObject



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/bitcoin/network/node.rb', line 107

def set_store
  backend, config = @config[:storage].split('::')
  @store = Bitcoin::Storage.send(backend, {
      db: config, mode: @config[:mode], cache_head: @config[:cache_head],
      skip_validation: @config[:skip_validation], index_nhash: @config[:index_nhash],
      index_p2sh_type: @config[:index_p2sh_type],
      log_level: @config[:log][:storage]}, ->(locator) {
      peer = @connections.select(&:connected?).sample
      peer.send_getblocks(locator)
    })
  @store.log.level = @config[:log][:storage]
  @store.check_consistency(@config[:check_blocks])
  if @config[:import]
    @importing = true
    EM.defer do
      begin
        @store.import(@config[:import]); @importing = false
      rescue
        log.fatal { $!.message }
        puts *$@
        stop
      end
    end
  end
end

#start_timersObject



178
179
180
181
182
183
184
185
# File 'lib/bitcoin/network/node.rb', line 178

def start_timers
  return EM.add_timer(1) { start_timers }  if @importing
  [:queue, :inv_queue, :addrs, :connect, :relay].each do |name|
    interval = @config[:intervals][name].to_f
    next  if !interval || interval == 0.0
    @timers[name] = EM.add_periodic_timer(interval, method("work_#{name}"))
  end
end

#stopObject



168
169
170
171
172
# File 'lib/bitcoin/network/node.rb', line 168

def stop
  puts "Shutting down..."
  stop_timers
  EM.stop
end

#stop_timersObject



187
188
189
# File 'lib/bitcoin/network/node.rb', line 187

def stop_timers
  @timers.each {|n, t| EM.cancel_timer t }
end

#store_addrsObject



153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/bitcoin/network/node.rb', line 153

def store_addrs
  return  if !@addrs || !@addrs.any?
  file = @config[:addr_file].sub("~", ENV["HOME"])
    .sub("<network>", Bitcoin.network_name.to_s)
  FileUtils.mkdir_p(File.dirname(file))
  File.open(file, 'w') do |f|
    addrs = @addrs.map {|a|
      Hash[[:time, :service, :ip, :port].zip(a.entries)] rescue nil }.compact
    f.write(JSON.pretty_generate(addrs))
  end
  log.info { "Stored #{@addrs.size} addrs to #{file}." }
rescue
  log.warn { "Error storing addrs to #{file}." }
end

#subscribe(channel) ⇒ Object

subscribe to notification channel. available channels are: block, tx, output, connection. see CommandHandler for details.



490
491
492
493
494
495
496
497
498
499
# File 'lib/bitcoin/network/node.rb', line 490

def subscribe channel
  @notifiers[channel.to_sym] ||= EM::Channel.new
  @notifiers[channel.to_sym].subscribe do |*data|
    begin
      yield(*data)
    rescue
      p $!; puts *$@
    end
  end
end

#unsubscribe(channel, id) ⇒ Object



501
502
503
# File 'lib/bitcoin/network/node.rb', line 501

def unsubscribe channel, id
  @notifiers[channel.to_sym].unsubscribe(id)
end

#uptimeObject



174
175
176
# File 'lib/bitcoin/network/node.rb', line 174

def uptime
  (Time.now - @started).to_i
end

#work_addrsObject

check if the addr store is full and request new addrs from a random peer if it isn’t



380
381
382
383
384
385
386
387
388
# File 'lib/bitcoin/network/node.rb', line 380

def work_addrs
  log.debug { "addr worker running" }
  @addrs.delete_if{|addr| !addr.alive? }  if @addrs.size >= @config[:max][:addr]
  return  if !@connections.any? || @config[:max][:connections] <= @connections.size
  connections = @connections.select(&:connected?)
  return  unless connections.any?
  log.info { "requesting addrs" }
  connections.sample.send_getaddr
end

#work_connectObject

check if there are enough connections and try to establish new ones if needed



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/bitcoin/network/node.rb', line 347

def work_connect
  log.debug { "Connect worker running" }
  desired = @config[:max][:connections_out] - @connections.select(&:outgoing?).size
  return  if desired <= 0
  desired = 32  if desired > 32 # connect to max 32 peers at once
  if addrs.any?
    addrs.sample(desired) do |addr|
      Time.now.tv_sec + 10800 - addr.time
    end.each do |addr|
      connect_peer(addr.ip, addr.port)
    end
  elsif @config[:dns]
    connect_dns
  end
rescue
  log.error { "Error during connect: #{$!.inspect}" }
end

#work_inv_queueObject

check for new items in the inv queue and process them, unless the queue is already full



435
436
437
438
439
440
441
442
443
444
# File 'lib/bitcoin/network/node.rb', line 435

def work_inv_queue
  @log.debug { "inv queue worker running" }
  return  if @inv_queue.size == 0
  return  if @queue.size >= @config[:max][:queue]
  while inv = @inv_queue.shift
    next  if !@store.in_sync? && inv[0] == :tx && @notifiers.empty?
    next  if @queue.map{|i|i[1]}.map(&:hash).include?(inv[1])
    inv[2].send("send_getdata_#{inv[0]}", inv[1])
  end
end

#work_queueObject

check for new items in the queue and process them



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/bitcoin/network/node.rb', line 391

def work_queue
  @log.debug { "queue worker running" }
  return getblocks  if @queue.size == 0

  # switch off utxo cache once there aren't tons of new blocks coming in
  if @store.in_sync?
    if @store.is_a?(Bitcoin::Storage::Backends::UtxoStore) && @store.config[:utxo_cache] > 0
      log.debug { "switching off utxo cache" }
      @store.config[:utxo_cache] = 0
    end
    @config[:intervals].each do |name, value|
      if value <= 1
        log.debug { "setting #{name} interval to 5 seconds" }
        @config[:intervals][name] = 5
      end
    end
  end

  while obj = @queue.shift
    begin
      if obj[0].to_sym == :block
        @store.new_block(obj[1])
      else
        drop = @unconfirmed.size - @config[:max][:unconfirmed] + 1
        drop.times { @unconfirmed.shift }  if drop > 0
        unless @unconfirmed[obj[1].hash]
          @unconfirmed[obj[1].hash] = obj[1]
          push_notification(:tx, [obj[1], 0])
        end
      end
    rescue Bitcoin::Validation::ValidationError
      @log.warn { "ValidationError storing #{obj[0]} #{obj[1].hash}: #{$!.message}" }
      # File.open("./validation_error_#{obj[0]}_#{obj[1].hash}.bin", "w") {|f|
      #   f.write(obj[1].to_payload) }
      # EM.stop
    rescue
      @log.warn { $!.inspect }
      puts *$@
    end
  end
end

#work_relayObject



461
462
463
464
465
466
# File 'lib/bitcoin/network/node.rb', line 461

def work_relay
  log.debug { "relay worker running" }
  @store.get_unconfirmed_tx.each do |tx|
    relay_tx(tx)
  end
end