msgpong.go raw

   1  package wire
   2  
   3  import (
   4  	"fmt"
   5  	"io"
   6  )
   7  
   8  // MsgPong implements the Message interface and represents a bitcoin pong message which is used primarily to confirm
   9  // that a connection is still valid in response to a bitcoin ping message (MsgPing). This message was not added until
  10  // protocol versions AFTER BIP0031Version.
  11  type MsgPong struct {
  12  	// Unique value associated with message that is used to identify specific ping message.
  13  	Nonce uint64
  14  }
  15  
  16  // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. This is part of the Message interface
  17  // implementation.
  18  func (msg *MsgPong) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) (e error) {
  19  	// NOTE: <= is not a mistake here.  The BIP0031 was defined as AFTER the version unlike most others.
  20  	if pver <= BIP0031Version {
  21  		str := fmt.Sprintf("pong message invalid for protocol "+
  22  			"version %d", pver,
  23  		)
  24  		return messageError("MsgPong.BtcDecode", str)
  25  	}
  26  	return readElement(r, &msg.Nonce)
  27  }
  28  
  29  // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. This is part of the Message interface
  30  // implementation.
  31  func (msg *MsgPong) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) (e error) {
  32  	// NOTE: <= is not a mistake here.  The BIP0031 was defined as AFTER the version unlike most others.
  33  	if pver <= BIP0031Version {
  34  		str := fmt.Sprintf("pong message invalid for protocol "+
  35  			"version %d", pver,
  36  		)
  37  		return messageError("MsgPong.BtcEncode", str)
  38  	}
  39  	return writeElement(w, msg.Nonce)
  40  }
  41  
  42  // Command returns the protocol command string for the message. This is part of the Message interface implementation.
  43  func (msg *MsgPong) Command() string {
  44  	return CmdPong
  45  }
  46  
  47  // MaxPayloadLength returns the maximum length the payload can be for the receiver. This is part of the Message
  48  // interface implementation.
  49  func (msg *MsgPong) MaxPayloadLength(pver uint32) uint32 {
  50  	plen := uint32(0)
  51  	// The pong message did not exist for BIP0031Version and earlier. NOTE: > is not a mistake here. The BIP0031 was
  52  	// defined as AFTER the version unlike most others.
  53  	if pver > BIP0031Version {
  54  		// Nonce 8 bytes.
  55  		plen += 8
  56  	}
  57  	return plen
  58  }
  59  
  60  // NewMsgPong returns a new bitcoin pong message that conforms to the Message interface.  See MsgPong for details.
  61  func NewMsgPong(nonce uint64) *MsgPong {
  62  	return &MsgPong{
  63  		Nonce: nonce,
  64  	}
  65  }
  66