比特币源码学习0.13-数据结构-交易

比特币交易是比特币系统中最重要的部分。根据比特币系统的设计原理,系统中任何其他的部分都是为了确保比特币交易可以被生成、能在比特币网络中得以传播和通过验证,并最终添加入全球比特币交易总账簿(比特币区块链)。比特币交易的本质是数据结构,这些数据结构中含有比特币交易参与者价值转移的相关信息。比特币区块链是一本全球复式记账总账簿,每个比特币交易都是在比特币区块链上的一个公开记录。
首先来看src/primitives/transaction.h
参考https://blog.csdn.net/pure_lady/article/details/77771392


  • COutPoint
  • CTxIn
  • CTxOut
  • CTransaction


画了类图,大概的来看下这几个类的关系
比特币源码学习0.13-数据结构-交易_第1张图片

COutPoint

字段尺寸 描述 数据类型 说明
32 hash uint256 交易的哈希
4 n uint32_t 指定tx输出的索引,第一笔输出的索引是0,以此类推
/** 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() { SetNull(); }
    COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; }
/*在类的主体中添加ADD_SERIALIZE_METHODS,可以使包装器作为成员,有三种方法,具体内容查看定义*/
    ADD_SERIALIZE_METHODS;  //用来序列化数据结构,方便存储和传输

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        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

字段尺寸 描述 数据类型 说明
36 prevout COutPoint 对前一输出的引用,即需要出示那个账单的txid,也就是说,你花费的任何一笔钱都应该有人转给你过
scriptSig CScript 用于确认交易授权的计算脚本,对这笔交易的签名
4 nSequence uint32_t 发送者定义的交易版本,用于在交易被写入block之前更改交易
scriptWitness CScriptWitness 隔离见证脚本

explicit避免够高函数的参数自动转换为类对象的标识符,explicit关键字只对有一个参数的类构造函数有效,如果类的构造函数参数大于或等于2个时,是不会发生隐式转换的,explicit关键字也就无效了,存在一个例外,当除了第一个参数以外的其他参数都有默认值的时候,explicit关键字依然有效参考https://www.cnblogs.com/ymy124/p/3632634.html

