Class: Bitcoin::Protocol::Addr

Inherits:
Struct
  • Object
show all
Defined in:
lib/bitcoin/protocol/address.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = nil) ⇒ Addr

create addr from raw binary data



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/bitcoin/protocol/address.rb', line 16

def initialize(data = nil)
  if data
    unpacked = data.unpack('VQx12a4n')
    self[:time], self[:service], self[:ip], self[:port] = unpacked
    self[:ip] = ip.unpack('C*').join('.')
  else
    self[:time] = Time.now.to_i
    self[:service] = 1
    self[:ip] = '127.0.0.1'
    self[:port] = Bitcoin.network[:default_port]
  end
end

Instance Attribute Details

#ipObject

Returns the value of attribute ip

Returns:

  • (Object)

    the current value of ip



5
6
7
# File 'lib/bitcoin/protocol/address.rb', line 5

def ip
  @ip
end

#portObject

Returns the value of attribute port

Returns:

  • (Object)

    the current value of port



5
6
7
# File 'lib/bitcoin/protocol/address.rb', line 5

def port
  @port
end

#serviceObject

Returns the value of attribute service

Returns:

  • (Object)

    the current value of service



5
6
7
# File 'lib/bitcoin/protocol/address.rb', line 5

def service
  @service
end

#timeObject

Returns the value of attribute time

Returns:

  • (Object)

    the current value of time



5
6
7
# File 'lib/bitcoin/protocol/address.rb', line 5

def time
  @time
end

Class Method Details

.pkt(*addrs) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/bitcoin/protocol/address.rb', line 43

def self.pkt(*addrs)
  addrs = addrs.select do |i|
    i.is_a?(Bitcoin::Protocol::Addr) && i.ip =~ /^\d+\.\d+\.\d+\.\d+$/
  end
  length = Bitcoin::Protocol.pack_var_int(addrs.size)
  Bitcoin::Protocol.pkt('addr', length + addrs.map(&:to_payload).join)
end

Instance Method Details

#alive?Boolean

is this address alive?

Returns:

  • (Boolean)


30
31
32
# File 'lib/bitcoin/protocol/address.rb', line 30

def alive?
  (Time.now.tv_sec - 7200) <= self[:time]
end

#stringObject



39
40
41
# File 'lib/bitcoin/protocol/address.rb', line 39

def string
  "#{self[:ip]}:#{self[:port]}"
end

#to_payloadObject



34
35
36
37
# File 'lib/bitcoin/protocol/address.rb', line 34

def to_payload
  ip = self[:ip].split('.').map(&:to_i)
  [time, service, ("\x00" * 10) + "\xff\xff", *ip, port].pack('VQa12C4n')
end