交易是比特币最重要的一块,比特币系统的其他部分都是为交易服务的。前面的章节中已经学习了各种共识算法以及比特币PoW共识的实现,本文来分析比特币中的交易相关的源码。

1 初识比特币交易

    通过比特币核心客户端的命令getrawtransaction和decoderawtransaction可以检索到比特币区块链上任意一笔交易的详细信息,以下是运行这两个命令后得到的某笔交易的详细信息,该示例摘自《精通比特币》一书:


 
  1. {

  2. "version": 1,

  3. "locktime": 0,

  4. "vin": [

  5. {

  6. "txid":"7957a35fe64f80d234d76d83a2a8f1a0d8149a41d81de548f0a65a8a999f6f18",

  7. "vout": 0,

  8. "scriptSig": "3045022100884d142d86652a3f47ba4746ec719bbfbd040a570b1deccbb6498c75c4ae24cb02204b9f039ff08df09cbe9f6addac960298cad530a863ea8f53982c09db8f6e3813[ALL] 0484ecc0d46f1918b30928fa0e4ed99f16a0fb4fde0735e7ade8416ab9fe423cc5412336376789d172787ec3457eee41c04f4938de5cc17b4a10fa336a8d752adf",

  9. "sequence": 4294967295

  10. }

  11. ],

  12. "vout": [

  13. {

  14. "value": 0.01500000,

  15. "scriptPubKey": "OP_DUP OP_HASH160 ab68025513c3dbd2f7b92a94e0581f5d50f654e7 OP_EQUALVERIFY OP_CHECKSIG"

  16. },

  17. {

  18. "value": 0.08450000,

  19. "scriptPubKey": "OP_DUP OP_HASH160 7f9b1a7fb68d60c536c2fd8aeaa53a8f3cc025a8 OP_EQUALVERIFY OP_CHECKSIG",

  20. }

  21. ]

  22. }

    我们仔细分析一下上面这个输出,来看看一笔比特币的交易到底包含了哪些东西。

    首先是vin字段,这是一个json数组,数组中的每个元素代表一笔交易的输入,在这个例子中的交易,只有一笔输入;

    其次是vout字段,这也是一个json数组,数组中的每个元素代表一笔未花费的输出(UTXO),在这个例子中的交易产生了两笔新的UTXO。

    OK,我们已经看到一笔比特币交易包含了输入和输出两个部分,其中输入表示要花费的比特币来自哪里,而输出则表示输入所指向的比特币去了哪里,换句话说,比特币的交易实际上隐含着价值的转移。以示例中的交易为例,该交易所花费的比特币来自于另外一笔交易7957a35fe64f80d234d76d83a2a8f1a0d8149a41d81de548f0a65a8a999f6f18的索引为0的UTXO,该UTXO的去向在vout中指定,0.015个比特币去了公钥为ab68025513c3dbd2f7b92a94e0581f5d50f654e7对应的钱包,而0.0845个比特币则流向了公钥为7f9b1a7fb68d60c536c2fd8aeaa53a8f3cc025a8对应的钱包。

1.1 交易输出

    交易的输出通常也称为UTXO,即未花费交易输出,从例子中可以看到一笔交易可能产生多个UTXO,这些UTXO在后续交易中会被花费。

    交易输出包含下面一些内容:

    value:该UTXO的比特币数量;

    scriptPubKey:通常称为锁定脚本,决定了谁可以花费这笔UTXO,只有提供了正确的解锁脚本才能解锁并花费该UTXO;

1.2 交易输入

    交易的输入可以理解为一个指向一笔UTXO的指针,表示该交易要花费的UTXO在哪里。交易输出包含如下内容:

    txid:该交易要花费的UTXO所在的交易的hash;

    vout:索引。一笔交易可能产生多个UTXO存放在数组中,该索引即为UTXO在数组中的下标。通过(txid, vout)就能检索到交易中的UTXO;

    scriptSig:解锁脚本,用于解锁(txid, vout)所指向的UTXO。前文提到交易生成的每一笔UTXO都会设定一个锁定脚本即scriptPubKey,解锁脚本scriptSig用来解锁。如果把UTXO比作一个包含了比特币的宝箱,那么scriptPubKey就是给该宝箱上了一把锁,而scriptSig则是钥匙,只有提供真确的钥匙才能解开锁并花费宝箱里的比特币。

1.3 交易链

    比特币的交易实际上是以链的形式串联在一起的,一笔交易与其前驱的交易通过交易输入串联起来。假设张三的钱包里有一笔2比特币的UTXO,然后张三给自己的好友李四转了0.5个比特币,于是生成一笔类似下面这样的交易:

    比特币源码分析--深入理解比特币交易-LMLPHP

    交易T1的输入指向了交易T0的UTXO,该UTXO被分成了两部分,形成两笔新的UTXO:0.5BTC归李四所有,剩下的1.5BTC作为找零又回到了张三的钱包。假设之后李四在咖啡馆将收到的0.5BTC消费掉了0.1BTC,则交易链条如下:

    比特币源码分析--深入理解比特币交易-LMLPHP

    应该注意到这样一个重要事实:每一笔新生成的交易,其交易的输入一定指向另外一笔交易的输出。比特币的交易通过这种链条的形式串联在一起,通过交易的输入就能找到其依赖的另外一笔交易。

