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