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

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

https://blog.csdn.net/ztemt_sw2/article/details/81101717

    交易是比特币最重要的一块,比特币系统的其他部分都是为交易服务的。前面的章节中已经学习了各种共识算法以及比特币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个比特币,于是生成一笔类似下面这样的交易:

    

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

    

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

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:

    D=Hash(msg)

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

     S=F\left ( key,D \right )

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

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

    D=F\left ( pubkey,S \right )

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

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

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

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

    Hash\left ( pubkey \right )=Hash\left ( P \right )

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

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

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

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

    D=Hash\left ( T \right )

    (2) 李四用ECDSA签名算法,用自己的私钥key对摘要D生成数字签名S:

    S=ECDSA\left ( key,D \right )

    (3) 李四将自己的公钥pubkey和签名S写入到交易T的解锁脚本scriptSig中,然后将交易T广播到网络中;

    (4) 网络中的节点收到交易T,对交易进行验证,确认李四确实可以花费这笔UTXO。首先对收到的交易T的锁定脚本中的公钥pubkey进行hash,看是否和UTXO的锁定脚本中的公钥hash相同(满足条件C1);然后检查签名:首先节点对收到的交易进行hash生成交易的摘要D':

    D'=Hash\left ( T \right )

    然后用公钥pubkey从签名S中解出交易摘要D:

    D=ECDSA\left ( pubkey, S \right )

    如果D'==D则可以证明这笔交易T确实是李四生成,他有权花费这笔UTXO。

