Sha256: 7a6a5bc236ba4aa05e0448dadfd9b2c4fcc28f1ac83b4a11d4106f9a337a4a8c

Contents?: true

Size: 1.87 KB

Versions: 10

Compression:

Stored size: 1.87 KB

Contents

require 'ipaddr'

module Tapyrus
  module Message
    class NetworkAddr
      # unix time.
      # Nodes advertising their own IP address set this to the current time.
      # Nodes advertising IP addresses they’ve connected to set this to the last time they connected to that node.
      # Other nodes just relaying the IP address should not change the time. Nodes can use the time field to avoid relaying old addr messages.
      attr_accessor :time

      # The services the node advertised in its version message.
      attr_accessor :services

      attr_accessor :ip_addr # IPAddr

      attr_accessor :port

      attr_reader :skip_time

      def initialize(
        ip: '127.0.0.1',
        port: Tapyrus.chain_params.default_port,
        services: DEFAULT_SERVICE_FLAGS,
        time: Time.now.to_i
      )
        @time = time
        @ip_addr = IPAddr.new(ip)
        @port = port
        @services = services
      end

      def self.parse_from_payload(payload)
        buf = payload.is_a?(String) ? StringIO.new(payload) : payload
        has_time = buf.size > 26
        addr = new(time: nil)
        addr.time = buf.read(4).unpack('V').first if has_time
        addr.services = buf.read(8).unpack('Q').first
        addr.ip_addr = IPAddr.new_ntoh(buf.read(16))
        addr.port = buf.read(2).unpack('n').first
        addr
      end

      def self.local_addr
        addr = new
        addr.ip_addr = IPAddr.new('127.0.0.1')
        addr.port = Tapyrus.chain_params.default_port
        addr.services = DEFAULT_SERVICE_FLAGS
        addr
      end

      def ip
        ip_addr.ipv4_mapped? ? ip_addr.native : ip_addr.to_s
      end

      def to_payload(skip_time = false)
        p = ''
        p << [time].pack('V') unless skip_time
        addr = ip_addr.ipv4? ? ip_addr.ipv4_mapped : ip_addr
        p << [services].pack('Q') << addr.hton << [port].pack('n')
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
tapyrus-0.3.4 lib/tapyrus/message/network_addr.rb
tapyrus-0.3.3 lib/tapyrus/message/network_addr.rb
tapyrus-0.3.2 lib/tapyrus/message/network_addr.rb
tapyrus-0.3.1 lib/tapyrus/message/network_addr.rb
tapyrus-0.3.0 lib/tapyrus/message/network_addr.rb
tapyrus-0.2.13 lib/tapyrus/message/network_addr.rb
tapyrus-0.2.12 lib/tapyrus/message/network_addr.rb
tapyrus-0.2.10 lib/tapyrus/message/network_addr.rb
tapyrus-0.2.9 lib/tapyrus/message/network_addr.rb
tapyrus-0.2.8 lib/tapyrus/message/network_addr.rb