2 交易相关的数据结构

    现在我们已经从直观上知道了比特币的交易长什么样子,本节我们看看在代码中,交易是如何表示的。

2.1 交易输入的数据结构

    交易的输入用如下的数据结构来表示:


 
  1. /** An input of a transaction. It contains the location of the previous

  2. * transaction's output that it claims and a signature that matches the

  3. * output's public key.

  4. */

  5. class CTxIn

  6. {

  7. public:

  8. //该输入引用的UTXO

  9. COutPoint prevout;

  10. //解锁脚本,用于解锁输入指向的UTXO

  11. CScript scriptSig;

  12. //相对时间锁

  13. uint32_t nSequence;

  14. //见证脚本

  15. CScriptWitness scriptWitness; //! Only serialized through CTransaction

  16.  
  17. /* Setting nSequence to this value for every input in a transaction

  18. * disables nLockTime. */

  19. static const uint32_t SEQUENCE_FINAL = 0xffffffff;

  20.  
  21. /* Below flags apply in the context of BIP 68*/

  22. /* If this flag set, CTxIn::nSequence is NOT interpreted as a

  23. * relative lock-time. */

  24. static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);

  25.  
  26. /* If CTxIn::nSequence encodes a relative lock-time and this flag

  27. * is set, the relative lock-time has units of 512 seconds,

  28. * otherwise it specifies blocks with a granularity of 1. */

  29. static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);

  30.  
  31. /* If CTxIn::nSequence encodes a relative lock-time, this mask is

  32. * applied to extract that lock-time from the sequence field. */

  33. static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;

  34.  
  35. /* In order to use the same number of bits to encode roughly the

  36. * same wall-clock duration, and because blocks are naturally

  37. * limited to occur every 600s on average, the minimum granularity

  38. * for time-based relative lock-time is fixed at 512 seconds.

  39. * Converting from CTxIn::nSequence to seconds is performed by

  40. * multiplying by 512 = 2^9, or equivalently shifting up by

  41. * 9 bits. */

  42. static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;

  43.  
  44. CTxIn()

  45. {

  46. nSequence = SEQUENCE_FINAL;

  47. }

  48.  
  49. explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);

  50. CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);

  51.  
  52. ADD_SERIALIZE_METHODS;

  53.  
  54. template <typename Stream, typename Operation>

  55. inline void SerializationOp(Stream& s, Operation ser_action) {

  56. READWRITE(prevout);

  57. READWRITE(scriptSig);

  58. READWRITE(nSequence);

  59. }

  60.  
  61. friend bool operator==(const CTxIn& a, const CTxIn& b)

  62. {

  63. return (a.prevout == b.prevout &&

  64. a.scriptSig == b.scriptSig &&

  65. a.nSequence == b.nSequence);

  66. }

  67.  
  68. friend bool operator!=(const CTxIn& a, const CTxIn& b)

  69. {

  70. return !(a == b);

  71. }

  72.  
  73. std::string ToString() const;

  74. };

    代码中的COutPoint是该输入所指向的UTXO,通过COutPoint定位到输入指向的UTXO:


 
  1. /** An outpoint - a combination of a transaction hash and an index n into its vout */

  2. class COutPoint

  3. {

  4. public:

  5. //UTXO所在的交易hash

  6. uint256 hash;

  7. //UTXO的索引

  8. uint32_t n;

  9.  
  10. COutPoint(): n((uint32_t) -1) { }

  11. COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }

  12.  
  13. ADD_SERIALIZE_METHODS;

  14.  
  15. template <typename Stream, typename Operation>

  16. inline void SerializationOp(Stream& s, Operation ser_action) {

  17. READWRITE(hash);

  18. READWRITE(n);

  19. }

  20.  
  21. void SetNull() { hash.SetNull(); n = (uint32_t) -1; }

  22. bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); }

  23.  
  24. friend bool operator<(const COutPoint& a, const COutPoint& b)

  25. {

  26. int cmp = a.hash.Compare(b.hash);

  27. return cmp < 0 || (cmp == 0 && a.n < b.n);

  28. }

  29.  
  30. friend bool operator==(const COutPoint& a, const COutPoint& b)

  31. {

  32. return (a.hash == b.hash && a.n == b.n);

  33. }

  34.  
  35. friend bool operator!=(const COutPoint& a, const COutPoint& b)

  36. {

  37. return !(a == b);

  38. }

  39.  
  40. std::string ToString() const;

  41. };

