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