PRCYCoin  2.0.0.7rc1
P2P Digital Currency
main.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2018 The PIVX developers
5 // Copyright (c) 2018-2020 The DAPS Project developers
6 // Distributed under the MIT software license, see the accompanying
7 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 
9 #include "main.h"
10 
11 #include "addrman.h"
12 #include "amount.h"
13 #include "blocksignature.h"
14 #include "chainparams.h"
15 #include "checkpoints.h"
16 #include "checkqueue.h"
17 #include "consensus/merkle.h"
18 #include "consensus/tx_verify.h"
19 #include "consensus/validation.h"
20 #include "fs.h"
21 #include "init.h"
22 #include "invalid.h"
23 #include "kernel.h"
24 #include "masternode-budget.h"
25 #include "masternode-payments.h"
26 #include "masternode-sync.h"
27 #include "masternodeman.h"
28 #include "merkleblock.h"
29 #include "net.h"
30 #include "poa.h"
31 #include "swifttx.h"
32 #include "txdb.h"
33 #include "txmempool.h"
34 #include "guiinterface.h"
35 #include "util.h"
36 #include "utilmoneystr.h"
37 #include "validationinterface.h"
38 
39 #include <sstream>
40 
41 #include <boost/algorithm/string/replace.hpp>
42 #include <boost/foreach.hpp>
43 #include <boost/thread.hpp>
44 
45 
46 #if defined(NDEBUG)
47 #error "PRCY cannot be compiled without assertions."
48 #endif
49 
66 
68 std::map<uint256, uint256> mapProofOfStake;
69 std::map<unsigned int, unsigned int> mapHashedBlocks;
72 int64_t nTimeBestReceived = 0;
73 
74 // Best block section
76 std::condition_variable g_best_block_cv;
78 
80 std::atomic<bool> fImporting{false};
81 std::atomic<bool> fReindex{false};
82 bool fTxIndex = true;
83 bool fIsBareMultisigStd = true;
84 bool fCheckBlockIndex = false;
85 bool fVerifyingBlocks = false;
86 size_t nCoinCacheUsage = 5000 * 300;
87 
88 /* If the tip is older than this (in seconds), the node is considered to be in initial block download. */
89 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
90 
93 const int MAX_TX_INPUTS = 50;
95 
101 
103 
104 struct COrphanTx {
107 };
108 std::map<uint256, COrphanTx> mapOrphanTransactions;
109 std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev;
110 std::map<uint256, int64_t> mapRejectedBlocks;
111 
112 void EraseOrphansFor(NodeId peer);
113 
114 static void CheckBlockIndex();
115 
118 
119 const std::string strMessageMagic = "DarkNet Signed Message:\n";
120 
121 // Internal stuff
122 namespace
123 {
124 struct CBlockIndexWorkComparator {
125  bool operator()(CBlockIndex* pa, CBlockIndex* pb) const
126  {
127  // First sort by most total work, ...
128  if (pa->nChainWork > pb->nChainWork) return false;
129  if (pa->nChainWork < pb->nChainWork) return true;
130 
131  // ... then by earliest time received, ...
132  if (pa->nSequenceId < pb->nSequenceId) return false;
133  if (pa->nSequenceId > pb->nSequenceId) return true;
134 
135  // Use pointer address as tie breaker (should only happen with blocks
136  // loaded from disk, as those all have id 0).
137  if (pa < pb) return false;
138  if (pa > pb) return true;
139 
140  // Identical blocks.
141  return false;
142  }
143 };
144 
145 CBlockIndex* pindexBestInvalid;
146 
151 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
153 int nSyncStarted = 0;
155 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
156 
157 RecursiveMutex cs_LastBlockFile;
158 std::vector<CBlockFileInfo> vinfoBlockFile;
159 int nLastBlockFile = 0;
160 
165 RecursiveMutex cs_nBlockSequenceId;
167 uint32_t nBlockSequenceId = 1;
168 
173 std::map<uint256, NodeId> mapBlockSource;
174 
195 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
196 uint256 hashRecentRejectsChainTip;
197 
199 struct QueuedBlock {
200  uint256 hash;
201  CBlockIndex* pindex;
202  int64_t nTime;
203  int nValidatedQueuedBefore;
204  bool fValidatedHeaders;
205 };
206 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
207 
209 int nQueuedValidatedHeaders = 0;
210 
212 int nPreferredDownload = 0;
213 
215 std::set<CBlockIndex*> setDirtyBlockIndex;
216 
218 std::set<int> setDirtyFileInfo;
219 } // namespace
220 
222 {
223  if (tx.IsCoinBase())
224  return 0;
225 
226  CAmount nResult = 0;
227 
228  if (tx.IsCoinStake()) {
229  for (unsigned int i = 0; i < tx.vin.size(); i++) {
230  CAmount nValueIn; // = txPrev.vout[prevout.n].nValue;
231  uint256 hashBlock;
232  CTransaction txPrev;
233  GetTransaction(tx.vin[i].prevout.hash, txPrev, hashBlock, true);
234  const CTxOut& out = txPrev.vout[tx.vin[i].prevout.n];
235  if (out.nValue > 0) {
236  nResult += out.nValue;
237  } else {
238  uint256 val = out.maskValue.amount;
239  uint256 mask = out.maskValue.mask;
240  CKey decodedMask;
241  CPubKey sharedSec;
242  sharedSec.Set(tx.vin[i].encryptionKey.begin(), tx.vin[i].encryptionKey.begin() + 33);
243  ECDHInfo::Decode(mask.begin(), val.begin(), sharedSec, decodedMask, nValueIn);
244  //Verify commitment
245  std::vector<unsigned char> commitment;
246  CWallet::CreateCommitment(decodedMask.begin(), nValueIn, commitment);
247  if (commitment != out.commitment) {
248  throw std::runtime_error("Commitment for coinstake not correct");
249  }
250  nResult += nValueIn;
251  }
252  }
253  }
254 
255  return nResult;
256 }
257 
259 double GetPriority(const CTransaction& tx, int nHeight)
260 {
261  if (tx.IsCoinBase() || tx.IsCoinStake())
262  return 0.0;
263  double dResult = 0.0;
264  /*for (const CTxIn& txin: tx.vin) {
265  std::vector<COutPoint> alldecoys = txin.decoys;
266  alldecoys.push_back(txin.prevout);
267  for (size_t j = 0; j < alldecoys.size(); j++) {
268  CTransaction prev;
269  uint256 bh;
270  if (!GetTransaction(alldecoys[j].hash, prev, bh, true)) {
271  return false;
272  }
273 
274  if (mapBlockIndex.count(bh) < 1) continue;
275  if (mapBlockIndex[bh]->nHeight < nHeight) {
276  dResult += 1000 * COIN * (nHeight - mapBlockIndex[bh]->nHeight);
277  }
278  }
279  }*/
280  return 1000000000 + tx.ComputePriority(dResult);
281 }
282 
283 bool IsSpentKeyImage(const std::string& kiHex, const uint256& againsHash)
284 {
285  if (kiHex.empty()) return false;
286  std::vector<uint256> bhs;
287  if (!pblocktree->ReadKeyImages(kiHex, bhs)) {
288  //not spent yet because not found in database
289  return false;
290  }
291  if (bhs.empty()) {
292  return false;
293  }
294  for (int i = 0; i < bhs.size(); i++) {
295  uint256 bh = bhs[i];
296  if (againsHash.IsNull()) {
297  //check if bh is in main chain
298  // Find the block it claims to be in
299  BlockMap::iterator mi = mapBlockIndex.find(bh);
300  if (mi == mapBlockIndex.end())
301  continue;
302  CBlockIndex* pindex = (*mi).second;
303  if (pindex && chainActive.Contains(pindex))
304  return true;
305  continue; //receive from mempool
306  } else {
307  if (bh == againsHash && !againsHash.IsNull()) return false;
308 
309  //check whether bh and againsHash is in the same fork
310  if (mapBlockIndex.count(bh) < 1) continue;
311  CBlockIndex* pindex = mapBlockIndex[againsHash];
312  CBlockIndex* bhIndex = mapBlockIndex[bh];
313  CBlockIndex* ancestor = pindex->GetAncestor(bhIndex->nHeight);
314  if (ancestor == bhIndex) return true;
315  }
316  }
317  return false;
318 }
319 
320 bool CheckKeyImageSpendInMainChain(const std::string& kiHex, int& confirmations)
321 {
322  confirmations = 0;
323  if (kiHex.empty()) return false;
324  std::vector<uint256> bhs;
325  if (!pblocktree->ReadKeyImages(kiHex, bhs)) {
326  //not spent yet because not found in database
327  return false;
328  }
329  if (bhs.empty()) {
330  return false;
331  }
332  for (int i = 0; i < bhs.size(); i++) {
333  uint256 bh = bhs[i];
334  //check if bh is in main chain
335  // Find the block it claims to be in
336  BlockMap::iterator mi = mapBlockIndex.find(bh);
337  if (mi == mapBlockIndex.end())
338  continue;
339  CBlockIndex* pindex = (*mi).second;
340  if (pindex && chainActive.Contains(pindex)) {
341  confirmations = 1 + chainActive.Height() - pindex->nHeight;
342  return true;
343  }
344  }
345  return false;
346 }
347 
349 {
350  static secp256k1_context2* both;
352  return both;
353 }
354 
356 {
357  static secp256k1_scratch_space2* scratch;
358  if (!scratch) scratch = secp256k1_scratch_space_create(GetContext(), 1024 * 1024 * 512);
359  return scratch;
360 }
361 
363 {
364  static secp256k1_bulletproof_generators* generator;
366  return generator;
367 }
368 
370 {
374 }
375 
377 {
378  if (IsInitialBlockDownload()) return true;
379  size_t len = tx.bulletproofs.size();
380  if (tx.vout.size() >= 5) return false;
381 
382  if (len == 0) return false;
383  const size_t MAX_VOUT = 5;
384  secp256k1_pedersen_commitment commitments[MAX_VOUT];
385  size_t i = 0;
386  for (i = 0; i < tx.vout.size(); i++) {
387  if (!secp256k1_pedersen_commitment_parse(GetContext(), &commitments[i], &(tx.vout[i].commitment[0])))
388  throw std::runtime_error("Failed to parse pedersen commitment");
389  }
390  return secp256k1_bulletproof_rangeproof_verify(GetContext(), GetScratch(), GetGenerator(), &(tx.bulletproofs[0]), len, NULL, commitments, tx.vout.size(), 64, &secp256k1_generator_const_h, NULL, 0);
391 }
392 
394 {
395  if (tx.nTxFee < 0) return false;
396  if (IsInitialBlockDownload()) return true;
397  const size_t MAX_VIN = MAX_TX_INPUTS;
398  SetRingSize(pindex->nHeight);
399  const size_t MAX_DECOYS = MAX_RING_SIZE; //padding 1 for safety reasons
400  const size_t MAX_VOUT = 5;
401 
402  if (tx.vin.size() > MAX_VIN) {
403  LogPrintf("Tx input too many\n");
404  return false;
405  }
406  for (size_t i = 1; i < tx.vin.size(); i++) {
407  if (tx.vin[i].decoys.size() != tx.vin[0].decoys.size()) {
408  LogPrintf("The number of decoys not equal for all inputs, input %d has %d decoys but input 0 has only %d\n", i, tx.vin[i].decoys.size(), tx.vin[0].decoys.size());
409  return false;
410  }
411  }
412  if (tx.vin.size() == 0) {
413  LogPrintf("Transaction %s has no inputs\n", tx.GetHash().GetHex());
414  return false;
415  }
416 
417  if (tx.vin[0].decoys.size() > MAX_DECOYS || tx.vin[0].decoys.size() < MIN_RING_SIZE) {
418  LogPrintf("The number of decoys RingSize %d not within range [%d, %d]\n", tx.vin[0].decoys.size(), MIN_RING_SIZE, MAX_RING_SIZE);
419  return false; //maximum decoys = 15
420  }
421 
422  unsigned char allInPubKeys[MAX_VIN + 1][MAX_DECOYS + 1][33];
423  unsigned char allKeyImages[MAX_VIN + 1][33];
424  unsigned char allInCommitments[MAX_VIN][MAX_DECOYS + 1][33];
425  unsigned char allOutCommitments[MAX_VOUT][33];
426 
427  unsigned char SIJ[MAX_VIN + 1][MAX_DECOYS + 1][32];
428  unsigned char LIJ[MAX_VIN + 1][MAX_DECOYS + 1][33];
429  unsigned char RIJ[MAX_VIN + 1][MAX_DECOYS + 1][33];
430 
431  secp256k1_context2* both = GetContext();
432 
433  //generating LIJ and RIJ at PI
434  for (size_t j = 0; j < tx.vin.size(); j++) {
435  memcpy(allKeyImages[j], tx.vin[j].keyImage.begin(), 33);
436  }
437 
438  //extract all public keys
439  for (size_t i = 0; i < tx.vin.size(); i++) {
440  std::vector<COutPoint> decoysForIn;
441  decoysForIn.push_back(tx.vin[i].prevout);
442  for (size_t j = 0; j < tx.vin[i].decoys.size(); j++) {
443  decoysForIn.push_back(tx.vin[i].decoys[j]);
444  }
445  for (size_t j = 0; j < tx.vin[0].decoys.size() + 1; j++) {
446  CTransaction txPrev;
447  uint256 hashBlock;
448  if (!GetTransaction(decoysForIn[j].hash, txPrev, hashBlock)) {
449  LogPrintf("Failed to find transaction %s\n", decoysForIn[j].hash.GetHex());
450  return false;
451  }
452  CBlockIndex* tip = chainActive.Tip();
453  if (!pindex) tip = pindex;
454 
455  uint256 hashTip = tip->GetBlockHash();
456  //verify that tip and hashBlock must be in the same fork
457  CBlockIndex* atTheblock = mapBlockIndex[hashBlock];
458  if (!atTheblock) {
459  LogPrintf("%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, decoysForIn[j].hash.GetHex(), tip->nHeight, tip->GetBlockHash().GetHex());
460  return false;
461  } else {
462  CBlockIndex* ancestor = tip->GetAncestor(atTheblock->nHeight);
463  if (ancestor != atTheblock) {
464  LogPrintf("%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, decoysForIn[j].hash.GetHex(), tip->nHeight, tip->GetBlockHash().GetHex());
465  return false;
466  }
467  }
468 
469  CPubKey extractedPub;
470  if (!ExtractPubKey(txPrev.vout[decoysForIn[j].n].scriptPubKey, extractedPub)) {
471  LogPrintf("Failed to extract pubkey\n");
472  return false;
473  }
474  memcpy(allInPubKeys[i][j], extractedPub.begin(), 33);
475  memcpy(allInCommitments[i][j], &(txPrev.vout[decoysForIn[j].n].commitment[0]), 33);
476  }
477  }
478  memcpy(allKeyImages[tx.vin.size()], tx.ntxFeeKeyImage.begin(), 33);
479 
480  for (size_t i = 0; i < tx.vin[0].decoys.size() + 1; i++) {
481  std::vector<uint256> S_column = tx.S[i];
482  for (size_t j = 0; j < tx.vin.size() + 1; j++) {
483  memcpy(SIJ[j][i], S_column[j].begin(), 32);
484  }
485  }
486 
487  //compute allInPubKeys[tx.vin.size()][..]
488  secp256k1_pedersen_commitment allInCommitmentsPacked[MAX_VIN][MAX_DECOYS + 1];
489  secp256k1_pedersen_commitment allOutCommitmentsPacked[MAX_VOUT + 1]; //+1 for tx fee
490 
491  for (size_t i = 0; i < tx.vout.size(); i++) {
492  if (tx.vout[i].commitment.empty()) {
493  LogPrintf("Commitment can not be null\n");
494  return false;
495  }
496  memcpy(allOutCommitments[i], &(tx.vout[i].commitment[0]), 33);
497  if (!secp256k1_pedersen_commitment_parse(both, &allOutCommitmentsPacked[i], allOutCommitments[i])) {
498  LogPrintf("Failed to parse commitment\n");
499  return false;
500  }
501  }
502 
503  //commitment to tx fee, blind = 0
504  unsigned char txFeeBlind[32];
505  memset(txFeeBlind, 0, 32);
506  if (!secp256k1_pedersen_commit(both, &allOutCommitmentsPacked[tx.vout.size()], txFeeBlind, tx.nTxFee, &secp256k1_generator_const_h, &secp256k1_generator_const_g))
507  throw std::runtime_error("Failed to computed commitment");
508 
509  //filling the additional pubkey elements for decoys: allInPubKeys[wtxNew.vin.size()][..]
510  //allInPubKeys[wtxNew.vin.size()][j] = sum of allInPubKeys[..][j] + sum of allInCommitments[..][j] + sum of allOutCommitments
511  const secp256k1_pedersen_commitment* outCptr[MAX_VOUT + 1];
512  for (size_t i = 0; i < tx.vout.size() + 1; i++) {
513  outCptr[i] = &allOutCommitmentsPacked[i];
514  }
515 
516  secp256k1_pedersen_commitment inPubKeysToCommitments[MAX_VIN][MAX_DECOYS + 1];
517  for (size_t i = 0; i < tx.vin.size(); i++) {
518  for (size_t j = 0; j < tx.vin[0].decoys.size() + 1; j++) {
519  secp256k1_pedersen_serialized_pubkey_to_commitment(allInPubKeys[i][j], 33, &inPubKeysToCommitments[i][j]);
520  }
521  }
522 
523  for (size_t j = 0; j < tx.vin[0].decoys.size() + 1; j++) {
524  const secp256k1_pedersen_commitment* inCptr[MAX_VIN * 2];
525  for (size_t k = 0; k < tx.vin.size(); k++) {
526  if (!secp256k1_pedersen_commitment_parse(both, &allInCommitmentsPacked[k][j], allInCommitments[k][j])) {
527  LogPrintf("Failed to parse commitment\n");
528  return false;
529  }
530  inCptr[k] = &allInCommitmentsPacked[k][j];
531  }
532 
533  for (size_t k = tx.vin.size(); k < 2 * tx.vin.size(); k++) {
534  inCptr[k] = &inPubKeysToCommitments[k - tx.vin.size()][j];
535  }
537  size_t length;
538  if (!secp256k1_pedersen_commitment_sum(both, inCptr, tx.vin.size() * 2, outCptr, tx.vout.size() + 1, &out)) {
539  LogPrintf("Failed to secp256k1_pedersen_commitment_sum\n");
540  return false;
541  }
542  if (!secp256k1_pedersen_commitment_to_serialized_pubkey(&out, allInPubKeys[tx.vin.size()][j], &length)) {
543  LogPrintf("Failed to serialized pubkey\n");
544  return false;
545  }
546  }
547 
548 
549  //verification
550  unsigned char C[32];
551  memcpy(C, tx.c.begin(), 32);
552  for (size_t j = 0; j < tx.vin[0].decoys.size() + 1; j++) {
553  for (size_t i = 0; i < tx.vin.size() + 1; i++) {
554  //compute LIJ, RIJ
555  unsigned char P[33];
556  memcpy(P, allInPubKeys[i][j], 33);
557  if (!secp256k1_ec_pubkey_tweak_mul(P, 33, C)) {
558  LogPrintf("Failed to mul pubkey\n");
559  return false;
560  }
561 
562  if (!secp256k1_ec_pubkey_tweak_add(P, 33, SIJ[i][j])) {
563  LogPrintf("Failed to add pubkey\n");
564  return false;
565  }
566 
567  memcpy(LIJ[i][j], P, 33);
568 
569  //compute RIJ
570  unsigned char sh[33];
571  CPubKey pkij;
572  pkij.Set(allInPubKeys[i][j], allInPubKeys[i][j] + 33);
573  PointHashingSuccessively(pkij, SIJ[i][j], sh);
574 
575  unsigned char ci[33];
576  memcpy(ci, allKeyImages[i], 33);
577  if (!secp256k1_ec_pubkey_tweak_mul(ci, 33, C)) {
578  LogPrintf("Failed to mul tweak\n");
579  return false;
580  }
581 
582  //convert shp into commitment
583  secp256k1_pedersen_commitment SHP_commitment;
585 
586  //convert CI*I into commitment
587  secp256k1_pedersen_commitment cii_commitment;
589 
590  const secp256k1_pedersen_commitment* twoElements[2];
591  twoElements[0] = &SHP_commitment;
592  twoElements[1] = &cii_commitment;
593 
595  if (!secp256k1_pedersen_commitment_sum_pos(both, twoElements, 2, &sum))
596  throw std::runtime_error("failed to compute secp256k1_pedersen_commitment_sum_pos");
597  size_t tempLength;
598  if (!secp256k1_pedersen_commitment_to_serialized_pubkey(&sum, RIJ[i][j], &tempLength))
599  throw std::runtime_error("failed to serialize pedersen commitment");
600  }
601 
602  //compute C
603  unsigned char tempForHash[2 * (MAX_VIN + 1) * 33 + 32];
604  unsigned char* tempForHashPtr = tempForHash;
605  for (size_t i = 0; i < tx.vin.size() + 1; i++) {
606  memcpy(tempForHashPtr, &(LIJ[i][j][0]), 33);
607  tempForHashPtr += 33;
608  memcpy(tempForHashPtr, &(RIJ[i][j][0]), 33);
609  tempForHashPtr += 33;
610  }
611  uint256 ctsHash = GetTxSignatureHash(tx);
612  memcpy(tempForHashPtr, ctsHash.begin(), 32);
613 
614  uint256 temppi1 = Hash(tempForHash, tempForHash + 2 * (tx.vin.size() + 1) * 33 + 32);
615  memcpy(C, temppi1.begin(), 32);
616  }
617  //LogPrintf("Verifying\n");
618  return HexStr(tx.c.begin(), tx.c.end()) == HexStr(C, C + 32);
619 }
620 
622 {
623  LOCK(cs_main);
624  {
625  if (!pindex) return false;
626  CBlock block;
627  if (!ReadBlockFromDisk(block, pindex)) return false;
628  if (!pindex->IsProofOfStake()) return false;
629  CAmount nFees = 0;
630  CAmount nValueIn = 0;
631  CAmount nValueOut = 0;
632  for (unsigned int i = 0; i < block.vtx.size(); i++) {
633  const CTransaction& tx = block.vtx[i];
634  if (!tx.IsCoinStake()) {
635  if (!tx.IsCoinAudit()) {
636  if (!VerifyRingSignatureWithTxFee(tx, pindex))
637  return false;
639  return false;
640  }
641  nFees += tx.nTxFee;
642  }
643  }
644 
645  const CTransaction coinstake = block.vtx[1];
647  nValueIn = GetValueIn(view, coinstake);
648  nValueOut = coinstake.GetValueOut();
649 
650  size_t numUTXO = coinstake.vout.size();
651  if (mapBlockIndex.count(block.hashPrevBlock) < 1) {
652  LogPrintf("%s: Previous block not found, received block %s, previous %s, current tip %s\n", __func__, block.GetHash().GetHex(), block.hashPrevBlock.GetHex(), chainActive.Tip()->GetBlockHash().GetHex());
653  return false;
654  }
655  CAmount blockValue = GetBlockValue(mapBlockIndex[block.hashPrevBlock]->nHeight);
656  const CTxOut& mnOut = coinstake.vout[numUTXO - 1];
657  std::string mnsa(mnOut.masternodeStealthAddress.begin(), mnOut.masternodeStealthAddress.end());
658  if (!VerifyDerivedAddress(mnOut, mnsa)) {
659  LogPrintf("%s: Incorrect derived address for masternode rewards\n", __func__);
660  return false;
661  }
662 
663  // track money supply and mint amount info
664  CAmount nMoneySupplyPrev = pindex->pprev ? pindex->pprev->nMoneySupply : 0;
665  pindex->nMoneySupply = nMoneySupplyPrev + nValueOut - nValueIn - nFees;
666  LogPrint(BCLog::SUPPLY, "%s: nMoneySupplyPrev=%d, pindex->nMoneySupply=%d, nFees = %d\n", __func__, nMoneySupplyPrev, pindex->nMoneySupply, nFees);
667  pindex->nMint = pindex->nMoneySupply - nMoneySupplyPrev + nFees;
668 
669  //PoW phase redistributed fees to miner. PoS stage destroys fees.
670  CAmount nExpectedMint = GetBlockValue(pindex->pprev->nHeight);
671  nExpectedMint += nFees;
672 
673  if (!IsBlockValueValid(pindex->nHeight, nExpectedMint, pindex->nMint)) {
674  LogPrintf("%s: reward pays too much (actual=%s vs limit=%s)\n", __func__, FormatMoney(pindex->nMint), FormatMoney(nExpectedMint));
675  return false;
676  }
677  return true;
678  }
679 }
680 
682 {
683  CTransactionSignature cts(tx);
684  return cts.GetHash();
685 }
686 
688 {
689  CTxInShortDigest cts(txin);
690  return cts.GetHash();
691 }
692 
694 //
695 // Registration of network node signals.
696 //
697 
698 namespace
699 {
700 struct CBlockReject {
701  unsigned char chRejectCode;
702  std::string strRejectReason;
703  uint256 hashBlock;
704 };
705 
706 
707 class CNodeBlocks
708 {
709 public:
710  CNodeBlocks():
711  maxSize(0),
712  maxAvg(0)
713  {
714  maxSize = GetArg("-blockspamfiltermaxsize", DEFAULT_BLOCK_SPAM_FILTER_MAX_SIZE);
715  maxAvg = GetArg("-blockspamfiltermaxavg", DEFAULT_BLOCK_SPAM_FILTER_MAX_AVG);
716  }
717 
718  bool onBlockReceived(int nHeight) {
719  if(nHeight > 0 && maxSize && maxAvg) {
720  addPoint(nHeight);
721  return true;
722  }
723  return false;
724  }
725 
726  bool updateState(CValidationState& state, bool ret)
727  {
728  // No Blocks
729  size_t size = points.size();
730  if(size == 0)
731  return ret;
732 
733  // Compute the number of the received blocks
734  size_t nBlocks = 0;
735  for(auto point : points)
736  {
737  nBlocks += point.second;
738  }
739 
740  // Compute the average value per height
741  double nAvgValue = (double)nBlocks / size;
742 
743  // Ban the node if try to spam
744  bool banNode = (nAvgValue >= 1.5 * maxAvg && size >= maxAvg) ||
745  (nAvgValue >= maxAvg && nBlocks >= maxSize) ||
746  (nBlocks >= maxSize * 3);
747  if(banNode)
748  {
749  // Clear the points and ban the node
750  points.clear();
751  return state.DoS(100, error("block-spam ban node for sending spam"));
752  }
753 
754  return ret;
755  }
756 
757 private:
758  void addPoint(int height)
759  {
760  // Remove the last element in the list
761  if(points.size() == maxSize)
762  {
763  points.erase(points.begin());
764  }
765 
766  // Add the point to the list
767  int occurrence = 0;
768  auto mi = points.find(height);
769  if (mi != points.end())
770  occurrence = (*mi).second;
771  occurrence++;
772  points[height] = occurrence;
773  }
774 
775 private:
776  std::map<int,int> points;
777  size_t maxSize;
778  size_t maxAvg;
779 };
780 
781 
782 
789 struct CNodeState {
791  CService address;
793  bool fCurrentlyConnected;
795  int nMisbehavior;
797  bool fShouldBan;
799  std::string name;
801  std::vector<CBlockReject> rejects;
803  CBlockIndex* pindexBestKnownBlock;
805  uint256 hashLastUnknownBlock;
807  CBlockIndex* pindexLastCommonBlock;
809  bool fSyncStarted;
811  int64_t nStallingSince;
812  std::list<QueuedBlock> vBlocksInFlight;
813  int nBlocksInFlight;
815  bool fPreferredDownload;
816 
817  CNodeBlocks nodeBlocks;
818 
819  CNodeState()
820  {
821  fCurrentlyConnected = false;
822  nMisbehavior = 0;
823  fShouldBan = false;
824  pindexBestKnownBlock = NULL;
825  hashLastUnknownBlock.SetNull();
826  pindexLastCommonBlock = NULL;
827  fSyncStarted = false;
828  nStallingSince = 0;
829  nBlocksInFlight = 0;
830  fPreferredDownload = false;
831  }
832 };
833 
835 std::map<NodeId, CNodeState> mapNodeState;
836 
837 // Requires cs_main.
838 CNodeState* State(NodeId pnode)
839 {
840  std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
841  if (it == mapNodeState.end())
842  return NULL;
843  return &it->second;
844 }
845 
846 int GetHeight()
847 {
848  while (true) {
849  TRY_LOCK(cs_main, lockMain);
850  if (!lockMain) {
851  MilliSleep(50);
852  continue;
853  }
854  return chainActive.Height();
855  }
856 }
857 
858 void UpdatePreferredDownload(CNode* node, CNodeState* state)
859 {
860  nPreferredDownload -= state->fPreferredDownload;
861 
862  // Whether this node should be marked as a preferred download node.
863  state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
864 
865  nPreferredDownload += state->fPreferredDownload;
866 }
867 
868 void InitializeNode(NodeId nodeid, const CNode* pnode)
869 {
870  LOCK(cs_main);
871  CNodeState& state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
872  state.name = pnode->addrName;
873  state.address = pnode->addr;
874 }
875 
876 void FinalizeNode(NodeId nodeid)
877 {
878  LOCK(cs_main);
879  CNodeState* state = State(nodeid);
880 
881  if (!state)
882  return;
883 
884  if (state->fSyncStarted)
885  nSyncStarted--;
886 
887  if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
888  AddressCurrentlyConnected(state->address);
889  }
890 
891  for (const QueuedBlock& entry : state->vBlocksInFlight)
892  mapBlocksInFlight.erase(entry.hash);
893  EraseOrphansFor(nodeid);
894  nPreferredDownload -= state->fPreferredDownload;
895 
896  mapNodeState.erase(nodeid);
897 }
898 
899 // Requires cs_main.
900 void MarkBlockAsReceived(const uint256& hash)
901 {
902  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
903  if (itInFlight != mapBlocksInFlight.end()) {
904  CNodeState* state = State(itInFlight->second.first);
905  nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
906  state->vBlocksInFlight.erase(itInFlight->second.second);
907  state->nBlocksInFlight--;
908  state->nStallingSince = 0;
909  mapBlocksInFlight.erase(itInFlight);
910  }
911 }
912 
913 // Requires cs_main.
914 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex* pindex = NULL)
915 {
916  CNodeState* state = State(nodeid);
917  assert(state != NULL);
918 
919  // Make sure it's not listed somewhere already.
920  MarkBlockAsReceived(hash);
921 
922  QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
923  nQueuedValidatedHeaders += newentry.fValidatedHeaders;
924  std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
925  state->nBlocksInFlight++;
926  mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
927 }
928 
930 void ProcessBlockAvailability(NodeId nodeid)
931 {
932  CNodeState* state = State(nodeid);
933  assert(state != NULL);
934 
935  if (!state->hashLastUnknownBlock.IsNull()) {
936  BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
937  if (itOld != mapBlockIndex.end() && itOld->second == NULL) {
938  LogPrint(BCLog::NET, "erasing block %s", itOld->first.GetHex());
939  mapBlockIndex.erase(itOld);
940  }
941  itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
942  if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
943  if (state->pindexBestKnownBlock == NULL ||
944  itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
945  state->pindexBestKnownBlock = itOld->second;
946  state->hashLastUnknownBlock.SetNull();
947  }
948  }
949 }
950 
952 void UpdateBlockAvailability(NodeId nodeid, const uint256& hash)
953 {
954  CNodeState* state = State(nodeid);
955  assert(state != NULL);
956  ProcessBlockAvailability(nodeid);
957  BlockMap::iterator it = mapBlockIndex.find(hash);
958  if (it != mapBlockIndex.end() && it->second == NULL) {
959  mapBlockIndex.erase(it);
960  }
961  it = mapBlockIndex.find(hash);
962  if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
963  // An actually better block was announced.
964  if (state->pindexBestKnownBlock == NULL ||
965  it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
966  state->pindexBestKnownBlock = it->second;
967  } else {
968  // An unknown block was announced; just assume that the latest one is the best one.
969  state->hashLastUnknownBlock = hash;
970  }
971 }
972 
975 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb)
976 {
977  if (pa->nHeight > pb->nHeight) {
978  pa = pa->GetAncestor(pb->nHeight);
979  } else if (pb->nHeight > pa->nHeight) {
980  pb = pb->GetAncestor(pa->nHeight);
981  }
982 
983  while (pa != pb && pa && pb) {
984  pa = pa->pprev;
985  pb = pb->pprev;
986  }
987 
988  // Eventually all chain branches meet at the genesis block.
989  assert(pa == pb);
990  return pa;
991 }
992 
995 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller)
996 {
997  if (count == 0)
998  return;
999 
1000  vBlocks.reserve(vBlocks.size() + count);
1001  CNodeState* state = State(nodeid);
1002  assert(state != NULL);
1003 
1004  // Make sure pindexBestKnownBlock is up to date, we'll need it.
1005  ProcessBlockAvailability(nodeid);
1006 
1007  if (state->pindexBestKnownBlock == NULL ||
1008  state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
1009  // This peer has nothing interesting.
1010  return;
1011  }
1012 
1013  if (state->pindexLastCommonBlock == NULL) {
1014  // Bootstrap quickly by guessing a parent of our best tip is the forking point.
1015  // Guessing wrong in either direction is not a problem.
1016  state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight,
1017  chainActive.Height())];
1018  }
1019 
1020  // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
1021  // of their current tip anymore. Go back enough to fix that.
1022  state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
1023  if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
1024  return;
1025 
1026  std::vector<CBlockIndex*> vToFetch;
1027  CBlockIndex* pindexWalk = state->pindexLastCommonBlock;
1028  // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
1029  // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
1030  // download that next block if the window were 1 larger.
1031  int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
1032  int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
1033  NodeId waitingfor = -1;
1034  while (pindexWalk->nHeight < nMaxHeight) {
1035  // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
1036  // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
1037  // as iterating over ~100 CBlockIndex* entries anyway.
1038  int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
1039  vToFetch.resize(nToFetch);
1040  pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
1041  vToFetch[nToFetch - 1] = pindexWalk;
1042  for (unsigned int i = nToFetch - 1; i > 0; i--) {
1043  vToFetch[i - 1] = vToFetch[i]->pprev;
1044  }
1045 
1046  // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
1047  // are not yet downloaded and not in flight to vBlocks. In the mean time, update
1048  // pindexLastCommonBlock as long as all ancestors are already downloaded.
1049  for (CBlockIndex* pindex : vToFetch) {
1050  if (!pindex->IsValid(BLOCK_VALID_TREE)) {
1051  // We consider the chain that this peer is on invalid.
1052  return;
1053  }
1054  if (pindex->nStatus & BLOCK_HAVE_DATA) {
1055  if (pindex->nChainTx)
1056  state->pindexLastCommonBlock = pindex;
1057  } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
1058  // The block is not already downloaded, and not yet in flight.
1059  if (pindex->nHeight > nWindowEnd) {
1060  // We reached the end of the window.
1061  if (vBlocks.size() == 0 && waitingfor != nodeid) {
1062  // We aren't able to fetch anything, but we would be if the download window was one larger.
1063  nodeStaller = waitingfor;
1064  }
1065  return;
1066  }
1067  vBlocks.push_back(pindex);
1068  if (vBlocks.size() == count) {
1069  return;
1070  }
1071  } else if (waitingfor == -1) {
1072  // This is the first already-in-flight block.
1073  waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
1074  }
1075  }
1076  }
1077 }
1078 
1079 } // namespace
1080 
1082 {
1083  LOCK(cs_main);
1084  CNodeState* state = State(nodeid);
1085  if (state == NULL)
1086  return false;
1087  stats.nMisbehavior = state->nMisbehavior;
1088  stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
1089  stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
1090  for (const QueuedBlock& queue : state->vBlocksInFlight) {
1091  if (queue.pindex)
1092  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
1093  }
1094  return true;
1095 }
1096 
1098 {
1099  nodeSignals.GetHeight.connect(&GetHeight);
1100  nodeSignals.ProcessMessages.connect(&ProcessMessages);
1101  nodeSignals.SendMessages.connect(&SendMessages);
1102  nodeSignals.InitializeNode.connect(&InitializeNode);
1103  nodeSignals.FinalizeNode.connect(&FinalizeNode);
1104 }
1105 
1107 {
1108  nodeSignals.GetHeight.disconnect(&GetHeight);
1109  nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
1110  nodeSignals.SendMessages.disconnect(&SendMessages);
1111  nodeSignals.InitializeNode.disconnect(&InitializeNode);
1112  nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
1113 }
1114 
1116 {
1117  // Find the first block the caller has in the main chain
1118  for (const uint256& hash : locator.vHave) {
1119  BlockMap::iterator mi = mapBlockIndex.find(hash);
1120  if (mi != mapBlockIndex.end()) {
1121  CBlockIndex* pindex = (*mi).second;
1122  if (pindex && chain.Contains(pindex)) {
1123  return pindex;
1124  }
1125  }
1126  }
1127  return chain.Genesis();
1128 }
1129 
1132 
1134 //
1135 // mapOrphanTransactions
1136 //
1137 
1138 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
1139 {
1140  uint256 hash = tx.GetHash();
1141  if (mapOrphanTransactions.count(hash))
1142  return false;
1143 
1144  // Ignore big transactions, to avoid a
1145  // send-big-orphans memory exhaustion attack. If a peer has a legitimate
1146  // large transaction with a missing parent then we assume
1147  // it will rebroadcast it later, after the parent transaction(s)
1148  // have been mined or received.
1149  // 10,000 orphans, each of which is at most 5,000 bytes big is
1150  // at most 500 megabytes of orphans:
1151  unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
1152  if (sz > 5000) {
1153  LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
1154  return false;
1155  }
1156 
1157  mapOrphanTransactions[hash].tx = tx;
1158  mapOrphanTransactions[hash].fromPeer = peer;
1159  for (const CTxIn& txin : tx.vin)
1160  mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
1161 
1162  LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
1164  return true;
1165 }
1166 
1167 void static EraseOrphanTx(uint256 hash)
1168 {
1169  std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
1170  if (it == mapOrphanTransactions.end())
1171  return;
1172  for (const CTxIn& txin : it->second.tx.vin) {
1173  std::map<uint256, std::set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
1174  if (itPrev == mapOrphanTransactionsByPrev.end())
1175  continue;
1176  itPrev->second.erase(hash);
1177  if (itPrev->second.empty())
1178  mapOrphanTransactionsByPrev.erase(itPrev);
1179  }
1180  mapOrphanTransactions.erase(it);
1181 }
1182 
1184 {
1185  int nErased = 0;
1186  std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
1187  while (iter != mapOrphanTransactions.end()) {
1188  std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
1189  if (maybeErase->second.fromPeer == peer) {
1190  EraseOrphanTx(maybeErase->second.tx.GetHash());
1191  ++nErased;
1192  }
1193  }
1194  if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer %d\n", nErased, peer);
1195 }
1196 
1197 
1198 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
1199 {
1200  unsigned int nEvicted = 0;
1201  while (mapOrphanTransactions.size() > nMaxOrphans) {
1202  // Evict a random orphan:
1203  uint256 randomhash = GetRandHash();
1204  std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
1205  if (it == mapOrphanTransactions.end())
1206  it = mapOrphanTransactions.begin();
1207  EraseOrphanTx(it->first);
1208  ++nEvicted;
1209  }
1210  return nEvicted;
1211 }
1212 
1213 bool IsStandardTx(const CTransaction& tx, std::string& reason)
1214 {
1216  if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
1217  reason = "version";
1218  return false;
1219  }
1220 
1221  // Treat non-final transactions as non-standard to prevent a specific type
1222  // of double-spend attack, as well as DoS attacks. (if the transaction
1223  // can't be mined, the attacker isn't expending resources broadcasting it)
1224  // Basically we don't want to propagate transactions that can't be included in
1225  // the next block.
1226  //
1227  // However, IsFinalTx() is confusing... Without arguments, it uses
1228  // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
1229  // is set to the value of nHeight in the block. However, when IsFinalTx()
1230  // is called within CBlock::AcceptBlock(), the height of the block *being*
1231  // evaluated is what is used. Thus if we want to know if a transaction can
1232  // be part of the *next* block, we need to call IsFinalTx() with one more
1233  // than chainActive.Height().
1234  //
1235  // Timestamps on the other hand don't get any special treatment, because we
1236  // can't know what timestamp the next block will have, and there aren't
1237  // timestamp applications where it matters.
1238  if (!IsFinalTx(tx, chainActive.Height() + 1)) {
1239  reason = "non-final";
1240  return false;
1241  }
1242 
1243  // Extremely large transactions with lots of inputs can cost the network
1244  // almost as much to process as they cost the sender in fees, because
1245  // computing signature hashes is O(ninputs*txsize). Limiting transactions
1246  // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
1247  unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
1248  unsigned int nMaxSize = MAX_STANDARD_TX_SIZE;
1249  if (sz >= nMaxSize) {
1250  reason = "tx-size";
1251  return false;
1252  }
1253 
1254  for (const CTxIn& txin : tx.vin) {
1255  // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
1256  // keys. (remember the 520 byte limit on redeemScript size) That works
1257  // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
1258  // bytes of scriptSig, which we round off to 1650 bytes for some minor
1259  // future-proofing. That's also enough to spend a 20-of-20
1260  // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
1261  // considered standard)
1262  if (txin.scriptSig.size() > 1650) {
1263  reason = "scriptsig-size";
1264  return false;
1265  }
1266  if (!txin.scriptSig.IsPushOnly()) {
1267  reason = "scriptsig-not-pushonly";
1268  return false;
1269  }
1270  }
1271 
1272  unsigned int nDataOut = 0;
1273  txnouttype whichType;
1274  for (const CTxOut& txout : tx.vout) {
1275  if (!::IsStandard(txout.scriptPubKey, whichType)) {
1276  reason = "scriptpubkey";
1277  return false;
1278  }
1279 
1280  if (whichType == TX_NULL_DATA)
1281  nDataOut++;
1282  else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
1283  reason = "bare-multisig";
1284  return false;
1285  } else if (txout.nValue != 0 && txout.IsDust(::minRelayTxFee)) {
1286  reason = "dust";
1287  return false;
1288  }
1289  }
1290 
1291  // only one OP_RETURN txout is permitted
1292  if (nDataOut > 1) {
1293  reason = "multi-op-return";
1294  return false;
1295  }
1296 
1297  return true;
1298 }
1299 
1309 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
1310 {
1311  if (tx.IsCoinBase())
1312  return true; // coinbase has no inputs
1313 
1314  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1315  CTransaction txPrev;
1316  uint256 hashBlockPrev;
1317  if (!GetTransaction(tx.vin[i].prevout.hash, txPrev, hashBlockPrev)) {
1318  continue; // previous transaction not in main chain
1319  }
1320 
1321  const CTxOut& prev = txPrev.vout[tx.vin[i].prevout.n];
1322 
1323  std::vector<std::vector<unsigned char> > vSolutions;
1324  txnouttype whichType;
1325  // get the scriptPubKey corresponding to this input:
1326  const CScript& prevScript = prev.scriptPubKey;
1327  if (!Solver(prevScript, whichType, vSolutions))
1328  return false;
1329  int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
1330  if (nArgsExpected < 0)
1331  return false;
1332 
1333  if (tx.vin[i].decoys.size() > 0) {
1334  continue;
1335  }
1336 
1337  // Transactions with extra stuff in their scriptSigs are
1338  // non-standard. Note that this EvalScript() call will
1339  // be quick, because if there are any operations
1340  // beside "push data" in the scriptSig
1341  // IsStandard() will have already returned false
1342  // and this method isn't called.
1343  std::vector<std::vector<unsigned char> > stack;
1344  if (!EvalScript(stack, tx.vin[i].scriptSig, false, BaseSignatureChecker()))
1345  return false;
1346 
1347  if (whichType == TX_SCRIPTHASH) {
1348  if (stack.empty())
1349  return false;
1350  CScript subscript(stack.back().begin(), stack.back().end());
1351  std::vector<std::vector<unsigned char> > vSolutions2;
1352  txnouttype whichType2;
1353  if (Solver(subscript, whichType2, vSolutions2)) {
1354  int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
1355  if (tmpExpected < 0)
1356  return false;
1357  nArgsExpected += tmpExpected;
1358  } else {
1359  // Any other Script with less than 15 sigops OK:
1360  unsigned int sigops = subscript.GetSigOpCount(true);
1361  // ... extra data left on the stack after execution is OK, too:
1362  return (sigops <= MAX_P2SH_SIGOPS);
1363  }
1364  }
1365 
1366  if (stack.size() != (unsigned int)nArgsExpected)
1367  return false;
1368  }
1369 
1370  return true;
1371 }
1372 
1374 {
1375  CCoinsView viewDummy;
1376  CCoinsViewCache view(&viewDummy);
1377  {
1378  LOCK(mempool.cs);
1379  CCoinsViewMemPool viewMempool(pcoinsTip, mempool);
1380  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
1381 
1382  const CCoins* coins = view.AccessCoins(vin.prevout.hash);
1383 
1384  if (coins) {
1385  if (coins->nHeight < 0) return 0;
1386  return WITH_LOCK(cs_main, return chainActive.Height() + 1) - coins->nHeight;
1387  } else
1388  return -1;
1389  }
1390 }
1391 
1393 {
1394  int sigs = 0;
1395 
1396  std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash);
1397  if (i != mapTxLocks.end()) {
1398  sigs = (*i).second.CountSignatures();
1399  }
1400  if (sigs >= SWIFTTX_SIGNATURES_REQUIRED) {
1401  return nSwiftTXDepth;
1402  }
1403 
1404  return 0;
1405 }
1406 
1407 bool VerifyShnorrKeyImageTxIn(const CTxIn& txin, uint256 ctsHash)
1408 {
1409  COutPoint prevout = txin.prevout;
1410  CTransaction prev;
1411  uint256 bh;
1412  if (!GetTransaction(prevout.hash, prev, bh, true)) {
1413  return false;
1414  }
1415  uint256 s(txin.s);
1416  unsigned char S[33];
1417  CPubKey P;
1418  ExtractPubKey(prev.vout[prevout.n].scriptPubKey, P);
1419  PointHashingSuccessively(P, s.begin(), S);
1420  CPubKey R(txin.R.begin(), txin.R.end());
1421 
1422  //compute H(R)I = eI
1423  unsigned char buff[33 + 32];
1424  memcpy(buff, R.begin(), 33);
1425  memcpy(buff + 33, ctsHash.begin(), 32);
1426  uint256 e = Hash(buff, buff + 65);
1427  unsigned char eI[33];
1428  memcpy(eI, txin.keyImage.begin(), 33);
1429  if (!secp256k1_ec_pubkey_tweak_mul(eI, 33, e.begin())) return false;
1430 
1431  secp256k1_pedersen_commitment R_commitment;
1432  secp256k1_pedersen_serialized_pubkey_to_commitment(R.begin(), 33, &R_commitment);
1433 
1434  //convert CI*I into commitment
1435  secp256k1_pedersen_commitment eI_commitment;
1437 
1438  const secp256k1_pedersen_commitment* twoElements[2];
1439  twoElements[0] = &R_commitment;
1440  twoElements[1] = &eI_commitment;
1442  if (!secp256k1_pedersen_commitment_sum_pos(GetContext(), twoElements, 2, &sum))
1443  throw std::runtime_error("failed to compute secp256k1_pedersen_commitment_sum_pos");
1444  size_t tempLength;
1445  unsigned char recomputed[33];
1446  if (!secp256k1_pedersen_commitment_to_serialized_pubkey(&sum, recomputed, &tempLength))
1447  throw std::runtime_error("failed to serialize pedersen commitment");
1448 
1449  for (int i = 0; i < 33; i++)
1450  if (S[i] != recomputed[i]) return false;
1451  return true;
1452 }
1453 
1455 {
1456  //check if a transaction is staking or spending collateral
1457  //this assumes that the transaction is already checked for either a staking transaction or transactions spending only UTXOs of 2.5K PRCY
1458  if (!tx.IsCoinStake()) return true;
1459  uint256 cts = GetTxInSignatureHash(tx.vin[0]);
1460  return VerifyShnorrKeyImageTxIn(tx.vin[0], cts);
1461 }
1462 
1463 
1464 
1465 bool CheckFinalTx(const CTransaction& tx, int flags)
1466 {
1468 
1469  // By convention a negative value for flags indicates that the
1470  // current network-enforced consensus rules should be used. In
1471  // a future soft-fork scenario that would mean checking which
1472  // rules would be enforced for the next block and setting the
1473  // appropriate flags. At the present time no soft-forks are
1474  // scheduled, so no flags are set.
1475  flags = std::max(flags, 0);
1476 
1477  // CheckFinalTx() uses chainActive.Height()+1 to evaluate
1478  // nLockTime because when IsFinalTx() is called within
1479  // CBlock::AcceptBlock(), the height of the block *being*
1480  // evaluated is what is used. Thus if we want to know if a
1481  // transaction can be part of the *next* block, we need to call
1482  // IsFinalTx() with one more than chainActive.Height().
1483  const int nBlockHeight = chainActive.Height() + 1;
1484 
1485  // BIP113 will require that time-locked transactions have nLockTime set to
1486  // less than the median time of the previous block they're contained in.
1487  // When the next block is created its previous block will be the current
1488  // chain tip, so we use that to calculate the median time passed to
1489  // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
1490  const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime();
1491 
1492  return IsFinalTx(tx, nBlockHeight, nBlockTime);
1493 }
1494 
1495 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1496 {
1497  {
1498  LOCK(mempool.cs);
1499  uint256 hash = tx.GetHash();
1500  double dPriorityDelta = 0;
1501  CAmount nFeeDelta = 0;
1502  mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1503  if (dPriorityDelta > 0 || nFeeDelta > 0)
1504  return 0;
1505  }
1506 
1507  CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1508 
1509  if (fAllowFree) {
1510  // There is a free transaction area in blocks created by most miners,
1511  // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1512  // to be considered to fall into this category. We don't want to encourage sending
1513  // multiple transactions instead of one big transaction to avoid fees.
1514  if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1515  nMinFee = 0;
1516  }
1517 
1518  return nMinFee;
1519 }
1520 
1521 bool CheckHaveInputs(const CCoinsViewCache& view, const CTransaction& tx)
1522 {
1523  CBlockIndex* pindexPrev = mapBlockIndex.find(view.GetBestBlock())->second;
1524  int nSpendHeight = pindexPrev->nHeight + 1;
1525  if (!tx.IsCoinBase()) {
1526  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1527  //check output and decoys
1528  std::vector<COutPoint> alldecoys = tx.vin[i].decoys;
1529 
1530  alldecoys.push_back(tx.vin[i].prevout);
1531  for (size_t j = 0; j < alldecoys.size(); j++) {
1532  CTransaction prev;
1533  uint256 bh;
1534  if (!GetTransaction(alldecoys[j].hash, prev, bh, true)) {
1535  return false;
1536  }
1537 
1538  if (mapBlockIndex.count(bh) < 1) return false;
1539  if (prev.IsCoinStake() || prev.IsCoinAudit() || prev.IsCoinBase()) {
1540  if (nSpendHeight - mapBlockIndex[bh]->nHeight < Params().COINBASE_MATURITY()) return false;
1541  }
1542 
1543  CBlockIndex* tip = chainActive.Tip();
1544  if (!pindexPrev) tip = pindexPrev;
1545 
1546  uint256 hashTip = tip->GetBlockHash();
1547  //verify that tip and hashBlock must be in the same fork
1548  CBlockIndex* atTheblock = mapBlockIndex[bh];
1549  if (!atTheblock) {
1550  LogPrintf("%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, alldecoys[j].hash.GetHex(), tip->nHeight, tip->GetBlockHash().GetHex());
1551  return false;
1552  } else {
1553  CBlockIndex* ancestor = tip->GetAncestor(atTheblock->nHeight);
1554  if (ancestor != atTheblock) {
1555  LogPrintf("%s: Decoy for transaction %s not in the same chain as block height=%s hash=%s\n", __func__, alldecoys[j].hash.GetHex(), tip->nHeight, tip->GetBlockHash().GetHex());
1556  return false;
1557  }
1558  }
1559  }
1560  if (!tx.IsCoinStake()) {
1561  if (tx.vin[i].decoys.size() != tx.vin[0].decoys.size()) {
1562  LogPrintf("%s: Transaction does not have the same ring size for inputs\n", __func__);
1563  return false;
1564  }
1565  }
1566  }
1567 
1568  if (tx.IsCoinStake()) {
1569  if (!VerifyShnorrKeyImageTx(tx)) {
1570  LogPrintf("%s: Failed to verify correctness of key image of staking transaction\n", __func__);
1571  return false;
1572  }
1573  }
1574  }
1575  return true;
1576 }
1577 
1578 
1579 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool ignoreFees)
1580 {
1582  if (pfMissingInputs)
1583  *pfMissingInputs = false;
1584 
1585  // Check transaction
1586  if (!CheckTransaction(tx, true, state))
1587  return state.DoS(100, error("%s : CheckTransaction failed", __func__), REJECT_INVALID, "bad-tx");
1588 
1589  // Coinbase is only valid in a block, not as a loose transaction
1590  if (tx.IsCoinBase())
1591  return state.DoS(100, error("%s : coinbase as individual tx",
1592  __func__), REJECT_INVALID, "coinbase");
1593 
1594  //Coinstake is also only valid in a block, not as a loose transaction
1595  if (tx.IsCoinStake())
1596  return state.DoS(100, error("%s : coinstake as individual tx (id=%s): %s",
1597  __func__, tx.GetHash().GetHex(), tx.ToString()), REJECT_INVALID, "coinstake");
1598 
1599  // Only accept nLockTime-using transactions that can be mined in the next
1600  // block; we don't want our mempool filled up with transactions that can't
1601  // be mined yet.
1602  if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1603  return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1604 
1605  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1606  std::string reason;
1607  if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1608  return state.DoS(0,
1609  error("AcceptToMemoryPool : nonstandard transaction: %s", reason),
1610  REJECT_NONSTANDARD, reason);
1611  // is it already in the memory pool?
1612  uint256 hash = tx.GetHash();
1613  if (pool.exists(hash)) {
1614  return error("%s tx already in mempool", __func__);
1615  }
1616  // ----------- swiftTX transaction scanning -----------
1617 
1618  {
1619  CCoinsView dummy;
1620  CCoinsViewCache view(&dummy);
1621  CAmount nValueIn = 0;
1622  {
1623  LOCK(pool.cs);
1624  CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1625  view.SetBackend(viewMemPool);
1626  // do we already have it?
1627  if (view.HaveCoins(hash)) {
1628  return false;
1629  }
1630 
1631  int banscore;
1632  if (!tx.IsCoinStake() && !tx.IsCoinBase() && !tx.IsCoinAudit()) {
1633  if (!tx.IsCoinAudit()) {
1635  banscore = 100;
1636  } else {
1637  banscore = 1;
1638  }
1640  return state.DoS(banscore, error("AcceptToMemoryPool() : Ring Signature check for transaction %s failed", tx.GetHash().ToString()),
1641  REJECT_INVALID, "bad-ring-signature");
1642  }
1643  if (!VerifyBulletProofAggregate(tx))
1644  return state.DoS(100, error("AcceptToMemoryPool() : Bulletproof check for transaction %s failed", tx.GetHash().ToString()),
1645  REJECT_INVALID, "bad-bulletproof");
1646  }
1647  }
1648 
1649  // Check key images not duplicated with what in db
1650  for (const CTxIn& txin : tx.vin) {
1651  const CKeyImage& keyImage = txin.keyImage;
1652  if (IsSpentKeyImage(keyImage.GetHex(), UINT256_ZERO)) {
1653  return state.Invalid(error("AcceptToMemoryPool : key image already spent %s", keyImage.GetHex()),
1654  REJECT_DUPLICATE, "bad-txns-inputs-spent");
1655  }
1656  // check for invalid/fraudulent inputs
1657  if (!ValidOutPoint(txin.prevout)) {
1658  return state.Invalid(error("%s : tried to spend invalid input %s in tx %s", __func__, txin.prevout.ToString(),
1659  tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs");
1660  }
1661  }
1662  // check for invalid/fraudulent decoys
1663  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1664  if (tx.IsCoinBase()) continue;
1665  //check output and decoys
1666  std::vector<COutPoint> alldecoys = tx.vin[i].decoys;
1667 
1668  alldecoys.push_back(tx.vin[i].prevout);
1669  for (size_t j = 0; j < alldecoys.size(); j++) {
1670  CTransaction prev;
1671  uint256 bh;
1672  if (!GetTransaction(alldecoys[j].hash, prev, bh, true)) {
1673  return false;
1674  }
1675  if (mapBlockIndex.count(bh) < 1) return false;
1676  if (!ValidOutPoint(alldecoys[j])) {
1677  return state.DoS(100, error("%s : tried to spend invalid decoy %s in tx %s", __func__, alldecoys[j].ToString(),
1678  tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs");
1679  }
1680  }
1681  }
1682 
1683  // Bring the best block into scope
1684  view.GetBestBlock();
1685  nValueIn = GetValueIn(view, tx);
1686 
1687  // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1688  view.SetBackend(dummy);
1689  }
1690 
1691  // Check for non-standard pay-to-script-hash in inputs
1692  if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1693  return error("AcceptToMemoryPool: nonstandard transaction input");
1694  // Check that the transaction doesn't have an excessive number of
1695  // sigops, making it impossible to mine. Since the coinbase transaction
1696  // itself can contain sigops MAX_TX_SIGOPS is less than
1697  // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1698  // merely non-standard transaction.
1699  {
1700  unsigned int nSigOps = GetLegacySigOpCount(tx);
1701  unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
1702  if (nSigOps > nMaxSigOps)
1703  return state.DoS(0,
1704  error("AcceptToMemoryPool : too many sigops %s, %d > %d",
1705  hash.ToString(), nSigOps, nMaxSigOps),
1706  REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1707  }
1708 
1709  CAmount nFees = tx.nTxFee;
1710  double dPriority = GetPriority(tx, chainActive.Height());
1711 
1712  CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
1713  unsigned int nSize = entry.GetTxSize();
1714 
1715  // Don't accept it if it can't get into a block
1716  if (!ignoreFees) {
1717  CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1718  if (fLimitFree && nFees < txMinFee)
1719  return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %d < %d", hash.ToString(), nFees, txMinFee),
1720  REJECT_INSUFFICIENTFEE, "insufficient fee");
1721 
1722  // Continuously rate-limit free (really, very-low-fee) transactions
1723  // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1724  // be annoying or make others' transactions take longer to confirm.
1725  if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize - 300)) {
1726  static RecursiveMutex csFreeLimiter;
1727  static double dFreeCount;
1728  static int64_t nLastTime;
1729  int64_t nNow = GetTime();
1730 
1731  LOCK(csFreeLimiter);
1732 
1733  // Use an exponentially decaying ~10-minute window:
1734  dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime));
1735  nLastTime = nNow;
1736  // -limitfreerelay unit is thousand-bytes-per-minute
1737  // At default rate it would take over a month to fill 1GB
1738  if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000)
1739  return state.DoS(0, error("AcceptToMemoryPool : free transaction rejected by rate limiter"),
1740  REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1741  LogPrint(BCLog::MEMPOOL, "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize);
1742  dFreeCount += nSize;
1743  }
1744  }
1745 
1746  bool fCLTVIsActivated = chainActive.Tip()->nHeight >= Params().BIP65ActivationHeight();
1747 
1748  // Check against previous transactions
1749  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1750  int flags = STANDARD_SCRIPT_VERIFY_FLAGS;
1751  if (fCLTVIsActivated)
1753  if (!CheckInputs(tx, state, view, true, flags, true)) {
1754  return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1755  }
1756 
1757  // Check again against just the consensus-critical mandatory script
1758  // verification flags, in case of bugs in the standard flags that cause
1759  // transactions to pass as valid when they're actually invalid. For
1760  // instance the STRICTENC flag was incorrectly allowing certain
1761  // CHECKSIG NOT scripts to pass, even though they were invalid.
1762  //
1763  // There is a similar check in CreateNewBlock() to prevent creating
1764  // invalid blocks, however allowing such transactions into the mempool
1765  // can be exploited as a DoS attack.
1766  flags = MANDATORY_SCRIPT_VERIFY_FLAGS;
1767  if (fCLTVIsActivated)
1769  if (!CheckInputs(tx, state, view, true, flags, true)) {
1770  return error(
1771  "AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s",
1772  hash.ToString());
1773  }
1774  // Store transaction in memory
1775  pool.addUnchecked(hash, entry);
1776  }
1777  SyncWithWallets(tx, nullptr);
1778 
1779  if (pwalletMain) {
1781  if (pwalletMain->mapWallet.count(tx.GetHash()) == 1) {
1782  for (size_t i = 0; i < tx.vin.size(); i++) {
1783  std::string outpoint = tx.vin[i].prevout.hash.GetHex() + std::to_string(tx.vin[i].prevout.n);
1784  if (pwalletMain->outpointToKeyImages[outpoint] == tx.vin[i].keyImage) {
1785  pwalletMain->inSpendQueueOutpoints[tx.vin[i].prevout] = true;
1786  continue;
1787  }
1788 
1789  for (size_t j = 0; j < tx.vin[i].decoys.size(); j++) {
1790  std::string outpoint = tx.vin[i].decoys[j].hash.GetHex() + std::to_string(tx.vin[i].decoys[j].n);
1791  if (pwalletMain->outpointToKeyImages[outpoint] == tx.vin[i].keyImage) {
1792  pwalletMain->inSpendQueueOutpoints[tx.vin[i].decoys[j]] = true;
1793  break;
1794  }
1795  }
1796  }
1797  }
1798  }
1799 
1800  return true;
1801 }
1802 
1803 bool AcceptableInputs(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool isDSTX)
1804 {
1806  if (pfMissingInputs)
1807  *pfMissingInputs = false;
1808 
1809  const int chainHeight = chainActive.Height();
1810 
1811  if (!CheckTransaction(tx, true, state))
1812  return error("AcceptableInputs: CheckTransaction failed");
1813 
1814  // Coinbase is only valid in a block, not as a loose transaction
1815  if (tx.IsCoinBase())
1816  return state.DoS(100, error("AcceptableInputs: coinbase as individual tx"),
1817  REJECT_INVALID, "coinbase");
1818 
1819  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1820  std::string reason;
1821 
1822  // is it already in the memory pool?
1823  uint256 hash = tx.GetHash();
1824  if (pool.exists(hash))
1825  return false;
1826 
1827  // ----------- swiftTX transaction scanning -----------
1828 
1829  for (const CTxIn& in : tx.vin) {
1830  if (mapLockedInputs.count(in.prevout)) {
1831  if (mapLockedInputs[in.prevout] != tx.GetHash()) {
1832  return state.DoS(0,
1833  error("AcceptableInputs : conflicts with existing transaction lock: %s", reason),
1834  REJECT_INVALID, "tx-lock-conflict");
1835  }
1836  }
1837  }
1838 
1839  // Check for conflicts with in-memory transactions
1840  {
1841  LOCK(pool.cs); // protect pool.mapNextTx
1842  for (const auto &in : tx.vin) {
1843  COutPoint outpoint = in.prevout;
1844  if (pool.mapNextTx.count(outpoint)) {
1845  // Disable replacement feature for now
1846  return false;
1847  }
1848  }
1849  }
1850 
1851 
1852  {
1853  CCoinsView dummy;
1854  CCoinsViewCache view(&dummy);
1855 
1856  CAmount nValueIn = 0;
1857  {
1858  LOCK(pool.cs);
1859  CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1860  view.SetBackend(viewMemPool);
1861 
1862  // do we already have it?
1863  if (view.HaveCoins(hash))
1864  return false;
1865 
1866  // do all inputs exist?
1867  // Note that this does not check for the presence of actual outputs (see the next check for that),
1868  // only helps filling in pfMissingInputs (to determine missing vs spent).
1869  for (const CTxIn& txin : tx.vin) {
1870  if (!view.HaveCoins(txin.prevout.hash)) {
1871  if (pfMissingInputs)
1872  *pfMissingInputs = true;
1873  return false;
1874  }
1875  //Check for invalid/fraudulent inputs
1876  if (!ValidOutPoint(txin.prevout)) {
1877  return state.Invalid(error("%s : tried to spend invalid input %s in tx %s", __func__, txin.prevout.ToString(),
1878  tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs");
1879  }
1880  }
1881 
1882  // check for invalid/fraudulent inputs
1883  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1884  if (tx.IsCoinBase()) continue;
1885  //check output and decoys
1886  std::vector<COutPoint> alldecoys = tx.vin[i].decoys;
1887 
1888  alldecoys.push_back(tx.vin[i].prevout);
1889  for (size_t j = 0; j < alldecoys.size(); j++) {
1890  CTransaction prev;
1891  uint256 bh;
1892  if (!GetTransaction(alldecoys[j].hash, prev, bh, true)) {
1893  return false;
1894  }
1895  if (mapBlockIndex.count(bh) < 1) return false;
1896  if (!ValidOutPoint(alldecoys[j])) {
1897  return state.DoS(100, error("%s : tried to spend invalid decoy %s in tx %s", __func__, alldecoys[j].ToString(),
1898  tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs");
1899  }
1900  }
1901  }
1902 
1903  // are the actual inputs available?
1904  if (!CheckHaveInputs(view, tx))
1905  return state.Invalid(error("AcceptableInputs : inputs already spent"),
1906  REJECT_DUPLICATE, "bad-txns-inputs-spent");
1907 
1908  // Bring the best block into scope
1909  view.GetBestBlock();
1910 
1911  nValueIn = GetValueIn(view, tx);
1912 
1913  // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1914  view.SetBackend(dummy);
1915  }
1916 
1917  // Check that the transaction doesn't have an excessive number of
1918  // sigops, making it impossible to mine. Since the coinbase transaction
1919  // itself can contain sigops MAX_TX_SIGOPS is less than
1920  // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1921  // merely non-standard transaction.
1922  unsigned int nSigOps = GetLegacySigOpCount(tx);
1923  unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
1924  if (nSigOps > nMaxSigOps)
1925  return state.DoS(0,
1926  error("AcceptableInputs : too many sigops %s, %d > %d",
1927  hash.ToString(), nSigOps, nMaxSigOps),
1928  REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1929 
1930  CAmount nValueOut = tx.GetValueOut();
1931  CAmount nFees = tx.nTxFee;
1932  double dPriority = GetPriority(tx, chainHeight);
1933 
1934  CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainHeight);
1935  unsigned int nSize = entry.GetTxSize();
1936 
1937  // Don't accept it if it can't get into a block
1938  // but prioritise dstx and don't check fees for it
1939  if (isDSTX) {
1940  mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1 * COIN);
1941  } else { // same as !ignoreFees for AcceptToMemoryPool
1942  CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1943  if (fLimitFree && nFees < txMinFee)
1944  return state.DoS(0, error("AcceptableInputs : not enough fees %s, %d < %d", hash.ToString(), nFees, txMinFee),
1945  REJECT_INSUFFICIENTFEE, "insufficient fee");
1946 
1947  // Require that free transactions have sufficient priority to be mined in the next block.
1948  //TODO: @campv need to recompute the fee
1949  /*if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) &&
1950  !AllowFree(view.GetPriority(tx, chainHeight + 1))) {
1951  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1952  }*/
1953 
1954  // Continuously rate-limit free (really, very-low-fee) transactions
1955  // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1956  // be annoying or make others' transactions take longer to confirm.
1957  if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize)) {
1958  static RecursiveMutex csFreeLimiter;
1959  static double dFreeCount;
1960  static int64_t nLastTime;
1961  int64_t nNow = GetTime();
1962 
1963  LOCK(csFreeLimiter);
1964 
1965  // Use an exponentially decaying ~10-minute window:
1966  dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime));
1967  nLastTime = nNow;
1968  // -limitfreerelay unit is thousand-bytes-per-minute
1969  // At default rate it would take over a month to fill 1GB
1970  if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000)
1971  return state.DoS(0, error("AcceptableInputs : free transaction rejected by rate limiter"),
1972  REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1973  LogPrint(BCLog::MEMPOOL, "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize);
1974  dFreeCount += nSize;
1975  }
1976  }
1977 
1978  if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1979  return error("AcceptableInputs: insane fees %s, %d > %d",
1980  hash.ToString(),
1981  nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1982 
1983  bool fCLTVIsActivated = chainActive.Tip()->nHeight >= Params().BIP65ActivationHeight();
1984 
1985  // Check against previous transactions
1986  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1987  int flags = STANDARD_SCRIPT_VERIFY_FLAGS;
1988  if (fCLTVIsActivated)
1990  if (!CheckInputs(tx, state, view, false, flags, true)) {
1991  return error("AcceptableInputs: ConnectInputs failed %s", hash.ToString());
1992  }
1993 
1994  // Check again against just the consensus-critical mandatory script
1995  // verification flags, in case of bugs in the standard flags that cause
1996  // transactions to pass as valid when they're actually invalid. For
1997  // instance the STRICTENC flag was incorrectly allowing certain
1998  // CHECKSIG NOT scripts to pass, even though they were invalid.
1999  //
2000  // There is a similar check in CreateNewBlock() to prevent creating
2001  // invalid blocks, however allowing such transactions into the mempool
2002  // can be exploited as a DoS attack.
2003  // for any real tx this will be checked on AcceptToMemoryPool anyway
2004  }
2005 
2006  return true;
2007 }
2008 
2010 bool GetTransaction(const uint256& hash, CTransaction& txOut, uint256& hashBlock, bool fAllowSlow, CBlockIndex* blockIndex)
2011 {
2012  CBlockIndex* pindexSlow = blockIndex;
2013 
2014  LOCK(cs_main);
2015 
2016  if (!blockIndex) {
2017  if (mempool.lookup(hash, txOut)) {
2018  return true;
2019  }
2020 
2021  if (fTxIndex) {
2022  CDiskTxPos postx;
2023  if (pblocktree->ReadTxIndex(hash, postx)) {
2024  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
2025  if (file.IsNull())
2026  return error("%s: OpenBlockFile failed", __func__);
2027  CBlockHeader header;
2028  try {
2029  file >> header;
2030  fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
2031  file >> txOut;
2032  } catch (const std::exception& e) {
2033  return error("%s : Deserialize or I/O error - %s", __func__, e.what());
2034  }
2035  hashBlock = header.GetHash();
2036  if (txOut.GetHash() != hash)
2037  return error("%s : txid mismatch, %s, %s", __func__, txOut.GetHash().GetHex(), hash.GetHex());
2038  return true;
2039  }
2040 
2041  // transaction not found in the index, nothing more can be done
2042  return false;
2043  }
2044 
2045  if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
2046  int nHeight = -1;
2047  {
2048  CCoinsViewCache& view = *pcoinsTip;
2049  const CCoins* coins = view.AccessCoins(hash);
2050  if (coins)
2051  nHeight = coins->nHeight;
2052  }
2053  if (nHeight > 0)
2054  pindexSlow = chainActive[nHeight];
2055  }
2056  }
2057 
2058  if (pindexSlow) {
2059  CBlock block;
2060  if (ReadBlockFromDisk(block, pindexSlow)) {
2061  for (const CTransaction& tx : block.vtx) {
2062  if (tx.GetHash() == hash) {
2063  txOut = tx;
2064  hashBlock = pindexSlow->GetBlockHash();
2065  return true;
2066  }
2067  }
2068  }
2069  }
2070 
2071  return false;
2072 }
2073 
2074 
2076 //
2077 // CBlock and CBlockIndex
2078 //
2079 
2081 {
2082  // Open history file to append
2083  CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
2084  if (fileout.IsNull())
2085  return error("WriteBlockToDisk : OpenBlockFile failed");
2086 
2087  // Write index header
2088  unsigned int nSize = fileout.GetSerializeSize(block);
2089  fileout << FLATDATA(Params().MessageStart()) << nSize;
2090 
2091  // Write block
2092  long fileOutPos = ftell(fileout.Get());
2093  if (fileOutPos < 0)
2094  return error("WriteBlockToDisk : ftell failed");
2095  pos.nPos = (unsigned int)fileOutPos;
2096  fileout << block;
2097 
2098  return true;
2099 }
2100 
2101 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
2102 {
2103  block.SetNull();
2104 
2105  // Open history file to read
2106  CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
2107  if (filein.IsNull())
2108  return error("ReadBlockFromDisk : OpenBlockFile failed");
2109 
2110  // Read block
2111  try {
2112  filein >> block;
2113  } catch (const std::exception& e) {
2114  return error("%s : Deserialize or I/O error - %s", __func__, e.what());
2115  }
2116 
2117  // Check the header
2118  if (block.IsProofOfWork()) {
2119  if (!CheckProofOfWork(block.GetHash(), block.nBits))
2120  return error("ReadBlockFromDisk : Errors in block header");
2121  }
2122 
2123  return true;
2124 }
2125 
2126 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
2127 {
2128  if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
2129  return false;
2130  if (block.GetHash() != pindex->GetBlockHash()) {
2131  LogPrintf("%s : block=%s index=%s\n", __func__, block.GetHash().ToString().c_str(),
2132  pindex->GetBlockHash().ToString().c_str());
2133  return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
2134  }
2135  return true;
2136 }
2137 
2138 
2139 double ConvertBitsToDouble(unsigned int nBits)
2140 {
2141  int nShift = (nBits >> 24) & 0xff;
2142 
2143  double dDiff =
2144  (double)0x0000ffff / (double)(nBits & 0x00ffffff);
2145 
2146  while (nShift < 29) {
2147  dDiff *= 256.0;
2148  nShift++;
2149  }
2150  while (nShift > 29) {
2151  dDiff /= 256.0;
2152  nShift--;
2153  }
2154 
2155  return dDiff;
2156 }
2157 
2159 {
2160  LOCK(cs_main);
2161 
2162  if (Params().IsRegTestNet()) {
2163  if (nHeight == 0)
2164  return 250 * COIN;
2165  }
2166 
2167  int64_t nSubsidy = 0;
2168  int64_t nMoneySupply = chainActive.Tip()->nMoneySupply;
2169 
2170  if (nMoneySupply >= Params().TOTAL_SUPPLY) {
2171  //zero rewards when total supply reach 70M PRCY
2172  return 0;
2173  }
2174  if (nHeight < Params().LAST_POW_BLOCK()) {
2175  nSubsidy = 120000 * COIN;
2176  } else {
2177  nSubsidy = 1 * COIN;
2178  }
2179 
2180  if (nMoneySupply + nSubsidy >= Params().TOTAL_SUPPLY) {
2181  nSubsidy = Params().TOTAL_SUPPLY - nMoneySupply;
2182  }
2183 
2184  return nSubsidy;
2185 }
2186 
2187 CAmount GetSeeSaw(const CAmount& blockValue, int nMasternodeCount, int nHeight)
2188 {
2189  //if a mn count is inserted into the function we are looking for a specific result for a masternode count
2190  if (nMasternodeCount < 1) {
2191  nMasternodeCount = mnodeman.size();
2192  }
2193 
2194  int64_t nMoneySupply = chainActive.Tip()->nMoneySupply;
2195  int64_t mNodeCoins = nMasternodeCount * Params().MNCollateralAmt();
2196 
2197  // Use this log to compare the masternode count for different clients
2198  LogPrintf("Adjusting seesaw at height %d with %d masternodes (without drift: %d) at %ld\n", nHeight,nMasternodeCount, nMasternodeCount - Params().MasternodeCountDrift(), GetTime());
2199  LogPrint(BCLog::SUPPLY, "%s: moneysupply=%s, nodecoins=%s \n", __func__, FormatMoney(nMoneySupply).c_str(), FormatMoney(mNodeCoins).c_str());
2200 
2201  CAmount ret = 0;
2202  if (mNodeCoins == 0) {
2203  ret = 0;
2204  } else if (nHeight <= Params().SoftFork()) {
2205  if (mNodeCoins <= (nMoneySupply * .05) && mNodeCoins > 0) {
2206  ret = blockValue * .6;
2207  } else if (mNodeCoins <= (nMoneySupply * .1) && mNodeCoins > (nMoneySupply * .05)) {
2208  ret = blockValue * .59;
2209  } else if (mNodeCoins <= (nMoneySupply * .15) && mNodeCoins > (nMoneySupply * .1)) {
2210  ret = blockValue * .58;
2211  } else if (mNodeCoins <= (nMoneySupply * .2) && mNodeCoins > (nMoneySupply * .15)) {
2212  ret = blockValue * .57;
2213  } else if (mNodeCoins <= (nMoneySupply * .25) && mNodeCoins > (nMoneySupply * .2)) {
2214  ret = blockValue * .56;
2215  } else if (mNodeCoins <= (nMoneySupply * .3) && mNodeCoins > (nMoneySupply * .25)) {
2216  ret = blockValue * .55;
2217  } else if (mNodeCoins <= (nMoneySupply * .35) && mNodeCoins > (nMoneySupply * .3)) {
2218  ret = blockValue * .54;
2219  } else if (mNodeCoins <= (nMoneySupply * .4) && mNodeCoins > (nMoneySupply * .35)) {
2220  ret = blockValue * .53;
2221  } else if (mNodeCoins <= (nMoneySupply * .45) && mNodeCoins > (nMoneySupply * .4)) {
2222  ret = blockValue * .52;
2223  } else if (mNodeCoins <= (nMoneySupply * .5) && mNodeCoins > (nMoneySupply * .45)) {
2224  ret = blockValue * .51;
2225  } else if (mNodeCoins <= (nMoneySupply * .525) && mNodeCoins > (nMoneySupply * .5)) {
2226  ret = blockValue * .50;
2227  } else if (mNodeCoins <= (nMoneySupply * .55) && mNodeCoins > (nMoneySupply * .525)) {
2228  ret = blockValue * .49;
2229  } else if (mNodeCoins <= (nMoneySupply * .6) && mNodeCoins > (nMoneySupply * .55)) {
2230  ret = blockValue * .48;
2231  } else if (mNodeCoins <= (nMoneySupply * .65) && mNodeCoins > (nMoneySupply * .6)) {
2232  ret = blockValue * .47;
2233  } else if (mNodeCoins <= (nMoneySupply * .7) && mNodeCoins > (nMoneySupply * .65)) {
2234  ret = blockValue * .46;
2235  } else if (mNodeCoins <= (nMoneySupply * .75) && mNodeCoins > (nMoneySupply * .7)) {
2236  ret = blockValue * .45;
2237  } else if (mNodeCoins <= (nMoneySupply * .8) && mNodeCoins > (nMoneySupply * .75)) {
2238  ret = blockValue * .44;
2239  } else if (mNodeCoins <= (nMoneySupply * .85) && mNodeCoins > (nMoneySupply * .8)) {
2240  ret = blockValue * .43;
2241  } else if (mNodeCoins <= (nMoneySupply * .9) && mNodeCoins > (nMoneySupply * .85)) {
2242  ret = blockValue * .42;
2243  } else if (mNodeCoins <= (nMoneySupply * .95) && mNodeCoins > (nMoneySupply * .9)) {
2244  ret = blockValue * .41;
2245  } else {
2246  ret = blockValue * .40;
2247  }
2248  } else if (nHeight > Params().SoftFork()) {
2249  if (mNodeCoins <= (nMoneySupply * .01) && mNodeCoins > 0) {
2250  ret = blockValue * .6;
2251  } else if (mNodeCoins <= (nMoneySupply * .02) && mNodeCoins > (nMoneySupply * .01)) {
2252  ret = blockValue * .598;
2253  } else if (mNodeCoins <= (nMoneySupply * .03) && mNodeCoins > (nMoneySupply * .02)) {
2254  ret = blockValue * .596;
2255  } else if (mNodeCoins <= (nMoneySupply * .04) && mNodeCoins > (nMoneySupply * .03)) {
2256  ret = blockValue * .594;
2257  } else if (mNodeCoins <= (nMoneySupply * .05) && mNodeCoins > (nMoneySupply * .04)) {
2258  ret = blockValue * .592;
2259  } else if (mNodeCoins <= (nMoneySupply * .06) && mNodeCoins > (nMoneySupply * .05)) {
2260  ret = blockValue * .59;
2261  } else if (mNodeCoins <= (nMoneySupply * .07) && mNodeCoins > (nMoneySupply * .06)) {
2262  ret = blockValue * .588;
2263  } else if (mNodeCoins <= (nMoneySupply * .08) && mNodeCoins > (nMoneySupply * .07)) {
2264  ret = blockValue * .586;
2265  } else if (mNodeCoins <= (nMoneySupply * .09) && mNodeCoins > (nMoneySupply * .08)) {
2266  ret = blockValue * .584;
2267  } else if (mNodeCoins <= (nMoneySupply * .1) && mNodeCoins > (nMoneySupply * .09)) {
2268  ret = blockValue * .582;
2269  } else if (mNodeCoins <= (nMoneySupply * .11) && mNodeCoins > (nMoneySupply * .1)) {
2270  ret = blockValue * .58;
2271  } else if (mNodeCoins <= (nMoneySupply * .12) && mNodeCoins > (nMoneySupply * .11)) {
2272  ret = blockValue * .578;
2273  } else if (mNodeCoins <= (nMoneySupply * .13) && mNodeCoins > (nMoneySupply * .12)) {
2274  ret = blockValue * .576;
2275  } else if (mNodeCoins <= (nMoneySupply * .14) && mNodeCoins > (nMoneySupply * .13)) {
2276  ret = blockValue * .574;
2277  } else if (mNodeCoins <= (nMoneySupply * .15) && mNodeCoins > (nMoneySupply * .14)) {
2278  ret = blockValue * .572;
2279  } else if (mNodeCoins <= (nMoneySupply * .16) && mNodeCoins > (nMoneySupply * .15)) {
2280  ret = blockValue * .57;
2281  } else if (mNodeCoins <= (nMoneySupply * .17) && mNodeCoins > (nMoneySupply * .16)) {
2282  ret = blockValue * .568;
2283  } else if (mNodeCoins <= (nMoneySupply * .18) && mNodeCoins > (nMoneySupply * .17)) {
2284  ret = blockValue * .566;
2285  } else if (mNodeCoins <= (nMoneySupply * .19) && mNodeCoins > (nMoneySupply * .18)) {
2286  ret = blockValue * .564;
2287  } else if (mNodeCoins <= (nMoneySupply * .20) && mNodeCoins > (nMoneySupply * .19)) {
2288  ret = blockValue * .562;
2289  } else if (mNodeCoins <= (nMoneySupply * .21) && mNodeCoins > (nMoneySupply * .20)) {
2290  ret = blockValue * .56;
2291  } else if (mNodeCoins <= (nMoneySupply * .22) && mNodeCoins > (nMoneySupply * .21)) {
2292  ret = blockValue * .558;
2293  } else if (mNodeCoins <= (nMoneySupply * .23) && mNodeCoins > (nMoneySupply * .22)) {
2294  ret = blockValue * .556;
2295  } else if (mNodeCoins <= (nMoneySupply * .24) && mNodeCoins > (nMoneySupply * .23)) {
2296  ret = blockValue * .554;
2297  } else if (mNodeCoins <= (nMoneySupply * .25) && mNodeCoins > (nMoneySupply * .24)) {
2298  ret = blockValue * .552;
2299  } else if (mNodeCoins <= (nMoneySupply * .26) && mNodeCoins > (nMoneySupply * .25)) {
2300  ret = blockValue * .55;
2301  } else if (mNodeCoins <= (nMoneySupply * .27) && mNodeCoins > (nMoneySupply * .26)) {
2302  ret = blockValue * .548;
2303  } else if (mNodeCoins <= (nMoneySupply * .28) && mNodeCoins > (nMoneySupply * .27)) {
2304  ret = blockValue * .546;
2305  } else if (mNodeCoins <= (nMoneySupply * .29) && mNodeCoins > (nMoneySupply * .28)) {
2306  ret = blockValue * .544;
2307  } else if (mNodeCoins <= (nMoneySupply * .30) && mNodeCoins > (nMoneySupply * .29)) {
2308  ret = blockValue * .542;
2309  } else if (mNodeCoins <= (nMoneySupply * .31) && mNodeCoins > (nMoneySupply * .30)) {
2310  ret = blockValue * .54;
2311  } else if (mNodeCoins <= (nMoneySupply * .32) && mNodeCoins > (nMoneySupply * .31)) {
2312  ret = blockValue * .538;
2313  } else if (mNodeCoins <= (nMoneySupply * .33) && mNodeCoins > (nMoneySupply * .32)) {
2314  ret = blockValue * .536;
2315  } else if (mNodeCoins <= (nMoneySupply * .34) && mNodeCoins > (nMoneySupply * .33)) {
2316  ret = blockValue * .534;
2317  } else if (mNodeCoins <= (nMoneySupply * .35) && mNodeCoins > (nMoneySupply * .34)) {
2318  ret = blockValue * .532;
2319  } else if (mNodeCoins <= (nMoneySupply * .36) && mNodeCoins > (nMoneySupply * .35)) {
2320  ret = blockValue * .53;
2321  } else if (mNodeCoins <= (nMoneySupply * .37) && mNodeCoins > (nMoneySupply * .36)) {
2322  ret = blockValue * .528;
2323  } else if (mNodeCoins <= (nMoneySupply * .38) && mNodeCoins > (nMoneySupply * .37)) {
2324  ret = blockValue * .526;
2325  } else if (mNodeCoins <= (nMoneySupply * .39) && mNodeCoins > (nMoneySupply * .38)) {
2326  ret = blockValue * .524;
2327  } else if (mNodeCoins <= (nMoneySupply * .40) && mNodeCoins > (nMoneySupply * .39)) {
2328  ret = blockValue * .522;
2329  } else if (mNodeCoins <= (nMoneySupply * .41) && mNodeCoins > (nMoneySupply * .40)) {
2330  ret = blockValue * .52;
2331  } else if (mNodeCoins <= (nMoneySupply * .42) && mNodeCoins > (nMoneySupply * .41)) {
2332  ret = blockValue * .518;
2333  } else if (mNodeCoins <= (nMoneySupply * .43) && mNodeCoins > (nMoneySupply * .42)) {
2334  ret = blockValue * .516;
2335  } else if (mNodeCoins <= (nMoneySupply * .44) && mNodeCoins > (nMoneySupply * .43)) {
2336  ret = blockValue * .514;
2337  } else if (mNodeCoins <= (nMoneySupply * .45) && mNodeCoins > (nMoneySupply * .44)) {
2338  ret = blockValue * .512;
2339  } else if (mNodeCoins <= (nMoneySupply * .46) && mNodeCoins > (nMoneySupply * .45)) {
2340  ret = blockValue * .51;
2341  } else if (mNodeCoins <= (nMoneySupply * .47) && mNodeCoins > (nMoneySupply * .46)) {
2342  ret = blockValue * .508;
2343  } else if (mNodeCoins <= (nMoneySupply * .48) && mNodeCoins > (nMoneySupply * .47)) {
2344  ret = blockValue * .506;
2345  } else if (mNodeCoins <= (nMoneySupply * .49) && mNodeCoins > (nMoneySupply * .48)) {
2346  ret = blockValue * .504;
2347  } else if (mNodeCoins <= (nMoneySupply * .50) && mNodeCoins > (nMoneySupply * .49)) {
2348  ret = blockValue * .502;
2349  } else if (mNodeCoins <= (nMoneySupply * .51) && mNodeCoins > (nMoneySupply * .5)) {
2350  ret = blockValue * .50;
2351  } else if (mNodeCoins <= (nMoneySupply * .52) && mNodeCoins > (nMoneySupply * .51)) {
2352  ret = blockValue * .498;
2353  } else if (mNodeCoins <= (nMoneySupply * .53) && mNodeCoins > (nMoneySupply * .52)) {
2354  ret = blockValue * .496;
2355  } else if (mNodeCoins <= (nMoneySupply * .54) && mNodeCoins > (nMoneySupply * .53)) {
2356  ret = blockValue * .494;
2357  } else if (mNodeCoins <= (nMoneySupply * .55) && mNodeCoins > (nMoneySupply * .54)) {
2358  ret = blockValue * .492;
2359  } else if (mNodeCoins <= (nMoneySupply * .56) && mNodeCoins > (nMoneySupply * .55)) {
2360  ret = blockValue * .49;
2361  } else if (mNodeCoins <= (nMoneySupply * .57) && mNodeCoins > (nMoneySupply * .56)) {
2362  ret = blockValue * .488;
2363  } else if (mNodeCoins <= (nMoneySupply * .58) && mNodeCoins > (nMoneySupply * .57)) {
2364  ret = blockValue * .486;
2365  } else if (mNodeCoins <= (nMoneySupply * .59) && mNodeCoins > (nMoneySupply * .58)) {
2366  ret = blockValue * .484;
2367  } else if (mNodeCoins <= (nMoneySupply * .60) && mNodeCoins > (nMoneySupply * .59)) {
2368  ret = blockValue * .482;
2369  } else if (mNodeCoins <= (nMoneySupply * .61) && mNodeCoins > (nMoneySupply * .60)) {
2370  ret = blockValue * .48;
2371  } else if (mNodeCoins <= (nMoneySupply * .62) && mNodeCoins > (nMoneySupply * .61)) {
2372  ret = blockValue * .478;
2373  } else if (mNodeCoins <= (nMoneySupply * .63) && mNodeCoins > (nMoneySupply * .62)) {
2374  ret = blockValue * .476;
2375  } else if (mNodeCoins <= (nMoneySupply * .64) && mNodeCoins > (nMoneySupply * .63)) {
2376  ret = blockValue * .474;
2377  } else if (mNodeCoins <= (nMoneySupply * .65) && mNodeCoins > (nMoneySupply * .64)) {
2378  ret = blockValue * .472;
2379  } else if (mNodeCoins <= (nMoneySupply * .66) && mNodeCoins > (nMoneySupply * .65)) {
2380  ret = blockValue * .47;
2381  } else if (mNodeCoins <= (nMoneySupply * .67) && mNodeCoins > (nMoneySupply * .66)) {
2382  ret = blockValue * .468;
2383  } else if (mNodeCoins <= (nMoneySupply * .68) && mNodeCoins > (nMoneySupply * .67)) {
2384  ret = blockValue * .466;
2385  } else if (mNodeCoins <= (nMoneySupply * .69) && mNodeCoins > (nMoneySupply * .68)) {
2386  ret = blockValue * .464;
2387  } else if (mNodeCoins <= (nMoneySupply * .70) && mNodeCoins > (nMoneySupply * .69)) {
2388  ret = blockValue * .462;
2389  } else if (mNodeCoins <= (nMoneySupply * .71) && mNodeCoins > (nMoneySupply * .7)) {
2390  ret = blockValue * .46;
2391  } else if (mNodeCoins <= (nMoneySupply * .72) && mNodeCoins > (nMoneySupply * .71)) {
2392  ret = blockValue * .458;
2393  } else if (mNodeCoins <= (nMoneySupply * .73) && mNodeCoins > (nMoneySupply * .72)) {
2394  ret = blockValue * .456;
2395  } else if (mNodeCoins <= (nMoneySupply * .74) && mNodeCoins > (nMoneySupply * .73)) {
2396  ret = blockValue * .454;
2397  } else if (mNodeCoins <= (nMoneySupply * .75) && mNodeCoins > (nMoneySupply * .74)) {
2398  ret = blockValue * .452;
2399  } else if (mNodeCoins <= (nMoneySupply * .76) && mNodeCoins > (nMoneySupply * .75)) {
2400  ret = blockValue * .45;
2401  } else if (mNodeCoins <= (nMoneySupply * .77) && mNodeCoins > (nMoneySupply * .76)) {
2402  ret = blockValue * .448;
2403  } else if (mNodeCoins <= (nMoneySupply * .78) && mNodeCoins > (nMoneySupply * .77)) {
2404  ret = blockValue * .446;
2405  } else if (mNodeCoins <= (nMoneySupply * .79) && mNodeCoins > (nMoneySupply * .78)) {
2406  ret = blockValue * .444;
2407  } else if (mNodeCoins <= (nMoneySupply * .80) && mNodeCoins > (nMoneySupply * .79)) {
2408  ret = blockValue * .442;
2409  } else if (mNodeCoins <= (nMoneySupply * .81) && mNodeCoins > (nMoneySupply * .8)) {
2410  ret = blockValue * .44;
2411  } else if (mNodeCoins <= (nMoneySupply * .82) && mNodeCoins > (nMoneySupply * .81)) {
2412  ret = blockValue * .438;
2413  } else if (mNodeCoins <= (nMoneySupply * .83) && mNodeCoins > (nMoneySupply * .82)) {
2414  ret = blockValue * .436;
2415  } else if (mNodeCoins <= (nMoneySupply * .84) && mNodeCoins > (nMoneySupply * .83)) {
2416  ret = blockValue * .434;
2417  } else if (mNodeCoins <= (nMoneySupply * .85) && mNodeCoins > (nMoneySupply * .84)) {
2418  ret = blockValue * .432;
2419  } else if (mNodeCoins <= (nMoneySupply * .86) && mNodeCoins > (nMoneySupply * .85)) {
2420  ret = blockValue * .43;
2421  } else if (mNodeCoins <= (nMoneySupply * .87) && mNodeCoins > (nMoneySupply * .86)) {
2422  ret = blockValue * .428;
2423  } else if (mNodeCoins <= (nMoneySupply * .88) && mNodeCoins > (nMoneySupply * .87)) {
2424  ret = blockValue * .426;
2425  } else if (mNodeCoins <= (nMoneySupply * .89) && mNodeCoins > (nMoneySupply * .88)) {
2426  ret = blockValue * .424;
2427  } else if (mNodeCoins <= (nMoneySupply * .90) && mNodeCoins > (nMoneySupply * .89)) {
2428  ret = blockValue * .422;
2429  } else if (mNodeCoins <= (nMoneySupply * .91) && mNodeCoins > (nMoneySupply * .90)) {
2430  ret = blockValue * .42;
2431  } else if (mNodeCoins <= (nMoneySupply * .92) && mNodeCoins > (nMoneySupply * .91)) {
2432  ret = blockValue * .418;
2433  } else if (mNodeCoins <= (nMoneySupply * .93) && mNodeCoins > (nMoneySupply * .92)) {
2434  ret = blockValue * .416;
2435  } else if (mNodeCoins <= (nMoneySupply * .94) && mNodeCoins > (nMoneySupply * .93)) {
2436  ret = blockValue * .414;
2437  } else if (mNodeCoins <= (nMoneySupply * .95) && mNodeCoins > (nMoneySupply * .94)) {
2438  ret = blockValue * .412;
2439  } else if (mNodeCoins <= (nMoneySupply * .96) && mNodeCoins > (nMoneySupply * .95)) {
2440  ret = blockValue * .41;
2441  } else if (mNodeCoins <= (nMoneySupply * .97) && mNodeCoins > (nMoneySupply * .96)) {
2442  ret = blockValue * .408;
2443  } else if (mNodeCoins <= (nMoneySupply * .98) && mNodeCoins > (nMoneySupply * .97)) {
2444  ret = blockValue * .404;
2445  } else if (mNodeCoins <= (nMoneySupply * .99) && mNodeCoins > (nMoneySupply * .98)) {
2446  ret = blockValue * .402;
2447  } else {
2448  ret = blockValue * .40;
2449  }
2450  }
2451  return ret;
2452 }
2453 
2454 int64_t GetMasternodePayment(int nHeight, int64_t blockValue, int nMasternodeCount)
2455 {
2456  int64_t ret = 0;
2457  int64_t blockValueForSeeSaw = blockValue;
2458 
2459  if (nHeight >= Params().LAST_POW_BLOCK()) {
2460  return GetSeeSaw(blockValueForSeeSaw, nMasternodeCount, nHeight);
2461  }
2462 
2463  return ret;
2464 }
2465 
2466 void SetRingSize(int nHeight)
2467 {
2468  if (chainActive.Tip() == NULL) return;
2469  if (nHeight == 0) {
2470  nHeight = chainActive.Tip()->nHeight;
2471  }
2472 
2473  // Original Ring Sizes on all networks
2474  MIN_RING_SIZE = 11;
2475  MAX_RING_SIZE = 15;
2476 
2477  // Ring Sizes after the Hard Fork block
2478  // Add any Ring Size increases as the last check
2479  if (nHeight >= Params().HardForkRingSize()) {
2480  MIN_RING_SIZE = 27;
2481  MAX_RING_SIZE = 32;
2482  }
2483 
2484  // Testnet Hard Forks were different
2485  if (Params().NetworkID() == CBaseChainParams::TESTNET) {
2486  if (nHeight >= Params().HardForkRingSize()) {
2487  MIN_RING_SIZE = 25;
2488  MAX_RING_SIZE = 30;
2489  }
2490  if (nHeight >= Params().HardForkRingSize2()) {
2491  MIN_RING_SIZE = 30;
2492  MAX_RING_SIZE = 32;
2493  }
2494  }
2495 
2496  LogPrint(BCLog::SELECTCOINS, "%s: height %d: min ring size %d, max ring size: %d\n", __func__, nHeight, MIN_RING_SIZE, MAX_RING_SIZE);
2497  return;
2498 }
2499 
2501 {
2502  LOCK(cs_main);
2503  const int chainHeight = chainActive.Height();
2505  return true;
2506  static bool lockIBDState = false;
2507  if (lockIBDState)
2508  return false;
2509  bool state = (chainHeight < pindexBestHeader->nHeight - 24 * 6 ||
2511  if (!state)
2512  lockIBDState = true;
2513  return state;
2514 }
2515 
2516 bool fLargeWorkForkFound = false;
2519 
2520 static void AlertNotify(const std::string& strMessage, bool fThread)
2521 {
2523  std::string strCmd = GetArg("-alertnotify", "");
2524  if (strCmd.empty()) return;
2525 
2526  // Alert text should be plain ascii coming from a trusted source, but to
2527  // be safe we first strip anything not in safeChars, then add single quotes around
2528  // the whole string before passing it to the shell:
2529  std::string singleQuote("'");
2530  std::string safeStatus = SanitizeString(strMessage);
2531  safeStatus = singleQuote+safeStatus+singleQuote;
2532  boost::replace_all(strCmd, "%s", safeStatus);
2533 
2534  if (fThread)
2535  boost::thread t(runCommand, strCmd); // thread runs free
2536  else
2537  runCommand(strCmd);
2538 }
2539 
2541 {
2542  if (out.nValue == 0) return true;
2543  unsigned char zeroBlind[32];
2544  std::vector<unsigned char> commitment;
2545  CWallet::CreateCommitmentWithZeroBlind(out.nValue, zeroBlind, commitment);
2546  return commitment == out.commitment;
2547 }
2548 
2549 bool VerifyDerivedAddress(const CTxOut& out, std::string stealth)
2550 {
2551  CPubKey addressGenPub, pubView, pubSpend;
2552  bool hasPaymentID;
2553  uint64_t paymentID;
2554  if (!CWallet::DecodeStealthAddress(stealth, pubView, pubSpend, hasPaymentID, paymentID)) {
2555  LogPrintf("%s: Cannot decode foundational address\n", __func__);
2556  return false;
2557  }
2558 
2559  //reconstruct destination address from masternode address and tx private key
2560  CKey addressTxPriv;
2561  addressTxPriv.Set(&(out.txPriv[0]), &(out.txPriv[0]) + 32, true);
2562  CPubKey foundationTxPub = addressTxPriv.GetPubKey();
2563  CPubKey origin(out.txPub.begin(), out.txPub.end());
2564  if (foundationTxPub != origin) return false;
2565  CWallet::ComputeStealthDestination(addressTxPriv, pubView, pubSpend, addressGenPub);
2566  CScript foundationalScript = GetScriptForDestination(addressGenPub);
2567  return foundationalScript == out.scriptPubKey;
2568 }
2569 
2571 {
2573  // Before we get past initial download, we cannot reliably alert about forks
2574  // (we assume we don't get stuck on a fork before the last checkpoint)
2575  if (IsInitialBlockDownload())
2576  return;
2577 
2578  // If our best fork is no longer within 72 blocks (+/- 3 hours if no one mines it)
2579  // of our head, drop it
2581  pindexBestForkTip = NULL;
2582 
2583  if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork +
2585  6))) {
2588  std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
2589  pindexBestForkBase->phashBlock->ToString() + std::string("'");
2590  AlertNotify(warning, true);
2591  }
2592  }
2595  LogPrintf(
2596  "CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
2599  fLargeWorkForkFound = true;
2600  }
2601  } else {
2602  LogPrintf(
2603  "CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
2605  }
2606  } else {
2607  fLargeWorkForkFound = false;
2609  }
2610 }
2611 
2613 {
2615  // If we are on a fork that is sufficiently large, set a warning flag
2616  CBlockIndex* pfork = pindexNewForkTip;
2617  CBlockIndex* plonger = chainActive.Tip();
2618  while (pfork && pfork != plonger) {
2619  while (plonger && plonger->nHeight > pfork->nHeight)
2620  plonger = plonger->pprev;
2621  if (pfork == plonger)
2622  break;
2623  pfork = pfork->pprev;
2624  }
2625 
2626  // We define a condition which we should warn the user about as a fork of at least 7 blocks
2627  // who's tip is within 72 blocks (+/- 3 hours if no one mines it) of ours
2628  // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
2629  // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
2630  // hash rate operating on the fork.
2631  // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
2632  // the 7-block condition and from this always have the most-likely-to-cause-warning fork
2633  if (pfork &&
2634  (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
2635  pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
2636  chainActive.Height() - pindexNewForkTip->nHeight < 72) {
2637  pindexBestForkTip = pindexNewForkTip;
2638  pindexBestForkBase = pfork;
2639  }
2640 
2642 }
2643 
2644 // Requires cs_main.
2646 {
2647  if (howmuch == 0)
2648  return;
2649 
2650  CNodeState* state = State(pnode);
2651  if (state == NULL)
2652  return;
2653 
2654  CAddress cAddr(state->address, NODE_NETWORK);
2655  if (CNode::IsWhitelistedRange(cAddr)) return;
2656 
2657  state->nMisbehavior += howmuch;
2658  int banscore = GetArg("-banscore", 100);
2659  if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) {
2660  LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior - howmuch,
2661  state->nMisbehavior);
2662  state->fShouldBan = true;
2663  } else
2664  LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior);
2665 }
2666 
2667 void static InvalidChainFound(CBlockIndex* pindexNew)
2668 {
2669  if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
2670  pindexBestInvalid = pindexNew;
2671 
2672  LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
2673  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
2674  log(pindexNew->nChainWork.getdouble()) / log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()));
2675 
2676  const CBlockIndex* pChainTip = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
2677  LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
2678  pChainTip->GetBlockHash().GetHex(), pChainTip->nHeight, log(pChainTip->nChainWork.getdouble()) / log(2.0),
2679  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pChainTip->GetBlockTime()));
2681 }
2682 
2683 void static InvalidBlockFound(CBlockIndex* pindex, const CValidationState& state)
2684 {
2685  int nDoS = 0;
2686  if (state.IsInvalid(nDoS)) {
2687  std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
2688  if (it != mapBlockSource.end() && State(it->second)) {
2689  CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH),
2690  pindex->GetBlockHash()};
2691  State(it->second)->rejects.push_back(reject);
2692  if (nDoS > 0) {
2693  LOCK(cs_main);
2694  Misbehaving(it->second, nDoS);
2695  }
2696  }
2697  }
2698  if (!state.CorruptionPossible()) {
2699  pindex->nStatus |= BLOCK_FAILED_VALID;
2700  setDirtyBlockIndex.insert(pindex);
2701  setBlockIndexCandidates.erase(pindex);
2702  InvalidChainFound(pindex);
2703  }
2704 }
2705 
2706 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo& txundo, int nHeight)
2707 {
2708  // mark inputs spent
2709  if (!tx.IsCoinAudit() && !tx.IsCoinBase() && tx.IsCoinStake()) {
2710  txundo.vprevout.reserve(tx.vin.size());
2711  for (const CTxIn& txin : tx.vin) {
2712  txundo.vprevout.push_back(CTxInUndo());
2713  bool ret = inputs.ModifyCoins(txin.prevout.hash)->Spend(txin.prevout, txundo.vprevout.back());
2714  //assert(ret);
2715  }
2716  }
2717 
2718  // add outputs
2719  inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
2720 }
2721 
2723 {
2724  const CScript& scriptSig = ptxTo->vin[nIn].scriptSig;
2726  &error)) {
2727  if (error != SCRIPT_ERR_EVAL_FALSE) {
2728  return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn,
2730  }
2731  }
2732  return true;
2733 }
2734 
2735 std::map<COutPoint, COutPoint> mapInvalidOutPoints;
2736 
2737 // Populate global map (mapInvalidOutPoints) of invalid/fraudulent OutPoints that are banned from being used on the chain.
2740 
2741 bool ValidOutPoint(const COutPoint out, int nHeight)
2742 {
2743  bool isInvalid = invalid_out::ContainsOutPoint(out);
2744 
2745  return !isInvalid;
2746 }
2747 
2749 {
2750  CAmount nValue = 0;
2751  for (auto it : mapInvalidOutPoints) {
2752  const COutPoint out = it.first;
2753  bool fSpent = false;
2754  CCoinsViewCache cache(pcoinsTip);
2755  const CCoins* coins = cache.AccessCoins(out.hash);
2756  if (!coins || !coins->IsAvailable(out.n))
2757  fSpent = true;
2758 
2759  if (!fSpent)
2760  nValue += coins->vout[out.n].nValue;
2761  }
2762 
2763  return nValue;
2764 }
2765 
2766 bool CheckInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck>* pvChecks)
2767 {
2768  if (!tx.IsCoinBase()) {
2769  if (pvChecks)
2770  pvChecks->reserve(tx.vin.size());
2771 
2772  // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
2773  // for an attacker to attempt to split the network.
2774  if (!CheckHaveInputs(inputs, tx))
2775  return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString()));
2776 
2777  // While checking, GetBestBlock() refers to the parent block.
2778  // This is also true for mempool checks.
2779  CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
2780  int nSpendHeight = pindexPrev->nHeight + 1;
2781  if (tx.IsCoinStake()) {
2782  for (unsigned int i = 0; i < tx.vin.size(); i++) {
2783  const COutPoint& prevout = tx.vin[i].prevout;
2784  CTransaction prev;
2785  uint256 bh;
2786  if (!GetTransaction(prevout.hash, prev, bh, true)) {
2787  return state.Invalid(
2788  error("CheckInputs() : Inputs not available"),
2789  REJECT_INVALID, "bad-txns");
2790  }
2791 
2792  // If prev is coinbase, check that it's matured
2793  if (prev.IsCoinBase() || prev.IsCoinStake()) {
2794  if (nSpendHeight - mapBlockIndex[bh]->nHeight < Params().COINBASE_MATURITY())
2795  return state.Invalid(
2796  error("CheckInputs() : tried to spend coinbase at depth %d, coinstake=%d",
2797  nSpendHeight - mapBlockIndex[bh]->nHeight, prev.IsCoinStake()),
2798  REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
2799  }
2800  }
2801  }
2802 
2803  // The first loop above does all the inexpensive checks.
2804  // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
2805  // Helps prevent CPU exhaustion attacks.
2806 
2807  // Skip ECDSA signature verification when connecting blocks
2808  // before the last block chain checkpoint. This is safe because block merkle hashes are
2809  // still computed and checked, and any change will be caught at the next checkpoint.
2810  //standard transaction does not have script
2811  if (fScriptChecks && tx.IsCoinStake()) {
2812  for (unsigned int i = 0; i < tx.vin.size(); i++) {
2813  const COutPoint& prevout = tx.vin[i].prevout;
2814  CTransaction prev;
2815  uint256 bh;
2816  if (!GetTransaction(prevout.hash, prev, bh, true)) {
2817  return state.Invalid(
2818  error("CheckInputs() : Inputs not available"),
2819  REJECT_INVALID, "bad-txns");
2820  }
2821  CCoins coins(prev, mapBlockIndex[bh]->nHeight);
2822 
2823  // Verify signature
2824  CScriptCheck check(coins, tx, i, flags, cacheStore);
2825  if (pvChecks) {
2826  pvChecks->push_back(CScriptCheck());
2827  check.swap(pvChecks->back());
2828  } else if (!check()) {
2829  if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
2830  // Check whether the failure was caused by a
2831  // non-mandatory script verification check, such as
2832  // non-standard DER encodings or non-null dummy
2833  // arguments; if so, don't trigger DoS protection to
2834  // avoid splitting the network between upgraded and
2835  // non-upgraded nodes.
2836  CScriptCheck check(coins, tx, i,
2837  flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
2838  if (check())
2839  return state.Invalid(false, REJECT_NONSTANDARD,
2840  strprintf("non-mandatory-script-verify-flag (%s)",
2841  ScriptErrorString(check.GetScriptError())));
2842  }
2843  // Failures of other flags indicate a transaction that is
2844  // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
2845  // such nodes as they are not following the protocol. That
2846  // said during an upgrade careful thought should be taken
2847  // as to the correct behavior - we may want to continue
2848  // peering with non-upgraded nodes even after a soft-fork
2849  // super-majority vote has passed.
2850  return state.DoS(100, false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
2851  }
2852  }
2853  }
2854  }
2855 
2856  return true;
2857 }
2858 
2860 static bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2861 {
2862  strMiscWarning = strMessage;
2863  LogPrintf("*** %s\n", strMessage);
2865  userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
2867  StartShutdown();
2868  return false;
2869 }
2870 
2871 static bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2872 {
2873  AbortNode(strMessage, userMessage);
2874  return state.Error(strMessage);
2875 }
2876 
2877 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2878 {
2879  if (pindex->GetBlockHash() != view.GetBestBlock())
2880  LogPrintf("%s : pindex=%s view=%s\n", __func__, pindex->GetBlockHash().GetHex(), view.GetBestBlock().GetHex());
2881  assert(pindex->GetBlockHash() == view.GetBestBlock());
2882 
2883  if (pfClean)
2884  *pfClean = false;
2885 
2886  bool fClean = true;
2887 
2888  CBlockUndo blockUndo;
2889  CDiskBlockPos pos = pindex->GetUndoPos();
2890  if (pos.IsNull())
2891  return error("DisconnectBlock() : no undo data available");
2892  if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2893  return error("DisconnectBlock() : failure reading undo data");
2894 
2895  if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2896  return error("DisconnectBlock() : block and undo data inconsistent");
2897 
2898  // undo transactions in reverse order
2899  for (int i = block.vtx.size() - 1; i >= 0; i--) {
2900  const CTransaction& tx = block.vtx[i];
2901 
2902  uint256 hash = tx.GetHash();
2903 
2904  // Check that all outputs are available and match the outputs in the block itself
2905  // exactly. Note that transactions with only provably unspendable outputs won't
2906  // have outputs available even in the block itself, so we handle that case
2907  // specially with outsEmpty.
2908  {
2909  CCoins outsEmpty;
2910  CCoinsModifier outs = view.ModifyCoins(hash);
2911  outs->ClearUnspendable();
2912 
2913  CCoins outsBlock(tx, pindex->nHeight);
2914  // The CCoins serialization does not serialize negative numbers.
2915  // No network rules currently depend on the version here, so an inconsistency is harmless
2916  // but it must be corrected before txout nversion ever influences a network rule.
2917  if (outsBlock.nVersion < 0)
2918  outs->nVersion = outsBlock.nVersion;
2919  if (*outs != outsBlock)
2920  fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
2921 
2922  // remove outputs
2923  outs->Clear();
2924  }
2925 
2926  // restore inputs
2927  if (!tx.IsCoinBase() && tx.IsCoinStake()) { // not coinbases because they dont have traditional inputs
2928  const CTxUndo& txundo = blockUndo.vtxundo[i - 1];
2929  if (txundo.vprevout.size() != tx.vin.size())
2930  return error(
2931  "DisconnectBlock() : transaction and undo data inconsistent - txundo.vprevout.siz=%d tx.vin.siz=%d",
2932  txundo.vprevout.size(), tx.vin.size());
2933  for (unsigned int j = tx.vin.size(); j-- > 0;) {
2934  const COutPoint& out = tx.vin[j].prevout;
2935  const CTxInUndo& undo = txundo.vprevout[j];
2936  CCoinsModifier coins = view.ModifyCoins(out.hash);
2937  if (undo.nHeight != 0) {
2938  // undo data contains height: this is the last output of the prevout tx being spent
2939  if (!coins->IsPruned())
2940  fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
2941  coins->Clear();
2942  coins->fCoinBase = undo.fCoinBase;
2943  coins->nHeight = undo.nHeight;
2944  coins->nVersion = undo.nVersion;
2945  } else {
2946  if (coins->IsPruned())
2947  fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
2948  }
2949  if (coins->IsAvailable(out.n))
2950  fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
2951  if (coins->vout.size() < out.n + 1)
2952  coins->vout.resize(out.n + 1);
2953  coins->vout[out.n] = undo.txout;
2954  }
2955  }
2956  }
2957 
2958  // move best block pointer to prevout block
2959  view.SetBestBlock(pindex->pprev->GetBlockHash());
2960 
2961  if (pfClean) {
2962  *pfClean = fClean;
2963  return true;
2964  } else {
2965  return fClean;
2966  }
2967 }
2968 
2969 void static FlushBlockFile(bool fFinalize = false)
2970 {
2971  LOCK(cs_LastBlockFile);
2972 
2973  CDiskBlockPos posOld(nLastBlockFile, 0);
2974 
2975  FILE* fileOld = OpenBlockFile(posOld);
2976  if (fileOld) {
2977  if (fFinalize)
2978  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2979  FileCommit(fileOld);
2980  fclose(fileOld);
2981  }
2982 
2983  fileOld = OpenUndoFile(posOld);
2984  if (fileOld) {
2985  if (fFinalize)
2986  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2987  FileCommit(fileOld);
2988  fclose(fileOld);
2989  }
2990 }
2991 
2992 bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize);
2993 
2994 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2995 
2997 {
2998  util::ThreadRename("prcycoin-scriptch");
2999  scriptcheckqueue.Thread();
3000 }
3001 
3002 bool RecalculatePRCYSupply(int nHeightStart)
3003 {
3004  const int chainHeight = chainActive.Height();
3005  if (nHeightStart > chainHeight)
3006  return false;
3007 
3008  CBlockIndex* pindex = chainActive[nHeightStart];
3009  CAmount nSupplyPrev = pindex->pprev->nMoneySupply;
3010 
3011  uiInterface.ShowProgress(_("Recalculating PRCY supply..."), 0);
3012  while (true) {
3013  if (pindex->nHeight % 1000 == 0) {
3014  LogPrintf("%s : block %d...\n", __func__, pindex->nHeight);
3015  int percent = std::max(1, std::min(99, (int)((double)((pindex->nHeight - nHeightStart) * 100) / (chainHeight - nHeightStart))));
3016  uiInterface.ShowProgress(_("Recalculating PRCY supply..."), percent);
3017  }
3018  CBlock block;
3019  assert(ReadBlockFromDisk(block, pindex));
3020 
3021  CAmount nValueIn = 0;
3022  CAmount nValueOut = 0;
3023  CAmount nFees = 0;
3024  for (const CTransaction& tx : block.vtx) {
3025  nFees += tx.nTxFee;
3026  if (tx.IsCoinStake()) {
3027  for (unsigned int i = 0; i < tx.vin.size(); i++) {
3028  CAmount nTemp; // = txPrev.vout[prevout.n].nValue;
3029  uint256 hashBlock;
3030  CTransaction txPrev;
3031  GetTransaction(tx.vin[i].prevout.hash, txPrev, hashBlock, true);
3032  const CTxOut& out = txPrev.vout[tx.vin[i].prevout.n];
3033  if (out.nValue > 0) {
3034  //UTXO created by coinbase/coin audit/coinstake transaction
3035  if (!VerifyZeroBlindCommitment(out)) {
3036  throw std::runtime_error("Commitment for coinstake not correct: failed to verify blind commitment");
3037  }
3038  nValueIn += out.nValue;
3039  } else {
3040  uint256 val = out.maskValue.amount;
3041  uint256 mask = out.maskValue.mask;
3042  CKey decodedMask;
3043  CPubKey sharedSec;
3044  sharedSec.Set(tx.vin[i].encryptionKey.begin(), tx.vin[i].encryptionKey.begin() + 33);
3045  ECDHInfo::Decode(mask.begin(), val.begin(), sharedSec, decodedMask, nTemp);
3046  //Verify commitment
3047  std::vector<unsigned char> commitment;
3048  CWallet::CreateCommitment(decodedMask.begin(), nTemp, commitment);
3049  if (commitment != out.commitment) {
3050  throw std::runtime_error("Commitment for coinstake not correct");
3051  }
3052  nValueIn += nTemp;
3053  }
3054  }
3055  }
3056 
3057  for (unsigned int i = 0; i < tx.vout.size(); i++) {
3058  if (i == 0 && tx.IsCoinStake())
3059  continue;
3060 
3061  nValueOut += tx.vout[i].nValue;
3062  }
3063  }
3064 
3065  // Rewrite money supply
3066  pindex->nMoneySupply = nSupplyPrev + nValueOut - nValueIn - nFees;
3067  nSupplyPrev = pindex->nMoneySupply;
3068 
3069  assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)));
3070 
3071  if (pindex->nHeight < chainHeight)
3072  pindex = chainActive.Next(pindex);
3073  else
3074  break;
3075  }
3076  return true;
3077 }
3078 
3079 static int64_t nTimeVerify = 0;
3080 static int64_t nTimeConnect = 0;
3081 static int64_t nTimeIndex = 0;
3082 static int64_t nTimeCallbacks = 0;
3083 static int64_t nTimeTotal = 0;
3084 
3085 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck, bool fAlreadyChecked)
3086 {
3088  // Check it again in case a previous version let a bad block in
3089  if (!fAlreadyChecked && !CheckBlock(block, state, !fJustCheck, !fJustCheck))
3090  return false;
3091 
3092  //Check PoA block time
3093  if (block.IsPoABlockByVersion() && !CheckPoAblockTime(block)) {
3094  return state.Invalid(error("ConnectBlock(): Time elapsed between two PoA blocks is too short"),
3095  REJECT_INVALID, "time-too-new");
3096  }
3097  //Check PoA block not auditing PoS blocks audited by its previous PoA block
3098  if (block.IsPoABlockByVersion() && !CheckPoABlockNotAuditingOverlap(block)) {
3099  return state.Invalid(error("ConnectBlock(): PoA block auditing PoS blocks previously audited by its parent"),
3100  REJECT_INVALID, "overlap-audit");
3101  }
3102 
3106  if (!fVerifyingBlocks && block.IsProofOfAudit()) {
3107  //Check PoA consensus rules
3108  if (!CheckPoAContainRecentHash(block)) {
3109  return state.DoS(100, error("ConnectBlock(): PoA block should contain only non-audited recent PoS blocks"),
3110  REJECT_INVALID, "blocks-already-audited");
3111  }
3112 
3113  if (!CheckNumberOfAuditedPoSBlocks(block, pindex)) {
3114  return state.DoS(100, error("ConnectBlock(): A PoA block should audit at least 59 PoS blocks and no more than 120 PoS blocks (65 max after block 169869)"),
3115  REJECT_INVALID, "incorrect-number-audited-blocks");
3116  }
3117 
3118  if (!CheckPoABlockNotContainingPoABlockInfo(block, pindex)) {
3119  return state.DoS(100, error("ConnectBlock(): A PoA block should not audit any existing PoA blocks"),
3120  REJECT_INVALID, "auditing-poa-block");
3121  }
3122 
3123  if (!CheckPoABlockRewardAmount(block, pindex)) {
3124  return state.DoS(100, error("ConnectBlock(): This PoA block reward does not match the value it should"),
3125  REJECT_INVALID, "incorrect-reward");
3126  }
3127 
3128  if (!CheckPoABlockPaddingAmount(block, pindex)) {
3129  return state.DoS(100, error("ConnectBlock(): This PoA block does not have the correct padding"),
3130  REJECT_INVALID, "incorrect-padding");
3131  }
3132 
3133  if (block.GetBlockTime() >= GetAdjustedTime() + 2 * 60) {
3134  return state.DoS(100, error("ConnectBlock(): A PoA block should not be in the future"),
3135  REJECT_INVALID, "time-in-future");
3136  }
3137  }
3138 
3139  // verify that the view's current state corresponds to the previous block
3140  uint256 hashPrevBlock = pindex->pprev == NULL ? UINT256_ZERO : pindex->pprev->GetBlockHash();
3141  if (hashPrevBlock != view.GetBestBlock())
3142  LogPrintf("%s: hashPrev=%s view=%s\n", __func__, hashPrevBlock.ToString().c_str(),
3143  view.GetBestBlock().ToString().c_str());
3144  assert(hashPrevBlock == view.GetBestBlock());
3145  // Special case for the genesis block, skipping connection of its transactions
3146  // (its coinbase is unspendable)
3147  if (block.GetHash() == Params().HashGenesisBlock()) {
3148  view.SetBestBlock(pindex->GetBlockHash());
3149  return true;
3150  }
3151  int nHeight = pindex->nHeight;
3152  if (nHeight <= Params().LAST_POW_BLOCK() && block.IsProofOfStake())
3153  return state.DoS(100, error("ConnectBlock() : PoS period not active"),
3154  REJECT_INVALID, "PoS-early");
3155 
3156  if (nHeight > Params().LAST_POW_BLOCK() && block.IsProofOfWork())
3157  return state.DoS(100, error("ConnectBlock() : PoW period ended"),
3158  REJECT_INVALID, "PoW-ended");
3159 
3160  bool fScriptChecks = nHeight >= Checkpoints::GetTotalBlocksEstimate();
3161 
3162  // If scripts won't be checked anyways, don't bother seeing if CLTV is activated
3163  bool fCLTVIsActivated = false;
3164  if (fScriptChecks && pindex->pprev) {
3165  fCLTVIsActivated = pindex->pprev->nHeight >= Params().BIP65ActivationHeight();
3166  }
3167 
3168  CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
3169 
3170  int64_t nTimeStart = GetTimeMicros();
3171  CAmount nFees = 0;
3172  int nInputs = 0;
3173  unsigned int nSigOps = 0;
3174  CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
3175  std::vector<std::pair<uint256, CDiskTxPos> > vPos;
3176  vPos.reserve(block.vtx.size());
3177  CBlockUndo blockundo;
3178  blockundo.vtxundo.reserve(block.vtx.size() - 1);
3179  CAmount nValueOut = 0;
3180  CAmount nValueIn = 0;
3181  unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_CURRENT;
3182  for (unsigned int i = 0; i < block.vtx.size(); i++) {
3183  const CTransaction& tx = block.vtx[i];
3184  nInputs += tx.vin.size();
3185  nSigOps += GetLegacySigOpCount(tx);
3186  if (!block.IsPoABlockByVersion() && nSigOps > nMaxBlockSigOps)
3187  return state.DoS(100, error("ConnectBlock() : too many sigops"),
3188  REJECT_INVALID, "bad-blk-sigops");
3189 
3190  if (!block.IsPoABlockByVersion() && !tx.IsCoinBase()) {
3191  if (!tx.IsCoinStake()) {
3192  if (!tx.IsCoinAudit()) {
3193  if (!VerifyRingSignatureWithTxFee(tx, pindex))
3194  return state.DoS(100, error("ConnectBlock() : Ring Signature check for transaction %s failed", tx.GetHash().ToString()),
3195  REJECT_INVALID, "bad-ring-signature");
3196  if (!VerifyBulletProofAggregate(tx))
3197  return state.DoS(100, error("ConnectBlock() : Bulletproof check for transaction %s failed", tx.GetHash().ToString()),
3198  REJECT_INVALID, "bad-bulletproof");
3199  }
3200  }
3201 
3202  // Check that the inputs are not marked as invalid/fraudulent
3203  uint256 bh = pindex->GetBlockHash();
3204  for (const CTxIn& in : tx.vin) {
3205  const CKeyImage& keyImage = in.keyImage;
3206  std::string kh = keyImage.GetHex();
3207  if (IsSpentKeyImage(kh, bh)) {
3208  //remove transaction from the pool?
3209  return state.Invalid(error("ConnectBlock() : key image already spent"),
3210  REJECT_DUPLICATE, "bad-txns-inputs-spent");
3211  }
3212  pblocktree->WriteKeyImage(keyImage.GetHex(), bh);
3213  if (pwalletMain != NULL && !pwalletMain->IsLocked()) {
3214  if (pwalletMain->GetDebit(in, ISMINE_ALL)) {
3215  pwalletMain->keyImagesSpends[keyImage.GetHex()] = true;
3216  }
3217  pwalletMain->pendingKeyImages.remove(keyImage.GetHex());
3218  }
3219  if (!ValidOutPoint(in.prevout) && nHeight > Params().FixChecks()) {
3220  return state.DoS(100, error("%s : tried to spend invalid input %s in tx %s", __func__, in.prevout.ToString(),
3221  tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs");
3222  }
3223  }
3224 
3225  for (unsigned int i = 0; i < tx.vin.size(); i++) {
3226  if (tx.IsCoinBase()) continue;
3227  //check output and decoys
3228  std::vector<COutPoint> alldecoys = tx.vin[i].decoys;
3229 
3230  alldecoys.push_back(tx.vin[i].prevout);
3231  for (size_t j = 0; j < alldecoys.size(); j++) {
3232  CTransaction prev;
3233  uint256 bh;
3234  if (!GetTransaction(alldecoys[j].hash, prev, bh, true)) {
3235  return false;
3236  }
3237  if (mapBlockIndex.count(bh) < 1) return false;
3238  if (!ValidOutPoint(alldecoys[j]) && nHeight > Params().FixChecks()) {
3239  return state.DoS(100, error("%s : tried to spend invalid decoy %s in tx %s", __func__, alldecoys[j].ToString(),
3240  tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs");
3241  }
3242  }
3243  }
3244 
3245  if (!tx.IsCoinStake() && tx.nTxFee < MIN_FEE && nHeight >= Params().HardFork())
3246  return state.Invalid(error("ConnectBlock() : Fee below Minimum. Network spam detected."),
3247  REJECT_INVALID, "bad-txns-low-fee");
3248  if (!tx.IsCoinStake())
3249  nFees += tx.nTxFee;
3250  CAmount valTemp = GetValueIn(view, tx);
3251  nValueIn += valTemp;
3252 
3253  std::vector<CScriptCheck> vChecks;
3255  if (fCLTVIsActivated)
3257 
3258  bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
3259  if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, nScriptCheckThreads ? &vChecks : NULL))
3260  return false;
3261  control.Add(vChecks);
3262  }
3263  nValueOut += tx.GetValueOut();
3264 
3265  CTxUndo undoDummy;
3266  if (i > 0) {
3267  blockundo.vtxundo.emplace_back();
3268  }
3269  UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), nHeight);
3270 
3271  vPos.emplace_back(tx.GetHash(), pos);
3272  pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
3273  }
3274 
3275  if (block.IsProofOfStake()) {
3276  const CAmount minStakingAmount = Params().MinimumStakeAmount();
3277  const CTransaction coinstake = block.vtx[1];
3278  size_t numUTXO = coinstake.vout.size();
3279  if (mapBlockIndex.count(block.hashPrevBlock) < 1) {
3280  return state.DoS(100, error("ConnectBlock() : Previous block not found, received block %s, previous %s, current tip %s", block.GetHash().GetHex(), block.hashPrevBlock.GetHex(), chainActive.Tip()->GetBlockHash().GetHex()));
3281  }
3282  CAmount blockValue = GetBlockValue(mapBlockIndex[block.hashPrevBlock]->nHeight);
3283  const CTxOut& mnOut = coinstake.vout[numUTXO - 1];
3284  std::string mnsa(mnOut.masternodeStealthAddress.begin(), mnOut.masternodeStealthAddress.end());
3285  if (!VerifyDerivedAddress(mnOut, mnsa))
3286  return state.DoS(100, error("ConnectBlock() : Incorrect derived address for masternode rewards"));
3287 
3288  if (nHeight >= Params().HardFork() && nValueIn < minStakingAmount)
3289  return state.DoS(100, error("ConnectBlock() : amount (%d) not allowed for staking. Min amount: %d",
3290  __func__, nValueIn, minStakingAmount), REJECT_INVALID, "bad-txns-stake");
3291 
3292  if (coinstake.vin.size() > 1 && nHeight > Params().FixChecks())
3293  return state.DoS(100, error("%s : multiple stake inputs not allowed", __func__), REJECT_INVALID, "bad-txns-stake");
3294  }
3295 
3296  // track money supply and mint amount info
3297  CAmount nMoneySupplyPrev = pindex->pprev ? pindex->pprev->nMoneySupply : 0;
3298  pindex->nMoneySupply = nMoneySupplyPrev + nValueOut - nValueIn - nFees;
3299  //LogPrintf("%s: nValueOut=%d, nValueIn=%d, nMoneySupplyPrev=%d, pindex->nMoneySupply=%d, nFees=%d", __func__, nValueOut, nValueIn, nMoneySupplyPrev, pindex->nMoneySupply, nFees);
3300  pindex->nMint = pindex->nMoneySupply - nMoneySupplyPrev + nFees;
3301 
3302  int64_t nTime1 = GetTimeMicros();
3303  nTimeConnect += nTime1 - nTimeStart;
3304  LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n",
3305  (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart),
3306  0.001 * (nTime1 - nTimeStart) / block.vtx.size(),
3307  nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs - 1), nTimeConnect * 0.000001);
3308 
3309  //PoW phase redistributed fees to miner. PoS stage destroys fees.
3310  CAmount nExpectedMint = GetBlockValue(pindex->pprev->nHeight);
3311  nExpectedMint += nFees;
3312 
3313  //Check that the block does not overmint
3314  if (!block.IsPoABlockByVersion() && !IsBlockValueValid(pindex->nHeight, nExpectedMint, pindex->nMint)) {
3315  return state.DoS(100, error("ConnectBlock() : reward pays too much (actual=%s vs limit=%s)",
3316  FormatMoney(pindex->nMint), FormatMoney(nExpectedMint)), REJECT_INVALID, "bad-cb-amount");
3317  }
3318 
3319  if (!control.Wait())
3320  return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
3321  int64_t nTime2 = GetTimeMicros();
3322  nTimeVerify += nTime2 - nTimeStart;
3323  LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1,
3324  0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs - 1),
3325  nTimeVerify * 0.000001);
3326 
3327  //IMPORTANT NOTE: Nothing before this point should actually store to disk (or even memory)
3328  if (fJustCheck)
3329  return true;
3330 
3331  // Write undo information to disk
3332  if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
3333  if (pindex->GetUndoPos().IsNull()) {
3334  CDiskBlockPos diskPosBlock;
3335  if (!FindUndoPos(state, pindex->nFile, diskPosBlock, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
3336  return error("ConnectBlock() : FindUndoPos failed");
3337  if (!blockundo.WriteToDisk(diskPosBlock, pindex->pprev->GetBlockHash()))
3338  return AbortNode(state, "Failed to write undo data");
3339 
3340  // update nUndoPos in block index
3341  pindex->nUndoPos = diskPosBlock.nPos;
3342  pindex->nStatus |= BLOCK_HAVE_UNDO;
3343  }
3344 
3346  setDirtyBlockIndex.insert(pindex);
3347  }
3348 
3349  if (fTxIndex)
3350  if (!pblocktree->WriteTxIndex(vPos))
3351  return AbortNode(state, "Failed to write transaction index");
3352 
3353  // add this block to the view's block chain
3354  view.SetBestBlock(pindex->GetBlockHash());
3355 
3356  int64_t nTime3 = GetTimeMicros();
3357  nTimeIndex += nTime3 - nTime2;
3358  LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
3359 
3360  // Watch for changes to the previous coinbase transaction.
3361  static uint256 hashPrevBestCoinBase;
3362  GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
3363  hashPrevBestCoinBase = block.vtx[0].GetHash();
3364 
3365  int64_t nTime4 = GetTimeMicros();
3366  nTimeCallbacks += nTime4 - nTime3;
3367  LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
3368 
3369  return true;
3370 }
3371 
3376 };
3377 
3383 bool static FlushStateToDisk(CValidationState& state, FlushStateMode mode)
3384 {
3385  LOCK(cs_main);
3386  static int64_t nLastWrite = 0;
3387  static int64_t nLastFlush = 0;
3388  static int64_t nLastSetChain = 0;
3389  try {
3390  int64_t nNow = GetTimeMicros();
3391  // Avoid writing/flushing immediately after startup.
3392  if (nLastWrite == 0) {
3393  nLastWrite = nNow;
3394  }
3395  if (nLastFlush == 0) {
3396  nLastFlush = nNow;
3397  }
3398  if (nLastSetChain == 0) {
3399  nLastSetChain = nNow;
3400  }
3401  size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
3402  // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
3403  bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
3404  // The cache is over the limit, we have to write now.
3405  bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
3406  // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
3407  bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
3408  // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
3409  bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
3410  // Combine all conditions that result in a full cache flush.
3411  bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush;
3412  // Write blocks and block index to disk.
3413  if (fDoFullFlush || fPeriodicWrite) {
3414  // Depend on nMinDiskSpace to ensure we can write block index
3415  if (!CheckDiskSpace(0))
3416  return state.Error("out of disk space");
3417  // First make sure all block and undo data is flushed to disk.
3418  FlushBlockFile();
3419  // Then update all block file information (which may refer to block and undo files).
3420  {
3421  std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
3422  vFiles.reserve(setDirtyFileInfo.size());
3423  for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
3424  vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
3425  setDirtyFileInfo.erase(it++);
3426  }
3427  std::vector<const CBlockIndex*> vBlocks;
3428  vBlocks.reserve(setDirtyBlockIndex.size());
3429  for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
3430  vBlocks.push_back(*it);
3431  setDirtyBlockIndex.erase(it++);
3432  }
3433 
3434  if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
3435  return AbortNode(state, "Files to write to block index database");
3436  }
3437  }
3438  nLastWrite = nNow;
3439  }
3440 
3441  // Flush best chain related state. This can only be done if the blocks / block index write was also done.
3442  if (fDoFullFlush) {
3443  // Typical CCoins structures on disk are around 128 bytes in size.
3444  // Pushing a new one to the database can cause it to be written
3445  // twice (once in the log, and once in the tables). This is already
3446  // an overestimation, as most will delete an existing entry or
3447  // overwrite one. Still, use a conservative safety factor of 2.
3448  if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
3449  return state.Error("out of disk space");
3450  // Flush the chainstate (which may refer to block index entries).
3451  if (!pcoinsTip->Flush())
3452  return AbortNode(state, "Failed to write to coin database");
3453  nLastFlush = nNow;
3454  }
3455  if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
3456  // Update best block in wallet (so we can detect restored wallets).
3458  nLastSetChain = nNow;
3459  }
3460 
3461  } catch (const std::runtime_error& e) {
3462  return AbortNode(state, std::string("System error while flushing: ") + e.what());
3463  }
3464  return true;
3465 }
3466 
3468 {
3469  CValidationState state;
3471 }
3472 
3474 void static UpdateTip(CBlockIndex* pindexNew)
3475 {
3476  chainActive.SetTip(pindexNew);
3477 
3478  // New best block
3481 
3482  {
3484  g_best_block = pindexNew->GetBlockHash();
3485  g_best_block_cv.notify_all();
3486  }
3487 
3488  const CBlockIndex* pChainTip = chainActive.Tip();
3489  LogPrintf("UpdateTip: new best=%s height=%d version=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n",
3490  pChainTip->GetBlockHash().GetHex(), pChainTip->nHeight, pChainTip->nVersion, log(pChainTip->nChainWork.getdouble()) / log(2.0), (unsigned long)pChainTip->nChainTx,
3491  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pChainTip->GetBlockTime()),
3493 
3494  // Check the version of the last 100 blocks to see if we need to upgrade:
3495  static bool fWarned = false;
3496  if (!IsInitialBlockDownload() && !fWarned) {
3497  int nUpgraded = 0;
3498  const CBlockIndex* pindex = chainActive.Tip();
3499  for (int i = 0; i < 100 && pindex != NULL; i++) {
3500  if (pindex->nVersion > CBlock::CURRENT_VERSION)
3501  ++nUpgraded;
3502  pindex = pindex->pprev;
3503  }
3504  if (nUpgraded > 0)
3505  LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
3506  if (nUpgraded > 100 / 2) {
3507  // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
3508  strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
3509  AlertNotify(strMiscWarning, true);
3510  fWarned = true;
3511  }
3512  }
3513 }
3514 
3516 bool static DisconnectTip(CValidationState& state)
3517 {
3518  CBlockIndex* pindexDelete = chainActive.Tip();
3519  assert(pindexDelete);
3521  // Read block from disk.
3522  CBlock block;
3523  if (!ReadBlockFromDisk(block, pindexDelete))
3524  return AbortNode(state, "Failed to read block");
3525  // Apply the block atomically to the chain state.
3526  int64_t nStart = GetTimeMicros();
3527  {
3528  CCoinsViewCache view(pcoinsTip);
3529  if (!DisconnectBlock(block, state, pindexDelete, view))
3530  return error("DisconnectTip() : DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
3531  assert(view.Flush());
3532  }
3533  LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
3534  // Write the chain state to disk, if necessary.
3535  if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS))
3536  return false;
3537  // Resurrect mempool transactions from the disconnected block.
3538  for (const CTransaction& tx : block.vtx) {
3539  // ignore validation errors in resurrected transactions
3540  std::list<CTransaction> removed;
3541  CValidationState stateDummy;
3542  if (tx.IsCoinBase() || tx.IsCoinStake() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
3543  mempool.remove(tx, removed, true);
3544  }
3547  // Update chainActive and related variables.
3548  UpdateTip(pindexDelete->pprev);
3549  // Let wallets know transactions went from 1-confirmed to
3550  // 0-confirmed or conflicted:void
3551 
3552  for (const CTransaction& tx : block.vtx) {
3553  SyncWithWallets(tx, NULL);
3554  }
3555  return true;
3556 }
3557 
3558 static int64_t nTimeReadFromDisk = 0;
3559 static int64_t nTimeConnectTotal = 0;
3560 static int64_t nTimeFlush = 0;
3561 static int64_t nTimeChainState = 0;
3562 static int64_t nTimePostConnect = 0;
3563 
3568 bool static ConnectTip(CValidationState& state, CBlockIndex* pindexNew, CBlock* pblock, bool fAlreadyChecked)
3569 {
3570  assert(pindexNew->pprev == chainActive.Tip());
3572  CCoinsViewCache view(pcoinsTip);
3573 
3574  if (pblock == NULL)
3575  fAlreadyChecked = false;
3576 
3577  // Read block from disk.
3578  int64_t nTime1 = GetTimeMicros();
3579  CBlock block;
3580  if (!pblock) {
3581  if (!ReadBlockFromDisk(block, pindexNew))
3582  return AbortNode(state, "Failed to read block");
3583  pblock = &block;
3584  }
3585  // Apply the block atomically to the chain state.
3586  int64_t nTime2 = GetTimeMicros();
3587  nTimeReadFromDisk += nTime2 - nTime1;
3588  int64_t nTime3;
3589  LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001,
3590  nTimeReadFromDisk * 0.000001);
3591  {
3592  CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
3593  bool rv = ConnectBlock(*pblock, state, pindexNew, view, false, fAlreadyChecked);
3594  GetMainSignals().BlockChecked(*pblock, state);
3595  if (!rv) {
3596  if (state.IsInvalid())
3597  InvalidBlockFound(pindexNew, state);
3598  return error("ConnectTip() : ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
3599  }
3600  mapBlockSource.erase(inv.hash);
3601  nTime3 = GetTimeMicros();
3602  nTimeConnectTotal += nTime3 - nTime2;
3603  LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001,
3604  nTimeConnectTotal * 0.000001);
3605  assert(view.Flush());
3606  }
3607  int64_t nTime4 = GetTimeMicros();
3608  nTimeFlush += nTime4 - nTime3;
3609  LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
3610 
3611  // Write the chain state to disk, if necessary. Always write to disk if this is the first of a new file.
3613  if (pindexNew->pprev && (pindexNew->GetBlockPos().nFile != pindexNew->pprev->GetBlockPos().nFile))
3614  flushMode = FLUSH_STATE_ALWAYS;
3615  if (!FlushStateToDisk(state, flushMode))
3616  return false;
3617  int64_t nTime5 = GetTimeMicros();
3618  nTimeChainState += nTime5 - nTime4;
3619  LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001,
3620  nTimeChainState * 0.000001);
3621 
3622  // Remove conflicting transactions from the mempool.
3623  std::list<CTransaction> txConflicted;
3624  mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
3626  // Update chainActive & related variables.
3627  UpdateTip(pindexNew);
3628  // Tell wallet about transactions that went from mempool
3629  // to conflicted:
3630  for (const CTransaction& tx : txConflicted) {
3631  SyncWithWallets(tx, NULL);
3632  }
3633  // ... and about transactions that got confirmed:
3634  for (const CTransaction& tx : pblock->vtx) {
3635  SyncWithWallets(tx, pblock);
3636  }
3637 
3638  int64_t nTime6 = GetTimeMicros();
3639  nTimePostConnect += nTime6 - nTime5;
3640  nTimeTotal += nTime6 - nTime1;
3641  LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001,
3642  nTimePostConnect * 0.000001);
3643  LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
3644  return true;
3645 }
3646 
3647 bool DisconnectBlocks(int nBlocks)
3648 {
3649  LOCK(cs_main);
3650 
3651  CValidationState state;
3652 
3653  LogPrintf("%s: Got command to replay %d blocks\n", __func__, nBlocks);
3654  for (int i = 0; i <= nBlocks; i++)
3655  DisconnectTip(state);
3656 
3657  return true;
3658 }
3659 
3660 void ReprocessBlocks(int nBlocks)
3661 {
3662  std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin();
3663  while (it != mapRejectedBlocks.end()) {
3664  //use a window twice as large as is usual for the nBlocks we want to reset
3665  if ((*it).second > GetTime() - (nBlocks * Params().TargetSpacing() * 2)) {
3666  BlockMap::iterator mi = mapBlockIndex.find((*it).first);
3667  if (mi != mapBlockIndex.end() && (*mi).second) {
3668  LOCK(cs_main);
3669 
3670  CBlockIndex* pindex = (*mi).second;
3671  LogPrintf("%s - %s\n", __func__, (*it).first.ToString());
3672 
3673  CValidationState state;
3674  ReconsiderBlock(state, pindex);
3675  }
3676  }
3677  ++it;
3678  }
3679 
3680  CValidationState state;
3681  {
3682  LOCK(cs_main);
3683  DisconnectBlocks(nBlocks);
3684  }
3685 
3686  if (state.IsValid()) {
3687  ActivateBestChain(state);
3688  }
3689 }
3690 
3692 {
3694  LOCK(mempool.cs);
3695  std::vector<CTransaction> tobeRemoveds;
3696  for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mempool.mapTx.begin(); it != mempool.mapTx.end(); ++it) {
3697  const CTransaction& tx = it->second.GetTx();
3698  for(size_t i = 0; i < tx.vin.size(); i++) {
3699  std::string kiHex = tx.vin[i].keyImage.GetHex();
3700  int confirm = 0;
3701  if (CheckKeyImageSpendInMainChain(kiHex, confirm)) {
3702  if (confirm > Params().MaxReorganizationDepth()) {
3703  tobeRemoveds.push_back(tx);
3704  break;
3705  }
3706  }
3707  bool needsBreak = false;
3708  std::vector<COutPoint> decoys = tx.vin[i].decoys;
3709  decoys.push_back(tx.vin[i].prevout);
3710  for (size_t j = 0; j < decoys.size(); j++) {
3711  CTransaction txPrev;
3712  uint256 hashBlock;
3713  if (!GetTransaction(decoys[j].hash, txPrev, hashBlock)) {
3714  tobeRemoveds.push_back(tx);
3715  needsBreak = true;
3716  break;
3717  }
3718 
3719  CBlockIndex* atTheblock = mapBlockIndex[hashBlock];
3720  if (!atTheblock) {
3721  tobeRemoveds.push_back(tx);
3722  needsBreak = true;
3723  break;
3724  } else {
3725  if (chainActive.Contains(atTheblock)) continue;
3726  if (1 + chainActive.Height() - atTheblock->nHeight > 100) {
3727  tobeRemoveds.push_back(tx);
3728  needsBreak = true;
3729  break;
3730  }
3731  }
3732  }
3733  if (needsBreak) break;
3734  }
3735  }
3736  std::list<CTransaction> removed;
3737  for(size_t i = 0; i < tobeRemoveds.size(); i++) {
3738  mempool.remove(tobeRemoveds[i], removed, true);
3739  }
3740 }
3741 
3746 static CBlockIndex* FindMostWorkChain()
3747 {
3748  do {
3749  CBlockIndex* pindexNew = NULL;
3750 
3751  // Find the best candidate header.
3752  {
3753  std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
3754  if (it == setBlockIndexCandidates.rend())
3755  return NULL;
3756  pindexNew = *it;
3757  }
3758 
3759  // Check whether all blocks on the path between the currently active chain and the candidate are valid.
3760  // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
3761  CBlockIndex* pindexTest = pindexNew;
3762  bool fInvalidAncestor = false;
3763  while (pindexTest && !chainActive.Contains(pindexTest)) {
3764  assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
3765 
3766  // Pruned nodes may have entries in setBlockIndexCandidates for
3767  // which block files have been deleted. Remove those as candidates
3768  // for the most work chain if we come across them; we can't switch
3769  // to a chain unless we have all the non-active-chain parent blocks.
3770  bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
3771  bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
3772  if (fFailedChain || fMissingData) {
3773  // Candidate chain is not usable (either invalid or missing data)
3774  if (fFailedChain &&
3775  (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
3776  pindexBestInvalid = pindexNew;
3777  CBlockIndex* pindexFailed = pindexNew;
3778  // Remove the entire chain from the set.
3779  while (pindexTest != pindexFailed) {
3780  if (fFailedChain) {
3781  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
3782  } else if (fMissingData) {
3783  // If we're missing data, then add back to mapBlocksUnlinked,
3784  // so that if the block arrives in the future we can try adding
3785  // to setBlockIndexCandidates again.
3786  mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
3787  }
3788  setBlockIndexCandidates.erase(pindexFailed);
3789  pindexFailed = pindexFailed->pprev;
3790  }
3791  setBlockIndexCandidates.erase(pindexTest);
3792  fInvalidAncestor = true;
3793  break;
3794  }
3795  pindexTest = pindexTest->pprev;
3796  }
3797  if (!fInvalidAncestor)
3798  return pindexNew;
3799  } while (true);
3800 }
3801 
3803 static void PruneBlockIndexCandidates()
3804 {
3805  // Note that we can't delete the current block itself, as we may need to return to it later in case a
3806  // reorganization to a better block fails.
3807  std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3808  while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
3809  setBlockIndexCandidates.erase(it++);
3810  }
3811  // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3812  assert(!setBlockIndexCandidates.empty());
3813 }
3814 
3819 static bool
3820 ActivateBestChainStep(CValidationState& state, CBlockIndex* pindexMostWork, CBlock* pblock, bool fAlreadyChecked)
3821 {
3823  if (pblock == NULL)
3824  fAlreadyChecked = false;
3825  bool fInvalidFound = false;
3826  const CBlockIndex* pindexOldTip = chainActive.Tip();
3827  const CBlockIndex* pindexFork = chainActive.FindFork(pindexMostWork);
3828 
3829  // Disconnect active blocks which are no longer in the best chain.
3830  while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
3831  if (!DisconnectTip(state))
3832  return false;
3833  }
3834 
3835  // Build list of new blocks to connect.
3836  std::vector<CBlockIndex*> vpindexToConnect;
3837  bool fContinue = true;
3838  int nHeight = pindexFork ? pindexFork->nHeight : -1;
3839  while (fContinue && nHeight != pindexMostWork->nHeight) {
3840  // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3841  // a few blocks along the way.
3842  int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3843  vpindexToConnect.clear();
3844  vpindexToConnect.reserve(nTargetHeight - nHeight);
3845  CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3846  while (pindexIter && pindexIter->nHeight != nHeight) {
3847  vpindexToConnect.push_back(pindexIter);
3848  pindexIter = pindexIter->pprev;
3849  }
3850  nHeight = nTargetHeight;
3851 
3852  // Connect new blocks.
3853  BOOST_REVERSE_FOREACH (CBlockIndex* pindexConnect, vpindexToConnect) {
3854  if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL, fAlreadyChecked)) {
3855  if (state.IsInvalid()) {
3856  // The block violates a consensus rule.
3857  if (!state.CorruptionPossible())
3858  InvalidChainFound(vpindexToConnect.back());
3859  state = CValidationState();
3860  fInvalidFound = true;
3861  fContinue = false;
3862  break;
3863  } else {
3864  // A system error occurred (disk space, database error, ...).
3865  return false;
3866  }
3867  } else {
3868  PruneBlockIndexCandidates();
3869  if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
3870  // We're in a better position than we were. Return temporarily to release the lock.
3871  fContinue = false;
3872  break;
3873  }
3874  }
3875  }
3876  }
3877 
3878  // Callbacks/notifications for a new best chain.
3879  if (fInvalidFound)
3880  CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
3881  else
3883 
3884  return true;
3885 }
3886 
3892 bool ActivateBestChain(CValidationState& state, CBlock* pblock, bool fAlreadyChecked)
3893 {
3894  // Note that while we're often called here from ProcessNewBlock, this is
3895  // far from a guarantee. Things in the P2P/RPC will often end up calling
3896  // us in the middle of ProcessNewBlock - do not assume pblock is set
3897  // sanely for performance or correctness!
3899 
3900  CBlockIndex* pindexNewTip = nullptr;
3901  CBlockIndex* pindexMostWork = nullptr;
3902  do {
3903  boost::this_thread::interruption_point();
3904 
3905  const CBlockIndex *pindexFork;
3906  bool fInitialDownload;
3907  while (true) {
3908  TRY_LOCK(cs_main, lockMain);
3909  if (!lockMain) {
3910  MilliSleep(50);
3911  continue;
3912  }
3913  CBlockIndex *pindexOldTip = chainActive.Tip();
3914  pindexMostWork = FindMostWorkChain();
3915  // Whether we have anything to do at all.
3916  if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
3917  return true;
3918  if (!ActivateBestChainStep(state, pindexMostWork,
3919  pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL,
3920  fAlreadyChecked))
3921  return false;
3922  pindexNewTip = chainActive.Tip();
3923  pindexFork = chainActive.FindFork(pindexOldTip);
3924  fInitialDownload = IsInitialBlockDownload();
3925  break;
3926  }
3927 
3928  // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3929  // Notifications/callbacks that can run without cs_main
3930  // Always notify the UI if a new block tip was connected
3931  if (pindexFork != pindexNewTip) {
3932 
3933  // Notify the UI
3934  uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
3935 
3936  // Notifications/callbacks that can run without cs_main
3937  if (!fInitialDownload) {
3938  uint256 hashNewTip = pindexNewTip->GetBlockHash();
3939  // Relay inventory, but don't relay old inventory during initial block download.
3940  int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
3941  {
3942  LOCK(cs_vNodes);
3943  for (CNode *pnode : vNodes)
3944  if (chainActive.Height() >
3945  (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
3946  pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
3947  }
3948  // Notify external listeners about the new tip.
3949  GetMainSignals().UpdatedBlockTip(pindexNewTip);
3950 
3951  unsigned size = 0;
3952  if (pblock)
3953  size = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION);
3954  // If the size is over 1 MB notify external listeners, and it is within the last 5 minutes
3955  if (size > MAX_BLOCK_SIZE_LEGACY && pblock->GetBlockTime() > GetAdjustedTime() - 300) {
3956  uiInterface.NotifyBlockSize(static_cast<int>(size), hashNewTip);
3957  }
3958  }
3959 
3960  }
3961  } while (pindexMostWork != chainActive.Tip());
3962  CheckBlockIndex();
3963 
3964  // Write changes periodically to disk, after relay.
3965  if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
3966  return false;
3967  }
3968 
3969  return true;
3970 }
3971 
3973 {
3975 
3976  // Mark the block itself as invalid.
3977  pindex->nStatus |= BLOCK_FAILED_VALID;
3978  setDirtyBlockIndex.insert(pindex);
3979  setBlockIndexCandidates.erase(pindex);
3980 
3981  while (chainActive.Contains(pindex)) {
3982  CBlockIndex* pindexWalk = chainActive.Tip();
3983  pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
3984  setDirtyBlockIndex.insert(pindexWalk);
3985  setBlockIndexCandidates.erase(pindexWalk);
3986  // ActivateBestChain considers blocks already in chainActive
3987  // unconditionally valid already, so force disconnect away from it.
3988  if (!DisconnectTip(state)) {
3989  return false;
3990  }
3991  }
3992 
3993  // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3994  // add them again.
3995  BlockMap::iterator it = mapBlockIndex.begin();
3996  while (it != mapBlockIndex.end()) {
3997  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx &&
3998  !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3999  setBlockIndexCandidates.insert(it->second);
4000  }
4001  it++;
4002  }
4003 
4004  InvalidChainFound(pindex);
4005  return true;
4006 }
4007 
4009 {
4011 
4012  int nHeight = pindex->nHeight;
4013 
4014  // Remove the invalidity flag from this block and all its descendants.
4015  BlockMap::iterator it = mapBlockIndex.begin();
4016  while (it != mapBlockIndex.end()) {
4017  if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
4018  it->second->nStatus &= ~BLOCK_FAILED_MASK;
4019  setDirtyBlockIndex.insert(it->second);
4020  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx &&
4021  setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
4022  setBlockIndexCandidates.insert(it->second);
4023  }
4024  if (it->second == pindexBestInvalid) {
4025  // Reset invalid block marker if it was pointing to one of those.
4026  pindexBestInvalid = NULL;
4027  }
4028  }
4029  it++;
4030  }
4031 
4032  // Remove the invalidity flag from all ancestors too.
4033  while (pindex != NULL) {
4034  if (pindex->nStatus & BLOCK_FAILED_MASK) {
4035  pindex->nStatus &= ~BLOCK_FAILED_MASK;
4036  setDirtyBlockIndex.insert(pindex);
4037  }
4038  pindex = pindex->pprev;
4039  }
4040  return true;
4041 }
4042 
4044 {
4045  // Check for duplicate
4046  uint256 hash = block.GetHash();
4047  BlockMap::iterator it = mapBlockIndex.find(hash);
4048  if (it != mapBlockIndex.end())
4049  return it->second;
4050 
4051  // Construct new block index object
4052  CBlockIndex* pindexNew = new CBlockIndex(block);
4053  assert(pindexNew);
4054  // We assign the sequence id to blocks only when the full data is available,
4055  // to avoid miners withholding blocks but broadcasting headers, to get a
4056  // competitive advantage.
4057  pindexNew->nSequenceId = 0;
4058  BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
4059 
4060  pindexNew->phashBlock = &((*mi).first);
4061  BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
4062  if (miPrev != mapBlockIndex.end()) {
4063  pindexNew->pprev = (*miPrev).second;
4064  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
4065  pindexNew->BuildSkip();
4066 
4067  //update previous block pointer
4068  pindexNew->pprev->pnext = pindexNew;
4069 
4070  // ppcoin: compute chain trust score
4071  pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
4072 
4073  // ppcoin: compute stake entropy bit for stake modifier
4074  if (!block.IsPoABlockByVersion() && !pindexNew->SetStakeEntropyBit(pindexNew->GetStakeEntropyBit()))
4075  LogPrintf("AddToBlockIndex() : SetStakeEntropyBit() failed \n");
4076 
4077  // ppcoin: record proof-of-stake hash value
4078  if (pindexNew->IsProofOfStake()) {
4079  if (!mapProofOfStake.count(hash))
4080  LogPrintf("AddToBlockIndex() : hashProofOfStake not found in map \n");
4081  pindexNew->hashProofOfStake = mapProofOfStake[hash];
4082  }
4083 
4084  // ppcoin: compute stake modifier
4085  uint64_t nStakeModifier = 0;
4086  bool fGeneratedStakeModifier = false;
4087  if (!block.IsPoABlockByVersion() && !ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
4088  LogPrintf("AddToBlockIndex() : ComputeNextStakeModifier() failed \n");
4089  pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
4090  pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
4091  if (!block.IsPoABlockByVersion() && !CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
4092  LogPrintf("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=%s \n",
4093  pindexNew->nHeight, std::to_string(nStakeModifier));
4094  }
4095  pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
4096  pindexNew->RaiseValidity(BLOCK_VALID_TREE);
4097  if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
4098  pindexBestHeader = pindexNew;
4099 
4100  //update previous block pointer
4101  if (pindexNew->nHeight)
4102  pindexNew->pprev->pnext = pindexNew;
4103 
4104  setDirtyBlockIndex.insert(pindexNew);
4105 
4106  return pindexNew;
4107 }
4108 
4110 bool ReceivedBlockTransactions(const CBlock& block, CValidationState& state, CBlockIndex* pindexNew, const CDiskBlockPos& pos)
4111 {
4112  if (block.IsProofOfStake())
4113  pindexNew->SetProofOfStake();
4114  pindexNew->nTx = block.vtx.size();
4115  pindexNew->nChainTx = 0;
4116  pindexNew->nFile = pos.nFile;
4117  pindexNew->nDataPos = pos.nPos;
4118  pindexNew->nUndoPos = 0;
4119  pindexNew->nStatus |= BLOCK_HAVE_DATA;
4121  setDirtyBlockIndex.insert(pindexNew);
4122 
4123  if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
4124  // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
4125  std::deque<CBlockIndex*> queue;
4126  queue.push_back(pindexNew);
4127 
4128  // Recursively process any descendant blocks that now may be eligible to be connected.
4129  while (!queue.empty()) {
4130  CBlockIndex* pindex = queue.front();
4131  queue.pop_front();
4132  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
4133  {
4134  LOCK(cs_nBlockSequenceId);
4135  pindex->nSequenceId = nBlockSequenceId++;
4136  }
4137  if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
4138  setBlockIndexCandidates.insert(pindex);
4139  }
4140  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(
4141  pindex);
4142  while (range.first != range.second) {
4143  std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
4144  queue.push_back(it->second);
4145  range.first++;
4146  mapBlocksUnlinked.erase(it);
4147  }
4148  }
4149  } else {
4150  if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
4151  mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
4152  }
4153  }
4154 
4155  return true;
4156 }
4157 
4158 bool FindBlockPos(CValidationState& state, CDiskBlockPos& pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
4159 {
4160  LOCK(cs_LastBlockFile);
4161 
4162  unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
4163  if (vinfoBlockFile.size() <= nFile) {
4164  vinfoBlockFile.resize(nFile + 1);
4165  }
4166 
4167  if (!fKnown) {
4168  while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
4169  LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
4170  FlushBlockFile(true);
4171  nFile++;
4172  if (vinfoBlockFile.size() <= nFile) {
4173  vinfoBlockFile.resize(nFile + 1);
4174  }
4175  }
4176  pos.nFile = nFile;
4177  pos.nPos = vinfoBlockFile[nFile].nSize;
4178  }
4179 
4180  nLastBlockFile = nFile;
4181  vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
4182  if (fKnown)
4183  vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
4184  else
4185  vinfoBlockFile[nFile].nSize += nAddSize;
4186 
4187  if (!fKnown) {
4188  unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
4189  unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
4190  if (nNewChunks > nOldChunks) {
4191  if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
4192  FILE* file = OpenBlockFile(pos);
4193  if (file) {
4194  LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE,
4195  pos.nFile);
4196  AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
4197  fclose(file);
4198  }
4199  } else
4200  return state.Error("out of disk space");
4201  }
4202  }
4203 
4204  setDirtyFileInfo.insert(nFile);
4205  return true;
4206 }
4207 
4208 bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize)
4209 {
4210  pos.nFile = nFile;
4211 
4212  LOCK(cs_LastBlockFile);
4213 
4214  unsigned int nNewSize;
4215  pos.nPos = vinfoBlockFile[nFile].nUndoSize;
4216  nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
4217  setDirtyFileInfo.insert(nFile);
4218 
4219  unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
4220  unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
4221  if (nNewChunks > nOldChunks) {
4222  if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
4223  FILE* file = OpenUndoFile(pos);
4224  if (file) {
4225  LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE,
4226  pos.nFile);
4227  AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
4228  fclose(file);
4229  }
4230  } else
4231  return state.Error("out of disk space");
4232  }
4233 
4234  return true;
4235 }
4236 
4237 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
4238 {
4239  // Check proof of work matches claimed amount
4240  if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
4241  return state.DoS(50, error("CheckBlockHeader() : proof of work failed"),
4242  REJECT_INVALID, "high-hash");
4243 
4244  if (Params().IsRegTestNet()) return true;
4245 
4246  //PoA specific header checks
4247  //Check that the header is valid for PoA mining, this check will use a PoA consensus rule
4248  if (block.IsPoABlockByVersion() && !CheckPoABlockMinedHash(block)) {
4249  return state.DoS(50, error("CheckBlockHeader() : proof of work PoA failed"),
4250  REJECT_INVALID, "high-hash");
4251  }
4252 
4253  //Check that the PoA header contains valid for PoA previous block hash, this check will use a PoA consensus rule
4254  if (block.IsPoABlockByVersion() && !CheckPrevPoABlockHash(block)) {
4255  return state.DoS(50, error("CheckBlockHeader() : Previous PoA block hash is not matched => failed"),
4256  REJECT_INVALID, "high-hash");
4257  }
4258 
4259  return true;
4260 }
4261 
4262 
4263 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig)
4264 {
4265  if (block.fChecked)
4266  return true;
4267 
4268  // Check that the header is valid (particularly PoW). This is mostly
4269  // redundant with the call in AcceptBlockHeader.
4270  if (!CheckBlockHeader(block, state, block.IsProofOfWork()))
4271  return state.DoS(100, error("CheckBlock() : CheckBlockHeader failed"),
4272  REJECT_INVALID, "bad-header", true);
4273  // Check timestamp
4274  //LogPrint("debug", "%s: block=%s is proof of stake=%d, is proof of audit=%d\n", __func__, block.GetHash().ToString().c_str(),
4275  //block.IsProofOfStake(), block.IsProofOfAudit());
4276  if (!Params().IsRegTestNet() && !block.IsPoABlockByVersion() && block.GetBlockTime() >
4277  GetAdjustedTime() + (block.IsProofOfStake() ? 180 : 7200)) // 3 minute future drift for PoS
4278  return state.Invalid(error("CheckBlock() : block timestamp too far in the future"),
4279  REJECT_INVALID, "time-too-new");
4280 
4281  //check duplicate key image in blocks
4282  std::set<CKeyImage> keyimages;
4283  for(size_t i = 0; i < block.vtx.size(); i++) {
4284  for (const CTxIn& txin : block.vtx[i].vin) {
4285  if (!txin.keyImage.IsValid()) continue;
4286  if (keyimages.count(txin.keyImage)) {
4287  return state.DoS(100, error("CheckBlock() : duplicate inputs"),
4288  REJECT_INVALID, "bad-txns-inputs-duplicate");
4289  }
4290  keyimages.insert(txin.keyImage);
4291  }
4292  }
4293 
4294  // Check the merkle root.
4295  if (fCheckMerkleRoot) {
4296  bool mutated;
4297  uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
4298  if (block.hashMerkleRoot != hashMerkleRoot2)
4299  return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"),
4300  REJECT_INVALID, "bad-txnmrklroot", true);
4301 
4302  // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
4303  // of transactions in a block without affecting the merkle root of a block,
4304  // while still invalidating it.
4305  if (mutated)
4306  return state.DoS(100, error("CheckBlock() : duplicate transaction"),
4307  REJECT_INVALID, "bad-txns-duplicate", true);
4308  }
4309 
4310  //Proof of Audit: Check audited PoS blocks infor merkle root
4311  {
4312  bool fMutated;
4313  if (!CheckPoAMerkleRoot(block, &fMutated)) {
4314  return state.DoS(100, error("CheckBlock() : hashPoAMerkleRoot mismatch"),
4315  REJECT_INVALID, "bad-txnmrklroot", true);
4316  }
4317  // Check for PoA merkle tree malleability (CVE-2012-2459): repeating sequences
4318  // of transactions in a block without affecting the PoA merkle root of a block,
4319  // while still invalidating it.
4320  if (fMutated)
4321  return state.DoS(100, error("CheckBlock() : duplicate PoS block info"),
4322  REJECT_INVALID, "bad-txns-duplicate", true);
4323  }
4324 
4325  // All potential-corruption validation must be done before we do any
4326  // transaction validation, as otherwise we may mark the header as invalid
4327  // because we receive the wrong transactions for it.
4328 
4329  // Size limits
4330  unsigned int nMaxBlockSize = MAX_BLOCK_SIZE_CURRENT;
4331  if (block.vtx.empty() || block.vtx.size() > nMaxBlockSize ||
4332  ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > nMaxBlockSize)
4333  return state.DoS(100, error("CheckBlock() : size limits failed"),
4334  REJECT_INVALID, "bad-blk-length");
4335 
4336  // First transaction must be coinbase, the rest must not be
4337  if ((!block.IsPoABlockByVersion()) && (block.vtx.empty() || !block.vtx[0].IsCoinBase()))
4338  return state.DoS(100, error("CheckBlock() : first tx is not coinbase"),
4339  REJECT_INVALID, "bad-cb-missing");
4340  for (unsigned int i = 1; i < block.vtx.size(); i++)
4341  if (block.vtx[i].IsCoinBase())
4342  return state.DoS(100, error("CheckBlock() : more than one coinbase"),
4343  REJECT_INVALID, "bad-cb-multiple");
4344 
4345  if (block.IsProofOfStake()) {
4346  // Coinbase output should be empty if proof-of-stake block
4347  if (block.vtx[0].vout.size() != 1 || !block.vtx[0].vout[0].IsEmpty())
4348  return state.DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
4349  // Second transaction must be coinstake, the rest must not be
4350  if (block.vtx.empty() || !block.vtx[1].IsCoinStake())
4351  return state.DoS(100, error("CheckBlock() : second tx is not coinstake"));
4352  for (unsigned int i = 2; i < block.vtx.size(); i++)
4353  if (block.vtx[i].IsCoinStake())
4354  return state.DoS(100, error("CheckBlock() : more than one coinstake"));
4355 
4356  const CTransaction& coinstake = block.vtx[1];
4357  int numUTXO = coinstake.vout.size();
4358 
4359  //verify shnorr signature
4360  if (!VerifyShnorrKeyImageTx(coinstake)) {
4361  return state.DoS(100, error("CheckBlock() : Failed to verify shnorr signature"));
4362  }
4363 
4364  //verify commitments for all UTXOs
4365  for (int i = 1; i < numUTXO; i++) {
4366  if (!VerifyZeroBlindCommitment(coinstake.vout[i]))
4367  return state.DoS(100, error("CheckBlock() : PoS rewards commitment not correct"));
4368  }
4369 
4370  std::set<COutPoint> vInOutPoints;
4371  for (const CTxIn& txin : block.vtx[1].vin) {
4372  if (vInOutPoints.count(txin.prevout) && chainActive.Tip()->nHeight > Params().SyncFix())
4373  return state.DoS(100, error("CheckBlock() : duplicate inputs"),
4374  REJECT_INVALID, "bad-txns-inputs-duplicate");
4375  vInOutPoints.insert(txin.prevout);
4376  }
4377 
4378  if (coinstake.vin.size() > 1 && chainActive.Tip()->nHeight > Params().FixChecks())
4379  return state.DoS(100, error("%s : multiple stake inputs not allowed", __func__), REJECT_INVALID, "bad-txns-stake");
4380  }
4381 
4382  if (block.IsProofOfAudit() || block.IsProofOfWork()) {
4383  //verify commitment
4384  if (!VerifyZeroBlindCommitment(block.vtx[0].vout[0]))
4385  return state.DoS(100, error("CheckBlock() : PoS rewards commitment not correct"));
4386  }
4387 
4391  if (block.IsProofOfAudit()) {
4392  if (chainActive.Tip()->nHeight < Params().START_POA_BLOCK()) {
4393  return state.DoS(100, error("CheckBlock() : PoA block should only start at block height=%d", Params().START_POA_BLOCK()));
4394  }
4395  }
4396 
4397  // masternode payments / budgets
4398  CBlockIndex* pindexPrev = chainActive.Tip();
4399  int nHeight = 0;
4400  if (pindexPrev != NULL) {
4401  if (pindexPrev->GetBlockHash() == block.hashPrevBlock) {
4402  nHeight = pindexPrev->nHeight + 1;
4403  } else { //out of order
4404  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
4405  if (mi != mapBlockIndex.end() && (*mi).second)
4406  nHeight = (*mi).second->nHeight + 1;
4407  }
4408 
4409  // PRCYcoin
4410  // It is entierly possible that we don't have enough data and this could fail
4411  // (i.e. the block could indeed be valid). Store the block for later consideration
4412  // but issue an initial reject message.
4413  // The case also exists that the sending peer could not have enough data to see
4414  // that this block is invalid, so don't issue an outright ban.
4415  if (block.IsProofOfStake() && nHeight != 0 && !IsInitialBlockDownload()) {
4416  if (!IsBlockPayeeValid(block, nHeight)) {
4417  mapRejectedBlocks.insert(std::make_pair(block.GetHash(), GetTime()));
4418  return state.DoS(0, error("CheckBlock() : Couldn't find masternode/budget payment"),
4419  REJECT_INVALID, "bad-cb-payee");
4420  }
4421  } else {
4422  LogPrint(BCLog::MASTERNODE, "%s: Masternode payment check skipped on sync - skipping IsBlockPayeeValid()\n", __func__);
4423  }
4424  }
4425 
4426  unsigned int nSigOps = 0;
4427  for (const CTransaction& tx : block.vtx) {
4428  nSigOps += GetLegacySigOpCount(tx);
4429  }
4430  unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_LEGACY;
4431  if (nSigOps > nMaxBlockSigOps)
4432  return state.DoS(100, error("ConnectBlock() : too many sigops"), REJECT_INVALID, "bad-blk-sigops");
4433 
4434  return true;
4435 }
4436 
4437 bool CheckWork(const CBlock block, CBlockIndex* const pindexPrev)
4438 {
4439  if (pindexPrev == NULL)
4440  return error("%s : null pindexPrev for block %s", __func__, block.GetHash().ToString().c_str());
4441  unsigned int nBitsRequired = GetNextWorkRequired(pindexPrev, &block);
4442  if (!Params().IsRegTestNet() && block.IsProofOfWork() && (pindexPrev->nHeight + 1 <= 68589)) {
4443  double n1 = ConvertBitsToDouble(block.nBits);
4444  double n2 = ConvertBitsToDouble(nBitsRequired);
4445 
4446  if (std::abs(n1 - n2) > n1 * 0.5)
4447  return error("%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, std::abs(n1 - n2), n1, n2, pindexPrev->nHeight + 1);
4448 
4449  return true;
4450  }
4451 
4452  if (block.nBits != nBitsRequired)
4453  return error("%s : incorrect proof of work at %d", __func__, pindexPrev->nHeight + 1);
4454 
4455  return true;
4456 }
4457 
4458 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex* const pindexPrev)
4459 {
4460  uint256 hash = block.GetHash();
4461 
4462  if (hash == Params().HashGenesisBlock())
4463  return true;
4464 
4465  assert(pindexPrev);
4466 
4467  const int nHeight = pindexPrev->nHeight + 1;
4468  const int chainHeight = chainActive.Height();
4469 
4470  if ((Params().IsRegTestNet() && block.nBits != GetNextWorkRequired(pindexPrev, &block)))
4471  return state.DoS(100, error("%s : incorrect proof of work", __func__),
4472  REJECT_INVALID, "bad-diffbits");
4473 
4474 
4475  //If this is a reorg, check that it is not too deep
4476  int nMaxReorgDepth = GetArg("-maxreorg", Params().MaxReorganizationDepth());
4477  if (chainHeight - nHeight >= nMaxReorgDepth)
4478  return state.DoS(1, error("%s: forked chain older than max reorganization depth (height %d)", __func__, chainHeight - nHeight));
4479 
4480  // Check timestamp against prev
4481  if (!block.IsPoABlockByVersion() && block.GetBlockTime() <= pindexPrev->GetMedianTimePast() && !Params().IsRegTestNet()) {
4482  LogPrintf("Block time = %d , GetMedianTimePast = %d \n", block.GetBlockTime(), pindexPrev->GetMedianTimePast());
4483  return state.Invalid(error("%s : block's timestamp is too early", __func__),
4484  REJECT_INVALID, "time-too-old");
4485  }
4486 
4487  // Check that the block chain matches the known block chain up to a checkpoint
4488  if (!Checkpoints::CheckBlock(nHeight, hash))
4489  return state.DoS(100, error("%s : rejected by checkpoint lock-in at %d", __func__, nHeight),
4490  REJECT_CHECKPOINT, "checkpoint mismatch");
4491 
4492  // Don't accept any forks from the main chain prior to last checkpoint
4494  if (pcheckpoint && nHeight < pcheckpoint->nHeight)
4495  return state.DoS(0, error("%s : forked chain older than last checkpoint (height %d)", __func__, nHeight));
4496 
4497  // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
4498  if (block.nVersion < 2 &&
4499  CBlockIndex::IsSuperMajority(2, pindexPrev, Params().RejectBlockOutdatedMajority())) {
4500  return state.Invalid(error("%s : rejected nVersion=1 block", __func__),
4501  REJECT_OBSOLETE, "bad-version");
4502  }
4503 
4504  // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
4505  if (block.nVersion < 3 && CBlockIndex::IsSuperMajority(3, pindexPrev, Params().RejectBlockOutdatedMajority())) {
4506  return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
4507  REJECT_OBSOLETE, "bad-version");
4508  }
4509 
4510  // Reject block.nVersion=4 blocks when 95% (75% on testnet) of the network has upgraded:
4511  if (block.nVersion < 5 && CBlockIndex::IsSuperMajority(5, pindexPrev, Params().RejectBlockOutdatedMajority())) {
4512  return state.Invalid(error("%s : rejected nVersion=4 block", __func__),
4513  REJECT_OBSOLETE, "bad-version");
4514  }
4515 
4516  return true;
4517 }
4518 
4519 bool IsBlockHashInChain(const uint256& hashBlock)
4520 {
4521  if (hashBlock.IsNull() || !mapBlockIndex.count(hashBlock))
4522  return false;
4523 
4524  return chainActive.Contains(mapBlockIndex[hashBlock]);
4525 }
4526 
4527 bool IsTransactionInChain(const uint256& txId, int& nHeightTx, CTransaction& tx)
4528 {
4529  uint256 hashBlock;
4530  if (!GetTransaction(txId, tx, hashBlock, true))
4531  return false;
4532  if (!IsBlockHashInChain(hashBlock))
4533  return false;
4534 
4535  nHeightTx = mapBlockIndex.at(hashBlock)->nHeight;
4536  return true;
4537 }
4538 
4539 bool IsTransactionInChain(const uint256& txId, int& nHeightTx)
4540 {
4541  CTransaction tx;
4542  return IsTransactionInChain(txId, nHeightTx, tx);
4543 }
4544 
4545 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex* const pindexPrev)
4546 {
4547  const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
4548 
4549  // Check that all transactions are finalized
4550  for (const CTransaction& tx : block.vtx)
4551  if (!block.IsProofOfAudit() && !IsFinalTx(tx, nHeight, block.GetBlockTime())) {
4552  return state.DoS(10, error("%s : contains a non-final transaction", __func__), REJECT_INVALID,
4553  "bad-txns-nonfinal");
4554  }
4555 
4556  // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
4557  // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
4558  if (!block.IsProofOfAudit() && block.nVersion >= 2 &&
4559  CBlockIndex::IsSuperMajority(2, pindexPrev, Params().EnforceBlockUpgradeMajority())) {
4560  CScript expect = CScript() << nHeight;
4561  if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
4562  !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
4563  return state.DoS(100, error("%s : block height mismatch in coinbase", __func__), REJECT_INVALID,
4564  "bad-cb-height");
4565  }
4566  }
4567 
4568  return true;
4569 }
4570 
4571 bool AcceptBlockHeader(const CBlock& block, CValidationState& state, CBlockIndex** ppindex)
4572 {
4574  // Check for duplicate
4575  uint256 hash = block.GetHash();
4576  BlockMap::iterator miSelf = mapBlockIndex.find(hash);
4577  CBlockIndex* pindex = NULL;
4578  // TODO : ENABLE BLOCK CACHE IN SPECIFIC CASES
4579  if (miSelf != mapBlockIndex.end()) {
4580  // Block header is already known.
4581  pindex = miSelf->second;
4582  if (ppindex)
4583  *ppindex = pindex;
4584  if (!pindex) {
4585  mapBlockIndex.erase(hash);
4586  return state.Invalid(error("%s : block is not found", __func__), 0, "not-found");
4587  }
4588  if (pindex->nStatus & BLOCK_FAILED_MASK)
4589  return state.Invalid(error("%s : block is marked invalid", __func__), 0, "duplicate");
4590  return true;
4591  }
4592  if (!CheckBlockHeader(block, state, false)) {
4593  LogPrintf("AcceptBlockHeader(): CheckBlockHeader failed \n");
4594  return false;
4595  }
4596  // Get prev block index
4597  CBlockIndex* pindexPrev = NULL;
4598  if (hash != Params().HashGenesisBlock()) {
4599  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
4600  if (mi == mapBlockIndex.end())
4601  return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.ToString().c_str()),
4602  0, "bad-prevblk");
4603  pindexPrev = (*mi).second;
4604  if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
4605  //If this "invalid" block is an exact match from the checkpoints, then reconsider it
4606  if (pindex && Checkpoints::CheckBlock(pindex->nHeight - 1, block.hashPrevBlock, true)) {
4607  LogPrintf("%s : Reconsidering block %s height %d\n", __func__, pindexPrev->GetBlockHash().GetHex(),
4608  pindexPrev->nHeight);
4609  CValidationState statePrev;
4610  ReconsiderBlock(statePrev, pindexPrev);
4611  if (statePrev.IsValid()) {
4612  ActivateBestChain(statePrev);
4613  return true;
4614  }
4615  }
4616 
4617  return state.DoS(100,
4618  error("%s : prev block height=%d hash=%s is invalid, unable to add block %s", __func__,
4619  pindexPrev->nHeight, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()),
4620  REJECT_INVALID, "bad-prevblk");
4621  }
4622  }
4623 
4624  if (!pindexPrev)
4625  return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.ToString().c_str()),
4626  0, "bad-prevblk");
4627  if (!ContextualCheckBlockHeader(block, state, pindexPrev))
4628  return false;
4629 
4630  if (pindex == NULL)
4631  pindex = AddToBlockIndex(block);
4632 
4633  if (ppindex)
4634  *ppindex = pindex;
4635 
4636  return true;
4637 }
4638 
4639 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp, bool fAlreadyCheckedBlock)
4640 {
4642  CBlockIndex*& pindex = *ppindex;
4643  // Get prev block index
4644  CBlockIndex* pindexPrev = NULL;
4645  if (block.GetHash() != Params().HashGenesisBlock()) {
4646  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
4647  if (mi == mapBlockIndex.end() || mi->second == NULL)
4648  return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.ToString().c_str()),
4649  0, "bad-prevblk");
4650  pindexPrev = (*mi).second;
4651  if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
4652  //If this "invalid" block is an exact match from the checkpoints or if it is a PoA block rejected previously due not synced with other nodes before, then reconsider it
4653  if (Checkpoints::CheckBlock(pindexPrev->nHeight, block.hashPrevBlock, true) || (pindexPrev->IsProofOfAudit() && chainActive.Height() - pindexPrev->nHeight < Params().MaxReorganizationDepth())) {
4654  LogPrintf("%s : Reconsidering block %s height %d\n", __func__, pindexPrev->GetBlockHash().GetHex(),
4655  pindexPrev->nHeight);
4656  CValidationState statePrev;
4657  ReconsiderBlock(statePrev, pindexPrev);
4658  if (statePrev.IsValid()) {
4659  ActivateBestChain(statePrev);
4660  return true;
4661  }
4662  }
4663  return state.DoS(100, error("%s : prev block %s is invalid, unable to add block %s", __func__, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()),
4664  REJECT_INVALID, "bad-prevblk");
4665  }
4666  }
4667  if (block.GetHash() != Params().HashGenesisBlock() && !CheckWork(block, pindexPrev)) {
4668  return false;
4669  }
4670 
4671  bool isPoS = false;
4672  if (block.IsProofOfStake()) {
4673  isPoS = true;
4674  uint256 hashProofOfStake = 0;
4675  std::unique_ptr<CStakeInput> stake;
4676 
4677  if (!CheckProofOfStake(block, hashProofOfStake, stake, pindexPrev->nHeight))
4678  return state.DoS(100, error("%s: proof of stake check failed", __func__));
4679 
4680  if (!stake)
4681  return error("%s: null stake ptr", __func__);
4682 
4683  uint256 hash = block.GetHash();
4684  if(!mapProofOfStake.count(hash)) // add to mapProofOfStake
4685  mapProofOfStake.insert(std::make_pair(hash, hashProofOfStake));
4686  }
4687 
4688  if (!AcceptBlockHeader(block, state, &pindex))
4689  return false;
4690 
4691  if (pindex->nStatus & BLOCK_HAVE_DATA) {
4692  // TODO: deal better with duplicate blocks.
4693  LogPrintf("AcceptBlock() : already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString());
4694  return true;
4695  }
4696 
4697  if ((!fAlreadyCheckedBlock && !CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
4698  if (state.IsInvalid() && !state.CorruptionPossible()) {
4699  pindex->nStatus |= BLOCK_FAILED_VALID;
4700  setDirtyBlockIndex.insert(pindex);
4701  }
4702  return false;
4703  }
4704 
4705  int nHeight = pindex->nHeight;
4706  int splitHeight = -1;
4707 
4708  if (isPoS) {
4709  LOCK(cs_main);
4710 
4711  // Blocks arrives in order, so if prev block is not the tip then we are on a fork.
4712  // Extra info: duplicated blocks are skipping this checks, so we don't have to worry about those here.
4713  bool isBlockFromFork = pindexPrev != nullptr && chainActive.Tip() != pindexPrev;
4714 
4715  // Coin stake
4716  CTransaction &stakeTxIn = block.vtx[1];
4717 
4718  // Only one input is allowed
4719  if (stakeTxIn.vin.size() > 1 && nHeight > Params().FixChecks())
4720  return state.DoS(100, error("%s : multiple stake inputs not allowed", __func__), REJECT_INVALID, "bad-txns-stake");
4721 
4722  // Inputs
4723  std::vector<CTxIn> prcyInputs;
4724 
4725  for (const CTxIn& stakeIn : stakeTxIn.vin) {
4726  prcyInputs.push_back(stakeIn);
4727  }
4728  const bool hasPRCYInputs = !prcyInputs.empty();
4729 
4730  for (const CTransaction& tx : block.vtx) {
4731  for (const CTxIn& in: tx.vin) {
4732  if(tx.IsCoinStake()) continue;
4733  if(hasPRCYInputs)
4734  // Check if coinstake input is double spent inside the same block
4735  for (const CTxIn& prcyIn : prcyInputs){
4736  if (IsSpentKeyImage(prcyIn.keyImage.GetHex(), block.GetHash())) {
4737  // double spent coinstake input inside block
4738  return error("%s: double spent coinstake input: %s, KeyImage: %s inside block: %s", __func__, prcyIn.prevout.hash.GetHex(), prcyIn.keyImage.GetHex(), block.GetHash().GetHex());
4739  }
4740  }
4741  }
4742  }
4743 
4744  // Check whether is a fork or not
4745  if (isBlockFromFork) {
4746 
4747  // Start at the block we're adding on to
4748  CBlockIndex *prev = pindexPrev;
4749 
4750  int readBlock = 0;
4751  CBlock bl;
4752  // Go backwards on the forked chain up to the split
4753  do {
4754  // Check if the forked chain is longer than the max reorg limit
4755  if(readBlock == Params().MaxReorganizationDepth()){
4756  // TODO: Remove this chain from disk.
4757  return error("%s: forked chain longer than maximum reorg limit", __func__);
4758  }
4759 
4760  if(!ReadBlockFromDisk(bl, prev))
4761  // Previous block not on disk
4762  return error("%s: previous block %s not on disk", __func__, prev->GetBlockHash().GetHex());
4763  // Increase amount of read blocks
4764  readBlock++;
4765  // Loop through every input from said block
4766  for (const CTransaction& t : bl.vtx) {
4767  for (const CTxIn& in: t.vin) {
4768  // Loop through every input of the staking tx
4769  for (const CTxIn& stakeIn : prcyInputs) {
4770  // if it's already spent
4771 
4772  // First regular staking check
4773  if(hasPRCYInputs) {
4774  if (IsSpentKeyImage(stakeIn.keyImage.GetHex(), bl.GetHash())) {
4775  return state.DoS(100, error("%s: input: %s already spent on a previous block: %s", __func__, stakeIn.keyImage.GetHex(), bl.GetHash().GetHex()));
4776  }
4777  }
4778  }
4779  }
4780  }
4781 
4782  prev = prev->pprev;
4783 
4784  } while (!chainActive.Contains(prev));
4785  }
4786 
4787 
4788  // Let's check if the inputs were spent on the main chain
4789  const CCoinsViewCache coins(pcoinsTip);
4790  for (const CTxIn& in: stakeTxIn.vin) {
4791  const CCoins* coin = coins.AccessCoins(in.prevout.hash);
4792 
4793  if(!coin && !isBlockFromFork){
4794  // No coins on the main chain
4795  return error("%s: coin stake inputs not available on main chain, received height %d vs current %d", __func__, nHeight, chainActive.Height());
4796  }
4797  if(coin && !coin->IsAvailable(in.prevout.n)){
4798  // If this is not available get the height of the spent and validate it with the forked height
4799  // Check if this occurred before the chain split
4800  if(!(isBlockFromFork && coin->nHeight > splitHeight)){
4801  // Coins not available
4802  return error("%s: coin stake inputs already spent in main chain", __func__);
4803  }
4804  }
4805  }
4806 
4807  }
4808 
4809  // Write block to history file
4810  try {
4811  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4812  CDiskBlockPos blockPos;
4813  if (dbp != NULL)
4814  blockPos = *dbp;
4815  if (!FindBlockPos(state, blockPos, nBlockSize + 8, nHeight, block.GetBlockTime(), dbp != NULL))
4816  return error("AcceptBlock() : FindBlockPos failed");
4817  if (dbp == NULL)
4818  if (!WriteBlockToDisk(block, blockPos))
4819  return AbortNode(state, "Failed to write block");
4820  if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4821  return error("AcceptBlock() : ReceivedBlockTransactions failed");
4822  } catch (const std::runtime_error& e) {
4823  return AbortNode(state, std::string("System error: ") + e.what());
4824  }
4825 
4826  return true;
4827 }
4828 
4829 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
4830 {
4831  unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
4832  unsigned int nFound = 0;
4833  for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) {
4834  if (pstart->nVersion >= minVersion)
4835  ++nFound;
4836  pstart = pstart->pprev;
4837  }
4838  return (nFound >= nRequired);
4839 }
4840 
4842 int static inline InvertLowestOne(int n) { return n & (n - 1); }
4843 
4845 int static inline GetSkipHeight(int height)
4846 {
4847  if (height < 2)
4848  return 0;
4849 
4850  // Determine which height to jump back to. Any number strictly lower than height is acceptable,
4851  // but the following expression seems to perform well in simulations (max 110 steps to go back
4852  // up to 2**18 blocks).
4853  return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
4854 }
4855 
4857 {
4858  if (height > nHeight || height < 0)
4859  return NULL;
4860 
4861  CBlockIndex* pindexWalk = this;
4862  int heightWalk = nHeight;
4863  while (heightWalk > height) {
4864  int heightSkip = GetSkipHeight(heightWalk);
4865  int heightSkipPrev = GetSkipHeight(heightWalk - 1);
4866  if (heightSkip == height ||
4867  (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) {
4868  // Only follow pskip if pprev->pskip isn't better than pskip->pprev.
4869  pindexWalk = pindexWalk->pskip;
4870  heightWalk = heightSkip;
4871  } else {
4872  pindexWalk = pindexWalk->pprev;
4873  heightWalk--;
4874  }
4875  }
4876  return pindexWalk;
4877 }
4878 
4879 const CBlockIndex* CBlockIndex::GetAncestor(int height) const
4880 {
4881  return const_cast<CBlockIndex*>(this)->GetAncestor(height);
4882 }
4883 
4885 {
4886  if (pprev)
4887  pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
4888 }
4889 
4890 bool ProcessNewBlock(CValidationState& state, CNode* pfrom, CBlock* pblock, CDiskBlockPos* dbp)
4891 {
4893 
4894  // Preliminary checks
4895  int64_t nStartTime = GetTimeMillis();
4896  bool checked = CheckBlock(*pblock, state);
4897 
4898  if (!pblock->IsPoABlockByVersion() && !CheckBlockSignature(*pblock))
4899  return error("ProcessNewBlock() : bad proof-of-stake block signature");
4900 
4901  if (pblock->GetHash() != Params().HashGenesisBlock() && pfrom != NULL) {
4902  //if we get this far, check if the prev block is our prev block, if not then request sync and return false
4903  BlockMap::iterator mi = mapBlockIndex.find(pblock->hashPrevBlock);
4904  if (mi == mapBlockIndex.end() || (mi != mapBlockIndex.end() && mi->second == NULL)) {
4905  mapBlockIndex.erase(pblock->hashPrevBlock);
4907  return false;
4908  } else {
4909  CBlock r;
4910  if (!ReadBlockFromDisk(r, mapBlockIndex[pblock->hashPrevBlock])) {
4912  return false;
4913  }
4914  }
4915  }
4916  {
4917  LOCK(cs_main); // Replaces the former TRY_LOCK loop because busy waiting wastes too much resources
4918 
4919  MarkBlockAsReceived(pblock->GetHash());
4920  if (!checked) {
4921  return error("%s : CheckBlock FAILED for block %s", __func__, pblock->GetHash().GetHex());
4922  }
4923 
4924  // Store to disk
4925  CBlockIndex* pindex = nullptr;
4926  bool ret = AcceptBlock(*pblock, state, &pindex, dbp, checked);
4927  if (pindex && pfrom) {
4928  mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
4929  }
4930  CheckBlockIndex();
4931  if (!ret) {
4932  if (pfrom) {
4934  }
4935  if (pwalletMain)
4936  {
4938  if (pblock->IsProofOfStake()) {
4939  if (pwalletMain->IsMine(pblock->vtx[1].vin[0])) {
4940  pwalletMain->mapWallet.erase(pblock->vtx[1].GetHash());
4941  }
4942  }
4943  bool initialDownloadCheck = IsInitialBlockDownload();
4944  if (!initialDownloadCheck &&
4945  pblock->IsPoABlockByVersion()) // Run DeleteWalletTransactions on PoA blocks
4946  {
4947  while(pwalletMain->DeleteWalletTransactions(pindex, false)) {}
4948  } else {
4949  if (initialDownloadCheck && pindex->nHeight % fDeleteInterval == 0) {
4950  while(pwalletMain->DeleteWalletTransactions(pindex, false)) {}
4951  }
4952  }
4953  }
4954  // Check spamming
4955  if(pindex && pfrom && GetBoolArg("-blockspamfilter", DEFAULT_BLOCK_SPAM_FILTER)) {
4956  CNodeState *nodestate = State(pfrom->GetId());
4957  if(nodestate != nullptr) {
4958  nodestate->nodeBlocks.onBlockReceived(pindex->nHeight);
4959  bool nodeStatus = true;
4960  // UpdateState will return false if the node is attacking us or update the score and return true.
4961  nodeStatus = nodestate->nodeBlocks.updateState(state, nodeStatus);
4962  int nDoS = 0;
4963  if (state.IsInvalid(nDoS)) {
4964  if (nDoS > 0)
4965  Misbehaving(pfrom->GetId(), nDoS);
4966  nodeStatus = false;
4967  }
4968  if (!nodeStatus)
4969  return error("%s : AcceptBlock FAILED - block spam protection", __func__);
4970  }
4971  }
4972  return error("%s : AcceptBlock FAILED", __func__);
4973  }
4974  }
4975 
4976  if (!ActivateBestChain(state, pblock, checked))
4977  return error("%s : ActivateBestChain failed", __func__);
4978  if (!fLiteMode) {
4980  masternodePayments.ProcessBlock(GetHeight() + 10);
4981  budget.NewBlock();
4982  }
4983  }
4984 
4985  if (pwalletMain) {
4987  /*// If turned on MultiSend will send a transaction (or more) on the after maturity of a stake
4988  if (pwalletMain->isMultiSendEnabled())
4989  pwalletMain->MultiSend();*/
4990 
4991  // If turned on Auto Combine will scan wallet for dust to combine
4992  if (pwalletMain->fCombineDust && chainActive.Height() % 15 == 0)
4994 
4995  if (chainActive.Height() % 15 == 0) {
4997  }
4999  }
5000 
5001  //Block is accepted, let's update decoys pool
5002  //First, update user decoy pool
5003  int userTxStartIdx = 1;
5004  int coinbaseIdx = 0;
5005  if (pwalletMain) {
5007  {
5008  if (pblock->IsProofOfStake()) {
5009  userTxStartIdx = 2;
5010  coinbaseIdx = 1;
5011  }
5012 
5013  if (pblock->IsProofOfStake()) {
5014  if (pwalletMain->userDecoysPool.count(pblock->vtx[1].vin[0].prevout) == 1) {
5015  pwalletMain->userDecoysPool.erase(pblock->vtx[1].vin[0].prevout);
5016  }
5017 
5018  if (pwalletMain->coinbaseDecoysPool.count(pblock->vtx[1].vin[0].prevout) == 1) {
5019  pwalletMain->coinbaseDecoysPool.erase(pblock->vtx[1].vin[0].prevout);
5020  }
5021  }
5022 
5023  if ((int)pblock->vtx.size() > userTxStartIdx) {
5024  for (int i = userTxStartIdx; i < (int)pblock->vtx.size(); i++) {
5025  for (int j = 0; j < (int)pblock->vtx[i].vout.size(); j++) {
5026  if (!pblock->vtx[i].vout[j].commitment.empty() && (secp256k1_rand32() % 100) <= CWallet::PROBABILITY_NEW_COIN_SELECTED) {
5027  COutPoint newOutPoint(pblock->vtx[i].GetHash(), j);
5028  if (pwalletMain->userDecoysPool.count(newOutPoint) == 1) {
5029  continue;
5030  }
5031  //add new user transaction to the pool
5032  if ((int32_t)pwalletMain->userDecoysPool.size() >= CWallet::MAX_DECOY_POOL) {
5033  int selected = secp256k1_rand32() % CWallet::MAX_DECOY_POOL;
5034  std::map<COutPoint, uint256>::const_iterator it = std::next(pwalletMain->userDecoysPool.begin(), selected);
5035  pwalletMain->userDecoysPool.erase(it->first);
5036  pwalletMain->userDecoysPool[newOutPoint] = pblock->GetHash();
5037  } else {
5038  pwalletMain->userDecoysPool[newOutPoint] = pblock->GetHash();
5039  }
5040  }
5041  }
5042  }
5043  }
5044 
5045  if (chainActive.Height() > Params().COINBASE_MATURITY()) {
5046  //read block chainActive.Height() - Params().COINBASE_MATURITY()
5048  CBlock b;
5049  if (ReadBlockFromDisk(b, p)) {
5050  coinbaseIdx = 0;
5051  if (p->IsProofOfStake()) {
5052  coinbaseIdx = 1;
5053  }
5054  CTransaction& coinbase = b.vtx[coinbaseIdx];
5055  if (b.posBlocksAudited.size() == 0) {
5056  for (int i = 0; i < (int)coinbase.vout.size(); i++) {
5057  if (!coinbase.vout[i].IsNull() && !coinbase.vout[i].commitment.empty() && coinbase.vout[i].nValue > 0 && !coinbase.vout[i].IsEmpty()) {
5058  if ((secp256k1_rand32() % 100) <= CWallet::PROBABILITY_NEW_COIN_SELECTED) {
5059  COutPoint newOutPoint(coinbase.GetHash(), i);
5060  if (pwalletMain->coinbaseDecoysPool.count(newOutPoint) == 1) {
5061  continue;
5062  }
5063  //add new coinbase transaction to the pool
5065  int selected = secp256k1_rand32() % CWallet::MAX_DECOY_POOL;
5066  std::map<COutPoint, uint256>::const_iterator it = std::next(pwalletMain->coinbaseDecoysPool.begin(), selected);
5067  pwalletMain->coinbaseDecoysPool.erase(it->first);
5068  pwalletMain->coinbaseDecoysPool[newOutPoint] = pblock->GetHash();
5069  } else {
5070  pwalletMain->coinbaseDecoysPool[newOutPoint] = pblock->GetHash();
5071  }
5072  }
5073  }
5074  }
5075  }
5076  }
5077  }
5078  LogPrintf("%s: Coinbase decoys = %d, user decoys = %d\n", __func__, pwalletMain->coinbaseDecoysPool.size(), pwalletMain->userDecoysPool.size());
5079  }
5080  }
5081 
5082  LogPrintf("%s: ACCEPTED in %ld milliseconds with size=%d, height=%d\n", __func__, GetTimeMillis() - nStartTime,
5083  pblock->GetSerializeSize(SER_DISK, CLIENT_VERSION), chainActive.Height());
5084 
5085  return true;
5086 }
5087 
5088 bool TestBlockValidity(CValidationState& state, const CBlock& block, CBlockIndex* const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
5089 {
5091  assert(pindexPrev && pindexPrev == chainActive.Tip());
5092  if (pindexPrev != chainActive.Tip()) {
5093  LogPrintf("%s : No longer working on chain tip\n", __func__);
5094  return false;
5095  }
5096 
5097  CCoinsViewCache viewNew(pcoinsTip);
5098  CBlockIndex indexDummy(block);
5099  indexDummy.pprev = pindexPrev;
5100  indexDummy.nHeight = pindexPrev->nHeight + 1;
5101 
5102  // NOTE: CheckBlockHeader is called by CheckBlock
5103  if (!ContextualCheckBlockHeader(block, state, pindexPrev))
5104  return false;
5105  if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
5106  return false;
5107  if (!ContextualCheckBlock(block, state, pindexPrev))
5108  return false;
5109  if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
5110  return false;
5111  assert(state.IsValid());
5112 
5113  return true;
5114 }
5115 
5116 bool CheckDiskSpace(uint64_t nAdditionalBytes)
5117 {
5118  uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
5119 
5120  // Check for nMinDiskSpace bytes (currently 50MB)
5121  if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
5122  return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
5123 
5124  return true;
5125 }
5126 
5127 FILE* OpenDiskFile(const CDiskBlockPos& pos, const char* prefix, bool fReadOnly)
5128 {
5129  if (pos.IsNull())
5130  return NULL;
5131  fs::path path = GetBlockPosFilename(pos, prefix);
5132  fs::create_directories(path.parent_path());
5133  FILE* file = fsbridge::fopen(path, "rb+");
5134  if (!file && !fReadOnly)
5135  file = fsbridge::fopen(path, "wb+");
5136  if (!file) {
5137  LogPrintf("Unable to open file %s\n", path.string());
5138  return NULL;
5139  }
5140  if (pos.nPos) {
5141  if (fseek(file, pos.nPos, SEEK_SET)) {
5142  LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
5143  fclose(file);
5144  return NULL;
5145  }
5146  }
5147  return file;
5148 }
5149 
5150 FILE* OpenBlockFile(const CDiskBlockPos& pos, bool fReadOnly)
5151 {
5152  return OpenDiskFile(pos, "blk", fReadOnly);
5153 }
5154 
5155 FILE* OpenUndoFile(const CDiskBlockPos& pos, bool fReadOnly)
5156 {
5157  return OpenDiskFile(pos, "rev", fReadOnly);
5158 }
5159 
5160 fs::path GetBlockPosFilename(const CDiskBlockPos& pos, const char* prefix)
5161 {
5162  return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
5163 }
5164 
5166 {
5167  if (hash.IsNull())
5168  return NULL;
5169 
5170  // Return existing
5171  BlockMap::iterator mi = mapBlockIndex.find(hash);
5172  if (mi != mapBlockIndex.end())
5173  return (*mi).second;
5174 
5175  // Create new
5176  CBlockIndex* pindexNew = new CBlockIndex();
5177  if (!pindexNew)
5178  throw std::runtime_error("LoadBlockIndex() : new CBlockIndex failed");
5179  mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
5180 
5181  pindexNew->phashBlock = &((*mi).first);
5182 
5183  return pindexNew;
5184 }
5185 
5186 bool static LoadBlockIndexDB(std::string& strError)
5187 {
5189  return false;
5190 
5191  boost::this_thread::interruption_point();
5192 
5193  // Calculate nChainWork
5194  std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
5195  vSortedByHeight.reserve(mapBlockIndex.size());
5196  for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex) {
5197  CBlockIndex* pindex = item.second;
5198  vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
5199  }
5200  std::sort(vSortedByHeight.begin(), vSortedByHeight.end());
5201  for (const PAIRTYPE(int, CBlockIndex*) & item : vSortedByHeight) {
5202  // Stop if shutdown was requested
5203  if (ShutdownRequested()) return false;
5204 
5205  CBlockIndex* pindex = item.second;
5206  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
5207  if (pindex->nStatus & BLOCK_HAVE_DATA) {
5208  if (pindex->pprev) {
5209  if (pindex->pprev->nChainTx) {
5210  pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
5211  } else {
5212  pindex->nChainTx = 0;
5213  mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
5214  }
5215  } else {
5216  pindex->nChainTx = pindex->nTx;
5217  }
5218  }
5219  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
5220  setBlockIndexCandidates.insert(pindex);
5221  if (pindex->nStatus & BLOCK_FAILED_MASK &&
5222  (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
5223  pindexBestInvalid = pindex;
5224  if (pindex->pprev)
5225  pindex->BuildSkip();
5226  if (pindex->IsValid(BLOCK_VALID_TREE) &&
5227  (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
5228  pindexBestHeader = pindex;
5229  }
5230 
5231  // Load block file info
5232  pblocktree->ReadLastBlockFile(nLastBlockFile);
5233  vinfoBlockFile.resize(nLastBlockFile + 1);
5234  LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
5235  for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
5236  pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
5237  }
5238  LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
5239  for (int nFile = nLastBlockFile + 1; true; nFile++) {
5240  CBlockFileInfo info;
5241  if (pblocktree->ReadBlockFileInfo(nFile, info)) {
5242  vinfoBlockFile.push_back(info);
5243  } else {
5244  break;
5245  }
5246  }
5247 
5248  // Check presence of blk files
5249  LogPrintf("Checking all blk files are present...\n");
5250  std::set<int> setBlkDataFiles;
5251  for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex) {
5252  CBlockIndex* pindex = item.second;
5253  if (pindex->nStatus & BLOCK_HAVE_DATA) {
5254  setBlkDataFiles.insert(pindex->nFile);
5255  }
5256  }
5257  for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
5258  CDiskBlockPos pos(*it, 0);
5259  if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
5260  return false;
5261  }
5262  }
5263 
5264  //Check if the shutdown procedure was followed on last client exit
5265  bool fLastShutdownWasPrepared = true;
5266  pblocktree->ReadFlag("shutdown", fLastShutdownWasPrepared);
5267  LogPrintf("%s: Last shutdown was prepared: %s\n", __func__, fLastShutdownWasPrepared);
5268 
5269  // Check whether we need to continue reindexing
5270  bool fReindexing = false;
5271  pblocktree->ReadReindexing(fReindexing);
5272  if(fReindexing) fReindex = true;
5273 
5274  // Check whether we have a transaction index
5275  pblocktree->ReadFlag("txindex", fTxIndex);
5276  LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
5277 
5278  // If this is written true before the next client init, then we know the shutdown process failed
5279  pblocktree->WriteFlag("shutdown", false);
5280 
5281  // Load pointer to end of best chain
5282  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
5283  if (it == mapBlockIndex.end())
5284  return true;
5285  chainActive.SetTip(it->second);
5286 
5287  PruneBlockIndexCandidates();
5288 
5289  const CBlockIndex* pChainTip = chainActive.Tip();
5290  LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
5291  pChainTip->GetBlockHash().GetHex(), pChainTip->nHeight,
5292  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pChainTip->GetBlockTime()),
5294 
5295  return true;
5296 }
5297 
5299 {
5300  uiInterface.ShowProgress(_("Verifying blocks..."), 0);
5301 }
5302 
5304 {
5305  uiInterface.ShowProgress("", 100);
5306 }
5307 
5308 bool CVerifyDB::VerifyDB(CCoinsView* coinsview, int nCheckLevel, int nCheckDepth)
5309 {
5310  LOCK(cs_main);
5311  if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
5312  return true;
5313 
5314  const int chainHeight = chainActive.Height();
5315  // Verify blocks in the best chain
5316  if (nCheckDepth <= 0)
5317  nCheckDepth = 1000000000; // suffices until the year 19000
5318  if (nCheckDepth > chainHeight)
5319  nCheckDepth = chainHeight;
5320  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
5321  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
5322  CCoinsViewCache coins(coinsview);
5323  CBlockIndex* pindexState = chainActive.Tip();
5324  CBlockIndex* pindexFailure = NULL;
5325  int nGoodTransactions = 0;
5326  CValidationState state;
5327  for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
5328  boost::this_thread::interruption_point();
5329  uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainHeight - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
5330  if (pindex->nHeight < chainHeight - nCheckDepth)
5331  break;
5332  CBlock block;
5333  // check level 0: read from disk
5334  if (!ReadBlockFromDisk(block, pindex))
5335  return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
5336  // check level 1: verify block validity
5337  if (nCheckLevel >= 1 && !CheckBlock(block, state))
5338  return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5339  // check level 2: verify undo validity
5340  if (nCheckLevel >= 2 && pindex) {
5341  CBlockUndo undo;
5342  CDiskBlockPos pos = pindex->GetUndoPos();
5343  if (!pos.IsNull()) {
5344  if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
5345  return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5346  }
5347  }
5348  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
5349  if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
5350  bool fClean = true;
5351  if (!DisconnectBlock(block, state, pindex, coins, &fClean))
5352  return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
5353  pindexState = pindex->pprev;
5354  if (!fClean) {
5355  nGoodTransactions = 0;
5356  pindexFailure = pindex;
5357  } else
5358  nGoodTransactions += block.vtx.size();
5359  }
5360  if (ShutdownRequested())
5361  return true;
5362  }
5363  if (pindexFailure)
5364  return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainHeight - pindexFailure->nHeight + 1, nGoodTransactions);
5365 
5366  // check level 4: try reconnecting blocks
5367  if (nCheckLevel >= 4) {
5368  CBlockIndex* pindex = pindexState;
5369  while (pindex != chainActive.Tip()) {
5370  boost::this_thread::interruption_point();
5371  uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainHeight - pindex->nHeight)) / (double)nCheckDepth * 50))));
5372  pindex = chainActive.Next(pindex);
5373  CBlock block;
5374  if (!ReadBlockFromDisk(block, pindex))
5375  return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
5376  if (!ConnectBlock(block, state, pindex, coins, false))
5377  return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
5378  }
5379  }
5380 
5381  LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainHeight - pindexState->nHeight, nGoodTransactions);
5382 
5383  return true;
5384 }
5385 
5387 {
5388  LOCK(cs_main);
5389  setBlockIndexCandidates.clear();
5390  chainActive.SetTip(NULL);
5391  pindexBestInvalid = NULL;
5392  pindexBestHeader = NULL;
5393  mempool.clear();
5394  mapOrphanTransactions.clear();
5396  nSyncStarted = 0;
5397  mapBlocksUnlinked.clear();
5398  vinfoBlockFile.clear();
5399  nLastBlockFile = 0;
5400  nBlockSequenceId = 1;
5401  mapBlockSource.clear();
5402  mapBlocksInFlight.clear();
5403  nQueuedValidatedHeaders = 0;
5404  nPreferredDownload = 0;
5405  setDirtyBlockIndex.clear();
5406  setDirtyFileInfo.clear();
5407  mapNodeState.clear();
5408  recentRejects.reset(nullptr);
5409 
5410  for (BlockMap::value_type& entry : mapBlockIndex) {
5411  delete entry.second;
5412  }
5413  mapBlockIndex.clear();
5414 }
5415 
5416 bool LoadBlockIndex(std::string& strError)
5417 {
5418  // Load block index from databases
5419  if (!fReindex && !LoadBlockIndexDB(strError))
5420  return false;
5421  return true;
5422 }
5423 
5424 
5426 {
5427  LOCK(cs_main);
5428 
5429  // Initialize global variables that cannot be constructed at startup.
5430  recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
5431 
5432  // Check whether we're already initialized
5433  if (chainActive.Genesis() != NULL)
5434  return true;
5435 
5436  // Use the provided setting for -txindex in the new database
5437  fTxIndex = GetBoolArg("-txindex", true);
5438  pblocktree->WriteFlag("txindex", fTxIndex);
5439  LogPrintf("Initializing databases...\n");
5440 
5441  // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
5442  if (!fReindex) {
5443  try {
5444  CBlock& block = const_cast<CBlock&>(Params().GenesisBlock());
5445  // Start new block file
5446  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
5447  CDiskBlockPos blockPos;
5448  CValidationState state;
5449  if (!FindBlockPos(state, blockPos, nBlockSize + 8, 0, block.GetBlockTime()))
5450  return error("LoadBlockIndex() : FindBlockPos failed");
5451  if (!WriteBlockToDisk(block, blockPos))
5452  return error("LoadBlockIndex() : writing genesis block to disk failed");
5453  CBlockIndex* pindex = AddToBlockIndex(block);
5454  if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
5455  return error("LoadBlockIndex() : genesis block not accepted");
5456  // Force a chainstate write so that when we VerifyDB in a moment, it doesnt check stale data
5457  return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
5458  } catch (const std::runtime_error& e) {
5459  return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
5460  }
5461  }
5462 
5463  return true;
5464 }
5465 
5466 
5467 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos* dbp)
5468 {
5469  // Map of disk positions for blocks with unknown parent (only used for reindex)
5470  static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
5471  int64_t nStart = GetTimeMillis();
5472 
5473  int nLoaded = 0;
5474  try {
5475  // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
5476  CBufferedFile blkdat(fileIn, 2 * MAX_BLOCK_SIZE_CURRENT, MAX_BLOCK_SIZE_CURRENT + 8, SER_DISK, CLIENT_VERSION);
5477  uint64_t nRewind = blkdat.GetPos();
5478  while (!blkdat.eof()) {
5479  boost::this_thread::interruption_point();
5480 
5481  blkdat.SetPos(nRewind);
5482  nRewind++; // start one byte further next time, in case of failure
5483  blkdat.SetLimit(); // remove former limit
5484  unsigned int nSize = 0;
5485  try {
5486  // locate a header
5487  unsigned char buf[MESSAGE_START_SIZE];
5488  blkdat.FindByte(Params().MessageStart()[0]);
5489  nRewind = blkdat.GetPos() + 1;
5490  blkdat >> FLATDATA(buf);
5491  if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
5492  continue;
5493  // read size
5494  blkdat >> nSize;
5495  if (nSize < 80 || nSize > MAX_BLOCK_SIZE_CURRENT)
5496  continue;
5497  } catch (const std::exception&) {
5498  // no valid block header found; don't complain
5499  break;
5500  }
5501  try {
5502  // read block
5503  uint64_t nBlockPos = blkdat.GetPos();
5504  if (dbp)
5505  dbp->nPos = nBlockPos;
5506  blkdat.SetLimit(nBlockPos + nSize);
5507  blkdat.SetPos(nBlockPos);
5508  CBlock block;
5509  blkdat >> block;
5510  nRewind = blkdat.GetPos();
5511 
5512  // detect out of order blocks, and store them for later
5513  uint256 hash = block.GetHash();
5514  if (hash != Params().HashGenesisBlock() &&
5515  mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
5516  LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__,
5517  hash.GetHex(), block.hashPrevBlock.GetHex());
5518  if (dbp)
5519  mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
5520  continue;
5521  }
5522 
5523  // process in case the block isn't known yet
5524  if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash] == NULL) || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
5525  CValidationState state;
5526  if (ProcessNewBlock(state, NULL, &block, dbp))
5527  nLoaded++;
5528  if (state.IsError())
5529  break;
5530  } else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) {
5531  LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(),
5532  mapBlockIndex[hash]->nHeight);
5533  }
5534 
5535  // Recursively process earlier encountered successors of this block
5536  std::deque<uint256> queue;
5537  queue.push_back(hash);
5538  while (!queue.empty()) {
5539  uint256 head = queue.front();
5540  queue.pop_front();
5541  std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(
5542  head);
5543  while (range.first != range.second) {
5544  std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
5545  if (ReadBlockFromDisk(block, it->second)) {
5546  LogPrintf("%s: Processing out of order child %s of %s\n", __func__,
5547  block.GetHash().ToString(),
5548  head.ToString());
5549  CValidationState dummy;
5550  if (ProcessNewBlock(dummy, NULL, &block, &it->second)) {
5551  nLoaded++;
5552  queue.push_back(block.GetHash());
5553  }
5554  }
5555  range.first++;
5556  mapBlocksUnknownParent.erase(it);
5557  }
5558  }
5559  } catch (const std::exception& e) {
5560  LogPrintf("%s : Deserialize or I/O error - %s\n", __func__, e.what());
5561  }
5562  }
5563  } catch (const std::runtime_error& e) {
5564  AbortNode(std::string("System error: ") + e.what());
5565  }
5566  if (nLoaded > 0)
5567  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
5568  return nLoaded > 0;
5569 }
5570 
5571 void static CheckBlockIndex()
5572 {
5573  if (!fCheckBlockIndex) {
5574  return;
5575  }
5576 
5577  LOCK(cs_main);
5578 
5579  // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
5580  // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
5581  // iterating the block tree require that chainActive has been initialized.)
5582  if (chainActive.Height() < 0) {
5583  assert(mapBlockIndex.size() <= 1);
5584  return;
5585  }
5586 
5587  // Build forward-pointing map of the entire block tree.
5588  std::multimap<CBlockIndex*, CBlockIndex*> forward;
5589  for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
5590  forward.insert(std::make_pair(it->second->pprev, it->second));
5591  }
5592 
5593  assert(forward.size() == mapBlockIndex.size());
5594 
5595  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(
5596  NULL);
5597  CBlockIndex* pindex = rangeGenesis.first->second;
5598  rangeGenesis.first++;
5599  assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
5600 
5601  // Iterate over the entire block tree, using depth-first search.
5602  // Along the way, remember whether there are blocks on the path from genesis
5603  // block being explored which are the first to have certain properties.
5604  size_t nNodes = 0;
5605  int nHeight = 0;
5606  CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
5607  CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
5608  CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
5609  CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
5610  CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
5611  while (pindex != NULL) {
5612  nNodes++;
5613  if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
5614  if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
5615  if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL &&
5617  pindexFirstNotTreeValid = pindex;
5618  if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL &&
5620  pindexFirstNotChainValid = pindex;
5621  if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL &&
5623  pindexFirstNotScriptsValid = pindex;
5624 
5625  // Begin: actual consistency checks.
5626  if (pindex->pprev == NULL) {
5627  // Genesis block checks.
5628  assert(pindex->GetBlockHash() == Params().HashGenesisBlock()); // Genesis block's hash must match.
5629  assert(pindex ==
5630  chainActive.Genesis()); // The current active chain's genesis block must be this block.
5631  }
5632  // HAVE_DATA is equivalent to VALID_TRANSACTIONS and equivalent to nTx > 0 (we stored the number of transactions in the block)
5633  assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
5634  assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0));
5635  if (pindex->nChainTx == 0)
5636  assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
5637  // All parents having data is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
5638  assert((pindexFirstMissing != NULL) == (pindex->nChainTx ==
5639  0)); // nChainTx == 0 is used to signal that all parent block's transaction data is available.
5640  assert(pindex->nHeight ==
5641  nHeight); // nHeight must be consistent.
5642  assert(pindex->pprev == NULL || pindex->nChainWork >=
5643  pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
5644  assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight <
5645  nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
5646  assert(pindexFirstNotTreeValid ==
5647  NULL); // All mapBlockIndex entries must at least be TREE valid
5648  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE)
5649  assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
5650  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN)
5651  assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
5652  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS)
5653  assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
5654  if (pindexFirstInvalid == NULL) {
5655  // Checks for not-invalid blocks.
5656  assert((pindex->nStatus & BLOCK_FAILED_MASK) ==
5657  0); // The failed mask cannot be set for blocks without invalid parents.
5658  }
5659  if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstMissing == NULL) {
5660  if (pindexFirstInvalid ==
5661  NULL) { // If this block sorts at least as good as the current tip and is valid, it must be in setBlockIndexCandidates.
5662  assert(setBlockIndexCandidates.count(pindex));
5663  }
5664  } else { // If this block sorts worse than the current tip, it cannot be in setBlockIndexCandidates.
5665  assert(setBlockIndexCandidates.count(pindex) == 0);
5666  }
5667  // Check whether this block is in mapBlocksUnlinked.
5668  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(
5669  pindex->pprev);
5670  bool foundInUnlinked = false;
5671  while (rangeUnlinked.first != rangeUnlinked.second) {
5672  assert(rangeUnlinked.first->first == pindex->pprev);
5673  if (rangeUnlinked.first->second == pindex) {
5674  foundInUnlinked = true;
5675  break;
5676  }
5677  rangeUnlinked.first++;
5678  }
5679  if (pindex->pprev && pindex->nStatus & BLOCK_HAVE_DATA && pindexFirstMissing != NULL) {
5680  if (pindexFirstInvalid ==
5681  NULL) { // If this block has block data available, some parent doesn't, and has no invalid parents, it must be in mapBlocksUnlinked.
5682  assert(foundInUnlinked);
5683  }
5684  } else { // If this block does not have block data available, or all parents do, it cannot be in mapBlocksUnlinked.
5685  assert(!foundInUnlinked);
5686  }
5687  // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
5688  // End: actual consistency checks.
5689 
5690  // Try descending into the first subnode.
5691  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = forward.equal_range(
5692  pindex);
5693  if (range.first != range.second) {
5694  // A subnode was found.
5695  pindex = range.first->second;
5696  nHeight++;
5697  continue;
5698  }
5699  // This is a leaf node.
5700  // Move upwards until we reach a node of which we have not yet visited the last child.
5701  while (pindex) {
5702  // We are going to either move to a parent or a sibling of pindex.
5703  // If pindex was the first with a certain property, unset the corresponding variable.
5704  if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
5705  if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
5706  if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
5707  if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
5708  if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
5709  // Find our parent.
5710  CBlockIndex* pindexPar = pindex->pprev;
5711  // Find which child we just visited.
5712  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangePar = forward.equal_range(
5713  pindexPar);
5714  while (rangePar.first->second != pindex) {
5715  assert(rangePar.first !=
5716  rangePar.second); // Our parent must have at least the node we're coming from as child.
5717  rangePar.first++;
5718  }
5719  // Proceed to the next one.
5720  rangePar.first++;
5721  if (rangePar.first != rangePar.second) {
5722  // Move to the sibling.
5723  pindex = rangePar.first->second;
5724  break;
5725  } else {
5726  // Move up further.
5727  pindex = pindexPar;
5728  nHeight--;
5729  continue;
5730  }
5731  }
5732  }
5733 
5734  // Check that we actually traversed the entire map.
5735  assert(nNodes == forward.size());
5736 }
5737 
5738 
5739 std::string GetWarnings(std::string strFor)
5740 {
5741  std::string strStatusBar;
5742  std::string strRPC;
5743 
5745  strStatusBar = _(
5746  "This is a pre-release test build - use at your own risk - do not use for staking or merchant applications!");
5747 
5748  if (GetBoolArg("-testsafemode", false))
5749  strStatusBar = strRPC = "testsafemode enabled";
5750 
5751  // Misc warnings like out of disk space and clock is wrong
5752  if (strMiscWarning != "") {
5753  strStatusBar = strMiscWarning;
5754  }
5755 
5756  if (fLargeWorkForkFound) {
5757  strStatusBar = strRPC = _(
5758  "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
5759  } else if (fLargeWorkInvalidChainFound) {
5760  strStatusBar = strRPC = _(
5761  "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
5762  }
5763 
5764  if (strFor == "statusbar")
5765  return strStatusBar;
5766  else if (strFor == "rpc")
5767  return strRPC;
5768  assert(!"GetWarnings() : invalid parameter");
5769  return "error";
5770 }
5771 
5772 
5774 //
5775 // Messages
5776 //
5777 
5778 
5779 bool static AlreadyHave(const CInv& inv)
5780 {
5781  switch (inv.type) {
5782  case MSG_TX: {
5783  assert(recentRejects);
5784  if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) {
5785  // If the chain tip has changed previously rejected transactions
5786  // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
5787  // or a double-spend. Reset the rejects filter and give those
5788  // txs a second chance.
5789  hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
5790  recentRejects->reset();
5791  }
5792 
5793  return recentRejects->contains(inv.hash) ||
5794  mempool.exists(inv.hash) ||
5795  mapOrphanTransactions.count(inv.hash) ||
5796  pcoinsTip->HaveCoins(inv.hash);
5797  }
5798  case MSG_BLOCK:
5799  return mapBlockIndex.count(inv.hash);
5800  case MSG_TXLOCK_REQUEST:
5801  return mapTxLockReq.count(inv.hash) ||
5802  mapTxLockReqRejected.count(inv.hash);
5803  case MSG_TXLOCK_VOTE:
5804  return mapTxLockVote.count(inv.hash);
5805  case MSG_MASTERNODE_WINNER:
5808  return true;
5809  }
5810  return false;
5811  case MSG_BUDGET_VOTE:
5812  if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) {
5814  return true;
5815  }
5816  return false;
5817  case MSG_BUDGET_PROPOSAL:
5818  if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) {
5820  return true;
5821  }
5822  return false;
5824  if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) {
5826  return true;
5827  }
5828  return false;
5829  case MSG_BUDGET_FINALIZED:
5830  if (budget.mapSeenFinalizedBudgets.count(inv.hash)) {
5832  return true;
5833  }
5834  return false;
5836  if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) {
5838  return true;
5839  }
5840  return false;
5841  case MSG_MASTERNODE_PING:
5842  return mnodeman.mapSeenMasternodePing.count(inv.hash);
5843  }
5844  // Don't know what it is, just say we already got one
5845  return true;
5846 }
5847 
5848 void static ProcessGetData(CNode* pfrom)
5849 {
5851 
5852  std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
5853  std::vector<CInv> vNotFound;
5854 
5855  LOCK(cs_main);
5856 
5857  while (it != pfrom->vRecvGetData.end()) {
5858  // Don't bother if send buffer is too full to respond anyway
5859  if (pfrom->nSendSize >= SendBufferSize())
5860  break;
5861 
5862  const CInv& inv = *it;
5863  {
5864  boost::this_thread::interruption_point();
5865  it++;
5866 
5867  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) {
5868  bool send = false;
5869  BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
5870  if (mi != mapBlockIndex.end()) {
5871  if (chainActive.Contains(mi->second)) {
5872  send = true;
5873  } else {
5874  // To prevent fingerprinting attacks, only send blocks outside of the active
5875  // chain if they are valid, and no more than a max reorg depth than the best header
5876  // chain we know about.
5877  send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
5878  (chainActive.Height() - mi->second->nHeight < Params().MaxReorganizationDepth());
5879  if (!send) {
5880  std::string remoteAddr;
5881  if (fLogIPs)
5882  remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
5883 
5884  LogPrintf(
5885  "ProcessGetData(): ignoring request from peer=%i%s for old block that is not in the main chain\n",
5886  pfrom->GetId(), remoteAddr);
5887  }
5888  }
5889  }
5890  // Don't send not-validated blocks
5891  if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) {
5892  // Send block from disk
5893  CBlock block;
5894  if (!ReadBlockFromDisk(block, (*mi).second))
5895  assert(!"cannot load block from disk");
5896  if (inv.type == MSG_BLOCK)
5897  pfrom->PushMessage(NetMsgType::BLOCK, block);
5898  else // MSG_FILTERED_BLOCK)
5899  {
5900  LOCK(pfrom->cs_filter);
5901  if (pfrom->pfilter) {
5902  CMerkleBlock merkleBlock(block, *pfrom->pfilter);
5903  pfrom->PushMessage(NetMsgType::MERKLEBLOCK, merkleBlock);
5904  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
5905  // This avoids hurting performance by pointlessly requiring a round-trip
5906  // Note that there is currently no way for a node to request any single transactions we didnt send here -
5907  // they must either disconnect and retry or request the full block.
5908  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
5909  // however we MUST always provide at least what the remote peer needs
5910  typedef std::pair<unsigned int, uint256> PairType;
5911  for (PairType& pair : merkleBlock.vMatchedTxn)
5912  pfrom->PushMessage(NetMsgType::TX, block.vtx[pair.first]);
5913  }
5914  // else
5915  // no response
5916  }
5917 
5918  // Trigger them to send a getblocks request for the next batch of inventory
5919  if (inv.hash == pfrom->hashContinue) {
5920  // Bypass PushInventory, this must send even if redundant,
5921  // and we want it right after the last block so they don't
5922  // wait for other stuff first.
5923  std::vector<CInv> vInv;
5924  vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
5925  pfrom->PushMessage(NetMsgType::INV, vInv);
5926  pfrom->hashContinue.SetNull();
5927  }
5928  }
5929  } else if (inv.IsKnownType()) {
5930  // Send stream from relay memory
5931  bool pushed = false;
5932  {
5933  LOCK(cs_mapRelay);
5934  std::map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
5935  if (mi != mapRelay.end()) {
5936  pfrom->PushMessage(inv.GetCommand(), (*mi).second);
5937  pushed = true;
5938  }
5939  }
5940 
5941  if (!pushed && inv.type == MSG_TX) {
5942  CTransaction tx;
5943  if (mempool.lookup(inv.hash, tx)) {
5944  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
5945  ss.reserve(1000);
5946  ss << tx;
5947  pfrom->PushMessage(NetMsgType::TX, ss);
5948  pushed = true;
5949  }
5950  }
5951  if (!pushed && inv.type == MSG_TXLOCK_VOTE) {
5952  if (mapTxLockVote.count(inv.hash)) {
5953  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
5954  ss.reserve(1000);
5955  ss << mapTxLockVote[inv.hash];
5956  pfrom->PushMessage(NetMsgType::IXLOCKVOTE, ss);
5957  pushed = true;
5958  }
5959  }
5960  if (!pushed && inv.type == MSG_TXLOCK_REQUEST) {
5961  if (mapTxLockReq.count(inv.hash)) {
5962  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
5963  ss.reserve(1000);
5964  ss << mapTxLockReq[inv.hash];
5965  pfrom->PushMessage(NetMsgType::IX, ss);
5966  pushed = true;
5967  }
5968  }
5969  if (!pushed && inv.type == MSG_MASTERNODE_WINNER) {
5971  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
5972  ss.reserve(1000);
5974  pfrom->PushMessage(NetMsgType::MNWINNER, ss);
5975  pushed = true;
5976  }
5977  }
5978  if (!pushed && inv.type == MSG_BUDGET_VOTE) {
5979  if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) {
5980  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
5981  ss.reserve(1000);
5983  pfrom->PushMessage(NetMsgType::BUDGETVOTE, ss);
5984  pushed = true;
5985  }
5986  }
5987 
5988  if (!pushed && inv.type == MSG_BUDGET_PROPOSAL) {
5989  if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) {
5990  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
5991  ss.reserve(1000);
5994  pushed = true;
5995  }
5996  }
5997 
5998  if (!pushed && inv.type == MSG_BUDGET_FINALIZED_VOTE) {
5999  if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) {
6000  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
6001  ss.reserve(1000);
6004  pushed = true;
6005  }
6006  }
6007 
6008  if (!pushed && inv.type == MSG_BUDGET_FINALIZED) {
6009  if (budget.mapSeenFinalizedBudgets.count(inv.hash)) {
6010  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
6011  ss.reserve(1000);
6012  ss << budget.mapSeenFinalizedBudgets[inv.hash];
6014  pushed = true;
6015  }
6016  }
6017 
6018  if (!pushed && inv.type == MSG_MASTERNODE_ANNOUNCE) {
6019  if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) {
6020  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
6021  ss.reserve(1000);
6024  pushed = true;
6025  }
6026  }
6027 
6028  if (!pushed && inv.type == MSG_MASTERNODE_PING) {
6029  if (mnodeman.mapSeenMasternodePing.count(inv.hash)) {
6030  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
6031  ss.reserve(1000);
6032  ss << mnodeman.mapSeenMasternodePing[inv.hash];
6033  pfrom->PushMessage(NetMsgType::MNPING, ss);
6034  pushed = true;
6035  }
6036  }
6037 
6038  if (!pushed) {
6039  vNotFound.push_back(inv);
6040  }
6041  }
6042 
6043  // Track requests for our stuff.
6044  GetMainSignals().Inventory(inv.hash);
6045 
6046  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
6047  break;
6048  }
6049  }
6050 
6051  pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
6052 
6053  if (!vNotFound.empty()) {
6054  // Let the peer know that we didn't find what it asked for, so it doesn't
6055  // have to wait around forever. Currently only SPV clients actually care
6056  // about this message: it's needed when they are recursively walking the
6057  // dependencies of relevant unconfirmed transactions. SPV clients want to
6058  // do that because they want to know about (and store and rebroadcast and
6059  // risk analyze) the dependencies of transactions relevant to them, without
6060  // having to download the entire memory pool.
6061  pfrom->PushMessage(NetMsgType::NOTFOUND, vNotFound);
6062  }
6063 }
6064 
6065 bool static ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
6066 {
6067  LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d, chainheight=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id, chainActive.Height());
6068  if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) {
6069  LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
6070  return true;
6071  }
6072  if (strCommand == NetMsgType::VERSION) {
6073  // Feeler connections exist only to verify if address is online.
6074  if (pfrom->fFeeler) {
6075  assert(pfrom->fInbound == false);
6076  pfrom->fDisconnect = true;
6077  }
6078 
6079  // Each connection can only send one version message
6080  if (pfrom->nVersion != 0) {
6081  pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message"));
6082  LOCK(cs_main);
6083  Misbehaving(pfrom->GetId(), 1);
6084  return false;
6085  }
6086 
6087  int64_t nTime;
6088  CAddress addrMe;
6089  CAddress addrFrom;
6090  uint64_t nNonce = 1;
6091  uint64_t nServiceInt;
6092  vRecv >> pfrom->nVersion >> nServiceInt >> nTime >> addrMe;
6093  pfrom->nServices = ServiceFlags(nServiceInt);
6094  if (!pfrom->fInbound) {
6095  addrman.SetServices(pfrom->addr, pfrom->nServices);
6096  }
6097  if (pfrom->nServicesExpected & ~pfrom->nServices) {
6098  LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->id, pfrom->nServices, pfrom->nServicesExpected);
6099  pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
6100  strprintf("Expected to offer services %08x", pfrom->nServicesExpected));
6101  pfrom->fDisconnect = true;
6102  return false;
6103  }
6104 
6105  if (pfrom->DisconnectOldProtocol(ActiveProtocol(), strCommand))
6106  return false;
6107 
6108  if (pfrom->DisconnectOldVersion(pfrom->strSubVer, chainActive.Height(), strCommand))
6109  return false;
6110 
6111  if (pfrom->nVersion == 10300)
6112  pfrom->nVersion = 300;
6113  if (!vRecv.empty())
6114  vRecv >> addrFrom >> nNonce;
6115  if (!vRecv.empty()) {
6116  vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
6117  pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
6118  }
6119  if (!vRecv.empty())
6120  vRecv >> pfrom->nStartingHeight;
6121  if (!vRecv.empty())
6122  vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
6123  else
6124  pfrom->fRelayTxes = true;
6125 
6126  // Disconnect if we connected to ourself
6127  if (nNonce == nLocalHostNonce && nNonce > 1) {
6128  LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
6129  pfrom->fDisconnect = true;
6130  return true;
6131  }
6132 
6133  pfrom->addrLocal = addrMe;
6134  if (pfrom->fInbound && addrMe.IsRoutable()) {
6135  SeenLocal(addrMe);
6136  }
6137 
6138  // Be shy and don't send version until we hear
6139  if (pfrom->fInbound)
6140  pfrom->PushVersion();
6141 
6142  pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
6143 
6144  {
6145  LOCK(cs_main);
6146  // Potentially mark this peer as a preferred download peer.
6147  UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
6148  }
6149  // Change version
6151  pfrom->ssSend.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
6152 
6153  if (!pfrom->fInbound) {
6154  // Advertise our address
6155  if (fListen && !IsInitialBlockDownload()) {
6156  CAddress addr = GetLocalAddress(&pfrom->addr);
6157  FastRandomContext insecure_rand;
6158  if (addr.IsRoutable()) {
6159  pfrom->PushAddress(addr, insecure_rand);
6160  } else if (IsPeerAddrLocalGood(pfrom)) {
6161  addr.SetIP(pfrom->addrLocal);
6162  pfrom->PushAddress(addr, insecure_rand);
6163  }
6164  }
6165 
6166  // Get recent addresses
6167  if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) {
6169  pfrom->fGetAddr = true;
6170  }
6171  addrman.Good(pfrom->addr);
6172  }
6173 
6174  pfrom->fSuccessfullyConnected = true;
6175 
6176  std::string remoteAddr;
6177  if (fLogIPs)
6178  remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
6179 
6180  LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
6181  pfrom->cleanSubVer, pfrom->nVersion,
6182  pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
6183  remoteAddr);
6184 
6185  int64_t nTimeOffset = nTime - GetTime();
6186  pfrom->nTimeOffset = nTimeOffset;
6187  AddTimeData(pfrom->addr, nTimeOffset);
6188  } else if (pfrom->nVersion == 0) {
6189  // Must have a version message before anything else
6190  LOCK(cs_main);
6191  Misbehaving(pfrom->GetId(), 1);
6192  return false;
6193  } else if (strCommand == NetMsgType::VERACK) {
6194  pfrom->SetRecvVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
6195 
6196  // Mark this node as currently connected, so we update its timestamp later.
6197  if (pfrom->fNetworkNode) {
6198  LOCK(cs_main);
6199  State(pfrom->GetId())->fCurrentlyConnected = true;
6200  }
6201  } else if (strCommand == NetMsgType::ADDR) {
6202  std::vector<CAddress> vAddr;
6203  vRecv >> vAddr;
6204 
6205  // Don't want addr from older versions unless seeding
6206  if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
6207  return true;
6208  if (vAddr.size() > 1000) {
6209  LOCK(cs_main);
6210  Misbehaving(pfrom->GetId(), 20);
6211  return error("message addr size() = %u", vAddr.size());
6212  }
6213 
6214  // Store the new addresses
6215  std::vector<CAddress> vAddrOk;
6216  int64_t nNow = GetAdjustedTime();
6217  int64_t nSince = nNow - 10 * 60;
6218  for (CAddress& addr : vAddr) {
6219  boost::this_thread::interruption_point();
6220 
6221  if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
6222  continue;
6223 
6224  if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
6225  addr.nTime = nNow - 5 * 24 * 60 * 60;
6226  pfrom->AddAddressKnown(addr);
6227  bool fReachable = IsReachable(addr);
6228  if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) {
6229  // Relay to a limited number of other nodes
6230  {
6231  LOCK(cs_vNodes);
6232  // Use deterministic randomness to send to the same nodes for 24 hours
6233  // at a time so the addrKnowns of the chosen nodes prevent repeats
6234  static uint256 hashSalt;
6235  if (hashSalt.IsNull())
6236  hashSalt = GetRandHash();
6237  uint64_t hashAddr = addr.GetHash();
6238  uint256 hashRand = hashSalt ^ (hashAddr << 32) ^ ((GetTime() + hashAddr) / (24 * 60 * 60));
6239  hashRand = Hash(BEGIN(hashRand), END(hashRand));
6240  std::multimap<uint256, CNode*> mapMix;
6241  for (CNode* pnode : vNodes) {
6242  if (pnode->nVersion < CADDR_TIME_VERSION)
6243  continue;
6244  unsigned int nPointer;
6245  memcpy(&nPointer, &pnode, sizeof(nPointer));
6246  uint256 hashKey = hashRand ^ nPointer;
6247  hashKey = Hash(BEGIN(hashKey), END(hashKey));
6248  mapMix.insert(std::make_pair(hashKey, pnode));
6249  }
6250  int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
6251  FastRandomContext insecure_rand;
6252  for (std::multimap<uint256, CNode*>::iterator mi = mapMix.begin();
6253  mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
6254  ((*mi).second)->PushAddress(addr, insecure_rand);
6255  }
6256  }
6257  // Do not store addresses outside our network
6258  if (fReachable)
6259  vAddrOk.push_back(addr);
6260  }
6261  addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
6262  if (vAddr.size() < 1000)
6263  pfrom->fGetAddr = false;
6264  if (pfrom->fOneShot)
6265  pfrom->fDisconnect = true;
6266  } else if (strCommand == NetMsgType::INV) {
6267  std::vector<CInv> vInv;
6268  vRecv >> vInv;
6269  if (vInv.size() > MAX_INV_SZ) {
6270  LOCK(cs_main);
6271  Misbehaving(pfrom->GetId(), 20);
6272  return error("message inv size() = %u", vInv.size());
6273  }
6274 
6275  // find last block in inv vector
6276  unsigned int nLastBlock = (unsigned int)(-1);
6277  for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
6278  if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
6279  nLastBlock = vInv.size() - 1 - nInv;
6280  break;
6281  }
6282  }
6283 
6284  LOCK(cs_main);
6285 
6286  std::vector<CInv> vToFetch;
6287  for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
6288  const CInv& inv = vInv[nInv];
6289 
6290  boost::this_thread::interruption_point();
6291  pfrom->AddInventoryKnown(inv);
6292 
6293  bool fAlreadyHave = AlreadyHave(inv);
6294  LogPrint(BCLog::NET, "got inv: %s %s peer=%d, inv.type=%d, mapBlocksInFlight.count(inv.hash)=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id, inv.type, mapBlocksInFlight.count(inv.hash));
6295 
6296  if (!fAlreadyHave && pfrom)
6297  pfrom->AskFor(inv, IsInitialBlockDownload()); // peershares: immediate retry during initial download
6298  if (inv.type == MSG_BLOCK) {
6299  UpdateBlockAvailability(pfrom->GetId(), inv.hash);
6300  if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
6301  // Add this to the list of blocks to request
6302  vToFetch.push_back(inv);
6303  LogPrint(BCLog::NET, "getblocks (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(),
6304  pfrom->id);
6305  }
6306  } else if (nInv == nLastBlock) {
6307  // In case we are on a very long side-chain, it is possible that we already have
6308  // the last block in an inv bundle sent in response to getblocks. Try to detect
6309  // this situation and push another getblocks to continue.
6310  std::vector<CInv> vGetData(1,inv);
6311 
6312  if (pfrom) {
6314  }
6315  printf("force request: %s\n", inv.ToString().c_str());
6316  }
6317 
6318  // Track requests for our stuff
6319  GetMainSignals().Inventory(inv.hash);
6320  if (pfrom->nSendSize > (SendBufferSize() * 2)) {
6321  Misbehaving(pfrom->GetId(), 50);
6322  return error("send buffer size() = %u", pfrom->nSendSize);
6323  }
6324  }
6325 
6326  if (!vToFetch.empty())
6327  pfrom->PushMessage(NetMsgType::GETDATA, vToFetch);
6328  } else if (strCommand == NetMsgType::GETDATA) {
6329  std::vector<CInv> vInv;
6330  vRecv >> vInv;
6331  if (vInv.size() > MAX_INV_SZ) {
6332  LOCK(cs_main);
6333  Misbehaving(pfrom->GetId(), 20);
6334  return error("message getdata size() = %u", vInv.size());
6335  }
6336 
6337  if ((vInv.size() != 1))
6338  LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
6339 
6340  if (vInv.size() > 0)
6341  LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
6342 
6343  pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
6344  ProcessGetData(pfrom);
6345  } else if (strCommand == NetMsgType::GETBLOCKS || strCommand == NetMsgType::GETHEADERS) {
6346  CBlockLocator locator;
6347  uint256 hashStop;
6348  vRecv >> locator >> hashStop;
6349 
6350  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
6351  LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId());
6352  pfrom->fDisconnect = true;
6353  return true;
6354  }
6355 
6356  LOCK(cs_main);
6357 
6358  // Find the last block the caller has in the main chain
6359  CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
6360 
6361  // Send the rest of the chain
6362  if (pindex)
6363  pindex = chainActive.Next(pindex);
6364  int nLimit = 500;
6365  LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1),
6366  hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
6367  for (; pindex; pindex = chainActive.Next(pindex)) {
6368  if (pindex->GetBlockHash() == hashStop) {
6369  LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
6370  break;
6371  }
6372  pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
6373  if (--nLimit <= 0) {
6374  // When this block is requested, we'll send an inv that'll make them
6375  // getblocks the next batch of inventory.
6376  LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight,
6377  pindex->GetBlockHash().ToString());
6378  pfrom->hashContinue = pindex->GetBlockHash();
6379  break;
6380  }
6381  }
6382  } else if (strCommand == NetMsgType::HEADERS && Params().HeadersFirstSyncingActive()) {
6383  CBlockLocator locator;
6384  uint256 hashStop;
6385  vRecv >> locator >> hashStop;
6386 
6387  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
6388  LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId());
6389  pfrom->fDisconnect = true;
6390  return true;
6391  }
6392 
6393  LOCK(cs_main);
6394 
6395  if (IsInitialBlockDownload())
6396  return true;
6397 
6398  CBlockIndex* pindex = NULL;
6399  if (locator.IsNull()) {
6400  // If locator is null, return the hashStop block
6401  BlockMap::iterator mi = mapBlockIndex.find(hashStop);
6402  if (mi == mapBlockIndex.end())
6403  return true;
6404  pindex = (*mi).second;
6405  } else {
6406  // Find the last block the caller has in the main chain
6407  pindex = FindForkInGlobalIndex(chainActive, locator);
6408  if (pindex)
6409  pindex = chainActive.Next(pindex);
6410  }
6411 
6412  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
6413  std::vector<CBlock> vHeaders;
6414  int nLimit = MAX_HEADERS_RESULTS;
6415  LogPrintf("getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
6416  for (; pindex; pindex = chainActive.Next(pindex)) {
6417  vHeaders.push_back(pindex->GetBlockHeader());
6418  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
6419  break;
6420  }
6421  pfrom->PushMessage(NetMsgType::HEADERS, vHeaders);
6422  } else if (strCommand == NetMsgType::TX) {
6423  std::vector<uint256> vWorkQueue;
6424  std::vector<uint256> vEraseQueue;
6425  CTransaction tx;
6426 
6427  //masternode signed transaction
6428  bool ignoreFees = false;
6429  CTxIn vin;
6430  std::vector<unsigned char> vchSig;
6431 
6432  vRecv >> tx;
6433 
6434  CInv inv(MSG_TX, tx.GetHash());
6435  pfrom->AddInventoryKnown(inv);
6436 
6437  LOCK(cs_main);
6438 
6439  bool fMissingInputs = false;
6440  CValidationState state;
6441 
6442  mapAlreadyAskedFor.erase(inv);
6443 
6444  if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs, false, ignoreFees)) {
6446  RelayTransaction(tx);
6447  vWorkQueue.push_back(inv.hash);
6448 
6449  LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d %s : accepted %s (poolsz %u)\n",
6450  pfrom->id, pfrom->cleanSubVer,
6451  tx.GetHash().ToString(),
6452  mempool.mapTx.size());
6453 
6454  // Recursively process any orphan transactions that depended on this one
6455  std::set<NodeId> setMisbehaving;
6456  for (unsigned int i = 0; i < vWorkQueue.size(); i++) {
6457  std::map<uint256, std::set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
6458  if (itByPrev == mapOrphanTransactionsByPrev.end())
6459  continue;
6460  for(std::set<uint256>::iterator mi = itByPrev->second.begin();
6461  mi != itByPrev->second.end();
6462  ++mi) {
6463  const uint256& orphanHash = *mi;
6464  const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
6465  NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
6466  bool fMissingInputs2 = false;
6467  // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
6468  // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
6469  // anyone relaying LegitTxX banned)
6470  CValidationState stateDummy;
6471 
6472 
6473  if (setMisbehaving.count(fromPeer))
6474  continue;
6475  if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) {
6476  LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
6477  RelayTransaction(orphanTx);
6478  vWorkQueue.push_back(orphanHash);
6479  vEraseQueue.push_back(orphanHash);
6480  } else if (!fMissingInputs2) {
6481  int nDos = 0;
6482  if (stateDummy.IsInvalid(nDos) && nDos > 0) {
6483  // Punish peer that gave us an invalid orphan tx
6484  Misbehaving(fromPeer, nDos);
6485  setMisbehaving.insert(fromPeer);
6486  LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
6487  }
6488  // Has inputs but not accepted to mempool
6489  // Probably non-standard or insufficient fee/priority
6490  LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
6491  vEraseQueue.push_back(orphanHash);
6492  assert(recentRejects);
6493  recentRejects->insert(orphanHash);
6494  }
6496  }
6497  }
6498 
6499  for (uint256 hash : vEraseQueue)
6500  EraseOrphanTx(hash);
6501  } else if (fMissingInputs) {
6502  AddOrphanTx(tx, pfrom->GetId());
6503 
6504  // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
6505  unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx",
6506  DEFAULT_MAX_ORPHAN_TRANSACTIONS));
6507  unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
6508  if (nEvicted > 0)
6509  LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
6510  } else {
6511  // AcceptToMemoryPool() returned false, possibly because the tx is
6512  // already in the mempool; if the tx isn't in the mempool that
6513  // means it was rejected and we shouldn't ask for it again.
6514  if (!mempool.exists(tx.GetHash())) {
6515  assert(recentRejects);
6516  recentRejects->insert(tx.GetHash());
6517  }
6518  if (pfrom->fWhitelisted) {
6519  // Always relay transactions received from whitelisted peers, even
6520  // if they were rejected from the mempool, allowing the node to
6521  // function as a gateway for nodes hidden behind it.
6522  //
6523  // FIXME: This includes invalid transactions, which means a
6524  // whitelisted peer could get us banned! We may want to change
6525  // that.
6526  RelayTransaction(tx);
6527  }
6528  }
6529 
6530  int nDoS = 0;
6531  if (state.IsInvalid(nDoS)) {
6532  LogPrint(BCLog::MEMPOOL, "%s from peer=%d %s was not accepted into the memory pool: %s\n",
6533  tx.GetHash().ToString(),
6534  pfrom->id, pfrom->cleanSubVer,
6535  state.GetRejectReason());
6536  pfrom->PushMessage(NetMsgType::REJECT, strCommand, state.GetRejectCode(),
6537  state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
6538  if (nDoS > 0)
6539  Misbehaving(pfrom->GetId(), nDoS);
6540  }
6541  } else if (strCommand == NetMsgType::HEADERS && Params().HeadersFirstSyncingActive() && !fImporting &&
6542  !fReindex) // Ignore headers received while importing
6543  {
6544  std::vector<CBlockHeader> headers;
6545 
6546  // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
6547  unsigned int nCount = ReadCompactSize(vRecv);
6548  if (nCount > MAX_HEADERS_RESULTS) {
6549  LOCK(cs_main);
6550  Misbehaving(pfrom->GetId(), 20);
6551  return error("headers message size = %u", nCount);
6552  }
6553  headers.resize(nCount);
6554  for (unsigned int n = 0; n < nCount; n++) {
6555  vRecv >> headers[n];
6556  ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
6557  }
6558 
6559  LOCK(cs_main);
6560 
6561  if (nCount == 0) {
6562  // Nothing interesting. Stop asking this peers for more headers.
6563  return true;
6564  }
6565  CBlockIndex* pindexLast = NULL;
6566  for (const CBlockHeader& header : headers) {
6567  CValidationState state;
6568  if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
6569  Misbehaving(pfrom->GetId(), 20);
6570  return error("non-continuous headers sequence");
6571  }
6572 
6573  /*TODO: this has a CBlock cast on it so that it will compile. There should be a solution for this
6574  * before headers are reimplemented on mainnet
6575  */
6576  if (!AcceptBlockHeader((CBlock)header, state, &pindexLast)) {
6577  int nDoS;
6578  if (state.IsInvalid(nDoS)) {
6579  if (nDoS > 0)
6580  Misbehaving(pfrom->GetId(), nDoS);
6581  std::string strError = "invalid header received " + header.GetHash().ToString();
6582  return error(strError.c_str());
6583  }
6584  }
6585  }
6586 
6587  if (pindexLast)
6588  UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
6589 
6590  if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
6591  // Headers message had its maximum size; the peer may have more headers.
6592  // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
6593  // from there instead.
6594  LogPrintf("more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id,
6595  pfrom->nStartingHeight);
6597  }
6598 
6599  CheckBlockIndex();
6600  } else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
6601  {
6602  CBlock block;
6603  vRecv >> block;
6604  uint256 hashBlock = block.GetHash();
6605  CInv inv(MSG_BLOCK, hashBlock);
6606  LogPrint(BCLog::NET, "received block %s peer=%d, height=%d\n", inv.hash.ToString(), pfrom->id, chainActive.Height());
6607 
6608  //sometimes we will be sent their most recent block and its not the one we want, in that case tell where we are
6609  if (!mapBlockIndex.count(block.hashPrevBlock)) {
6610  if (find(pfrom->vBlockRequested.begin(), pfrom->vBlockRequested.end(), hashBlock) != pfrom->vBlockRequested.end()) {
6611  //we already asked for this block, so lets work backwards and ask for the previous block
6612  pfrom->PushMessage(NetMsgType::GETBLOCKS, chainActive.GetLocator(), block.hashPrevBlock);
6613  pfrom->vBlockRequested.push_back(block.hashPrevBlock);
6614  } else {
6615  //ask to sync to this block
6617  pfrom->vBlockRequested.push_back(hashBlock);
6618  }
6619  } else {
6620  pfrom->AddInventoryKnown(inv);
6621  CValidationState state;
6622  if (!mapBlockIndex.count(block.GetHash())) {
6623  ProcessNewBlock(state, pfrom, &block);
6624  int nDoS;
6625  if (state.IsInvalid(nDoS)) {
6626  pfrom->PushMessage(NetMsgType::REJECT, strCommand, state.GetRejectCode(),
6627  state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
6628  if (nDoS > 0) {
6629  TRY_LOCK(cs_main, lockMain);
6630  if (lockMain) Misbehaving(pfrom->GetId(), nDoS);
6631  }
6632  }
6633  //disconnect this node if its old protocol version
6634  pfrom->DisconnectOldProtocol(ActiveProtocol(), strCommand);
6635  pfrom->DisconnectOldVersion(pfrom->strSubVer, chainActive.Height(), strCommand);
6636  if (mapBlockIndex.count(block.GetHash())) {
6637  LogPrint(BCLog::NET, "Added block %s to block index map\n", block.GetHash().GetHex());
6638  }
6639  } else {
6640  LogPrint(BCLog::NET, "%s : Already processed block %s, skipping ProcessNewBlock()\n", __func__,
6641  block.GetHash().GetHex());
6642  }
6643  }
6644  }
6645 
6646 
6647  // This asymmetric behavior for inbound and outbound connections was introduced
6648  // to prevent a fingerprinting attack: an attacker can send specific fake addresses
6649  // to users' AddrMan and later request them by sending getaddr messages.
6650  // Making users (which are behind NAT and can only make outgoing connections) ignore
6651  // getaddr message mitigates the attack.
6652  else if ((strCommand == NetMsgType::GETADDR) && (pfrom->fInbound)) {
6653  pfrom->vAddrToSend.clear();
6654  std::vector<CAddress> vAddr = addrman.GetAddr();
6655  FastRandomContext insecure_rand;
6656  for (const CAddress& addr : vAddr)
6657  pfrom->PushAddress(addr, insecure_rand);
6658  } else if (strCommand == NetMsgType::MEMPOOL) {
6659  LOCK2(cs_main, pfrom->cs_filter);
6660 
6661  std::vector<uint256> vtxid;
6662  mempool.queryHashes(vtxid);
6663  std::vector<CInv> vInv;
6664  for (uint256& hash : vtxid) {
6665  CInv inv(MSG_TX, hash);
6666  CTransaction tx;
6667  bool fInMemPool = mempool.lookup(hash, tx);
6668  if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
6669  if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
6670  (!pfrom->pfilter))
6671  vInv.push_back(inv);
6672  if (vInv.size() == MAX_INV_SZ) {
6673  pfrom->PushMessage(NetMsgType::INV, vInv);
6674  vInv.clear();
6675  }
6676  }
6677  if (vInv.size() > 0)
6678  pfrom->PushMessage(NetMsgType::INV, vInv);
6679  } else if (strCommand == NetMsgType::PING) {
6680  if (pfrom->nVersion > BIP0031_VERSION) {
6681  uint64_t nonce = 0;
6682  vRecv >> nonce;
6683  // Echo the message back with the nonce. This allows for two useful features:
6684  //
6685  // 1) A remote node can quickly check if the connection is operational
6686  // 2) Remote nodes can measure the latency of the network thread. If this node
6687  // is overloaded it won't respond to pings quickly and the remote node can
6688  // avoid sending us more work, like chain download requests.
6689  //
6690  // The nonce stops the remote getting confused between different pings: without
6691  // it, if the remote node sends a ping once per second and this node takes 5
6692  // seconds to respond to each, the 5th ping the remote sends would appear to
6693  // return very quickly.
6694  pfrom->PushMessage(NetMsgType::PONG, nonce);
6695  }
6696  } else if (strCommand == NetMsgType::PONG) {
6697  int64_t pingUsecEnd = nTimeReceived;
6698  uint64_t nonce = 0;
6699  size_t nAvail = vRecv.in_avail();
6700  bool bPingFinished = false;
6701  std::string sProblem;
6702 
6703  if (nAvail >= sizeof(nonce)) {
6704  vRecv >> nonce;
6705 
6706  // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
6707  if (pfrom->nPingNonceSent != 0) {
6708  if (nonce == pfrom->nPingNonceSent) {
6709  // Matching pong received, this ping is no longer outstanding
6710  bPingFinished = true;
6711  int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
6712  if (pingUsecTime > 0) {
6713  // Successful ping time measurement, replace previous
6714  pfrom->nPingUsecTime = pingUsecTime;
6715  pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
6716  } else {
6717  // This should never happen
6718  sProblem = "Timing mishap";
6719  }
6720  } else {
6721  // Nonce mismatches are normal when pings are overlapping
6722  sProblem = "Nonce mismatch";
6723  if (nonce == 0) {
6724  // This is most likely a bug in another implementation somewhere, cancel this ping
6725  bPingFinished = true;
6726  sProblem = "Nonce zero";
6727  }
6728  }
6729  } else {
6730  sProblem = "Unsolicited pong without ping";
6731  }
6732  } else {
6733  // This is most likely a bug in another implementation somewhere, cancel this ping
6734  bPingFinished = true;
6735  sProblem = "Short payload";
6736  }
6737 
6738  if (!(sProblem.empty())) {
6739  LogPrint(BCLog::NET, "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
6740  pfrom->id,
6741  pfrom->cleanSubVer,
6742  sProblem,
6743  pfrom->nPingNonceSent,
6744  nonce,
6745  nAvail);
6746  }
6747  if (bPingFinished) {
6748  pfrom->nPingNonceSent = 0;
6749  }
6750  } else if (!(nLocalServices & NODE_BLOOM) &&
6751  (strCommand == NetMsgType::FILTERLOAD ||
6752  strCommand == NetMsgType::FILTERADD ||
6753  strCommand == NetMsgType::FILTERCLEAR)) {
6754  LogPrintf("bloom message=%s\n", strCommand);
6755  LOCK(cs_main);
6756  Misbehaving(pfrom->GetId(), 100);
6757  } else if (strCommand == NetMsgType::FILTERLOAD) {
6758  CBloomFilter filter;
6759  vRecv >> filter;
6760 
6761  if (!filter.IsWithinSizeConstraints()) {
6762  // There is no excuse for sending a too-large filter
6763  LOCK(cs_main);
6764  Misbehaving(pfrom->GetId(), 100);
6765  } else {
6766  LOCK(pfrom->cs_filter);
6767  delete pfrom->pfilter;
6768  pfrom->pfilter = new CBloomFilter(filter);
6769  pfrom->pfilter->UpdateEmptyFull();
6770  }
6771  pfrom->fRelayTxes = true;
6772  } else if (strCommand == NetMsgType::FILTERADD) {
6773  std::vector<unsigned char> vData;
6774  vRecv >> vData;
6775 
6776  // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
6777  // and thus, the maximum size any matched object can have) in a filteradd message
6778  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
6779  LOCK(cs_main);
6780  Misbehaving(pfrom->GetId(), 100);
6781  } else {
6782  LOCK(pfrom->cs_filter);
6783  if (pfrom->pfilter)
6784  pfrom->pfilter->insert(vData);
6785  else {
6786  LOCK(cs_main);
6787  Misbehaving(pfrom->GetId(), 100);
6788  }
6789  }
6790  } else if (strCommand == NetMsgType::FILTERCLEAR) {
6791  LOCK(pfrom->cs_filter);
6792  delete pfrom->pfilter;
6793  pfrom->pfilter = new CBloomFilter();
6794  pfrom->fRelayTxes = true;
6795  } else if (strCommand == NetMsgType::REJECT) {
6796  try {
6797  std::string strMsg;
6798  unsigned char ccode;
6799  std::string strReason;
6800  vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
6801 
6802  std::ostringstream ss;
6803  ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
6804 
6805  if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX) {
6806  uint256 hash;
6807  vRecv >> hash;
6808  ss << ": hash " << hash.ToString();
6809  }
6810  LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
6811  } catch (const std::ios_base::failure& e) {
6812  // Avoid feedback loops by preventing reject messages from triggering a new reject message.
6813  LogPrint(BCLog::NET, "Unparseable reject message received\n");
6814  }
6815  } else {
6816  bool found = false;
6817  const std::vector<std::string> &allMessages = getAllNetMessageTypes();
6818  for (const std::string msg : allMessages) {
6819  if(msg == strCommand) {
6820  found = true;
6821  break;
6822  }
6823  }
6824 
6825  if (found) {
6826  //probably one the extensions
6827  mnodeman.ProcessMessage(pfrom, strCommand, vRecv);
6828  budget.ProcessMessage(pfrom, strCommand, vRecv);
6829  masternodePayments.ProcessMessageMasternodePayments(pfrom, strCommand, vRecv);
6830  ProcessMessageSwiftTX(pfrom, strCommand, vRecv);
6831  masternodeSync.ProcessMessage(pfrom, strCommand, vRecv);
6832  } else {
6833  // Ignore unknown commands for extensibility
6834  LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
6835  }
6836  }
6837 
6838 
6839  return true;
6840 }
6841 
6842 // Note: whenever a protocol update is needed toggle between both implementations (comment out the formerly active one)
6843 // it was the one which was commented out
6845 {
6846  return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT;
6847 }
6848 
6850 {
6851  // Message format
6852  // (4) message start
6853  // (12) command
6854  // (4) size
6855  // (4) checksum
6856  // (x) data
6857  //
6858  bool fOk = true;
6859 
6860  if (!pfrom->vRecvGetData.empty())
6861  ProcessGetData(pfrom);
6862 
6863  // this maintains the order of responses
6864  if (!pfrom->vRecvGetData.empty()) return fOk;
6865 
6866  std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
6867  while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
6868  // Don't bother if send buffer is too full to respond anyway
6869  if (pfrom->nSendSize >= SendBufferSize())
6870  break;
6871 
6872  // get next message
6873  CNetMessage& msg = *it;
6874 
6875  // end, if an incomplete message is found
6876  if (!msg.complete())
6877  break;
6878 
6879  // at this point, any failure means we can delete the current message
6880  it++;
6881 
6882  // Scan for message start
6883  if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
6884  LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
6885  fOk = false;
6886  break;
6887  }
6888 
6889  // Read header
6890  CMessageHeader& hdr = msg.hdr;
6891  if (!hdr.IsValid()) {
6892  LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
6893  continue;
6894  }
6895  std::string strCommand = hdr.GetCommand();
6896 
6897  // Message size
6898  unsigned int nMessageSize = hdr.nMessageSize;
6899 
6900  // Checksum
6901  CDataStream& vRecv = msg.vRecv;
6902  uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
6903  unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
6904  if (nChecksum != hdr.nChecksum) {
6905  LogPrintf("ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
6906  SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
6907  continue;
6908  }
6909 
6910  // Process message
6911  bool fRet = false;
6912  try {
6913  fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
6914  boost::this_thread::interruption_point();
6915  } catch (const std::ios_base::failure& e) {
6916  pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message"));
6917  if (strstr(e.what(), "end of data")) {
6918  // Allow exceptions from under-length message on vRecv
6919  LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what());
6920  } else if (strstr(e.what(), "size too large")) {
6921  // Allow exceptions from over-long size
6922  LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what());
6923  } else {
6924  PrintExceptionContinue(&e, "ProcessMessages()");
6925  }
6926  } catch (const boost::thread_interrupted&) {
6927  throw;
6928  } catch (const std::exception& e) {
6929  PrintExceptionContinue(&e, "ProcessMessages()");
6930  } catch (...) {
6931  PrintExceptionContinue(NULL, "ProcessMessages()");
6932  }
6933 
6934  if (!fRet)
6935  LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize, pfrom->id);
6936 
6937  break;
6938  }
6939 
6940  // In case the connection got shut down, its receive buffer was wiped
6941  if (!pfrom->fDisconnect)
6942  pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
6943 
6944  return fOk;
6945 }
6946 
6947 
6949 {
6950  {
6951  // Don't send anything until we get their version message
6952  if (pto->nVersion == 0)
6953  return true;
6954 
6955  //
6956  // Message: ping
6957  //
6958  bool pingSend = false;
6959  if (pto->fPingQueued) {
6960  // RPC ping request by user
6961  pingSend = true;
6962  }
6963  if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
6964  // Ping automatically sent as a latency probe & keepalive.
6965  pingSend = true;
6966  }
6967  if (pingSend && !pto->fDisconnect) {
6968  uint64_t nonce = 0;
6969  while (nonce == 0) {
6970  GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
6971  }
6972  pto->fPingQueued = false;
6973  pto->nPingUsecStart = GetTimeMicros();
6974  if (pto->nVersion > BIP0031_VERSION) {
6975  pto->nPingNonceSent = nonce;
6976  pto->PushMessage(NetMsgType::PING, nonce);
6977  } else {
6978  // Peer is too old to support ping command with nonce, pong will never arrive.
6979  pto->nPingNonceSent = 0;
6981  }
6982  }
6983 
6984  TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
6985  if (!lockMain)
6986  return true;
6987 
6988  // Address refresh broadcast
6989  int64_t nNow = GetTimeMicros();
6990  if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
6991  AdvertiseLocal(pto);
6992  pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
6993  }
6994 
6995  //
6996  // Message: addr
6997  //
6998  if (pto->nNextAddrSend < nNow) {
6999  pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
7000  std::vector<CAddress> vAddr;
7001  vAddr.reserve(pto->vAddrToSend.size());
7002  for (const CAddress& addr : pto->vAddrToSend) {
7003  if (!pto->addrKnown.contains(addr.GetKey())) {
7004  pto->addrKnown.insert(addr.GetKey());
7005  vAddr.push_back(addr);
7006  // receiver rejects addr messages larger than 1000
7007  if (vAddr.size() >= 1000) {
7008  pto->PushMessage(NetMsgType::ADDR, vAddr);
7009  vAddr.clear();
7010  }
7011  }
7012  }
7013  pto->vAddrToSend.clear();
7014  if (!vAddr.empty())
7015  pto->PushMessage(NetMsgType::ADDR, vAddr);
7016  }
7017 
7018  CNodeState& state = *State(pto->GetId());
7019  if (state.fShouldBan) {
7020  if (pto->fWhitelisted)
7021  LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
7022  else {
7023  pto->fDisconnect = true;
7024  if (pto->addr.IsLocal())
7025  LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
7026  else {
7028  }
7029  }
7030  state.fShouldBan = false;
7031  }
7032 
7033  for (const CBlockReject& reject : state.rejects)
7034  pto->PushMessage(NetMsgType::REJECT, (std::string) NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
7035  state.rejects.clear();
7036 
7037  // Start block sync
7038  if (pindexBestHeader == NULL)
7040  bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient &&
7041  !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
7042  if (!state.fSyncStarted && !pto->fClient && !pto->fDisconnect && fFetch /*&& !fImporting*/ && !fReindex) {
7043  // Only actively request headers from a single peer, unless we're close to end of initial download.
7044  if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() >
7045  GetAdjustedTime() - 6 * 60 * 60) { // NOTE: was "close to today" and 24h in Bitcoin
7046  state.fSyncStarted = true;
7047  nSyncStarted++;
7048 
7050  }
7051  }
7052 
7053  // Resend wallet transactions that haven't gotten in a block yet
7054  // Except during reindex, importing and IBD, when old wallet
7055  // transactions become unconfirmed and spams other nodes.
7056  if (!fReindex && !fImporting && !IsInitialBlockDownload()) {
7058  }
7059 
7060  //
7061  // Message: inventory
7062  //
7063  std::vector<CInv> vInv;
7064  std::vector<CInv> vInvWait;
7065  {
7066  bool fSendTrickle = pto->fWhitelisted;
7067  if (pto->nNextInvSend < nNow) {
7068  fSendTrickle = true;
7069  pto->nNextInvSend = PoissonNextSend(nNow, AVG_INVENTORY_BROADCAST_INTERVAL);
7070  }
7071  LOCK(pto->cs_inventory);
7072  vInv.reserve(pto->vInventoryToSend.size());
7073  vInvWait.reserve(pto->vInventoryToSend.size());
7074  for (const CInv& inv : pto->vInventoryToSend) {
7075  if (inv.type == MSG_TX && pto->filterInventoryKnown.contains(inv.hash))
7076  continue;
7077 
7078  // trickle out tx inv to protect privacy
7079  if (inv.type == MSG_TX && !fSendTrickle) {
7080  // 1/4 of tx invs blast to all immediately
7081  static uint256 hashSalt;
7082  if (hashSalt.IsNull())
7083  hashSalt = GetRandHash();
7084  uint256 hashRand = inv.hash ^ hashSalt;
7085  hashRand = Hash(BEGIN(hashRand), END(hashRand));
7086  bool fTrickleWait = ((hashRand & 3) != 0);
7087 
7088  if (fTrickleWait) {
7089  vInvWait.push_back(inv);
7090  continue;
7091  }
7092  }
7093 
7094  pto->filterInventoryKnown.insert(inv.hash);
7095 
7096  vInv.push_back(inv);
7097  if (vInv.size() >= 1000) {
7098  pto->PushMessage(NetMsgType::INV, vInv);
7099  vInv.clear();
7100  }
7101  }
7102  pto->vInventoryToSend = vInvWait;
7103  }
7104  if (!vInv.empty())
7105  pto->PushMessage(NetMsgType::INV, vInv);
7106 
7107  // Detect whether we're stalling
7108  nNow = GetTimeMicros();
7109  if (!pto->fDisconnect && state.nStallingSince &&
7110  state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
7111  // Stalling only triggers when the block download window cannot move. During normal steady state,
7112  // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
7113  // should only happen during initial block download.
7114  LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
7115  pto->fDisconnect = true;
7116  }
7117  // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
7118  // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
7119  // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
7120  // being saturated. We only count validated in-flight blocks so peers can't advertise nonexisting block hashes
7121  // to unreasonably increase our timeout.
7122  if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
7123  LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n",
7124  state.vBlocksInFlight.front().hash.ToString(), pto->id);
7125  pto->fDisconnect = true;
7126  }
7127 
7128  //
7129  // Message: getdata (blocks)
7130  //
7131  std::vector<CInv> vGetData;
7132  if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
7133  std::vector<CBlockIndex*> vToDownload;
7134  NodeId staller = -1;
7135  FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload,
7136  staller);
7137  for (CBlockIndex* pindex : vToDownload) {
7138  vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
7139  MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
7140  LogPrintf("Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
7141  pindex->nHeight, pto->id);
7142  }
7143  if (state.nBlocksInFlight == 0 && staller != -1) {
7144  if (State(staller)->nStallingSince == 0) {
7145  State(staller)->nStallingSince = nNow;
7146  LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
7147  }
7148  }
7149  }
7150 
7151  //
7152  // Message: getdata (non-blocks)
7153  //
7154  while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) {
7155  const CInv& inv = (*pto->mapAskFor.begin()).second;
7156  if (!AlreadyHave(inv)) {
7157  LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->id);
7158  vGetData.push_back(inv);
7159  if (vGetData.size() >= 1000) {
7160  pto->PushMessage(NetMsgType::GETDATA, vGetData);
7161  vGetData.clear();
7162  }
7163  }
7164  pto->mapAskFor.erase(pto->mapAskFor.begin());
7165  }
7166  if (!vGetData.empty())
7167  pto->PushMessage(NetMsgType::GETDATA, vGetData);
7168  }
7169  return true;
7170 }
7171 
7172 
7173 bool CBlockUndo::WriteToDisk(CDiskBlockPos& pos, const uint256& hashBlock)
7174 {
7175  // Open history file to append
7176  CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
7177  if (fileout.IsNull())
7178  return error("CBlockUndo::WriteToDisk : OpenUndoFile failed");
7179 
7180  // Write index header
7181  unsigned int nSize = fileout.GetSerializeSize(*this);
7182  fileout << FLATDATA(Params().MessageStart()) << nSize;
7183 
7184  // Write undo data
7185  long fileOutPos = ftell(fileout.Get());
7186  if (fileOutPos < 0)
7187  return error("CBlockUndo::WriteToDisk : ftell failed");
7188  pos.nPos = (unsigned int)fileOutPos;
7189  fileout << *this;
7190 
7191  // calculate & write checksum
7192  CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
7193  hasher << hashBlock;
7194  hasher << *this;
7195  fileout << hasher.GetHash();
7196 
7197  return true;
7198 }
7199 
7200 bool CBlockUndo::ReadFromDisk(const CDiskBlockPos& pos, const uint256& hashBlock)
7201 {
7202  // Open history file to read
7203  CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
7204  if (filein.IsNull())
7205  return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed");
7206 
7207  // Read block
7208  uint256 hashChecksum;
7209  try {
7210  filein >> *this;
7211  filein >> hashChecksum;
7212  } catch (const std::exception& e) {
7213  return error("%s : Deserialize or I/O error - %s", __func__, e.what());
7214  }
7215 
7216  // Verify checksum
7217  CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
7218  hasher << hashBlock;
7219  hasher << *this;
7220  if (hashChecksum != hasher.GetHash())
7221  return error("CBlockUndo::ReadFromDisk : Checksum mismatch");
7222 
7223  return true;
7224 }
7225 
7226 std::string CBlockFileInfo::ToString() const
7227 {
7228  return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst,
7230 }
7231 
7232 
7234 {
7235 public:
7237 
7239  {
7240  // block headers
7241  BlockMap::iterator it1 = mapBlockIndex.begin();
7242  for (; it1 != mapBlockIndex.end(); it1++)
7243  delete (*it1).second;
7244  mapBlockIndex.clear();
7245 
7246  // orphan transactions
7247  mapOrphanTransactions.clear();
7249  }
7250 };
CTransaction::IsCoinAudit
bool IsCoinAudit() const
Definition: transaction.h:364
kernel.h
CNode::addrLocal
CService addrLocal
Definition: net.h:334
CVerifyDB::~CVerifyDB
~CVerifyDB()
Definition: main.cpp:5303
secp256k1_pedersen_commit
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commit(const secp256k1_context2 *ctx, secp256k1_pedersen_commitment *commit, const unsigned char *blind, uint64_t value, const secp256k1_generator *value_gen, const secp256k1_generator *blind_gen) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(6)
Generate a Pedersen commitment.
Definition: main_impl.h:93
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: chain.h:364
pindexBestHeader
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: main.cpp:71
CCoinsViewBacked::SetBackend
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:77
CTxIn
An input of a transaction.
Definition: transaction.h:83
NodeId
int64_t NodeId
Definition: net.h:92
secp256k1_scratch_space_struct2
Definition: scratch.h:14
mapRelay
std::map< CInv, CDataStream > mapRelay
Definition: net.cpp:87
OpenBlockFile
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
Definition: main.cpp:5150
CBlockIndex::pnext
CBlockIndex * pnext
pointer to the index of the next block
Definition: chain.h:172
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:183
BLOCK_FAILED_CHILD
@ BLOCK_FAILED_CHILD
stage after last reached validness failed
Definition: chain.h:153
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:133
mapRejectedBlocks
std::map< uint256, int64_t > mapRejectedBlocks
Definition: main.cpp:110
CNode::filterInventoryKnown
CRollingBloomFilter filterInventoryKnown
Definition: net.h:390
UINT256_ZERO
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:129
fImporting
std::atomic< bool > fImporting
Definition: main.cpp:80
CheckPrevPoABlockHash
bool CheckPrevPoABlockHash(const CBlockHeader &block)
Definition: poa.cpp:359
secp256k1_scratch_space_destroy
SECP256K1_API void secp256k1_scratch_space_destroy(secp256k1_scratch_space2 *scratch)
Destroy a secp256k1 scratch space.
Definition: secp256k1_2.c:140
CBudgetManager::mapSeenMasternodeBudgetProposals
std::map< uint256, CBudgetProposalBroadcast > mapSeenMasternodeBudgetProposals
Definition: masternode-budget.h:187
CBlockIndex::RaiseValidity
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:464
CWallet::pendingKeyImages
std::list< std::string > pendingKeyImages
Definition: wallet.h:371
CNodeStateStats::vHeightInFlight
std::vector< int > vHeightInFlight
Definition: main.h:292
CTxMemPool::AddTransactionsUpdated
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:395
merkleblock.h
CNode::cs_filter
RecursiveMutex cs_filter
Definition: net.h:355
IsBlockValueValid
bool IsBlockValueValid(int nHeight, CAmount nExpectedValue, CAmount nMinted)
Definition: masternode-payments.cpp:175
vNodes
std::vector< CNode * > vNodes
Definition: net.cpp:85
fLogIPs
bool fLogIPs
Definition: logging.cpp:30
CBlockIndex::IsProofOfStake
bool IsProofOfStake() const
Definition: chain.h:390
SendBufferSize
unsigned int SendBufferSize()
Definition: net.cpp:2243
CBufferedFile::GetPos
uint64_t GetPos()
Definition: streams.h:522
CValidationState::IsError
bool IsError() const
Definition: validation.h:70
CNode::cs_inventory
RecursiveMutex cs_inventory
Definition: net.h:392
g_best_block_mutex
Mutex g_best_block_mutex
Definition: main.cpp:75
CNodeStateStats::nCommonHeight
int nCommonHeight
Definition: main.h:291
base_uint::end
unsigned char * end()
Definition: arith_uint256.h:245
CBlockFileInfo::nTimeFirst
uint64_t nTimeFirst
highest height of block in file
Definition: chain.h:26
CNode::fWhitelisted
bool fWhitelisted
Definition: net.h:341
CBlockIndex::nFile
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:184
CBlockIndex::nMint
int64_t nMint
Definition: chain.h:222
minRelayTxFee
CFeeRate minRelayTxFee
Fees smaller than this (in duffs) are considered zero fee (for relaying and mining) We are ~100 times...
Definition: main.cpp:100
CInv::type
int type
Definition: protocol.h:383
CBlockIndex::GetAncestor
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: main.cpp:4856
MSG_TXLOCK_VOTE
@ MSG_TXLOCK_VOTE
Definition: protocol.h:394
InitBlockIndex
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
Definition: main.cpp:5425
ShutdownRequested
bool ShutdownRequested()
Definition: init.cpp:135
SendMessages
bool SendMessages(CNode *pto)
Send queued protocol messages to be sent to a give node.
Definition: main.cpp:6948
CScriptCheck::operator()
bool operator()()
Definition: main.cpp:2722
CBlockIndex::phashBlock
const uint256 * phashBlock
pointer to the hash of the block, if any. memory is owned by this CBlockIndex
Definition: chain.h:166
CCoinsViewCache::GetCacheSize
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transactions)
Definition: coins.cpp:231
GetTime
int64_t GetTime()
For unit testing.
Definition: utiltime.cpp:19
CWallet::mapWallet
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:344
fCheckBlockIndex
bool fCheckBlockIndex
Definition: main.cpp:84
SER_GETHASH
@ SER_GETHASH
Definition: serialize.h:161
ValidOutPoint
bool ValidOutPoint(const COutPoint out, int nHeight)
Definition: main.cpp:2741
ReadCompactSize
uint64_t ReadCompactSize(Stream &is)
Definition: serialize.h:273
CNode::nServices
ServiceFlags nServices
Definition: net.h:310
CBlockHeader::hashMerkleRoot
uint256 hashMerkleRoot
Definition: block.h:62
CRollingBloomFilter::insert
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:220
CNode::GetId
NodeId GetId() const
Definition: net.h:423
CBlockIndex::SetProofOfStake
void SetProofOfStake()
Definition: chain.h:395
CMasternodeSync::RequestedMasternodeAssets
int RequestedMasternodeAssets
Definition: masternode-sync.h:57
CBudgetManager::mapSeenFinalizedBudgets
std::map< uint256, CFinalizedBudgetBroadcast > mapSeenFinalizedBudgets
Definition: masternode-budget.h:190
CBlockIndex::SetStakeEntropyBit
bool SetStakeEntropyBit(unsigned int nEntropyBit)
Definition: chain.h:418
CCoinsViewCache::ModifyCoins
CCoinsModifier ModifyCoins(const uint256 &txid)
Return a modifiable reference to a CCoins.
Definition: coins.cpp:123
FLATDATA
#define FLATDATA(obj)
Definition: serialize.h:365
CBlockHeader::nBits
uint32_t nBits
Definition: block.h:65
fs.h
b
void const uint64_t * b
Definition: field_5x52_asm_impl.h:10
AddressCurrentlyConnected
void AddressCurrentlyConnected(const CService &addr)
Definition: net.cpp:291
VerifyDerivedAddress
bool VerifyDerivedAddress(const CTxOut &out, std::string stealth)
Definition: main.cpp:2549
BEGIN
#define BEGIN(a)
Utilities for converting data from/to strings.
Definition: utilstrencodings.h:17
FlushStateToDisk
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
Definition: main.cpp:3467
CBlock::IsProofOfWork
bool IsProofOfWork() const
Definition: block.h:218
StartShutdown
void StartShutdown()
Definition: init.cpp:131
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:52
BLOCK_HAVE_DATA
@ BLOCK_HAVE_DATA
Definition: chain.h:148
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:13
CTxMemPool::removeCoinbaseSpends
void removeCoinbaseSpends(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight)
Definition: txmempool.cpp:468
CNode::DisconnectOldProtocol
bool DisconnectOldProtocol(int nVersionRequired, std::string strLastCommand="")
Definition: net.cpp:430
CTxUndo
Undo information for a CTransaction.
Definition: undo.h:63
CWallet::IsMine
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1333
Checkpoints::GetTotalBlocksEstimate
int GetTotalBlocksEstimate()
Return conservative estimate of total number of blocks, 0 if unknown.
Definition: checkpoints.cpp:77
IsTransactionInChain
bool IsTransactionInChain(const uint256 &txId, int &nHeightTx, CTransaction &tx)
Context-independent validity checks.
Definition: main.cpp:4527
CBloomFilter
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:43
CDataStream::begin
const_iterator begin() const
Definition: streams.h:116
MSG_BUDGET_PROPOSAL
@ MSG_BUDGET_PROPOSAL
Definition: protocol.h:398
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:155
CNode::addrKnown
CRollingBloomFilter addrKnown
Definition: net.h:383
CBufferedFile::SetPos
bool SetPos(uint64_t nPos)
Definition: streams.h:528
CheckForkWarningConditionsOnNewFork
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
Definition: main.cpp:2612
CBlockIndex::nTx
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:197
base_uint::begin
unsigned char * begin()
Definition: arith_uint256.h:240
CNodeSignals::FinalizeNode
boost::signals2::signal< void(NodeId)> FinalizeNode
Definition: net.h:115
CBlockTreeDB::LoadBlockIndexGuts
bool LoadBlockIndexGuts()
Definition: txdb.cpp:238
ThreadScriptCheck
void ThreadScriptCheck()
Run an instance of the script checking thread.
Definition: main.cpp:2996
CAddrMan::Add
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0)
Add a single address.
Definition: addrman.h:505
DestroyContext
void DestroyContext()
Definition: main.cpp:369
CTransaction::S
std::vector< std::vector< uint256 > > S
Definition: transaction.h:301
CBlockHeader::nVersion
int32_t nVersion
Definition: block.h:59
chainActive
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:70
CNode::nPingUsecTime
int64_t nPingUsecTime
Definition: net.h:403
CBlockIndex::nMoneySupply
int64_t nMoneySupply
Definition: chain.h:223
GetInvalidUTXOValue
CAmount GetInvalidUTXOValue()
Definition: main.cpp:2748
CTxInUndo::nVersion
int nVersion
Definition: undo.h:27
BLOCK_FAILED_MASK
@ BLOCK_FAILED_MASK
descends from failed block
Definition: chain.h:154
uiInterface
CClientUIInterface uiInterface
Definition: init.cpp:101
CNetMessage::nTime
int64_t nTime
Definition: net.h:216
COutPoint::hash
uint256 hash
Definition: transaction.h:39
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:285
IsBlockPayeeValid
bool IsBlockPayeeValid(const CBlock &block, int nBlockHeight)
Definition: masternode-payments.cpp:194
CheckPoABlockRewardAmount
bool CheckPoABlockRewardAmount(const CBlock &block, const CBlockIndex *pindex)
Definition: poa.cpp:483
LoadBlockIndex
bool LoadBlockIndex(std::string &strError)
Load the block tree and coins database from disk.
Definition: main.cpp:5416
CBudgetManager::mapSeenMasternodeBudgetVotes
std::map< uint256, CBudgetVote > mapSeenMasternodeBudgetVotes
Definition: masternode-budget.h:188
CAutoFile::Get
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:351
secp256k1_pedersen_commitment_parse
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_parse(const secp256k1_context2 *ctx, secp256k1_pedersen_commitment *commit, const unsigned char *input) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Parse a 33-byte commitment into a commitment object.
Definition: main_impl.h:56
COrphanTx::fromPeer
NodeId fromPeer
Definition: main.cpp:106
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:97
CNode::AddInventoryKnown
void AddInventoryKnown(const CInv &inv)
Definition: net.h:486
CMerkleBlock
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:127
CheckHaveInputs
bool CheckHaveInputs(const CCoinsViewCache &view, const CTransaction &tx)
Find the best known block, and make it the tip of the block chain.
Definition: main.cpp:1521
CMainSignals::UpdatedTransaction
boost::signals2::signal< bool(const uint256 &)> UpdatedTransaction
Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becomi...
Definition: validationinterface.h:59
CTransactionSignature
Definition: transaction.h:436
mapArgs
std::map< std::string, std::string > mapArgs
Definition: util.cpp:111
CPubKey::Set
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Definition: pubkey.h:71
NetMsgType::FINALBUDGET
const char * FINALBUDGET
The finalbudget message is used to broadcast or relay finalized budget metadata to connected peers.
Definition: protocol.cpp:57
CTxMemPool::exists
bool exists(uint256 hash)
Definition: txmempool.h:179
CMasternodeSync::IsBlockchainSynced
bool IsBlockchainSynced()
Definition: masternode-sync.cpp:32
CBlockIndex::pprev
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:169
CKey::Set
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:83
ScriptErrorString
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
CCoins::IsAvailable
bool IsAvailable(unsigned int nPos) const
check whether a particular output is still available
Definition: coins.h:275
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:181
CDiskBlockPos::nFile
int nFile
Definition: chain.h:77
CNode
Information about a peer.
Definition: net.h:306
BLOCK_VALID_TREE
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:127
CBlockIndex::GetStakeEntropyBit
unsigned int GetStakeEntropyBit() const
Definition: chain.h:409
NetMsgType::PING
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:39
fListPopulatedAfterLock
bool fListPopulatedAfterLock
Definition: main.cpp:2739
CMainCleanup::CMainCleanup
CMainCleanup()
Definition: main.cpp:7236
validationinterface.h
FileCommit
void FileCommit(FILE *fileout)
Definition: util.cpp:477
CScriptCheck::ptxTo
const CTransaction * ptxTo
Definition: main.h:355
NetMsgType::FILTERLOAD
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:43
CMasternodeSync::AddedMasternodeList
void AddedMasternodeList(uint256 hash)
Definition: masternode-sync.cpp:89
CNode::addr
CAddress addr
Definition: net.h:332
tinyformat::printf
void printf(const char *fmt, const Args &... args)
Format list of arguments to std::cout, according to the given format string.
Definition: tinyformat.h:975
CheckInputs
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector< CScriptCheck > *pvChecks)
Check whether all inputs of this transaction are valid (no double spends, scripts & sigs,...
Definition: main.cpp:2766
NetMsgType::IX
const char * IX
The ix message transmits a single SwiftX transaction.
Definition: protocol.cpp:48
flags
int flags
Definition: prcycoin-tx.cpp:297
MSG_BLOCK
@ MSG_BLOCK
Definition: protocol.h:389
VerifyRingSignatureWithTxFee
bool VerifyRingSignatureWithTxFee(const CTransaction &tx, CBlockIndex *pindex)
Definition: main.cpp:393
CWallet::inSpendQueueOutpoints
std::map< COutPoint, bool > inSpendQueueOutpoints
Definition: wallet.h:372
CBlockHeader::IsPoABlockByVersion
bool IsPoABlockByVersion() const
Definition: block.h:105
secp256k1_scratch_space_create
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT secp256k1_scratch_space2 * secp256k1_scratch_space_create(const secp256k1_context2 *ctx, size_t max_size) SECP256K1_ARG_NONNULL(1)
Create a secp256k1 scratch space object.
Definition: secp256k1_2.c:135
masternode-sync.h
SeenLocal
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:262
CMasternodePayments::ProcessBlock
bool ProcessBlock(int nBlockHeight)
Definition: masternode-payments.cpp:615
CMasternodePayments::mapMasternodePayeeVotes
std::map< uint256, CMasternodePaymentWinner > mapMasternodePayeeVotes
Definition: masternode-payments.h:238
invalid_out::ContainsOutPoint
bool ContainsOutPoint(const COutPoint &out)
Definition: invalid.cpp:54
CMainSignals::UpdatedBlockTip
boost::signals2::signal< void(const CBlockIndex *)> UpdatedBlockTip
Notifies listeners of updated block chain tip.
Definition: validationinterface.h:53
CNode::PushInventory
void PushInventory(const CInv &inv)
Definition: net.h:494
FindForkInGlobalIndex
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: main.cpp:1115
BCLog::BENCH
@ BENCH
Definition: logging.h:44
strMiscWarning
std::string strMiscWarning
Definition: util.cpp:115
CCoins::FromTx
void FromTx(const CTransaction &tx, int nHeightIn)
Definition: coins.h:94
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:209
CMasternodeMan::size
int size()
Return the number of (unique) Masternodes.
Definition: masternodeman.h:148
CNode::fSuccessfullyConnected
bool fSuccessfullyConnected
Definition: net.h:347
CTxOut::IsDust
bool IsDust(CFeeRate minRelayTxFee) const
Definition: transaction.h:227
CBlockUndo::ReadFromDisk
bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
Definition: main.cpp:7200
BaseSignatureChecker
Definition: interpreter.h:88
UpdateCoins
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
Definition: main.cpp:2706
fLargeWorkInvalidChainFound
bool fLargeWorkInvalidChainFound
Definition: main.cpp:2517
CNodeStateStats::nSyncHeight
int nSyncHeight
Definition: main.h:290
CBlockIndex::nChainWork
uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:193
CNode::vInventoryToSend
std::vector< CInv > vInventoryToSend
Definition: net.h:391
CNode::nNextLocalAddrSend
int64_t nNextLocalAddrSend
Definition: net.h:387
AnnotatedMixin< std::recursive_mutex >
mapOrphanTransactionsByPrev
std::map< uint256, std::set< uint256 > > mapOrphanTransactionsByPrev
Definition: main.cpp:109
memcpy
void * memcpy(void *a, const void *b, size_t c)
Definition: glibc_compat.cpp:15
CNodeStateStats::nMisbehavior
int nMisbehavior
Definition: main.h:289
CDiskTxPos
Definition: txdb.h:29
CAddress::nTime
unsigned int nTime
Definition: protocol.h:354
expect
#define expect(bit)
Definition: univalue_read.cpp:249
CValidationState::Invalid
bool Invalid(bool ret=false, unsigned char _chRejectCode=0, std::string _strRejectReason="")
Definition: validation.h:49
CDiskTxPos::nTxOffset
unsigned int nTxOffset
Definition: txdb.h:30
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:296
CChainParams::BIP65ActivationHeight
int BIP65ActivationHeight() const
Definition: chainparams.h:118
CNode::hashContinue
uint256 hashContinue
Definition: net.h:378
SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
Definition: interpreter.h:83
CClientUIInterface::NotifyBlockSize
boost::signals2::signal< void(int size, const uint256 &hash)> NotifyBlockSize
New block has been accepted and is over a certain size.
Definition: guiinterface.h:107
CMessageHeader::GetCommand
std::string GetCommand() const
Definition: protocol.cpp:155
CAddress::nServices
ServiceFlags nServices
Definition: protocol.h:351
CBlockIndex::nChainTx
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:202
cs_vNodes
RecursiveMutex cs_vNodes
Definition: net.cpp:86
GetSerializeSize
unsigned int GetSerializeSize(char a, int, int=0)
Definition: serialize.h:194
CBlockIndex::nDataPos
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:187
CCoins::nHeight
int nHeight
at which height this transaction was included in the active block chain
Definition: coins.h:88
mapTxLockReq
std::map< uint256, CTransaction > mapTxLockReq
Definition: swifttx.cpp:24
SCRIPT_ERR_EVAL_FALSE
@ SCRIPT_ERR_EVAL_FALSE
Definition: script_error.h:13
CNode::nTimeOffset
int64_t nTimeOffset
Definition: net.h:331
TRY_LOCK
#define TRY_LOCK(cs, name)
Definition: sync.h:186
TruncateFile
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:494
CNode::Ban
static void Ban(const CNetAddr &ip, const BanReason &banReason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
Definition: net.cpp:522
ReconsiderBlock
bool ReconsiderBlock(CValidationState &state, CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
Definition: main.cpp:4008
MIN_TX_INPUTS_FOR_SWEEPING
const int MIN_TX_INPUTS_FOR_SWEEPING
Definition: main.cpp:94
CTxInUndo::txout
CTxOut txout
Definition: undo.h:23
Checkpoints::GetLastCheckpoint
CBlockIndex * GetLastCheckpoint()
Returns last CBlockIndex* in mapBlockIndex that is a checkpoint.
Definition: checkpoints.cpp:87
CDiskBlockIndex
Used to marshal pointers into hashes for db storage.
Definition: chain.h:485
CBlockIndex::nStatus
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:205
FlushStateMode
FlushStateMode
Definition: main.cpp:3372
DateTimeStrFormat
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:50
InvalidateBlock
bool InvalidateBlock(CValidationState &state, CBlockIndex *pindex)
Mark a block as invalid.
Definition: main.cpp:3972
CTransaction::GetValueOut
CAmount GetValueOut() const
Definition: transaction.cpp:155
GetLegacySigOpCount
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
Definition: tx_verify.cpp:30
NODE_NETWORK
@ NODE_NETWORK
Definition: protocol.h:302
CBlockIndex::pskip
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:175
secp256k1_context_destroy
SECP256K1_API void secp256k1_context_destroy(secp256k1_context2 *ctx)
Destroy a secp256k1 context object.
Definition: secp256k1_2.c:110
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: utilstrencodings.cpp:32
CInv
inv message data
Definition: protocol.h:358
CTxInUndo::nHeight
unsigned int nHeight
Definition: undo.h:26
chainparams.h
guiinterface.h
MAX_TX_INPUTS
const int MAX_TX_INPUTS
Definition: main.cpp:93
CValidationState::GetRejectReason
std::string GetRejectReason() const
Definition: validation.h:87
BLOCK_FAILED_VALID
@ BLOCK_FAILED_VALID
Definition: chain.h:152
NetMsgType::PONG
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition: protocol.cpp:40
GetContext
secp256k1_context2 * GetContext()
Definition: main.cpp:348
FormatMoney
std::string FormatMoney(const CAmount &n, bool fPlus)
Money parsing/formatting utilities.
Definition: utilmoneystr.cpp:13
CBufferedFile::FindByte
void FindByte(char ch)
Definition: streams.h:574
MSG_MASTERNODE_ANNOUNCE
@ MSG_MASTERNODE_ANNOUNCE
Definition: protocol.h:402
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:159
IsFinalTx
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:12
GetSeeSaw
CAmount GetSeeSaw(const CAmount &blockValue, int nMasternodeCount, int nHeight)
Definition: main.cpp:2187
masternodeman.h
CWallet::keyImagesSpends
std::map< std::string, bool > keyImagesSpends
Definition: wallet.h:369
GetNextWorkRequired
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, bool fProofOfStake)
MSG_TX
@ MSG_TX
Definition: protocol.h:388
CVerifyDB::CVerifyDB
CVerifyDB()
Definition: main.cpp:5298
nSwiftTXDepth
int nSwiftTXDepth
Definition: util.cpp:103
CTxMemPool::check
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.cpp:540
GetTxSignatureHash
uint256 GetTxSignatureHash(const CTransaction &tx)
Definition: main.cpp:681
CNode::vBlockRequested
std::vector< uint256 > vBlockRequested
Definition: net.h:394
CBlockUndo::vtxundo
std::vector< CTxUndo > vtxundo
Definition: undo.h:82
BLOCK_VALID_MASK
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:144
CNode::fDisconnect
std::atomic_bool fDisconnect
Definition: net.h:348
CBlockTreeDB::ReadReindexing
bool ReadReindexing(bool &fReindex)
Definition: txdb.cpp:100
CBloomFilter::UpdateEmptyFull
void UpdateEmptyFull()
Checks for empty and full filters to avoid wasting cpu.
Definition: bloom.cpp:195
DisconnectBlocks
bool DisconnectBlocks(int nBlocks)
Reprocess a number of blocks to try and get on the correct chain again.
Definition: main.cpp:3647
CNode::ssSend
CDataStream ssSend
Definition: net.h:313
mapProofOfStake
std::map< uint256, uint256 > mapProofOfStake
Definition: main.cpp:68
CFeeRate
Fee rate in PRCY per kilobyte: CAmount / kB.
Definition: amount.h:39
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:80
CheckPoABlockNotContainingPoABlockInfo
bool CheckPoABlockNotContainingPoABlockInfo(const CBlock &block, const CBlockIndex *pindex)
Definition: poa.cpp:400
NetMsgType::MNWINNER
const char * MNWINNER
The mnwinner message is used to relay and distribute consensus for masternode payout ordering.
Definition: protocol.cpp:52
validation.h
CWallet::coinbaseDecoysPool
std::map< COutPoint, uint256 > coinbaseDecoysPool
Definition: wallet.h:377
CRollingBloomFilter::contains
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:240
PrintExceptionContinue
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: util.cpp:309
CNode::PushVersion
void PushVersion()
Definition: net.cpp:461
CNode::PushMessage
void PushMessage(const char *pszCommand)
Definition: net.h:518
nCoinCacheUsage
size_t nCoinCacheUsage
Definition: main.cpp:86
CChain::FindFork
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:54
CPubKey::GetHex
std::string GetHex() const
Definition: pubkey.h:193
cs_mapRelay
RecursiveMutex cs_mapRelay
Definition: net.cpp:89
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:269
fIsBareMultisigStd
bool fIsBareMultisigStd
Definition: main.cpp:83
CDiskBlockPos::IsNull
bool IsNull() const
Definition: chain.h:115
atoi
int atoi(const std::string &str)
Definition: utilstrencodings.cpp:587
AreInputsStandard
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: main.cpp:1309
ComputeNextStakeModifier
bool ComputeNextStakeModifier(const CBlockIndex *pindexPrev, uint64_t &nStakeModifier, bool &fGeneratedStakeModifier)
Definition: kernel.cpp:150
MaskValue::mask
uint256 mask
Definition: transaction.h:151
CValidationState::IsInvalid
bool IsInvalid() const
Definition: validation.h:66
GetMainSignals
CMainSignals & GetMainSignals()
Definition: validationinterface.cpp:10
CNode::nVersion
int nVersion
Definition: net.h:335
CScriptCheck::nIn
unsigned int nIn
Definition: main.h:356
txmempool.h
CNode::fRelayTxes
bool fRelayTxes
Definition: net.h:353
CMainSignals::Broadcast
boost::signals2::signal< void()> Broadcast
Tells listeners to broadcast their data.
Definition: validationinterface.h:66
AcceptableInputs
bool AcceptableInputs(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee, bool isDSTX)
Definition: main.cpp:1803
CTxInShortDigest
Definition: transaction.h:489
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:346
masternodeSync
CMasternodeSync masternodeSync
Definition: masternode-sync.cpp:19
prefix
const char * prefix
Definition: rest.cpp:588
r
void const uint64_t uint64_t * r
Definition: field_5x52_asm_impl.h:10
AcceptToMemoryPool
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee, bool ignoreFees)
(try to) add transaction to memory pool
Definition: main.cpp:1579
nScriptCheckThreads
int nScriptCheckThreads
Definition: main.cpp:79
GetStakeModifierChecksum
unsigned int GetStakeModifierChecksum(const CBlockIndex *pindex)
Definition: kernel.cpp:419
g_best_block
uint256 g_best_block
Definition: main.cpp:77
CTxInShortDigest::GetHash
uint256 GetHash()
Definition: transaction.h:522
CAddrMan::GetAddr
std::vector< CAddress > GetAddr()
Return a bunch of addresses, selected at random.
Definition: addrman.h:566
CTxOut::nValue
CAmount nValue
Definition: transaction.h:167
CScript::IsPushOnly
bool IsPushOnly(const_iterator pc) const
Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical).
Definition: script.cpp:244
ActivateBestChain
bool ActivateBestChain(CValidationState &state, CBlock *pblock, bool fAlreadyChecked)
Make the best chain active, in multiple steps.
Definition: main.cpp:3892
CAutoFile
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:303
CBlockHeader::CURRENT_VERSION
static const int32_t CURRENT_VERSION
Definition: block.h:56
CCheckQueueControl::Add
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:200
GetLocalAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
Definition: net.cpp:164
GetRand
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:351
CPubKey::begin
const unsigned char * begin() const
Definition: pubkey.h:95
VerifyZeroBlindCommitment
bool VerifyZeroBlindCommitment(const CTxOut &out)
Definition: main.cpp:2540
cs_main
RecursiveMutex cs_main
Global state.
Definition: main.cpp:65
CKey::begin
const unsigned char * begin() const
Definition: key.h:100
TX_MULTISIG
@ TX_MULTISIG
Definition: standard.h:64
CBlockIndex::GetBlockHeader
CBlockHeader GetBlockHeader() const
Definition: chain.h:340
BLOCK_VALID_TRANSACTIONS
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:134
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:359
pblocktree
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: main.cpp:1131
fLargeWorkForkFound
bool fLargeWorkForkFound
Definition: main.cpp:2516
ActiveProtocol
int ActiveProtocol()
See whether the protocol update is enforced for connected nodes.
Definition: main.cpp:6844
CWallet::ComputeStealthDestination
static bool ComputeStealthDestination(const CKey &secret, const CPubKey &pubViewKey, const CPubKey &pubSpendKey, CPubKey &des)
Definition: wallet.cpp:6618
CheckForkWarningConditions
void CheckForkWarningConditions()
Definition: main.cpp:2570
CNode::nPingUsecStart
int64_t nPingUsecStart
Definition: net.h:401
CCoins::vout
std::vector< CTxOut > vout
unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are d...
Definition: coins.h:85
CValidationState::CorruptionPossible
bool CorruptionPossible() const
Definition: validation.h:82
CBlock::fChecked
bool fChecked
Definition: block.h:156
CBlockFileInfo::nTimeLast
uint64_t nTimeLast
earliest time of block in file
Definition: chain.h:27
CNode::fNetworkNode
bool fNetworkNode
Definition: net.h:346
fDeleteInterval
int fDeleteInterval
Definition: wallet.cpp:62
CScriptCheck::swap
void swap(CScriptCheck &check)
Definition: main.h:368
COrphanTx
Definition: main.cpp:104
mnodeman
CMasternodeMan mnodeman
Masternode manager.
Definition: masternodeman.cpp:22
CWallet::MAX_DECOY_POOL
static const int32_t MAX_DECOY_POOL
Definition: wallet.h:276
CNode::pfilter
CBloomFilter * pfilter
Definition: net.h:356
CInv::GetCommand
const char * GetCommand() const
Definition: protocol.cpp:244
CheckTransaction
bool CheckTransaction(const CTransaction &tx, bool fRejectBadUTXO, CValidationState &state)
Transaction validation functions.
Definition: tx_verify.cpp:42
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:568
CheckWork
bool CheckWork(const CBlock block, CBlockIndex *const pindexPrev)
Definition: main.cpp:4437
AddToBlockIndex
CBlockIndex * AddToBlockIndex(const CBlock &block)
Definition: main.cpp:4043
CMainCleanup
Definition: main.cpp:7233
SWIFTTX_SIGNATURES_REQUIRED
#define SWIFTTX_SIGNATURES_REQUIRED
Definition: swifttx.h:26
IsInitialBlockDownload
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
Definition: main.cpp:2500
CBlockIndex::IsSuperMajority
static bool IsSuperMajority(int minVersion, const CBlockIndex *pstart, unsigned int nRequired)
Returns true if there are nRequired or more blocks of minVersion or above in the last Params()....
Definition: main.cpp:4829
checkqueue.h
CBlockTreeDB::WriteBlockIndex
bool WriteBlockIndex(const CDiskBlockIndex &blockindex)
Definition: txdb.cpp:81
MAX_RING_SIZE
int MAX_RING_SIZE
Definition: main.cpp:92
NetMsgType::INV
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:20
ReVerifyPoSBlock
bool ReVerifyPoSBlock(CBlockIndex *pindex)
Definition: main.cpp:621
CTxMemPool::cs
RecursiveMutex cs
sum of all mempool tx' byte sizes
Definition: txmempool.h:135
CNode::fInbound
bool fInbound
Definition: net.h:345
NetMsgType::GETHEADERS
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:24
CChainParams::COINBASE_MATURITY
int COINBASE_MATURITY() const
Definition: chainparams.h:85
GetTransaction
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock.
Definition: main.cpp:2010
IsPeerAddrLocalGood
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:182
CWallet::resetPendingOutPoints
void resetPendingOutPoints()
Definition: wallet.cpp:2998
CMessageHeader::nChecksum
unsigned int nChecksum
Definition: protocol.h:63
CNode::fFeeler
bool fFeeler
Definition: net.h:342
CachingTransactionSignatureChecker
Definition: sigcache.h:43
AssertLockNotHeld
#define AssertLockNotHeld(cs)
Definition: sync.h:72
CTransactionSignature::GetHash
uint256 GetHash()
Definition: transaction.h:484
UnloadBlockIndex
void UnloadBlockIndex()
Unload database information.
Definition: main.cpp:5386
RegisterNodeSignals
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
Definition: main.cpp:1097
CBufferedFile
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from.
Definition: streams.h:433
CNode::vRecvGetData
std::deque< CInv > vRecvGetData
Definition: net.h:322
CBlockFileInfo::nBlocks
unsigned int nBlocks
Definition: chain.h:21
CScriptCheck::GetScriptError
ScriptError GetScriptError() const
Definition: main.h:378
CTxOut
An output of a transaction.
Definition: transaction.h:164
_
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
Definition: guiinterface.h:119
CCheckQueue
Queue for verifications that have to be performed.
Definition: checkqueue.h:29
GetRandBytes
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:273
tx_verify.h
GetWarnings
std::string GetWarnings(std::string strFor)
Format a string that describes several potential problems detected by the core.
Definition: main.cpp:5739
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:135
secp256k1_bulletproof_generators_create_with_pregenerated
SECP256K1_API secp256k1_bulletproof_generators * secp256k1_bulletproof_generators_create_with_pregenerated(const secp256k1_context2 *ctx) SECP256K1_ARG_NONNULL(1)
Definition: main_impl.h:72
IsReachable
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
Definition: net.cpp:280
CBloomFilter::insert
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:58
CheckPoABlockPaddingAmount
bool CheckPoABlockPaddingAmount(const CBlock &block, const CBlockIndex *pindex)
Definition: poa.cpp:500
CBlockTreeDB::WriteBatchSync
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo * > > &fileInfo, int nLastFile, const std::vector< const CBlockIndex * > &blockinfo)
Definition: txdb.cpp:156
CTxMemPool::removeForBlock
void removeForBlock(const std::vector< CTransaction > &vtx, unsigned int nBlockHeight, std::list< CTransaction > &conflicts)
Called when a block is connected.
Definition: txmempool.cpp:512
CNetMessage::complete
bool complete() const
Definition: net.h:227
CCoinsViewCache::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:90
CBlockIndex::GetMedianTimePast
int64_t GetMedianTimePast() const
Definition: chain.h:371
OpenDiskFile
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
Definition: main.cpp:5127
init.h
CTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:286
CTxMemPool::PrioritiseTransaction
void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:675
NetMsgType::IXLOCKVOTE
const char * IXLOCKVOTE
The ixlockvote message is used to reach consensus for SwiftX transaction locks.
Definition: protocol.cpp:49
CBufferedFile::eof
bool eof() const
Definition: streams.h:492
ExtractPubKey
bool ExtractPubKey(const CScript &scriptPubKey, CPubKey &out)
Definition: standard.cpp:185
BCLog::SUPPLY
@ SUPPLY
Definition: logging.h:66
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:168
CClientUIInterface::ThreadSafeMessageBox
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: guiinterface.h:80
CTxMemPool::remove
void remove(const CTransaction &tx, std::list< CTransaction > &removed, bool fRecursive=false)
Definition: txmempool.cpp:424
VerifyShnorrKeyImageTx
bool VerifyShnorrKeyImageTx(const CTransaction &tx)
Definition: main.cpp:1454
CBlockFileInfo::nHeightFirst
unsigned int nHeightFirst
number of used bytes in the undo file
Definition: chain.h:24
ISMINE_ALL
@ ISMINE_ALL
Definition: wallet_ismine.h:21
CNetAddr::IsRoutable
bool IsRoutable() const
Definition: netaddress.cpp:224
IsStandard
bool IsStandard(const CScript &scriptPubKey, txnouttype &whichType)
Definition: standard.cpp:165
CNode::fGetAddr
bool fGetAddr
Definition: net.h:384
RecalculatePRCYSupply
bool RecalculatePRCYSupply(int nHeightStart)
Definition: main.cpp:3002
GetBlockHash
bool GetBlockHash(uint256 &hash, int nBlockHeight)
Definition: masternode.cpp:26
CNetAddr::GetHash
uint64_t GetHash() const
Definition: netaddress.cpp:368
fLiteMode
bool fLiteMode
Definition: util.cpp:100
CTxOut::txPriv
std::vector< unsigned char > txPriv
Definition: transaction.h:172
CChainParams::MinimumStakeAmount
CAmount MinimumStakeAmount() const
Definition: chainparams.h:87
CBlockTreeDB::ReadBlockFileInfo
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
Definition: txdb.cpp:87
CheckPoAMerkleRoot
bool CheckPoAMerkleRoot(const CBlock &block, bool *fMutate)
Definition: poa.cpp:390
NetMsgType::HEADERS
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:35
g_best_block_cv
std::condition_variable g_best_block_cv
Definition: main.cpp:76
CBlockIndex::IsValid
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:454
util::ThreadRename
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:57
TX_SCRIPTHASH
@ TX_SCRIPTHASH
Definition: standard.h:63
CWallet::userDecoysPool
std::map< COutPoint, uint256 > userDecoysPool
Definition: wallet.h:376
ScriptSigArgsExpected
int ScriptSigArgsExpected(txnouttype t, const std::vector< std::vector< unsigned char >> &vSolutions)
Definition: standard.cpp:147
CMainSignals::Inventory
boost::signals2::signal< void(const uint256 &)> Inventory
Notifies listeners about an inventory item being seen on the network.
Definition: validationinterface.h:63
CCoins::ClearUnspendable
void ClearUnspendable()
Definition: coins.h:131
HexStr
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: utilstrencodings.h:85
CTransaction::ntxFeeKeyImage
CKeyImage ntxFeeKeyImage
Definition: transaction.h:304
GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:255
PAIRTYPE
#define PAIRTYPE(t1, t2)
This is needed because the foreach macro can't get over the comma in pair<t1, t2>
Definition: utilstrencodings.h:24
SyncWithWallets
void SyncWithWallets(const CTransaction &tx, const CBlock *pblock=NULL)
Push an updated transaction to all registered wallets.
Definition: validationinterface.cpp:54
secp256k1_bulletproof_rangeproof_verify
SECP256K1_WARN_UNUSED_RESULT SECP256K1_API int secp256k1_bulletproof_rangeproof_verify(const secp256k1_context2 *ctx, secp256k1_scratch_space2 *scratch, const secp256k1_bulletproof_generators *gens, const unsigned char *proof, size_t plen, const uint64_t *min_value, const secp256k1_pedersen_commitment *commit, size_t n_commits, size_t nbits, const secp256k1_generator *value_gen, const unsigned char *extra_commit, size_t extra_commit_len) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(7) SECP256K1_ARG_NONNULL(10)
Verifies a single bulletproof (aggregate) rangeproof Returns: 1: rangeproof was valid 0: rangeproof w...
Definition: main_impl.h:477
secp256k1_ec_pubkey_tweak_mul
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3)
Tweak a public key by multiplying it with tweak.
Definition: secp256k1.c:281
CBlockTreeDB
Access to the block database (blocks/index/)
Definition: txdb.h:74
CDiskBlockPos
Definition: chain.h:76
CScriptCheck::scriptPubKey
CScript scriptPubKey
Definition: main.h:354
CValidationState::GetRejectCode
unsigned char GetRejectCode() const
Definition: validation.h:86
WriteBlockToDisk
bool WriteBlockToDisk(CBlock &block, CDiskBlockPos &pos)
Functions for disk access for blocks.
Definition: main.cpp:2080
CCoinsModifier
A reference to a mutable cache entry.
Definition: coins.h:398
CWallet::outpointToKeyImages
std::map< std::string, CKeyImage > outpointToKeyImages
Definition: wallet.h:368
NODE_BLOOM
@ NODE_BLOOM
Definition: protocol.h:307
LogPrintf
#define LogPrintf(...)
Definition: logging.h:147
CAmount
int64_t CAmount
Amount in PRCY (Can be negative)
Definition: amount.h:17
MSG_TXLOCK_REQUEST
@ MSG_TXLOCK_REQUEST
Definition: protocol.h:393
CTxIn::R
std::vector< unsigned char > R
Definition: transaction.h:91
blocksignature.h
CNode::DisconnectOldVersion
bool DisconnectOldVersion(std::string strSubVer, int nHeight, std::string strLastCommand="")
Definition: net.cpp:442
pcoinsTip
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:1130
NetMsgType::FINALBUDGETVOTE
const char * FINALBUDGETVOTE
The finalbudgetvote message is used to broadcast or relay finalized budget votes to connected peers.
Definition: protocol.cpp:58
CheckKeyImageSpendInMainChain
bool CheckKeyImageSpendInMainChain(const std::string &kiHex, int &confirmations)
Definition: main.cpp:320
CTransaction::nTxFee
CAmount nTxFee
Definition: transaction.h:298
GetRandHash
uint256 GetRandHash()
Definition: random.cpp:371
CClientUIInterface::NotifyAlertChanged
boost::signals2::signal< void()> NotifyAlertChanged
New, updated or cancelled alert.
Definition: guiinterface.h:95
masternodePayments
CMasternodePayments masternodePayments
Object for who's going to get paid on which blocks.
Definition: masternode-payments.cpp:19
CMasternodeSync::AddedMasternodeWinner
void AddedMasternodeWinner(uint256 hash)
Definition: masternode-sync.cpp:102
FindUndoPos
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
Definition: main.cpp:4208
PointHashingSuccessively
bool PointHashingSuccessively(const CPubKey &pk, const unsigned char *tweak, unsigned char *out)
Definition: util.cpp:619
mempool
CTxMemPool mempool(::minRelayTxFee)
BCLog::REINDEX
@ REINDEX
Definition: logging.h:51
GetInputAge
int GetInputAge(CTxIn &vin)
Definition: main.cpp:1373
EraseOrphansFor
void EraseOrphansFor(NodeId peer)
Definition: main.cpp:1183
CheckStakeModifierCheckpoints
bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
Definition: kernel.cpp:433
COINBASE_FLAGS
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: main.cpp:117
SER_DISK
@ SER_DISK
Definition: serialize.h:160
CMasternodeMan::mapSeenMasternodeBroadcast
std::map< uint256, CMasternodeBroadcast > mapSeenMasternodeBroadcast
Definition: masternodeman.h:76
GetSizeOfCompactSize
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:242
CNode::vRecvMsg
std::deque< CNetMessage > vRecvMsg
Definition: net.h:323
IsStandardTx
bool IsStandardTx(const CTransaction &tx, std::string &reason)
Check for standard transaction types.
Definition: main.cpp:1213
CAutoFile::IsNull
bool IsNull() const
Return true if the wrapped FILE* is NULL, false otherwise.
Definition: streams.h:355
pindexBestForkBase
CBlockIndex * pindexBestForkBase
Definition: main.cpp:2518
CMainSignals::SetBestChain
boost::signals2::signal< void(const CBlockLocator &)> SetBestChain
Notifies listeners of a new active block chain.
Definition: validationinterface.h:61
AssertLockHeld
#define AssertLockHeld(cs)
Definition: sync.h:71
NetMsgType::FILTERCLEAR
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:45
mapHashedBlocks
std::map< unsigned int, unsigned int > mapHashedBlocks
Definition: main.cpp:69
CheckPoABlockMinedHash
bool CheckPoABlockMinedHash(const CBlockHeader &block)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: poa.cpp:331
CTxOut::masternodeStealthAddress
std::vector< unsigned char > masternodeStealthAddress
Definition: transaction.h:177
CheckBlock
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig)
Definition: main.cpp:4263
masternode-payments.h
GetMasternodePayment
int64_t GetMasternodePayment(int nHeight, int64_t blockValue, int nMasternodeCount)
Definition: main.cpp:2454
CTxMemPool::lookup
bool lookup(uint256 hash, CTransaction &result) const
Definition: txmempool.cpp:624
ProcessMessageSwiftTX
void ProcessMessageSwiftTX(CNode *pfrom, std::string &strCommand, CDataStream &vRecv)
Definition: swifttx.cpp:39
CChainParams::GenesisBlock
const CBlock & GenesisBlock() const
Definition: chainparams.h:68
uint256
256-bit unsigned big integer.
Definition: uint256.h:38
CheckFinalTx
bool CheckFinalTx(const CTransaction &tx, int flags)
Check if transaction will be final in the next block to be created.
Definition: main.cpp:1465
uint256::GetHash
uint64_t GetHash(const uint256 &salt) const
Definition: uint256.cpp:99
GetScratch
secp256k1_scratch_space2 * GetScratch()
Definition: main.cpp:355
CScriptCheck::error
ScriptError error
Definition: main.h:359
CBlockTreeDB::ReadFlag
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:219
CBlockIndex::nVersion
int nVersion
block header
Definition: chain.h:226
CWallet::CreateCommitment
static bool CreateCommitment(const CAmount val, CKey &blind, std::vector< unsigned char > &commitment)
Definition: wallet.cpp:3096
CKey::GetPubKey
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:79
CBlockFileInfo::nHeightLast
unsigned int nHeightLast
lowest height of block in file
Definition: chain.h:25
TX_NULL_DATA
@ TX_NULL_DATA
Definition: standard.h:65
CNode::AskFor
void AskFor(const CInv &inv, bool fImmediateRetry=false)
Definition: net.cpp:2316
LogPrint
#define LogPrint(category,...)
Definition: logging.h:162
MaskValue::amount
uint256 amount
Definition: transaction.h:150
NetMsgType::REJECT
const char * REJECT
The reject message informs the receiving node that one of its previous messages has been rejected.
Definition: protocol.cpp:46
CCheckQueueControl
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:16
CMasternodeSync::AddedBudgetItem
void AddedBudgetItem(uint256 hash)
Definition: masternode-sync.cpp:115
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:363
CWallet::DeleteWalletTransactions
bool DeleteWalletTransactions(const CBlockIndex *pindex, bool fRescan=false)
Definition: wallet.cpp:1909
CheckProofOfStake
bool CheckProofOfStake(const CBlock block, uint256 &hashProofOfStake, std::unique_ptr< CStakeInput > &stake, int nPreviousBlockHeight)
Definition: kernel.cpp:351
base_uint::IsNull
bool IsNull() const
Definition: arith_uint256.h:312
AdvertiseLocal
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:188
CMainSignals::BlockChecked
boost::signals2::signal< void(const CBlock &, const CValidationState &)> BlockChecked
Notifies listeners of a block validation result.
Definition: validationinterface.h:68
addrman
CAddrMan addrman
Definition: net.cpp:80
CBlockIndex::nStakeModifierChecksum
unsigned int nStakeModifierChecksum
Definition: chain.h:218
CBaseChainParams::TESTNET
@ TESTNET
Definition: chainparamsbase.h:20
CBlockLocator::IsNull
bool IsNull()
Definition: block.h:274
CInv::IsKnownType
bool IsKnownType() const
Definition: protocol.cpp:235
CheckProofOfWork
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: poa.cpp:145
BLOCK_VALID_SCRIPTS
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:141
MESSAGE_START_SIZE
#define MESSAGE_START_SIZE
Definition: protocol.h:21
CChain::SetTip
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:12
AddTimeData
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
Definition: timedata.cpp:40
mapTxLockVote
std::map< uint256, CConsensusVote > mapTxLockVote
Definition: swifttx.cpp:26
NetMsgType::GETBLOCKS
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:23
secp256k1_pedersen_commitment_to_serialized_pubkey
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_to_serialized_pubkey(secp256k1_pedersen_commitment *commit, unsigned char *pubkey, size_t *length) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Definition: main_impl.h:44
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:359
CNode::PushAddress
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:471
CWallet::GetDebit
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Definition: wallet.cpp:1402
MSG_MASTERNODE_PING
@ MSG_MASTERNODE_PING
Definition: protocol.h:403
mapLockedInputs
std::map< COutPoint, uint256 > mapLockedInputs
Definition: swifttx.cpp:28
CNodeSignals::SendMessages
boost::signals2::signal< bool(CNode *), CombinerAll > SendMessages
Definition: net.h:113
CMasternodeMan::ProcessMessage
void ProcessMessage(CNode *pfrom, std::string &strCommand, CDataStream &vRecv)
Definition: masternodeman.cpp:672
EvalScript
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
Definition: interpreter.cpp:241
GetPriority
double GetPriority(const CTransaction &tx, int nHeight)
Return priority of tx at height nHeight.
Definition: main.cpp:259
NetMsgType::GETDATA
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:21
ConnectBlock
bool ConnectBlock(const CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck, bool fAlreadyChecked)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
Definition: main.cpp:3085
CCoinsViewCache::AccessCoins
const CCoins * AccessCoins(const uint256 &txid) const
Return a pointer to CCoins in the cache, or NULL if not found.
Definition: coins.cpp:145
CDataStream::size
size_type size() const
Definition: streams.h:120
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:641
merkle.h
checkpoints.h
NetMsgType::NOTFOUND
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:42
CDataStream::SetVersion
void SetVersion(int n)
Definition: streams.h:212
SetRingSize
void SetRingSize(int nHeight)
Definition: main.cpp:2466
fVerifyingBlocks
bool fVerifyingBlocks
Definition: main.cpp:85
CValidationState::DoS
bool DoS(int level, bool ret=false, unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", bool corruptionIn=false)
Definition: validation.h:38
CheckPoAblockTime
bool CheckPoAblockTime(const CBlock &block)
Definition: poa.cpp:422
CNode::SetRecvVersion
void SetRecvVersion(int nVersionIn)
Definition: net.h:447
CheckBlockHeader
bool CheckBlockHeader(const CBlockHeader &block, CValidationState &state, bool fCheckPOW)
Context-independent validity checks.
Definition: main.cpp:4237
CBlockTreeDB::WriteTxIndex
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
Definition: txdb.cpp:173
NetMsgType::ADDR
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:19
GetBlockPosFilename
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
Definition: main.cpp:5160
RelayTransaction
void RelayTransaction(const CTransaction &tx)
Definition: net.cpp:2028
NetMsgType::BUDGETPROPOSAL
const char * BUDGETPROPOSAL
The budgetproposal message is used to broadcast or relay budget proposal metadata to connected peers.
Definition: protocol.cpp:54
name
const char * name
Definition: rest.cpp:34
poa.h
CBlockHeader::hashPrevBlock
uint256 hashPrevBlock
Definition: block.h:61
base_uint::SetNull
void SetNull()
Definition: arith_uint256.h:308
ContextualCheckBlockHeader
bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, CBlockIndex *const pindexPrev)
Context-dependent validity checks.
Definition: main.cpp:4458
CWallet::PROBABILITY_NEW_COIN_SELECTED
static const int32_t PROBABILITY_NEW_COIN_SELECTED
Definition: wallet.h:277
CBlock::vtx
std::vector< CTransaction > vtx
Definition: block.h:146
GetTimeMillis
int64_t GetTimeMillis()
Definition: utiltime.cpp:31
CCoins::nVersion
int nVersion
version of the CTransaction; accesses to this value should probably check for nHeight as well,...
Definition: coins.h:92
AcceptBlock
bool AcceptBlock(CBlock &block, CValidationState &state, CBlockIndex **ppindex, CDiskBlockPos *dbp, bool fAlreadyCheckedBlock)
Store block on disk.
Definition: main.cpp:4639
NetMsgType::BLOCK
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:36
CNode::IsWhitelistedRange
static bool IsWhitelistedRange(const CNetAddr &ip)
Definition: net.cpp:624
VerifyScript
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
Definition: interpreter.cpp:1163
R
#define R(a, b)
CTransaction::CURRENT_VERSION
static const int32_t CURRENT_VERSION
Definition: transaction.h:277
CDiskBlockPos::nPos
unsigned int nPos
Definition: chain.h:78
CChainParams::MaxReorganizationDepth
int MaxReorganizationDepth() const
Definition: chainparams.h:63
CNode::nServicesExpected
ServiceFlags nServicesExpected
Definition: net.h:311
invalid.h
fTxIndex
bool fTxIndex
Definition: main.cpp:82
CBlock
Definition: block.h:142
CTxMemPool::addUnchecked
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry)
Definition: txmempool.cpp:402
Checkpoints::CheckBlock
bool CheckBlock(int nHeight, const uint256 &hash, bool fMatchesCheckpoint)
Returns true if block passes checkpoint checks.
Definition: checkpoints.cpp:31
CWallet::DecodeStealthAddress
static bool DecodeStealthAddress(const std::string &stealth, CPubKey &pubViewKey, CPubKey &pubSpendKey, bool &hasPaymentID, uint64_t &paymentID)
Definition: wallet.cpp:6522
strprintf
#define strprintf
Definition: tinyformat.h:1056
CClientUIInterface::MSG_ERROR
@ MSG_ERROR
Definition: guiinterface.h:76
CWallet::fCombineDust
bool fCombineDust
Definition: wallet.h:331
NetMsgType::MEMPOOL
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:38
CBlockTreeDB::WriteFlag
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:214
CTxMemPool::queryHashes
void queryHashes(std::vector< uint256 > &vtxid)
Definition: txmempool.cpp:614
MSG_BUDGET_FINALIZED
@ MSG_BUDGET_FINALIZED
Definition: protocol.h:399
LOCKTIME_MEDIAN_TIME_PAST
@ LOCKTIME_MEDIAN_TIME_PAST
Definition: consensus.h:30
Checkpoints::GuessVerificationProgress
double GuessVerificationProgress(const CBlockIndex *pindex, bool fSigchecks)
Guess how far we are in the verification process at the given block index.
Definition: checkpoints.cpp:45
CWallet::AutoCombineDust
void AutoCombineDust()
Definition: wallet.cpp:5728
CPubKey
An encapsulated public key.
Definition: pubkey.h:37
GetBlockProof
uint256 GetBlockProof(const CBlockIndex &block)
Definition: poa.cpp:171
GetAdjustedTime
int64_t GetAdjustedTime()
Definition: timedata.cpp:30
CBudgetManager::ProcessMessage
void ProcessMessage(CNode *pfrom, std::string &strCommand, CDataStream &vRecv)
Definition: masternode-budget.cpp:988
GetTimeMicros
int64_t GetTimeMicros()
Definition: utiltime.cpp:38
CVerifyDB::VerifyDB
bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
Definition: main.cpp:5308
CChain
An in-memory indexed chain of blocks.
Definition: chain.h:583
CTransaction::ToString
std::string ToString() const
Definition: transaction.cpp:217
CBlockTreeDB::ReadTxIndex
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Definition: txdb.cpp:168
CAddress
A CService with information about it as peer.
Definition: protocol.h:323
CMainCleanup::~CMainCleanup
~CMainCleanup()
Definition: main.cpp:7238
mapOrphanTransactions
std::map< uint256, COrphanTx > mapOrphanTransactions
Definition: main.cpp:108
CCheckQueueControl::Wait
bool Wait()
Definition: checkqueue.h:191
CMessageHeader
Message header.
Definition: protocol.h:29
CChain::GetLocator
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:25
CBlockUndo::WriteToDisk
bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
Definition: main.cpp:7173
CAutoFile::GetSerializeSize
unsigned int GetSerializeSize(const T &obj)
Definition: streams.h:400
AllocateFileRange
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: util.cpp:531
CTransaction::bulletproofs
std::vector< unsigned char > bulletproofs
Definition: transaction.h:296
NetMsgType::TX
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:25
CInv::hash
uint256 hash
Definition: protocol.h:384
CTxMemPool::mapNextTx
std::map< COutPoint, CInPoint > mapNextTx
Definition: txmempool.h:137
BCLog::MEMPOOL
@ MEMPOOL
Definition: logging.h:42
CBlockIndex::GetBlockPos
CDiskBlockPos GetBlockPos() const
Definition: chain.h:320
secp256k1_context_struct2
Definition: secp256k1_types.h:15
CKey
An encapsulated private key.
Definition: key.h:39
CTxOut::maskValue
MaskValue maskValue
Definition: transaction.h:176
LimitOrphanTxSize
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
Definition: main.cpp:1198
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:414
END
#define END(a)
Definition: utilstrencodings.h:18
LoadExternalBlockFile
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
Definition: main.cpp:5467
itostr
std::string itostr(int n)
Definition: utilstrencodings.cpp:564
NetMsgType::BUDGETVOTE
const char * BUDGETVOTE
The budgetvote message is used to broadcast or relay budget proposal votes to connected peers.
Definition: protocol.cpp:55
utilmoneystr.h
BCLog::MASTERNODE
@ MASTERNODE
Definition: logging.h:62
secp256k1_bulletproof_generators_destroy
SECP256K1_API void secp256k1_bulletproof_generators_destroy(const secp256k1_context2 *ctx, secp256k1_bulletproof_generators *gen) SECP256K1_ARG_NONNULL(1)
Destroys a list of NUMS generators, freeing allocated memory Args: ctx: pointer to a context object (...
Definition: main_impl.h:469
secp256k1_pedersen_commitment
Opaque data structure that stores a Pedersen commitment.
Definition: secp256k1_commitment.h:22
fReindex
std::atomic< bool > fReindex
Definition: main.cpp:81
CCoinsViewCache::SetBestBlock
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:172
CheckDiskSpace
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
Definition: main.cpp:5116
main.h
CValidationState::Error
bool Error(std::string strRejectReasonIn="")
Definition: validation.h:55
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:50
BanReasonNodeMisbehaving
@ BanReasonNodeMisbehaving
Definition: net.h:247
CBlockLocator::vHave
std::vector< uint256 > vHave
Definition: block.h:251
COutPoint::n
uint32_t n
Definition: transaction.h:40
CCoinsViewCache::HaveCoins
bool HaveCoins(const uint256 &txid) const
Just check whether we have data for a given txid.
Definition: coins.cpp:155
CWallet::CreateCommitmentWithZeroBlind
static bool CreateCommitmentWithZeroBlind(const CAmount val, unsigned char *pBlind, std::vector< unsigned char > &commitment)
Definition: wallet.cpp:3102
CTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:285
CNode::fPingQueued
bool fPingQueued
Definition: net.h:407
Solver
bool Solver(const CKeyStore &keystore, const CScript &scriptPubKey, uint256 hash, int nHashType, CScript &scriptSigRet, txnouttype &whichTypeRet)
Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
Definition: sign.cpp:50
CMasternodeMan::mapSeenMasternodePing
std::map< uint256, CMasternodePing > mapSeenMasternodePing
Definition: masternodeman.h:78
CTxMemPoolEntry
CTxMemPool stores these:
Definition: txmempool.h:40
CTxMemPool::mapTx
std::map< uint256, CTxMemPoolEntry > mapTx
Definition: txmempool.h:136
swifttx.h
secp256k1_generator_const_g
const SECP256K1_API secp256k1_generator secp256k1_generator_const_g
Standard secp256k1 generator G.
Definition: main_impl.h:18
LOCK
#define LOCK(cs)
Definition: sync.h:182
CBlockIndex::nUndoPos
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:190
CTxIn::s
std::vector< unsigned char > s
Definition: transaction.h:90
nLocalServices
ServiceFlags nLocalServices
Definition: net.cpp:73
ProcessNewBlock
bool ProcessNewBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
Definition: main.cpp:4890
CScript::GetSigOpCount
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:163
CBlockIndex::BuildSkip
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: main.cpp:4884
CBlockFileInfo
Definition: chain.h:18
MSG_BUDGET_FINALIZED_VOTE
@ MSG_BUDGET_FINALIZED_VOTE
Definition: protocol.h:400
CNodeSignals::ProcessMessages
boost::signals2::signal< bool(CNode *), CombinerAll > ProcessMessages
Definition: net.h:112
MIN_RING_SIZE
int MIN_RING_SIZE
Definition: main.cpp:91
nLocalHostNonce
uint64_t nLocalHostNonce
Definition: net.cpp:78
CNode::nNextInvSend
int64_t nNextInvSend
Definition: net.h:395
secp256k1_generator_const_h
const SECP256K1_API secp256k1_generator secp256k1_generator_const_h
Alternate secp256k1 generator from Elements Alpha.
Definition: main_impl.h:32
CNetMessage
Definition: net.h:204
ReadBlockFromDisk
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
Definition: main.cpp:2101
pindexBestForkTip
CBlockIndex * pindexBestForkTip
Definition: main.cpp:2518
VerifyBulletProofAggregate
bool VerifyBulletProofAggregate(const CTransaction &tx)
Definition: main.cpp:376
GetValueIn
CAmount GetValueIn(CCoinsViewCache view, const CTransaction &tx)
Definition: main.cpp:221
DisconnectBlock
bool DisconnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
Functions for validating blocks and updating the block tree.
Definition: main.cpp:2877
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:86
FLUSH_STATE_IF_NEEDED
@ FLUSH_STATE_IF_NEEDED
Definition: main.cpp:3373
CBlockIndex::nSequenceId
uint32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:239
CHashWriter
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:259
prevector::size
size_type size() const
Definition: prevector.h:282
CCoinsViewMemPool
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:202
CTxIn::scriptSig
CScript scriptSig
Definition: transaction.h:87
CheckNumberOfAuditedPoSBlocks
bool CheckNumberOfAuditedPoSBlocks(const CBlock &block, const CBlockIndex *pindex)
Definition: poa.cpp:314
CMasternodeSync::ProcessMessage
void ProcessMessage(CNode *pfrom, std::string &strCommand, CDataStream &vRecv)
Definition: masternode-sync.cpp:180
CNetMessage::vRecv
CDataStream vRecv
Definition: net.h:213
ProcessMessages
bool ProcessMessages(CNode *pfrom)
Process protocol messages received from a given node.
Definition: main.cpp:6849
strMessageMagic
const std::string strMessageMagic
Definition: main.cpp:119
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:349
CNode::nPingNonceSent
uint64_t nPingNonceSent
Definition: net.h:399
TestBlockValidity
bool TestBlockValidity(CValidationState &state, const CBlock &block, CBlockIndex *const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block,...
Definition: main.cpp:5088
CMessageHeader::pchMessageStart
char pchMessageStart[MESSAGE_START_SIZE]
Definition: protocol.h:60
PoissonNextSend
int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:2503
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:463
GetNodeStateStats
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
Definition: main.cpp:1081
RemoveInvalidTransactionsFromMempool
void RemoveInvalidTransactionsFromMempool()
Definition: main.cpp:3691
masternode-budget.h
CScriptCheck
Closure representing one script verification Note that this stores references to the spending transac...
Definition: main.h:351
CNode::addrName
std::string addrName
Definition: net.h:333
CChain::Contains
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:626
CScriptCheck::cacheStore
bool cacheStore
Definition: main.h:358
secp256k1_ec_pubkey_tweak_add
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3)
Tweak a public key by adding tweak times the generator to it.
Definition: secp256k1.c:237
MilliSleep
void MilliSleep(int64_t n)
Definition: utiltime.cpp:45
CNode::fOneShot
bool fOneShot
Definition: net.h:343
CDataStream::in_avail
int in_avail()
Definition: streams.h:208
BCLog::SELECTCOINS
@ SELECTCOINS
Definition: logging.h:50
getAllNetMessageTypes
const std::vector< std::string > & getAllNetMessageTypes()
Definition: protocol.cpp:259
COrphanTx::tx
CTransaction tx
Definition: main.cpp:105
CTxMemPool::ApplyDeltas
void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta)
Definition: txmempool.cpp:686
ConvertBitsToDouble
double ConvertBitsToDouble(unsigned int nBits)
Definition: main.cpp:2139
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:301
secp256k1_pedersen_serialized_pubkey_to_commitment
SECP256K1_API void secp256k1_pedersen_serialized_pubkey_to_commitment(const unsigned char *pubkey, size_t length, secp256k1_pedersen_commitment *commit) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3)
Definition: main_impl.h:50
InsertBlockIndex
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
Definition: main.cpp:5165
VerifyShnorrKeyImageTxIn
bool VerifyShnorrKeyImageTxIn(const CTxIn &txin, uint256 ctsHash)
Definition: main.cpp:1407
mapInvalidOutPoints
std::map< COutPoint, COutPoint > mapInvalidOutPoints
Definition: main.cpp:2735
SCRIPT_VERIFY_P2SH
@ SCRIPT_VERIFY_P2SH
Definition: interpreter.h:36
CAddrMan::SetServices
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: addrman.h:587
GetBlockValue
CAmount GetBlockValue(int nHeight)
Definition: main.cpp:2158
AcceptBlockHeader
bool AcceptBlockHeader(const CBlock &block, CValidationState &state, CBlockIndex **ppindex)
Definition: main.cpp:4571
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:34
UnregisterNodeSignals
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
Definition: main.cpp:1106
secp256k1_context_create2
SECP256K1_API secp256k1_context2 * secp256k1_context_create2(unsigned int flags) SECP256K1_WARN_UNUSED_RESULT
Create a secp256k1 context object.
Definition: secp256k1_2.c:75
CTxInUndo
Undo information for a CTxIn.
Definition: undo.h:20
nFilteredThroughBittrex
CAmount nFilteredThroughBittrex
Definition: main.cpp:2738
addrman.h
NetMsgType::VERACK
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:18
CNode::nMinPingUsecTime
int64_t nMinPingUsecTime
Definition: net.h:405
CCoins
Definition: coins.h:77
CMessageHeader::nMessageSize
unsigned int nMessageSize
Definition: protocol.h:62
CAddrMan::size
int size()
Return the number of (unique) addresses in all tables.
Definition: addrman.h:485
CCoins::fCoinBase
bool fCoinBase
whether transaction is a coinbase
Definition: coins.h:81
BlockMap
boost::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: main.h:134
runCommand
void runCommand(std::string strCommand)
Definition: util.cpp:593
CNode::nNextAddrSend
int64_t nNextAddrSend
Definition: net.h:386
CTxMemPoolEntry::GetTxSize
size_t GetTxSize() const
Definition: txmempool.h:59
NetMsgType::FILTERADD
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:44
CBlock::IsProofOfAudit
bool IsProofOfAudit() const
Definition: block.h:228
CTxOut::commitment
std::vector< unsigned char > commitment
Definition: transaction.h:178
COutPoint::ToString
std::string ToString() const
Definition: transaction.cpp:21
CNode::id
NodeId id
Definition: net.h:358
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:342
CAddrMan::Good
void Good(const CService &addr, int64_t nTime=GetAdjustedTime())
Mark an entry as accessible.
Definition: addrman.h:532
CCoinsViewCache::GetBestBlock
uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:165
IsBlockHashInChain
bool IsBlockHashInChain(const uint256 &hashBlock)
Definition: main.cpp:4519
CScriptCheck::nFlags
unsigned int nFlags
Definition: main.h:357
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
CBlockIndex::hashProofOfStake
uint256 hashProofOfStake
Definition: chain.h:221
CChain::Tip
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:596
txnouttype
txnouttype
Definition: standard.h:57
CBlockIndex::IsProofOfAudit
bool IsProofOfAudit() const
Definition: chain.h:400
CDataStream::empty
bool empty() const
Definition: streams.h:121
CPubKey::IsValid
bool IsValid() const
Definition: pubkey.h:159
CCoins::Clear
void Clear()
Definition: coins.h:110
MSG_FILTERED_BLOCK
@ MSG_FILTERED_BLOCK
Definition: protocol.h:392
CheckBlockSignature
bool CheckBlockSignature(const CBlock &block)
Definition: blocksignature.cpp:57
CBlockFileInfo::ToString
std::string ToString() const
Definition: main.cpp:7226
CNodeSignals
Definition: net.h:109
CBlockIndex::bnChainTrust
uint256 bnChainTrust
Definition: chain.h:178
CTransaction::nVersion
const int32_t nVersion
Definition: transaction.h:284
CMessageHeader::IsValid
bool IsValid() const
Definition: protocol.cpp:160
CBlockTreeDB::ReadKeyImages
bool ReadKeyImages(const std::string &keyImage, std::vector< uint256 > &bhs)
Definition: txdb.cpp:188
CClientUIInterface::NotifyBlockTip
boost::signals2::signal< void(bool fInitialDownload, const CBlockIndex *newTip)> NotifyBlockTip
New block has been accepted.
Definition: guiinterface.h:104
CBlock::SetNull
void SetNull()
Definition: block.h:183
budget
CBudgetManager budget
Definition: masternode-budget.cpp:19
CCoins::Spend
bool Spend(const COutPoint &out, CTxInUndo &undo)
mark an outpoint spent, and construct undo information
Definition: coins.cpp:38
CTxUndo::vprevout
std::vector< CTxInUndo > vprevout
Definition: undo.h:67
nTimeBestReceived
int64_t nTimeBestReceived
Definition: main.cpp:72
CBloomFilter::IsRelevantAndUpdate
bool IsRelevantAndUpdate(const CTransaction &tx)
Also adds any outputs which match the filter to the filter (to match their spending txes)
Definition: bloom.cpp:131
CNode::mapAskFor
std::multimap< int64_t, CInv > mapAskFor
Definition: net.h:393
FLUSH_STATE_ALWAYS
@ FLUSH_STATE_ALWAYS
Definition: main.cpp:3375
ReprocessBlocks
void ReprocessBlocks(int nBlocks)
Definition: main.cpp:3660
CValidationState::IsValid
bool IsValid() const
Definition: validation.h:62
CClientUIInterface::ShowProgress
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: guiinterface.h:101
BCLog::NET
@ NET
Definition: logging.h:40
Hash
std::string Hash(std::string input)
Compute the 256-bit hash of a std::string.
Definition: hash.h:122
secp256k1_pedersen_commitment_sum_pos
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_sum_pos(const secp256k1_context2 *ctx, const secp256k1_pedersen_commitment *const *pos, size_t n_pos, secp256k1_pedersen_commitment *out) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4)
Definition: main_impl.h:205
CBlockLocator
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:249
mapTxLockReqRejected
std::map< uint256, CTransaction > mapTxLockReqRejected
Definition: swifttx.cpp:25
GetGenerator
secp256k1_bulletproof_generators * GetGenerator()
Definition: main.cpp:362
CHashWriter::GetHash
uint256 GetHash()
Definition: hash.h:277
CNodeSignals::InitializeNode
boost::signals2::signal< void(NodeId, const CNode *)> InitializeNode
Definition: net.h:114
CFeeRate::GetFee
CAmount GetFee(size_t size) const
Definition: amount.cpp:20
NetMsgType::VERSION
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:17
fListen
bool fListen
Definition: net.cpp:72
CBudgetManager::NewBlock
void NewBlock()
Definition: masternode-budget.cpp:876
CTransaction::ComputePriority
double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const
Definition: transaction.cpp:191
FLUSH_STATE_PERIODIC
@ FLUSH_STATE_PERIODIC
Definition: main.cpp:3374
ContextualCheckBlock
bool ContextualCheckBlock(const CBlock &block, CValidationState &state, CBlockIndex *const pindexPrev)
Definition: main.cpp:4545
GetMinRelayFee
CAmount GetMinRelayFee(const CTransaction &tx, unsigned int nBytes, bool fAllowFree)
Definition: main.cpp:1495
CTxIn::keyImage
CKeyImage keyImage
Definition: transaction.h:97
CBudgetManager::mapSeenFinalizedBudgetVotes
std::map< uint256, CFinalizedBudgetVote > mapSeenFinalizedBudgetVotes
Definition: masternode-budget.h:191
CNodeStateStats
Definition: main.h:288
net.h
GetTxInSignatureHash
uint256 GetTxInSignatureHash(const CTxIn &txin)
Definition: main.cpp:687
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:162
secp256k1_pedersen_commitment_sum
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_pedersen_commitment_sum(const secp256k1_context2 *ctx, const secp256k1_pedersen_commitment *const *pos, size_t n_pos, const secp256k1_pedersen_commitment *const *neg, size_t n_neg, secp256k1_pedersen_commitment *out) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(6)
Definition: main_impl.h:175
CNode::fClient
bool fClient
Definition: net.h:344
MSG_BUDGET_VOTE
@ MSG_BUDGET_VOTE
Definition: protocol.h:397
SECP256K1_CONTEXT_VERIFY
#define SECP256K1_CONTEXT_VERIFY
Flags to pass to secp256k1_context_create2.
Definition: secp256k1_2.h:167
ReceivedBlockTransactions
bool ReceivedBlockTransactions(const CBlock &block, CValidationState &state, CBlockIndex *pindexNew, const CDiskBlockPos &pos)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
Definition: main.cpp:4110
SCRIPT_VERIFY_DERSIG
@ SCRIPT_VERIFY_DERSIG
Definition: interpreter.h:44
GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:241
CNode::nSendSize
size_t nSendSize
Definition: net.h:314
pwalletMain
CWallet * pwalletMain
Definition: wallet.cpp:49
NetMsgType::MNPING
const char * MNPING
The mnping message is used to ensure a masternode is still active.
Definition: protocol.cpp:51
BLOCK_VALID_CHAIN
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends,...
Definition: chain.h:138
CBlockIndex::GetBlockTrust
uint256 GetBlockTrust() const
Definition: chain.cpp:66
CNode::nStartingHeight
int nStartingHeight
Definition: net.h:379
AddOrphanTx
bool AddOrphanTx(const CTransaction &tx, NodeId peer)
Definition: main.cpp:1138
amount.h
CTransaction::c
uint256 c
Definition: transaction.h:300
MASTERNODE_SYNC_LIST
#define MASTERNODE_SYNC_LIST
Definition: masternode-sync.h:11
CBlockFileInfo::nSize
unsigned int nSize
number of blocks stored in file
Definition: chain.h:22
base_uint::getdouble
double getdouble() const
Definition: arith_uint256.cpp:143
CBlockIndex::SetStakeModifier
void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
Definition: chain.h:431
CTxMemPool::clear
void clear()
Definition: txmempool.cpp:531
CNode::strSubVer
std::string strSubVer
Definition: net.h:340
CNetAddr::IsLocal
bool IsLocal() const
Definition: netaddress.cpp:168
GetIXConfirmations
int GetIXConfirmations(uint256 nTXHash)
Definition: main.cpp:1392
CValidationState
Capture information about block/transaction validation.
Definition: validation.h:23
BLOCK_HAVE_UNDO
@ BLOCK_HAVE_UNDO
full block available in blk*.dat
Definition: chain.h:149
CChainParams::MNCollateralAmt
CAmount MNCollateralAmt() const
Definition: chainparams.h:86
CBlockIndex::GetUndoPos
CDiskBlockPos GetUndoPos() const
Definition: chain.h:330
util.h
CRollingBloomFilter
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:116
CNodeSignals::GetHeight
boost::signals2::signal< int()> GetHeight
Definition: net.h:111
LIMITED_STRING
#define LIMITED_STRING(obj, n)
Definition: serialize.h:367
CChainParams::TOTAL_SUPPLY
CAmount TOTAL_SUPPLY
Definition: chainparams.h:130
CNetMessage::hdr
CMessageHeader hdr
Definition: net.h:210
CheckPoABlockNotAuditingOverlap
bool CheckPoABlockNotAuditingOverlap(const CBlock &block)
Definition: poa.cpp:445
OpenUndoFile
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
Open an undo file (rev?????.dat)
Definition: main.cpp:5155
CLIENT_VERSION_IS_RELEASE
#define CLIENT_VERSION_IS_RELEASE
Definition: prcycoin-config.h:15
NetMsgType::MNBROADCAST
const char * MNBROADCAST
The mnbroadcast message is used to broadcast masternode startup data to connected peers.
Definition: protocol.cpp:50
MSG_MASTERNODE_WINNER
@ MSG_MASTERNODE_WINNER
Definition: protocol.h:395
CBufferedFile::SetLimit
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
Definition: streams.h:557
CChain::Next
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip.
Definition: chain.h:632
FindBlockPos
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
Definition: main.cpp:4158
CBlock::IsProofOfStake
bool IsProofOfStake() const
Definition: block.h:213
CChain::Genesis
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: chain.h:590
CNetAddr::SetIP
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:24
CBlockTreeDB::WriteKeyImage
bool WriteKeyImage(const std::string &keyImage, const uint256 &height)
Definition: txdb.cpp:201
txdb.h
CInv::ToString
std::string ToString() const
Definition: protocol.cpp:254
FastRandomContext
Fast randomness source.
Definition: random.h:44
CBlockUndo
Undo information for a CBlock.
Definition: undo.h:79
CCoinsViewCache::Flush
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:223
S
#define S(x0, x1, x2, x3, cb, r)
Definition: jh.c:494
CNode::vAddrToSend
std::vector< CAddress > vAddrToSend
Definition: net.h:382
IsSpentKeyImage
bool IsSpentKeyImage(const std::string &kiHex, const uint256 &againsHash)
Definition: main.cpp:283
CCryptoKeyStore::IsLocked
bool IsLocked() const
Definition: crypter.h:159
CheckPoAContainRecentHash
bool CheckPoAContainRecentHash(const CBlock &block)
Definition: poa.cpp:192
secp256k1_bulletproof_generators
Definition: main_impl.h:54
CTxInUndo::fCoinBase
bool fCoinBase
Definition: undo.h:24
CNode::cleanSubVer
std::string cleanSubVer
Definition: net.h:340
error
bool error(const char *fmt, const Args &... args)
Definition: util.h:61
nMaxTipAge
int64_t nMaxTipAge
Definition: main.cpp:89
mapTxLocks
std::map< uint256, CTransactionLock > mapTxLocks
Definition: swifttx.cpp:27
CChainParams::ToCheckBlockUpgradeMajority
int ToCheckBlockUpgradeMajority() const
Definition: chainparams.h:62
mapBlockIndex
BlockMap mapBlockIndex
Definition: main.cpp:67
NetMsgType::GETADDR
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:37
BlockMerkleRoot
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:150
CNode::AddAddressKnown
void AddAddressKnown(const CAddress &addr)
Definition: net.h:466
CTxOut::txPub
std::vector< unsigned char > txPub
Definition: transaction.h:173
CService::GetKey
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:544
mapAlreadyAskedFor
limitedmap< CInv, int64_t > mapAlreadyAskedFor(MAX_INV_SZ)
NetMsgType::MERKLEBLOCK
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:22
SECP256K1_CONTEXT_SIGN
#define SECP256K1_CONTEXT_SIGN
Definition: secp256k1_2.h:168
CCoins::IsPruned
bool IsPruned() const
check whether the entire CCoins is spent note that only !IsPruned() CCoins can be serialized
Definition: coins.h:282
ECDHInfo::Decode
static void Decode(unsigned char *encodedMask, unsigned char *encodedAmount, const CPubKey &sharedSec, CKey &decodedMask, CAmount &decodedAmount)
Definition: wallet.cpp:126
CMessageHeader::COMMAND_SIZE
@ COMMAND_SIZE
Definition: protocol.h:52
CTransaction::IsCoinStake
bool IsCoinStake() const
Definition: transaction.cpp:143
Misbehaving
void Misbehaving(NodeId pnode, int howmuch) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Increase a node's misbehavior score.
Definition: main.cpp:2645
base_uint::ToString
std::string ToString() const
Definition: arith_uint256.cpp:199
CBlockTreeDB::ReadLastBlockFile
bool ReadLastBlockFile(int &nFile)
Definition: txdb.cpp:106
CMasternodePayments::ProcessMessageMasternodePayments
void ProcessMessageMasternodePayments(CNode *pfrom, std::string &strCommand, CDataStream &vRecv)
Definition: masternode-payments.cpp:298