2.2 交易输出的数据结构

    交易输出的数据结构如下:


 
  1. /** An output of a transaction. It contains the public key that the next input

  2. * must be able to sign with to claim it.

  3. */

  4. class CTxOut

  5. {

  6. public:

  7. CAmount nValue;

  8. CScript scriptPubKey;

  9.  
  10. CTxOut()

  11. {

  12. SetNull();

  13. }

  14.  
  15. CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);

  16.  
  17. ADD_SERIALIZE_METHODS;

  18.  
  19. template <typename Stream, typename Operation>

  20. inline void SerializationOp(Stream& s, Operation ser_action) {

  21. READWRITE(nValue);

  22. READWRITE(scriptPubKey);

  23. }

  24.  
  25. void SetNull()

  26. {

  27. nValue = -1;

  28. scriptPubKey.clear();

  29. }

  30.  
  31. bool IsNull() const

  32. {

  33. return (nValue == -1);

  34. }

  35.  
  36. friend bool operator==(const CTxOut& a, const CTxOut& b)

  37. {

  38. return (a.nValue == b.nValue &&

  39. a.scriptPubKey == b.scriptPubKey);

  40. }

  41.  
  42. friend bool operator!=(const CTxOut& a, const CTxOut& b)

  43. {

  44. return !(a == b);

  45. }

  46.  
  47. std::string ToString() const;

  48. };

    可以看到定义非常简单,只有两个字段:CAmount表示该UTXO的比特币数量,scriptPubKey表示该UTXO的锁定脚本。

2.3 UTXO

    UTXO的概念在比特币中非常重要,专门用一个类Coin来封装:


 
  1. /**

  2. * A UTXO entry.

  3. *

  4. * Serialized format:

  5. * - VARINT((coinbase ? 1 : 0) | (height << 1))

  6. * - the non-spent CTxOut (via CTxOutCompressor)

  7. */

  8. class Coin

  9. {

  10. public:

  11. //! unspent transaction output

  12. //UTXO对应的急交易输出

  13. CTxOut out;

  14.  
  15. //! whether containing transaction was a coinbase

  16. //该UTXO是否是coinbase交易

  17. unsigned int fCoinBase : 1;

  18.  
  19. //! at which height this containing transaction was included in the active block chain

  20. //包含该UTXO的交易所在区块在区块链上的高度

  21. uint32_t nHeight : 31;

  22.  
  23. //! construct a Coin from a CTxOut and height/coinbase information.

  24. Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}

  25. Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}

  26.  
  27. void Clear() {

  28. out.SetNull();

  29. fCoinBase = false;

  30. nHeight = 0;

  31. }

  32.  
  33. //! empty constructor

  34. Coin() : fCoinBase(false), nHeight(0) { }

  35.  
  36. bool IsCoinBase() const {

  37. return fCoinBase;

  38. }

  39.  
  40. template<typename Stream>

  41. void Serialize(Stream &s) const {

  42. assert(!IsSpent());

  43. uint32_t code = nHeight * 2 + fCoinBase;

  44. ::Serialize(s, VARINT(code));

  45. ::Serialize(s, CTxOutCompressor(REF(out)));

  46. }

  47.  
  48. template<typename Stream>

  49. void Unserialize(Stream &s) {

  50. uint32_t code = 0;

  51. ::Unserialize(s, VARINT(code));

  52. nHeight = code >> 1;

  53. fCoinBase = code & 1;

  54. ::Unserialize(s, CTxOutCompressor(out));

  55. }

  56.  
  57. bool IsSpent() const {

  58. return out.IsNull();

  59. }

  60.  
  61. size_t DynamicMemoryUsage() const {

  62. return memusage::DynamicUsage(out.scriptPubKey);

  63. }

  64. };

    比特币钱包实际上就是一个由Coin构成的DB。bitcoind在启动的时候会从DB中加载Coin并存放至内存中。

