上一篇:數(shù)據(jù)結(jié)構(gòu)-區(qū)塊Block
首先,通過blockchain.info查看一筆交易的基本數(shù)據(jù)結(jié)構(gòu):
blockchain.info_1
blockchain.info_2
blockchain.info_3
源碼初窺
- 代碼路徑: bitcoin/src/private
COutPut
/** An outpoint - a combination of a transaction hash and an index n into its vout
*
** 一個交易哈希值與輸出下標(biāo)的集合
*/
class COutPoint
{
public:
uint256 hash; //交易哈西
uint32_t n; //對應(yīng)序列號
COutPoint(): n((uint32_t) -1) { }
COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
ADD_SERIALIZE_METHODS; //用來序列化數(shù)據(jù)結(jié)構(gòu)幌绍,方便存儲和傳輸
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); }
//小于號<重載函數(shù)
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);
}
//==重載函數(shù)
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
//!=重載函數(shù)
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const;
};
CTxIn
/** 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.
*
**交易的輸入,包括當(dāng)前輸入所對應(yīng)上一筆交易的輸出位置仆潮,
*并且還包括上一筆輸出所需要的簽名腳本
*/
class CTxIn
{
public:
COutPoint prevout; //上一筆交易輸出位置
CScript scriptSig; //解鎖腳本
uint32_t nSequence; /**序列號,可用于交易的鎖定
nSequence字段的設(shè)計初心是想讓交易能在在內(nèi)存中修改遣臼,可惜后面從未運用過
對于具有nLocktime或CHECKLOCKTIMEVERIFY的交易性置,
nSequence值必須設(shè)置為小于2^32,以使時間鎖定器有效揍堰。通常設(shè)置為2^32-1
由于BIP-68的激活鹏浅,新的共識規(guī)則適用于任何包含nSequence值小于2^31的輸入的交易(bit 1<<31 is not set)。
以編程方式屏歹,這意味著如果沒有設(shè)置最高有效(bit 1<<31)隐砸,它是一個表示“相對鎖定時間”的標(biāo)志。
否則(bit 1<<31set)蝙眶,nSequence值被保留用于其他用途季希,
例如啟用CHECKLOCKTIMEVERIFY,nLocktime幽纷,Opt-In-Replace-By-Fee以及其他未來的新產(chǎn)品式塌。
一筆輸入交易,當(dāng)輸入腳本中的nSequence值小于2^31時友浸,就是相對時間鎖定的輸入交易峰尝。
這種交易只有到了相對鎖定時間后才生效。例如收恢,
具有30個區(qū)塊的nSequence相對時間鎖的一個輸入的交易
只有在從輸入中引用的UTXO開始的時間起至少有30個塊時才有效武学。
由于nSequence是每個輸入字段祭往,因此交易可能包含任何數(shù)量的時間鎖定輸入,
所有這些都必須具有足夠的時間以使交易有效劳淆。
*/
CScriptWitness scriptWitness; //! Only serialized through CTransaction
/* Setting nSequence to this value for every input in a transaction
* disables nLockTime.
*
* 規(guī)則1:如果一筆交易中所有的SEQUENCE_FINAL都被賦值了相應(yīng)的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.
*
* 規(guī)則2:如果設(shè)置了該值默赂,nSequence不被用于相對時間鎖定沛鸵。規(guī)則1失效
*/
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.
*
* 規(guī)則3:如果規(guī)則1有效并且設(shè)置了此變量,那么相對鎖定時間單位為512秒缆八,否則鎖定時間就為1個區(qū)塊
*/
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.
*
* 規(guī)則4:如果nSequence用于相對時間鎖曲掰,即規(guī)則1有效,那么這個變量就用來從nSequence計算對應(yīng)的鎖定時間
*/
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.
*
* 相對時間鎖粒度
* 為了使用相同的位數(shù)來粗略地編碼相同的掛鐘時間奈辰,
* 因為區(qū)塊的產(chǎn)生限制于每600s產(chǎn)生一個栏妖,
* 相對時間鎖定的最小單位為512是,512 = 2^9
* 所以相對時間鎖定的時間轉(zhuǎn)化為相當(dāng)于當(dāng)前值左移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;
};
CTxOut
/** 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);
}
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;
};
CTransaction
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*
*
** 基本的交易吊趾,就是那些在網(wǎng)絡(luò)中廣播并被最終打包到區(qū)塊中的數(shù)據(jù)結(jié)構(gòu)。
* 一個交易可以包含多個交易輸入和輸出
*/
class CTransaction
{
public:
// Default transaction version.
static const int32_t CURRENT_VERSION=2; //默認(rèn)交易版本
// 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.
/** 更改默認(rèn)交易版本需要兩個步驟:
* 1.首先通過碰撞MAX_STANDARD_VERSION來調(diào)整中繼策略瑟啃,
* 2.然后在稍后的日期碰撞默認(rèn)的CURRENT_VERSION
*
* 最終MAX_STANDARD_VERSION和CURRENT_VERSION會一致
*/
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
// strcture, including the hash.
/** 下面這些變量都被定義為常量類型论泛,從而避免無意識的修改了交易而沒有更新緩存的hash值;
* 然而CTransaction不是可變的
* 反序列化和分配被執(zhí)行的時候會繞過常量
* 這才是安全的蛹屿,因為更新整個結(jié)構(gòu)包括哈希值
*/
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. */
/**可變交易轉(zhuǎn)換為交易*/
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.
*
** 提供此反序列化構(gòu)造函數(shù)而不是Unserialize方法屁奏。
* 反序列化是不可能的,因為它需要覆蓋const字段
*/
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; //計算包含交易和witness數(shù)據(jù)的散列
// 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; // 返回交易大小
bool IsCoinBase() const //判斷是否是創(chuàng)幣交易
{
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;
}
};
CMutableTransaction
可變交易類错负,內(nèi)容和CTransaction差不多坟瓢。只是交易可以直接修改,廣播中傳播和打包到區(qū)塊的交易都是CTransaction類型犹撒。
交易結(jié)構(gòu)
交易是比特幣的核心數(shù)據(jù)結(jié)構(gòu)折联,包括區(qū)塊在內(nèi)的數(shù)據(jù)結(jié)構(gòu)都是在為交易服務(wù)。
整體結(jié)構(gòu)
數(shù)據(jù)項 | 大小(Byte) | 數(shù)據(jù)類型 | 描述 |
---|---|---|---|
Version | 4 | uint32_t | 交易版本 |
tx_in count | Varies | CompactSize Unsigned Integer | 交易輸入量 |
tx_out count | Varies | CompactSize Unsigned Integer | 交易輸出量 |
tx_in | Varies | CTxIn | 交易輸入 |
tx_in | Varies | CTxOut | 交易輸出 |
lock_time | 4 | uint32_t | 交易鎖定時間识颊,詳見鎖定規(guī)則 |
交易輸入TxIn
數(shù)據(jù)項 | 大小(Byte) | 數(shù)據(jù)類型 | 描述 |
---|---|---|---|
previous_output | 36 | COutPoint | 上一個交易的輸出 |
script bytes | Varies < 10000 | CompactSize Unsigned Integer | 解鎖腳本大小 |
signature script | Varies | char[] | 解鎖腳本 |
sequence | 4 | uint32_t | 序列號诚镰,可用于相對時間鎖定 |
交易輸出TxOut
數(shù)據(jù)項 | 大小(Byte) | 數(shù)據(jù)類型 | 描述 |
---|---|---|---|
value | 8 | int64_t | 交易輸出,單位為Satoshis |
pk_script bytes | Varies < 10000 | CompactSize Unsigned Integer | 鎖定腳本大小 |
pk_script | Varies | char[] | 鎖定腳本谊囚,定義花費須滿足的條件 |
創(chuàng)幣交易CoinbaseTransaction
每一個區(qū)塊內(nèi)包含的第一條交易為CoinbaseTransaction怕享,它作為對挖出該區(qū)塊的礦工的比特幣獎勵交易。
- 沒有TxIn
- 交易哈希為0
- 輸出的索引值固定镰踏,為0xffffffff
- 大端存儲
- BIP34規(guī)定增加一個4字節(jié)的height的字段函筋,現(xiàn)在這個參數(shù)是必須的
下一篇:數(shù)據(jù)結(jié)構(gòu)-交易池(TransactionPool)
參考文獻
.
.
.
.
互聯(lián)網(wǎng)顛覆世界,區(qū)塊鏈顛覆互聯(lián)網(wǎng)!
--------------------------------------------------20180420 22:57