4.3 交易签名的生成

    我们再次回顾了比特币交易签名的原理。接下来我们来看看交易输入的解锁脚本(公钥+签名)是如何生成的。第3节介绍了通过createrawtransaction生成交易的过程,但是createrawtransaction生成的交易的输入中还缺少解锁脚本scriptSig,解锁脚本需要通过另一个jsonapi:signrawtransaction,这条命令需要的参数如下:


 
  1. "1. \"hexstring\" (string, required) The transaction hex string\n"

  2. "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"

  3. " [ (json array of json objects, or 'null' if none provided)\n"

  4. " {\n"

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

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

  7. " \"scriptPubKey\": \"hex\", (string, required) script key\n"

  8. " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"

  9. " \"amount\": value (numeric, required) The amount spent\n"

  10. " }\n"

  11. " ,...\n"

  12. " ]\n"

  13. "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"

  14. " [ (json array of strings, or 'null' if none provided)\n"

  15. " \"privatekey\" (string) private key in base58-encoding\n"

  16. " ,...\n"

  17. " ]\n"

  18. "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"

  19. " \"ALL\"\n"

  20. " \"NONE\"\n"

  21. " \"SINGLE\"\n"

  22. " \"ALL|ANYONECANPAY\"\n"

  23. " \"NONE|ANYONECANPAY\"\n"

  24. " \"SINGLE|ANYONECANPAY\"\n"

    prevtxs提供该交易的输入所指向的UTXO,privkeys则是解锁这些UTXO需要的私钥,sighashtype则指定了只签名交易中的一部分交易还是对全部交易输入都进行签名。

    签名的过程如下:


 
  1. UniValue signrawtransaction(const JSONRPCRequest& request) {

  2. #ifdef ENABLE_WALLET

  3. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);

  4. #endif

  5.  
  6. //检查参数格式,如果格式不正确,抛出异常提示正确用法

  7. if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)

  8. throw std::runtime_error(

  9. "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"

  10. "\nDEPRECATED. Sign inputs for raw transaction (serialized, hex-encoded).\n"

  11. "The second optional argument (may be null) is an array of previous transaction outputs that\n"

  12. "this transaction depends on but may not yet be in the block chain.\n"

  13. "The third optional argument (may be null) is an array of base58-encoded private\n"

  14. "keys that, if given, will be the only keys used to sign the transaction.\n"

  15. #ifdef ENABLE_WALLET

  16. + HelpRequiringPassphrase(pwallet) + "\n"

  17. #endif

  18. "\nArguments:\n"

  19. "1. \"hexstring\" (string, required) The transaction hex string\n"

  20. "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"

  21. " [ (json array of json objects, or 'null' if none provided)\n"

  22. " {\n"

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

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

  25. " \"scriptPubKey\": \"hex\", (string, required) script key\n"

  26. " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"

  27. " \"amount\": value (numeric, required) The amount spent\n"

  28. " }\n"

  29. " ,...\n"

  30. " ]\n"

  31. "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"

  32. " [ (json array of strings, or 'null' if none provided)\n"

  33. " \"privatekey\" (string) private key in base58-encoding\n"

  34. " ,...\n"

  35. " ]\n"

  36. "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"

  37. " \"ALL\"\n"

  38. " \"NONE\"\n"

  39. " \"SINGLE\"\n"

  40. " \"ALL|ANYONECANPAY\"\n"

  41. " \"NONE|ANYONECANPAY\"\n"

  42. " \"SINGLE|ANYONECANPAY\"\n"

  43.  
  44. "\nResult:\n"

  45. "{\n"

  46. " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"

  47. " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"

  48. " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"

  49. " {\n"

  50. " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"

  51. " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"

  52. " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"

  53. " \"sequence\" : n, (numeric) Script sequence number\n"

  54. " \"error\" : \"text\" (string) Verification or signing error related to the input\n"

  55. " }\n"

  56. " ,...\n"

  57. " ]\n"

  58. "}\n"

  59.  
  60. "\nExamples:\n"

  61. + HelpExampleCli("signrawtransaction", "\"myhex\"")

  62. + HelpExampleRpc("signrawtransaction", "\"myhex\"")

  63. );

  64.  
  65. if (!IsDeprecatedRPCEnabled("signrawtransaction")) {

  66. throw JSONRPCError(RPC_METHOD_DEPRECATED,

  67. "signrawtransaction is deprecated and will be fully removed in v0.18. "

  68. "To use signrawtransaction in v0.17, restart bitcoind with -deprecatedrpc=signrawtransaction.\n"

  69. "Projects should transition to using signrawtransactionwithkey and signrawtransactionwithwallet before upgrading to v0.18");

  70. }

  71.  
  72. //检查参数

  73. RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR},

  74. true);

  75.  
  76. // Make a JSONRPCRequest to pass on to the right signrawtransaction* command

  77. JSONRPCRequest new_request;

  78. new_request.id = request.id;

  79. new_request.params.setArray();

  80.  
  81. // For signing with private keys

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

  83. //通过参数提供的私钥进行签名

  84. new_request.params.push_back(request.params[0]);

  85. // Note: the prevtxs and privkeys are reversed for signrawtransactionwithkey

  86. new_request.params.push_back(request.params[2]);

  87. new_request.params.push_back(request.params[1]);

  88. new_request.params.push_back(request.params[3]);

  89. return signrawtransactionwithkey(new_request);

  90. } else {

  91. #ifdef ENABLE_WALLET

  92. // Otherwise sign with the wallet which does not take a privkeys parameter

  93. //通过钱包进行签名

  94. new_request.params.push_back(request.params[0]);

  95. new_request.params.push_back(request.params[1]);

  96. new_request.params.push_back(request.params[3]);

  97. return signrawtransactionwithwallet(new_request);

  98. #else

  99. // If we have made it this far, then wallet is disabled and no private keys were given, so fail here.

  100. throw JSONRPCError(RPC_INVALID_PARAMETER, "No private keys available.");

  101. #endif

  102. }

    我们这里只分析通过提供的私钥进行签名的过程,这个是通过signrawtransactionwithkey方法实现:


 
  1.  
  2. static UniValue signrawtransactionwithkey(const JSONRPCRequest& request)

  3. {

  4. //参数检查

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

  6. throw std::runtime_error(

  7. "signrawtransactionwithkey \"hexstring\" [\"privatekey1\",...] ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] sighashtype )\n"

  8. "\nSign inputs for raw transaction (serialized, hex-encoded).\n"

  9. "The second argument is an array of base58-encoded private\n"

  10. "keys that will be the only keys used to sign the transaction.\n"

  11. "The third optional argument (may be null) is an array of previous transaction outputs that\n"

  12. "this transaction depends on but may not yet be in the block chain.\n"

  13.  
  14. "\nArguments:\n"

  15. "1. \"hexstring\" (string, required) The transaction hex string\n"

  16. "2. \"privkeys\" (string, required) A json array of base58-encoded private keys for signing\n"

  17. " [ (json array of strings)\n"

  18. " \"privatekey\" (string) private key in base58-encoding\n"

  19. " ,...\n"

  20. " ]\n"

  21. "3. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"

  22. " [ (json array of json objects, or 'null' if none provided)\n"

  23. " {\n"

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

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

  26. " \"scriptPubKey\": \"hex\", (string, required) script key\n"

  27. " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"

  28. " \"amount\": value (numeric, required) The amount spent\n"

  29. " }\n"

  30. " ,...\n"

  31. " ]\n"

  32. "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"

  33. " \"ALL\"\n"

  34. " \"NONE\"\n"

  35. " \"SINGLE\"\n"

  36. " \"ALL|ANYONECANPAY\"\n"

  37. " \"NONE|ANYONECANPAY\"\n"

  38. " \"SINGLE|ANYONECANPAY\"\n"

  39.  
  40. "\nResult:\n"

  41. "{\n"

  42. " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"

  43. " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"

  44. " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"

  45. " {\n"

  46. " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"

  47. " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"

  48. " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"

  49. " \"sequence\" : n, (numeric) Script sequence number\n"

  50. " \"error\" : \"text\" (string) Verification or signing error related to the input\n"

  51. " }\n"

  52. " ,...\n"

  53. " ]\n"

  54. "}\n"

  55.  
  56. "\nExamples:\n"

  57. + HelpExampleCli("signrawtransactionwithkey", "\"myhex\"")

  58. + HelpExampleRpc("signrawtransactionwithkey", "\"myhex\"")

  59. );

  60.  
  61. RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);

  62.  
  63. //解码出原始交易

  64. CMutableTransaction mtx;

  65. if (!DecodeHexTx(mtx, request.params[0].get_str(), true)) {

  66. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");

  67. }

  68.  
  69. //从提供的私钥得到对应的公钥,并且将私钥-公钥对保存在keystore中

  70. CBasicKeyStore keystore;

  71. const UniValue& keys = request.params[1].get_array();

  72. for (unsigned int idx = 0; idx < keys.size(); ++idx) {

  73. UniValue k = keys[idx];

  74. CKey key = DecodeSecret(k.get_str());

  75. if (!key.IsValid()) {

  76. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");

  77. }

  78. keystore.AddKey(key);

  79. }

  80.  
  81. //对交易输入进行签名,生成解锁脚本scriptSig

  82. return SignTransaction(mtx, request.params[2], &keystore, true, request.params[3]);

  83. }

    这个函数中从提供的私钥得到对应的公钥,然后将私钥-公钥的配对存放在keystore中,方便后续进行检索。真正的交易签名是在SignTransaction中:


 
  1. UniValue SignTransaction(CMutableTransaction& mtx, const UniValue& prevTxsUnival, CBasicKeyStore *keystore, bool is_temp_keystore, const UniValue& hashType)

  2. {

  3. // Fetch previous transactions (inputs):

  4. CCoinsView viewDummy;

  5. CCoinsViewCache view(&viewDummy);

  6. {

  7. LOCK2(cs_main, mempool.cs);

  8. CCoinsViewCache &viewChain = *pcoinsTip;

  9. CCoinsViewMemPool viewMempool(&viewChain, mempool);

  10. view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view

  11.  
  12. for (const CTxIn& txin : mtx.vin) {

  13. view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.

  14. }

  15.  
  16. view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long

  17. }

  18.  
  19. // Add previous txouts given in the RPC call:

  20. //查找交易输入指向的UTXO并加入到内存中

  21. if (!prevTxsUnival.isNull()) {

  22. UniValue prevTxs = prevTxsUnival.get_array();

  23. for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) {

  24. const UniValue& p = prevTxs[idx];

  25. if (!p.isObject()) {

  26. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");

  27. }

  28.  
  29. UniValue prevOut = p.get_obj();

  30.  
  31. //参数检查

  32. RPCTypeCheckObj(prevOut,

  33. {

  34. {"txid", UniValueType(UniValue::VSTR)},

  35. {"vout", UniValueType(UniValue::VNUM)},

  36. {"scriptPubKey", UniValueType(UniValue::VSTR)},

  37. });

  38. //从参数中得到txid和vout,生成COutPoint指向交易输入引用的UTXO

  39. uint256 txid = ParseHashO(prevOut, "txid");

  40.  
  41. int nOut = find_value(prevOut, "vout").get_int();

  42. if (nOut < 0) {

  43. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");

  44. }

  45.  
  46. COutPoint out(txid, nOut);

  47.  
  48. //解析参数,得到交易输入指向的UTXO的锁定脚本

  49. std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));

  50. CScript scriptPubKey(pkData.begin(), pkData.end());

  51.  
  52. //查找交易输入指向的UTXO

  53. {

  54. const Coin& coin = view.AccessCoin(out);

  55. if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {

  56. std::string err("Previous output scriptPubKey mismatch:\n");

  57. err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+

  58. ScriptToAsmStr(scriptPubKey);

  59. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);

  60. }

  61. Coin newcoin;

  62. newcoin.out.scriptPubKey = scriptPubKey;

  63. newcoin.out.nValue = 0;

  64. if (prevOut.exists("amount")) {

  65. newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));

  66. }

  67. newcoin.nHeight = 1;

  68. view.AddCoin(out, std::move(newcoin), true);

  69. }

  70.  
  71. // if redeemScript given and not using the local wallet (private keys

  72. // given), add redeemScript to the keystore so it can be signed:

  73. //如果是P2SH或者P2WSH交易,如果指定了赎回脚本也需要加入到keystore中

  74. if (is_temp_keystore && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {

  75. RPCTypeCheckObj(prevOut,

  76. {

  77. {"redeemScript", UniValueType(UniValue::VSTR)},

  78. });

  79. UniValue v = find_value(prevOut, "redeemScript");

  80. if (!v.isNull()) {

  81. std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));

  82. CScript redeemScript(rsData.begin(), rsData.end());

  83. keystore->AddCScript(redeemScript);

  84. // Automatically also add the P2WSH wrapped version of the script (to deal with P2SH-P2WSH).

  85. keystore->AddCScript(GetScriptForWitness(redeemScript));

  86. }

  87. }

  88. }

  89. }

  90.  
  91. //解析hashtype

  92. int nHashType = SIGHASH_ALL;

  93. if (!hashType.isNull()) {

  94. static std::map<std::string, int> mapSigHashValues = {

  95. {std::string("ALL"), int(SIGHASH_ALL)},

  96. {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},

  97. {std::string("NONE"), int(SIGHASH_NONE)},

  98. {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},

  99. {std::string("SINGLE"), int(SIGHASH_SINGLE)},

  100. {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},

  101. };

  102. std::string strHashType = hashType.get_str();

  103. if (mapSigHashValues.count(strHashType)) {

  104. nHashType = mapSigHashValues[strHashType];

  105. } else {

  106. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");

  107. }

  108. }

  109.  
  110. bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);

  111.  
  112. // Script verification errors

  113. UniValue vErrors(UniValue::VARR);

  114.  
  115. // Use CTransaction for the constant parts of the

  116. // transaction to avoid rehashing.

  117. const CTransaction txConst(mtx);

  118. // Sign what we can:

  119. //对交易输入生成签名

  120. for (unsigned int i = 0; i < mtx.vin.size(); i++) {

  121. //找到交易输入指向的UTXO

  122. CTxIn& txin = mtx.vin[i];

  123. const Coin& coin = view.AccessCoin(txin.prevout);

  124. if (coin.IsSpent()) {

  125. TxInErrorToJSON(txin, vErrors, "Input not found or already spent");

  126. continue;

  127. }

  128. //拿到输入指向的UTXO的锁定脚本

  129. const CScript& prevPubKey = coin.out.scriptPubKey;

  130. const CAmount& amount = coin.out.nValue;

  131.  
  132. SignatureData sigdata;

  133. // Only sign SIGHASH_SINGLE if there's a corresponding output:

  134.  
  135. //生成交易的解锁脚本,存放在sigdata中

  136. if (!fHashSingle || (i < mtx.vout.size())) {

  137. ProduceSignature(*keystore, MutableTransactionSignatureCreator(&mtx, i, amount, nHashType), prevPubKey, sigdata);

  138. }

  139. sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(mtx, i));

  140.  
  141. //将生成的解锁脚本填充到交易输入中

  142. UpdateTransaction(mtx, i, sigdata);

  143.  
  144. ScriptError serror = SCRIPT_ERR_OK;

  145. //脚本校验

  146. if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {

  147. if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {

  148. // Unable to sign input and verification failed (possible attempt to partially sign).

  149. TxInErrorToJSON(txin, vErrors, "Unable to sign input, invalid stack size (possibly missing key)");

  150. } else {

  151. TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));

  152. }

  153. }

  154. }

  155. bool fComplete = vErrors.empty();

  156.  
  157. UniValue result(UniValue::VOBJ);

  158. result.pushKV("hex", EncodeHexTx(mtx));

  159. result.pushKV("complete", fComplete);

  160. if (!vErrors.empty()) {

  161. result.pushKV("errors", vErrors);

  162. }

  163.  
  164. return result;

  165. }

    如果抛开细节问题,这个函数主要做的其实就是两件事:为交易输入生成解锁脚本以及校验脚本。