2.4 交易脚本

    交易输入的解锁脚本scriptSig和交易输出的锁定脚本scriptPubKey都是CScript类型,CScript用来表示交易脚本。交易脚本是比特币中一个非常重要的内容,用比特币提供的脚本语言可以完成非常复杂的功能,本文稍后还会有更详细介绍。


 
  1. /** Serialized script, used inside transaction inputs and outputs */

  2. class CScript : public CScriptBase

  3. {

  4. protected:

  5. CScript& push_int64(int64_t n)

  6. {

  7. if (n == -1 || (n >= 1 && n <= 16))

  8. {

  9. push_back(n + (OP_1 - 1));

  10. }

  11. else if (n == 0)

  12. {

  13. push_back(OP_0);

  14. }

  15. else

  16. {

  17. *this << CScriptNum::serialize(n);

  18. }

  19. return *this;

  20. }

  21. public:

  22. CScript() { }

  23. CScript(const_iterator pbegin, const_iterator pend) : CScriptBase(pbegin, pend) { }

  24. CScript(std::vector<unsigned char>::const_iterator pbegin, std::vector<unsigned char>::const_iterator pend) : CScriptBase(pbegin, pend) { }

  25. CScript(const unsigned char* pbegin, const unsigned char* pend) : CScriptBase(pbegin, pend) { }

  26.  
  27. ADD_SERIALIZE_METHODS;

  28.  
  29. template <typename Stream, typename Operation>

  30. inline void SerializationOp(Stream& s, Operation ser_action) {

  31. READWRITEAS(CScriptBase, *this);

  32. }

  33.  
  34. CScript& operator+=(const CScript& b)

  35. {

  36. reserve(size() + b.size());

  37. insert(end(), b.begin(), b.end());

  38. return *this;

  39. }

  40.  
  41. friend CScript operator+(const CScript& a, const CScript& b)

  42. {

  43. CScript ret = a;

  44. ret += b;

  45. return ret;

  46. }

  47.  
  48. CScript(int64_t b) { operator<<(b); }

  49.  
  50. explicit CScript(opcodetype b) { operator<<(b); }

  51. explicit CScript(const CScriptNum& b) { operator<<(b); }

  52. explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }

  53.  
  54.  
  55. CScript& operator<<(int64_t b) { return push_int64(b); }

  56.  
  57. CScript& operator<<(opcodetype opcode)

  58. {

  59. if (opcode < 0 || opcode > 0xff)

  60. throw std::runtime_error("CScript::operator<<(): invalid opcode");

  61. insert(end(), (unsigned char)opcode);

  62. return *this;

  63. }

  64.  
  65. CScript& operator<<(const CScriptNum& b)

  66. {

  67. *this << b.getvch();

  68. return *this;

  69. }

  70.  
  71. CScript& operator<<(const std::vector<unsigned char>& b)

  72. {

  73. if (b.size() < OP_PUSHDATA1)

  74. {

  75. insert(end(), (unsigned char)b.size());

  76. }

  77. else if (b.size() <= 0xff)

  78. {

  79. insert(end(), OP_PUSHDATA1);

  80. insert(end(), (unsigned char)b.size());

  81. }

  82. else if (b.size() <= 0xffff)

  83. {

  84. insert(end(), OP_PUSHDATA2);

  85. uint8_t _data[2];

  86. WriteLE16(_data, b.size());

  87. insert(end(), _data, _data + sizeof(_data));

  88. }

  89. else

  90. {

  91. insert(end(), OP_PUSHDATA4);

  92. uint8_t _data[4];

  93. WriteLE32(_data, b.size());

  94. insert(end(), _data, _data + sizeof(_data));

  95. }

  96. insert(end(), b.begin(), b.end());

  97. return *this;

  98. }

  99.  
  100. CScript& operator<<(const CScript& b)

  101. {

  102. // I'm not sure if this should push the script or concatenate scripts.

  103. // If there's ever a use for pushing a script onto a script, delete this member fn

  104. assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");

  105. return *this;

  106. }

  107.  
  108.  
  109. bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const

  110. {

  111. return GetScriptOp(pc, end(), opcodeRet, &vchRet);

  112. }

  113.  
  114. bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const

  115. {

  116. return GetScriptOp(pc, end(), opcodeRet, nullptr);

  117. }

  118.  
  119.  
  120. /** Encode/decode small integers: */

  121. static int DecodeOP_N(opcodetype opcode)

  122. {

  123. if (opcode == OP_0)

  124. return 0;

  125. assert(opcode >= OP_1 && opcode <= OP_16);

  126. return (int)opcode - (int)(OP_1 - 1);

  127. }

  128. static opcodetype EncodeOP_N(int n)

  129. {

  130. assert(n >= 0 && n <= 16);

  131. if (n == 0)

  132. return OP_0;

  133. return (opcodetype)(OP_1+n-1);

  134. }

  135.  
  136. /**

  137. * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs

  138. * as 20 sigops. With pay-to-script-hash, that changed:

  139. * CHECKMULTISIGs serialized in scriptSigs are

  140. * counted more accurately, assuming they are of the form

  141. * ... OP_N CHECKMULTISIG ...

  142. */

  143. unsigned int GetSigOpCount(bool fAccurate) const;

  144.  
  145. /**

  146. * Accurately count sigOps, including sigOps in

  147. * pay-to-script-hash transactions:

  148. */

  149. unsigned int GetSigOpCount(const CScript& scriptSig) const;

  150.  
  151. bool IsPayToScriptHash() const;

  152. bool IsPayToWitnessScriptHash() const;

  153. bool IsWitnessProgram(int& version, std::vector<unsigned char>& program) const;

  154.  
  155. /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */

  156. bool IsPushOnly(const_iterator pc) const;

  157. bool IsPushOnly() const;

  158.  
  159. /** Check if the script contains valid OP_CODES */

  160. bool HasValidOps() const;

  161.  
  162. /**

  163. * Returns whether the script is guaranteed to fail at execution,

  164. * regardless of the initial stack. This allows outputs to be pruned

  165. * instantly when entering the UTXO set.

  166. */

  167. bool IsUnspendable() const

  168. {

  169. return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE);

  170. }

  171.  
  172. void clear()

  173. {

  174. // The default prevector::clear() does not release memory

  175. CScriptBase::clear();

  176. shrink_to_fit();

  177. }

  178. };

    CScript继承自ScriptBase:


 
  1. /**

  2. * We use a prevector for the script to reduce the considerable memory overhead

  3. * of vectors in cases where they normally contain a small number of small elements.

  4. * Tests in October 2015 showed use of this reduced dbcache memory usage by 23%

  5. * and made an initial sync 13% faster.

  6. */

  7. typedef prevector<28, unsigned char> CScriptBase;

    CScriptBase实际上一个自定义的vector。CScript重写了<<操作符,可以很方便的向向量中添加数据。

