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