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