2.5 交易

     比特币的交易和我们已经看到的那样,由一组输入和一组输出组成:


 
  1. /** The basic transaction that is broadcasted on the network and contained in

  2. * blocks. A transaction can contain multiple inputs and outputs.

  3. */

  4. class CTransaction

  5. {

  6. public:

  7. // Default transaction version.

  8. static const int32_t CURRENT_VERSION=2;

  9.  
  10. // Changing the default transaction version requires a two step process: first

  11. // adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date

  12. // bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and

  13. // MAX_STANDARD_VERSION will be equal.

  14. static const int32_t MAX_STANDARD_VERSION=2;

  15.  
  16. // The local variables are made const to prevent unintended modification

  17. // without updating the cached hash value. However, CTransaction is not

  18. // actually immutable; deserialization and assignment are implemented,

  19. // and bypass the constness. This is safe, as they update the entire

  20. // structure, including the hash.

  21. //交易的全部输入

  22. const std::vector<CTxIn> vin;

  23. //交易的全部输出

  24. const std::vector<CTxOut> vout;

  25. //交易版本

  26. const int32_t nVersion;

  27. //交易锁定时间,用来控制在一定的时间之后交易的输出才能被花费

  28. const uint32_t nLockTime;

  29.  
  30. private:

  31. /** Memory only. */

  32. const uint256 hash;

  33.  
  34. uint256 ComputeHash() const;

  35.  
  36. public:

  37. /** Construct a CTransaction that qualifies as IsNull() */

  38. CTransaction();

  39.  
  40. /** Convert a CMutableTransaction into a CTransaction. */

  41. CTransaction(const CMutableTransaction &tx);

  42. CTransaction(CMutableTransaction &&tx);

  43.  
  44. template <typename Stream>

  45. inline void Serialize(Stream& s) const {

  46. SerializeTransaction(*this, s);

  47. }

  48.  
  49. /** This deserializing constructor is provided instead of an Unserialize method.

  50. * Unserialize is not possible, since it would require overwriting const fields. */

  51. template <typename Stream>

  52. CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}

  53.  
  54. bool IsNull() const {

  55. return vin.empty() && vout.empty();

  56. }

  57.  
  58. const uint256& GetHash() const {

  59. return hash;

  60. }

  61.  
  62. // Compute a hash that includes both transaction and witness data

  63. uint256 GetWitnessHash() const;

  64.  
  65. // Return sum of txouts.

  66. CAmount GetValueOut() const;

  67. // GetValueIn() is a method on CCoinsViewCache, because

  68. // inputs must be known to compute value in.

  69.  
  70. /**

  71. * Get the total transaction size in bytes, including witness data.

  72. * "Total Size" defined in BIP141 and BIP144.

  73. * @return Total transaction size in bytes

  74. */

  75. unsigned int GetTotalSize() const;

  76.  
  77. bool IsCoinBase() const

  78. {

  79. return (vin.size() == 1 && vin[0].prevout.IsNull());

  80. }

  81.  
  82. friend bool operator==(const CTransaction& a, const CTransaction& b)

  83. {

  84. return a.hash == b.hash;

  85. }

  86.  
  87. friend bool operator!=(const CTransaction& a, const CTransaction& b)

  88. {

  89. return a.hash != b.hash;

  90. }

  91.  
  92. std::string ToString() const;

  93.  
  94. bool HasWitness() const

  95. {

  96. for (size_t i = 0; i < vin.size(); i++) {

  97. if (!vin[i].scriptWitness.IsNull()) {

  98. return true;

  99. }

  100. }

  101. return false;

  102. }

  103. };

     除了交易输入和输出外,还有交易的版本和交易时间锁nLockTime,交易时间锁用来控制交易的输出只有在一段时间后才能被花费,关于该字段在《精通比特币》第2版有详细说明。

    另外需要注意的是CTransaction中所有的字段全部用const修饰符来修饰,说明一旦创建出CTransaction对象以后,其中的内容就不能在更改了,因此CTransaction是一个不可变的对象,与之相对应的,还有一个交易的可变版本:


 
  1. /** A mutable version of CTransaction. */

  2. struct CMutableTransaction

  3. {

  4. std::vector<CTxIn> vin;

  5. std::vector<CTxOut> vout;

  6. int32_t nVersion;

  7. uint32_t nLockTime;

  8.  
  9. CMutableTransaction();

  10. CMutableTransaction(const CTransaction& tx);

  11.  
  12. template <typename Stream>

  13. inline void Serialize(Stream& s) const {

  14. SerializeTransaction(*this, s);

  15. }

  16.  
  17.  
  18. template <typename Stream>

  19. inline void Unserialize(Stream& s) {

  20. UnserializeTransaction(*this, s);

  21. }

  22.  
  23. template <typename Stream>

  24. CMutableTransaction(deserialize_type, Stream& s) {

  25. Unserialize(s);

  26. }

  27.  
  28. /** Compute the hash of this CMutableTransaction. This is computed on the

  29. * fly, as opposed to GetHash() in CTransaction, which uses a cached result.

  30. */

  31. uint256 GetHash() const;

  32.  
  33. friend bool operator==(const CMutableTransaction& a, const CMutableTransaction& b)

  34. {

  35. return a.GetHash() == b.GetHash();

  36. }

  37.  
  38. bool HasWitness() const

  39. {

  40. for (size_t i = 0; i < vin.size(); i++) {

  41. if (!vin[i].scriptWitness.IsNull()) {

  42. return true;

  43. }

  44. }

  45. return false;

  46. }

  47. };

    CMutableTransaction与CTransaction的字段完全相同,所不同的是字段前面少了const修饰符,因此一个CMutableTransaction对象生成以后,它的字段还可以重新赋值。

