message.go raw

   1  // Copyright (c) 2013-2024 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  	"fmt"
  10  	"io"
  11  	"unicode/utf8"
  12  
  13  	"github.com/btcsuite/btcd/chainhash/v2"
  14  )
  15  
  16  // MessageHeaderSize is the number of bytes in a bitcoin message header.
  17  // Bitcoin network (magic) 4 bytes + command 12 bytes + payload length 4 bytes +
  18  // checksum 4 bytes.
  19  const MessageHeaderSize = 24
  20  
  21  // CommandSize is the fixed size of all commands in the common bitcoin message
  22  // header.  Shorter commands must be zero padded.
  23  const CommandSize = 12
  24  
  25  // MaxMessagePayload is the maximum bytes a message can be regardless of other
  26  // individual limits imposed by messages themselves. This is used as a
  27  // serialization bound for all contexts (disk, RPC, network, etc.).
  28  const MaxMessagePayload = (1024 * 1024 * 32) // 32MiB
  29  
  30  // MaxProtocolMessageLength is the maximum length of an incoming/outgoing p2p
  31  // protocol message. This is separate from MaxMessagePayload which is used as a
  32  // general serialization bound. No current valid p2p message exceeds 4MB.
  33  // This mirrors Bitcoin Core's MAX_PROTOCOL_MESSAGE_LENGTH introduced in
  34  // bitcoin/bitcoin#5843.
  35  const MaxProtocolMessageLength = (4 * 1000 * 1000) // ~4MB
  36  
  37  // Commands used in bitcoin message headers which describe the type of message.
  38  const (
  39  	CmdVersion      = "version"
  40  	CmdVerAck       = "verack"
  41  	CmdGetAddr      = "getaddr"
  42  	CmdAddr         = "addr"
  43  	CmdAddrV2       = "addrv2"
  44  	CmdGetBlocks    = "getblocks"
  45  	CmdInv          = "inv"
  46  	CmdGetData      = "getdata"
  47  	CmdNotFound     = "notfound"
  48  	CmdBlock        = "block"
  49  	CmdTx           = "tx"
  50  	CmdGetHeaders   = "getheaders"
  51  	CmdHeaders      = "headers"
  52  	CmdPing         = "ping"
  53  	CmdPong         = "pong"
  54  	CmdMemPool      = "mempool"
  55  	CmdFilterAdd    = "filteradd"
  56  	CmdFilterClear  = "filterclear"
  57  	CmdFilterLoad   = "filterload"
  58  	CmdMerkleBlock  = "merkleblock"
  59  	CmdReject       = "reject"
  60  	CmdSendHeaders  = "sendheaders"
  61  	CmdFeeFilter    = "feefilter"
  62  	CmdGetCFilters  = "getcfilters"
  63  	CmdGetCFHeaders = "getcfheaders"
  64  	CmdGetCFCheckpt = "getcfcheckpt"
  65  	CmdCFilter      = "cfilter"
  66  	CmdCFHeaders    = "cfheaders"
  67  	CmdCFCheckpt    = "cfcheckpt"
  68  	CmdSendAddrV2   = "sendaddrv2"
  69  	CmdWTxIdRelay   = "wtxidrelay"
  70  )
  71  
  72  var (
  73  	v2MessageIDs = map[uint8]string{
  74  		1:  CmdAddr,
  75  		2:  CmdBlock,
  76  		5:  CmdFeeFilter,
  77  		6:  CmdFilterAdd,
  78  		7:  CmdFilterClear,
  79  		8:  CmdFilterLoad,
  80  		9:  CmdGetBlocks,
  81  		11: CmdGetData,
  82  		12: CmdGetHeaders,
  83  		13: CmdHeaders,
  84  		14: CmdInv,
  85  		15: CmdMemPool,
  86  		16: CmdMerkleBlock,
  87  		17: CmdNotFound,
  88  		18: CmdPing,
  89  		19: CmdPong,
  90  		21: CmdTx,
  91  		22: CmdGetCFilters,
  92  		23: CmdCFilter,
  93  		24: CmdGetCFHeaders,
  94  		25: CmdCFHeaders,
  95  		26: CmdGetCFCheckpt,
  96  		27: CmdCFCheckpt,
  97  		28: CmdAddrV2,
  98  	}
  99  
 100  	v2Messages = map[string]uint8{
 101  		CmdAddr:         1,
 102  		CmdBlock:        2,
 103  		CmdFeeFilter:    5,
 104  		CmdFilterAdd:    6,
 105  		CmdFilterClear:  7,
 106  		CmdFilterLoad:   8,
 107  		CmdGetBlocks:    9,
 108  		CmdGetData:      11,
 109  		CmdGetHeaders:   12,
 110  		CmdHeaders:      13,
 111  		CmdInv:          14,
 112  		CmdMemPool:      15,
 113  		CmdMerkleBlock:  16,
 114  		CmdNotFound:     17,
 115  		CmdPing:         18,
 116  		CmdPong:         19,
 117  		CmdTx:           21,
 118  		CmdGetCFilters:  22,
 119  		CmdCFilter:      23,
 120  		CmdGetCFHeaders: 24,
 121  		CmdCFHeaders:    25,
 122  		CmdGetCFCheckpt: 26,
 123  		CmdCFCheckpt:    27,
 124  		CmdAddrV2:       28,
 125  	}
 126  )
 127  
 128  // MessageEncoding represents the wire message encoding format to be used.
 129  type MessageEncoding uint32
 130  
 131  const (
 132  	// BaseEncoding encodes all messages in the default format specified
 133  	// for the Bitcoin wire protocol.
 134  	BaseEncoding MessageEncoding = 1 << iota
 135  
 136  	// WitnessEncoding encodes all messages other than transaction messages
 137  	// using the default Bitcoin wire protocol specification. For transaction
 138  	// messages, the new encoding format detailed in BIP0144 will be used.
 139  	WitnessEncoding
 140  )
 141  
 142  // LatestEncoding is the most recently specified encoding for the Bitcoin wire
 143  // protocol.
 144  var LatestEncoding = WitnessEncoding
 145  
 146  // ErrUnknownMessage is the error returned when decoding an unknown message.
 147  var ErrUnknownMessage = fmt.Errorf("received unknown message")
 148  
 149  // ErrInvalidHandshake is the error returned when a peer sends us a known
 150  // message that does not belong in the version-verack handshake.
 151  var ErrInvalidHandshake = fmt.Errorf("invalid message during handshake")
 152  
 153  // Message is an interface that describes a bitcoin message.  A type that
 154  // implements Message has complete control over the representation of its data
 155  // and may therefore contain additional or fewer fields than those which
 156  // are used directly in the protocol encoded message.
 157  type Message interface {
 158  	BtcDecode(io.Reader, uint32, MessageEncoding) error
 159  	BtcEncode(io.Writer, uint32, MessageEncoding) error
 160  	Command() string
 161  	MaxPayloadLength(uint32) uint32
 162  }
 163  
 164  // makeEmptyMessage creates a message of the appropriate concrete type based
 165  // on the command.
 166  func makeEmptyMessage(command string) (Message, error) {
 167  	var msg Message
 168  	switch command {
 169  	case CmdVersion:
 170  		msg = &MsgVersion{}
 171  
 172  	case CmdVerAck:
 173  		msg = &MsgVerAck{}
 174  
 175  	case CmdSendAddrV2:
 176  		msg = &MsgSendAddrV2{}
 177  
 178  	case CmdGetAddr:
 179  		msg = &MsgGetAddr{}
 180  
 181  	case CmdAddr:
 182  		msg = &MsgAddr{}
 183  
 184  	case CmdAddrV2:
 185  		msg = &MsgAddrV2{}
 186  
 187  	case CmdGetBlocks:
 188  		msg = &MsgGetBlocks{}
 189  
 190  	case CmdBlock:
 191  		msg = &MsgBlock{}
 192  
 193  	case CmdInv:
 194  		msg = &MsgInv{}
 195  
 196  	case CmdGetData:
 197  		msg = &MsgGetData{}
 198  
 199  	case CmdNotFound:
 200  		msg = &MsgNotFound{}
 201  
 202  	case CmdTx:
 203  		msg = &MsgTx{}
 204  
 205  	case CmdPing:
 206  		msg = &MsgPing{}
 207  
 208  	case CmdPong:
 209  		msg = &MsgPong{}
 210  
 211  	case CmdGetHeaders:
 212  		msg = &MsgGetHeaders{}
 213  
 214  	case CmdHeaders:
 215  		msg = &MsgHeaders{}
 216  
 217  	case CmdMemPool:
 218  		msg = &MsgMemPool{}
 219  
 220  	case CmdFilterAdd:
 221  		msg = &MsgFilterAdd{}
 222  
 223  	case CmdFilterClear:
 224  		msg = &MsgFilterClear{}
 225  
 226  	case CmdFilterLoad:
 227  		msg = &MsgFilterLoad{}
 228  
 229  	case CmdMerkleBlock:
 230  		msg = &MsgMerkleBlock{}
 231  
 232  	case CmdReject:
 233  		msg = &MsgReject{}
 234  
 235  	case CmdSendHeaders:
 236  		msg = &MsgSendHeaders{}
 237  
 238  	case CmdFeeFilter:
 239  		msg = &MsgFeeFilter{}
 240  
 241  	case CmdGetCFilters:
 242  		msg = &MsgGetCFilters{}
 243  
 244  	case CmdGetCFHeaders:
 245  		msg = &MsgGetCFHeaders{}
 246  
 247  	case CmdGetCFCheckpt:
 248  		msg = &MsgGetCFCheckpt{}
 249  
 250  	case CmdCFilter:
 251  		msg = &MsgCFilter{}
 252  
 253  	case CmdCFHeaders:
 254  		msg = &MsgCFHeaders{}
 255  
 256  	case CmdCFCheckpt:
 257  		msg = &MsgCFCheckpt{}
 258  
 259  	default:
 260  		return nil, ErrUnknownMessage
 261  	}
 262  	return msg, nil
 263  }
 264  
 265  // messageHeader defines the header structure for all bitcoin protocol messages.
 266  type messageHeader struct {
 267  	magic    BitcoinNet // 4 bytes
 268  	command  string     // 12 bytes
 269  	length   uint32     // 4 bytes
 270  	checksum [4]byte    // 4 bytes
 271  }
 272  
 273  // readMessageHeader reads a bitcoin message header from r.
 274  func readMessageHeader(r io.Reader) (int, *messageHeader, error) {
 275  	// Since readElements doesn't return the amount of bytes read, attempt
 276  	// to read the entire header into a buffer first in case there is a
 277  	// short read so the proper amount of read bytes are known.  This works
 278  	// since the header is a fixed size.
 279  	var headerBytes [MessageHeaderSize]byte
 280  	n, err := io.ReadFull(r, headerBytes[:])
 281  	if err != nil {
 282  		return n, nil, err
 283  	}
 284  	hr := bytes.NewReader(headerBytes[:])
 285  
 286  	// Create and populate a messageHeader struct from the raw header bytes.
 287  	hdr := messageHeader{}
 288  	var command [CommandSize]byte
 289  	readElements(hr, &hdr.magic, &command, &hdr.length, &hdr.checksum)
 290  
 291  	// Strip trailing zeros from command string.
 292  	hdr.command = string(bytes.TrimRight(command[:], "\x00"))
 293  
 294  	return n, &hdr, nil
 295  }
 296  
 297  // readPartialHeader reads a partial bitcon message header from r. It takes a
 298  // prefix that contains the already-parsed bytes. This is needed in the case of
 299  // a downgraded v2->v1 transport connection since we have already started
 300  // parsing the header bytes when calling into this function.
 301  func readPartialHeader(prefix []byte, r io.Reader) (int, *messageHeader,
 302  	error) {
 303  
 304  	// Fill out the messageHeader with the network magic from the prefix.
 305  	hdr := messageHeader{}
 306  
 307  	var command [CommandSize]byte
 308  	prefixReader := bytes.NewReader(prefix[:])
 309  	if err := readElements(prefixReader, &hdr.magic, &command); err != nil {
 310  		return 0, nil, err
 311  	}
 312  
 313  	// Strip trailing zeros from command string.
 314  	hdr.command = string(bytes.TrimRight(command[:], "\x00"))
 315  
 316  	// Read the rest of the message header from the passed-in reader.
 317  	if err := readElements(r, &hdr.length, &hdr.checksum); err != nil {
 318  		return 0, nil, err
 319  	}
 320  
 321  	return MessageHeaderSize, &hdr, nil
 322  }
 323  
 324  // discardInput reads n bytes from reader r in chunks and discards the read
 325  // bytes.  This is used to skip payloads when various errors occur and helps
 326  // prevent rogue nodes from causing massive memory allocation through forging
 327  // header length.
 328  func discardInput(r io.Reader, n uint32) {
 329  	maxSize := uint32(10 * 1024) // 10k at a time
 330  	numReads := n / maxSize
 331  	bytesRemaining := n % maxSize
 332  	if n > 0 {
 333  		buf := make([]byte, maxSize)
 334  		for i := uint32(0); i < numReads; i++ {
 335  			io.ReadFull(r, buf)
 336  		}
 337  	}
 338  	if bytesRemaining > 0 {
 339  		buf := make([]byte, bytesRemaining)
 340  		io.ReadFull(r, buf)
 341  	}
 342  }
 343  
 344  // WriteMessageN writes a bitcoin Message to w including the necessary header
 345  // information and returns the number of bytes written.    This function is the
 346  // same as WriteMessage except it also returns the number of bytes written.
 347  func WriteMessageN(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) (int, error) {
 348  	return WriteMessageWithEncodingN(w, msg, pver, btcnet, BaseEncoding)
 349  }
 350  
 351  // WriteMessage writes a bitcoin Message to w including the necessary header
 352  // information.  This function is the same as WriteMessageN except it doesn't
 353  // doesn't return the number of bytes written.  This function is mainly provided
 354  // for backwards compatibility with the original API, but it's also useful for
 355  // callers that don't care about byte counts.
 356  func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) error {
 357  	_, err := WriteMessageN(w, msg, pver, btcnet)
 358  	return err
 359  }
 360  
 361  // WriteV2MessageN writes a Message to the passed Writer using the bip324
 362  // v2 encoding.
 363  func WriteV2MessageN(w io.Writer, msg Message, pver uint32,
 364  	encoding MessageEncoding) (int, error) {
 365  
 366  	var totalBytes int
 367  
 368  	cmd := msg.Command()
 369  	if len(cmd) > CommandSize {
 370  		str := fmt.Sprintf("command [%s] is too long [max %v]",
 371  			cmd, CommandSize)
 372  		return totalBytes, messageError("WriteMessage", str)
 373  	}
 374  
 375  	index, exists := v2Messages[cmd]
 376  	if !exists {
 377  		var command [CommandSize]byte
 378  		copy(command[:], cmd)
 379  		hw := bytes.NewBuffer(make([]byte, 0, CommandSize+1))
 380  		writeElements(hw, byte(0x00), command)
 381  
 382  		n, err := w.Write(hw.Bytes())
 383  		if err != nil {
 384  			return 0, err
 385  		}
 386  
 387  		totalBytes += n
 388  	} else {
 389  		hw := bytes.NewBuffer(make([]byte, 0, 1))
 390  		writeElement(hw, index)
 391  
 392  		n, err := w.Write(hw.Bytes())
 393  		if err != nil {
 394  			return 0, err
 395  		}
 396  
 397  		totalBytes += n
 398  	}
 399  
 400  	var bw bytes.Buffer
 401  	err := msg.BtcEncode(&bw, pver, encoding)
 402  	if err != nil {
 403  		return totalBytes, err
 404  	}
 405  
 406  	payload := bw.Bytes()
 407  	lenp := len(payload)
 408  
 409  	// Enforce maximum protocol message payload.
 410  	if lenp > MaxProtocolMessageLength {
 411  		str := fmt.Sprintf("message payload is too large - encoded "+
 412  			"%d bytes, but maximum message payload is %d bytes",
 413  			lenp, MaxProtocolMessageLength)
 414  		return totalBytes, messageError("WriteMessage", str)
 415  	}
 416  
 417  	mpl := msg.MaxPayloadLength(pver)
 418  	if uint32(lenp) > mpl {
 419  		str := fmt.Sprintf("message payload is too large - encoded "+
 420  			"%d bytes, but maximum message payload size for "+
 421  			"messages of type [%s] is %d.", lenp, cmd, mpl)
 422  		return totalBytes, messageError("WriteMessage", str)
 423  	}
 424  
 425  	if len(payload) > 0 {
 426  		n, err := w.Write(payload)
 427  		totalBytes += n
 428  
 429  		return totalBytes, err
 430  	}
 431  
 432  	return totalBytes, nil
 433  }
 434  
 435  // WriteMessageWithEncodingN writes a bitcoin Message to w including the
 436  // necessary header information and returns the number of bytes written.
 437  // This function is the same as WriteMessageN except it also allows the caller
 438  // to specify the message encoding format to be used when serializing wire
 439  // messages.
 440  func WriteMessageWithEncodingN(w io.Writer, msg Message, pver uint32,
 441  	btcnet BitcoinNet, encoding MessageEncoding) (int, error) {
 442  
 443  	totalBytes := 0
 444  
 445  	// Enforce max command size.
 446  	var command [CommandSize]byte
 447  	cmd := msg.Command()
 448  	if len(cmd) > CommandSize {
 449  		str := fmt.Sprintf("command [%s] is too long [max %v]",
 450  			cmd, CommandSize)
 451  		return totalBytes, messageError("WriteMessage", str)
 452  	}
 453  	copy(command[:], []byte(cmd))
 454  
 455  	// Encode the message payload.
 456  	var bw bytes.Buffer
 457  	err := msg.BtcEncode(&bw, pver, encoding)
 458  	if err != nil {
 459  		return totalBytes, err
 460  	}
 461  	payload := bw.Bytes()
 462  	lenp := len(payload)
 463  
 464  	// Enforce maximum protocol message payload.
 465  	if lenp > MaxProtocolMessageLength {
 466  		str := fmt.Sprintf("message payload is too large - encoded "+
 467  			"%d bytes, but maximum message payload is %d bytes",
 468  			lenp, MaxProtocolMessageLength)
 469  		return totalBytes, messageError("WriteMessage", str)
 470  	}
 471  
 472  	// Enforce maximum message payload based on the message type.
 473  	mpl := msg.MaxPayloadLength(pver)
 474  	if uint32(lenp) > mpl {
 475  		str := fmt.Sprintf("message payload is too large - encoded "+
 476  			"%d bytes, but maximum message payload size for "+
 477  			"messages of type [%s] is %d.", lenp, cmd, mpl)
 478  		return totalBytes, messageError("WriteMessage", str)
 479  	}
 480  
 481  	// Create header for the message.
 482  	hdr := messageHeader{}
 483  	hdr.magic = btcnet
 484  	hdr.command = cmd
 485  	hdr.length = uint32(lenp)
 486  	copy(hdr.checksum[:], chainhash.DoubleHashB(payload)[0:4])
 487  
 488  	// Encode the header for the message.  This is done to a buffer
 489  	// rather than directly to the writer since writeElements doesn't
 490  	// return the number of bytes written.
 491  	hw := bytes.NewBuffer(make([]byte, 0, MessageHeaderSize))
 492  	writeElements(hw, hdr.magic, command, hdr.length, hdr.checksum)
 493  
 494  	// Write header.
 495  	n, err := w.Write(hw.Bytes())
 496  	totalBytes += n
 497  	if err != nil {
 498  		return totalBytes, err
 499  	}
 500  
 501  	// Only write the payload if there is one, e.g., verack messages don't
 502  	// have one.
 503  	if len(payload) > 0 {
 504  		n, err = w.Write(payload)
 505  		totalBytes += n
 506  	}
 507  
 508  	return totalBytes, err
 509  }
 510  
 511  // ReadV2MessageN takes the passed plaintext and attempts to construct a
 512  // Message from the bytes using the bip324 v2 encoding.
 513  func ReadV2MessageN(plaintext []byte, pver uint32, enc MessageEncoding) (
 514  	Message, []byte, error) {
 515  
 516  	if len(plaintext) == 0 {
 517  		return nil, nil, messageError("ReadV2MessageN",
 518  			"invalid plaintext length")
 519  	}
 520  
 521  	var msgCmd string
 522  
 523  	// If the first byte is 0x00, read the next 12 bytes to determine what
 524  	// message this is.
 525  	if plaintext[0] == 0x00 {
 526  		if len(plaintext) < CommandSize+1 {
 527  			return nil, nil, messageError("ReadV2MessageN",
 528  				"invalid plaintext length")
 529  		}
 530  
 531  		// Slice off the first 0x00 and the trailing 0x00 bytes.
 532  		var command [CommandSize]byte
 533  		copy(command[:], plaintext[1:CommandSize+1])
 534  
 535  		msgCmd = string(bytes.TrimRight(command[:], "\x00"))
 536  
 537  		plaintext = plaintext[CommandSize+1:]
 538  	} else {
 539  		// The first byte denotes what message this is.
 540  		msgCmd = v2MessageIDs[plaintext[0]]
 541  
 542  		plaintext = plaintext[1:]
 543  	}
 544  
 545  	msg, err := makeEmptyMessage(msgCmd)
 546  	if err != nil {
 547  		return nil, nil, err
 548  	}
 549  
 550  	// Enforce maximum protocol message payload.
 551  	if len(plaintext) > MaxProtocolMessageLength {
 552  		str := fmt.Sprintf("message payload is too large - "+
 553  			"%d bytes, but max message payload is %d bytes",
 554  			len(plaintext), MaxProtocolMessageLength)
 555  		return nil, nil, messageError("ReadV2MessageN", str)
 556  	}
 557  
 558  	// Check for maximum length based on the message type.
 559  	mpl := msg.MaxPayloadLength(pver)
 560  	if len(plaintext) > int(mpl) {
 561  		str := fmt.Sprintf("payload exceeds max length - "+
 562  			"%d bytes, but max payload size for messages of "+
 563  			"type [%v] is %v.", len(plaintext), msgCmd, mpl)
 564  		return nil, nil, messageError("ReadV2MessageN", str)
 565  	}
 566  
 567  	buf := bytes.NewBuffer(plaintext)
 568  	err = msg.BtcDecode(buf, pver, enc)
 569  	if err != nil {
 570  		return nil, nil, err
 571  	}
 572  
 573  	if buf.Len() > 0 {
 574  		str := fmt.Sprintf("message payload has %d extra bytes "+
 575  			"after decode", buf.Len())
 576  		return nil, nil, messageError("ReadV2MessageN", str)
 577  	}
 578  
 579  	return msg, plaintext, nil
 580  }
 581  
 582  // ReadMessageWithEncodingN reads, validates, and parses the next bitcoin Message
 583  // from r for the provided protocol version and bitcoin network.  It returns the
 584  // number of bytes read in addition to the parsed Message and raw bytes which
 585  // comprise the message.  This function is the same as ReadMessageN except it
 586  // allows the caller to specify which message encoding is to to consult when
 587  // decoding wire messages.
 588  func ReadMessageWithEncodingN(r io.Reader, pver uint32, btcnet BitcoinNet,
 589  	enc MessageEncoding) (int, Message, []byte, error) {
 590  
 591  	totalBytes := 0
 592  	n, hdr, err := readMessageHeader(r)
 593  	totalBytes += n
 594  	if err != nil {
 595  		return totalBytes, nil, nil, err
 596  	}
 597  
 598  	return readMessageWithEncodingNInternal(
 599  		r, pver, hdr, btcnet, enc, totalBytes,
 600  	)
 601  }
 602  
 603  // ReadPartialMessageWithEncodingN is used in the case that we are expecting a
 604  // v2 connection and then receive a v1 version header. In this case, we
 605  // downgrade the implicit v2 connection to a v1 connection and must parse the
 606  // rest of the version bytes and check it properly.
 607  func ReadPartialMessageWithEncodingN(r io.Reader, pver uint32,
 608  	btcnet BitcoinNet, enc MessageEncoding, prefix []byte) (int, Message,
 609  	[]byte, error) {
 610  
 611  	totalBytes := 0
 612  	n, hdr, err := readPartialHeader(prefix, r)
 613  	totalBytes += n
 614  	if err != nil {
 615  		return totalBytes, nil, nil, err
 616  	}
 617  
 618  	return readMessageWithEncodingNInternal(
 619  		r, pver, hdr, btcnet, enc, totalBytes,
 620  	)
 621  }
 622  
 623  // readMessageWithEncodingNInternal is used to deduplicate the code because we
 624  // typically parse messages and headers all at once except in the case of a
 625  // downgraded v2->v1 conncection.
 626  func readMessageWithEncodingNInternal(r io.Reader, pver uint32,
 627  	hdr *messageHeader, btcnet BitcoinNet, enc MessageEncoding,
 628  	totalBytes int) (int, Message, []byte, error) {
 629  
 630  	// Enforce maximum protocol message payload.
 631  	if hdr.length > MaxProtocolMessageLength {
 632  		str := fmt.Sprintf("message payload is too large - header "+
 633  			"indicates %d bytes, but max message payload is %d "+
 634  			"bytes.", hdr.length, MaxProtocolMessageLength)
 635  		return totalBytes, nil, nil, messageError("ReadMessage", str)
 636  
 637  	}
 638  
 639  	// Check for messages from the wrong bitcoin network.
 640  	if hdr.magic != btcnet {
 641  		discardInput(r, hdr.length)
 642  		str := fmt.Sprintf("message from other network [%v]", hdr.magic)
 643  		return totalBytes, nil, nil, messageError("ReadMessage", str)
 644  	}
 645  
 646  	// Check for malformed commands.
 647  	command := hdr.command
 648  	if !utf8.ValidString(command) {
 649  		discardInput(r, hdr.length)
 650  		str := fmt.Sprintf("invalid command %v", []byte(command))
 651  		return totalBytes, nil, nil, messageError("ReadMessage", str)
 652  	}
 653  
 654  	// Create struct of appropriate message type based on the command.
 655  	msg, err := makeEmptyMessage(command)
 656  	if err != nil {
 657  		// makeEmptyMessage can only return ErrUnknownMessage and it is
 658  		// important that we bubble it up to the caller.
 659  		discardInput(r, hdr.length)
 660  		return totalBytes, nil, nil, err
 661  	}
 662  
 663  	// Check for maximum length based on the message type as a malicious client
 664  	// could otherwise create a well-formed header and set the length to max
 665  	// numbers in order to exhaust the machine's memory.
 666  	mpl := msg.MaxPayloadLength(pver)
 667  	if hdr.length > mpl {
 668  		discardInput(r, hdr.length)
 669  		str := fmt.Sprintf("payload exceeds max length - header "+
 670  			"indicates %v bytes, but max payload size for "+
 671  			"messages of type [%v] is %v.", hdr.length, command, mpl)
 672  		return totalBytes, nil, nil, messageError("ReadMessage", str)
 673  	}
 674  
 675  	// Read the payload as bytes arrive so a header cannot reserve the full
 676  	// claimed length on its own.
 677  	payload, err := readBytes(r, uint64(hdr.length))
 678  	totalBytes += len(payload)
 679  	if err != nil {
 680  		return totalBytes, nil, nil, err
 681  	}
 682  
 683  	// Test checksum.
 684  	checksum := chainhash.DoubleHashB(payload)[0:4]
 685  	if !bytes.Equal(checksum, hdr.checksum[:]) {
 686  		str := fmt.Sprintf("payload checksum failed - header "+
 687  			"indicates %v, but actual checksum is %v.",
 688  			hdr.checksum, checksum)
 689  		return totalBytes, nil, nil, messageError("ReadMessage", str)
 690  	}
 691  
 692  	// Unmarshal message.  NOTE: This must be a *bytes.Buffer since the
 693  	// MsgVersion BtcDecode function requires it.
 694  	pr := bytes.NewBuffer(payload)
 695  	err = msg.BtcDecode(pr, pver, enc)
 696  	if err != nil {
 697  		return totalBytes, nil, nil, err
 698  	}
 699  
 700  	// Reject messages where the payload was not fully consumed by
 701  	// BtcDecode. A peer could otherwise append arbitrary trailing bytes
 702  	// to an otherwise valid message, which would be silently accepted
 703  	// and persisted (e.g., in the block database).
 704  	if pr.Len() > 0 {
 705  		str := fmt.Sprintf("message payload has %d extra bytes "+
 706  			"after decode", pr.Len())
 707  		return totalBytes, nil, nil, messageError("ReadMessage", str)
 708  	}
 709  
 710  	return totalBytes, msg, payload, nil
 711  }
 712  
 713  // ReadMessageN reads, validates, and parses the next bitcoin Message from r for
 714  // the provided protocol version and bitcoin network.  It returns the number of
 715  // bytes read in addition to the parsed Message and raw bytes which comprise the
 716  // message.  This function is the same as ReadMessage except it also returns the
 717  // number of bytes read.
 718  func ReadMessageN(r io.Reader, pver uint32, btcnet BitcoinNet) (int, Message, []byte, error) {
 719  	return ReadMessageWithEncodingN(r, pver, btcnet, BaseEncoding)
 720  }
 721  
 722  // ReadMessage reads, validates, and parses the next bitcoin Message from r for
 723  // the provided protocol version and bitcoin network.  It returns the parsed
 724  // Message and raw bytes which comprise the message.  This function only differs
 725  // from ReadMessageN in that it doesn't return the number of bytes read.  This
 726  // function is mainly provided for backwards compatibility with the original
 727  // API, but it's also useful for callers that don't care about byte counts.
 728  func ReadMessage(r io.Reader, pver uint32, btcnet BitcoinNet) (Message, []byte, error) {
 729  	_, msg, buf, err := ReadMessageN(r, pver, btcnet)
 730  	return msg, buf, err
 731  }
 732