4.3.1 为交易输入生成解锁脚本

    给交易输入生成解锁脚本是在ProduceSignature方法中进行:


 
  1. bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)

  2. {

  3. std::vector<valtype> result;

  4. txnouttype whichType;

  5. //进行签名

  6. bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE);

  7. bool P2SH = false;

  8. CScript subscript;

  9. sigdata.scriptWitness.stack.clear();

  10.  
  11. //P2SH交易,需要对子脚本进行签名

  12. if (solved && whichType == TX_SCRIPTHASH)

  13. {

  14. // Solver returns the subscript that needs to be evaluated;

  15. // the final scriptSig is the signatures from that

  16. // and then the serialized subscript:

  17. subscript = CScript(result[0].begin(), result[0].end());

  18. solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE) && whichType != TX_SCRIPTHASH;

  19. P2SH = true;

  20. }

  21.  
  22. //P2WKH交易,需要对见证脚本签名

  23. if (solved && whichType == TX_WITNESS_V0_KEYHASH)

  24. {

  25. CScript witnessscript;

  26. witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;

  27. txnouttype subType;

  28. solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0);

  29. sigdata.scriptWitness.stack = result;

  30. result.clear();

  31. }

  32. //P2WSH交易

  33. else if (solved && whichType == TX_WITNESS_V0_SCRIPTHASH)

  34. {

  35. CScript witnessscript(result[0].begin(), result[0].end());

  36. txnouttype subType;

  37. solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0) && subType != TX_SCRIPTHASH && subType != TX_WITNESS_V0_SCRIPTHASH && subType != TX_WITNESS_V0_KEYHASH;

  38. result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end()));

  39. sigdata.scriptWitness.stack = result;

  40. result.clear();

  41. }

  42.  
  43. if (P2SH) {

  44. result.push_back(std::vector<unsigned char>(subscript.begin(), subscript.end()));

  45. }

  46.  
  47. //将生成的解锁脚本写入到sigdata中

  48. sigdata.scriptSig = PushAll(result);

  49.  
  50. // 校验脚本

  51. return solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());

  52. }

    先来看看函数的参数:provider:keystore,存放了公钥-私钥配对,之前的代码中已经提到过;

    creator:BaseSignatureCreator类型的实例,用于最后对交易生成签名;

    fromPubKey:CScript类型,交易输入引用的UTXO的锁定脚本;

    sigData:SignatureData类型,是输出参数,用于存放生成的解锁脚本;

    像洋葱一样一层又一层后,最终对交易输入完成签名的是SignStep这个方法:


 
  1. /**

  2. * Sign scriptPubKey using signature made with creator.

  3. * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),

  4. * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.

  5. * Returns false if scriptPubKey could not be completely satisfied.

  6. */

  7. static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,

  8. std::vector<valtype>& ret, txnouttype& whichTypeRet, SigVersion sigversion)

  9. {

  10. CScript scriptRet;

  11. uint160 h160;

  12. ret.clear();

  13.  
  14. std::vector<valtype> vSolutions;

  15. //解析交易输入引用的UTXO的锁定脚本,锁定脚本的类型存在输出参数whichTypeRet中,锁定脚本的数据存放在向量vSolutions中

  16. if (!Solver(scriptPubKey, whichTypeRet, vSolutions))

  17. return false;

  18.  
  19. CKeyID keyID;

  20. //根据不同的锁定脚本的类型执行签名

  21. switch (whichTypeRet)

  22. {

  23. case TX_NONSTANDARD:

  24. case TX_NULL_DATA:

  25. case TX_WITNESS_UNKNOWN:

  26. return false;

  27. case TX_PUBKEY: //锁定脚本是P2PK类型

  28. keyID = CPubKey(vSolutions[0]).GetID();

  29. return Sign1(provider, keyID, creator, scriptPubKey, ret, sigversion);

  30. case TX_PUBKEYHASH: //锁定脚本是P2PKH类型

  31. keyID = CKeyID(uint160(vSolutions[0]));

  32. if (!Sign1(provider, keyID, creator, scriptPubKey, ret, sigversion))

  33. return false;

  34. else

  35. {

  36. CPubKey vch;

  37. provider.GetPubKey(keyID, vch);

  38. ret.push_back(ToByteVector(vch));

  39. }

  40. return true;

  41. case TX_SCRIPTHASH: //锁定脚本是P2SH类型

  42. if (provider.GetCScript(uint160(vSolutions[0]), scriptRet)) {

  43. ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));

  44. return true;

  45. }

  46. return false;

  47.  
  48. case TX_MULTISIG: //锁定脚本是MultiSig(多重签名)

  49. ret.push_back(valtype()); // workaround CHECKMULTISIG bug

  50. return (SignN(provider, vSolutions, creator, scriptPubKey, ret, sigversion));

  51.  
  52. case TX_WITNESS_V0_KEYHASH: //锁定脚本是P2WKH类型

  53. ret.push_back(vSolutions[0]);

  54. return true;

  55.  
  56. case TX_WITNESS_V0_SCRIPTHASH: //锁定脚本是P2WSH类型

  57. CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160.begin());

  58. if (provider.GetCScript(h160, scriptRet)) {

  59. ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));

  60. return true;

  61. }

  62. return false;

  63.  
  64. default:

  65. return false;

  66. }

  67. }

  68.  

    首先是解析交易输入引用的UTXO的锁定脚本,然后根据不同的锁定脚本类型进行签名。此处我们以最常见的P2PKH交易来作为例子,其他的交易类型原理差不多。

    (1) 解析锁定脚本

    先来过下源码,看看锁定脚本是如何解析的:


 
  1. bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)

  2. {

  3. // Templates

  4. //P2PK/P2PKH/MULTISIG交易的锁定脚本模板

  5. static std::multimap<txnouttype, CScript> mTemplates;

  6. if (mTemplates.empty())

  7. {

  8. // Standard tx, sender provides pubkey, receiver adds signature

  9. mTemplates.insert(std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));

  10.  
  11. // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey

  12. mTemplates.insert(std::make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));

  13.  
  14. // Sender provides N pubkeys, receivers provides M signatures

  15. mTemplates.insert(std::make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));

  16. }

  17.  
  18. vSolutionsRet.clear();

  19.  
  20. // Shortcut for pay-to-script-hash, which are more constrained than the other types:

  21. // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL

  22. //锁定脚本是P2SH类型,这种类型的锁定脚本的格式:OP_HASH160 20 [20 byte hash] OP_EQUAL,脚本中2-22为20字节的数据,放到vSolutionsRet中

  23. if (scriptPubKey.IsPayToScriptHash())

  24. {

  25. typeRet = TX_SCRIPTHASH;

  26. std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);

  27. vSolutionsRet.push_back(hashBytes);

  28. return true;

  29. }

  30.  
  31. //P2WKH/P2WSH类型的处理

  32. int witnessversion;

  33. std::vector<unsigned char> witnessprogram;

  34. if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {

  35. if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_KEYHASH_SIZE) {

  36. typeRet = TX_WITNESS_V0_KEYHASH;

  37. vSolutionsRet.push_back(witnessprogram);

  38. return true;

  39. }

  40. if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) {

  41. typeRet = TX_WITNESS_V0_SCRIPTHASH;

  42. vSolutionsRet.push_back(witnessprogram);

  43. return true;

  44. }

  45. if (witnessversion != 0) {

  46. typeRet = TX_WITNESS_UNKNOWN;

  47. vSolutionsRet.push_back(std::vector<unsigned char>{(unsigned char)witnessversion});

  48. vSolutionsRet.push_back(std::move(witnessprogram));

  49. return true;

  50. }

  51. return false;

  52. }

  53.  
  54. // Provably prunable, data-carrying output

  55. //

  56. // So long as script passes the IsUnspendable() test and all but the first

  57. // byte passes the IsPushOnly() test we don't care what exactly is in the

  58. // script.

  59. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {

  60. typeRet = TX_NULL_DATA;

  61. return true;

  62. }

  63.  
  64. // Scan templates

  65. //P2PKH/P2PK/MULTISIG类型,扫描模板进行解析

  66. const CScript& script1 = scriptPubKey;

  67. for (const std::pair<txnouttype, CScript>& tplate : mTemplates)

  68. {

  69. const CScript& script2 = tplate.second;

  70. vSolutionsRet.clear();

  71.  
  72. opcodetype opcode1, opcode2;

  73. std::vector<unsigned char> vch1, vch2;

  74.  
  75. // Compare

  76. //pc1指向UTXO的锁定脚本,pc2指向脚本模板

  77. CScript::const_iterator pc1 = script1.begin();

  78. CScript::const_iterator pc2 = script2.begin();

  79. while (true)

  80. {

  81. //两个指针同时到了结尾,则找到和模板匹配的交易类型,返回

  82. if (pc1 == script1.end() && pc2 == script2.end())

  83. {

  84. // Found a match

  85. typeRet = tplate.first;

  86. if (typeRet == TX_MULTISIG)

  87. {

  88. // Additional checks for TX_MULTISIG:

  89. unsigned char m = vSolutionsRet.front()[0];

  90. unsigned char n = vSolutionsRet.back()[0];

  91. if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)

  92. return false;

  93. }

  94. return true;

  95. }

  96. //得到操作符和操作数

  97. if (!script1.GetOp(pc1, opcode1, vch1))

  98. break;

  99. if (!script2.GetOp(pc2, opcode2, vch2))

  100. break;

  101.  
  102. // Template matching opcodes:

  103. //几种操作符的处理

  104. if (opcode2 == OP_PUBKEYS)

  105. {

  106. while (CPubKey::ValidSize(vch1))

  107. {

  108. vSolutionsRet.push_back(vch1);

  109. if (!script1.GetOp(pc1, opcode1, vch1))

  110. break;

  111. }

  112. if (!script2.GetOp(pc2, opcode2, vch2))

  113. break;

  114. // Normal situation is to fall through

  115. // to other if/else statements

  116. }

  117.  
  118. if (opcode2 == OP_PUBKEY)

  119. {

  120. if (!CPubKey::ValidSize(vch1))

  121. break;

  122. vSolutionsRet.push_back(vch1);

  123. }

  124. else if (opcode2 == OP_PUBKEYHASH)

  125. {

  126. if (vch1.size() != sizeof(uint160))

  127. break;

  128. vSolutionsRet.push_back(vch1);

  129. }

  130. else if (opcode2 == OP_SMALLINTEGER)

  131. { // Single-byte small integer pushed onto vSolutions

  132. if (opcode1 == OP_0 ||

  133. (opcode1 >= OP_1 && opcode1 <= OP_16))

  134. {

  135. char n = (char)CScript::DecodeOP_N(opcode1);

  136. vSolutionsRet.push_back(valtype(1, n));

  137. }

  138. else

  139. break;

  140. }

  141. else if (opcode1 != opcode2 || vch1 != vch2)

  142. {

  143. // Others must match exactly

  144. break;

  145. }

  146. }

  147. }

  148.  
  149. vSolutionsRet.clear();

  150. typeRet = TX_NONSTANDARD;

  151. return false;

  152. }

    上面的代码针对不同的类型有不同的处理,对于P2PKH/P2PK/MULTISIG,是通过模板来进行匹配处理的。看代码可能不能一下子理解这里的逻辑,画个图来说明一下会非常清楚。以P2PKH为例:

    首先锁定脚本的模板如下:

    然后看看UTXO的锁定脚本是什么样的,回顾之前创建交易的代码中为交易输出生成锁定脚本的代码(CScriptVisitor),对于P2PKH类型:


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

  2. script->clear();

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

  4. return true;

  5. }

    这里要注意下CScript重载的<<操作符的以vector为参数的实现,其中keyID是160位无符号整数,占20字节。根据CScript重载的<<操作符的实现,最终生成的锁定脚本的长下面这样:

    

   20代表脚本中随后的一个元素是20字节的公钥。

    根据代码,解析的时候将从模板脚本和锁定脚本的开始处逐一解析每个操作符,首先OP_DUP和OP_HASH什么都不做,指针向前移动即可,进行到下面的状态的时候,需要留神了:

   模板的指针好处理,直接前移,但是锁定脚本的处理就不一样了,看看解析操作符和参数的代码,已经根据例子对代码做了注释:


 
  1. bool GetScriptOp(CScriptBase::const_iterator& pc, CScriptBase::const_iterator end, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet)

  2. {

  3. opcodeRet = OP_INVALIDOPCODE;

  4. if (pvchRet)

  5. pvchRet->clear();

  6. if (pc >= end)

  7. return false;

  8.  
  9. // Read instruction

  10. if (end - pc < 1)

  11. return false;

  12. //在我们的例子中opcode将会是20,然后指针前移到下一个元素(20字节的公钥)

  13. unsigned int opcode = *pc++;

  14.  
  15. // Immediate operand

  16. //OP_PUSHDATA4的值为0x4e,例子中opcode为20,所以进入分支

  17. if (opcode <= OP_PUSHDATA4)

  18. {

  19. unsigned int nSize = 0;

  20. //opcode为20,OP_PUSHDATA1为0x4c,进入此分支

  21. if (opcode < OP_PUSHDATA1)

  22. {

  23. nSize = opcode;

  24. }

  25. else if (opcode == OP_PUSHDATA1)

  26. {

  27. if (end - pc < 1)

  28. return false;

  29. nSize = *pc++;

  30. }

  31. else if (opcode == OP_PUSHDATA2)

  32. {

  33. if (end - pc < 2)

  34. return false;

  35. nSize = ReadLE16(&pc[0]);

  36. pc += 2;

  37. }

  38. else if (opcode == OP_PUSHDATA4)

  39. {

  40. if (end - pc < 4)

  41. return false;

  42. nSize = ReadLE32(&pc[0]);

  43. pc += 4;

  44. }

  45. if (end - pc < 0 || (unsigned int)(end - pc) < nSize)

  46. return false;

  47. //将随后20字节的公钥填充的输出参数中

  48. if (pvchRet)

  49. pvchRet->assign(pc, pc + nSize);

  50. //指针移动20字节

  51. pc += nSize;

  52. }

  53.  
  54. opcodeRet = static_cast<opcodetype>(opcode);

  55. return true;

  56. }

    最终,20字节的公钥值被提取并保存再来,执行完操作符解析后的状态如下:

   (2) 签名

    解析完UTXO的锁定脚本后,接下来就要开始签名了,还是以上面的例子来分析,SignStep函数在调用Solver解析完锁定脚本,得到锁定脚本的类型和其中的参数,然后根据不同的锁定脚本类型进行处理,对于P2PKH类型,处理如下:


 
  1. case TX_PUBKEYHASH:

  2. keyID = CKeyID(uint160(vSolutions[0]));

  3. if (!Sign1(provider, keyID, creator, scriptPubKey, ret, sigversion))

  4. return false;

  5. else

  6. {

  7. CPubKey vch;

  8. provider.GetPubKey(keyID, vch);

  9. ret.push_back(ToByteVector(vch));

  10. }

  11. return true;

    首先拿到Solver函数解析出的20字节的公钥,然后调用Sign1函数进行签名:


 
  1. static bool Sign1(const SigningProvider& provider, const CKeyID& address, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion)

  2. {

  3. std::vector<unsigned char> vchSig;

  4. if (!creator.CreateSig(provider, vchSig, address, scriptCode, sigversion))

  5. return false;

  6. ret.push_back(vchSig);

  7. return true;

  8. }

    很简单,通过传入的参数BaseSignatureCreator::CreateSig进行签名,将生成的签名保存在输出参数ret中。这里参数中传入的BaseSignatureCreator是MutableTransactionSignatureCreator类型,回忆下前面ProduceSignature的代码:


 
  1. if (!fHashSingle || (i < mtx.vout.size())) {

  2. ProduceSignature(*keystore, MutableTransactionSignatureCreator(&mtx, i, amount, nHashType), prevPubKey, sigdata);

  3. }

    可以看到,创建MutableTransactionSignatureCreator时,传入了交易、要签名的交易输入的索引,交易输入引用的UTXO的比特币数量以及hashtype,来看看签名的过程:


 
  1. bool TransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const

  2. {

  3. //从keystore中拿到与公钥对应的私钥

  4. CKey key;

  5. if (!provider.GetKey(address, key))

  6. return false;

  7.  
  8. // Signing with uncompressed keys is disabled in witness scripts

  9. if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())

  10. return false;

  11.  
  12. //对交易生成hash摘要

  13. uint256 hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion);

  14.  
  15. //用私钥对交易的hash摘要进行数字签名,签名保存在输出参数vchSig中

  16. if (!key.Sign(hash, vchSig))

  17. return false;

  18. vchSig.push_back((unsigned char)nHashType);

  19. return true;

  20. }

    到此为止,对交易的签名就算是完成了。