3 交易的创建

    了解了和交易相关的数据结构以后,本节我们来分析一下比特币交易是如何创建的。

    通过比特币的JSONAP命令createrawtransaction可以创建一笔交易,这个命令需要传入以下形式的json参数:


 
  1. "1. \"inputs\" (array, required) A json array of json objects\n"

  2. " [\n"

  3. " {\n"

  4. " \"txid\":\"id\", (string, required) The transaction id\n"

  5. " \"vout\":n, (numeric, required) The output number\n"

  6. " \"sequence\":n (numeric, optional) The sequence number\n"

  7. " } \n"

  8. " ,...\n"

  9. " ]\n"

  10. "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n"

  11. " [\n"

  12. " {\n"

  13. " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n"

  14. " },\n"

  15. " {\n"

  16. " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex encoded data\n"

  17. " }\n"

  18. " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"

  19. " accepted as second parameter.\n"

  20. " ]\n"

  21. "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"

  22. "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"

  23. " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n"

    需要在参数中指定每一笔输入和输出。实际中使用比特币钱包时,这些脏活都由钱包帮我们做了。

    我们看看createrawtransaction是如何创建出一笔比特币交易的,该命令的实现位于rawtransaction.cpp中:


 
  1. static UniValue createrawtransaction(const JSONRPCRequest& request)

  2. {

  3. //输入参数不合法,抛出异常,提示参数格式

  4. if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) {

  5. throw std::runtime_error(

  6. // clang-format off

  7. "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable )\n"

  8. "\nCreate a transaction spending the given inputs and creating new outputs.\n"

  9. "Outputs can be addresses or data.\n"

  10. "Returns hex-encoded raw transaction.\n"

  11. "Note that the transaction's inputs are not signed, and\n"

  12. "it is not stored in the wallet or transmitted to the network.\n"

  13.  
  14. "\nArguments:\n"

  15. "1. \"inputs\" (array, required) A json array of json objects\n"

  16. " [\n"

  17. " {\n"

  18. " \"txid\":\"id\", (string, required) The transaction id\n"

  19. " \"vout\":n, (numeric, required) The output number\n"

  20. " \"sequence\":n (numeric, optional) The sequence number\n"

  21. " } \n"

  22. " ,...\n"

  23. " ]\n"

  24. "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n"

  25. " [\n"

  26. " {\n"

  27. " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n"

  28. " },\n"

  29. " {\n"

  30. " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex encoded data\n"

  31. " }\n"

  32. " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"

  33. " accepted as second parameter.\n"

  34. " ]\n"

  35. "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"

  36. "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"

  37. " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n"

  38. "\nResult:\n"

  39. "\"transaction\" (string) hex string of the transaction\n"

  40.  
  41. "\nExamples:\n"

  42. + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")

  43. + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")

  44. + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"")

  45. + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")

  46. // clang-format on

  47. );

  48. }

  49.  
  50. //检查参数

  51. RPCTypeCheck(request.params, {

  52. UniValue::VARR,

  53. UniValueType(), // ARR or OBJ, checked later

  54. UniValue::VNUM,

  55. UniValue::VBOOL

  56. }, true

  57. );

  58. if (request.params[0].isNull() || request.params[1].isNull())

  59. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");

  60.  
  61. UniValue inputs = request.params[0].get_array();

  62. const bool outputs_is_obj = request.params[1].isObject();

  63. UniValue outputs = outputs_is_obj ?

  64. request.params[1].get_obj() :

  65. request.params[1].get_array();

  66.  
  67. //生成交易对象

  68. CMutableTransaction rawTx;

  69.  
  70. //从参数提取交易的锁定时间(如果提供的话)

  71. if (!request.params[2].isNull()) {

  72. int64_t nLockTime = request.params[2].get_int64();

  73. if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())

  74. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");

  75. rawTx.nLockTime = nLockTime;

  76. }

  77.  
  78. bool rbfOptIn = request.params[3].isTrue();

  79.  
  80. //解析参数,生成交易的输入

  81. for (unsigned int idx = 0; idx < inputs.size(); idx++) {

  82. const UniValue& input = inputs[idx];

  83. const UniValue& o = input.get_obj();

  84.  
  85. //该输入指向的交易

  86. uint256 txid = ParseHashO(o, "txid");

  87. //该输入指向的UTXO在其交易中的索引

  88. const UniValue& vout_v = find_value(o, "vout");

  89. if (!vout_v.isNum())

  90. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");

  91. int nOutput = vout_v.get_int();

  92. if (nOutput < 0)

  93. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");

  94.  
  95. uint32_t nSequence;

  96. if (rbfOptIn) {

  97. nSequence = MAX_BIP125_RBF_SEQUENCE;

  98. } else if (rawTx.nLockTime) {

  99. nSequence = std::numeric_limits<uint32_t>::max() - 1;

  100. } else {

  101. nSequence = std::numeric_limits<uint32_t>::max();

  102. }

  103.  
  104. // set the sequence number if passed in the parameters object

  105. const UniValue& sequenceObj = find_value(o, "sequence");

  106. if (sequenceObj.isNum()) {

  107. int64_t seqNr64 = sequenceObj.get_int64();

  108. if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {

  109. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");

  110. } else {

  111. nSequence = (uint32_t)seqNr64;

  112. }

  113. }

  114.  
  115. CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);

  116.  
  117. rawTx.vin.push_back(in);

  118. }

  119.  
  120. std::set<CTxDestination> destinations;

  121. if (!outputs_is_obj) {

  122. // Translate array of key-value pairs into dict

  123. UniValue outputs_dict = UniValue(UniValue::VOBJ);

  124. for (size_t i = 0; i < outputs.size(); ++i) {

  125. const UniValue& output = outputs[i];

  126. if (!output.isObject()) {

  127. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected");

  128. }

  129. if (output.size() != 1) {

  130. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key");

  131. }

  132. outputs_dict.pushKVs(output);

  133. }

  134. outputs = std::move(outputs_dict);

  135. }

  136. //根据参数生成交易的输出

  137. for (const std::string& name_ : outputs.getKeys()) {

  138. if (name_ == "data") {

  139. std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data");

  140.  
  141. CTxOut out(0, CScript() << OP_rawTx.vout.push_back(out)RETURN << data);

  142.  
  143. } else {

  144. //解析出目标地址(比特币最终流向的地方)

  145. CTxDestination destination = DecodeDestination(name_);

  146. if (!IsValidDestination(destination)) {

  147. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + name_);

  148. }

  149.  
  150. if (!destinations.insert(destination).second) {

  151. throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);

  152. }

  153. //根据地址生成交易输出的锁定脚本

  154. CScript scriptPubKey = GetScriptForDestination(destination);

  155.  
  156. CAmount nAmount = AmountFromValue(outputs[name_]);

  157.  
  158. CTxOut out(nAmount, scriptPubKey);

  159. rawTx.vout.push_back(out);

  160. }

  161. }

  162.  
  163. if (!request.params[3].isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) {

  164. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");

  165. }

  166.  
  167. //对交易进行编码并返回

  168. return EncodeHexTx(rawTx);

  169. }

    整体的过程并不复杂:从参数中解析出每一笔输入和输出,并填写到CMutableTransaction对象中,最后将对象编码后返回。但是这里有两个问题值得注意:

    (1) 从代码中没有看到交易输入中的解锁脚本scriptSig;

    (2) 交易输出的锁定脚本如何生成的需要了解;

    关于第一个问题,随后在分析交易签名时解答,下面我们先来看看第二个问题:交易输出的锁定脚本如何生成。生成锁定脚本的代码如下:

