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.

core.h 16KB

estimatefee / estimatepriority RPC methods New RPC methods: return an estimate of the fee (or priority) a transaction needs to be likely to confirm in a given number of blocks. Mike Hearn created the first version of this method for estimating fees. It works as follows: For transactions that took 1 to N (I picked N=25) blocks to confirm, keep N buckets with at most 100 entries in each recording the fees-per-kilobyte paid by those transactions. (separate buckets are kept for transactions that confirmed because they are high-priority) The buckets are filled as blocks are found, and are saved/restored in a new fee_estiamtes.dat file in the data directory. A few variations on Mike's initial scheme: To estimate the fee needed for a transaction to confirm in X buckets, all of the samples in all of the buckets are used and a median of all of the data is used to make the estimate. For example, imagine 25 buckets each containing the full 100 entries. Those 2,500 samples are sorted, and the estimate of the fee needed to confirm in the very next block is the 50'th-highest-fee-entry in that sorted list; the estimate of the fee needed to confirm in the next two blocks is the 150'th-highest-fee-entry, etc. That algorithm has the nice property that estimates of how much fee you need to pay to get confirmed in block N will always be greater than or equal to the estimate for block N+1. It would clearly be wrong to say "pay 11 uBTC and you'll get confirmed in 3 blocks, but pay 12 uBTC and it will take LONGER". A single block will not contribute more than 10 entries to any one bucket, so a single miner and a large block cannot overwhelm the estimates.
7 years ago
estimatefee / estimatepriority RPC methods New RPC methods: return an estimate of the fee (or priority) a transaction needs to be likely to confirm in a given number of blocks. Mike Hearn created the first version of this method for estimating fees. It works as follows: For transactions that took 1 to N (I picked N=25) blocks to confirm, keep N buckets with at most 100 entries in each recording the fees-per-kilobyte paid by those transactions. (separate buckets are kept for transactions that confirmed because they are high-priority) The buckets are filled as blocks are found, and are saved/restored in a new fee_estiamtes.dat file in the data directory. A few variations on Mike's initial scheme: To estimate the fee needed for a transaction to confirm in X buckets, all of the samples in all of the buckets are used and a median of all of the data is used to make the estimate. For example, imagine 25 buckets each containing the full 100 entries. Those 2,500 samples are sorted, and the estimate of the fee needed to confirm in the very next block is the 50'th-highest-fee-entry in that sorted list; the estimate of the fee needed to confirm in the next two blocks is the 150'th-highest-fee-entry, etc. That algorithm has the nice property that estimates of how much fee you need to pay to get confirmed in block N will always be greater than or equal to the estimate for block N+1. It would clearly be wrong to say "pay 11 uBTC and you'll get confirmed in 3 blocks, but pay 12 uBTC and it will take LONGER". A single block will not contribute more than 10 entries to any one bucket, so a single miner and a large block cannot overwhelm the estimates.
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef BITCOIN_CORE_H
  6. #define BITCOIN_CORE_H
  7. #include "script.h"
  8. #include "serialize.h"
  9. #include "uint256.h"
  10. #include <stdint.h>
  11. class CTransaction;
  12. static const int64_t COIN = 100000000;
  13. static const int64_t CENT = 1000000;
  14. /** No amount larger than this (in satoshi) is valid */
  15. static const int64_t MAX_MONEY = 21000000 * COIN;
  16. inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
  17. /** An outpoint - a combination of a transaction hash and an index n into its vout */
  18. class COutPoint
  19. {
  20. public:
  21. uint256 hash;
  22. uint32_t n;
  23. COutPoint() { SetNull(); }
  24. COutPoint(uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; }
  25. ADD_SERIALIZE_METHODS;
  26. template <typename Stream, typename Operation>
  27. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  28. READWRITE(FLATDATA(*this));
  29. }
  30. void SetNull() { hash = 0; n = (uint32_t) -1; }
  31. bool IsNull() const { return (hash == 0 && n == (uint32_t) -1); }
  32. friend bool operator<(const COutPoint& a, const COutPoint& b)
  33. {
  34. return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
  35. }
  36. friend bool operator==(const COutPoint& a, const COutPoint& b)
  37. {
  38. return (a.hash == b.hash && a.n == b.n);
  39. }
  40. friend bool operator!=(const COutPoint& a, const COutPoint& b)
  41. {
  42. return !(a == b);
  43. }
  44. std::string ToString() const;
  45. };
  46. /** An inpoint - a combination of a transaction and an index n into its vin */
  47. class CInPoint
  48. {
  49. public:
  50. const CTransaction* ptx;
  51. uint32_t n;
  52. CInPoint() { SetNull(); }
  53. CInPoint(const CTransaction* ptxIn, uint32_t nIn) { ptx = ptxIn; n = nIn; }
  54. void SetNull() { ptx = NULL; n = (uint32_t) -1; }
  55. bool IsNull() const { return (ptx == NULL && n == (uint32_t) -1); }
  56. };
  57. /** An input of a transaction. It contains the location of the previous
  58. * transaction's output that it claims and a signature that matches the
  59. * output's public key.
  60. */
  61. class CTxIn
  62. {
  63. public:
  64. COutPoint prevout;
  65. CScript scriptSig;
  66. uint32_t nSequence;
  67. CTxIn()
  68. {
  69. nSequence = std::numeric_limits<unsigned int>::max();
  70. }
  71. explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max());
  72. CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=std::numeric_limits<uint32_t>::max());
  73. ADD_SERIALIZE_METHODS;
  74. template <typename Stream, typename Operation>
  75. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  76. READWRITE(prevout);
  77. READWRITE(scriptSig);
  78. READWRITE(nSequence);
  79. }
  80. bool IsFinal() const
  81. {
  82. return (nSequence == std::numeric_limits<uint32_t>::max());
  83. }
  84. friend bool operator==(const CTxIn& a, const CTxIn& b)
  85. {
  86. return (a.prevout == b.prevout &&
  87. a.scriptSig == b.scriptSig &&
  88. a.nSequence == b.nSequence);
  89. }
  90. friend bool operator!=(const CTxIn& a, const CTxIn& b)
  91. {
  92. return !(a == b);
  93. }
  94. std::string ToString() const;
  95. };
  96. /** Type-safe wrapper class to for fee rates
  97. * (how much to pay based on transaction size)
  98. */
  99. class CFeeRate
  100. {
  101. private:
  102. int64_t nSatoshisPerK; // unit is satoshis-per-1,000-bytes
  103. public:
  104. CFeeRate() : nSatoshisPerK(0) { }
  105. explicit CFeeRate(int64_t _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { }
  106. CFeeRate(int64_t nFeePaid, size_t nSize);
  107. CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; }
  108. int64_t GetFee(size_t size) const; // unit returned is satoshis
  109. int64_t GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes
  110. friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; }
  111. friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; }
  112. friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; }
  113. friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; }
  114. friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; }
  115. std::string ToString() const;
  116. ADD_SERIALIZE_METHODS;
  117. template <typename Stream, typename Operation>
  118. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  119. READWRITE(nSatoshisPerK);
  120. }
  121. };
  122. /** An output of a transaction. It contains the public key that the next input
  123. * must be able to sign with to claim it.
  124. */
  125. class CTxOut
  126. {
  127. public:
  128. int64_t nValue;
  129. CScript scriptPubKey;
  130. CTxOut()
  131. {
  132. SetNull();
  133. }
  134. CTxOut(int64_t nValueIn, CScript scriptPubKeyIn);
  135. ADD_SERIALIZE_METHODS;
  136. template <typename Stream, typename Operation>
  137. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  138. READWRITE(nValue);
  139. READWRITE(scriptPubKey);
  140. }
  141. void SetNull()
  142. {
  143. nValue = -1;
  144. scriptPubKey.clear();
  145. }
  146. bool IsNull() const
  147. {
  148. return (nValue == -1);
  149. }
  150. uint256 GetHash() const;
  151. bool IsDust(CFeeRate minRelayTxFee) const
  152. {
  153. // "Dust" is defined in terms of CTransaction::minRelayTxFee,
  154. // which has units satoshis-per-kilobyte.
  155. // If you'd pay more than 1/3 in fees
  156. // to spend something, then we consider it dust.
  157. // A typical txout is 34 bytes big, and will
  158. // need a CTxIn of at least 148 bytes to spend:
  159. // so dust is a txout less than 546 satoshis
  160. // with default minRelayTxFee.
  161. size_t nSize = GetSerializeSize(SER_DISK,0)+148u;
  162. return (nValue < 3*minRelayTxFee.GetFee(nSize));
  163. }
  164. friend bool operator==(const CTxOut& a, const CTxOut& b)
  165. {
  166. return (a.nValue == b.nValue &&
  167. a.scriptPubKey == b.scriptPubKey);
  168. }
  169. friend bool operator!=(const CTxOut& a, const CTxOut& b)
  170. {
  171. return !(a == b);
  172. }
  173. std::string ToString() const;
  174. };
  175. struct CMutableTransaction;
  176. /** The basic transaction that is broadcasted on the network and contained in
  177. * blocks. A transaction can contain multiple inputs and outputs.
  178. */
  179. class CTransaction
  180. {
  181. private:
  182. /** Memory only. */
  183. const uint256 hash;
  184. void UpdateHash() const;
  185. public:
  186. static const int32_t CURRENT_VERSION=1;
  187. // The local variables are made const to prevent unintended modification
  188. // without updating the cached hash value. However, CTransaction is not
  189. // actually immutable; deserialization and assignment are implemented,
  190. // and bypass the constness. This is safe, as they update the entire
  191. // structure, including the hash.
  192. const int32_t nVersion;
  193. const std::vector<CTxIn> vin;
  194. const std::vector<CTxOut> vout;
  195. const uint32_t nLockTime;
  196. /** Construct a CTransaction that qualifies as IsNull() */
  197. CTransaction();
  198. /** Convert a CMutableTransaction into a CTransaction. */
  199. CTransaction(const CMutableTransaction &tx);
  200. CTransaction& operator=(const CTransaction& tx);
  201. ADD_SERIALIZE_METHODS;
  202. template <typename Stream, typename Operation>
  203. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  204. READWRITE(*const_cast<int32_t*>(&this->nVersion));
  205. nVersion = this->nVersion;
  206. READWRITE(*const_cast<std::vector<CTxIn>*>(&vin));
  207. READWRITE(*const_cast<std::vector<CTxOut>*>(&vout));
  208. READWRITE(*const_cast<uint32_t*>(&nLockTime));
  209. if (ser_action.ForRead())
  210. UpdateHash();
  211. }
  212. bool IsNull() const {
  213. return vin.empty() && vout.empty();
  214. }
  215. const uint256& GetHash() const {
  216. return hash;
  217. }
  218. // Return sum of txouts.
  219. int64_t GetValueOut() const;
  220. // GetValueIn() is a method on CCoinsViewCache, because
  221. // inputs must be known to compute value in.
  222. // Compute priority, given priority of inputs and (optionally) tx size
  223. double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const;
  224. bool IsCoinBase() const
  225. {
  226. return (vin.size() == 1 && vin[0].prevout.IsNull());
  227. }
  228. friend bool operator==(const CTransaction& a, const CTransaction& b)
  229. {
  230. return a.hash == b.hash;
  231. }
  232. friend bool operator!=(const CTransaction& a, const CTransaction& b)
  233. {
  234. return a.hash != b.hash;
  235. }
  236. std::string ToString() const;
  237. };
  238. /** A mutable version of CTransaction. */
  239. struct CMutableTransaction
  240. {
  241. int32_t nVersion;
  242. std::vector<CTxIn> vin;
  243. std::vector<CTxOut> vout;
  244. uint32_t nLockTime;
  245. CMutableTransaction();
  246. CMutableTransaction(const CTransaction& tx);
  247. ADD_SERIALIZE_METHODS;
  248. template <typename Stream, typename Operation>
  249. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  250. READWRITE(this->nVersion);
  251. nVersion = this->nVersion;
  252. READWRITE(vin);
  253. READWRITE(vout);
  254. READWRITE(nLockTime);
  255. }
  256. /** Compute the hash of this CMutableTransaction. This is computed on the
  257. * fly, as opposed to GetHash() in CTransaction, which uses a cached result.
  258. */
  259. uint256 GetHash() const;
  260. };
  261. /** wrapper for CTxOut that provides a more compact serialization */
  262. class CTxOutCompressor
  263. {
  264. private:
  265. CTxOut &txout;
  266. public:
  267. static uint64_t CompressAmount(uint64_t nAmount);
  268. static uint64_t DecompressAmount(uint64_t nAmount);
  269. CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
  270. ADD_SERIALIZE_METHODS;
  271. template <typename Stream, typename Operation>
  272. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  273. if (!ser_action.ForRead()) {
  274. uint64_t nVal = CompressAmount(txout.nValue);
  275. READWRITE(VARINT(nVal));
  276. } else {
  277. uint64_t nVal = 0;
  278. READWRITE(VARINT(nVal));
  279. txout.nValue = DecompressAmount(nVal);
  280. }
  281. CScriptCompressor cscript(REF(txout.scriptPubKey));
  282. READWRITE(cscript);
  283. }
  284. };
  285. /** Undo information for a CTxIn
  286. *
  287. * Contains the prevout's CTxOut being spent, and if this was the
  288. * last output of the affected transaction, its metadata as well
  289. * (coinbase or not, height, transaction version)
  290. */
  291. class CTxInUndo
  292. {
  293. public:
  294. CTxOut txout; // the txout data before being spent
  295. bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
  296. unsigned int nHeight; // if the outpoint was the last unspent: its height
  297. int nVersion; // if the outpoint was the last unspent: its version
  298. CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
  299. CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
  300. unsigned int GetSerializeSize(int nType, int nVersion) const {
  301. return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
  302. (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
  303. ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
  304. }
  305. template<typename Stream>
  306. void Serialize(Stream &s, int nType, int nVersion) const {
  307. ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
  308. if (nHeight > 0)
  309. ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
  310. ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
  311. }
  312. template<typename Stream>
  313. void Unserialize(Stream &s, int nType, int nVersion) {
  314. unsigned int nCode = 0;
  315. ::Unserialize(s, VARINT(nCode), nType, nVersion);
  316. nHeight = nCode / 2;
  317. fCoinBase = nCode & 1;
  318. if (nHeight > 0)
  319. ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
  320. ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
  321. }
  322. };
  323. /** Undo information for a CTransaction */
  324. class CTxUndo
  325. {
  326. public:
  327. // undo information for all txins
  328. std::vector<CTxInUndo> vprevout;
  329. ADD_SERIALIZE_METHODS;
  330. template <typename Stream, typename Operation>
  331. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  332. READWRITE(vprevout);
  333. }
  334. };
  335. /** Nodes collect new transactions into a block, hash them into a hash tree,
  336. * and scan through nonce values to make the block's hash satisfy proof-of-work
  337. * requirements. When they solve the proof-of-work, they broadcast the block
  338. * to everyone and the block is added to the block chain. The first transaction
  339. * in the block is a special one that creates a new coin owned by the creator
  340. * of the block.
  341. */
  342. class CBlockHeader
  343. {
  344. public:
  345. // header
  346. static const int32_t CURRENT_VERSION=2;
  347. int32_t nVersion;
  348. uint256 hashPrevBlock;
  349. uint256 hashMerkleRoot;
  350. uint32_t nTime;
  351. uint32_t nBits;
  352. uint32_t nNonce;
  353. CBlockHeader()
  354. {
  355. SetNull();
  356. }
  357. ADD_SERIALIZE_METHODS;
  358. template <typename Stream, typename Operation>
  359. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  360. READWRITE(this->nVersion);
  361. nVersion = this->nVersion;
  362. READWRITE(hashPrevBlock);
  363. READWRITE(hashMerkleRoot);
  364. READWRITE(nTime);
  365. READWRITE(nBits);
  366. READWRITE(nNonce);
  367. }
  368. void SetNull()
  369. {
  370. nVersion = CBlockHeader::CURRENT_VERSION;
  371. hashPrevBlock = 0;
  372. hashMerkleRoot = 0;
  373. nTime = 0;
  374. nBits = 0;
  375. nNonce = 0;
  376. }
  377. bool IsNull() const
  378. {
  379. return (nBits == 0);
  380. }
  381. uint256 GetHash() const;
  382. int64_t GetBlockTime() const
  383. {
  384. return (int64_t)nTime;
  385. }
  386. };
  387. class CBlock : public CBlockHeader
  388. {
  389. public:
  390. // network and disk
  391. std::vector<CTransaction> vtx;
  392. // memory only
  393. mutable std::vector<uint256> vMerkleTree;
  394. CBlock()
  395. {
  396. SetNull();
  397. }
  398. CBlock(const CBlockHeader &header)
  399. {
  400. SetNull();
  401. *((CBlockHeader*)this) = header;
  402. }
  403. ADD_SERIALIZE_METHODS;
  404. template <typename Stream, typename Operation>
  405. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  406. READWRITE(*(CBlockHeader*)this);
  407. READWRITE(vtx);
  408. }
  409. void SetNull()
  410. {
  411. CBlockHeader::SetNull();
  412. vtx.clear();
  413. vMerkleTree.clear();
  414. }
  415. CBlockHeader GetBlockHeader() const
  416. {
  417. CBlockHeader block;
  418. block.nVersion = nVersion;
  419. block.hashPrevBlock = hashPrevBlock;
  420. block.hashMerkleRoot = hashMerkleRoot;
  421. block.nTime = nTime;
  422. block.nBits = nBits;
  423. block.nNonce = nNonce;
  424. return block;
  425. }
  426. uint256 BuildMerkleTree() const;
  427. std::vector<uint256> GetMerkleBranch(int nIndex) const;
  428. static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
  429. std::string ToString() const;
  430. };
  431. /** Describes a place in the block chain to another node such that if the
  432. * other node doesn't have the same branch, it can find a recent common trunk.
  433. * The further back it is, the further before the fork it may be.
  434. */
  435. struct CBlockLocator
  436. {
  437. std::vector<uint256> vHave;
  438. CBlockLocator() {}
  439. CBlockLocator(const std::vector<uint256>& vHaveIn)
  440. {
  441. vHave = vHaveIn;
  442. }
  443. ADD_SERIALIZE_METHODS;
  444. template <typename Stream, typename Operation>
  445. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  446. if (!(nType & SER_GETHASH))
  447. READWRITE(nVersion);
  448. READWRITE(vHave);
  449. }
  450. void SetNull()
  451. {
  452. vHave.clear();
  453. }
  454. bool IsNull()
  455. {
  456. return vHave.empty();
  457. }
  458. };
  459. #endif // BITCOIN_CORE_H