简介

交易(transaction)是比特币甚至所有区块链中最核心的数据结构之一,其他所有的模块都是为交易服务的,包括交易的产生、广播、共识、存储等等,都是首先从交易出发,然后逐步延伸到其他模块。

文件名 //transaction.h

1
2
3
4
class COutPoint
class CTxIn
class CTxOut
class CTransaction

01 COutPoint

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
/** 
* An outpoint - a combination of a transaction hash and an index n into its vout
* COutPoint主要用在交易的输入CTxIn中,用来确定当前输出的来源,
* 包括前一笔的交易hash,以及对应前一笔交易中的第几个输出的序列号。
*/
class COutPoint
{
public:
uint256 hash;//交易的哈希
uint32_t n; //交易对应的序列号

COutPoint(): n((uint32_t) -1) { }
COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }

ADD_SERIALIZE_METHODS; //用来序列化数据结构

template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(hash);
READWRITE(n);
}

void SetNull() { hash.SetNull(); n = (uint32_t) -1; }
bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); }

//重载小于号
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
int cmp = a.hash.Compare(b.hash);
return cmp < 0 || (cmp == 0 && a.n < b.n);
}

friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}

friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}

std::string ToString() const;
};

02 CTxIn

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/** An input of a transaction.  It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
* 交易的输入,包括当前输入对应前一笔交易的输出的位置,以及花费前一笔输出需要的签名脚本
* CScriptWitness是用来支持隔离见证时使用的。
*/
class CTxIn
{
public:
COutPoint prevout;//上一笔一笔交易输出位置
CScript scriptSig;//解锁脚本
uint32_t nSequence;//交易序列号
CScriptWitness scriptWitness; //! Only serialized through CTransaction

/* Setting nSequence to this value for every input in a transaction
* disables nLockTime.
* 规则1:如果一笔交易中所有SEQUENCE_FINAL都被赋值到相应的nSequence参数,nLockTime将会被禁用*/
static const uint32_t SEQUENCE_FINAL = 0xffffffff;

/* Below flags apply in the context of BIP 68*/
/* If this flag set, CTxIn::nSequence is NOT interpreted as a
* relative lock-time.
* 规则2:如果设置了这个变量,那么规则1(nLockTime被禁用)就失效了 */
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);

/* If CTxIn::nSequence encodes a relative lock-time and this flag
* is set, the relative lock-time has units of 512 seconds,
* otherwise it specifies blocks with a granularity of 1.
* 规则3:如果规则1有效并且设置了此变量,那么相对锁定时间就为512秒,否则锁定时间就为1个区块 */
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);

/* If CTxIn::nSequence encodes a relative lock-time, this mask is
* applied to extract that lock-time from the sequence field.
* 规则4:如果规则1有效,那么这个变量就用来从nSequence计算对应的锁定时间 */
*
static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;

/* In order to use the same number of bits to encode roughly the
* same wall-clock duration, and because blocks are naturally
* limited to occur every 600s on average, the minimum granularity
* for time-based relative lock-time is fixed at 512 seconds.
* Converting from CTxIn::nSequence to seconds is performed by
* multiplying by 512 = 2^9, or equivalently shifting up by
* 9 bits. */
static const int SEQUENCE_LOCKTIME_GRANULARITY = 9; static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;

CTxIn()
{
nSequence = SEQUENCE_FINAL;
}

// 禁用隐式转换,构造函数必须明确使用当前形式
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);

ADD_SERIALIZE_METHODS;

template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
}

friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}

friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}

std::string ToString() const;
};

03 CTxOut

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
/** An output of a transaction.  It contains the public key that the next input
* must be able to sign with to claim it.
* 交易的输出体,包含交易金额和锁定脚本
*/
class CTxOut
{
public:
CAmount nValue;//输出金额
CScript scriptPubKey;//锁定脚本

CTxOut()
{
SetNull();
}

CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);

ADD_SERIALIZE_METHODS;

template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(nValue);
READWRITE(scriptPubKey);
}

void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}

bool IsNull() const
{
return (nValue == -1);
}

// 获取dust阈值,一笔交易如果交易费小于dust阈值,就会被认为是dust tx
// 此函数在最新版本中已转移到src/policy/policy.h中
// CAmount GetDustThreshold(const CFeeRate &minRelayTxFee)

friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}

friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}

std::string ToString() const;
};

04 CTransaction

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
* 这是网络中广播然后被打进区块的最基本的交易结构,一个交易体可以包含多个交易
*/
class CTransaction
{
public:
// Default transaction version. 默认交易版本号
static const int32_t CURRENT_VERSION=2;

// Changing the default transaction version requires a two step process: first
// adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date
// bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and
// MAX_STANDARD_VERSION will be equal.
static const int32_t MAX_STANDARD_VERSION=2;

// The local variables are made const to prevent unintended modification
// without updating the cached hash value. However, CTransaction is not
// actually immutable; deserialization and assignment are implemented,
// and bypass the constness. This is safe, as they update the entire
// structure, including the hash.

const std::vector<CTxIn> vin; //交易版本号
const std::vector<CTxOut> vout; //交易输入
const int32_t nVersion; //交易输出
const uint32_t nLockTime; //交易锁定时间

private:
/** Memory only. */
const uint256 hash;

uint256 ComputeHash() const;

public:
/** Construct a CTransaction that qualifies as IsNull() */
CTransaction();

/** Convert a CMutableTransaction into a CTransaction. */
CTransaction(const CMutableTransaction &tx);
CTransaction(CMutableTransaction &&tx);

template <typename Stream>
inline void Serialize(Stream& s) const {
SerializeTransaction(*this, s);
}

/** This deserializing constructor is provided instead of an Unserialize method.
* Unserialize is not possible, since it would require overwriting const fields. */
template <typename Stream>
CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}

bool IsNull() const {
return vin.empty() && vout.empty();
}

const uint256& GetHash() const {
return hash;
}

// Compute a hash that includes both transaction and witness data
uint256 GetWitnessHash() const;//计算哈希值 (包含交易和见证数据)

// Return sum of txouts. 返回交易输出金额和总数
CAmount GetValueOut() const;
// GetValueIn() is a method on CCoinsViewCache, because
// inputs must be known to compute value in.

/**
* Get the total transaction size in bytes, including witness data.
* "Total Size" defined in BIP141 and BIP144.
* @return Total transaction size in bytes
*/
unsigned int GetTotalSize() const;// 返回交易数据字节性大小

//判断是否为coinbase交易
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}

friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return a.hash == b.hash;
}

friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return a.hash != b.hash;
}

std::string ToString() const;

bool HasWitness() const
{
for (size_t i = 0; i < vin.size(); i++) {
if (!vin[i].scriptWitness.IsNull()) {
return true;
}
}
return false;
}
};