CScript scriptPubKey = GetScriptForDestination(destination);

    我们来看看这个函数的实现:


 
  1. CScript GetScriptForDestination(const CTxDestination& dest)

  2. {

  3. CScript script;

  4.  
  5. boost::apply_visitor(CScriptVisitor(&script), dest);

  6. return script;

  7. }

    首先,该方法接受CTxDestination类型的参数,该类型定义如下:


 
  1. /**

  2. * A txout script template with a specific destination. It is either:

  3. * * CNoDestination: no destination set

  4. * * CKeyID: TX_PUBKEYHASH destination (P2PKH)

  5. * * CScriptID: TX_SCRIPTHASH destination (P2SH)

  6. * * WitnessV0ScriptHash: TX_WITNESS_V0_SCRIPTHASH destination (P2WSH)

  7. * * WitnessV0KeyHash: TX_WITNESS_V0_KEYHASH destination (P2WPKH)

  8. * * WitnessUnknown: TX_WITNESS_UNKNOWN destination (P2W???)

  9. * A CTxDestination is the internal data type encoded in a bitcoin address

  10. */

  11. typedef boost::variant<CNoDestination, CKeyID, CScriptID, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown> CTxDestination;

    CTxDestination是boost::variant类型,表示一个特定的比特币地址。boost::variant可以理解为一种增强的union类型,从该类型的定义我们也可以看出目前比特币支持如下几种类型的地址:

    CKeyID:公钥,适用于P2PKH标准交易,锁定脚本中指定比特币接受者的公钥;

    CScriptID:适用于P2SH标准交易的地址;

    WitnessV0ScriptHash:适用于P2WSH交易的地址;

    WitnessV0KeyHash:适用于P2WPKH交易的地址;

    可见,针对不同类型的交易,有不同类型的地址,因此生成交易输出的锁定脚本时也要根据交易类型来具体处理。为了避免出现很多if-else分支,比特币使用boost提供的visitor设计模式的实现来进行处理,提供了CScriptVisitor针对不同类型的地址生成对应的锁定脚本:


 
  1. class CScriptVisitor : public boost::static_visitor<bool>

  2. {

  3. private:

  4. CScript *script;

  5. public:

  6. explicit CScriptVisitor(CScript *scriptin) { script = scriptin; }

  7.  
  8. bool operator()(const CNoDestination &dest) const {

  9. script->clear();

  10. return false;

  11. }

  12.  
  13. //P2PKH标准交易

  14. bool operator()(const CKeyID &keyID) const {

  15. script->clear();

  16. *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;

  17. return true;

  18. }

  19. //P2SH标准交易

  20. bool operator()(const CScriptID &scriptID) const {

  21. script->clear();

  22. *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;

  23. return true;

  24. }

  25. //P2WSH交易

  26. bool operator()(const WitnessV0KeyHash& id) const

  27. {

  28. script->clear();

  29. *script << OP_0 << ToByteVector(id);

  30. return true;

  31. }

  32. //P2WKH交易

  33. bool operator()(const WitnessV0ScriptHash& id) const

  34. {

  35. script->clear();

  36. *script << OP_0 << ToByteVector(id);

  37. return true;

  38. }

  39.  
  40. bool operator()(const WitnessUnknown& id) const

  41. {

  42. script->clear();

  43. *script << CScript::EncodeOP_N(id.version) << std::vector<unsigned char>(id.program, id.program + id.length);

  44. return true;

  45. }

  46. };

    现在,我们已经了解到交易输出的锁定脚本的生成过程了,暂时先不用管脚本是如何执行的,本文稍后还会详细说明交易脚本的运行原理。