4.3.2 校验脚本

   对交易签名完成以后,交易的输入就有了解锁脚本,接下来就要进行校验,看生成的这个解锁脚本是不是能够和交易输入指向的UTXO的锁定脚本匹配(一把钥匙一把锁,一个萝卜一个坑)。无论是本地还是网络中的其他节点,对于新交易,都必须对脚本进行校验后才能将交易添加到内存交易池里等待被矿工挖取。

4.3.2.1 比特币脚本语言

    比特币的脚本语言是一种基于堆栈的非图灵完备的脚本语言。我们知道区块链2.0的一个标识是智能合约,其代表就是以太坊,以太坊提供了solidity语言,利用该语言可以编写出非常复杂的去中心化DApp。比特币的脚本语言的作用和solidity类似,利用该脚本语言同样也可以写出具有复杂逻辑的执行脚本。我们之前介绍的P2PKH就是用脚本语言编写的一个简单脚本的例子。

    比特币的脚本语言不支持类似于for的循环,这样可以避免不怀好意的节点编写出具有无限循环的恶意脚本引发DoS攻击。但是像if-else这样的逻辑是支持的。

    比特币脚本语言支持的操作符定义在枚举opcode中,这里列出来,读者可以了解一下:


 
  1. /** Script opcodes */

  2. enum opcodetype

  3. {

  4. // push value

  5. OP_0 = 0x00,

  6. OP_FALSE = OP_0,

  7. OP_PUSHDATA1 = 0x4c,

  8. OP_PUSHDATA2 = 0x4d,

  9. OP_PUSHDATA4 = 0x4e,

  10. OP_1NEGATE = 0x4f,

  11. OP_RESERVED = 0x50,

  12. OP_1 = 0x51,

  13. OP_TRUE=OP_1,

  14. OP_2 = 0x52,

  15. OP_3 = 0x53,

  16. OP_4 = 0x54,

  17. OP_5 = 0x55,

  18. OP_6 = 0x56,

  19. OP_7 = 0x57,

  20. OP_8 = 0x58,

  21. OP_9 = 0x59,

  22. OP_10 = 0x5a,

  23. OP_11 = 0x5b,

  24. OP_12 = 0x5c,

  25. OP_13 = 0x5d,

  26. OP_14 = 0x5e,

  27. OP_15 = 0x5f,

  28. OP_16 = 0x60,

  29.  
  30. // control

  31. OP_NOP = 0x61,

  32. OP_VER = 0x62,

  33. OP_IF = 0x63,

  34. OP_NOTIF = 0x64,

  35. OP_VERIF = 0x65,

  36. OP_VERNOTIF = 0x66,

  37. OP_ELSE = 0x67,

  38. OP_ENDIF = 0x68,

  39. OP_VERIFY = 0x69,

  40. OP_RETURN = 0x6a,

  41.  
  42. // stack ops

  43. OP_TOALTSTACK = 0x6b,

  44. OP_FROMALTSTACK = 0x6c,

  45. OP_2DROP = 0x6d,

  46. OP_2DUP = 0x6e,

  47. OP_3DUP = 0x6f,

  48. OP_2OVER = 0x70,

  49. OP_2ROT = 0x71,

  50. OP_2SWAP = 0x72,

  51. OP_IFDUP = 0x73,

  52. OP_DEPTH = 0x74,

  53. OP_DROP = 0x75,

  54. OP_DUP = 0x76,

  55. OP_NIP = 0x77,

  56. OP_OVER = 0x78,

  57. OP_PICK = 0x79,

  58. OP_ROLL = 0x7a,

  59. OP_ROT = 0x7b,

  60. OP_SWAP = 0x7c,

  61. OP_TUCK = 0x7d,

  62.  
  63. // splice ops

  64. OP_CAT = 0x7e,

  65. OP_SUBSTR = 0x7f,

  66. OP_LEFT = 0x80,

  67. OP_RIGHT = 0x81,

  68. OP_SIZE = 0x82,

  69.  
  70. // bit logic

  71. OP_INVERT = 0x83,

  72. OP_AND = 0x84,

  73. OP_OR = 0x85,

  74. OP_XOR = 0x86,

  75. OP_EQUAL = 0x87,

  76. OP_EQUALVERIFY = 0x88,

  77. OP_RESERVED1 = 0x89,

  78. OP_RESERVED2 = 0x8a,

  79.  
  80. // numeric

  81. OP_1ADD = 0x8b,

  82. OP_1SUB = 0x8c,

  83. OP_2MUL = 0x8d,

  84. OP_2DIV = 0x8e,

  85. OP_NEGATE = 0x8f,

  86. OP_ABS = 0x90,

  87. OP_NOT = 0x91,

  88. OP_0NOTEQUAL = 0x92,

  89.  
  90. OP_ADD = 0x93,

  91. OP_SUB = 0x94,

  92. OP_MUL = 0x95,

  93. OP_DIV = 0x96,

  94. OP_MOD = 0x97,

  95. OP_LSHIFT = 0x98,

  96. OP_RSHIFT = 0x99,

  97.  
  98. OP_BOOLAND = 0x9a,

  99. OP_BOOLOR = 0x9b,

  100. OP_NUMEQUAL = 0x9c,

  101. OP_NUMEQUALVERIFY = 0x9d,

  102. OP_NUMNOTEQUAL = 0x9e,

  103. OP_LESSTHAN = 0x9f,

  104. OP_GREATERTHAN = 0xa0,

  105. OP_LESSTHANOREQUAL = 0xa1,

  106. OP_GREATERTHANOREQUAL = 0xa2,

  107. OP_MIN = 0xa3,

  108. OP_MAX = 0xa4,

  109.  
  110. OP_WITHIN = 0xa5,

  111.  
  112. // crypto

  113. OP_RIPEMD160 = 0xa6,

  114. OP_SHA1 = 0xa7,

  115. OP_SHA256 = 0xa8,

  116. OP_HASH160 = 0xa9,

  117. OP_HASH256 = 0xaa,

  118. OP_CODESEPARATOR = 0xab,

  119. OP_CHECKSIG = 0xac,

  120. OP_CHECKSIGVERIFY = 0xad,

  121. OP_CHECKMULTISIG = 0xae,

  122. OP_CHECKMULTISIGVERIFY = 0xaf,

  123.  
  124. // expansion

  125. OP_NOP1 = 0xb0,

  126. OP_CHECKLOCKTIMEVERIFY = 0xb1,

  127. OP_NOP2 = OP_CHECKLOCKTIMEVERIFY,

  128. OP_CHECKSEQUENCEVERIFY = 0xb2,

  129. OP_NOP3 = OP_CHECKSEQUENCEVERIFY,

  130. OP_NOP4 = 0xb3,

  131. OP_NOP5 = 0xb4,

  132. OP_NOP6 = 0xb5,

  133. OP_NOP7 = 0xb6,

  134. OP_NOP8 = 0xb7,

  135. OP_NOP9 = 0xb8,

  136. OP_NOP10 = 0xb9,

  137.  
  138.  
  139. // template matching params

  140. OP_SMALLINTEGER = 0xfa,

  141. OP_PUBKEYS = 0xfb,

  142. OP_PUBKEYHASH = 0xfd,

  143. OP_PUBKEY = 0xfe,

  144.  
  145. OP_INVALIDOPCODE = 0xff,

  146. };

    这些操作符分为几类,比如OP_N(N=0,1,...,16)用来push值,if,else等流程控制的操作符,加减乘除等数学运算操作符,用来操作堆栈的操作符等等。

