netaddressv2.go raw

   1  package wire
   2  
   3  import (
   4  	"bytes"
   5  	"encoding/base32"
   6  	"encoding/binary"
   7  	"fmt"
   8  	"io"
   9  	"net"
  10  	"strings"
  11  	"time"
  12  
  13  	"golang.org/x/crypto/sha3"
  14  )
  15  
  16  const (
  17  	// minNetAddressV2Payload is the minimum number of bytes needed to
  18  	// encode an address. An unknown network can carry an empty address, but
  19  	// still includes the timestamp, services, network ID, length, and port.
  20  	minNetAddressV2Payload = 9
  21  
  22  	// maxAddrV2Size is the maximum size an address may be in the addrv2
  23  	// message.
  24  	maxAddrV2Size = 512
  25  )
  26  
  27  var (
  28  	// ErrInvalidAddressSize is an error that means an incorrect address
  29  	// size was decoded for a networkID or that the address exceeded the
  30  	// maximum size for an unknown networkID.
  31  	ErrInvalidAddressSize = fmt.Errorf("invalid address size")
  32  
  33  	// ErrSkippedNetworkID is returned when the cjdns, i2p, or unknown
  34  	// networks are encountered during decoding. btcd does not support i2p
  35  	// or cjdns addresses. In the case of an unknown networkID, this is so
  36  	// that a future BIP reserving a new networkID does not cause older
  37  	// addrv2-supporting btcd software to disconnect upon receiving the new
  38  	// addresses. This error can also be returned when an OnionCat-encoded
  39  	// torv2 address is received with the ipv6 networkID. This error
  40  	// signals to the caller to continue reading.
  41  	ErrSkippedNetworkID = fmt.Errorf("skipped networkID")
  42  )
  43  
  44  // maxNetAddressV2Payload returns the max payload size for an address used in
  45  // the addrv2 message.
  46  func maxNetAddressV2Payload() uint32 {
  47  	// The timestamp takes up four bytes.
  48  	plen := uint32(4)
  49  
  50  	// The ServiceFlag is a varint and its maximum size is 9 bytes.
  51  	plen += 9
  52  
  53  	// The netID is a single byte.
  54  	plen += 1
  55  
  56  	// The largest address is 512 bytes. Even though it will not be a valid
  57  	// address, we should read and ignore it. The preceding varint to
  58  	// store 512 bytes is 3 bytes long. This gives us a total of 515 bytes.
  59  	plen += 515
  60  
  61  	// The port is 2 bytes.
  62  	plen += 2
  63  
  64  	return plen
  65  }
  66  
  67  // isOnionCatTor returns whether a given ip address is actually an encoded tor
  68  // v2 address. The wire package is unable to use the addrmgr's IsOnionCatTor as
  69  // doing so would give an import cycle.
  70  func isOnionCatTor(ip net.IP) bool {
  71  	onionCatNet := net.IPNet{
  72  		IP:   net.ParseIP("fd87:d87e:eb43::"),
  73  		Mask: net.CIDRMask(48, 128),
  74  	}
  75  	return onionCatNet.Contains(ip)
  76  }
  77  
  78  // ipv4MappedPrefix is the prefix for IPv4-mapped IPv6 addresses (::ffff:0:0/96)
  79  // as defined by RFC 4291.
  80  var ipv4MappedPrefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
  81  
  82  // isIPv4Mapped returns whether a given 16-byte IPv6 address is actually an
  83  // IPv4-mapped IPv6 address (::ffff:0:0/96).
  84  func isIPv4Mapped(addr []byte) bool {
  85  	return bytes.HasPrefix(addr, ipv4MappedPrefix)
  86  }
  87  
  88  // NetAddressV2 defines information about a peer on the network including the
  89  // last time it was seen, the services it supports, its address, and port. This
  90  // struct is used in the addrv2 message (MsgAddrV2) and can contain larger
  91  // addresses, like Tor. Additionally, it can contain any NetAddress address.
  92  type NetAddressV2 struct {
  93  	// Last time the address was seen. This is, unfortunately, encoded as a
  94  	// uint32 on the wire and therefore is limited to 2106. This field is
  95  	// not present in the bitcoin version message (MsgVersion) nor was it
  96  	// added until protocol version >= NetAddressTimeVersion.
  97  	Timestamp time.Time
  98  
  99  	// Services is a bitfield which identifies the services supported by
 100  	// the address. This is encoded in CompactSize.
 101  	Services ServiceFlag
 102  
 103  	// Addr is the network address of the peer. This is a variable-length
 104  	// address. Network() returns the BIP-155 networkID which is a uint8
 105  	// encoded as a string. String() returns the address as a string.
 106  	Addr net.Addr
 107  
 108  	// Port is the port of the address. This is 0 if the network doesn't
 109  	// use ports.
 110  	Port uint16
 111  }
 112  
 113  // HasService returns whether the specified service is supported by the
 114  // address.
 115  func (na *NetAddressV2) HasService(service ServiceFlag) bool {
 116  	return na.Services&service == service
 117  }
 118  
 119  // AddService adds a service to the Services bitfield.
 120  func (na *NetAddressV2) AddService(service ServiceFlag) {
 121  	na.Services |= service
 122  }
 123  
 124  // ToLegacy attempts to convert a NetAddressV2 to a legacy NetAddress. This
 125  // only works for ipv4, ipv6, or torv2 addresses as they can be encoded with
 126  // the OnionCat encoding. If this method is called on a torv3 address, nil will
 127  // be returned.
 128  func (na *NetAddressV2) ToLegacy() *NetAddress {
 129  	legacyNa := &NetAddress{
 130  		Timestamp: na.Timestamp,
 131  		Services:  na.Services,
 132  		Port:      na.Port,
 133  	}
 134  
 135  	switch a := na.Addr.(type) {
 136  	case *ipv4Addr:
 137  		legacyNa.IP = a.addr[:]
 138  	case *ipv6Addr:
 139  		legacyNa.IP = a.addr[:]
 140  	case *torv2Addr:
 141  		legacyNa.IP = a.onionCatEncoding()
 142  	case *torv3Addr:
 143  		return nil
 144  	}
 145  
 146  	return legacyNa
 147  }
 148  
 149  // IsTorV3 returns a bool that signals to the caller whether or not this is a
 150  // torv3 address.
 151  func (na *NetAddressV2) IsTorV3() bool {
 152  	_, ok := na.Addr.(*torv3Addr)
 153  	return ok
 154  }
 155  
 156  // TorV3Key returns the first byte of the v3 public key. This is used in the
 157  // addrmgr to calculate a key from a network group.
 158  func (na *NetAddressV2) TorV3Key() byte {
 159  	// This should never be called on a non-torv3 address.
 160  	addr, ok := na.Addr.(*torv3Addr)
 161  	if !ok {
 162  		panic("unexpected TorV3Key call on non-torv3 address")
 163  	}
 164  
 165  	return addr.addr[0]
 166  }
 167  
 168  // NetAddressV2FromBytes creates a NetAddressV2 from a byte slice. It will
 169  // also handle a torv2 address using the OnionCat encoding.
 170  func NetAddressV2FromBytes(timestamp time.Time, services ServiceFlag,
 171  	addrBytes []byte, port uint16) *NetAddressV2 {
 172  
 173  	var netAddr net.Addr
 174  	switch len(addrBytes) {
 175  	case ipv4Size:
 176  		addr := &ipv4Addr{}
 177  		addr.netID = ipv4
 178  		copy(addr.addr[:], addrBytes)
 179  		netAddr = addr
 180  	case ipv6Size:
 181  		if isOnionCatTor(addrBytes) {
 182  			addr := &torv2Addr{}
 183  			addr.netID = torv2
 184  			copy(addr.addr[:], addrBytes[6:])
 185  			netAddr = addr
 186  			break
 187  		}
 188  
 189  		// IPv4-mapped IPv6 addresses (::ffff:0:0/96) should use the
 190  		// IPv4 networkID. Bitcoin Core silently drops IPv6 addrv2
 191  		// entries with this prefix. Go's net.IP commonly stores
 192  		// IPv4 addresses in this 16-byte form, so extract the
 193  		// 4-byte IPv4 address.
 194  		if isIPv4Mapped(addrBytes) {
 195  			addr := &ipv4Addr{}
 196  			addr.netID = ipv4
 197  			copy(addr.addr[:], addrBytes[12:])
 198  			netAddr = addr
 199  			break
 200  		}
 201  
 202  		addr := &ipv6Addr{}
 203  		addr.netID = ipv6
 204  		copy(addr.addr[:], addrBytes)
 205  		netAddr = addr
 206  	case torv2Size:
 207  		addr := &torv2Addr{}
 208  		addr.netID = torv2
 209  		copy(addr.addr[:], addrBytes)
 210  		netAddr = addr
 211  	case TorV3Size:
 212  		addr := &torv3Addr{}
 213  		addr.netID = torv3
 214  		copy(addr.addr[:], addrBytes)
 215  		netAddr = addr
 216  	}
 217  
 218  	return &NetAddressV2{
 219  		Timestamp: timestamp,
 220  		Services:  services,
 221  		Addr:      netAddr,
 222  		Port:      port,
 223  	}
 224  }
 225  
 226  // writeNetAddressV2 writes a NetAddressV2 to a writer.
 227  func writeNetAddressV2(w io.Writer, pver uint32, na *NetAddressV2) error {
 228  	err := writeElement(w, uint32(na.Timestamp.Unix()))
 229  	if err != nil {
 230  		return err
 231  	}
 232  
 233  	if err := WriteVarInt(w, pver, uint64(na.Services)); err != nil {
 234  		return err
 235  	}
 236  
 237  	var (
 238  		netID   networkID
 239  		address []byte
 240  	)
 241  
 242  	switch a := na.Addr.(type) {
 243  	case *ipv4Addr:
 244  		netID = a.netID
 245  		address = a.addr[:]
 246  	case *ipv6Addr:
 247  		netID = a.netID
 248  		address = a.addr[:]
 249  	case *torv2Addr:
 250  		netID = a.netID
 251  		address = a.addr[:]
 252  	case *torv3Addr:
 253  		netID = a.netID
 254  		address = a.addr[:]
 255  	default:
 256  		// This should not occur.
 257  		return fmt.Errorf("unexpected address type")
 258  	}
 259  
 260  	if err := writeElement(w, netID); err != nil {
 261  		return err
 262  	}
 263  
 264  	addressSize := uint64(len(address))
 265  	if err := WriteVarInt(w, pver, addressSize); err != nil {
 266  		return err
 267  	}
 268  
 269  	if err := writeElement(w, address); err != nil {
 270  		return err
 271  	}
 272  
 273  	return binary.Write(w, bigEndian, na.Port)
 274  }
 275  
 276  // readNetAddressV2 reads a NetAddressV2 from a reader. This function has
 277  // checks that the corresponding write function doesn't. This is because
 278  // reading from the peer is untrusted whereas writing assumes we have already
 279  // validated the NetAddressV2.
 280  func readNetAddressV2(r io.Reader, pver uint32, na *NetAddressV2) error {
 281  	err := readElement(r, (*uint32Time)(&na.Timestamp))
 282  	if err != nil {
 283  		return err
 284  	}
 285  
 286  	// Services is encoded as a variable length integer in addrv2.
 287  	services, err := ReadVarInt(r, pver)
 288  	if err != nil {
 289  		return err
 290  	}
 291  	na.Services = ServiceFlag(services)
 292  
 293  	var netID uint8
 294  	if err := readElement(r, &netID); err != nil {
 295  		return err
 296  	}
 297  
 298  	decodedSize, err := ReadVarInt(r, pver)
 299  	if err != nil {
 300  		return err
 301  	}
 302  
 303  	if !isKnownNetworkID(netID) {
 304  		// In the case of an unknown networkID, we'll read the address
 305  		// size and error with ErrInvalidAddressSize if it's greater
 306  		// than maxAddrV2Size. If the address size is within the valid
 307  		// range, we'll just read and discard the address. In this
 308  		// case, ErrSkippedNetworkID will be returned to signal to the
 309  		// caller to continue reading.
 310  		if decodedSize > maxAddrV2Size {
 311  			return ErrInvalidAddressSize
 312  		}
 313  
 314  		// The +2 is the port field.
 315  		discardedAddrPort := make([]byte, decodedSize+2)
 316  		if err := readElement(r, &discardedAddrPort); err != nil {
 317  			return err
 318  		}
 319  
 320  		return ErrSkippedNetworkID
 321  	}
 322  
 323  	// If the netID is an i2p or cjdns address, we'll advance the reader
 324  	// and return a special error to signal to the caller to not use the
 325  	// passed NetAddressV2 struct. Otherwise, we'll just read the address
 326  	// and port without returning an error.
 327  	switch networkID(netID) {
 328  	case ipv4:
 329  		addr := &ipv4Addr{}
 330  		addr.netID = ipv4
 331  		if decodedSize != uint64(ipv4Size) {
 332  			return ErrInvalidAddressSize
 333  		}
 334  
 335  		if err := readElement(r, &addr.addr); err != nil {
 336  			return err
 337  		}
 338  
 339  		na.Port, err = binarySerializer.Uint16(r, bigEndian)
 340  		if err != nil {
 341  			return err
 342  		}
 343  
 344  		na.Addr = addr
 345  	case ipv6:
 346  		addr := &ipv6Addr{}
 347  		addr.netID = ipv6
 348  		if decodedSize != uint64(ipv6Size) {
 349  			return ErrInvalidAddressSize
 350  		}
 351  
 352  		if err := readElement(r, &addr.addr); err != nil {
 353  			return err
 354  		}
 355  
 356  		na.Port, err = binarySerializer.Uint16(r, bigEndian)
 357  		if err != nil {
 358  			return err
 359  		}
 360  
 361  		na.Addr = addr
 362  
 363  		// BIP-155 says to ignore OnionCat addresses in addrv2
 364  		// messages.
 365  		if isOnionCatTor(addr.addr[:]) {
 366  			return ErrSkippedNetworkID
 367  		}
 368  
 369  		// Skip IPv4-mapped IPv6 addresses (RFC 4291). These addresses
 370  		// should use networkID 0x01 (IPv4), not 0x02 (IPv6).
 371  		if isIPv4Mapped(addr.addr[:]) {
 372  			return ErrSkippedNetworkID
 373  		}
 374  	case torv2:
 375  		addr := &torv2Addr{}
 376  		addr.netID = torv2
 377  		if decodedSize != uint64(torv2Size) {
 378  			return ErrInvalidAddressSize
 379  		}
 380  
 381  		if err := readElement(r, &addr.addr); err != nil {
 382  			return err
 383  		}
 384  
 385  		na.Port, err = binarySerializer.Uint16(r, bigEndian)
 386  		if err != nil {
 387  			return err
 388  		}
 389  
 390  		na.Addr = addr
 391  	case torv3:
 392  		addr := &torv3Addr{}
 393  		addr.netID = torv3
 394  		if decodedSize != uint64(TorV3Size) {
 395  			return ErrInvalidAddressSize
 396  		}
 397  
 398  		if err := readElement(r, &addr.addr); err != nil {
 399  			return err
 400  		}
 401  
 402  		na.Port, err = binarySerializer.Uint16(r, bigEndian)
 403  		if err != nil {
 404  			return err
 405  		}
 406  
 407  		// BIP-155 does not specify to validate the public key here.
 408  		// bitcoind does not validate the ed25519 pubkey.
 409  		na.Addr = addr
 410  	case i2p:
 411  		addr := &i2pAddr{}
 412  		addr.netID = i2p
 413  		if decodedSize != uint64(i2pSize) {
 414  			return ErrInvalidAddressSize
 415  		}
 416  
 417  		if err := readElement(r, &addr.addr); err != nil {
 418  			return err
 419  		}
 420  
 421  		na.Port, err = binarySerializer.Uint16(r, bigEndian)
 422  		if err != nil {
 423  			return err
 424  		}
 425  
 426  		return ErrSkippedNetworkID
 427  	case cjdns:
 428  		addr := &cjdnsAddr{}
 429  		addr.netID = cjdns
 430  		if decodedSize != uint64(cjdnsSize) {
 431  			return ErrInvalidAddressSize
 432  		}
 433  
 434  		if err := readElement(r, &addr.addr); err != nil {
 435  			return err
 436  		}
 437  
 438  		na.Port, err = binarySerializer.Uint16(r, bigEndian)
 439  		if err != nil {
 440  			return err
 441  		}
 442  
 443  		return ErrSkippedNetworkID
 444  	}
 445  
 446  	return nil
 447  }
 448  
 449  // networkID represents the network that a given address is in. CJDNS and I2P
 450  // addresses are not included.
 451  type networkID uint8
 452  
 453  const (
 454  	// ipv4 means the following address is ipv4.
 455  	ipv4 networkID = iota + 1
 456  
 457  	// ipv6 means the following address is ipv6.
 458  	ipv6
 459  
 460  	// torv2 means the following address is a torv2 hidden service address.
 461  	torv2
 462  
 463  	// torv3 means the following address is a torv3 hidden service address.
 464  	torv3
 465  
 466  	// i2p means the following address is an i2p address.
 467  	i2p
 468  
 469  	// cjdns means the following address is a cjdns address.
 470  	cjdns
 471  )
 472  
 473  const (
 474  	// ipv4Size is the size of an ipv4 address.
 475  	ipv4Size = 4
 476  
 477  	// ipv6Size is the size of an ipv6 address.
 478  	ipv6Size = 16
 479  
 480  	// torv2Size is the size of a torv2 address.
 481  	torv2Size = 10
 482  
 483  	// TorV3Size is the size of a torv3 address in bytes.
 484  	TorV3Size = 32
 485  
 486  	// i2pSize is the size of an i2p address.
 487  	i2pSize = 32
 488  
 489  	// cjdnsSize is the size of a cjdns address.
 490  	cjdnsSize = 16
 491  )
 492  
 493  const (
 494  	// TorV2EncodedSize is the size of a torv2 address encoded in base32
 495  	// with the ".onion" suffix.
 496  	TorV2EncodedSize = 22
 497  
 498  	// TorV3EncodedSize is the size of a torv3 address encoded in base32
 499  	// with the ".onion" suffix.
 500  	TorV3EncodedSize = 62
 501  )
 502  
 503  // isKnownNetworkID returns true if the networkID is one listed above and false
 504  // otherwise.
 505  func isKnownNetworkID(netID uint8) bool {
 506  	return uint8(ipv4) <= netID && netID <= uint8(cjdns)
 507  }
 508  
 509  type ipv4Addr struct {
 510  	addr  [ipv4Size]byte
 511  	netID networkID
 512  }
 513  
 514  // Part of the net.Addr interface.
 515  func (a *ipv4Addr) String() string {
 516  	return net.IP(a.addr[:]).String()
 517  }
 518  
 519  // Part of the net.Addr interface.
 520  func (a *ipv4Addr) Network() string {
 521  	return string(a.netID)
 522  }
 523  
 524  // Compile-time constraints to check that ipv4Addr meets the net.Addr
 525  // interface.
 526  var _ net.Addr = (*ipv4Addr)(nil)
 527  
 528  type ipv6Addr struct {
 529  	addr  [ipv6Size]byte
 530  	netID networkID
 531  }
 532  
 533  // Part of the net.Addr interface.
 534  func (a *ipv6Addr) String() string {
 535  	return net.IP(a.addr[:]).String()
 536  }
 537  
 538  // Part of the net.Addr interface.
 539  func (a *ipv6Addr) Network() string {
 540  	return string(a.netID)
 541  }
 542  
 543  // Compile-time constraints to check that ipv6Addr meets the net.Addr
 544  // interface.
 545  var _ net.Addr = (*ipv4Addr)(nil)
 546  
 547  type torv2Addr struct {
 548  	addr  [torv2Size]byte
 549  	netID networkID
 550  }
 551  
 552  // Part of the net.Addr interface.
 553  func (a *torv2Addr) String() string {
 554  	base32Hash := base32.StdEncoding.EncodeToString(a.addr[:])
 555  	return strings.ToLower(base32Hash) + ".onion"
 556  }
 557  
 558  // Part of the net.Addr interface.
 559  func (a *torv2Addr) Network() string {
 560  	return string(a.netID)
 561  }
 562  
 563  // onionCatEncoding returns a torv2 address as an ipv6 address.
 564  func (a *torv2Addr) onionCatEncoding() net.IP {
 565  	prefix := []byte{0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43}
 566  	return net.IP(append(prefix, a.addr[:]...))
 567  }
 568  
 569  // Compile-time constraints to check that torv2Addr meets the net.Addr
 570  // interface.
 571  var _ net.Addr = (*torv2Addr)(nil)
 572  
 573  type torv3Addr struct {
 574  	addr  [TorV3Size]byte
 575  	netID networkID
 576  }
 577  
 578  // Part of the net.Addr interface.
 579  func (a *torv3Addr) String() string {
 580  	// BIP-155 describes the torv3 address format:
 581  	// onion_address = base32(PUBKEY | CHECKSUM | VERSION) + ".onion"
 582  	// CHECKSUM = H(".onion checksum" | PUBKEY | VERSION)[:2]
 583  	// PUBKEY = addr, which is the ed25519 pubkey of the hidden service.
 584  	// VERSION = '\x03'
 585  	// H() is the SHA3-256 cryptographic hash function.
 586  
 587  	torV3Version := []byte("\x03")
 588  	checksumConst := []byte(".onion checksum")
 589  
 590  	// Write never returns an error so there is no need to handle it.
 591  	h := sha3.New256()
 592  	h.Write(checksumConst)
 593  	h.Write(a.addr[:])
 594  	h.Write(torV3Version)
 595  	truncatedChecksum := h.Sum(nil)[:2]
 596  
 597  	var base32Input [35]byte
 598  	copy(base32Input[:32], a.addr[:])
 599  	copy(base32Input[32:34], truncatedChecksum)
 600  	copy(base32Input[34:], torV3Version)
 601  
 602  	base32Hash := base32.StdEncoding.EncodeToString(base32Input[:])
 603  	return strings.ToLower(base32Hash) + ".onion"
 604  }
 605  
 606  // Part of the net.Addr interface.
 607  func (a *torv3Addr) Network() string {
 608  	return string(a.netID)
 609  }
 610  
 611  // Compile-time constraints to check that torv3Addr meets the net.Addr
 612  // interface.
 613  var _ net.Addr = (*torv3Addr)(nil)
 614  
 615  type i2pAddr struct {
 616  	addr  [i2pSize]byte
 617  	netID networkID
 618  }
 619  
 620  type cjdnsAddr struct {
 621  	addr  [cjdnsSize]byte
 622  	netID networkID
 623  }
 624