netaddress.go raw

   1  // Copyright (c) 2013-2015 The btcsuite developers
   2  // Use of this source code is governed by an ISC
   3  // license that can be found in the LICENSE file.
   4  
   5  package wire
   6  
   7  import (
   8  	"io"
   9  	"net"
  10  	"time"
  11  )
  12  
  13  const (
  14  	// minNetAddressPayload is the encoded size of an address without its
  15  	// optional timestamp.
  16  	minNetAddressPayload = 26
  17  )
  18  
  19  // maxNetAddressPayload returns the max payload size for a bitcoin NetAddress
  20  // based on the protocol version.
  21  func maxNetAddressPayload(pver uint32) uint32 {
  22  	// Services 8 bytes + ip 16 bytes + port 2 bytes.
  23  	plen := uint32(minNetAddressPayload)
  24  
  25  	// NetAddressTimeVersion added a timestamp field.
  26  	if pver >= NetAddressTimeVersion {
  27  		// Timestamp 4 bytes.
  28  		plen += 4
  29  	}
  30  
  31  	return plen
  32  }
  33  
  34  // NetAddress defines information about a peer on the network including the time
  35  // it was last seen, the services it supports, its IP address, and port.
  36  type NetAddress struct {
  37  	// Last time the address was seen.  This is, unfortunately, encoded as a
  38  	// uint32 on the wire and therefore is limited to 2106.  This field is
  39  	// not present in the bitcoin version message (MsgVersion) nor was it
  40  	// added until protocol version >= NetAddressTimeVersion.
  41  	Timestamp time.Time
  42  
  43  	// Bitfield which identifies the services supported by the address.
  44  	Services ServiceFlag
  45  
  46  	// IP address of the peer.
  47  	IP net.IP
  48  
  49  	// Port the peer is using.  This is encoded in big endian on the wire
  50  	// which differs from most everything else.
  51  	Port uint16
  52  }
  53  
  54  // HasService returns whether the specified service is supported by the address.
  55  func (na *NetAddress) HasService(service ServiceFlag) bool {
  56  	return na.Services&service == service
  57  }
  58  
  59  // AddService adds service as a supported service by the peer generating the
  60  // message.
  61  func (na *NetAddress) AddService(service ServiceFlag) {
  62  	na.Services |= service
  63  }
  64  
  65  // NewNetAddressIPPort returns a new NetAddress using the provided IP, port, and
  66  // supported services with defaults for the remaining fields.
  67  func NewNetAddressIPPort(ip net.IP, port uint16, services ServiceFlag) *NetAddress {
  68  	return NewNetAddressTimestamp(time.Now(), services, ip, port)
  69  }
  70  
  71  // NewNetAddressTimestamp returns a new NetAddress using the provided
  72  // timestamp, IP, port, and supported services. The timestamp is rounded to
  73  // single second precision.
  74  func NewNetAddressTimestamp(
  75  	timestamp time.Time, services ServiceFlag, ip net.IP, port uint16) *NetAddress {
  76  	// Limit the timestamp to one second precision since the protocol
  77  	// doesn't support better.
  78  	na := NetAddress{
  79  		Timestamp: time.Unix(timestamp.Unix(), 0),
  80  		Services:  services,
  81  		IP:        ip,
  82  		Port:      port,
  83  	}
  84  	return &na
  85  }
  86  
  87  // NewNetAddress returns a new NetAddress using the provided TCP address and
  88  // supported services with defaults for the remaining fields.
  89  func NewNetAddress(addr *net.TCPAddr, services ServiceFlag) *NetAddress {
  90  	return NewNetAddressIPPort(addr.IP, uint16(addr.Port), services)
  91  }
  92  
  93  // readNetAddress reads an encoded NetAddress from r depending on the protocol
  94  // version and whether or not the timestamp is included per ts.  Some messages
  95  // like version do not include the timestamp.
  96  func readNetAddress(r io.Reader, pver uint32, na *NetAddress, ts bool) error {
  97  	buf := binarySerializer.Borrow()
  98  	defer binarySerializer.Return(buf)
  99  
 100  	err := readNetAddressBuf(r, pver, na, ts, buf)
 101  	return err
 102  }
 103  
 104  // readNetAddressBuf reads an encoded NetAddress from r depending on the
 105  // protocol version and whether or not the timestamp is included per ts.  Some
 106  // messages like version do not include the timestamp.
 107  //
 108  // If b is non-nil, the provided buffer will be used for serializing small
 109  // values.  Otherwise a buffer will be drawn from the binarySerializer's pool
 110  // and return when the method finishes.
 111  //
 112  // NOTE: b MUST either be nil or at least an 8-byte slice.
 113  func readNetAddressBuf(r io.Reader, pver uint32, na *NetAddress, ts bool,
 114  	buf []byte) error {
 115  
 116  	var (
 117  		timestamp time.Time
 118  		services  ServiceFlag
 119  		ip        [16]byte
 120  		port      uint16
 121  	)
 122  
 123  	// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will
 124  	// stop working somewhere around 2106.  Also timestamp wasn't added until
 125  	// protocol version >= NetAddressTimeVersion
 126  	if ts && pver >= NetAddressTimeVersion {
 127  		if _, err := io.ReadFull(r, buf[:4]); err != nil {
 128  			return err
 129  		}
 130  		timestamp = time.Unix(int64(littleEndian.Uint32(buf[:4])), 0)
 131  	}
 132  
 133  	if _, err := io.ReadFull(r, buf); err != nil {
 134  		return err
 135  	}
 136  	services = ServiceFlag(littleEndian.Uint64(buf))
 137  
 138  	if _, err := io.ReadFull(r, ip[:]); err != nil {
 139  		return err
 140  	}
 141  
 142  	// Sigh.  Bitcoin protocol mixes little and big endian.
 143  	if _, err := io.ReadFull(r, buf[:2]); err != nil {
 144  		return err
 145  	}
 146  	port = bigEndian.Uint16(buf[:2])
 147  
 148  	*na = NetAddress{
 149  		Timestamp: timestamp,
 150  		Services:  services,
 151  		IP:        net.IP(ip[:]),
 152  		Port:      port,
 153  	}
 154  	return nil
 155  }
 156  
 157  // writeNetAddress serializes a NetAddress to w depending on the protocol
 158  // version and whether or not the timestamp is included per ts.  Some messages
 159  // like version do not include the timestamp.
 160  func writeNetAddress(w io.Writer, pver uint32, na *NetAddress, ts bool) error {
 161  	buf := binarySerializer.Borrow()
 162  	defer binarySerializer.Return(buf)
 163  	err := writeNetAddressBuf(w, pver, na, ts, buf)
 164  
 165  	return err
 166  }
 167  
 168  // writeNetAddressBuf serializes a NetAddress to w depending on the protocol
 169  // version and whether or not the timestamp is included per ts.  Some messages
 170  // like version do not include the timestamp.
 171  //
 172  // If b is non-nil, the provided buffer will be used for serializing small
 173  // values.  Otherwise a buffer will be drawn from the binarySerializer's pool
 174  // and return when the method finishes.
 175  //
 176  // NOTE: b MUST either be nil or at least an 8-byte slice.
 177  func writeNetAddressBuf(w io.Writer, pver uint32, na *NetAddress, ts bool, buf []byte) error {
 178  	// NOTE: The bitcoin protocol uses a uint32 for the timestamp so it will
 179  	// stop working somewhere around 2106.  Also timestamp wasn't added until
 180  	// until protocol version >= NetAddressTimeVersion.
 181  	if ts && pver >= NetAddressTimeVersion {
 182  		littleEndian.PutUint32(buf[:4], uint32(na.Timestamp.Unix()))
 183  		if _, err := w.Write(buf[:4]); err != nil {
 184  			return err
 185  		}
 186  	}
 187  
 188  	littleEndian.PutUint64(buf, uint64(na.Services))
 189  	if _, err := w.Write(buf); err != nil {
 190  		return err
 191  	}
 192  
 193  	// Ensure to always write 16 bytes even if the ip is nil.
 194  	var ip [16]byte
 195  	if na.IP != nil {
 196  		copy(ip[:], na.IP.To16())
 197  	}
 198  	if _, err := w.Write(ip[:]); err != nil {
 199  		return err
 200  	}
 201  
 202  	// Sigh.  Bitcoin protocol mixes little and big endian.
 203  	bigEndian.PutUint16(buf[:2], na.Port)
 204  	_, err := w.Write(buf[:2])
 205  
 206  	return err
 207  }
 208