Cleanup forward declaration in main.h
[novacoin.git] / src / txdb-bdb.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "db.h"
7 #include "kernel.h"
8 #include "checkpoints.h"
9 #include "txdb-bdb.h"
10 #include "util.h"
11 #include "main.h"
12 #include <boost/version.hpp>
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
15
16 #ifndef WIN32
17 #include "sys/stat.h"
18 #endif
19
20 using namespace std;
21 using namespace boost;
22
23 //
24 // CTxDB
25 //
26
27 bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
28 {
29     assert(!fClient);
30     txindex.SetNull();
31     return Read(make_pair(string("tx"), hash), txindex);
32 }
33
34 bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
35 {
36     assert(!fClient);
37     return Write(make_pair(string("tx"), hash), txindex);
38 }
39
40 bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
41 {
42     assert(!fClient);
43
44     // Add to tx index
45     uint256 hash = tx.GetHash();
46     CTxIndex txindex(pos, tx.vout.size());
47     return Write(make_pair(string("tx"), hash), txindex);
48 }
49
50 bool CTxDB::EraseTxIndex(const CTransaction& tx)
51 {
52     assert(!fClient);
53     uint256 hash = tx.GetHash();
54
55     return Erase(make_pair(string("tx"), hash));
56 }
57
58 bool CTxDB::ContainsTx(uint256 hash)
59 {
60     assert(!fClient);
61     return Exists(make_pair(string("tx"), hash));
62 }
63
64 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
65 {
66     assert(!fClient);
67     tx.SetNull();
68     if (!ReadTxIndex(hash, txindex))
69         return false;
70     return (tx.ReadFromDisk(txindex.pos));
71 }
72
73 bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
74 {
75     CTxIndex txindex;
76     return ReadDiskTx(hash, tx, txindex);
77 }
78
79 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
80 {
81     return ReadDiskTx(outpoint.hash, tx, txindex);
82 }
83
84 bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
85 {
86     CTxIndex txindex;
87     return ReadDiskTx(outpoint.hash, tx, txindex);
88 }
89
90 bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
91 {
92     return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
93 }
94
95 bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
96 {
97     return Read(string("hashBestChain"), hashBestChain);
98 }
99
100 bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
101 {
102     return Write(string("hashBestChain"), hashBestChain);
103 }
104
105 bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
106 {
107     return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
108 }
109
110 bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
111 {
112     return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
113 }
114
115 bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
116 {
117     return Read(string("hashSyncCheckpoint"), hashCheckpoint);
118 }
119
120 bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
121 {
122     return Write(string("hashSyncCheckpoint"), hashCheckpoint);
123 }
124
125 bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
126 {
127     return Read(string("strCheckpointPubKey"), strPubKey);
128 }
129
130 bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
131 {
132     return Write(string("strCheckpointPubKey"), strPubKey);
133 }
134
135 bool CTxDB::ReadModifierUpgradeTime(unsigned int& nUpgradeTime)
136 {
137     return Read(string("nUpgradeTime"), nUpgradeTime);
138 }
139
140 bool CTxDB::WriteModifierUpgradeTime(const unsigned int& nUpgradeTime)
141 {
142     return Write(string("nUpgradeTime"), nUpgradeTime);
143 }
144
145 CBlockIndex static * InsertBlockIndex(uint256 hash)
146 {
147     if (hash == 0)
148         return NULL;
149
150     // Return existing
151     auto mi = mapBlockIndex.find(hash);
152     if (mi != mapBlockIndex.end())
153         return (*mi).second;
154
155     // Create new
156     auto pindexNew = new(nothrow) CBlockIndex();
157     if (!pindexNew)
158         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
159     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
160     pindexNew->phashBlock = &((*mi).first);
161
162     return pindexNew;
163 }
164
165 bool CTxDB::LoadBlockIndex()
166 {
167     if (!LoadBlockIndexGuts())
168         return false;
169
170     if (fRequestShutdown)
171         return true;
172
173     // Calculate nChainTrust
174     vector<pair<int, CBlockIndex*> > vSortedByHeight;
175     vSortedByHeight.reserve(mapBlockIndex.size());
176     for(const auto& item : mapBlockIndex)
177     {
178         auto pindex = item.second;
179         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
180     }
181     sort(vSortedByHeight.begin(), vSortedByHeight.end());
182     for(const auto& item : vSortedByHeight)
183     {
184         auto pindex = item.second;
185         pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
186         // ppcoin: calculate stake modifier checksum
187         pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
188         if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
189             return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindex->nHeight, pindex->nStakeModifier);
190     }
191
192     // Load hashBestChain pointer to end of best chain
193     if (!ReadHashBestChain(hashBestChain))
194     {
195         if (pindexGenesisBlock == NULL)
196             return true;
197         return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
198     }
199     if (!mapBlockIndex.count(hashBestChain))
200         return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
201     pindexBest = mapBlockIndex[hashBestChain];
202     nBestHeight = pindexBest->nHeight;
203     nBestChainTrust = pindexBest->nChainTrust;
204     printf("LoadBlockIndex(): hashBestChain=%s  height=%d  trust=%s  date=%s\n",
205       hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
206       DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
207
208     // ppcoin: load hashSyncCheckpoint
209     if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
210         return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
211     printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
212
213     // Load bnBestInvalidTrust, OK if it doesn't exist
214     CBigNum bnBestInvalidTrust;
215     ReadBestInvalidTrust(bnBestInvalidTrust);
216     nBestInvalidTrust = bnBestInvalidTrust.getuint256();
217
218     // Verify blocks in the best chain
219     int nCheckLevel = GetArgInt("-checklevel", 1);
220     int nCheckDepth = GetArgInt( "-checkblocks", 192);
221     if (nCheckDepth == 0)
222         nCheckDepth = 1000000000; // suffices until the year 19000
223     if (nCheckDepth > nBestHeight)
224         nCheckDepth = nBestHeight;
225     printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
226     CBlockIndex* pindexFork = NULL;
227     map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
228     for (auto pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
229     {
230         if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
231             break;
232         CBlock block;
233         if (!block.ReadFromDisk(pindex))
234             return error("LoadBlockIndex() : block.ReadFromDisk failed");
235         // check level 1: verify block validity
236         // check level 7: verify block signature too
237         if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
238         {
239             printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
240             pindexFork = pindex->pprev;
241         }
242         // check level 2: verify transaction index validity
243         if (nCheckLevel>1)
244         {
245             auto pos = make_pair(pindex->nFile, pindex->nBlockPos);
246             mapBlockPos[pos] = pindex;
247             for(const auto &tx :  block.vtx)
248             {
249                 auto hashTx = tx.GetHash();
250                 CTxIndex txindex;
251                 if (ReadTxIndex(hashTx, txindex))
252                 {
253                     // check level 3: checker transaction hashes
254                     if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
255                     {
256                         // either an error or a duplicate transaction
257                         CTransaction txFound;
258                         if (!txFound.ReadFromDisk(txindex.pos))
259                         {
260                             printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
261                             pindexFork = pindex->pprev;
262                         }
263                         else
264                             if (txFound.GetHash() != hashTx) // not a duplicate tx
265                             {
266                                 printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
267                                 pindexFork = pindex->pprev;
268                             }
269                     }
270                     // check level 4: check whether spent txouts were spent within the main chain
271                     unsigned int nOutput = 0;
272                     if (nCheckLevel>3)
273                     {
274                         for(const CDiskTxPos &txpos :  txindex.vSpent)
275                         {
276                             if (!txpos.IsNull())
277                             {
278                                 auto posFind = make_pair(txpos.nFile, txpos.nBlockPos);
279                                 if (!mapBlockPos.count(posFind))
280                                 {
281                                     printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
282                                     pindexFork = pindex->pprev;
283                                 }
284                                 // check level 6: check whether spent txouts were spent by a valid transaction that consume them
285                                 if (nCheckLevel>5)
286                                 {
287                                     CTransaction txSpend;
288                                     if (!txSpend.ReadFromDisk(txpos))
289                                     {
290                                         printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
291                                         pindexFork = pindex->pprev;
292                                     }
293                                     else if (!txSpend.CheckTransaction())
294                                     {
295                                         printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
296                                         pindexFork = pindex->pprev;
297                                     }
298                                     else
299                                     {
300                                         bool fFound = false;
301                                         for(const CTxIn &txin :  txSpend.vin)
302                                             if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
303                                                 fFound = true;
304                                         if (!fFound)
305                                         {
306                                             printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
307                                             pindexFork = pindex->pprev;
308                                         }
309                                     }
310                                 }
311                             }
312                             nOutput++;
313                         }
314                     }
315                 }
316                 // check level 5: check whether all prevouts are marked spent
317                 if (nCheckLevel>4)
318                 {
319                      for(const CTxIn &txin :  tx.vin)
320                      {
321                           CTxIndex txindex;
322                           if (ReadTxIndex(txin.prevout.hash, txindex))
323                               if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
324                               {
325                                   printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
326                                   pindexFork = pindex->pprev;
327                               }
328                      }
329                 }
330             }
331         }
332     }
333     if (pindexFork && !fRequestShutdown)
334     {
335         // Reorg back to the fork
336         printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
337         CBlock block;
338         if (!block.ReadFromDisk(pindexFork))
339             return error("LoadBlockIndex() : block.ReadFromDisk failed");
340         CTxDB txdb;
341         block.SetBestChain(txdb, pindexFork);
342     }
343
344     return true;
345 }
346
347
348
349 bool CTxDB::LoadBlockIndexGuts()
350 {
351     // Get database cursor
352     Dbc* pcursor = GetCursor();
353     if (!pcursor)
354         return false;
355
356     // Load mapBlockIndex
357     unsigned int fFlags = DB_SET_RANGE;
358     for ( ; ; )
359     {
360         // Read next record
361         CDataStream ssKey(SER_DISK, CLIENT_VERSION);
362         if (fFlags == DB_SET_RANGE)
363             ssKey << make_pair(string("blockindex"), uint256(0));
364         CDataStream ssValue(SER_DISK, CLIENT_VERSION);
365         int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
366         fFlags = DB_NEXT;
367         if (ret == DB_NOTFOUND)
368             break;
369         else if (ret != 0)
370             return false;
371
372         // Unserialize
373
374         try {
375         string strType;
376         ssKey >> strType;
377         if (strType == "blockindex" && !fRequestShutdown)
378         {
379             CDiskBlockIndex diskindex;
380             ssValue >> diskindex;
381
382             uint256 blockHash = diskindex.GetBlockHash();
383
384             // Construct block index object
385             CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
386             pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
387             pindexNew->pnext          = InsertBlockIndex(diskindex.hashNext);
388             pindexNew->nFile          = diskindex.nFile;
389             pindexNew->nBlockPos      = diskindex.nBlockPos;
390             pindexNew->nHeight        = diskindex.nHeight;
391             pindexNew->nMint          = diskindex.nMint;
392             pindexNew->nMoneySupply   = diskindex.nMoneySupply;
393             pindexNew->nFlags         = diskindex.nFlags;
394             pindexNew->nStakeModifier = diskindex.nStakeModifier;
395             pindexNew->prevoutStake   = diskindex.prevoutStake;
396             pindexNew->nStakeTime     = diskindex.nStakeTime;
397             pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
398             pindexNew->nVersion       = diskindex.nVersion;
399             pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
400             pindexNew->nTime          = diskindex.nTime;
401             pindexNew->nBits          = diskindex.nBits;
402             pindexNew->nNonce         = diskindex.nNonce;
403
404             // Watch for genesis block
405             if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
406                 pindexGenesisBlock = pindexNew;
407
408             if (!pindexNew->CheckIndex())
409                 return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
410
411             // ppcoin: build setStakeSeen
412             if (pindexNew->IsProofOfStake())
413                 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
414         }
415         else
416         {
417             break; // if shutdown requested or finished loading block index
418         }
419         }    // try
420         catch (const std::exception&) {
421             return error("%s() : deserialize error", BOOST_CURRENT_FUNCTION);
422         }
423     }
424     pcursor->close();
425
426     return true;
427 }
428
429