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.cpp 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 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. #include "core.h"
  6. #include "hash.h"
  7. #include "tinyformat.h"
  8. #include "utilstrencodings.h"
  9. std::string COutPoint::ToString() const
  10. {
  11. return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
  12. }
  13. CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn)
  14. {
  15. prevout = prevoutIn;
  16. scriptSig = scriptSigIn;
  17. nSequence = nSequenceIn;
  18. }
  19. CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn)
  20. {
  21. prevout = COutPoint(hashPrevTx, nOut);
  22. scriptSig = scriptSigIn;
  23. nSequence = nSequenceIn;
  24. }
  25. std::string CTxIn::ToString() const
  26. {
  27. std::string str;
  28. str += "CTxIn(";
  29. str += prevout.ToString();
  30. if (prevout.IsNull())
  31. str += strprintf(", coinbase %s", HexStr(scriptSig));
  32. else
  33. str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24));
  34. if (nSequence != std::numeric_limits<unsigned int>::max())
  35. str += strprintf(", nSequence=%u", nSequence);
  36. str += ")";
  37. return str;
  38. }
  39. CTxOut::CTxOut(const CAmount& nValueIn, CScript scriptPubKeyIn)
  40. {
  41. nValue = nValueIn;
  42. scriptPubKey = scriptPubKeyIn;
  43. }
  44. uint256 CTxOut::GetHash() const
  45. {
  46. return SerializeHash(*this);
  47. }
  48. std::string CTxOut::ToString() const
  49. {
  50. return strprintf("CTxOut(nValue=%d.%08d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30));
  51. }
  52. CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize)
  53. {
  54. if (nSize > 0)
  55. nSatoshisPerK = nFeePaid*1000/nSize;
  56. else
  57. nSatoshisPerK = 0;
  58. }
  59. CAmount CFeeRate::GetFee(size_t nSize) const
  60. {
  61. CAmount nFee = nSatoshisPerK*nSize / 1000;
  62. if (nFee == 0 && nSatoshisPerK > 0)
  63. nFee = nSatoshisPerK;
  64. return nFee;
  65. }
  66. std::string CFeeRate::ToString() const
  67. {
  68. return strprintf("%d.%08d BTC/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN);
  69. }
  70. CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {}
  71. CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {}
  72. uint256 CMutableTransaction::GetHash() const
  73. {
  74. return SerializeHash(*this);
  75. }
  76. void CTransaction::UpdateHash() const
  77. {
  78. *const_cast<uint256*>(&hash) = SerializeHash(*this);
  79. }
  80. CTransaction::CTransaction() : hash(0), nVersion(CTransaction::CURRENT_VERSION), vin(), vout(), nLockTime(0) { }
  81. CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime) {
  82. UpdateHash();
  83. }
  84. CTransaction& CTransaction::operator=(const CTransaction &tx) {
  85. *const_cast<int*>(&nVersion) = tx.nVersion;
  86. *const_cast<std::vector<CTxIn>*>(&vin) = tx.vin;
  87. *const_cast<std::vector<CTxOut>*>(&vout) = tx.vout;
  88. *const_cast<unsigned int*>(&nLockTime) = tx.nLockTime;
  89. *const_cast<uint256*>(&hash) = tx.hash;
  90. return *this;
  91. }
  92. CAmount CTransaction::GetValueOut() const
  93. {
  94. CAmount nValueOut = 0;
  95. for (std::vector<CTxOut>::const_iterator it(vout.begin()); it != vout.end(); ++it)
  96. {
  97. nValueOut += it->nValue;
  98. if (!MoneyRange(it->nValue) || !MoneyRange(nValueOut))
  99. throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
  100. }
  101. return nValueOut;
  102. }
  103. double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const
  104. {
  105. nTxSize = CalculateModifiedSize(nTxSize);
  106. if (nTxSize == 0) return 0.0;
  107. return dPriorityInputs / nTxSize;
  108. }
  109. unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const
  110. {
  111. // In order to avoid disincentivizing cleaning up the UTXO set we don't count
  112. // the constant overhead for each txin and up to 110 bytes of scriptSig (which
  113. // is enough to cover a compressed pubkey p2sh redemption) for priority.
  114. // Providing any more cleanup incentive than making additional inputs free would
  115. // risk encouraging people to create junk outputs to redeem later.
  116. if (nTxSize == 0)
  117. nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
  118. for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it)
  119. {
  120. unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size());
  121. if (nTxSize > offset)
  122. nTxSize -= offset;
  123. }
  124. return nTxSize;
  125. }
  126. std::string CTransaction::ToString() const
  127. {
  128. std::string str;
  129. str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
  130. GetHash().ToString().substr(0,10),
  131. nVersion,
  132. vin.size(),
  133. vout.size(),
  134. nLockTime);
  135. for (unsigned int i = 0; i < vin.size(); i++)
  136. str += " " + vin[i].ToString() + "\n";
  137. for (unsigned int i = 0; i < vout.size(); i++)
  138. str += " " + vout[i].ToString() + "\n";
  139. return str;
  140. }
  141. // Amount compression:
  142. // * If the amount is 0, output 0
  143. // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
  144. // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
  145. // * call the result n
  146. // * output 1 + 10*(9*n + d - 1) + e
  147. // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
  148. // (this is decodable, as d is in [1-9] and e is in [0-9])
  149. uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
  150. {
  151. if (n == 0)
  152. return 0;
  153. int e = 0;
  154. while (((n % 10) == 0) && e < 9) {
  155. n /= 10;
  156. e++;
  157. }
  158. if (e < 9) {
  159. int d = (n % 10);
  160. assert(d >= 1 && d <= 9);
  161. n /= 10;
  162. return 1 + (n*9 + d - 1)*10 + e;
  163. } else {
  164. return 1 + (n - 1)*10 + 9;
  165. }
  166. }
  167. uint64_t CTxOutCompressor::DecompressAmount(uint64_t x)
  168. {
  169. // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
  170. if (x == 0)
  171. return 0;
  172. x--;
  173. // x = 10*(9*n + d - 1) + e
  174. int e = x % 10;
  175. x /= 10;
  176. uint64_t n = 0;
  177. if (e < 9) {
  178. // x = 9*n + d - 1
  179. int d = (x % 9) + 1;
  180. x /= 9;
  181. // x = n
  182. n = x*10 + d;
  183. } else {
  184. n = x+1;
  185. }
  186. while (e) {
  187. n *= 10;
  188. e--;
  189. }
  190. return n;
  191. }
  192. uint256 CBlockHeader::GetHash() const
  193. {
  194. return Hash(BEGIN(nVersion), END(nNonce));
  195. }
  196. uint256 CBlock::BuildMerkleTree(bool* fMutated) const
  197. {
  198. /* WARNING! If you're reading this because you're learning about crypto
  199. and/or designing a new system that will use merkle trees, keep in mind
  200. that the following merkle tree algorithm has a serious flaw related to
  201. duplicate txids, resulting in a vulnerability (CVE-2012-2459).
  202. The reason is that if the number of hashes in the list at a given time
  203. is odd, the last one is duplicated before computing the next level (which
  204. is unusual in Merkle trees). This results in certain sequences of
  205. transactions leading to the same merkle root. For example, these two
  206. trees:
  207. A A
  208. / \ / \
  209. B C B C
  210. / \ | / \ / \
  211. D E F D E F F
  212. / \ / \ / \ / \ / \ / \ / \
  213. 1 2 3 4 5 6 1 2 3 4 5 6 5 6
  214. for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
  215. 6 are repeated) result in the same root hash A (because the hash of both
  216. of (F) and (F,F) is C).
  217. The vulnerability results from being able to send a block with such a
  218. transaction list, with the same merkle root, and the same block hash as
  219. the original without duplication, resulting in failed validation. If the
  220. receiving node proceeds to mark that block as permanently invalid
  221. however, it will fail to accept further unmodified (and thus potentially
  222. valid) versions of the same block. We defend against this by detecting
  223. the case where we would hash two identical hashes at the end of the list
  224. together, and treating that identically to the block having an invalid
  225. merkle root. Assuming no double-SHA256 collisions, this will detect all
  226. known ways of changing the transactions without affecting the merkle
  227. root.
  228. */
  229. vMerkleTree.clear();
  230. vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
  231. for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
  232. vMerkleTree.push_back(it->GetHash());
  233. int j = 0;
  234. bool mutated = false;
  235. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  236. {
  237. for (int i = 0; i < nSize; i += 2)
  238. {
  239. int i2 = std::min(i+1, nSize-1);
  240. if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
  241. // Two identical hashes at the end of the list at a particular level.
  242. mutated = true;
  243. }
  244. vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
  245. BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
  246. }
  247. j += nSize;
  248. }
  249. if (fMutated) {
  250. *fMutated = mutated;
  251. }
  252. return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
  253. }
  254. std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
  255. {
  256. if (vMerkleTree.empty())
  257. BuildMerkleTree();
  258. std::vector<uint256> vMerkleBranch;
  259. int j = 0;
  260. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  261. {
  262. int i = std::min(nIndex^1, nSize-1);
  263. vMerkleBranch.push_back(vMerkleTree[j+i]);
  264. nIndex >>= 1;
  265. j += nSize;
  266. }
  267. return vMerkleBranch;
  268. }
  269. uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
  270. {
  271. if (nIndex == -1)
  272. return 0;
  273. for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it)
  274. {
  275. if (nIndex & 1)
  276. hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
  277. else
  278. hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
  279. nIndex >>= 1;
  280. }
  281. return hash;
  282. }
  283. std::string CBlock::ToString() const
  284. {
  285. std::stringstream s;
  286. s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
  287. GetHash().ToString(),
  288. nVersion,
  289. hashPrevBlock.ToString(),
  290. hashMerkleRoot.ToString(),
  291. nTime, nBits, nNonce,
  292. vtx.size());
  293. for (unsigned int i = 0; i < vtx.size(); i++)
  294. {
  295. s << " " << vtx[i].ToString() << "\n";
  296. }
  297. s << " vMerkleTree: ";
  298. for (unsigned int i = 0; i < vMerkleTree.size(); i++)
  299. s << " " << vMerkleTree[i].ToString();
  300. s << "\n";
  301. return s.str();
  302. }