1. 程式人生 > >比特幣原始碼分析--深入理解比特幣交易

比特幣原始碼分析--深入理解比特幣交易

交易是比特幣最重要的一塊,比特幣系統的其他部分都是為交易服務的。前面的章節中已經學習了各種共識演算法以及比特幣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. /* Setting nSequence to this value for every input in a transaction

  17. * disables nLockTime. */

  18. static const uint32_t SEQUENCE_FINAL = 0xffffffff;

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

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

  21. * relative lock-time. */

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

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

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

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

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

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

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

  29. static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;

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

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

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

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

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

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

  36. * 9 bits. */

  37. static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;

  38. CTxIn()

  39. {

  40. nSequence = SEQUENCE_FINAL;

  41. }

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

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

  44. ADD_SERIALIZE_METHODS;

  45. template <typename Stream, typename Operation>

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

  47. READWRITE(prevout);

  48. READWRITE(scriptSig);

  49. READWRITE(nSequence);

  50. }

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

  52. {

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

  54. a.scriptSig == b.scriptSig &&

  55. a.nSequence == b.nSequence);

  56. }

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

  58. {

  59. return !(a == b);

  60. }

  61. std::string ToString() const;

  62. };

    程式碼中的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. COutPoint(): n((uint32_t) -1) { }

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

  11. ADD_SERIALIZE_METHODS;

  12. template <typename Stream, typename Operation>

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

  14. READWRITE(hash);

  15. READWRITE(n);

  16. }

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

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

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

  20. {

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

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

  23. }

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

  25. {

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

  27. }

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

  29. {

  30. return !(a == b);

  31. }

  32. std::string ToString() const;

  33. };

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. CTxOut()

  10. {

  11. SetNull();

  12. }

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

  14. ADD_SERIALIZE_METHODS;

  15. template <typename Stream, typename Operation>

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

  17. READWRITE(nValue);

  18. READWRITE(scriptPubKey);

  19. }

  20. void SetNull()

  21. {

  22. nValue = -1;

  23. scriptPubKey.clear();

  24. }

  25. bool IsNull() const

  26. {

  27. return (nValue == -1);

  28. }

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

  30. {

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

  32. a.scriptPubKey == b.scriptPubKey);

  33. }

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

  35. {

  36. return !(a == b);

  37. }

  38. std::string ToString() const;

  39. };

    可以看到定義非常簡單,只有兩個欄位: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. //! whether containing transaction was a coinbase

  15. //該UTXO是否是coinbase交易

  16. unsigned int fCoinBase : 1;

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

  18. //包含該UTXO的交易所在區塊在區塊鏈上的高度

  19. uint32_t nHeight : 31;

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

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

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

  23. void Clear() {

  24. out.SetNull();

  25. fCoinBase = false;

  26. nHeight = 0;

  27. }

  28. //! empty constructor

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

  30. bool IsCoinBase() const {

  31. return fCoinBase;

  32. }

  33. template<typename Stream>

  34. void Serialize(Stream &s) const {

  35. assert(!IsSpent());

  36. uint32_t code = nHeight * 2 + fCoinBase;

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

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

  39. }

  40. template<typename Stream>

  41. void Unserialize(Stream &s) {

  42. uint32_t code = 0;

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

  44. nHeight = code >> 1;

  45. fCoinBase = code & 1;

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

  47. }

  48. bool IsSpent() const {

  49. return out.IsNull();

  50. }

  51. size_t DynamicMemoryUsage() const {

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

  53. }

  54. };

    比特幣錢包實際上就是一個由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. ADD_SERIALIZE_METHODS;

  27. template <typename Stream, typename Operation>

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

  29. READWRITEAS(CScriptBase, *this);

  30. }

  31. CScript& operator+=(const CScript& b)

  32. {

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

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

  35. return *this;

  36. }

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

  38. {

  39. CScript ret = a;

  40. ret += b;

  41. return ret;

  42. }

  43. CScript(int64_t b) { operator<<(b); }

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

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

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

  47. CScript& operator<<(int64_t b) { return push_int64(b); }

  48. CScript& operator<<(opcodetype opcode)

  49. {

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

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

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

  53. return *this;

  54. }

  55. CScript& operator<<(const CScriptNum& b)

  56. {

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

  58. return *this;

  59. }

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

  61. {

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

  63. {

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

  65. }

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

  67. {

  68. insert(end(), OP_PUSHDATA1);

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

  70. }

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

  72. {

  73. insert(end(), OP_PUSHDATA2);

  74. uint8_t _data[2];

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

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

  77. }

  78. else

  79. {

  80. insert(end(), OP_PUSHDATA4);

  81. uint8_t _data[4];

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

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

  84. }

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

  86. return *this;

  87. }

  88. CScript& operator<<(const CScript& b)

  89. {

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

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

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

  93. return *this;

  94. }

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

  96. {

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

  98. }

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

  100. {

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

  102. }

  103. /** Encode/decode small integers: */

  104. static int DecodeOP_N(opcodetype opcode)

  105. {

  106. if (opcode == OP_0)

  107. return 0;

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

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

  110. }

  111. static opcodetype EncodeOP_N(int n)

  112. {

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

  114. if (n == 0)

  115. return OP_0;

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

  117. }

  118. /**

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

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

  121. * CHECKMULTISIGs serialized in scriptSigs are

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

  123. * ... OP_N CHECKMULTISIG ...

  124. */

  125. unsigned int GetSigOpCount(bool fAccurate) const;

  126. /**

  127. * Accurately count sigOps, including sigOps in

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

  129. */

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

  131. bool IsPayToScriptHash() const;

  132. bool IsPayToWitnessScriptHash() const;

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

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

  135. bool IsPushOnly(const_iterator pc) const;

  136. bool IsPushOnly() const;

  137. /** Check if the script contains valid OP_CODES */

  138. bool HasValidOps() const;

  139. /**

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

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

  142. * instantly when entering the UTXO set.

  143. */

  144. bool IsUnspendable() const

  145. {

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

  147. }

  148. void clear()

  149. {

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

  151. CScriptBase::clear();

  152. shrink_to_fit();

  153. }

  154. };

    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. // Changing the default transaction version requires a two step process: first

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

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

  12. // MAX_STANDARD_VERSION will be equal.

  13. static const int32_t MAX_STANDARD_VERSION=2;

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

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

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

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

  18. // structure, including the hash.

  19. //交易的全部輸入

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

  21. //交易的全部輸出

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

  23. //交易版本

  24. const int32_t nVersion;

  25. //交易鎖定時間,用來控制在一定的時間之後交易的輸出才能被花費

  26. const uint32_t nLockTime;

  27. private:

  28. /** Memory only. */

  29. const uint256 hash;

  30. uint256 ComputeHash() const;

  31. public:

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

  33. CTransaction();

  34. /** Convert a CMutableTransaction into a CTransaction. */

  35. CTransaction(const CMutableTransaction &tx);

  36. CTransaction(CMutableTransaction &&tx);

  37. template <typename Stream>

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

  39. SerializeTransaction(*this, s);

  40. }

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

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

  43. template <typename Stream>

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

  45. bool IsNull() const {

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

  47. }

  48. const uint256& GetHash() const {

  49. return hash;

  50. }

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

  52. uint256 GetWitnessHash() const;

  53. // Return sum of txouts.

  54. CAmount GetValueOut() const;

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

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

  57. /**

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

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

  60. * @return Total transaction size in bytes

  61. */

  62. unsigned int GetTotalSize() const;

  63. bool IsCoinBase() const

  64. {

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

  66. }

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

  68. {

  69. return a.hash == b.hash;

  70. }

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

  72. {

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

  74. }

  75. std::string ToString() const;

  76. bool HasWitness() const

  77. {

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

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

  80. return true;

  81. }

  82. }

  83. return false;

  84. }

  85. };

     除了交易輸入和輸出外,還有交易的版本和交易時間鎖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. CMutableTransaction();

  9. CMutableTransaction(const CTransaction& tx);

  10. template <typename Stream>

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

  12. SerializeTransaction(*this, s);

  13. }

  14. template <typename Stream>

  15. inline void Unserialize(Stream& s) {

  16. UnserializeTransaction(*this, s);

  17. }

  18. template <typename Stream>

  19. CMutableTransaction(deserialize_type, Stream& s) {

  20. Unserialize(s);

  21. }

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

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

  24. */

  25. uint256 GetHash() const;

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

  27. {

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

  29. }

  30. bool HasWitness() const

  31. {

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

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

  34. return true;

  35. }

  36. }

  37. return false;

  38. }

  39. };

    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. "\nArguments:\n"

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

  15. " [\n"

  16. " {\n"

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

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

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

  20. " } \n"

  21. " ,...\n"

  22. " ]\n"

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

  24. " [\n"

  25. " {\n"

  26. " \"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"

  27. " },\n"

  28. " {\n"

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

  30. " }\n"

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

  32. " accepted as second parameter.\n"

  33. " ]\n"

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

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

  36. " 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"

  37. "\nResult:\n"

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

  39. "\nExamples:\n"

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

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

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

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

  44. // clang-format on

  45. );

  46. }

  47. //檢查引數

  48. RPCTypeCheck(request.params, {

  49. UniValue::VARR,

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

  51. UniValue::VNUM,

  52. UniValue::VBOOL

  53. }, true

  54. );

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

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

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

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

  59. UniValue outputs = outputs_is_obj ?

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

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

  62. //生成交易物件

  63. CMutableTransaction rawTx;

  64. //從引數提取交易的鎖定時間(如果提供的話)

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

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

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

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

  69. rawTx.nLockTime = nLockTime;

  70. }

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

  72. //解析引數,生成交易的輸入

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

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

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

  76. //該輸入指向的交易

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

  78. //該輸入指向的UTXO在其交易中的索引

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

  80. if (!vout_v.isNum())

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

  82. int nOutput = vout_v.get_int();

  83. if (nOutput < 0)

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

  85. uint32_t nSequence;

  86. if (rbfOptIn) {

  87. nSequence = MAX_BIP125_RBF_SEQUENCE;

  88. } else if (rawTx.nLockTime) {

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

  90. } else {

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

  92. }

  93. // set the sequence number if passed in the parameters object

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

  95. if (sequenceObj.isNum()) {

  96. int64_t seqNr64 = sequenceObj.get_int64();

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

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

  99. } else {

  100. nSequence = (uint32_t)seqNr64;

  101. }

  102. }

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

  104. rawTx.vin.push_back(in);

  105. }

  106. std::set<CTxDestination> destinations;

  107. if (!outputs_is_obj) {

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

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

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

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

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

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

  114. }

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

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

  117. }

  118. outputs_dict.pushKVs(output);

  119. }

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

  121. }

  122. //根據引數生成交易的輸出

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

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

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

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

  127. } else {

  128. //解析出目標地址(比特幣最終流向的地方)

  129. CTxDestination destination = DecodeDestination(name_);

  130. if (!IsValidDestination(destination)) {

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

  132. }

  133. if (!destinations.insert(destination).second) {

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

  135. }

  136. //根據地址生成交易輸出的鎖定指令碼

  137. CScript scriptPubKey = GetScriptForDestination(destination);

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

  139. CTxOut out(nAmount, scriptPubKey);

  140. rawTx.vout.push_back(out);

  141. }

  142. }

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

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

  145. }

  146. //對交易進行編碼並返回

  147. return EncodeHexTx(rawTx);

  148. }

    整體的過程並不複雜:從引數中解析出每一筆輸入和輸出,並填寫到CMutableTransaction物件中,最後將物件編碼後返回。但是這裡有兩個問題值得注意:

    (1) 從程式碼中沒有看到交易輸入中的解鎖指令碼scriptSig;

    (2) 交易輸出的鎖定指令碼如何生成的需要了解;

    關於第一個問題,隨後在分析交易簽名時解答,下面我們先來看看第二個問題:交易輸出的鎖定指令碼如何生成。生成鎖定指令碼的程式碼如下:

CScript scriptPubKey = GetScriptForDestination(destination);

    我們來看看這個函式的實現:

  1. CScript GetScriptForDestination(const CTxDestination& dest)

  2. {

  3. CScript script;

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

  5. return script;

  6. }

    首先,該方法接受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. bool operator()(const CNoDestination &dest) const {

  8. script->clear();

  9. return false;

  10. }

  11. //P2PKH標準交易

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

  13. script->clear();

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

  15. return true;

  16. }

  17. //P2SH標準交易

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

  19. script->clear();

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

  21. return true;

  22. }

  23. //P2WSH交易

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

  25. {

  26. script->clear();

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

  28. return true;

  29. }

  30. //P2WKH交易

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

  32. {

  33. script->clear();

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

  35. return true;

  36. }

  37. bool operator()(const WitnessUnknown& id) const

  38. {

  39. script->clear();

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

  41. return true;

  42. }

  43. };

    現在,我們已經瞭解到交易輸出的鎖定指令碼的生成過程了,暫時先不用管指令碼是如何執行的,本文稍後還會詳細說明交易指令碼的執行原理。

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:signra