4 交易签名

    本节来回答上一节提到的第一个问题:交易输入的解锁脚本scriptSig是如何生成的。我们先来搞清楚一个问题:为什么需要对交易签名,签名的原理又是怎样?

4.1 为什么交易需要签名

    在比特币中对交易进行签名的主要作用是证明某人对某一笔UTXO的所有权。假设张三给李四转账1BTC,交易中就会生成一个1BTC的UTXO,为了确保这笔UTXO随后只能被李四花费,必须要对交易进行数字签名。

4.2 交易签名的原理

    交易签名实际上就是对交易进行数字签名。数字签名之前在加密算法中已经有说明,这里我们再次回顾一下:假设张三在一条不可靠的通信信道上给李四发送了一条消息msg,李四如何确认发送消息的人就是张三而不是别人呢?

    (1) 张三用hash对msg生成摘要D:

    

    (2) 张三用某种签名算法F,加上自己的私钥key对摘要D生成签名S:

     

    (3) 张三将签名S和消息msg一并发送给李四;

    (4) 李四用张三的公钥pubkey从收到的签名S中解出消息摘要D:

    

    (5) 李四对收到的消息msg进行hash得到摘要D1,然后和解出的D对比是否相同,相同就能证明该消息确实来自于张三;

    比特币交易签名的是相同的道理,其中msg就是交易,F是比特币采用的ECDSA椭圆曲线签名算法,我们以最常见的P2PKH交易为例来说明。

    假设张三给李四转账1BTC,于是张三的钱包生成了交易,交易T中有一笔指向李四的UTXO,价值1BTC。张三为了确保这笔UTXO以后只能由李四消费,会在锁定脚本scriptPubKey中设置两个条件:

    (C1) 消费者必须提供自己的公钥,并且对公钥进行hash后的值需要与李四的公钥的hash值相等,假设李四的公钥为P,消费者提供的公钥为pubkey,则必须满足:

    

    张三会将李四的公钥hash即Hash(P)写入到scriptPubKey脚本中;

    (C2) 消费者提供的签名必须正确。

    随后,李四的钱包生成交易T,想花费这笔UTXO,则李四需要提供两样东西:李四的公钥pubkey,和李四对交易T的签名。

    (1) 李四对交易T采用hash生成摘要D:

    比特币源码分析--深入理解比特币交易-LMLPHP10-03 10:25