比特幣源碼研讀(3)數(shù)據(jù)結(jié)構(gòu)-交易Transaction

上一篇:數(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末奠伪,一起剝皮案震驚了整個濱河市跌帐,隨后出現(xiàn)的幾起案子首懈,更是在濱河造成了極大的恐慌,老刑警劉巖谨敛,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件究履,死亡現(xiàn)場離奇詭異,居然都是意外死亡脸狸,警方通過查閱死者的電腦和手機最仑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來炊甲,“玉大人泥彤,你說我怎么就攤上這事∏浞龋” “怎么了吟吝?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長颈娜。 經(jīng)常有香客問我剑逃,道長,這世上最難降的妖魔是什么官辽? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任蛹磺,我火速辦了婚禮,結(jié)果婚禮上野崇,老公的妹妹穿的比我還像新娘称开。我一直安慰自己,他們只是感情好乓梨,可當(dāng)我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布鳖轰。 她就那樣靜靜地躺著,像睡著了一般扶镀。 火紅的嫁衣襯著肌膚如雪蕴侣。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天臭觉,我揣著相機與錄音昆雀,去河邊找鬼。 笑死蝠筑,一個胖子當(dāng)著我的面吹牛狞膘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播什乙,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼挽封,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了臣镣?” 一聲冷哼從身側(cè)響起辅愿,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤智亮,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后点待,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體阔蛉,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年癞埠,在試婚紗的時候發(fā)現(xiàn)自己被綠了状原。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡燕差,死狀恐怖遭笋,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情徒探,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布喂窟,位于F島的核電站测暗,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏磨澡。R本人自食惡果不足惜碗啄,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望稳摄。 院中可真熱鬧稚字,春花似錦、人聲如沸厦酬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽仗阅。三九已至昌讲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間减噪,已是汗流浹背短绸。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留筹裕,地道東北人醋闭。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像朝卒,于是被迫代替她去往敵國和親证逻。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 一扎运、快速術(shù)語檢索 比特幣地址:(例如:1DSrfJdB2AnWaFNgSbv3MZC2m74996JafV)由一串...
    不如假如閱讀 15,997評論 4 87
  • 在本章中瑟曲,我們將討論Bitcoin中的權(quán)力下放(去中心化)饮戳。在第一章中,我們研究了比特幣基礎(chǔ)的加密基礎(chǔ)洞拨,并以我們稱...
    Nutbox_Lab閱讀 1,839評論 -1 3
  • 最近關(guān)于左右先生的毒雞湯刷爆了整個朋友圈扯罐,很多姑娘都開始抱怨男朋友這里不對,那里不好烦衣,沒有像文章里那樣面面俱到歹河。 ...
    洛小婭閱讀 2,055評論 0 1
  • 前段時間做了個月子,真正體會了什么是一孕傻三年花吟。一孕傻三年真的是智商下降了嗎秸歧?背后是否有科學(xué)性先不追究,只說說我的...
    后知后覺人閱讀 375評論 0 1
  • 一句話像子彈 貫穿了我的心 傷口處 流經(jīng)的風(fēng)成了刀 撕扯著皮肉 碎屑在當(dāng)中翻飛 可能我要死了 眼前不斷重復(fù) 美好與...
    大棚蓋澆飯閱讀 164評論 0 0