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