BitCoin 源码(go语言btcd源码)交易过程中各种主体之间的关系

yezhijing · 收录于 2023-06-03 04:24:06 · source URL

btcd源码的交易部分

下载btcd源码

btcd源码的整体目录结构如下:

 本篇文章要讲的是比特币交易过程中各种主体之间的关系,涉及到的文件有:msgblock.go、msgtx.go、utxoviewpoint.go如下:

1、wire目录下的msgblock.go及msgtx.go

 

 

2、blockchain 目录下的 utxoviewpoint.go

 

各种主体之间的关系

1、 我们从 msgblock.go 的源码中可以看到如下源码:

// MsgBlock implements the Message interface and represents a bitcoin
// block message.  It is used to deliver block and transaction information in
// response to a getdata message (MsgGetData) for a given block hash.
type MsgBlock struct {
	Header       BlockHeader
	Transactions []*MsgTx
}
  • 可以看出比特币发送交易时会将交易打包成一个【交易区块】 也就是这个【MsgBlock】
  • 【MsgBlock】中包含两个主体结构:【区块头】和【交易】
  • 【交易】是一个切片,也就是说一个【交易区块】包含多个【交易】

如上我们可以得到如下关系图:

2、从Transactions 的类型可以知道【交易】其实就是【MsgTx】 ,我们需要看 msgtx.go的源码:

// 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
}

从其源码上我们可以得到如下信息:

  • 【交易】里包含 一个【版本号_Version】、多个【TxIn】、多个【TxOut】和一个【锁定时间_LockTime】 

接下来我们需要确认【TxIn】和【TxOut】分别代表什么,我们直接看其定义的源码:

// TxIn defines a bitcoin transaction input.
type TxIn struct {
	PreviousOutPoint OutPoint
	SignatureScript  []byte
	Witness          TxWitness
	Sequence         uint32
// TxOut defines a bitcoin transaction output.
type TxOut struct {
	Value    int64
	PkScript []byte
}

从注释中不难理解:

  • 【TxIn】和 【TxOut】分别代表比特币交易的输入、比特币交易的输出

由以上信息我们可得到如下关系:

3、当这个【MsgBlock】被矿工开采完成之后,每个账户新增加的金额或是剩下的金额都会放到对应账户下的【UTXO】中,其结构源码如下:

// UtxoEntry houses details about an individual transaction output in a utxo
// view such as whether or not it was contained in a coinbase tx, the height of
// the block that contains the tx, whether or not it is spent, its public key
// script, and how much it pays.
type UtxoEntry struct {
	// NOTE: Additions, deletions, or modifications to the order of the
	// definitions in this struct should not be changed without considering
	// how it affects alignment on 64-bit platforms.  The current order is
	// specifically crafted to result in minimal padding.  There will be a
	// lot of these in memory, so a few extra bytes of padding adds up.

	amount      int64
	pkScript    []byte // The public key script for the output.
	blockHeight int32  // Height of block containing tx.

	// packedFlags contains additional info about output such as whether it
	// is a coinbase, whether it is spent, and whether it has been modified
	// since it was loaded.  This approach is used in order to reduce memory
	// usage since there will be a lot of these in memory.
	packedFlags txoFlags
}
  • 【packedFlags】 会标记这个【UTXO】的类型:【coinbase】、【已花费】、【已花费】,用来实现快速的从数据库中检索。

其关系如下:

 说明

以上仅仅是本人的理解分析,不代表官方真实逻辑,如有问题请留言。