参考:protocol documentbtcd

  • 协议其实就是一个标准,btc有多种语言的实现版本,他们之间能够正常通信的基础就是共同遵守了这个标准。btc定义的协议有很多,包括p2p之间通信协议、交易认证协议、pow共识协议等等。本文主要分析p2p网络的消息协议及代码实现
  • btc 的p2p网络的传输层支持tcp、udp、onion,应用层使用的即是本文讨论的消息协议

一、Message

一次通信以message为单位,具体结构如上图: d018cee1eb87aabcbc1bd44609e2beb3.png

代码实现:

(1)通用接口定义

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Message is an interface that describes a bitcoin message.  A type that
// implements Message has complete control over the representation of its data
// and may therefore contain additional or fewer fields than those which
// are used directly in the protocol encoded message.
type Message interface {
	BtcDecode(io.Reader, uint32, MessageEncoding) error
	BtcEncode(io.Writer, uint32, MessageEncoding) error
	Command() string
	MaxPayloadLength(uint32) uint32
}

message 接口,定义通用方法,由具体的消息类型去实现

  • BtcDecode BtcEnode 将结构化的消息体序列化为字节流 (对应payload) 或者将字节流实例化为某种消息格式
  • Commd 返回具体消息的命令字符串,标识不同的命令
  • MaxPayloadLength 最大payload 长度

(2)通用header

Magic bytes are used as a way to identify the separate messages sent between nodes on the bitcoin network.

1
2
3
4
5
6
7
// messageHeader defines the header structure for all bitcoin protocol messages.
type messageHeader struct {
	magic    BitcoinNet // 4 bytes
	command  string     // 12 bytes
	length   uint32     // 4 bytes
	checksum [4]byte    // 4 bytes
}

message header 结构体,定义通用部分字段

(3)发送

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
func WriteMessageN(w io.Writer, msg Message, pver uint32, hcnet CurrencyNet) (int, error) {
	totalBytes := 0

	// Enforce max command size.
	var command [CommandSize]byte
	cmd := msg.Command()
	if len(cmd) > CommandSize {
		str := fmt.Sprintf("command [%s] is too long [max %v]",
			cmd, CommandSize)
		return totalBytes, messageError("WriteMessage", str)
	}
	copy(command[:], []byte(cmd))

	// Encode the message payload.
	var bw bytes.Buffer
	err := msg.BtcEncode(&bw, pver)
	if err != nil {
		return totalBytes, err
	}
	payload := bw.Bytes()
	lenp := len(payload)

	// Enforce maximum overall message payload.
	if lenp > MaxMessagePayload {
		str := fmt.Sprintf("message payload is too large - encoded "+
			"%d bytes, but maximum message payload is %d bytes",
			lenp, MaxMessagePayload)
		return totalBytes, messageError("WriteMessage", str)
	}

	// Enforce maximum message payload based on the message type.
	mpl := msg.MaxPayloadLength(pver)
	if uint32(lenp) > mpl {
		str := fmt.Sprintf("message payload is too large - encoded "+
			"%d bytes, but maximum message payload size for "+
			"messages of type [%s] is %d.", lenp, cmd, mpl)
		return totalBytes, messageError("WriteMessage", str)
	}

	// Create header for the message.
	hdr := messageHeader{}
	hdr.magic = hcnet
	hdr.command = cmd
	hdr.length = uint32(lenp)
	copy(hdr.checksum[:], chainhash.HashB(payload)[0:4])

	// Encode the header for the message.  This is done to a buffer
	// rather than directly to the writer since writeElements doesn't
	// return the number of bytes written.
	hw := bytes.NewBuffer(make([]byte, 0, MessageHeaderSize))
	writeElements(hw, hdr.magic, command, hdr.length, hdr.checksum)

	// Write header.
	n, err := w.Write(hw.Bytes())
	totalBytes += n
	if err != nil {
		return totalBytes, err
	}

	// Write payload.
	n, err = w.Write(payload)
	totalBytes += n
	return totalBytes, err
}

发送message时,先发送header再发送payload

二、具体消息举例:Tx

99cea19d9cefbb3d00df0c5331f6458e.png

代码实现:

(1)定义tx结构体

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// MsgTx implements the Message interface and represents a bitcoin tx message.
// It is used to deliver transaction information in response to a getdata
// message (MsgGetData) for a given transaction.
//
// Use the AddTxIn and AddTxOut functions to build up the list of transaction
// inputs and outputs.
type MsgTx struct {
	Version  int32
	TxIn     []*TxIn
	TxOut    []*TxOut
	LockTime uint32
}

(2) 接口实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Command returns the protocol command string for the message.  This is part
// of the Message interface implementation.
func (msg *MsgTx) Command() string {
	return CmdTx
}

// MaxPayloadLength returns the maximum length the payload can be for the
// receiver.  This is part of the Message interface implementation.
func (msg *MsgTx) MaxPayloadLength(pver uint32) uint32 {
	return MaxBlockPayload
}

BtcDecode BtcEnode 不再赘述,具体可参考 btcd