/** 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; //序列号

    /* Setting nSequence to this value for every input in a transaction
     * disables nLockTime. */
    //如果一笔交易中的所有输入的nSequence都被设置为SEQUENCE_FINAL,那么禁用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. */
    //这个标志应用于bip68的上下文中如果设置了这个变量,nSequence设置就与lock-time无关
    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. */
   //如果nSequence与lock-time相关并且设置了这个变量,那么相关的锁定时间就为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. */
    //如果nSequence与lock-time相关,那么这个变量就用来从序列字段中提取锁定时间
    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;

    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, int nType, int nVersion) {
        READWRITE(prevout);
        READWRITE(*(CScriptBase*)(&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

字段尺寸 描述 数据类型 说明
8 nValue CAmount(int64_t) 交易的比特币数量,单位聪(0.00000001)
scriptPubKey CScript 锁定脚本,一般为对方的公钥,有一系列与交易相关的信息和操作组成
/** 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, int nType, int nVersion) {
        READWRITE(nValue);
        READWRITE(*(CScriptBase*)(&scriptPubKey));
    }

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

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

    uint256 GetHash() const;
//获取dust阈值,一笔交易如果交易费大于dust阈值,就会被认为是dust tx
    CAmount GetDustThreshold(const CFeeRate &minRelayTxFee) const
    {
        // "Dust" is defined in terms of CTransaction::minRelayTxFee,
        // which has units satoshis-per-kilobyte.
        // If you'd pay more than 1/3 in fees
        // to spend something, then we consider it dust.
        // A typical spendable non-segwit txout is 34 bytes big, and will
        // need a CTxIn of at least 148 bytes to spend:
        // so dust is a spendable txout less than
        // 546*minRelayTxFee/1000 (in satoshis).
        // A typical spendable segwit txout is 31 bytes big, and will
        // need a CTxIn of at least 67 bytes to spend:
        // so dust is a spendable txout less than
        // 294*minRelayTxFee/1000 (in satoshis).
        /*"Dust"是从CTransaction::minRelayTxFee来定义的,单位是satoshis/千字节,
        *如果在一笔交易中交易费占了1/3以上,那么我们认为该交易是"Dust"交易。
        *一个典型的可花费的非隔离见证的txout是34字节大小,CTxIn至少需要148字节,
        *因此dust交易的可花费支出少于546*minRelayTxFee/1000聪
        *典型的隔离见证中dust交易的可花费支出少于294*minRelayTxFee/1000*/
        if (scriptPubKey.IsUnspendable())//判断脚本格式是否正确
            return 0;

        size_t nSize = GetSerializeSize(SER_DISK, 0);
        int witnessversion = 0;
        std::vector<unsigned char> witnessprogram;
//判断是否支持隔离见证
        if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
            // sum the sizes of the parts of a transaction input
            // with 75% segwit discount applied to the script size.
            nSize += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
        } else {
            nSize += (32 + 4 + 1 + 107 + 4); // the 148 mentioned above
        }

        return 3 * minRelayTxFee.GetFee(nSize);
    }

    bool IsDust(const CFeeRate &minRelayTxFee) const
    {
        return (nValue < GetDustThreshold(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;
};

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

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

CTransaction

字段尺寸 描述 数据类型 说明
4 nVersion int32_t 交易数据格式版本
41+ vin std::vector 交易的输入
9+ vout std::vector 交易的输出
4 nLockTime uint32_t

nLockTime应该理解为锁定交易的期限或者block数目,若该交易的所有输入CTxIn的nSequence字段为uint32_t的最大值(0xffffffff),则忽略该字段的逻辑检查。
当nSequence<0xffffffff,且nLockTime==0,该交易可以立即被打包
当nSequence<0xffffffff,且nLockTime!=0时:

// Threshold for nLockTime: below this value it is interpreted as block number,
// otherwise as UNIX timestamp.
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC

若nLockTime<500000000,则nLockTime代表区块数,该交易只能被打包进高度大于等于nLockTime的区块;
若nLockTime>500000000,则nLockTime代表unix时间戳,该交易只能等到当前时间大于等于nLockTime才能被打包进区块

/** The basic transaction that is broadcasted on the network and contained in
 * blocks.  A transaction can contain multiple inputs and outputs.
 *在网络中被广播并打包进区块的基本交易。一个交易可以包含多个输入和输出
 */
class CTransaction
{
private:
    /** Memory only. */
    const uint256 hash;

public:
    // Default transaction version.默认交易版本
    static const int32_t CURRENT_VERSION=1;

    // 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.
    /*本地变量被定义为常量类型,从而避免无意识的修改了交易而没有更新缓存的hash值,
    *但还是可以通过重新构造一个交易然后赋值给当前交易来进行修改,这样就更新了交易的所有内容*/
    const int32_t nVersion;//版本
    const std::vector vin;//交易输入
    const std::vector vout;//交易输出
    CTxWitness wit; // Not const: can change without invalidating the txid cache 可以更改
    const uint32_t nLockTime;

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

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

    CTransaction& operator=(const CTransaction& tx);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
        SerializeTransaction(*this, s, ser_action, nType, nVersion);
        if (ser_action.ForRead()) {
            UpdateHash();
        }
    }

    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.

    // Compute priority, given priority of inputs and (optionally) tx size 计算优先级
    double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const;

    // Compute modified tx size for priority calculation (optionally given tx size) 为优先级的估算计算修改的交易大小
    unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const;

    bool IsCoinBase() const//判断是否CoinBase交易
    {
        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;

    void UpdateHash() const;
};

还定义了class CTxWitness以及struct CMutableTransactionCMutableTransaction* A mutable version of CTransaction.*,其变量内容都可以修改,最后广播和网络中传输的类型都是CTransaction.

你可能感兴趣的:(比特币源码)