4.3.2.2 标准的比特币交易

    比特币当前支持的标准交易都是用脚本语言编写的可执行脚本的例子,可以理解成是比特币上用脚本语言编写的智能合约。本小节我们简单的过一下这些标准交易。

    (1)P2PKH交易

     最常见的比特币标准交易,全称为Pay to public key hash的简称。从名字中就可以猜出这种交易是基于公钥的。这种交易会指定新的UTXO的接收者的公钥,花费UTXO的人须提供自己的公钥和交易签名,只有满足下面两个条件时才可以消耗UTXO:

     (C1) 消费者提供的公钥的hash必须和UTXO上指定的公钥的hash相同;

     (C2) 消费者的签名必须正确(对交易生成摘要D,然后用给定的公钥从签名中求得的交易摘要D‘必须和D相同)

     只要能满足上面两个条件,就能证明某人对UTXO的所有权,而能满足上面这两个条件的脚本如下:

     Signature  |  Public key  |  OP_DU  |  OP_HASH160  |  OP_PUBKEYHASH  |  OP_EQUALVERIFY  |  OP_CHECKSIG

     将交易的解锁脚本和锁定脚本合并起来就形成了上述脚本,这段脚本最终由脚本引擎解释并执行。

     (2) P2PK交易

    Pay To Public Key的简称,这种交易更简单,与P2PKH不同的地方在于他不用验证UTXO上指定的公钥与消费者提供的公钥的hash,只检查签名,相应的脚本如下:

     Signature  |  Public Key  |  OP_CHECKSIG

     (3) MULTISIG交易

  多重签名交易,这种交易用在要求更加严格的场合,简单的说就是要支出一笔钱,需要得到N个人中至少M个人的签字认可(M <= N)才行。这种交易会在UTXO上指定N个公钥(N个监管人的公钥),需要提取资金时,必须提供至少M个签名,只有所有的签名都能满足才行。以3个人管理一笔资金,提取时必须得到其中2个人的签名为例,满足条件的脚本如下:

     0  |  Sig1 |  Sig2  |  2  |  Public Key 1  | Public Key 2  | Public Key 3  |  3  |  OP_CHECKMULTISIG

     注意这里MULTISIG的脚本必须以0开始,这源自与OP_CHECKMULTISIG操作符在执行过程中的一个bug。

     (4) P2SH交易

    注意到MULTISIG多重签名的交易存在一些问题,假设A要向B支付一笔资金,但是B要求这笔资金需要MULTISIG,也就是要花这笔钱需要B自己以及他的若干合伙人同时签名。这样A的钱包生成给B转账的交易时,交易的锁定脚本会包含很多长度很长的公钥,导致交易所占用的体积会相当大,这会导致A要多支付不少的交易费用。P2SH交易可以解决这个问题。如果一个交易的锁定脚本非常复杂,就可以考虑用P2SH。

     仍旧以2-3多重签名为例,锁定脚本我们假设为S,则:

     S = 2  |  Public Key 1  | Public Key 2  | Public Key 3  |  3  |  OP_CHECKMULTISIG

     由于公钥的长度很长,所以上面的锁定脚本最终的体积会很大,如果改用P2SH交易,只需要对上面长长的锁定脚本进行hash处理,生成20字节的脚本hash,这样锁定脚本就变成了下面这样:

    OP_HASH160  |  [20 bytes script hash]  |  OP_EQUAL

    然后消费者为了支出资金,必须提供一个赎回脚本(redeem script),这个赎回脚本redeem和S是相同的,当执行脚本校验时,首先将消费者提供的赎回脚本进行hash,然后比较hash是否和锁定脚本中的hash相同:

     redeem  |  OP_HASH160  |  20 bytes script hash |  OP_EQUAL

     如果上一步执行成功,则执行解锁脚本:

     Sig1  |  Sig2  |  2  |  Public Key 1  | Public Key 2  | Public Key 3  |  3  |  OP_CHECKMULTISIG

  与多重签名相比,P2SH最大的不同是锁定脚本变短了,而解锁脚本变长了,这样额外的交易费变成了由UTXO的消费者来支付,而不是支付者。

    以上这些标准交易脚本最终由脚本引擎解释执行,我们在下节在详细说明。

