比特币源代码--13--数据结构-交易

查看比特币交易信息:https://www.blockchain.com/explorer缓存

比特币交易是比特币系统中最重要的部分。根据比特币系统的设计原理,系统中任何其余的部分都是为了确保比特币交易能够被生成、能在比特币网络中得以传播和经过验证,并最终添加入全球比特币交易总帐簿(比特币区块链)。比特币交易的本质是数据结构,这些数据结构中含有比特币交易参与者价值转移的相关信息。比特币区块链是一本全球复式记帐总帐簿,每一个比特币交易都是在比特币区块链上的一个公开记录。安全

1、总体结构

下面是对一个交易解码事后的信息。网络

{
  "version": 1,
  "locktime": 0,
  "vin": [
    {
      "txid":"7957a35fe64f80d234d76d83a2a8f1a0d8149a41d81de548f0a65a8a999f6f18",
      "vout": 0,
      "scriptSig": "3045022100884d142d86652a3f47ba4746ec719bbfbd040a570b1deccbb6498c75c4ae24cb02204b9f039ff08df09cbe9f6addac960298cad530a863ea8f53982c09db8f6e3813[ALL] 0484ecc0d46f1918b30928fa0e4ed99f16a0fb4fde0735e7ade8416ab9fe423cc5412336376789d172787ec3457eee41c04f4938de5cc17b4a10fa336a8d752adf",
      "sequence": 4294967295
    }
 ],
  "vout": [
    {
      "value": 0.01500000,
      "scriptPubKey": "OP_DUP OP_HASH160 ab68025513c3dbd2f7b92a94e0581f5d50f654e7 OP_EQUALVERIFY OP_CHECKSIG"
    },
    {
      "value": 0.08450000,
      "scriptPubKey": "OP_DUP OP_HASH160 7f9b1a7fb68d60c536c2fd8aeaa53a8f3cc025a8 OP_EQUALVERIFY OP_CHECKSIG",
    }
  ]
}

从以上信息咱们能够看出,交易中主要有如下信息:数据结构

数据项 大小(Byte) 数据类型 描述
Version 4 uint32_t 交易版本
tx_in count Varies compactSize unsigned integer 交易输入量
tx_out count Varies compactSize unsigned integer 交易输出量
tx_in Varies CTxIn 交易输入
tx_out Varies CTxOut 交易输出
lock_time 4 uint32_t 交易锁定时间

const uint32_t nLockTime;app

锁定时间定义了能被加到区块链里的最先的交易时间,在大多数交易里,它被设定为0,用来表示便可执行,若是锁定时间不是0,而且小于5亿,就被视为区块高度,意指在这个指定区块高度以前的交易没有被包含在这个区块链里。若是锁定时间设定为大于5亿,则它被看成是一个unix纪元时间戳(从1970年1月1日)以来的秒数,而且在这个指定的时间以前的交易没有被包含这个区块链里ide

交易数据结构由CTransaction类来定义的,位于Src/primitives/transaction.h(264),参数都是常量,都定义成const字段,目的是这些参数在没有更新缓存和哈希值的时候不能被恶意修改。函数

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

 

2、交易概念

比特币交易中的基础构建单元是交易输出。在比特币的世界里既没有帐户,也没有余额,只有分散到区块链里的UTXO[未花费的交易输出]。区块链

例如,你有20比特币的UTXO而且想支付1比特币,那么你的交易必须消耗掉整个20比特币的UTXO而且产生两个输出:一个是支付了1比特币给接收人,另外一个是支付19比特币的找零到你的钱包。ui

交易形式

交易形式主要有三种this

1) 支付并找零

2) 多个输入一个输出

3) 一个输入多个输出

3、COutPoint

用于定位该交易输入的来源(UTXO),起到point的做用

字段尺寸 描述 数据类型 说明
32 hash uint256 交易的哈希
4 n uint32_t 指定tx输出的索引,第一笔输出的索引是0,以此类推
/** 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;
};

4、交易的输入

COutPoint prevout;
    CScript scriptSig;
    uint32_t nSequence;
    CScriptWitness scriptWitness; //! Only serialized through CTransaction
数据项 大小(Byte) 数据类型 描述
previous_output 36 COutPoint 上一个交易的输出
scriptwitness Varies < 10000 CompactSize Unsigned Integer 隔离见证
signature script Varies char[] 解锁脚本
sequence 4 uint32_t 序列号,可用于相对时间锁定

1)Prevout  

是指前一个交易的输出,也就是父交易

其中COutPoint是一个类,也就是前面提到的。

2) scriptSig

解锁脚本,经过密钥能够解锁这个交易输入(UTXO),并使用这个UTXO(J交易输出)

3)nSequence

指定交易何时能够被写到区块链中。其参数设置下面在详细分析

/* 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;

4)scriptWitness

隔离见证。

参考《精通比特币》附录四 隔离见证

在引入“隔离见证”以前,每个交易输入后面都跟着用来对其解锁的见证数据, 见证数据做为输入的一部分被内嵌其中。术语“隔离见证”( segregated witness), 或简称为“segwit”,简单理解就是将某个特定输出的签名分离开,或将某个特定输 入的脚本进行解锁。用最简单的形式来理解就是“分离解锁脚本”(separate scriptSig),或“分离签名”(separate signature)
所以,隔离见证就是比特币的一种结构性调整,旨在将见证数据部分从一笔交易 的 scriptSig(解锁脚本)字段移出至一个伴随交易的单独的见证数据结构。客户 端请求交易数据时能够选择要或不要该部分伴随的见证数据。

5、交易输出

class CTxOut
{
public:
    CAmount nValue;            // 比特币数量
    CScript scriptPubKey;      // 锁定脚本,决定了谁能够花费这笔UTXO
    ...
};
数据项 大小(Byte) 数据类型 描述
value 8 int64_t 交易输出,单位为Satoshis
scriptpubkey Varies cscript 锁定脚本大小

1)比特币数量

CAmount定义在CAmount.h中,64bit,8个字节

2)锁定脚本

锁定脚本,锁定脚本对应输入脚本中的解锁脚本,在锁定脚本中,咱们经过私钥对该交易输出进行锁定,当这笔交易做为其余交易的输入时,须要经过私钥来解锁,即经过前面输入交易中提到的解锁脚原本实现。

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