比特幣原始碼研讀(3)資料結構-交易Transaction

chaors發表於2018-04-25

上一篇:資料結構-區塊Block

首先,通過blockchain.info檢視一筆交易的基本資料結構:

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 
*
** 一個交易雜湊值與輸出下標的集合
*/
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;
};
複製程式碼

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.
 *
 **交易的輸入,包括當前輸入所對應上一筆交易的輸出位置,
 *並且還包括上一筆輸出所需要的簽名指令碼
 */
class CTxIn
{
public:
    COutPoint prevout;      //上一筆交易輸出位置
    CScript scriptSig;      //解鎖指令碼
    uint32_t nSequence;     /**序列號,可用於交易的鎖定 
                            nSequence欄位的設計初心是想讓交易能在在記憶體中修改,可惜後面從未運用過
                            對於具有nLocktime或CHECKLOCKTIMEVERIFY的交易,
                            nSequence值必須設定為小於2^32,以使時間鎖定器有效。通常設定為2^32-1
                            由於BIP-68的啟用,新的共識規則適用於任何包含nSequence值小於2^31的輸入的交易(bit 1<<31 is not set)。
                            以程式設計方式,這意味著如果沒有設定最高有效(bit 1<<31),它是一個表示“相對鎖定時間”的標誌。
                            否則(bit 1<<31set),nSequence值被保留用於其他用途,
                            例如啟用CHECKLOCKTIMEVERIFY,nLocktime,Opt-In-Replace-By-Fee以及其他未來的新產品。
                            一筆輸入交易,當輸入指令碼中的nSequence值小於2^31時,就是相對時間鎖定的輸入交易。
                            這種交易只有到了相對鎖定時間後才生效。例如,
                            具有30個區塊的nSequence相對時間鎖的一個輸入的交易
                            只有在從輸入中引用的UTXO開始的時間起至少有30個塊時才有效。
                            由於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:如果設定了該值,nSequence不被用於相對時間鎖定。規則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. 
     *
     * 規則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:如果nSequence用於相對時間鎖,即規則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. 
     *
     * 相對時間鎖粒度
     * 為了使用相同的位數來粗略地編碼相同的掛鐘時間,
     * 因為區塊的產生限制於每600s產生一個,
     * 相對時間鎖定的最小單位為512是,512 = 2^9
     * 所以相對時間鎖定的時間轉化為相當於當前值左移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.
 *
 *
 ** 基本的交易,就是那些在網路中廣播並被最終打包到區塊中的資料結構。
 *  一個交易可以包含多個交易輸入和輸出
 */
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.
    /** 更改預設交易版本需要兩個步驟:
    *   1.首先通過碰撞MAX_STANDARD_VERSION來調整中繼策略,
    *   2.然後在稍後的日期碰撞預設的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不是可變的
    *   反序列化和分配被執行的時候會繞過常量
    *   這才是安全的,因為更新整個結構包括雜湊值
    */
    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. 
     *
     ** 提供此反序列化建構函式而不是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資料的雜湊           

    // 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                 //判斷是否是創幣交易
    {
        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

可變交易類,內容和CTransaction差不多。只是交易可以直接修改,廣播中傳播和打包到區塊的交易都是CTransaction型別。

交易結構

交易是比特幣的核心資料結構,包括區塊在內的資料結構都是在為交易服務。

整體結構

資料項 大小(Byte) 資料型別 描述
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 交易鎖定時間,詳見鎖定規則

交易輸入TxIn

資料項 大小(Byte) 資料型別 描述
previous_output 36 COutPoint 上一個交易的輸出
script bytes Varies < 10000 CompactSize Unsigned Integer 解鎖指令碼大小
signature script Varies char[] 解鎖指令碼
sequence 4 uint32_t 序列號,可用於相對時間鎖定

交易輸出TxOut

資料項 大小(Byte) 資料型別 描述
value 8 int64_t 交易輸出,單位為Satoshis
pk_script bytes Varies < 10000 CompactSize Unsigned Integer 鎖定指令碼大小
pk_script Varies char[] 鎖定指令碼,定義花費須滿足的條件

創幣交易CoinbaseTransaction

每一個區塊內包含的第一條交易為CoinbaseTransaction,它作為對挖出該區塊的礦工的比特幣獎勵交易。

  • 沒有TxIn
  • 交易雜湊為0
  • 輸出的索引值固定,為0xffffffff
  • 大端儲存
  • BIP34規定增加一個4位元組的height的欄位,現在這個引數是必須的

下一篇:資料結構-交易池(TransactionPool)

###參考文獻

. . . .

網際網路顛覆世界,區塊鏈顛覆網際網路!

--------------------------------------------------20180420 22:57

相關文章