4.3.2.3 交易脚本的运行原理

    比特币的脚本引擎是基于堆栈的,脚本解释器会逐一解析脚本的操作符,根据操作符进行入栈和弹栈的操作。仍然以P2PKH交易为例,比特币会将UTXO的锁定脚本和解锁脚本合并在一起,然后在堆栈上进行操作,我们用图来表示整个过程会更清楚一些:

    (1)签名入栈

    

    (2)公钥入栈

    

     (3)复制栈顶元素

    

     (4)栈顶元素弹栈,进行hash后的值入栈

    

     (5)公钥hash入栈

    

     (6)OP_EQUALVERIFY将堆栈中的前两个操作数弹栈,并进行比较,相同则继续,不相等出错。

    

     (7)弹出堆栈中的两个操作数,进行签名校验,成功栈顶入栈TRUE,否则栈顶入栈FALSE

    

     最后,如果栈顶元素为TRUE则脚本运行的结果为真,脚本验证通过。

     上面描述的交易脚本的运行过程,位于interpreter.cpp(名字很形象,一看就知道文件中是脚本解释器相关的实现)的EvalScript函数中,该函数的原型如下:

bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)

     该函数的参数如下:

     stack:输出参数,上文图中的堆栈;

     script:要解释的脚本;

     flags:校验相关的标识;

     checker:用于校验交易签名;

     serror:存放错误信息;

     EvalScript在执行时,会从头依次开始解析输入脚本,并根据不同的操作符更改堆栈。整个过程就是前文图中描述的那样,读者可以自行在源码中阅读这段代码,这里就不在列出了。

     我们在回头看看交易签名的最后一步,当ProduceSignature函数为交易输入生成了签名以后,最后一步就是要进行脚本校验了,如果脚本校验通过,说明确实有权消费交易输入引用的UTXO,该交易随后就可以添加到内存池并广播到网络中了,在SignTransaction的最后:


 
  1. if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {

  2. if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {

  3. // Unable to sign input and verification failed (possible attempt to partially sign).

  4. TxInErrorToJSON(txin, vErrors, "Unable to sign input, invalid stack size (possibly missing key)");

  5. } else {

  6. TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));

  7. }

  8. }

     可以看到调用了VerifyScript来校验脚本,传入了交易输入的解锁脚本以及输入引用的UTXO的锁定脚本,另外还有一个TransactionSignatureChecker对象,用于校验交易签名,这里列出VerifyScript的源码供读者参考:


 
  1. bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)

  2. {

  3. static const CScriptWitness emptyWitness;

  4. if (witness == nullptr) {

  5. witness = &emptyWitness;

  6. }

  7. bool hadWitness = false;

  8.  
  9. set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);

  10.  
  11. if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {

  12. return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);

  13. }

  14.  
  15. //堆栈

  16. std::vector<std::vector<unsigned char> > stack, stackCopy;

  17.  
  18. //解析并执行解锁脚本,如果解析过程中出错则返回,以P2PKH交易为例,执行完后堆栈中将保存公钥和签名

  19. if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))

  20. // serror is set

  21. return false;

  22. if (flags & SCRIPT_VERIFY_P2SH)

  23. stackCopy = stack;

  24. //继续解析执行锁定脚本

  25. if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))

  26. // serror is set

  27. return false;

  28.  
  29. //如果最终堆栈为空,则说明有错误,返回

  30. if (stack.empty())

  31. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);

  32. //堆栈中拿出脚本运行的结果

  33. if (CastToBool(stack.back()) == false)

  34. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);

  35.  
  36. //其他一些交易类型的处理

  37. // Bare witness programs

  38. int witnessversion;

  39. std::vector<unsigned char> witnessprogram;

  40. if (flags & SCRIPT_VERIFY_WITNESS) {

  41. if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {

  42. hadWitness = true;

  43. if (scriptSig.size() != 0) {

  44. // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.

  45. return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);

  46. }

  47. if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {

  48. return false;

  49. }

  50. // Bypass the cleanstack check at the end. The actual stack is obviously not clean

  51. // for witness programs.

  52. stack.resize(1);

  53. }

  54. }

  55.  
  56. // Additional validation for spend-to-script-hash transactions:

  57. if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())

  58. {

  59. // scriptSig must be literals-only or validation fails

  60. if (!scriptSig.IsPushOnly())

  61. return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);

  62.  
  63. // Restore stack.

  64. swap(stack, stackCopy);

  65.  
  66. // stack cannot be empty here, because if it was the

  67. // P2SH HASH <> EQUAL scriptPubKey would be evaluated with

  68. // an empty stack and the EvalScript above would return false.

  69. assert(!stack.empty());

  70.  
  71. const valtype& pubKeySerialized = stack.back();

  72. CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());

  73. popstack(stack);

  74.  
  75. if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))

  76. // serror is set

  77. return false;

  78. if (stack.empty())

  79. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);

  80. if (!CastToBool(stack.back()))

  81. return set_error(serror, SCRIPT_ERR_EVAL_FALSE);

  82.  
  83. // P2SH witness program

  84. if (flags & SCRIPT_VERIFY_WITNESS) {

  85. if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {

  86. hadWitness = true;

  87. if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {

  88. // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we

  89. // reintroduce malleability.

  90. return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);

  91. }

  92. if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {

  93. return false;

  94. }

  95. // Bypass the cleanstack check at the end. The actual stack is obviously not clean

  96. // for witness programs.

  97. stack.resize(1);

  98. }

  99. }

  100. }

  101.  
  102. // The CLEANSTACK check is only performed after potential P2SH evaluation,

  103. // as the non-P2SH evaluation of a P2SH script will obviously not result in

  104. // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.

  105. if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {

  106. // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK

  107. // would be possible, which is not a softfork (and P2SH should be one).

  108. assert((flags & SCRIPT_VERIFY_P2SH) != 0);

  109. assert((flags & SCRIPT_VERIFY_WITNESS) != 0);

  110. if (stack.size() != 1) {

  111. return set_error(serror, SCRIPT_ERR_CLEANSTACK);

  112. }

  113. }

  114.  
  115. if (flags & SCRIPT_VERIFY_WITNESS) {

  116. // We can't check for correct unexpected witness data if P2SH was off, so require

  117. // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be

  118. // possible, which is not a softfork.

  119. assert((flags & SCRIPT_VERIFY_P2SH) != 0);

  120. if (!hadWitness && !witness->IsNull()) {

  121. return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);

  122. }

  123. }

  124.  
  125. return set_success(serror);

  126. }

     可以看到源码中主要就是调用前面提到的EvalScript函数解析脚本并更新堆栈,还是比较容易理解的。

5 交易广播与接收

    经过上一节的处理以后,交易的脚本以及脚本的验证都通过,一笔交易就正式创建成功了,接下来就需要将交易加入到节点的 内存交易池中,等待被挖矿,同时节点还要将交易广播到网络中,其他节点对交易进行验证,无误以后也加入到自己的交易池里。

