You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

transaction.h 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Starwels developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef STARWELS_PRIMITIVES_TRANSACTION_H
  6. #define STARWELS_PRIMITIVES_TRANSACTION_H
  7. #include <stdint.h>
  8. #include "amount.h"
  9. #include "script/script.h"
  10. #include "serialize.h"
  11. #include "uint256.h"
  12. static const int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000;
  13. /** An outpoint - a combination of a transaction hash and an index n into its vout */
  14. class COutPoint
  15. {
  16. public:
  17. uint256 hash;
  18. uint32_t n;
  19. COutPoint(): n((uint32_t) -1) { }
  20. COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
  21. ADD_SERIALIZE_METHODS;
  22. template <typename Stream, typename Operation>
  23. inline void SerializationOp(Stream& s, Operation ser_action) {
  24. READWRITE(hash);
  25. READWRITE(n);
  26. }
  27. void SetNull() { hash.SetNull(); n = (uint32_t) -1; }
  28. bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); }
  29. friend bool operator<(const COutPoint& a, const COutPoint& b)
  30. {
  31. int cmp = a.hash.Compare(b.hash);
  32. return cmp < 0 || (cmp == 0 && a.n < b.n);
  33. }
  34. friend bool operator==(const COutPoint& a, const COutPoint& b)
  35. {
  36. return (a.hash == b.hash && a.n == b.n);
  37. }
  38. friend bool operator!=(const COutPoint& a, const COutPoint& b)
  39. {
  40. return !(a == b);
  41. }
  42. std::string ToString() const;
  43. };
  44. /** An input of a transaction. It contains the location of the previous
  45. * transaction's output that it claims and a signature that matches the
  46. * output's public key.
  47. */
  48. class CTxIn
  49. {
  50. public:
  51. COutPoint prevout;
  52. CScript scriptSig;
  53. uint32_t nSequence;
  54. CScriptWitness scriptWitness; //! Only serialized through CTransaction
  55. /* Setting nSequence to this value for every input in a transaction
  56. * disables nLockTime. */
  57. static const uint32_t SEQUENCE_FINAL = 0xffffffff;
  58. /* Below flags apply in the context of BIP 68*/
  59. /* If this flag set, CTxIn::nSequence is NOT interpreted as a
  60. * relative lock-time. */
  61. static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
  62. /* If CTxIn::nSequence encodes a relative lock-time and this flag
  63. * is set, the relative lock-time has units of 512 seconds,
  64. * otherwise it specifies blocks with a granularity of 1. */
  65. static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
  66. /* If CTxIn::nSequence encodes a relative lock-time, this mask is
  67. * applied to extract that lock-time from the sequence field. */
  68. static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
  69. /* In order to use the same number of bits to encode roughly the
  70. * same wall-clock duration, and because blocks are naturally
  71. * limited to occur every 600s on average, the minimum granularity
  72. * for time-based relative lock-time is fixed at 512 seconds.
  73. * Converting from CTxIn::nSequence to seconds is performed by
  74. * multiplying by 512 = 2^9, or equivalently shifting up by
  75. * 9 bits. */
  76. static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
  77. CTxIn()
  78. {
  79. nSequence = SEQUENCE_FINAL;
  80. }
  81. explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
  82. CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL);
  83. ADD_SERIALIZE_METHODS;
  84. template <typename Stream, typename Operation>
  85. inline void SerializationOp(Stream& s, Operation ser_action) {
  86. READWRITE(prevout);
  87. READWRITE(scriptSig);
  88. READWRITE(nSequence);
  89. }
  90. friend bool operator==(const CTxIn& a, const CTxIn& b)
  91. {
  92. return (a.prevout == b.prevout &&
  93. a.scriptSig == b.scriptSig &&
  94. a.nSequence == b.nSequence);
  95. }
  96. friend bool operator!=(const CTxIn& a, const CTxIn& b)
  97. {
  98. return !(a == b);
  99. }
  100. std::string ToString() const;
  101. };
  102. /** An output of a transaction. It contains the public key that the next input
  103. * must be able to sign with to claim it.
  104. */
  105. class CTxOut
  106. {
  107. public:
  108. CAmount nValue;
  109. CScript scriptPubKey;
  110. CTxOut()
  111. {
  112. SetNull();
  113. }
  114. CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn);
  115. ADD_SERIALIZE_METHODS;
  116. template <typename Stream, typename Operation>
  117. inline void SerializationOp(Stream& s, Operation ser_action) {
  118. READWRITE(nValue);
  119. READWRITE(scriptPubKey);
  120. }
  121. void SetNull()
  122. {
  123. nValue = -1;
  124. scriptPubKey.clear();
  125. }
  126. bool IsNull() const
  127. {
  128. return (nValue == -1);
  129. }
  130. friend bool operator==(const CTxOut& a, const CTxOut& b)
  131. {
  132. return (a.nValue == b.nValue &&
  133. a.scriptPubKey == b.scriptPubKey);
  134. }
  135. friend bool operator!=(const CTxOut& a, const CTxOut& b)
  136. {
  137. return !(a == b);
  138. }
  139. std::string ToString() const;
  140. };
  141. struct CMutableTransaction;
  142. /**
  143. * Basic transaction serialization format:
  144. * - int32_t nVersion
  145. * - std::vector<CTxIn> vin
  146. * - std::vector<CTxOut> vout
  147. * - uint32_t nLockTime
  148. *
  149. * Extended transaction serialization format:
  150. * - int32_t nVersion
  151. * - unsigned char dummy = 0x00
  152. * - unsigned char flags (!= 0)
  153. * - std::vector<CTxIn> vin
  154. * - std::vector<CTxOut> vout
  155. * - if (flags & 1):
  156. * - CTxWitness wit;
  157. * - uint32_t nLockTime
  158. */
  159. template<typename Stream, typename TxType>
  160. inline void UnserializeTransaction(TxType& tx, Stream& s) {
  161. const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
  162. s >> tx.nVersion;
  163. unsigned char flags = 0;
  164. tx.vin.clear();
  165. tx.vout.clear();
  166. /* Try to read the vin. In case the dummy is there, this will be read as an empty vector. */
  167. s >> tx.vin;
  168. if (tx.vin.size() == 0 && fAllowWitness) {
  169. /* We read a dummy or an empty vin. */
  170. s >> flags;
  171. if (flags != 0) {
  172. s >> tx.vin;
  173. s >> tx.vout;
  174. }
  175. } else {
  176. /* We read a non-empty vin. Assume a normal vout follows. */
  177. s >> tx.vout;
  178. }
  179. if ((flags & 1) && fAllowWitness) {
  180. /* The witness flag is present, and we support witnesses. */
  181. flags ^= 1;
  182. for (size_t i = 0; i < tx.vin.size(); i++) {
  183. s >> tx.vin[i].scriptWitness.stack;
  184. }
  185. }
  186. if (flags) {
  187. /* Unknown flag in the serialization */
  188. throw std::ios_base::failure("Unknown transaction optional data");
  189. }
  190. s >> tx.nLockTime;
  191. }
  192. template<typename Stream, typename TxType>
  193. inline void SerializeTransaction(const TxType& tx, Stream& s) {
  194. const bool fAllowWitness = !(s.GetVersion() & SERIALIZE_TRANSACTION_NO_WITNESS);
  195. s << tx.nVersion;
  196. unsigned char flags = 0;
  197. // Consistency check
  198. if (fAllowWitness) {
  199. /* Check whether witnesses need to be serialized. */
  200. if (tx.HasWitness()) {
  201. flags |= 1;
  202. }
  203. }
  204. if (flags) {
  205. /* Use extended format in case witnesses are to be serialized. */
  206. std::vector<CTxIn> vinDummy;
  207. s << vinDummy;
  208. s << flags;
  209. }
  210. s << tx.vin;
  211. s << tx.vout;
  212. if (flags & 1) {
  213. for (size_t i = 0; i < tx.vin.size(); i++) {
  214. s << tx.vin[i].scriptWitness.stack;
  215. }
  216. }
  217. s << tx.nLockTime;
  218. }
  219. /** The basic transaction that is broadcasted on the network and contained in
  220. * blocks. A transaction can contain multiple inputs and outputs.
  221. */
  222. class CTransaction
  223. {
  224. public:
  225. // Default transaction version.
  226. static const int32_t CURRENT_VERSION=2;
  227. // Changing the default transaction version requires a two step process: first
  228. // adapting relay policy by bumping MAX_STANDARD_VERSION, and then later date
  229. // bumping the default CURRENT_VERSION at which point both CURRENT_VERSION and
  230. // MAX_STANDARD_VERSION will be equal.
  231. static const int32_t MAX_STANDARD_VERSION=2;
  232. // The local variables are made const to prevent unintended modification
  233. // without updating the cached hash value. However, CTransaction is not
  234. // actually immutable; deserialization and assignment are implemented,
  235. // and bypass the constness. This is safe, as they update the entire
  236. // structure, including the hash.
  237. const int32_t nVersion;
  238. const std::vector<CTxIn> vin;
  239. const std::vector<CTxOut> vout;
  240. const uint32_t nLockTime;
  241. private:
  242. /** Memory only. */
  243. const uint256 hash;
  244. uint256 ComputeHash() const;
  245. public:
  246. /** Construct a CTransaction that qualifies as IsNull() */
  247. CTransaction();
  248. /** Convert a CMutableTransaction into a CTransaction. */
  249. CTransaction(const CMutableTransaction &tx);
  250. CTransaction(CMutableTransaction &&tx);
  251. template <typename Stream>
  252. inline void Serialize(Stream& s) const {
  253. SerializeTransaction(*this, s);
  254. }
  255. /** This deserializing constructor is provided instead of an Unserialize method.
  256. * Unserialize is not possible, since it would require overwriting const fields. */
  257. template <typename Stream>
  258. CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}
  259. bool IsNull() const {
  260. return vin.empty() && vout.empty();
  261. }
  262. const uint256& GetHash() const {
  263. return hash;
  264. }
  265. // Compute a hash that includes both transaction and witness data
  266. uint256 GetWitnessHash() const;
  267. // Return sum of txouts.
  268. CAmount GetValueOut() const;
  269. // GetValueIn() is a method on CCoinsViewCache, because
  270. // inputs must be known to compute value in.
  271. /**
  272. * Get the total transaction size in bytes, including witness data.
  273. * "Total Size" defined in BIP141 and BIP144.
  274. * @return Total transaction size in bytes
  275. */
  276. unsigned int GetTotalSize() const;
  277. bool IsCoinBase() const
  278. {
  279. return (vin.size() == 1 && vin[0].prevout.IsNull());
  280. }
  281. friend bool operator==(const CTransaction& a, const CTransaction& b)
  282. {
  283. return a.hash == b.hash;
  284. }
  285. friend bool operator!=(const CTransaction& a, const CTransaction& b)
  286. {
  287. return a.hash != b.hash;
  288. }
  289. std::string ToString() const;
  290. bool HasWitness() const
  291. {
  292. for (size_t i = 0; i < vin.size(); i++) {
  293. if (!vin[i].scriptWitness.IsNull()) {
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. };
  300. /** A mutable version of CTransaction. */
  301. struct CMutableTransaction
  302. {
  303. int32_t nVersion;
  304. std::vector<CTxIn> vin;
  305. std::vector<CTxOut> vout;
  306. uint32_t nLockTime;
  307. CMutableTransaction();
  308. CMutableTransaction(const CTransaction& tx);
  309. template <typename Stream>
  310. inline void Serialize(Stream& s) const {
  311. SerializeTransaction(*this, s);
  312. }
  313. template <typename Stream>
  314. inline void Unserialize(Stream& s) {
  315. UnserializeTransaction(*this, s);
  316. }
  317. template <typename Stream>
  318. CMutableTransaction(deserialize_type, Stream& s) {
  319. Unserialize(s);
  320. }
  321. /** Compute the hash of this CMutableTransaction. This is computed on the
  322. * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
  323. */
  324. uint256 GetHash() const;
  325. friend bool operator==(const CMutableTransaction& a, const CMutableTransaction& b)
  326. {
  327. return a.GetHash() == b.GetHash();
  328. }
  329. bool HasWitness() const
  330. {
  331. for (size_t i = 0; i < vin.size(); i++) {
  332. if (!vin[i].scriptWitness.IsNull()) {
  333. return true;
  334. }
  335. }
  336. return false;
  337. }
  338. };
  339. typedef std::shared_ptr<const CTransaction> CTransactionRef;
  340. static inline CTransactionRef MakeTransactionRef() { return std::make_shared<const CTransaction>(); }
  341. template <typename Tx> static inline CTransactionRef MakeTransactionRef(Tx&& txIn) { return std::make_shared<const CTransaction>(std::forward<Tx>(txIn)); }
  342. #endif // STARWELS_PRIMITIVES_TRANSACTION_H