主页 > imtoken钱包国际版下载 > 图解比特币第 1 部分
图解比特币第 1 部分
比特币简介第 11.1 部分
本系列使用golang从零开始编写一个比特币轻量级节点。 最终实现与实际比特币网络的交易和SPV(Simplified Payment Verification)。
注:大部分代码来源于BTCD,其实是一篇BTCD源码分析文章。 最终实现了以下功能:
连接比特币网络(包括mainnet、testnet、simnet)加入比特币网络(“版本握手”),从其他节点获取区块链状态,下载区块链头,实现SPV(Simplified Payment Verification)交易比特币
注意:阅读前请确认您对比特币的区块链结构有初步了解。
1.2 代码地址
比特币 Part_1 的插图
1.3 搭建测试网络
编程之初比特币源码分析教程,我们使用的是BCTD自带的测试网。 测试网络配置如下:
# btcd.conf
[Application Options]
datadir=./btcd/data
listen=127.0.0.1:9333
simnet=1
nobanning=1
debuglevel=debug
listen为测试网的ipsimnet,代表模拟网络(Simulation Network) nobanning 不禁止任何节点 debuglevel=debug输出日志信息
启动终端,输入命令:btcd --configfile ./btcd.conf 启动测试网络。
1.4 节点建立连接
在比特币系统中,节点通过执行初始“握手”来建立连接。
Version:版本消息(关键内容:版本号,当前节点区块链的区块高度)
Verack:确认已收到消息
第 1 部分的最终效果是与比特币网络发送和接收消息并建立连接。
1.5 代码结构
1.6 时序图
1.7 通讯协议
追求女生的第一步,就是要了解对方想要什么。 比如初次见面,先看相貌。 节点间通信也是如此。 一开始先检查版本。 如果版本不好,也会被拒。
// #msgversion.go
type MsgVersion struct {
// Version of the protocol the node is using.
ProtocolVersion int32
// Bitfield which identifies the enabled services.
Services ServiceFlag
// Time the message was generated. This is encoded as an int64 on the wire.
Timestamp time.Time
// Address of the remote peer.
AddrYou NetAddress
// Address of the local peer.
AddrMe NetAddress
// Unique value associated with message that is used to detect self
// connections.
Nonce uint64
// The user agent that generated messsage. This is a encoded as a varString
// on the wire. This has a max length of MaxUserAgentLen.
UserAgent string
// Last block seen by the generator of the version message.
LastBlock int32
// Don't announce transactions to peer.
DisableRelayTx bool
}
ProtocolVersion表示协议版本,版本号越大比特币源码分析教程,版本越新。查看详情
services代表节点支持的服务,暂用1代表全节点
UserAgent类似于http协议的User-Agent,包括节点软件的名称和版本
LastBlock 表示最新区块的高度
MsgVersion 表示需要发送的内容。
由于消息的底层是一个字节序列,我们需要就字节序列的格式达成一致。
// #message.go
type messageHeader struct {
magic BitcoinNet // 4 bytes
command string // 12 bytes
length uint32 // 4 bytes
checksum [4]byte // 4 bytes
}
magic表示网络类型,目前使用SimNet表示测试网络。 command表示命令名称,目前CmdVersion表示这是获取版本的命令。 length表示数据内容的长度。 校验和数据内容的双重散列。
获取数据内容的接口是下面的BtcEncode。
获取数据内容最大长度的接口是下面的MaxPayloadLength。
获取命令名的接口是下面的Command。
// #message.go
type Message interface {
BtcDecode(io.Reader, uint32, MessageEncoding) error
BtcEncode(io.Writer, uint32, MessageEncoding) error
Command() string
MaxPayloadLength(uint32) uint32
}
最终发送报文的字节序列格式:
BYTES(Msg.magic) + BYTES(Msg.Command()) + BYTES(Msg.length) + BYTES(Msg.checksum) + BYTES(Msg.BtcEncode())
1.8 测试:
结果如下:
$ go run ./
INFO[0000] version70013
INFO[0000] verack
1.9 总结:
关键内容是消息的解构,消息由消息头和消息组成。
最终发送报文的字节序列格式:
BYTES(Msg.magic) + BYTES(Msg.Command()) + BYTES(Msg.length) + BYTES(Msg.checksum) + BYTES(Msg.BtcEncode())
参考:
BTCD
一点点
《比特币白皮书》
《解构区块链》
本作品采用《CC协议》,转载需注明作者及本文链接