5.1 广播交易

    创建好的交易可以通过jsonapi sendrawtransaction命令广播到网络当中,我们直接看这个命令的实现:


 
  1. static UniValue sendrawtransaction(const JSONRPCRequest& request)

  2. {

  3. //参数检查

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

  5. throw std::runtime_error(

  6. "sendrawtransaction \"hexstring\" ( allowhighfees )\n"

  7. "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"

  8. "\nAlso see createrawtransaction and signrawtransaction calls.\n"

  9. "\nArguments:\n"

  10. "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"

  11. "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"

  12. "\nResult:\n"

  13. "\"hex\" (string) The transaction hash in hex\n"

  14. "\nExamples:\n"

  15. "\nCreate a transaction\n"

  16. + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +

  17. "Sign the transaction, and get back the hex\n"

  18. + HelpExampleCli("signrawtransaction", "\"myhex\"") +

  19. "\nSend the transaction (signed hex)\n"

  20. + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +

  21. "\nAs a json rpc call\n"

  22. + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")

  23. );

  24.  
  25. std::promise<void> promise;

  26.  
  27. RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});

  28.  
  29. // parse hex string from parameter

  30. //解码出交易

  31. CMutableTransaction mtx;

  32. if (!DecodeHexTx(mtx, request.params[0].get_str()))

  33. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");

  34. CTransactionRef tx(MakeTransactionRef(std::move(mtx)));

  35. const uint256& hashTx = tx->GetHash();

  36.  
  37. CAmount nMaxRawTxFee = maxTxFee;

  38. if (!request.params[1].isNull() && request.params[1].get_bool())

  39. nMaxRawTxFee = 0;

  40.  
  41. { // cs_main scope

  42. LOCK(cs_main);

  43. CCoinsViewCache &view = *pcoinsTip;

  44. //判断交易是否已经在内存池中,交易是否有输出已经被花费掉了

  45. bool fHaveChain = false;

  46. for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {

  47. const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));

  48. fHaveChain = !existingCoin.IsSpent();

  49. }

  50. bool fHaveMempool = mempool.exists(hashTx);

  51. //如果交易在内存池中不存在,并且交易所有的输出都未花费,则将交易加入内存交易池中

  52. if (!fHaveMempool && !fHaveChain) {

  53. // push to local node and sync with wallets

  54. CValidationState state;

  55. bool fMissingInputs;

  56. //尝试将交易加入交易池

  57. if (!AcceptToMemoryPool(mempool, state, std::move(tx), &fMissingInputs,

  58. nullptr /* plTxnReplaced */, false /* bypass_limits */, nMaxRawTxFee)) {

  59. if (state.IsInvalid()) {

  60. throw JSONRPCError(RPC_TRANSACTION_REJECTED, FormatStateMessage(state));

  61. } else {

  62. if (fMissingInputs) {

  63. throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");

  64. }

  65. throw JSONRPCError(RPC_TRANSACTION_ERROR, FormatStateMessage(state));

  66. }

  67. } else {

  68. // If wallet is enabled, ensure that the wallet has been made aware

  69. // of the new transaction prior to returning. This prevents a race

  70. // where a user might call sendrawtransaction with a transaction

  71. // to/from their wallet, immediately call some wallet RPC, and get

  72. // a stale result because callbacks have not yet been processed.

  73. CallFunctionInValidationInterfaceQueue([&promise] {

  74. promise.set_value();

  75. });

  76. }

  77. } else if (fHaveChain) {

  78. throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");

  79. } else {

  80. // Make sure we don't block forever if re-sending

  81. // a transaction already in mempool.

  82. promise.set_value();

  83. }

  84.  
  85. } // cs_main

  86.  
  87. promise.get_future().wait();

  88.  
  89. if(!g_connman)

  90. throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

  91.  
  92. //发送INV消息,将交易广播到网络中

  93. CInv inv(MSG_TX, hashTx);

  94. g_connman->ForEachNode([&inv](CNode* pnode)

  95. {

  96. pnode->PushInventory(inv);

  97. });

  98.  
  99. return hashTx.GetHex();

  100. }

    只有交易在交易池中不存在,并且交易的每一笔输出都未被花费,才能将交易添加到交易池中。

    最后会生成一个INV消息加入到集合当中,等待广播到网络中。

