f44a93d5613c7ab7ca773e2052ef7d2ba22d2daf
[NovacoinLibrary.git] / Novacoin / CBlockStore.cs
1 \feff/**
2 *  Novacoin classes library
3 *  Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
4
5 *  This program is free software: you can redistribute it and/or modify
6 *  it under the terms of the GNU Affero General Public License as
7 *  published by the Free Software Foundation, either version 3 of the
8 *  License, or (at your option) any later version.
9
10 *  This program is distributed in the hope that it will be useful,
11 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 *  GNU Affero General Public License for more details.
14
15 *  You should have received a copy of the GNU Affero General Public License
16 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 using System;
21 using System.IO;
22 using System.Collections.Concurrent;
23
24 using SQLite.Net;
25 using SQLite.Net.Interop;
26 using SQLite.Net.Platform.Generic;
27 using System.Collections.Generic;
28 using System.Text;
29 using System.Diagnostics.Contracts;
30 using System.Linq;
31
32 namespace Novacoin
33 {
34     public class CBlockStore : IDisposable
35     {
36         public const uint nMagicNumber = 0xe5e9e8e4;
37
38         private bool disposed = false;
39         private object LockObj = new object();
40
41         /// <summary>
42         /// SQLite connection object.
43         /// </summary>
44         private SQLiteConnection dbConn;
45
46         /// <summary>
47         /// Current SQLite platform
48         /// </summary>
49         private ISQLitePlatform dbPlatform;
50
51         /// <summary>
52         /// Block file.
53         /// </summary>
54         private string strBlockFile;
55
56         /// <summary>
57         /// Index database file.
58         /// </summary>
59         private string strDbFile;
60
61         /// <summary>
62         /// Map of block tree nodes.
63         /// 
64         /// blockHash => CBlockStoreItem
65         /// </summary>
66         private ConcurrentDictionary<uint256, CBlockStoreItem> blockMap = new ConcurrentDictionary<uint256, CBlockStoreItem>();
67
68         /// <summary>
69         /// Orphaned blocks map.
70         /// </summary>
71         private ConcurrentDictionary<uint256, CBlock> orphanMap = new ConcurrentDictionary<uint256, CBlock>();
72         private ConcurrentDictionary<uint256, CBlock> orphanMapByPrev = new ConcurrentDictionary<uint256, CBlock>();
73
74         /// <summary>
75         /// Unconfirmed transactions.
76         /// 
77         /// TxID => Transaction
78         /// </summary>
79         private ConcurrentDictionary<uint256, CTransaction> mapUnconfirmedTx = new ConcurrentDictionary<uint256, CTransaction>();
80
81         /// <summary>
82         /// Map of the proof-of-stake hashes. This is necessary for stake duplication checks.
83         /// </summary>
84         private ConcurrentDictionary<uint256, uint256> mapProofOfStake = new ConcurrentDictionary<uint256, uint256>();
85
86
87         private ConcurrentDictionary<COutPoint, uint> mapStakeSeen = new ConcurrentDictionary<COutPoint, uint>();
88         private ConcurrentDictionary<COutPoint, uint> mapStakeSeenOrphan = new ConcurrentDictionary<COutPoint, uint>();
89
90
91         /// <summary>
92         /// Copy of chain state object.
93         /// </summary>
94         private ChainState ChainParams;
95
96         /// <summary>
97         /// Cursor which is pointing us to the end of best chain.
98         /// </summary>
99         private CBlockStoreItem bestBlockCursor = null;
100
101         /// <summary>
102         /// Cursor which is always pointing us to genesis block.
103         /// </summary>
104         private CBlockStoreItem genesisBlockCursor = null;
105
106         /// <summary>
107         /// Current and the only instance of block storage manager. Should be a property with private setter though it's enough for the beginning.
108         /// </summary>
109         public static CBlockStore Instance = null;
110
111         /// <summary>
112         /// Block file stream with read/write access
113         /// </summary>
114         private Stream fStreamReadWrite;
115         private uint nTimeBestReceived;
116         private int nTransactionsUpdated;
117
118         /// <summary>
119         /// Init the block storage manager.
120         /// </summary>
121         /// <param name="IndexDB">Path to index database</param>
122         /// <param name="BlockFile">Path to block file</param>
123         public CBlockStore(string IndexDB = "blockstore.dat", string BlockFile = "blk0001.dat")
124         {
125             strDbFile = IndexDB;
126             strBlockFile = BlockFile;
127
128             bool firstInit = !File.Exists(strDbFile);
129             dbPlatform = new SQLitePlatformGeneric();
130             dbConn = new SQLiteConnection(dbPlatform, strDbFile);
131
132             fStreamReadWrite = File.Open(strBlockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
133
134             Instance = this;
135
136             if (firstInit)
137             {
138                 lock (LockObj)
139                 {
140                     // Create tables
141                     dbConn.CreateTable<CBlockStoreItem>(CreateFlags.AutoIncPK);
142                     dbConn.CreateTable<CMerkleNode>(CreateFlags.AutoIncPK);
143                     dbConn.CreateTable<TxOutItem>(CreateFlags.ImplicitPK);
144                     dbConn.CreateTable<ChainState>(CreateFlags.AutoIncPK);
145
146                     ChainParams = new ChainState()
147                     {
148                         nBestChainTrust = 0,
149                         nBestHeight = 0,
150                         nHashBestChain = 0
151                     };
152
153                     dbConn.Insert(ChainParams);
154
155                     var genesisBlock = new CBlock(
156                         Interop.HexToArray(
157                             "01000000" + // nVersion=1
158                             "0000000000000000000000000000000000000000000000000000000000000000" + // prevhash is zero
159                             "7b0502ad2f9f675528183f83d6385794fbcaa914e6d385c6cb1d866a3b3bb34c" + // merkle root
160                             "398e1151" + // nTime=1360105017
161                             "ffff0f1e" + // nBits=0x1e0fffff
162                             "d3091800" + // nNonce=1575379
163                             "01" +       // nTxCount=1
164                             "01000000" + // nVersion=1
165                             "398e1151" + // nTime=1360105017
166                             "01" +       // nInputs=1
167                             "0000000000000000000000000000000000000000000000000000000000000000" + // input txid is zero
168                             "ffffffff" + // n=uint.maxValue
169                             "4d" +       // scriptSigLen=77
170                             "04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936" + // scriptSig
171                             "ffffffff" + // nSequence=uint.maxValue
172                             "01" +       // nOutputs=1
173                             "0000000000000000" + // nValue=0
174                             "00" +       // scriptPubkeyLen=0
175                             "00000000" + // nLockTime=0
176                             "00"         // sigLen=0
177                     ));
178
179                     // Write block to file.
180                     var itemTemplate = new CBlockStoreItem()
181                     {
182                         nHeight = 0
183                     };
184
185                     itemTemplate.FillHeader(genesisBlock.header);
186
187                     if (!AddItemToIndex(ref itemTemplate, ref genesisBlock))
188                     {
189                         throw new Exception("Unable to write genesis block");
190                     }
191                 }
192             }
193             else
194             {
195                 var blockTreeItems = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] order by [ItemId] asc");
196
197                 // Init list of block items
198                 foreach (var item in blockTreeItems)
199                 {
200                     blockMap.TryAdd(item.Hash, item);
201
202                     if (item.IsProofOfStake)
203                     {
204                         // build mapStakeSeen
205                         mapStakeSeen.TryAdd(item.prevoutStake, item.nStakeTime);
206                     }
207                 }
208
209                 // Load data about the top node.
210                 ChainParams = dbConn.Table<ChainState>().First();
211
212                 genesisBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])NetInfo.nHashGenesisBlock).First();
213                 bestBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", ChainParams.HashBestChain).First();
214             }
215         }
216
217         public bool GetTxOutCursor(COutPoint outpoint, ref TxOutItem txOutCursor)
218         {
219             var queryResults = dbConn.Query<TxOutItem>("select o.* from [Outputs] o left join [MerkleNodes] m on (m.nMerkleNodeID = o.nMerkleNodeID) where m.[TransactionHash] = ?", (byte[])outpoint.hash);
220
221             if (queryResults.Count == 1)
222             {
223                 txOutCursor = queryResults[0];
224
225                 return true;
226             }
227
228             // Tx not found
229
230             return false;
231         }
232         
233         public bool FetchInputs(CTransaction tx, ref Dictionary<COutPoint, TxOutItem> queued, ref Dictionary<COutPoint, TxOutItem> inputs, bool IsBlock, out bool Invalid)
234         {
235             Invalid = false;
236
237             if (tx.IsCoinBase)
238             {
239                 // Coinbase transactions have no inputs to fetch.
240                 return true;
241             }
242
243             StringBuilder queryBuilder = new StringBuilder();
244
245             queryBuilder.Append("select o.*, m.[TransactionHash] from [Outputs] o left join [MerkleNodes] m on (m.[nMerkleNodeID] = o.[nMerkleNodeID]) where ");
246
247             for (var i = 0; i < tx.vin.Length; i++)
248             {
249                 queryBuilder.AppendFormat(" {0} (m.[TransactionHash] = x'{1}' and o.[OutputNumber] = x'{2}')",
250                     (i > 0 ? "or" : string.Empty), Interop.ToHex(tx.vin[i].prevout.hash),
251                     Interop.ToHex(VarInt.EncodeVarInt(tx.vin[i].prevout.n)
252                 ));
253             }
254
255             var queryResults = dbConn.Query<InputsJoin>(queryBuilder.ToString());
256
257             foreach (var item in queryResults)
258             {
259                 if (item.IsSpent)
260                 {
261                     return false; // Already spent
262                 }
263
264                 var inputsKey = new COutPoint(item.TransactionHash, item.nOut);
265
266                 // Add output data to dictionary
267                 inputs.Add(inputsKey, item.getTxOutItem());
268             }
269
270             if (queryResults.Count < tx.vin.Length)
271             {
272                 if (IsBlock)
273                 {
274                     // It seems that some transactions are being spent in the same block.
275
276                     foreach (var txin in tx.vin)
277                     {
278                         var outPoint = txin.prevout;
279
280                         if (inputs.ContainsKey(outPoint))
281                         {
282                             continue; // We have already seen this input.
283                         }
284
285                         if (!queued.ContainsKey(outPoint))
286                         {
287                             return false; // No such transaction
288                         }
289
290                         // Add output data to dictionary
291                         inputs.Add(outPoint, queued[outPoint]);
292
293                         // Mark output as spent
294                         // queued[outPoint].IsSpent = true;
295                     }
296                 }
297                 else
298                 {
299                     // Unconfirmed transaction
300
301                     foreach (var txin in tx.vin)
302                     {
303                         var outPoint = txin.prevout;
304                         CTransaction txPrev;
305
306                         if (!mapUnconfirmedTx.TryGetValue(outPoint.hash, out txPrev))
307                         {
308                             return false; // No such transaction
309                         }
310
311                         if (outPoint.n > txPrev.vout.Length)
312                         {
313                             Invalid = true;
314
315                             return false; // nOut is out of range
316                         }
317
318                         // TODO: return inputs from map 
319                         throw new NotImplementedException();
320
321                     }
322
323                     return false;
324                 }
325             }
326
327             return true;
328         }
329
330         private bool AddItemToIndex(ref CBlockStoreItem itemTemplate, ref CBlock block)
331         {
332             uint256 blockHash = itemTemplate.Hash;
333
334             if (blockMap.ContainsKey(blockHash))
335             {
336                 // Already have this block.
337                 return false;
338             }
339
340             // Begin transaction
341             dbConn.BeginTransaction();
342
343             // Compute chain trust score
344             itemTemplate.nChainTrust = (itemTemplate.prev != null ? itemTemplate.prev.nChainTrust : 0) + itemTemplate.nBlockTrust;
345
346             if (!itemTemplate.SetStakeEntropyBit(Entropy.GetStakeEntropyBit(itemTemplate.nHeight, blockHash)))
347             {
348                 return false; // SetStakeEntropyBit() failed
349             }
350
351             // Save proof-of-stake hash value
352             if (itemTemplate.IsProofOfStake)
353             {
354                 uint256 hashProofOfStake;
355                 if (!GetProofOfStakeHash(blockHash, out hashProofOfStake))
356                 {
357                     return false;  // hashProofOfStake not found 
358                 }
359                 itemTemplate.hashProofOfStake = hashProofOfStake;
360             }
361
362             // compute stake modifier
363             long nStakeModifier = 0;
364             bool fGeneratedStakeModifier = false;
365             if (!StakeModifier.ComputeNextStakeModifier(itemTemplate, ref nStakeModifier, ref fGeneratedStakeModifier))
366             {
367                 return false;  // ComputeNextStakeModifier() failed
368             }
369
370             itemTemplate.SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
371             itemTemplate.nStakeModifierChecksum = StakeModifier.GetStakeModifierChecksum(itemTemplate);
372
373             // TODO: verify stake modifier checkpoints
374
375             // Add to index
376             if (block.IsProofOfStake)
377             {
378                 itemTemplate.SetProofOfStake();
379
380                 itemTemplate.prevoutStake = block.vtx[1].vin[0].prevout;
381                 itemTemplate.nStakeTime = block.vtx[1].nTime;
382             }
383
384             if (!itemTemplate.WriteToFile(ref fStreamReadWrite, ref block))
385             {
386                 return false;
387             }
388
389             if (dbConn.Insert(itemTemplate) == 0)
390             {
391                 return false; // Insert failed
392             }
393
394             // Get last RowID.
395             itemTemplate.ItemID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
396
397             if (!blockMap.TryAdd(blockHash, itemTemplate))
398             {
399                 return false; // blockMap add failed
400             }
401
402             if (itemTemplate.nChainTrust > ChainParams.nBestChainTrust)
403             {
404                 // New best chain
405
406                 if (!SetBestChain(ref itemTemplate))
407                 {
408                     return false; // SetBestChain failed.
409                 }
410             }
411
412             // Commit transaction
413             dbConn.Commit();
414
415             return true;
416         }
417
418         private bool SetBestChain(ref CBlockStoreItem cursor)
419         {
420             uint256 hashBlock = cursor.Hash;
421
422             if (genesisBlockCursor == null && hashBlock == NetInfo.nHashGenesisBlock)
423             {
424                 genesisBlockCursor = cursor;
425             }
426             else if (ChainParams.nHashBestChain == (uint256)cursor.prevHash)
427             {
428                 if (!SetBestChainInner(cursor))
429                 {
430                     return false;
431                 }
432             }
433             else
434             {
435                 // the first block in the new chain that will cause it to become the new best chain
436                 var cursorIntermediate = cursor;
437
438                 // list of blocks that need to be connected afterwards
439                 var secondary = new List<CBlockStoreItem>();
440
441                 // Reorganize is costly in terms of db load, as it works in a single db transaction.
442                 // Try to limit how much needs to be done inside
443                 while (cursorIntermediate.prev != null && cursorIntermediate.prev.nChainTrust > bestBlockCursor.nChainTrust)
444                 {
445                     secondary.Add(cursorIntermediate);
446                     cursorIntermediate = cursorIntermediate.prev;
447                 }
448
449                 // Switch to new best branch
450                 if (!Reorganize(cursorIntermediate))
451                 {
452                     InvalidChainFound(cursor);
453                     return false; // reorganize failed
454                 }
455
456                 // Connect further blocks
457                 foreach (var currentCursor in secondary)
458                 {
459                     CBlock block;
460                     if (!currentCursor.ReadFromFile(ref fStreamReadWrite, out block))
461                     {
462                         // ReadFromDisk failed
463                         break;
464                     }
465
466                     // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
467                     if (!SetBestChainInner(currentCursor))
468                     {
469                         break;
470                     }
471                 }
472             }
473
474             bestBlockCursor = cursor;
475             nTimeBestReceived = Interop.GetTime();
476             nTransactionsUpdated++;
477
478             if (!UpdateTopChain(cursor))
479             {
480                 return false; // unable to set top chain node.
481             }
482
483             return true;
484         }
485
486         private void InvalidChainFound(CBlockStoreItem cursor)
487         {
488             throw new NotImplementedException();
489         }
490
491         private bool Reorganize(CBlockStoreItem cursorIntermediate)
492         {
493             // Find the fork
494             var fork = bestBlockCursor;
495             var longer = cursorIntermediate;
496
497             while (fork.ItemID != longer.ItemID)
498             {
499                 while (longer.nHeight > fork.nHeight)
500                 {
501                     if ((longer = longer.prev) == null)
502                     {
503                         return false; // longer.prev is null
504                     }
505                 }
506
507                 if (fork.ItemID == longer.ItemID)
508                 {
509                     break;
510                 }
511
512                 if ((fork = fork.prev) == null)
513                 {
514                     return false; // fork.prev is null
515                 }
516             }
517
518             // List of what to disconnect
519             var disconnect = new List<CBlockStoreItem>();
520             for (var cursor = bestBlockCursor; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
521             {
522                 disconnect.Add(cursor);
523             }
524
525             // List of what to connect
526             var connect = new List<CBlockStoreItem>();
527             for (var cursor = cursorIntermediate; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
528             {
529                 connect.Add(cursor);
530             }
531             connect.Reverse();
532
533             // Disconnect shorter branch
534             var txResurrect = new List<CTransaction>();
535             foreach (var blockCursor in disconnect)
536             {
537                 CBlock block;
538                 if (!blockCursor.ReadFromFile(ref fStreamReadWrite, out block))
539                 {
540                     return false; // ReadFromFile for disconnect failed.
541                 }
542                 if (!DisconnectBlock(blockCursor, ref block))
543                 {
544                     return false; // DisconnectBlock failed.
545                 }
546
547                 // Queue memory transactions to resurrect
548                 foreach (var tx in block.vtx)
549                 {
550                     if (!tx.IsCoinBase && !tx.IsCoinStake)
551                     {
552                         txResurrect.Add(tx);
553                     }
554                 }
555             }
556
557
558             // Connect longer branch
559             var txDelete = new List<CTransaction>();
560             foreach (var cursor in connect)
561             {
562                 CBlock block;
563                 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
564                 {
565                     return false; // ReadFromDisk for connect failed
566                 }
567
568                 if (!ConnectBlock(cursor, ref block))
569                 {
570                     // Invalid block
571                     return false; // ConnectBlock failed
572                 }
573
574                 // Queue memory transactions to delete
575                 foreach (var tx in block.vtx)
576                 {
577                     txDelete.Add(tx);
578                 }
579             }
580
581             if (!UpdateTopChain(cursorIntermediate))
582             {
583                 return false; // UpdateTopChain failed
584             }
585
586             // Resurrect memory transactions that were in the disconnected branch
587             foreach (var tx in txResurrect)
588             {
589                 mapUnconfirmedTx.TryAdd(tx.Hash, tx);
590             }
591
592             // Delete redundant memory transactions that are in the connected branch
593             foreach (var tx in txDelete)
594             {
595                 CTransaction dummy;
596                 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
597             }
598
599             return true; // Done
600         }
601
602         private bool DisconnectBlock(CBlockStoreItem blockCursor, ref CBlock block)
603         {
604             throw new NotImplementedException();
605         }
606
607         private bool SetBestChainInner(CBlockStoreItem cursor)
608         {
609             uint256 hash = cursor.Hash;
610             CBlock block;
611             if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
612             {
613                 return false; // Unable to read block from file.
614             }
615
616             // Adding to current best branch
617             if (!ConnectBlock(cursor, ref block) || !UpdateTopChain(cursor))
618             {
619                 InvalidChainFound(cursor);
620                 return false;
621             }
622
623             // Add to current best branch
624             var prevCursor = cursor.prev;
625             prevCursor.next = cursor;
626
627             if (!UpdateDBCursor(ref prevCursor))
628             {
629                 return false; // unable to update
630             }
631
632             // Delete redundant memory transactions
633             foreach (var tx in block.vtx)
634             {
635                 CTransaction dummy;
636                 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
637             }
638
639             return true;
640         }
641
642         private bool ConnectBlock(CBlockStoreItem cursor, ref CBlock block, bool fJustCheck = false)
643         {
644             // Check it again in case a previous version let a bad block in, but skip BlockSig checking
645             if (!block.CheckBlock(!fJustCheck, !fJustCheck, false))
646             {
647                 return false; // Invalid block found.
648             }
649
650             bool fScriptChecks = cursor.nHeight >= Checkpoints.TotalBlocksEstimate;
651             var scriptFlags = scriptflag.SCRIPT_VERIFY_NOCACHE | scriptflag.SCRIPT_VERIFY_P2SH;
652
653             ulong nFees = 0;
654             ulong nValueIn = 0;
655             ulong nValueOut = 0;
656             uint nSigOps = 0;
657
658             var queuedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
659             var queuedOutputs = new Dictionary<COutPoint, TxOutItem>();
660
661             for (var nTx = 0; nTx < block.vtx.Length; nTx++)
662             {
663                 var tx = block.vtx[nTx];
664                 var hashTx = tx.Hash;
665
666                 if (!queuedMerkleNodes.ContainsKey(hashTx))
667                 {
668                     var nTxPos = cursor.nBlockPos + block.GetTxOffset(nTx);
669                     var mNode = new CMerkleNode(cursor.ItemID, nTxPos, tx);
670
671                     queuedMerkleNodes.Add(hashTx, mNode);
672                 }
673
674                 Dictionary<COutPoint, TxOutItem> txouts;
675                 if (GetOutputs(hashTx, out txouts))
676                 {
677                     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
678                     // unless those are already completely spent.
679                     return false;
680                 }
681
682                 nSigOps += tx.LegacySigOpCount;
683                 if (nSigOps > CBlock.nMaxSigOps)
684                 {
685                     return false; // too many sigops
686                 }
687
688                 var inputs = new Dictionary<COutPoint, TxOutItem>();
689
690                 if (tx.IsCoinBase)
691                 {
692                     nValueOut += tx.nValueOut;
693                 }
694                 else
695                 {
696                     bool Invalid;
697                     if (!FetchInputs(tx, ref queuedOutputs, ref inputs, true, out Invalid))
698                     {
699                         return false; // Unable to fetch some inputs.
700                     }
701
702                     // Add in sigops done by pay-to-script-hash inputs;
703                     // this is to prevent a "rogue miner" from creating
704                     // an incredibly-expensive-to-validate block.
705                     nSigOps += tx.GetP2SHSigOpCount(ref inputs);
706                     if (nSigOps > CBlock.nMaxSigOps)
707                     {
708                         return false; // too many sigops
709                     }
710
711                     ulong nTxValueIn = tx.GetValueIn(ref inputs);
712                     ulong nTxValueOut = tx.nValueOut;
713
714                     nValueIn += nTxValueIn;
715                     nValueOut += nTxValueOut;
716
717                     if (!tx.IsCoinStake)
718                     {
719                         nFees += nTxValueIn - nTxValueOut;
720                     }
721
722                     if (!ConnectInputs(tx, ref inputs, ref queuedOutputs, ref cursor, true, fScriptChecks, scriptFlags))
723                     {
724                         return false;
725                     }
726                 }
727
728                 for (var i = 0u; i < tx.vout.Length; i++)
729                 {
730                     var outKey = new COutPoint(hashTx, i);
731                     var outData = new TxOutItem()
732                     {
733                         nMerkleNodeID = -1,
734                         nValue = tx.vout[i].nValue,
735                         scriptPubKey = tx.vout[i].scriptPubKey,
736                         IsSpent = false,
737                         nOut = i
738                     };
739
740                     queuedOutputs.Add(outKey, outData);
741                 }
742             }
743
744             if (!block.IsProofOfStake)
745             {
746                 ulong nBlockReward = CBlock.GetProofOfWorkReward(cursor.nBits, nFees);
747
748                 // Check coinbase reward
749                 if (block.vtx[0].nValueOut > nBlockReward)
750                 {
751                     return false; // coinbase reward exceeded
752                 }
753             }
754
755             cursor.nMint = (long)(nValueOut - nValueIn + nFees);
756             cursor.nMoneySupply = (cursor.prev != null ? cursor.prev.nMoneySupply : 0) + (long)nValueOut - (long)nValueIn;
757
758             if (!UpdateDBCursor(ref cursor))
759             {
760                 return false; // Unable to commit changes
761             }
762
763             if (fJustCheck)
764             {
765                 return true;
766             }
767
768             // Flush merkle nodes.
769             var savedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
770             foreach (var merklePair in queuedMerkleNodes)
771             {
772                 var merkleNode = merklePair.Value;
773
774                 if (!SaveMerkleNode(ref merkleNode))
775                 {
776                     // Unable to save merkle tree cursor.
777                     return false;
778                 }
779
780                 savedMerkleNodes.Add(merklePair.Key, merkleNode);
781             }
782
783             // Write queued transaction changes
784             var newOutpointItems = new List<TxOutItem>();
785             var updatedOutpointItems = new List<TxOutItem>();
786             foreach (var outPair in queuedOutputs)
787             {
788                 var outItem = outPair.Value;
789
790                 if (outItem.nMerkleNodeID == -1)
791                 {
792                     // This outpoint doesn't exist yet, adding to insert list.
793
794                     outItem.nMerkleNodeID = savedMerkleNodes[outPair.Key.hash].nMerkleNodeID;
795                     newOutpointItems.Add(outItem);
796                 }
797                 else
798                 {
799                     // This outpount already exists, adding to update list.
800
801                     updatedOutpointItems.Add(outItem);
802                 }
803             }
804
805             if (updatedOutpointItems.Count != 0 && !UpdateOutpoints(ref updatedOutpointItems))
806             {
807                 return false; // Unable to update outpoints
808             }
809
810             if (newOutpointItems.Count != 0 && !InsertOutpoints(ref newOutpointItems))
811             {
812                 return false; // Unable to insert outpoints
813             }
814
815             return true;
816         }
817
818         /// <summary>
819         /// Insert set of new outpoints
820         /// </summary>
821         /// <param name="newOutpointItems">List of TxOutItem objects.</param>
822         /// <returns>Result</returns>
823         private bool InsertOutpoints(ref List<TxOutItem> newOutpointItems)
824         {
825             return (dbConn.InsertAll(newOutpointItems, false) != 0);
826         }
827
828
829         /// <summary>
830         /// Update set of outpoints
831         /// </summary>
832         /// <param name="queuedOutpointItems">List of TxOutItem objects.</param>
833         /// <returns>Result</returns>
834         private bool UpdateOutpoints(ref List<TxOutItem> updatedOutpointItems)
835         {
836             return (dbConn.UpdateAll(updatedOutpointItems, false) != 0);
837         }
838
839         /// <summary>
840         /// Insert merkle node into db and set actual record id value.
841         /// </summary>
842         /// <param name="merkleNode">Merkle node object reference.</param>
843         /// <returns>Result</returns>
844         private bool SaveMerkleNode(ref CMerkleNode merkleNode)
845         {
846             if (dbConn.Insert(merkleNode) == 0)
847             {
848                 return false;
849             }
850
851             merkleNode.nMerkleNodeID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
852
853             return true;
854         }
855
856         private bool ConnectInputs(CTransaction tx, ref Dictionary<COutPoint, TxOutItem> inputs, ref Dictionary<COutPoint, TxOutItem> queued, ref CBlockStoreItem cursorBlock, bool fBlock, bool fScriptChecks, scriptflag scriptFlags)
857         {
858             // Take over previous transactions' spent items
859             // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
860
861             if (!tx.IsCoinBase)
862             {
863                 ulong nValueIn = 0;
864                 ulong nFees = 0;
865                 for (uint i = 0; i < tx.vin.Length; i++)
866                 {
867                     var prevout = tx.vin[i].prevout;
868                     Contract.Assert(inputs.ContainsKey(prevout));
869                     var input = inputs[prevout];
870
871                     CBlockStoreItem parentBlockCursor;
872
873                     if (input.nMerkleNodeID == -1)
874                     {
875                         // This input seems as is confirmed by the same block.
876
877                         if (!queued.ContainsKey(prevout))
878                         {
879                             return false; // No such output has been queued by this block.
880                         }
881
882                         // TODO: Ensure that neither coinbase nor coinstake outputs are 
883                         //    available for spending in the generation block.
884                     }
885                     else
886                     {
887                         // This input has been confirmed by one of the earlier accepted blocks.
888
889                         var merkleItem = GetMerkleCursor(input, out parentBlockCursor);
890
891                         if (merkleItem == null)
892                         {
893                             return false; // Unable to find merkle node
894                         }
895
896                         // If prev is coinbase or coinstake, check that it's matured
897                         if (merkleItem.IsCoinBase || merkleItem.IsCoinStake)
898                         {
899                             if (cursorBlock.nHeight - parentBlockCursor.nHeight < NetInfo.nGeneratedMaturity)
900                             {
901                                 return false; // tried to spend non-matured generation input.
902                             }
903                         }
904
905                         // check transaction timestamp
906                         if (merkleItem.nTime > tx.nTime)
907                         {
908                             return false; // transaction timestamp earlier than input transaction
909                         }
910                     }
911
912                     // Check for negative or overflow input values
913                     nValueIn += input.nValue;
914                     if (!CTransaction.MoneyRange(input.nValue) || !CTransaction.MoneyRange(nValueIn))
915                     {
916                         return false; // txin values out of range
917                     }
918
919                 }
920
921                 // The first loop above does all the inexpensive checks.
922                 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
923                 // Helps prevent CPU exhaustion attacks.
924                 for (int i = 0; i < tx.vin.Length; i++)
925                 {
926                     var prevout = tx.vin[i].prevout;
927                     Contract.Assert(inputs.ContainsKey(prevout));
928                     var input = inputs[prevout];
929
930                     // Check for conflicts (double-spend)
931                     if (input.IsSpent)
932                     {
933                         return false;
934                     }
935
936                     // Skip ECDSA signature verification when connecting blocks (fBlock=true)
937                     // before the last blockchain checkpoint. This is safe because block merkle hashes are
938                     // still computed and checked, and any change will be caught at the next checkpoint.
939                     if (fScriptChecks)
940                     {
941                         // Verify signature
942                         if (!ScriptCode.VerifyScript(tx.vin[i].scriptSig, input.scriptPubKey, tx, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
943                         {
944                             return false; // VerifyScript failed.
945                         }
946                     }
947
948                     // Mark outpoint as spent
949                     input.IsSpent = true;
950                     inputs[prevout] = input;
951
952                     // Write back
953                     if (fBlock)
954                     {
955                         if (input.nMerkleNodeID != -1)
956                         {
957                             // Input has been confirmed earlier.
958                             queued.Add(prevout, input);
959                         }
960                         else
961                         {
962                             // Input has been confirmed by current block.
963                             queued[prevout] = input;
964                         }
965                     }
966                 }
967
968                 if (tx.IsCoinStake)
969                 {
970                     // ppcoin: coin stake tx earns reward instead of paying fee
971                     ulong nCoinAge;
972                     if (!tx.GetCoinAge(ref inputs, out nCoinAge))
973                     {
974                         return false; // unable to get coin age for coinstake
975                     }
976
977                     ulong nReward = tx.nValueOut - nValueIn;
978
979                     ulong nCalculatedReward = CBlock.GetProofOfStakeReward(nCoinAge, cursorBlock.nBits, tx.nTime) - tx.GetMinFee(1, false, CTransaction.MinFeeMode.GMF_BLOCK) + CTransaction.nCent;
980
981                     if (nReward > nCalculatedReward)
982                     {
983                         return false; // coinstake pays too much
984                     }
985                 }
986                 else
987                 {
988                     if (nValueIn < tx.nValueOut)
989                     {
990                         return false; // value in < value out
991                     }
992
993                     // Tally transaction fees
994                     ulong nTxFee = nValueIn - tx.nValueOut;
995                     if (nTxFee < 0)
996                     {
997                         return false; // nTxFee < 0
998                     }
999
1000                     nFees += nTxFee;
1001
1002                     if (!CTransaction.MoneyRange(nFees))
1003                     {
1004                         return false; // nFees out of range
1005                     }
1006                 }
1007                 
1008             }
1009
1010             return true;
1011         }
1012
1013
1014         /// <summary>
1015         /// Set new top node or current best chain.
1016         /// </summary>
1017         /// <param name="cursor"></param>
1018         /// <returns></returns>
1019         private bool UpdateTopChain(CBlockStoreItem cursor)
1020         {
1021             ChainParams.HashBestChain = cursor.Hash;
1022             ChainParams.nBestChainTrust = cursor.nChainTrust;
1023             ChainParams.nBestHeight = cursor.nHeight;
1024
1025             return dbConn.Update(ChainParams) != 0;
1026         }
1027
1028         /// <summary>
1029         /// Try to find proof-of-stake hash in the map.
1030         /// </summary>
1031         /// <param name="blockHash">Block hash</param>
1032         /// <param name="hashProofOfStake">Proof-of-stake hash</param>
1033         /// <returns>Proof-of-Stake hash value</returns>
1034         private bool GetProofOfStakeHash(uint256 blockHash, out uint256 hashProofOfStake)
1035         {
1036             return mapProofOfStake.TryGetValue(blockHash, out hashProofOfStake);
1037         }
1038
1039         public bool AcceptBlock(ref CBlock block)
1040         {
1041             uint256 nHash = block.header.Hash;
1042
1043             if (blockMap.ContainsKey(nHash))
1044             {
1045                 // Already have this block.
1046                 return false;
1047             }
1048
1049             CBlockStoreItem prevBlockCursor = null;
1050             if (!blockMap.TryGetValue(block.header.prevHash, out prevBlockCursor))
1051             {
1052                 // Unable to get the cursor.
1053                 return false;
1054             }
1055
1056             var prevBlockHeader = prevBlockCursor.BlockHeader;
1057
1058             // TODO: proof-of-work/proof-of-stake verification
1059             uint nHeight = prevBlockCursor.nHeight + 1;
1060
1061             // Check timestamp against prev
1062             if (NetInfo.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
1063             {
1064                 // block's timestamp is too early
1065                 return false;
1066             }
1067
1068             // Check that all transactions are finalized
1069             foreach (var tx in block.vtx)
1070             {
1071                 if (!tx.IsFinal(nHeight, block.header.nTime))
1072                 {
1073                     return false;
1074                 }
1075             }
1076
1077             // TODO: Enforce rule that the coinbase starts with serialized block height
1078
1079             // Write block to file.
1080             var itemTemplate = new CBlockStoreItem()
1081             {
1082                 nHeight = nHeight,
1083             };
1084
1085             itemTemplate.FillHeader(block.header);
1086
1087             if (!AddItemToIndex(ref itemTemplate, ref block))
1088             {
1089                 dbConn.Rollback();
1090
1091                 return false;
1092             }
1093
1094             return true;
1095         }
1096
1097         /// <summary>
1098         /// GEt block by hash.
1099         /// </summary>
1100         /// <param name="blockHash">Block hash</param>
1101         /// <param name="block">Block object reference</param>
1102         /// <param name="nBlockPos">Block position reference</param>
1103         /// <returns>Result</returns>
1104         public bool GetBlock(uint256 blockHash, ref CBlock block, ref long nBlockPos)
1105         {
1106             CBlockStoreItem cursor;
1107
1108             if (!blockMap.TryGetValue(blockHash, out cursor))
1109             {
1110                 return false; // Unable to fetch block cursor
1111             }
1112
1113             nBlockPos = cursor.nBlockPos;
1114
1115             return cursor.ReadFromFile(ref fStreamReadWrite, out block);
1116         }
1117
1118         /// <summary>
1119         /// Get block and transaction by transaction hash.
1120         /// </summary>
1121         /// <param name="TxID">Transaction hash</param>
1122         /// <param name="block">Block reference</param>
1123         /// <param name="nBlockPos">Block position reference</param>
1124         /// <returns>Result of operation</returns>
1125         public bool GetBlockByTransactionID(uint256 TxID, out CBlock block, out long nBlockPos)
1126         {
1127             block = null;
1128             nBlockPos = -1;
1129
1130             var queryResult = dbConn.Query<CBlockStoreItem>("select b.* from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
1131
1132             if (queryResult.Count == 1)
1133             {
1134                 CBlockStoreItem blockCursor = queryResult[0];
1135
1136                 nBlockPos = blockCursor.nBlockPos;
1137
1138                 return blockCursor.ReadFromFile(ref fStreamReadWrite, out block);
1139             }
1140
1141             // Tx not found
1142
1143             return false;
1144         }
1145
1146         public bool GetOutputs(uint256 transactionHash, out Dictionary<COutPoint, TxOutItem> txouts, bool fUnspentOnly=true)
1147         {
1148             txouts = null;
1149
1150             var queryParams = new object[] { (byte[])transactionHash, fUnspentOnly ? OutputFlags.AVAILABLE : (OutputFlags.AVAILABLE | OutputFlags.SPENT) };
1151             var queryResult = dbConn.Query<TxOutItem>("select o.* from [Outputs] o left join [MerkleNodes] m on m.[nMerkleNodeID] = o.[nMerkleNodeID] where m.[TransactionHash] = ? and outputFlags = ?", queryParams);
1152
1153             if (queryResult.Count != 0)
1154             {
1155                 txouts = new Dictionary<COutPoint, TxOutItem>();
1156
1157                 foreach (var o in queryResult)
1158                 {
1159                     var outpointKey = new COutPoint(transactionHash, o.nOut);
1160                     var outpointData = o;
1161
1162                     txouts.Add(outpointKey, outpointData);
1163                 }
1164
1165                 // There are some unspent inputs.
1166                 return true;
1167             }
1168
1169             // This transaction has been spent completely.
1170             return false;
1171         }
1172
1173         /// <summary>
1174         /// Get block cursor from map.
1175         /// </summary>
1176         /// <param name="blockHash">block hash</param>
1177         /// <returns>Cursor or null</returns>
1178         public CBlockStoreItem GetMapCursor(uint256 blockHash)
1179         {
1180             if (blockHash == 0)
1181             {
1182                 // Genesis block has zero prevHash and no parent.
1183                 return null;
1184             }
1185
1186             CBlockStoreItem cursor = null;
1187             blockMap.TryGetValue(blockHash, out cursor);
1188
1189             return cursor;
1190         }
1191
1192         /// <summary>
1193         /// Get merkle node cursor by output metadata.
1194         /// </summary>
1195         /// <param name="item">Output metadata object</param>
1196         /// <returns>Merkle node cursor or null</returns>
1197         public CMerkleNode GetMerkleCursor(TxOutItem item, out CBlockStoreItem blockCursor)
1198         {
1199             blockCursor = null;
1200
1201             // Trying to get cursor from the database.
1202             var QueryMerkleCursor = dbConn.Query<CMerkleNode>("select * from [MerkleNodes] where [nMerkleNodeID] = ?", item.nMerkleNodeID);
1203
1204             if (QueryMerkleCursor.Count == 1)
1205             {
1206                 var merkleNode = QueryMerkleCursor[0];
1207
1208                 // Search for block
1209                 var results = blockMap.Where(x => x.Value.ItemID == merkleNode.nParentBlockID).Select(x => x.Value).ToArray();
1210
1211                 blockCursor = results[0];
1212
1213                 return merkleNode;
1214             }
1215
1216             // Nothing found.
1217             return null;
1218         }
1219
1220         /// <summary>
1221         /// Load cursor from database.
1222         /// </summary>
1223         /// <param name="blockHash">Block hash</param>
1224         /// <returns>Block cursor object</returns>
1225         public CBlockStoreItem GetDBCursor(uint256 blockHash)
1226         {
1227             // Trying to get cursor from the database.
1228             var QueryBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
1229
1230             if (QueryBlockCursor.Count == 1)
1231             {
1232                 return QueryBlockCursor[0];
1233             }
1234
1235             // Nothing found.
1236             return null;
1237         }
1238
1239         /// <summary>
1240         /// Update cursor in memory and on disk.
1241         /// </summary>
1242         /// <param name="cursor">Block cursor</param>
1243         /// <returns>Result</returns>
1244         public bool UpdateMapCursor(CBlockStoreItem cursor)
1245         {
1246             var original = blockMap[cursor.Hash];
1247             return blockMap.TryUpdate(cursor.Hash, cursor, original);
1248         }
1249
1250         /// <summary>
1251         /// Update cursor record in database.
1252         /// </summary>
1253         /// <param name="cursor">Block cursor object</param>
1254         /// <returns>Result</returns>
1255         public bool UpdateDBCursor(ref CBlockStoreItem cursor)
1256         {
1257             return dbConn.Update(cursor) != 0;
1258         }
1259
1260         public bool ProcessBlock(ref CBlock block)
1261         {
1262             var blockHash = block.header.Hash;
1263
1264             if (blockMap.ContainsKey(blockHash))
1265             {
1266                 // We already have this block.
1267                 return false;
1268             }
1269
1270             if (orphanMap.ContainsKey(blockHash))
1271             {
1272                 // We already have block in the list of orphans.
1273                 return false;
1274             }
1275
1276             // TODO: Limited duplicity on stake and reserialization of block signature
1277
1278             if (!block.CheckBlock(true, true, true))
1279             {
1280                 // Preliminary checks failure.
1281                 return false;
1282             }
1283
1284             if (block.IsProofOfStake)
1285             {
1286                 if (!block.SignatureOK)
1287                 {
1288                     // Proof-of-Stake signature validation failure.
1289                     return false;
1290                 }
1291
1292                 // TODO: proof-of-stake validation
1293
1294                 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1295                 if (!StakeModifier.CheckProofOfStake(block.vtx[1], block.header.nBits, out hashProofOfStake, out targetProofOfStake))
1296                 {
1297                     return false; // do not error here as we expect this during initial block download
1298                 }
1299                 if (!mapProofOfStake.ContainsKey(blockHash)) 
1300                 {
1301                     // add to mapProofOfStake
1302                     mapProofOfStake.TryAdd(blockHash, hashProofOfStake);
1303                 }
1304
1305             }
1306
1307             // TODO: difficulty verification
1308
1309             // If don't already have its previous block, shunt it off to holding area until we get it
1310             if (!blockMap.ContainsKey(block.header.prevHash))
1311             {
1312                 if (block.IsProofOfStake)
1313                 {
1314                     // TODO: limit duplicity on stake
1315                 }
1316
1317                 var block2 = new CBlock(block);
1318                 orphanMap.TryAdd(blockHash, block2);
1319                 orphanMapByPrev.TryAdd(blockHash, block2);
1320
1321                 return true;
1322             }
1323
1324             // Store block to disk
1325             if (!AcceptBlock(ref block))
1326             {
1327                 // Accept failed
1328                 return false;
1329             }
1330
1331             // Recursively process any orphan blocks that depended on this one
1332             var orphansQueue = new List<uint256>();
1333             orphansQueue.Add(blockHash);
1334
1335             for (int i = 0; i < orphansQueue.Count; i++)
1336             {
1337                 var hashPrev = orphansQueue[i];
1338
1339                 foreach (var pair in orphanMap)
1340                 {
1341                     var orphanBlock = pair.Value;
1342
1343                     if (orphanBlock.header.prevHash == blockHash)
1344                     {
1345                         if (AcceptBlock(ref orphanBlock))
1346                         {
1347                             orphansQueue.Add(pair.Key);
1348                         }
1349
1350                         CBlock dummy1;
1351                         orphanMap.TryRemove(pair.Key, out dummy1);
1352                     }
1353                 }
1354
1355                 CBlock dummy2;
1356                 orphanMap.TryRemove(hashPrev, out dummy2);
1357             }
1358
1359             return true;
1360         }
1361
1362         public bool ParseBlockFile(string BlockFile = "bootstrap.dat")
1363         {
1364             // TODO: Rewrite completely.
1365
1366             var nOffset = 0L;
1367
1368             var buffer = new byte[CBlock.nMaxBlockSize]; // Max block size is 1Mb
1369             var intBuffer = new byte[4];
1370
1371             var fStream2 = File.OpenRead(BlockFile);
1372
1373             fStream2.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
1374
1375             while (fStream2.Read(buffer, 0, 4) == 4) // Read magic number
1376             {
1377                 var nMagic = BitConverter.ToUInt32(buffer, 0);
1378                 if (nMagic != 0xe5e9e8e4)
1379                 {
1380                     throw new Exception("Incorrect magic number.");
1381                 }
1382
1383                 var nBytesRead = fStream2.Read(buffer, 0, 4);
1384                 if (nBytesRead != 4)
1385                 {
1386                     throw new Exception("BLKSZ EOF");
1387                 }
1388
1389                 var nBlockSize = BitConverter.ToInt32(buffer, 0);
1390
1391                 nOffset = fStream2.Position;
1392
1393                 nBytesRead = fStream2.Read(buffer, 0, nBlockSize);
1394
1395                 if (nBytesRead == 0 || nBytesRead != nBlockSize)
1396                 {
1397                     throw new Exception("BLK EOF");
1398                 }
1399
1400                 var block = new CBlock(buffer);
1401                 var hash = block.header.Hash;
1402
1403                 if (blockMap.ContainsKey(hash))
1404                 {
1405                     continue;
1406                 }
1407
1408                 if (!ProcessBlock(ref block))
1409                 {
1410                     throw new Exception("Invalid block: " + block.header.Hash);
1411                 }
1412
1413                 int nCount = blockMap.Count;
1414                 Console.WriteLine("nCount={0}, Hash={1}, NumTx={2}, Time={3}", nCount, block.header.Hash, block.vtx.Length, DateTime.Now); // Commit on each 100th block
1415
1416                 /*
1417                 if (nCount % 100 == 0 && nCount != 0)
1418                 {
1419                     Console.WriteLine("Commit...");
1420                     dbConn.Commit();
1421                     dbConn.BeginTransaction();
1422                 }*/
1423             }
1424
1425             return true;
1426         }
1427
1428         ~CBlockStore()
1429         {
1430             Dispose(false);
1431         }
1432
1433         public void Dispose()
1434         {
1435             Dispose(true);
1436             GC.SuppressFinalize(this);
1437         }
1438
1439         protected virtual void Dispose(bool disposing)
1440         {
1441             if (!disposed)
1442             {
1443                 if (disposing)
1444                 {
1445                     // Free other state (managed objects).
1446
1447                     fStreamReadWrite.Dispose();
1448                 }
1449
1450                 if (dbConn != null)
1451                 {
1452                     dbConn.Close();
1453                     dbConn = null;
1454                 }
1455
1456                 disposed = true;
1457             }
1458         }
1459
1460     }
1461 }