Save proof-of-stake kernel hash.
[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                 itemTemplate.hashProofOfStake = mapProofOfStake[blockHash];
383             }
384
385             if (!itemTemplate.WriteToFile(ref fStreamReadWrite, ref block))
386             {
387                 return false;
388             }
389
390             if (dbConn.Insert(itemTemplate) == 0)
391             {
392                 return false; // Insert failed
393             }
394
395             // Get last RowID.
396             itemTemplate.ItemID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
397
398             if (!blockMap.TryAdd(blockHash, itemTemplate))
399             {
400                 return false; // blockMap add failed
401             }
402
403             if (itemTemplate.nChainTrust > ChainParams.nBestChainTrust)
404             {
405                 // New best chain
406
407                 if (!SetBestChain(ref itemTemplate))
408                 {
409                     return false; // SetBestChain failed.
410                 }
411             }
412
413             // Commit transaction
414             dbConn.Commit();
415
416             return true;
417         }
418
419         private bool SetBestChain(ref CBlockStoreItem cursor)
420         {
421             uint256 hashBlock = cursor.Hash;
422
423             if (genesisBlockCursor == null && hashBlock == NetInfo.nHashGenesisBlock)
424             {
425                 genesisBlockCursor = cursor;
426             }
427             else if (ChainParams.nHashBestChain == (uint256)cursor.prevHash)
428             {
429                 if (!SetBestChainInner(cursor))
430                 {
431                     return false;
432                 }
433             }
434             else
435             {
436                 // the first block in the new chain that will cause it to become the new best chain
437                 var cursorIntermediate = cursor;
438
439                 // list of blocks that need to be connected afterwards
440                 var secondary = new List<CBlockStoreItem>();
441
442                 // Reorganize is costly in terms of db load, as it works in a single db transaction.
443                 // Try to limit how much needs to be done inside
444                 while (cursorIntermediate.prev != null && cursorIntermediate.prev.nChainTrust > bestBlockCursor.nChainTrust)
445                 {
446                     secondary.Add(cursorIntermediate);
447                     cursorIntermediate = cursorIntermediate.prev;
448                 }
449
450                 // Switch to new best branch
451                 if (!Reorganize(cursorIntermediate))
452                 {
453                     InvalidChainFound(cursor);
454                     return false; // reorganize failed
455                 }
456
457                 // Connect further blocks
458                 foreach (var currentCursor in secondary)
459                 {
460                     CBlock block;
461                     if (!currentCursor.ReadFromFile(ref fStreamReadWrite, out block))
462                     {
463                         // ReadFromDisk failed
464                         break;
465                     }
466
467                     // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
468                     if (!SetBestChainInner(currentCursor))
469                     {
470                         break;
471                     }
472                 }
473             }
474
475             bestBlockCursor = cursor;
476             nTimeBestReceived = Interop.GetTime();
477             nTransactionsUpdated++;
478
479             if (!UpdateTopChain(cursor))
480             {
481                 return false; // unable to set top chain node.
482             }
483
484             return true;
485         }
486
487         private void InvalidChainFound(CBlockStoreItem cursor)
488         {
489             throw new NotImplementedException();
490         }
491
492         private bool Reorganize(CBlockStoreItem cursorIntermediate)
493         {
494             // Find the fork
495             var fork = bestBlockCursor;
496             var longer = cursorIntermediate;
497
498             while (fork.ItemID != longer.ItemID)
499             {
500                 while (longer.nHeight > fork.nHeight)
501                 {
502                     if ((longer = longer.prev) == null)
503                     {
504                         return false; // longer.prev is null
505                     }
506                 }
507
508                 if (fork.ItemID == longer.ItemID)
509                 {
510                     break;
511                 }
512
513                 if ((fork = fork.prev) == null)
514                 {
515                     return false; // fork.prev is null
516                 }
517             }
518
519             // List of what to disconnect
520             var disconnect = new List<CBlockStoreItem>();
521             for (var cursor = bestBlockCursor; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
522             {
523                 disconnect.Add(cursor);
524             }
525
526             // List of what to connect
527             var connect = new List<CBlockStoreItem>();
528             for (var cursor = cursorIntermediate; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
529             {
530                 connect.Add(cursor);
531             }
532             connect.Reverse();
533
534             // Disconnect shorter branch
535             var txResurrect = new List<CTransaction>();
536             foreach (var blockCursor in disconnect)
537             {
538                 CBlock block;
539                 if (!blockCursor.ReadFromFile(ref fStreamReadWrite, out block))
540                 {
541                     return false; // ReadFromFile for disconnect failed.
542                 }
543                 if (!DisconnectBlock(blockCursor, ref block))
544                 {
545                     return false; // DisconnectBlock failed.
546                 }
547
548                 // Queue memory transactions to resurrect
549                 foreach (var tx in block.vtx)
550                 {
551                     if (!tx.IsCoinBase && !tx.IsCoinStake)
552                     {
553                         txResurrect.Add(tx);
554                     }
555                 }
556             }
557
558
559             // Connect longer branch
560             var txDelete = new List<CTransaction>();
561             foreach (var cursor in connect)
562             {
563                 CBlock block;
564                 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
565                 {
566                     return false; // ReadFromDisk for connect failed
567                 }
568
569                 if (!ConnectBlock(cursor, ref block))
570                 {
571                     // Invalid block
572                     return false; // ConnectBlock failed
573                 }
574
575                 // Queue memory transactions to delete
576                 foreach (var tx in block.vtx)
577                 {
578                     txDelete.Add(tx);
579                 }
580             }
581
582             if (!UpdateTopChain(cursorIntermediate))
583             {
584                 return false; // UpdateTopChain failed
585             }
586
587             // Resurrect memory transactions that were in the disconnected branch
588             foreach (var tx in txResurrect)
589             {
590                 mapUnconfirmedTx.TryAdd(tx.Hash, tx);
591             }
592
593             // Delete redundant memory transactions that are in the connected branch
594             foreach (var tx in txDelete)
595             {
596                 CTransaction dummy;
597                 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
598             }
599
600             return true; // Done
601         }
602
603         private bool DisconnectBlock(CBlockStoreItem blockCursor, ref CBlock block)
604         {
605             throw new NotImplementedException();
606         }
607
608         private bool SetBestChainInner(CBlockStoreItem cursor)
609         {
610             uint256 hash = cursor.Hash;
611             CBlock block;
612             if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
613             {
614                 return false; // Unable to read block from file.
615             }
616
617             // Adding to current best branch
618             if (!ConnectBlock(cursor, ref block) || !UpdateTopChain(cursor))
619             {
620                 InvalidChainFound(cursor);
621                 return false;
622             }
623
624             // Add to current best branch
625             var prevCursor = cursor.prev;
626             prevCursor.next = cursor;
627
628             if (!UpdateDBCursor(ref prevCursor))
629             {
630                 return false; // unable to update
631             }
632
633             // Delete redundant memory transactions
634             foreach (var tx in block.vtx)
635             {
636                 CTransaction dummy;
637                 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
638             }
639
640             return true;
641         }
642
643         private bool ConnectBlock(CBlockStoreItem cursor, ref CBlock block, bool fJustCheck = false)
644         {
645             // Check it again in case a previous version let a bad block in, but skip BlockSig checking
646             if (!block.CheckBlock(!fJustCheck, !fJustCheck, false))
647             {
648                 return false; // Invalid block found.
649             }
650
651             bool fScriptChecks = cursor.nHeight >= Checkpoints.TotalBlocksEstimate;
652             var scriptFlags = scriptflag.SCRIPT_VERIFY_NOCACHE | scriptflag.SCRIPT_VERIFY_P2SH;
653
654             ulong nFees = 0;
655             ulong nValueIn = 0;
656             ulong nValueOut = 0;
657             uint nSigOps = 0;
658
659             var queuedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
660             var queuedOutputs = new Dictionary<COutPoint, TxOutItem>();
661
662             for (var nTx = 0; nTx < block.vtx.Length; nTx++)
663             {
664                 var tx = block.vtx[nTx];
665                 var hashTx = tx.Hash;
666
667                 if (!queuedMerkleNodes.ContainsKey(hashTx))
668                 {
669                     var nTxPos = cursor.nBlockPos + block.GetTxOffset(nTx);
670                     var mNode = new CMerkleNode(cursor.ItemID, nTxPos, tx);
671
672                     queuedMerkleNodes.Add(hashTx, mNode);
673                 }
674
675                 Dictionary<COutPoint, TxOutItem> txouts;
676                 if (GetOutputs(hashTx, out txouts))
677                 {
678                     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
679                     // unless those are already completely spent.
680                     return false;
681                 }
682
683                 nSigOps += tx.LegacySigOpCount;
684                 if (nSigOps > CBlock.nMaxSigOps)
685                 {
686                     return false; // too many sigops
687                 }
688
689                 var inputs = new Dictionary<COutPoint, TxOutItem>();
690
691                 if (tx.IsCoinBase)
692                 {
693                     nValueOut += tx.nValueOut;
694                 }
695                 else
696                 {
697                     bool Invalid;
698                     if (!FetchInputs(tx, ref queuedOutputs, ref inputs, true, out Invalid))
699                     {
700                         return false; // Unable to fetch some inputs.
701                     }
702
703                     // Add in sigops done by pay-to-script-hash inputs;
704                     // this is to prevent a "rogue miner" from creating
705                     // an incredibly-expensive-to-validate block.
706                     nSigOps += tx.GetP2SHSigOpCount(ref inputs);
707                     if (nSigOps > CBlock.nMaxSigOps)
708                     {
709                         return false; // too many sigops
710                     }
711
712                     ulong nTxValueIn = tx.GetValueIn(ref inputs);
713                     ulong nTxValueOut = tx.nValueOut;
714
715                     nValueIn += nTxValueIn;
716                     nValueOut += nTxValueOut;
717
718                     if (!tx.IsCoinStake)
719                     {
720                         nFees += nTxValueIn - nTxValueOut;
721                     }
722
723                     if (!ConnectInputs(tx, ref inputs, ref queuedOutputs, ref cursor, true, fScriptChecks, scriptFlags))
724                     {
725                         return false;
726                     }
727                 }
728
729                 for (var i = 0u; i < tx.vout.Length; i++)
730                 {
731                     var outKey = new COutPoint(hashTx, i);
732                     var outData = new TxOutItem()
733                     {
734                         nMerkleNodeID = -1,
735                         nValue = tx.vout[i].nValue,
736                         scriptPubKey = tx.vout[i].scriptPubKey,
737                         IsSpent = false,
738                         nOut = i
739                     };
740
741                     queuedOutputs.Add(outKey, outData);
742                 }
743             }
744
745             if (!block.IsProofOfStake)
746             {
747                 ulong nBlockReward = CBlock.GetProofOfWorkReward(cursor.nBits, nFees);
748
749                 // Check coinbase reward
750                 if (block.vtx[0].nValueOut > nBlockReward)
751                 {
752                     return false; // coinbase reward exceeded
753                 }
754             }
755
756             cursor.nMint = (long)(nValueOut - nValueIn + nFees);
757             cursor.nMoneySupply = (cursor.prev != null ? cursor.prev.nMoneySupply : 0) + (long)nValueOut - (long)nValueIn;
758
759             if (!UpdateDBCursor(ref cursor))
760             {
761                 return false; // Unable to commit changes
762             }
763
764             if (fJustCheck)
765             {
766                 return true;
767             }
768
769             // Flush merkle nodes.
770             var savedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
771             foreach (var merklePair in queuedMerkleNodes)
772             {
773                 var merkleNode = merklePair.Value;
774
775                 if (!SaveMerkleNode(ref merkleNode))
776                 {
777                     // Unable to save merkle tree cursor.
778                     return false;
779                 }
780
781                 savedMerkleNodes.Add(merklePair.Key, merkleNode);
782             }
783
784             // Write queued transaction changes
785             var newOutpointItems = new List<TxOutItem>();
786             var updatedOutpointItems = new List<TxOutItem>();
787             foreach (var outPair in queuedOutputs)
788             {
789                 var outItem = outPair.Value;
790
791                 if (outItem.nMerkleNodeID == -1)
792                 {
793                     // This outpoint doesn't exist yet, adding to insert list.
794
795                     outItem.nMerkleNodeID = savedMerkleNodes[outPair.Key.hash].nMerkleNodeID;
796                     newOutpointItems.Add(outItem);
797                 }
798                 else
799                 {
800                     // This outpount already exists, adding to update list.
801
802                     updatedOutpointItems.Add(outItem);
803                 }
804             }
805
806             if (updatedOutpointItems.Count != 0 && !UpdateOutpoints(ref updatedOutpointItems))
807             {
808                 return false; // Unable to update outpoints
809             }
810
811             if (newOutpointItems.Count != 0 && !InsertOutpoints(ref newOutpointItems))
812             {
813                 return false; // Unable to insert outpoints
814             }
815
816             return true;
817         }
818
819         /// <summary>
820         /// Insert set of new outpoints
821         /// </summary>
822         /// <param name="newOutpointItems">List of TxOutItem objects.</param>
823         /// <returns>Result</returns>
824         private bool InsertOutpoints(ref List<TxOutItem> newOutpointItems)
825         {
826             return (dbConn.InsertAll(newOutpointItems, false) != 0);
827         }
828
829
830         /// <summary>
831         /// Update set of outpoints
832         /// </summary>
833         /// <param name="queuedOutpointItems">List of TxOutItem objects.</param>
834         /// <returns>Result</returns>
835         private bool UpdateOutpoints(ref List<TxOutItem> updatedOutpointItems)
836         {
837             return (dbConn.UpdateAll(updatedOutpointItems, false) != 0);
838         }
839
840         /// <summary>
841         /// Insert merkle node into db and set actual record id value.
842         /// </summary>
843         /// <param name="merkleNode">Merkle node object reference.</param>
844         /// <returns>Result</returns>
845         private bool SaveMerkleNode(ref CMerkleNode merkleNode)
846         {
847             if (dbConn.Insert(merkleNode) == 0)
848             {
849                 return false;
850             }
851
852             merkleNode.nMerkleNodeID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
853
854             return true;
855         }
856
857         private bool ConnectInputs(CTransaction tx, ref Dictionary<COutPoint, TxOutItem> inputs, ref Dictionary<COutPoint, TxOutItem> queued, ref CBlockStoreItem cursorBlock, bool fBlock, bool fScriptChecks, scriptflag scriptFlags)
858         {
859             // Take over previous transactions' spent items
860             // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
861
862             if (!tx.IsCoinBase)
863             {
864                 ulong nValueIn = 0;
865                 ulong nFees = 0;
866                 for (uint i = 0; i < tx.vin.Length; i++)
867                 {
868                     var prevout = tx.vin[i].prevout;
869                     Contract.Assert(inputs.ContainsKey(prevout));
870                     var input = inputs[prevout];
871
872                     CBlockStoreItem parentBlockCursor;
873
874                     if (input.nMerkleNodeID == -1)
875                     {
876                         // This input seems as is confirmed by the same block.
877
878                         if (!queued.ContainsKey(prevout))
879                         {
880                             return false; // No such output has been queued by this block.
881                         }
882
883                         // TODO: Ensure that neither coinbase nor coinstake outputs are 
884                         //    available for spending in the generation block.
885                     }
886                     else
887                     {
888                         // This input has been confirmed by one of the earlier accepted blocks.
889
890                         var merkleItem = GetMerkleCursor(input, out parentBlockCursor);
891
892                         if (merkleItem == null)
893                         {
894                             return false; // Unable to find merkle node
895                         }
896
897                         // If prev is coinbase or coinstake, check that it's matured
898                         if (merkleItem.IsCoinBase || merkleItem.IsCoinStake)
899                         {
900                             if (cursorBlock.nHeight - parentBlockCursor.nHeight < NetInfo.nGeneratedMaturity)
901                             {
902                                 return false; // tried to spend non-matured generation input.
903                             }
904                         }
905
906                         // check transaction timestamp
907                         if (merkleItem.nTime > tx.nTime)
908                         {
909                             return false; // transaction timestamp earlier than input transaction
910                         }
911                     }
912
913                     // Check for negative or overflow input values
914                     nValueIn += input.nValue;
915                     if (!CTransaction.MoneyRange(input.nValue) || !CTransaction.MoneyRange(nValueIn))
916                     {
917                         return false; // txin values out of range
918                     }
919
920                 }
921
922                 // The first loop above does all the inexpensive checks.
923                 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
924                 // Helps prevent CPU exhaustion attacks.
925                 for (int i = 0; i < tx.vin.Length; i++)
926                 {
927                     var prevout = tx.vin[i].prevout;
928                     Contract.Assert(inputs.ContainsKey(prevout));
929                     var input = inputs[prevout];
930
931                     // Check for conflicts (double-spend)
932                     if (input.IsSpent)
933                     {
934                         return false;
935                     }
936
937                     // Skip ECDSA signature verification when connecting blocks (fBlock=true)
938                     // before the last blockchain checkpoint. This is safe because block merkle hashes are
939                     // still computed and checked, and any change will be caught at the next checkpoint.
940                     if (fScriptChecks)
941                     {
942                         // Verify signature
943                         if (!ScriptCode.VerifyScript(tx.vin[i].scriptSig, input.scriptPubKey, tx, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
944                         {
945                             return false; // VerifyScript failed.
946                         }
947                     }
948
949                     // Mark outpoint as spent
950                     input.IsSpent = true;
951                     inputs[prevout] = input;
952
953                     // Write back
954                     if (fBlock)
955                     {
956                         if (input.nMerkleNodeID != -1)
957                         {
958                             // Input has been confirmed earlier.
959                             queued.Add(prevout, input);
960                         }
961                         else
962                         {
963                             // Input has been confirmed by current block.
964                             queued[prevout] = input;
965                         }
966                     }
967                 }
968
969                 if (tx.IsCoinStake)
970                 {
971                     // ppcoin: coin stake tx earns reward instead of paying fee
972                     ulong nCoinAge;
973                     if (!tx.GetCoinAge(ref inputs, out nCoinAge))
974                     {
975                         return false; // unable to get coin age for coinstake
976                     }
977
978                     ulong nReward = tx.nValueOut - nValueIn;
979
980                     ulong nCalculatedReward = CBlock.GetProofOfStakeReward(nCoinAge, cursorBlock.nBits, tx.nTime) - tx.GetMinFee(1, false, CTransaction.MinFeeMode.GMF_BLOCK) + CTransaction.nCent;
981
982                     if (nReward > nCalculatedReward)
983                     {
984                         return false; // coinstake pays too much
985                     }
986                 }
987                 else
988                 {
989                     if (nValueIn < tx.nValueOut)
990                     {
991                         return false; // value in < value out
992                     }
993
994                     // Tally transaction fees
995                     ulong nTxFee = nValueIn - tx.nValueOut;
996                     if (nTxFee < 0)
997                     {
998                         return false; // nTxFee < 0
999                     }
1000
1001                     nFees += nTxFee;
1002
1003                     if (!CTransaction.MoneyRange(nFees))
1004                     {
1005                         return false; // nFees out of range
1006                     }
1007                 }
1008                 
1009             }
1010
1011             return true;
1012         }
1013
1014
1015         /// <summary>
1016         /// Set new top node or current best chain.
1017         /// </summary>
1018         /// <param name="cursor"></param>
1019         /// <returns></returns>
1020         private bool UpdateTopChain(CBlockStoreItem cursor)
1021         {
1022             ChainParams.HashBestChain = cursor.Hash;
1023             ChainParams.nBestChainTrust = cursor.nChainTrust;
1024             ChainParams.nBestHeight = cursor.nHeight;
1025
1026             return dbConn.Update(ChainParams) != 0;
1027         }
1028
1029         /// <summary>
1030         /// Try to find proof-of-stake hash in the map.
1031         /// </summary>
1032         /// <param name="blockHash">Block hash</param>
1033         /// <param name="hashProofOfStake">Proof-of-stake hash</param>
1034         /// <returns>Proof-of-Stake hash value</returns>
1035         private bool GetProofOfStakeHash(uint256 blockHash, out uint256 hashProofOfStake)
1036         {
1037             return mapProofOfStake.TryGetValue(blockHash, out hashProofOfStake);
1038         }
1039
1040         public bool AcceptBlock(ref CBlock block)
1041         {
1042             uint256 nHash = block.header.Hash;
1043
1044             if (blockMap.ContainsKey(nHash))
1045             {
1046                 // Already have this block.
1047                 return false;
1048             }
1049
1050             CBlockStoreItem prevBlockCursor = null;
1051             if (!blockMap.TryGetValue(block.header.prevHash, out prevBlockCursor))
1052             {
1053                 // Unable to get the cursor.
1054                 return false;
1055             }
1056
1057             var prevBlockHeader = prevBlockCursor.BlockHeader;
1058
1059             // TODO: proof-of-work/proof-of-stake verification
1060             uint nHeight = prevBlockCursor.nHeight + 1;
1061
1062             // Check timestamp against prev
1063             if (NetInfo.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
1064             {
1065                 // block's timestamp is too early
1066                 return false;
1067             }
1068
1069             // Check that all transactions are finalized
1070             foreach (var tx in block.vtx)
1071             {
1072                 if (!tx.IsFinal(nHeight, block.header.nTime))
1073                 {
1074                     return false;
1075                 }
1076             }
1077
1078             // TODO: Enforce rule that the coinbase starts with serialized block height
1079
1080             // Write block to file.
1081             var itemTemplate = new CBlockStoreItem()
1082             {
1083                 nHeight = nHeight,
1084             };
1085
1086             itemTemplate.FillHeader(block.header);
1087
1088             if (!AddItemToIndex(ref itemTemplate, ref block))
1089             {
1090                 dbConn.Rollback();
1091
1092                 return false;
1093             }
1094
1095             return true;
1096         }
1097
1098         /// <summary>
1099         /// GEt block by hash.
1100         /// </summary>
1101         /// <param name="blockHash">Block hash</param>
1102         /// <param name="block">Block object reference</param>
1103         /// <param name="nBlockPos">Block position reference</param>
1104         /// <returns>Result</returns>
1105         public bool GetBlock(uint256 blockHash, ref CBlock block, ref long nBlockPos)
1106         {
1107             CBlockStoreItem cursor;
1108
1109             if (!blockMap.TryGetValue(blockHash, out cursor))
1110             {
1111                 return false; // Unable to fetch block cursor
1112             }
1113
1114             nBlockPos = cursor.nBlockPos;
1115
1116             return cursor.ReadFromFile(ref fStreamReadWrite, out block);
1117         }
1118
1119         /// <summary>
1120         /// Get block and transaction by transaction hash.
1121         /// </summary>
1122         /// <param name="TxID">Transaction hash</param>
1123         /// <param name="block">Block reference</param>
1124         /// <param name="nBlockPos">Block position reference</param>
1125         /// <returns>Result of operation</returns>
1126         public bool GetBlockByTransactionID(uint256 TxID, out CBlock block, out long nBlockPos)
1127         {
1128             block = null;
1129             nBlockPos = -1;
1130
1131             var queryResult = dbConn.Query<CBlockStoreItem>("select b.* from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
1132
1133             if (queryResult.Count == 1)
1134             {
1135                 CBlockStoreItem blockCursor = queryResult[0];
1136
1137                 nBlockPos = blockCursor.nBlockPos;
1138
1139                 return blockCursor.ReadFromFile(ref fStreamReadWrite, out block);
1140             }
1141
1142             // Tx not found
1143
1144             return false;
1145         }
1146
1147         public bool GetOutputs(uint256 transactionHash, out Dictionary<COutPoint, TxOutItem> txouts, bool fUnspentOnly=true)
1148         {
1149             txouts = null;
1150
1151             var queryParams = new object[] { (byte[])transactionHash, fUnspentOnly ? OutputFlags.AVAILABLE : (OutputFlags.AVAILABLE | OutputFlags.SPENT) };
1152             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);
1153
1154             if (queryResult.Count != 0)
1155             {
1156                 txouts = new Dictionary<COutPoint, TxOutItem>();
1157
1158                 foreach (var o in queryResult)
1159                 {
1160                     var outpointKey = new COutPoint(transactionHash, o.nOut);
1161                     var outpointData = o;
1162
1163                     txouts.Add(outpointKey, outpointData);
1164                 }
1165
1166                 // There are some unspent inputs.
1167                 return true;
1168             }
1169
1170             // This transaction has been spent completely.
1171             return false;
1172         }
1173
1174         /// <summary>
1175         /// Get block cursor from map.
1176         /// </summary>
1177         /// <param name="blockHash">block hash</param>
1178         /// <returns>Cursor or null</returns>
1179         public CBlockStoreItem GetMapCursor(uint256 blockHash)
1180         {
1181             if (blockHash == 0)
1182             {
1183                 // Genesis block has zero prevHash and no parent.
1184                 return null;
1185             }
1186
1187             CBlockStoreItem cursor = null;
1188             blockMap.TryGetValue(blockHash, out cursor);
1189
1190             return cursor;
1191         }
1192
1193         /// <summary>
1194         /// Get merkle node cursor by output metadata.
1195         /// </summary>
1196         /// <param name="item">Output metadata object</param>
1197         /// <returns>Merkle node cursor or null</returns>
1198         public CMerkleNode GetMerkleCursor(TxOutItem item, out CBlockStoreItem blockCursor)
1199         {
1200             blockCursor = null;
1201
1202             // Trying to get cursor from the database.
1203             var QueryMerkleCursor = dbConn.Query<CMerkleNode>("select * from [MerkleNodes] where [nMerkleNodeID] = ?", item.nMerkleNodeID);
1204
1205             if (QueryMerkleCursor.Count == 1)
1206             {
1207                 var merkleNode = QueryMerkleCursor[0];
1208
1209                 // Search for block
1210                 var results = blockMap.Where(x => x.Value.ItemID == merkleNode.nParentBlockID).Select(x => x.Value).ToArray();
1211
1212                 blockCursor = results[0];
1213
1214                 return merkleNode;
1215             }
1216
1217             // Nothing found.
1218             return null;
1219         }
1220
1221         /// <summary>
1222         /// Load cursor from database.
1223         /// </summary>
1224         /// <param name="blockHash">Block hash</param>
1225         /// <returns>Block cursor object</returns>
1226         public CBlockStoreItem GetDBCursor(uint256 blockHash)
1227         {
1228             // Trying to get cursor from the database.
1229             var QueryBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
1230
1231             if (QueryBlockCursor.Count == 1)
1232             {
1233                 return QueryBlockCursor[0];
1234             }
1235
1236             // Nothing found.
1237             return null;
1238         }
1239
1240         /// <summary>
1241         /// Update cursor in memory and on disk.
1242         /// </summary>
1243         /// <param name="cursor">Block cursor</param>
1244         /// <returns>Result</returns>
1245         public bool UpdateMapCursor(CBlockStoreItem cursor)
1246         {
1247             var original = blockMap[cursor.Hash];
1248             return blockMap.TryUpdate(cursor.Hash, cursor, original);
1249         }
1250
1251         /// <summary>
1252         /// Update cursor record in database.
1253         /// </summary>
1254         /// <param name="cursor">Block cursor object</param>
1255         /// <returns>Result</returns>
1256         public bool UpdateDBCursor(ref CBlockStoreItem cursor)
1257         {
1258             return dbConn.Update(cursor) != 0;
1259         }
1260
1261         public bool ProcessBlock(ref CBlock block)
1262         {
1263             var blockHash = block.header.Hash;
1264
1265             if (blockMap.ContainsKey(blockHash))
1266             {
1267                 // We already have this block.
1268                 return false;
1269             }
1270
1271             if (orphanMap.ContainsKey(blockHash))
1272             {
1273                 // We already have block in the list of orphans.
1274                 return false;
1275             }
1276
1277             // TODO: Limited duplicity on stake and reserialization of block signature
1278
1279             if (!block.CheckBlock(true, true, true))
1280             {
1281                 // Preliminary checks failure.
1282                 return false;
1283             }
1284
1285             if (block.IsProofOfStake)
1286             {
1287                 if (!block.SignatureOK)
1288                 {
1289                     // Proof-of-Stake signature validation failure.
1290                     return false;
1291                 }
1292
1293                 // TODO: proof-of-stake validation
1294
1295                 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1296                 if (!StakeModifier.CheckProofOfStake(block.vtx[1], block.header.nBits, out hashProofOfStake, out targetProofOfStake))
1297                 {
1298                     return false; // do not error here as we expect this during initial block download
1299                 }
1300                 if (!mapProofOfStake.ContainsKey(blockHash)) 
1301                 {
1302                     // add to mapProofOfStake
1303                     mapProofOfStake.TryAdd(blockHash, hashProofOfStake);
1304                 }
1305
1306             }
1307
1308             // TODO: difficulty verification
1309
1310             // If don't already have its previous block, shunt it off to holding area until we get it
1311             if (!blockMap.ContainsKey(block.header.prevHash))
1312             {
1313                 if (block.IsProofOfStake)
1314                 {
1315                     // TODO: limit duplicity on stake
1316                 }
1317
1318                 var block2 = new CBlock(block);
1319                 orphanMap.TryAdd(blockHash, block2);
1320                 orphanMapByPrev.TryAdd(blockHash, block2);
1321
1322                 return true;
1323             }
1324
1325             // Store block to disk
1326             if (!AcceptBlock(ref block))
1327             {
1328                 // Accept failed
1329                 return false;
1330             }
1331
1332             // Recursively process any orphan blocks that depended on this one
1333             var orphansQueue = new List<uint256>();
1334             orphansQueue.Add(blockHash);
1335
1336             for (int i = 0; i < orphansQueue.Count; i++)
1337             {
1338                 var hashPrev = orphansQueue[i];
1339
1340                 foreach (var pair in orphanMap)
1341                 {
1342                     var orphanBlock = pair.Value;
1343
1344                     if (orphanBlock.header.prevHash == blockHash)
1345                     {
1346                         if (AcceptBlock(ref orphanBlock))
1347                         {
1348                             orphansQueue.Add(pair.Key);
1349                         }
1350
1351                         CBlock dummy1;
1352                         orphanMap.TryRemove(pair.Key, out dummy1);
1353                     }
1354                 }
1355
1356                 CBlock dummy2;
1357                 orphanMap.TryRemove(hashPrev, out dummy2);
1358             }
1359
1360             return true;
1361         }
1362
1363         public bool ParseBlockFile(string BlockFile = "bootstrap.dat")
1364         {
1365             // TODO: Rewrite completely.
1366
1367             var nOffset = 0L;
1368
1369             var buffer = new byte[CBlock.nMaxBlockSize]; // Max block size is 1Mb
1370             var intBuffer = new byte[4];
1371
1372             var fStream2 = File.OpenRead(BlockFile);
1373
1374             fStream2.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
1375
1376             while (fStream2.Read(buffer, 0, 4) == 4) // Read magic number
1377             {
1378                 var nMagic = BitConverter.ToUInt32(buffer, 0);
1379                 if (nMagic != 0xe5e9e8e4)
1380                 {
1381                     throw new Exception("Incorrect magic number.");
1382                 }
1383
1384                 var nBytesRead = fStream2.Read(buffer, 0, 4);
1385                 if (nBytesRead != 4)
1386                 {
1387                     throw new Exception("BLKSZ EOF");
1388                 }
1389
1390                 var nBlockSize = BitConverter.ToInt32(buffer, 0);
1391
1392                 nOffset = fStream2.Position;
1393
1394                 nBytesRead = fStream2.Read(buffer, 0, nBlockSize);
1395
1396                 if (nBytesRead == 0 || nBytesRead != nBlockSize)
1397                 {
1398                     throw new Exception("BLK EOF");
1399                 }
1400
1401                 var block = new CBlock(buffer);
1402                 var hash = block.header.Hash;
1403
1404                 if (blockMap.ContainsKey(hash))
1405                 {
1406                     continue;
1407                 }
1408
1409                 if (!ProcessBlock(ref block))
1410                 {
1411                     throw new Exception("Invalid block: " + block.header.Hash);
1412                 }
1413
1414                 int nCount = blockMap.Count;
1415                 Console.WriteLine("nCount={0}, Hash={1}, NumTx={2}, Time={3}", nCount, block.header.Hash, block.vtx.Length, DateTime.Now); // Commit on each 100th block
1416
1417                 /*
1418                 if (nCount % 100 == 0 && nCount != 0)
1419                 {
1420                     Console.WriteLine("Commit...");
1421                     dbConn.Commit();
1422                     dbConn.BeginTransaction();
1423                 }*/
1424             }
1425
1426             return true;
1427         }
1428
1429         ~CBlockStore()
1430         {
1431             Dispose(false);
1432         }
1433
1434         public void Dispose()
1435         {
1436             Dispose(true);
1437             GC.SuppressFinalize(this);
1438         }
1439
1440         protected virtual void Dispose(bool disposing)
1441         {
1442             if (!disposed)
1443             {
1444                 if (disposing)
1445                 {
1446                     // Free other state (managed objects).
1447
1448                     fStreamReadWrite.Dispose();
1449                 }
1450
1451                 if (dbConn != null)
1452                 {
1453                     dbConn.Close();
1454                     dbConn = null;
1455                 }
1456
1457                 disposed = true;
1458             }
1459         }
1460
1461     }
1462 }