5.2 接收交易

    再来看看网络中的节点收到一笔新交易后如何处理。ProcessMessage中对INV消息的处理:


 
  1. else if (strCommand == NetMsgType::INV)

  2. {

  3. //读出数据

  4. std::vector<CInv> vInv;

  5. vRecv >> vInv;

  6. if (vInv.size() > MAX_INV_SZ)

  7. {

  8. LOCK(cs_main);

  9. Misbehaving(pfrom->GetId(), 20, strprintf("message inv size() = %u", vInv.size()));

  10. return false;

  11. }

  12.  
  13. bool fBlocksOnly = !fRelayTxes;

  14.  
  15. // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true

  16. if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))

  17. fBlocksOnly = false;

  18.  
  19. LOCK(cs_main);

  20.  
  21. uint32_t nFetchFlags = GetFetchFlags(pfrom);

  22.  
  23. //处理收到的每一个INV消息

  24. for (CInv &inv : vInv)

  25. {

  26. if (interruptMsgProc)

  27. return true;

  28.  
  29. //判断交易是否已经存在于区块链上

  30. bool fAlreadyHave = AlreadyHave(inv);

  31. LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());

  32.  
  33. if (inv.type == MSG_TX) {

  34. inv.type |= nFetchFlags;

  35. }

  36.  
  37. //如果是一个区块

  38. if (inv.type == MSG_BLOCK) {

  39. UpdateBlockAvailability(pfrom->GetId(), inv.hash);

  40. if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {

  41. // We used to request the full block here, but since headers-announcements are now the

  42. // primary method of announcement on the network, and since, in the case that a node

  43. // fell back to inv we probably have a reorg which we should get the headers for first,

  44. // we now only provide a getheaders response here. When we receive the headers, we will

  45. // then ask for the blocks we need.

  46. connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));

  47. LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());

  48. }

  49. }

  50. //如果收到的是一笔交易

  51. else

  52. {

  53. pfrom->AddInventoryKnown(inv);

  54. if (fBlocksOnly) {

  55. LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());

  56. } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {

  57. //如果交易不存在,则将该交易加入到请求集合中

  58. pfrom->AskFor(inv);

  59. }

  60. }

  61.  
  62. // Track requests for our stuff

  63. GetMainSignals().Inventory(inv.hash);

  64. }

  65. }

    如果节点不存在收到的交易hash,则会调用AskFor来请求交易数据,AskFor会将请求加入到队列中(mapAskFor)。之后会遍历该队列,生成GETDATA消息,批量拉取本地缺失的交易(或区块)数据(参考SendMessage函数):


 
  1. //遍历队列

  2. while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)

  3. {

  4. const CInv& inv = (*pto->mapAskFor.begin()).second;

  5. if (!AlreadyHave(inv))

  6. {

  7. //交易(或者区块)数据不存在,插入vGetData集合,当集合中数据达到1000+时,发送GETDATA消息批量获取数据

  8. LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());

  9. vGetData.push_back(inv);

  10. if (vGetData.size() >= 1000)

  11. {

  12. connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));

  13. vGetData.clear();

  14. }

  15. } else {

  16. //If we're not going to ask, don't expect a response.

  17. //已经存在了,从集合里删除

  18. pto->setAskFor.erase(inv.hash);

  19. }

  20. //从队列中删除

  21. pto->mapAskFor.erase(pto->mapAskFor.begin());

  22. }

  23.  
  24. //如果集合不空

  25. if (!vGetData.empty())

  26. connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));

    长话短说就是等队列中集齐1000条或更多数据时,发送一条GETDATA消息,批量拉取数据。

    再来看看节点收到GETDATA消息后如何处理:


 
  1. else if (strCommand == NetMsgType::GETDATA)

  2. {

  3. //从流中读取数据

  4. std::vector<CInv> vInv;

  5. vRecv >> vInv;

  6. if (vInv.size() > MAX_INV_SZ)

  7. {

  8. LOCK(cs_main);

  9. Misbehaving(pfrom->GetId(), 20, strprintf("message getdata size() = %u", vInv.size()));

  10. return false;

  11. }

  12.  
  13. LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());

  14.  
  15. if (vInv.size() > 0) {

  16. LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());

  17. }

  18.  
  19. //将所有GETDATA请求添加到集合中

  20. pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());

  21. //处理请求

  22. ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);

  23. }

    很简单,主要是调用ProcessGetData来处理,继续跟进去一探究竟:


 
  1. void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)

  2. {

  3. AssertLockNotHeld(cs_main);

  4.  
  5. std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();

  6. std::vector<CInv> vNotFound;

  7. const CNetMsgMaker msgMaker(pfrom->GetSendVersion());

  8. {

  9. LOCK(cs_main);

  10.  
  11. //遍历集合

  12. while (it != pfrom->vRecvGetData.end() && (it->type == MSG_TX || it->type == MSG_WITNESS_TX)) {

  13. if (interruptMsgProc)

  14. return;

  15. // Don't bother if send buffer is too full to respond anyway

  16. if (pfrom->fPauseSend)

  17. break;

  18.  
  19. const CInv &inv = *it;

  20. it++;

  21.  
  22. // Send stream from relay memory

  23. //检查mapRelay或者内存交易池中是否存在交易,如果存在发送TX消息,将交易数据发送给请求方

  24. bool push = false;

  25. auto mi = mapRelay.find(inv.hash);

  26. int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);

  27. if (mi != mapRelay.end()) {

  28. connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));

  29. push = true;

  30. } else if (pfrom->timeLastMempoolReq) {

  31. auto txinfo = mempool.info(inv.hash);

  32. // To protect privacy, do not answer getdata using the mempool when

  33. // that TX couldn't have been INVed in reply to a MEMPOOL request.

  34. if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {

  35. connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));

  36. push = true;

  37. }

  38. }

  39. if (!push) {

  40. vNotFound.push_back(inv);

  41. }

  42.  
  43. // Track requests for our stuff.

  44. GetMainSignals().Inventory(inv.hash);

  45. }

  46. } // release cs_main

  47.  
  48. if (it != pfrom->vRecvGetData.end() && !pfrom->fPauseSend) {

  49. const CInv &inv = *it;

  50. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK) {

  51. it++;

  52. ProcessGetBlockData(pfrom, consensusParams, inv, connman, interruptMsgProc);

  53. }

  54. }

  55.  
  56. //处理完以后从集合中删除掉

  57. pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);

  58.  
  59. if (!vNotFound.empty()) {

  60. // Let the peer know that we didn't find what it asked for, so it doesn't

  61. // have to wait around forever. Currently only SPV clients actually care

  62. // about this message: it's needed when they are recursively walking the

  63. // dependencies of relevant unconfirmed transactions. SPV clients want to

  64. // do that because they want to know about (and store and rebroadcast and

  65. // risk analyze) the dependencies of transactions relevant to them, without

  66. // having to download the entire memory pool.

  67. connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));

  68. }

  69. }

    节点会从RelayMap和内存交易池中寻找请求的交易,如果找到将向peer发送TX消息,将交易数据发送给peer。

    最后,peer收到TX消息,拿到交易,然后对交易进行校验,验证无误后将交易加入到自己的交易池中,TX消息的处理比较复杂,涉及到孤立交易的处理(两种情况:该交易依赖的交易还没收到,此时收到的交易成为孤立交易;另外一种情况是孤立交易池中有依赖于该交易的孤立交易,当该交易收到以后,需要将孤立交易从鼓励交易池中移走并加入到内存交易池中),我们只截取一部分代码,详细的处理读者可自行阅读源码net_processing.cpp的ProcessMessage方法。


 
  1. else if (strCommand == NetMsgType::TX)

  2. {

  3. // Stop processing the transaction early if

  4. // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off

  5. if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))

  6. {

  7. LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());

  8. return true;

  9. }

  10.  
  11. std::deque<COutPoint> vWorkQueue;

  12. std::vector<uint256> vEraseQueue;

  13.  
  14. //从流中读取交易

  15. CTransactionRef ptx;

  16. vRecv >> ptx;

  17. const CTransaction& tx = *ptx;

  18.  
  19. CInv inv(MSG_TX, tx.GetHash());

  20. pfrom->AddInventoryKnown(inv);

  21.  
  22. LOCK2(cs_main, g_cs_orphans);

  23.  
  24. bool fMissingInputs = false;

  25. CValidationState state;

  26.  
  27. //交易已经获取,从相关集合中删除

  28. pfrom->setAskFor.erase(inv.hash);

  29. mapAlreadyAskedFor.erase(inv.hash);

  30.  
  31. std::list<CTransactionRef> lRemovedTxn;

  32.  
  33. //如果交易不存在,则调用AcceptToMemoryPool将交易加入到内存交易池中

  34. if (!AlreadyHave(inv) &&

  35. AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {

  36. mempool.check(pcoinsTip.get());

  37. RelayTransaction(tx, connman);

    最终同样调用AcceptToMemoryPool将交易添加到交易池中。AcceptToMemoryPool这个函数的处理逻辑非常复杂,会对交易进行各种检查,包括交易的格式,交易是否是有双花问题,交易签名的验证等等。这个函数非常重要,建议读者可以仔细阅读该函数的源码加深对交易的理解。AcceptToMemoryPool 函数里会调用CheckInputs检查交易的每一笔输入,其中就包含交易签名的验证:


 
  1. /**

  2. * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)

  3. * This does not modify the UTXO set.

  4. *

  5. * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any

  6. * script checks which are not necessary (eg due to script execution cache hits) are, obviously,

  7. * not pushed onto pvChecks/run.

  8. *

  9. * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache

  10. * which are matched. This is useful for checking blocks where we will likely never need the cache

  11. * entry again.

  12. *

  13. * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp

  14. */

  15. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)

  16. {

  17. if (!tx.IsCoinBase())

  18. {

  19. if (pvChecks)

  20. pvChecks->reserve(tx.vin.size());

  21.  
  22. // The first loop above does all the inexpensive checks.

  23. // Only if ALL inputs pass do we perform expensive ECDSA signature checks.

  24. // Helps prevent CPU exhaustion attacks.

  25.  
  26. // Skip script verification when connecting blocks under the

  27. // assumevalid block. Assuming the assumevalid block is valid this

  28. // is safe because block merkle hashes are still computed and checked,

  29. // Of course, if an assumed valid block is invalid due to false scriptSigs

  30. // this optimization would allow an invalid chain to be accepted.

  31. if (fScriptChecks) {

  32. // First check if script executions have been cached with the same

  33. // flags. Note that this assumes that the inputs provided are

  34. // correct (ie that the transaction hash which is in tx's prevouts

  35. // properly commits to the scriptPubKey in the inputs view of that

  36. // transaction).

  37. uint256 hashCacheEntry;

  38. // We only use the first 19 bytes of nonce to avoid a second SHA

  39. // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)

  40. static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");

  41. CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());

  42. AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks

  43. if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {

  44. return true;

  45. }

  46.  
  47. //检查交易的每一笔输入

  48. for (unsigned int i = 0; i < tx.vin.size(); i++) {

  49. //找到输入指向的UTXO,确保其并未被花费

  50. const COutPoint &prevout = tx.vin[i].prevout;

  51. const Coin& coin = inputs.AccessCoin(prevout);

  52. assert(!coin.IsSpent());

  53.  
  54. // We very carefully only pass in things to CScriptCheck which

  55. // are clearly committed to by tx' witness hash. This provides

  56. // a sanity check that our caching is not introducing consensus

  57. // failures through additional data in, eg, the coins being

  58. // spent being checked as a part of CScriptCheck.

  59.  
  60. // Verify signature

  61. //校验交易签名

  62. CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);

  63. if (pvChecks) {

  64. pvChecks->push_back(CScriptCheck());

  65. check.swap(pvChecks->back());

  66. } else if (!check()) {

  67. if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {

  68. // Check whether the failure was caused by a

  69. // non-mandatory script verification check, such as

  70. // non-standard DER encodings or non-null dummy

  71. // arguments; if so, don't trigger DoS protection to

  72. // avoid splitting the network between upgraded and

  73. // non-upgraded nodes.

  74. CScriptCheck check2(coin.out, tx, i,

  75. flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);

  76. if (check2())

  77. return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));

  78. }

  79. // Failures of other flags indicate a transaction that is

  80. // invalid in new blocks, e.g. an invalid P2SH. We DoS ban

  81. // such nodes as they are not following the protocol. That

  82. // said during an upgrade careful thought should be taken

  83. // as to the correct behavior - we may want to continue

  84. // peering with non-upgraded nodes even after soft-fork

  85. // super-majority signaling has occurred.

  86. return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));

  87. }

  88. }

  89.  
  90. if (cacheFullScriptStore && !pvChecks) {

  91. // We executed all of the provided scripts, and were told to

  92. // cache the result. Do so now.

  93. scriptExecutionCache.insert(hashCacheEntry);

  94. }

  95. }

  96. }

  97.  
  98. return true;

  99. }

    代码中通过仿函数CScriptCheck来对交易签名进行校验,以交易、交易输入的索引、交易输入指向的UTXO等作为参数构建CScriptCheck对象,执行校验的过程:


 
  1. bool CScriptCheck::operator()() {

  2. const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;

  3. const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;

  4. return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);

  5. }

    这里最终还是调用了我们在第4节介绍的VerifyScript函数来执行脚本的校验,这里就不在重复了。

5.3 时序

    代码贴了一串又一串,可能很少有读者能耐着性子看完,我们这里用一张简单的图来说明一下整个过程:

    

    阅读源代码过程中只要顺着图里面的这条主线一直往下看,就能捋清楚交易从生成、签名、广播、接收直到交易加入交易池的整个过程。

6 总结

    交易是比特币中最重要的一块内容。本文从源码角度,分析了比特币交易的创建、交易的签名、‘’交易脚本的运行、交易的广播和接收。读者可以顺着本文中主线来阅读代码,一旦搞懂了这一部分代码,就能更深刻的理解比特币交易。

展开阅读全文

没有更多推荐了,返回首页