common.go raw

   1  // Copyright (c) 2013-2016 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  	"bytes"
   9  	"crypto/rand"
  10  	"encoding/binary"
  11  	"fmt"
  12  	"io"
  13  	"math"
  14  	"time"
  15  
  16  	"github.com/btcsuite/btcd/chainhash/v2"
  17  )
  18  
  19  const (
  20  	// MaxVarIntPayload is the maximum payload size for a variable length integer.
  21  	MaxVarIntPayload = 9
  22  
  23  	// binaryFreeListMaxItems is the number of buffers to keep in the free
  24  	// list to use for binary serialization and deserialization.
  25  	binaryFreeListMaxItems = 1024
  26  
  27  	// defaultReadBufferSize bounds speculative allocation when a reader does
  28  	// not expose the number of bytes it has remaining.
  29  	defaultReadBufferSize = 4096
  30  
  31  	// defaultStreamingElementCap bounds speculative vector allocation when a
  32  	// reader does not expose the number of bytes it has remaining.
  33  	defaultStreamingElementCap = 128
  34  )
  35  
  36  // readBytes reads count bytes without allocating the full claimed size until
  37  // the reader proves that the bytes are available. Buffered message decoders
  38  // expose their remaining length, which preserves the single allocation fast
  39  // path for complete payloads. Streaming readers grow in small increments as
  40  // data arrives.
  41  func readBytes(r io.Reader, count uint64) ([]byte, error) {
  42  	if count == 0 {
  43  		return []byte{}, nil
  44  	}
  45  
  46  	available, known := readerRemaining(r)
  47  	if known && count <= available {
  48  		result := make([]byte, count)
  49  		n, err := io.ReadFull(r, result)
  50  		return result[:n], err
  51  	}
  52  
  53  	// Read into bounded chunks rather than using io.CopyN with a
  54  	// bytes.Buffer. Buffer.ReadFrom reserves more space before its final EOF
  55  	// check, which can grow the buffer beyond count after a complete read.
  56  	// Each chunk below is capped by the remaining payload and is allocated
  57  	// only after the preceding bytes arrive.
  58  	remaining := count
  59  	chunkSize := uint64(defaultReadBufferSize)
  60  
  61  	// The current payload maximum needs fewer than 16 geometrically sized
  62  	// chunks, so the chunk metadata does not need to grow while reading.
  63  	chunks := make([][]byte, 0, 16)
  64  	totalRead := 0
  65  	for remaining > 0 {
  66  		chunkSize = min(chunkSize, remaining)
  67  		chunk := make([]byte, int(chunkSize))
  68  		n := 0
  69  		var err error
  70  		for n < len(chunk) && err == nil {
  71  			var bytesRead int
  72  			bytesRead, err = r.Read(chunk[n:])
  73  			n += bytesRead
  74  		}
  75  
  76  		chunks = append(chunks, chunk[:n])
  77  		totalRead += n
  78  		remaining -= uint64(n)
  79  		if err != nil && remaining > 0 {
  80  			if err == io.EOF && totalRead > 0 {
  81  				err = io.ErrUnexpectedEOF
  82  			}
  83  			if len(chunks) == 1 {
  84  				return chunks[0], err
  85  			}
  86  
  87  			return bytes.Join(chunks, nil), err
  88  		}
  89  
  90  		chunkSize *= 2
  91  	}
  92  
  93  	if len(chunks) == 1 {
  94  		return chunks[0], nil
  95  	}
  96  
  97  	return bytes.Join(chunks, nil), nil
  98  }
  99  
 100  // readerRemaining returns the number of buffered bytes exposed by the concrete
 101  // readers used by wire decoders. Other readers use the staged streaming path.
 102  func readerRemaining(r io.Reader) (uint64, bool) {
 103  	switch r := r.(type) {
 104  	case *bytes.Buffer:
 105  		return uint64(r.Len()), true
 106  
 107  	case *bytes.Reader:
 108  		return uint64(r.Len()), true
 109  
 110  	default:
 111  		return 0, false
 112  	}
 113  }
 114  
 115  // validateElementCount ensures a buffered payload has enough bytes remaining
 116  // to encode the claimed number of elements before a decoder allocates for the
 117  // count. The framed wire path passes a bytes.Buffer to each message decoder,
 118  // while callers without a measurable remainder retain streaming semantics.
 119  func validateElementCount(r io.Reader, count,
 120  	minElementSize uint64) error {
 121  
 122  	_, err := canPreallocateElements(r, count, minElementSize)
 123  	return err
 124  }
 125  
 126  // canPreallocateElements reports whether a reader proves that the minimum
 127  // encoding for count elements is already buffered. Readers without a
 128  // measurable remainder must grow element storage as decoding makes progress.
 129  func canPreallocateElements(r io.Reader, count,
 130  	minElementSize uint64) (bool, error) {
 131  
 132  	remaining, ok := readerRemaining(r)
 133  	if !ok || minElementSize == 0 {
 134  		return false, nil
 135  	}
 136  
 137  	if count <= remaining/minElementSize {
 138  		return true, nil
 139  	}
 140  
 141  	return false, elementCountError(remaining)
 142  }
 143  
 144  // elementCountError preserves the short-read error returned by the element
 145  // decoder when the claimed vector cannot fit in the remaining payload.
 146  func elementCountError(remaining uint64) error {
 147  	if remaining == 0 {
 148  		return io.EOF
 149  	}
 150  
 151  	return io.ErrUnexpectedEOF
 152  }
 153  
 154  var (
 155  	// littleEndian is a convenience variable since binary.LittleEndian is
 156  	// quite long.
 157  	littleEndian = binary.LittleEndian
 158  
 159  	// bigEndian is a convenience variable since binary.BigEndian is quite
 160  	// long.
 161  	bigEndian = binary.BigEndian
 162  )
 163  
 164  // binaryFreeList defines a concurrent safe free list of byte slices (up to the
 165  // maximum number defined by the binaryFreeListMaxItems constant) that have a
 166  // cap of 8 (thus it supports up to a uint64).  It is used to provide temporary
 167  // buffers for serializing and deserializing primitive numbers to and from their
 168  // binary encoding in order to greatly reduce the number of allocations
 169  // required.
 170  //
 171  // For convenience, functions are provided for each of the primitive unsigned
 172  // integers that automatically obtain a buffer from the free list, perform the
 173  // necessary binary conversion, read from or write to the given io.Reader or
 174  // io.Writer, and return the buffer to the free list.
 175  type binaryFreeList chan []byte
 176  
 177  // Borrow returns a byte slice from the free list with a length of 8.  A new
 178  // buffer is allocated if there are not any available on the free list.
 179  func (l binaryFreeList) Borrow() []byte {
 180  	var buf []byte
 181  	select {
 182  	case buf = <-l:
 183  	default:
 184  		buf = make([]byte, 8)
 185  	}
 186  	return buf[:8]
 187  }
 188  
 189  // Return puts the provided byte slice back on the free list.  The buffer MUST
 190  // have been obtained via the Borrow function and therefore have a cap of 8.
 191  func (l binaryFreeList) Return(buf []byte) {
 192  	select {
 193  	case l <- buf:
 194  	default:
 195  		// Let it go to the garbage collector.
 196  	}
 197  }
 198  
 199  // Uint8 reads a single byte from the provided reader using a buffer from the
 200  // free list and returns it as a uint8.
 201  func (l binaryFreeList) Uint8(r io.Reader) (uint8, error) {
 202  	buf := l.Borrow()[:1]
 203  	defer l.Return(buf)
 204  
 205  	if _, err := io.ReadFull(r, buf); err != nil {
 206  		return 0, err
 207  	}
 208  	rv := buf[0]
 209  
 210  	return rv, nil
 211  }
 212  
 213  // Uint16 reads two bytes from the provided reader using a buffer from the
 214  // free list, converts it to a number using the provided byte order, and returns
 215  // the resulting uint16.
 216  func (l binaryFreeList) Uint16(r io.Reader, byteOrder binary.ByteOrder) (uint16, error) {
 217  	buf := l.Borrow()[:2]
 218  	defer l.Return(buf)
 219  
 220  	if _, err := io.ReadFull(r, buf); err != nil {
 221  		return 0, err
 222  	}
 223  	rv := byteOrder.Uint16(buf)
 224  
 225  	return rv, nil
 226  }
 227  
 228  // Uint32 reads four bytes from the provided reader using a buffer from the
 229  // free list, converts it to a number using the provided byte order, and returns
 230  // the resulting uint32.
 231  func (l binaryFreeList) Uint32(r io.Reader, byteOrder binary.ByteOrder) (uint32, error) {
 232  	buf := l.Borrow()[:4]
 233  	defer l.Return(buf)
 234  
 235  	if _, err := io.ReadFull(r, buf); err != nil {
 236  		return 0, err
 237  	}
 238  	rv := byteOrder.Uint32(buf)
 239  
 240  	return rv, nil
 241  }
 242  
 243  // Uint64 reads eight bytes from the provided reader using a buffer from the
 244  // free list, converts it to a number using the provided byte order, and returns
 245  // the resulting uint64.
 246  func (l binaryFreeList) Uint64(r io.Reader, byteOrder binary.ByteOrder) (uint64, error) {
 247  	buf := l.Borrow()[:8]
 248  	defer l.Return(buf)
 249  
 250  	if _, err := io.ReadFull(r, buf); err != nil {
 251  		return 0, err
 252  	}
 253  	rv := byteOrder.Uint64(buf)
 254  
 255  	return rv, nil
 256  }
 257  
 258  // PutUint8 copies the provided uint8 into a buffer from the free list and
 259  // writes the resulting byte to the given writer.
 260  func (l binaryFreeList) PutUint8(w io.Writer, val uint8) error {
 261  	buf := l.Borrow()[:1]
 262  	defer l.Return(buf)
 263  
 264  	buf[0] = val
 265  	_, err := w.Write(buf)
 266  
 267  	return err
 268  }
 269  
 270  // PutUint16 serializes the provided uint16 using the given byte order into a
 271  // buffer from the free list and writes the resulting two bytes to the given
 272  // writer.
 273  func (l binaryFreeList) PutUint16(w io.Writer, byteOrder binary.ByteOrder, val uint16) error {
 274  	buf := l.Borrow()[:2]
 275  	defer l.Return(buf)
 276  
 277  	byteOrder.PutUint16(buf, val)
 278  	_, err := w.Write(buf)
 279  
 280  	return err
 281  }
 282  
 283  // PutUint32 serializes the provided uint32 using the given byte order into a
 284  // buffer from the free list and writes the resulting four bytes to the given
 285  // writer.
 286  func (l binaryFreeList) PutUint32(w io.Writer, byteOrder binary.ByteOrder, val uint32) error {
 287  	buf := l.Borrow()[:4]
 288  	defer l.Return(buf)
 289  
 290  	byteOrder.PutUint32(buf, val)
 291  	_, err := w.Write(buf)
 292  
 293  	return err
 294  }
 295  
 296  // PutUint64 serializes the provided uint64 using the given byte order into a
 297  // buffer from the free list and writes the resulting eight bytes to the given
 298  // writer.
 299  func (l binaryFreeList) PutUint64(w io.Writer, byteOrder binary.ByteOrder, val uint64) error {
 300  	buf := l.Borrow()[:8]
 301  	defer l.Return(buf)
 302  
 303  	byteOrder.PutUint64(buf, val)
 304  	_, err := w.Write(buf)
 305  
 306  	return err
 307  }
 308  
 309  // binarySerializer provides a free list of buffers to use for serializing and
 310  // deserializing primitive integer values to and from io.Readers and io.Writers.
 311  var binarySerializer binaryFreeList = make(chan []byte, binaryFreeListMaxItems)
 312  
 313  // errNonCanonicalVarInt is the common format string used for non-canonically
 314  // encoded variable length integer errors.
 315  var errNonCanonicalVarInt = "non-canonical varint %x - discriminant %x must " +
 316  	"encode a value greater than %x"
 317  
 318  // uint32Time represents a unix timestamp encoded with a uint32.  It is used as
 319  // a way to signal the readElement function how to decode a timestamp into a Go
 320  // time.Time since it is otherwise ambiguous.
 321  type uint32Time time.Time
 322  
 323  // int64Time represents a unix timestamp encoded with an int64.  It is used as
 324  // a way to signal the readElement function how to decode a timestamp into a Go
 325  // time.Time since it is otherwise ambiguous.
 326  type int64Time time.Time
 327  
 328  // readElement reads the next sequence of bytes from r using little endian
 329  // depending on the concrete type of element pointed to.
 330  func readElement(r io.Reader, element interface{}) error {
 331  	// Attempt to read the element based on the concrete type via fast
 332  	// type assertions first.
 333  	switch e := element.(type) {
 334  	case *int32:
 335  		rv, err := binarySerializer.Uint32(r, littleEndian)
 336  		if err != nil {
 337  			return err
 338  		}
 339  		*e = int32(rv)
 340  		return nil
 341  
 342  	case *uint32:
 343  		rv, err := binarySerializer.Uint32(r, littleEndian)
 344  		if err != nil {
 345  			return err
 346  		}
 347  		*e = rv
 348  		return nil
 349  
 350  	case *int64:
 351  		rv, err := binarySerializer.Uint64(r, littleEndian)
 352  		if err != nil {
 353  			return err
 354  		}
 355  		*e = int64(rv)
 356  		return nil
 357  
 358  	case *uint64:
 359  		rv, err := binarySerializer.Uint64(r, littleEndian)
 360  		if err != nil {
 361  			return err
 362  		}
 363  		*e = rv
 364  		return nil
 365  
 366  	case *bool:
 367  		rv, err := binarySerializer.Uint8(r)
 368  		if err != nil {
 369  			return err
 370  		}
 371  		if rv == 0x00 {
 372  			*e = false
 373  		} else {
 374  			*e = true
 375  		}
 376  		return nil
 377  
 378  	// Unix timestamp encoded as a uint32.
 379  	case *uint32Time:
 380  		rv, err := binarySerializer.Uint32(r, binary.LittleEndian)
 381  		if err != nil {
 382  			return err
 383  		}
 384  		*e = uint32Time(time.Unix(int64(rv), 0))
 385  		return nil
 386  
 387  	// Unix timestamp encoded as an int64.
 388  	case *int64Time:
 389  		rv, err := binarySerializer.Uint64(r, binary.LittleEndian)
 390  		if err != nil {
 391  			return err
 392  		}
 393  		*e = int64Time(time.Unix(int64(rv), 0))
 394  		return nil
 395  
 396  	// Message header checksum.
 397  	case *[4]byte:
 398  		_, err := io.ReadFull(r, e[:])
 399  		if err != nil {
 400  			return err
 401  		}
 402  		return nil
 403  
 404  	// Message header command.
 405  	case *[CommandSize]uint8:
 406  		_, err := io.ReadFull(r, e[:])
 407  		if err != nil {
 408  			return err
 409  		}
 410  		return nil
 411  
 412  	// IP address.
 413  	case *[16]byte:
 414  		_, err := io.ReadFull(r, e[:])
 415  		if err != nil {
 416  			return err
 417  		}
 418  		return nil
 419  
 420  	case *chainhash.Hash:
 421  		_, err := io.ReadFull(r, e[:])
 422  		if err != nil {
 423  			return err
 424  		}
 425  		return nil
 426  
 427  	case *ServiceFlag:
 428  		rv, err := binarySerializer.Uint64(r, littleEndian)
 429  		if err != nil {
 430  			return err
 431  		}
 432  		*e = ServiceFlag(rv)
 433  		return nil
 434  
 435  	case *InvType:
 436  		rv, err := binarySerializer.Uint32(r, littleEndian)
 437  		if err != nil {
 438  			return err
 439  		}
 440  		*e = InvType(rv)
 441  		return nil
 442  
 443  	case *BitcoinNet:
 444  		rv, err := binarySerializer.Uint32(r, littleEndian)
 445  		if err != nil {
 446  			return err
 447  		}
 448  		*e = BitcoinNet(rv)
 449  		return nil
 450  
 451  	case *BloomUpdateType:
 452  		rv, err := binarySerializer.Uint8(r)
 453  		if err != nil {
 454  			return err
 455  		}
 456  		*e = BloomUpdateType(rv)
 457  		return nil
 458  
 459  	case *RejectCode:
 460  		rv, err := binarySerializer.Uint8(r)
 461  		if err != nil {
 462  			return err
 463  		}
 464  		*e = RejectCode(rv)
 465  		return nil
 466  	}
 467  
 468  	// Fall back to the slower binary.Read if a fast path was not available
 469  	// above.
 470  	return binary.Read(r, littleEndian, element)
 471  }
 472  
 473  // readElements reads multiple items from r.  It is equivalent to multiple
 474  // calls to readElement.
 475  func readElements(r io.Reader, elements ...interface{}) error {
 476  	for _, element := range elements {
 477  		err := readElement(r, element)
 478  		if err != nil {
 479  			return err
 480  		}
 481  	}
 482  	return nil
 483  }
 484  
 485  // writeElement writes the little endian representation of element to w.
 486  func writeElement(w io.Writer, element interface{}) error {
 487  	// Attempt to write the element based on the concrete type via fast
 488  	// type assertions first.
 489  	switch e := element.(type) {
 490  	case int32:
 491  		err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
 492  		if err != nil {
 493  			return err
 494  		}
 495  		return nil
 496  
 497  	case uint32:
 498  		err := binarySerializer.PutUint32(w, littleEndian, e)
 499  		if err != nil {
 500  			return err
 501  		}
 502  		return nil
 503  
 504  	case int64:
 505  		err := binarySerializer.PutUint64(w, littleEndian, uint64(e))
 506  		if err != nil {
 507  			return err
 508  		}
 509  		return nil
 510  
 511  	case uint64:
 512  		err := binarySerializer.PutUint64(w, littleEndian, e)
 513  		if err != nil {
 514  			return err
 515  		}
 516  		return nil
 517  
 518  	case bool:
 519  		var err error
 520  		if e {
 521  			err = binarySerializer.PutUint8(w, 0x01)
 522  		} else {
 523  			err = binarySerializer.PutUint8(w, 0x00)
 524  		}
 525  		if err != nil {
 526  			return err
 527  		}
 528  		return nil
 529  
 530  	// Message header checksum.
 531  	case [4]byte:
 532  		_, err := w.Write(e[:])
 533  		if err != nil {
 534  			return err
 535  		}
 536  		return nil
 537  
 538  	// Message header command.
 539  	case [CommandSize]uint8:
 540  		_, err := w.Write(e[:])
 541  		if err != nil {
 542  			return err
 543  		}
 544  		return nil
 545  
 546  	// IP address.
 547  	case [16]byte:
 548  		_, err := w.Write(e[:])
 549  		if err != nil {
 550  			return err
 551  		}
 552  		return nil
 553  
 554  	case *chainhash.Hash:
 555  		_, err := w.Write(e[:])
 556  		if err != nil {
 557  			return err
 558  		}
 559  		return nil
 560  
 561  	case ServiceFlag:
 562  		err := binarySerializer.PutUint64(w, littleEndian, uint64(e))
 563  		if err != nil {
 564  			return err
 565  		}
 566  		return nil
 567  
 568  	case InvType:
 569  		err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
 570  		if err != nil {
 571  			return err
 572  		}
 573  		return nil
 574  
 575  	case BitcoinNet:
 576  		err := binarySerializer.PutUint32(w, littleEndian, uint32(e))
 577  		if err != nil {
 578  			return err
 579  		}
 580  		return nil
 581  
 582  	case BloomUpdateType:
 583  		err := binarySerializer.PutUint8(w, uint8(e))
 584  		if err != nil {
 585  			return err
 586  		}
 587  		return nil
 588  
 589  	case RejectCode:
 590  		err := binarySerializer.PutUint8(w, uint8(e))
 591  		if err != nil {
 592  			return err
 593  		}
 594  		return nil
 595  	}
 596  
 597  	// Fall back to the slower binary.Write if a fast path was not available
 598  	// above.
 599  	return binary.Write(w, littleEndian, element)
 600  }
 601  
 602  // writeElements writes multiple items to w.  It is equivalent to multiple
 603  // calls to writeElement.
 604  func writeElements(w io.Writer, elements ...interface{}) error {
 605  	for _, element := range elements {
 606  		err := writeElement(w, element)
 607  		if err != nil {
 608  			return err
 609  		}
 610  	}
 611  	return nil
 612  }
 613  
 614  // ReadVarInt reads a variable length integer from r and returns it as a uint64.
 615  func ReadVarInt(r io.Reader, pver uint32) (uint64, error) {
 616  	buf := binarySerializer.Borrow()
 617  	defer binarySerializer.Return(buf)
 618  
 619  	n, err := ReadVarIntBuf(r, pver, buf)
 620  	return n, err
 621  }
 622  
 623  // ReadVarIntBuf reads a variable length integer from r using a preallocated
 624  // scratch buffer and returns it as a uint64.
 625  //
 626  // NOTE: buf MUST at least an 8-byte slice.
 627  func ReadVarIntBuf(r io.Reader, pver uint32, buf []byte) (uint64, error) {
 628  	if _, err := io.ReadFull(r, buf[:1]); err != nil {
 629  		return 0, err
 630  	}
 631  	discriminant := buf[0]
 632  
 633  	var rv uint64
 634  	switch discriminant {
 635  	case 0xff:
 636  		if _, err := io.ReadFull(r, buf); err != nil {
 637  			return 0, err
 638  		}
 639  		rv = littleEndian.Uint64(buf)
 640  
 641  		// The encoding is not canonical if the value could have been
 642  		// encoded using fewer bytes.
 643  		min := uint64(0x100000000)
 644  		if rv < min {
 645  			return 0, messageError("ReadVarInt", fmt.Sprintf(
 646  				errNonCanonicalVarInt, rv, discriminant, min))
 647  		}
 648  
 649  	case 0xfe:
 650  		if _, err := io.ReadFull(r, buf[:4]); err != nil {
 651  			return 0, err
 652  		}
 653  		rv = uint64(littleEndian.Uint32(buf[:4]))
 654  
 655  		// The encoding is not canonical if the value could have been
 656  		// encoded using fewer bytes.
 657  		min := uint64(0x10000)
 658  		if rv < min {
 659  			return 0, messageError("ReadVarInt", fmt.Sprintf(
 660  				errNonCanonicalVarInt, rv, discriminant, min))
 661  		}
 662  
 663  	case 0xfd:
 664  		if _, err := io.ReadFull(r, buf[:2]); err != nil {
 665  			return 0, err
 666  		}
 667  		rv = uint64(littleEndian.Uint16(buf[:2]))
 668  
 669  		// The encoding is not canonical if the value could have been
 670  		// encoded using fewer bytes.
 671  		min := uint64(0xfd)
 672  		if rv < min {
 673  			return 0, messageError("ReadVarInt", fmt.Sprintf(
 674  				errNonCanonicalVarInt, rv, discriminant, min))
 675  		}
 676  
 677  	default:
 678  		rv = uint64(discriminant)
 679  	}
 680  
 681  	return rv, nil
 682  }
 683  
 684  // WriteVarInt serializes val to w using a variable number of bytes depending
 685  // on its value.
 686  func WriteVarInt(w io.Writer, pver uint32, val uint64) error {
 687  	buf := binarySerializer.Borrow()
 688  	defer binarySerializer.Return(buf)
 689  
 690  	err := WriteVarIntBuf(w, pver, val, buf)
 691  	return err
 692  }
 693  
 694  // WriteVarIntBuf serializes val to w using a variable number of bytes depending
 695  // on its value using a preallocated scratch buffer.
 696  //
 697  // NOTE: buf MUST at least an 8-byte slice.
 698  func WriteVarIntBuf(w io.Writer, pver uint32, val uint64, buf []byte) error {
 699  	switch {
 700  	case val < 0xfd:
 701  		buf[0] = uint8(val)
 702  		_, err := w.Write(buf[:1])
 703  		return err
 704  
 705  	case val <= math.MaxUint16:
 706  		buf[0] = 0xfd
 707  		littleEndian.PutUint16(buf[1:3], uint16(val))
 708  		_, err := w.Write(buf[:3])
 709  		return err
 710  
 711  	case val <= math.MaxUint32:
 712  		buf[0] = 0xfe
 713  		littleEndian.PutUint32(buf[1:5], uint32(val))
 714  		_, err := w.Write(buf[:5])
 715  		return err
 716  
 717  	default:
 718  		buf[0] = 0xff
 719  		if _, err := w.Write(buf[:1]); err != nil {
 720  			return err
 721  		}
 722  
 723  		littleEndian.PutUint64(buf, val)
 724  		_, err := w.Write(buf)
 725  		return err
 726  	}
 727  }
 728  
 729  // VarIntSerializeSize returns the number of bytes it would take to serialize
 730  // val as a variable length integer.
 731  func VarIntSerializeSize(val uint64) int {
 732  	// The value is small enough to be represented by itself, so it's
 733  	// just 1 byte.
 734  	if val < 0xfd {
 735  		return 1
 736  	}
 737  
 738  	// Discriminant 1 byte plus 2 bytes for the uint16.
 739  	if val <= math.MaxUint16 {
 740  		return 3
 741  	}
 742  
 743  	// Discriminant 1 byte plus 4 bytes for the uint32.
 744  	if val <= math.MaxUint32 {
 745  		return 5
 746  	}
 747  
 748  	// Discriminant 1 byte plus 8 bytes for the uint64.
 749  	return 9
 750  }
 751  
 752  // ReadVarString reads a variable length string from r and returns it as a Go
 753  // string.  A variable length string is encoded as a variable length integer
 754  // containing the length of the string followed by the bytes that represent the
 755  // string itself.  An error is returned if the length is greater than the
 756  // maximum block payload size since it helps protect against memory exhaustion
 757  // attacks and forced panics through malformed messages.
 758  func ReadVarString(r io.Reader, pver uint32) (string, error) {
 759  	buf := binarySerializer.Borrow()
 760  	defer binarySerializer.Return(buf)
 761  
 762  	str, err := readVarStringBuf(r, pver, buf)
 763  	return str, err
 764  }
 765  
 766  // readVarStringBuf reads a variable length string from r and returns it as a Go
 767  // string.  A variable length string is encoded as a variable length integer
 768  // containing the length of the string followed by the bytes that represent the
 769  // string itself.  An error is returned if the length is greater than the
 770  // maximum block payload size since it helps protect against memory exhaustion
 771  // attacks and forced panics through malformed messages.
 772  //
 773  // NOTE: buf MUST be at least an 8-byte slice.
 774  func readVarStringBuf(r io.Reader, pver uint32, buf []byte) (string, error) {
 775  	count, err := ReadVarIntBuf(r, pver, buf)
 776  	if err != nil {
 777  		return "", err
 778  	}
 779  
 780  	// Prevent variable length strings that are larger than the maximum
 781  	// message size.  It would be possible to cause memory exhaustion and
 782  	// panics without a sane upper bound on this count.
 783  	if count > MaxMessagePayload {
 784  		str := fmt.Sprintf("variable length string is too long "+
 785  			"[count %d, max %d]", count, MaxMessagePayload)
 786  		return "", messageError("ReadVarString", str)
 787  	}
 788  
 789  	str, err := readBytes(r, count)
 790  	if err != nil {
 791  		return "", err
 792  	}
 793  	return string(str), nil
 794  }
 795  
 796  // WriteVarString serializes str to w as a variable length integer containing
 797  // the length of the string followed by the bytes that represent the string
 798  // itself.
 799  func WriteVarString(w io.Writer, pver uint32, str string) error {
 800  	buf := binarySerializer.Borrow()
 801  	defer binarySerializer.Return(buf)
 802  
 803  	err := writeVarStringBuf(w, pver, str, buf)
 804  	return err
 805  }
 806  
 807  // writeVarStringBuf serializes str to w as a variable length integer containing
 808  // the length of the string followed by the bytes that represent the string
 809  // itself.
 810  //
 811  // NOTE: buf MUST be at least an 8-byte slice.
 812  func writeVarStringBuf(w io.Writer, pver uint32, str string, buf []byte) error {
 813  	err := WriteVarIntBuf(w, pver, uint64(len(str)), buf)
 814  	if err != nil {
 815  		return err
 816  	}
 817  
 818  	_, err = w.Write([]byte(str))
 819  	return err
 820  }
 821  
 822  // ReadVarBytes reads a variable length byte array.  A byte array is encoded
 823  // as a varInt containing the length of the array followed by the bytes
 824  // themselves.  An error is returned if the length is greater than the
 825  // passed maxAllowed parameter which helps protect against memory exhaustion
 826  // attacks and forced panics through malformed messages.  The fieldName
 827  // parameter is only used for the error message so it provides more context in
 828  // the error.
 829  func ReadVarBytes(r io.Reader, pver uint32, maxAllowed uint32,
 830  	fieldName string) ([]byte, error) {
 831  
 832  	buf := binarySerializer.Borrow()
 833  	defer binarySerializer.Return(buf)
 834  
 835  	b, err := ReadVarBytesBuf(r, pver, buf, maxAllowed, fieldName)
 836  	return b, err
 837  }
 838  
 839  // ReadVarBytesBuf reads a variable length byte array.  A byte array is encoded
 840  // as a varInt containing the length of the array followed by the bytes
 841  // themselves.  An error is returned if the length is greater than the
 842  // passed maxAllowed parameter which helps protect against memory exhaustion
 843  // attacks and forced panics through malformed messages.  The fieldName
 844  // parameter is only used for the error message so it provides more context in
 845  // the error.
 846  //
 847  // NOTE: buf MUST be at least an 8-byte slice.
 848  func ReadVarBytesBuf(r io.Reader, pver uint32, buf []byte, maxAllowed uint32,
 849  	fieldName string) ([]byte, error) {
 850  
 851  	count, err := ReadVarIntBuf(r, pver, buf)
 852  	if err != nil {
 853  		return nil, err
 854  	}
 855  
 856  	// Prevent byte array larger than the max message size.  It would
 857  	// be possible to cause memory exhaustion and panics without a sane
 858  	// upper bound on this count.
 859  	if count > uint64(maxAllowed) {
 860  		str := fmt.Sprintf("%s is larger than the max allowed size "+
 861  			"[count %d, max %d]", fieldName, count, maxAllowed)
 862  		return nil, messageError("ReadVarBytes", str)
 863  	}
 864  
 865  	bytes, err := readBytes(r, count)
 866  	if err != nil {
 867  		return nil, err
 868  	}
 869  
 870  	return bytes, nil
 871  }
 872  
 873  // WriteVarBytes serializes a variable length byte array to w as a varInt
 874  // containing the number of bytes, followed by the bytes themselves.
 875  func WriteVarBytes(w io.Writer, pver uint32, bytes []byte) error {
 876  	buf := binarySerializer.Borrow()
 877  	defer binarySerializer.Return(buf)
 878  
 879  	err := WriteVarBytesBuf(w, pver, bytes, buf)
 880  	return err
 881  }
 882  
 883  // WriteVarBytesBuf serializes a variable length byte array to w as a varInt
 884  // containing the number of bytes, followed by the bytes themselves. If b is
 885  // non-nil, the provided buffer will be used for serializing small values.
 886  // Otherwise a buffer will be drawn from the binarySerializer's pool and return
 887  // when the method finishes.
 888  func WriteVarBytesBuf(w io.Writer, pver uint32, bytes, buf []byte) error {
 889  	slen := uint64(len(bytes))
 890  
 891  	err := WriteVarIntBuf(w, pver, slen, buf)
 892  	if err != nil {
 893  		return err
 894  	}
 895  
 896  	_, err = w.Write(bytes)
 897  	return err
 898  }
 899  
 900  // randomUint64 returns a cryptographically random uint64 value.  This
 901  // unexported version takes a reader primarily to ensure the error paths
 902  // can be properly tested by passing a fake reader in the tests.
 903  func randomUint64(r io.Reader) (uint64, error) {
 904  	rv, err := binarySerializer.Uint64(r, bigEndian)
 905  	if err != nil {
 906  		return 0, err
 907  	}
 908  	return rv, nil
 909  }
 910  
 911  // RandomUint64 returns a cryptographically random uint64 value.
 912  func RandomUint64() (uint64, error) {
 913  	return randomUint64(rand.Reader)
 914  }
 915