2 * Novacoin classes library
3 * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
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.
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.
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/>.
22 using System.Collections.Concurrent;
25 using SQLite.Net.Interop;
26 using SQLite.Net.Platform.Generic;
27 using System.Collections.Generic;
29 using System.Diagnostics.Contracts;
34 public class CBlockStore : IDisposable
36 public const uint nMagicNumber = 0xe5e9e8e4;
38 private bool disposed = false;
39 private object LockObj = new object();
42 /// SQLite connection object.
44 private SQLiteConnection dbConn;
47 /// Current SQLite platform
49 private ISQLitePlatform dbPlatform;
54 private string strBlockFile;
57 /// Index database file.
59 private string strDbFile;
62 /// Map of block tree nodes.
64 /// blockHash => CBlockStoreItem
66 private ConcurrentDictionary<uint256, CBlockStoreItem> blockMap = new ConcurrentDictionary<uint256, CBlockStoreItem>();
69 /// Orphaned blocks map.
71 private ConcurrentDictionary<uint256, CBlock> orphanMap = new ConcurrentDictionary<uint256, CBlock>();
72 private ConcurrentDictionary<uint256, CBlock> orphanMapByPrev = new ConcurrentDictionary<uint256, CBlock>();
75 /// Unconfirmed transactions.
77 /// TxID => Transaction
79 private ConcurrentDictionary<uint256, CTransaction> mapUnconfirmedTx = new ConcurrentDictionary<uint256, CTransaction>();
82 /// Map of the proof-of-stake hashes. This is necessary for stake duplication checks.
84 private ConcurrentDictionary<uint256, uint256> mapProofOfStake = new ConcurrentDictionary<uint256, uint256>();
87 private ConcurrentDictionary<COutPoint, uint> mapStakeSeen = new ConcurrentDictionary<COutPoint, uint>();
88 private ConcurrentDictionary<COutPoint, uint> mapStakeSeenOrphan = new ConcurrentDictionary<COutPoint, uint>();
92 /// Copy of chain state object.
94 private ChainState ChainParams;
97 /// Cursor which is pointing us to the end of best chain.
99 private CBlockStoreItem bestBlockCursor = null;
102 /// Cursor which is always pointing us to genesis block.
104 private CBlockStoreItem genesisBlockCursor = null;
107 /// Current and the only instance of block storage manager. Should be a property with private setter though it's enough for the beginning.
109 public static CBlockStore Instance = null;
112 /// Block file stream with read/write access
114 private Stream fStreamReadWrite;
115 private uint nTimeBestReceived;
116 private int nTransactionsUpdated;
119 /// Init the block storage manager.
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")
126 strBlockFile = BlockFile;
128 bool firstInit = !File.Exists(strDbFile);
129 dbPlatform = new SQLitePlatformGeneric();
130 dbConn = new SQLiteConnection(dbPlatform, strDbFile);
132 fStreamReadWrite = File.Open(strBlockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
141 dbConn.CreateTable<CBlockStoreItem>(CreateFlags.AutoIncPK);
142 dbConn.CreateTable<CMerkleNode>(CreateFlags.AutoIncPK);
143 dbConn.CreateTable<TxOutItem>(CreateFlags.ImplicitPK);
144 dbConn.CreateTable<ChainState>(CreateFlags.AutoIncPK);
146 ChainParams = new ChainState()
153 dbConn.Insert(ChainParams);
155 var genesisBlock = new CBlock(
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
164 "01000000" + // nVersion=1
165 "398e1151" + // nTime=1360105017
167 "0000000000000000000000000000000000000000000000000000000000000000" + // input txid is zero
168 "ffffffff" + // n=uint.maxValue
169 "4d" + // scriptSigLen=77
170 "04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936" + // scriptSig
171 "ffffffff" + // nSequence=uint.maxValue
173 "0000000000000000" + // nValue=0
174 "00" + // scriptPubkeyLen=0
175 "00000000" + // nLockTime=0
179 // Write block to file.
180 var itemTemplate = new CBlockStoreItem()
185 itemTemplate.FillHeader(genesisBlock.header);
187 if (!AddItemToIndex(ref itemTemplate, ref genesisBlock))
189 throw new Exception("Unable to write genesis block");
195 var blockTreeItems = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] order by [ItemId] asc");
197 // Init list of block items
198 foreach (var item in blockTreeItems)
200 blockMap.TryAdd(item.Hash, item);
202 if (item.IsProofOfStake)
204 // build mapStakeSeen
205 mapStakeSeen.TryAdd(item.prevoutStake, item.nStakeTime);
209 // Load data about the top node.
210 ChainParams = dbConn.Table<ChainState>().First();
212 genesisBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])NetInfo.nHashGenesisBlock).First();
213 bestBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", ChainParams.HashBestChain).First();
217 public bool GetTxOutCursor(COutPoint outpoint, out TxOutItem txOutCursor)
219 var queryResults = dbConn.Query<TxOutItem>("select o.* from [Outputs] o left join [MerkleNodes] m on (m.nMerkleNodeID = o.nMerkleNodeID) where m.[TransactionHash] = ?", (byte[])outpoint.hash);
221 if (queryResults.Count == 1)
223 txOutCursor = queryResults[0];
235 public bool FetchInputs(ref CTransaction tx, ref Dictionary<COutPoint, TxOutItem> queued, ref Dictionary<COutPoint, TxOutItem> inputs, bool IsBlock, out bool Invalid)
241 // Coinbase transactions have no inputs to fetch.
245 StringBuilder queryBuilder = new StringBuilder();
247 queryBuilder.Append("select o.*, m.[TransactionHash] from [Outputs] o left join [MerkleNodes] m on (m.[nMerkleNodeID] = o.[nMerkleNodeID]) where ");
249 for (var i = 0; i < tx.vin.Length; i++)
251 queryBuilder.AppendFormat(" {0} (m.[TransactionHash] = x'{1}' and o.[OutputNumber] = x'{2}')",
252 (i > 0 ? "or" : string.Empty), Interop.ToHex(tx.vin[i].prevout.hash),
253 Interop.ToHex(VarInt.EncodeVarInt(tx.vin[i].prevout.n)
257 var queryResults = dbConn.Query<InputsJoin>(queryBuilder.ToString());
259 foreach (var item in queryResults)
263 return false; // Already spent
266 var inputsKey = new COutPoint(item.TransactionHash, item.nOut);
268 // Add output data to dictionary
269 inputs.Add(inputsKey, item.getTxOutItem());
272 if (queryResults.Count < tx.vin.Length)
276 // It seems that some transactions are being spent in the same block.
278 foreach (var txin in tx.vin)
280 var outPoint = txin.prevout;
282 if (inputs.ContainsKey(outPoint))
284 continue; // We have already seen this input.
287 if (!queued.ContainsKey(outPoint))
289 return false; // No such transaction
292 // Add output data to dictionary
293 inputs.Add(outPoint, queued[outPoint]);
295 // Mark output as spent
296 // queued[outPoint].IsSpent = true;
301 // Unconfirmed transaction
303 foreach (var txin in tx.vin)
305 var outPoint = txin.prevout;
308 if (!mapUnconfirmedTx.TryGetValue(outPoint.hash, out txPrev))
310 return false; // No such transaction
313 if (outPoint.n > txPrev.vout.Length)
317 return false; // nOut is out of range
320 // TODO: return inputs from map
321 throw new NotImplementedException();
332 private bool AddItemToIndex(ref CBlockStoreItem itemTemplate, ref CBlock block)
334 uint256 blockHash = itemTemplate.Hash;
336 if (blockMap.ContainsKey(blockHash))
338 // Already have this block.
343 dbConn.BeginTransaction();
345 // Compute chain trust score
346 itemTemplate.nChainTrust = (itemTemplate.prev != null ? itemTemplate.prev.nChainTrust : 0) + itemTemplate.nBlockTrust;
348 if (!itemTemplate.SetStakeEntropyBit(Entropy.GetStakeEntropyBit(itemTemplate.nHeight, blockHash)))
350 return false; // SetStakeEntropyBit() failed
353 // compute stake modifier
354 long nStakeModifier = 0;
355 bool fGeneratedStakeModifier = false;
356 if (!StakeModifier.ComputeNextStakeModifier(itemTemplate, ref nStakeModifier, ref fGeneratedStakeModifier))
358 return false; // ComputeNextStakeModifier() failed
361 itemTemplate.SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
362 itemTemplate.nStakeModifierChecksum = StakeModifier.GetStakeModifierChecksum(ref itemTemplate);
364 // TODO: verify stake modifier checkpoints
367 if (block.IsProofOfStake)
369 itemTemplate.SetProofOfStake();
371 itemTemplate.prevoutStake = block.vtx[1].vin[0].prevout;
372 itemTemplate.nStakeTime = block.vtx[1].nTime;
374 // Save proof-of-stake hash value
375 uint256 hashProofOfStake;
376 if (!GetProofOfStakeHash(ref blockHash, out hashProofOfStake))
378 return false; // hashProofOfStake not found
380 itemTemplate.hashProofOfStake = hashProofOfStake;
383 if (!itemTemplate.WriteToFile(ref fStreamReadWrite, ref block))
388 if (dbConn.Insert(itemTemplate) == 0)
390 return false; // Insert failed
394 itemTemplate.ItemID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
396 if (!blockMap.TryAdd(blockHash, itemTemplate))
398 return false; // blockMap add failed
401 if (itemTemplate.nChainTrust > ChainParams.nBestChainTrust)
405 if (!SetBestChain(ref itemTemplate))
407 return false; // SetBestChain failed.
411 // Commit transaction
417 private bool SetBestChain(ref CBlockStoreItem cursor)
419 uint256 hashBlock = cursor.Hash;
421 if (genesisBlockCursor == null && hashBlock == NetInfo.nHashGenesisBlock)
423 genesisBlockCursor = cursor;
425 else if (ChainParams.nHashBestChain == (uint256)cursor.prevHash)
427 if (!SetBestChainInner(cursor))
434 // the first block in the new chain that will cause it to become the new best chain
435 var cursorIntermediate = cursor;
437 // list of blocks that need to be connected afterwards
438 var secondary = new List<CBlockStoreItem>();
440 // Reorganize is costly in terms of db load, as it works in a single db transaction.
441 // Try to limit how much needs to be done inside
442 while (cursorIntermediate.prev != null && cursorIntermediate.prev.nChainTrust > bestBlockCursor.nChainTrust)
444 secondary.Add(cursorIntermediate);
445 cursorIntermediate = cursorIntermediate.prev;
448 // Switch to new best branch
449 if (!Reorganize(cursorIntermediate))
451 InvalidChainFound(cursor);
452 return false; // reorganize failed
455 // Connect further blocks
456 foreach (var currentCursor in secondary)
459 if (!currentCursor.ReadFromFile(ref fStreamReadWrite, out block))
461 // ReadFromDisk failed
465 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
466 if (!SetBestChainInner(currentCursor))
473 bestBlockCursor = cursor;
474 nTimeBestReceived = Interop.GetTime();
475 nTransactionsUpdated++;
477 if (!UpdateTopChain(cursor))
479 return false; // unable to set top chain node.
485 private void InvalidChainFound(CBlockStoreItem cursor)
487 throw new NotImplementedException();
490 private bool Reorganize(CBlockStoreItem cursorIntermediate)
493 var fork = bestBlockCursor;
494 var longer = cursorIntermediate;
496 while (fork.ItemID != longer.ItemID)
498 while (longer.nHeight > fork.nHeight)
500 if ((longer = longer.prev) == null)
502 return false; // longer.prev is null
506 if (fork.ItemID == longer.ItemID)
511 if ((fork = fork.prev) == null)
513 return false; // fork.prev is null
517 // List of what to disconnect
518 var disconnect = new List<CBlockStoreItem>();
519 for (var cursor = bestBlockCursor; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
521 disconnect.Add(cursor);
524 // List of what to connect
525 var connect = new List<CBlockStoreItem>();
526 for (var cursor = cursorIntermediate; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
532 // Disconnect shorter branch
533 var txResurrect = new List<CTransaction>();
534 foreach (var blockCursor in disconnect)
537 if (!blockCursor.ReadFromFile(ref fStreamReadWrite, out block))
539 return false; // ReadFromFile for disconnect failed.
541 if (!DisconnectBlock(blockCursor, ref block))
543 return false; // DisconnectBlock failed.
546 // Queue memory transactions to resurrect
547 foreach (var tx in block.vtx)
549 if (!tx.IsCoinBase && !tx.IsCoinStake)
556 // Connect longer branch
557 var txDelete = new List<CTransaction>();
558 foreach (var cursor in connect)
561 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
563 return false; // ReadFromDisk for connect failed
566 if (!ConnectBlock(cursor, ref block))
569 return false; // ConnectBlock failed
572 // Queue memory transactions to delete
573 foreach (var tx in block.vtx)
579 if (!UpdateTopChain(cursorIntermediate))
581 return false; // UpdateTopChain failed
584 // Resurrect memory transactions that were in the disconnected branch
585 foreach (var tx in txResurrect)
587 mapUnconfirmedTx.TryAdd(tx.Hash, tx);
590 // Delete redundant memory transactions that are in the connected branch
591 foreach (var tx in txDelete)
594 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
600 private bool DisconnectBlock(CBlockStoreItem blockCursor, ref CBlock block)
602 throw new NotImplementedException();
605 private bool SetBestChainInner(CBlockStoreItem cursor)
607 uint256 hash = cursor.Hash;
609 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
611 return false; // Unable to read block from file.
614 // Adding to current best branch
615 if (!ConnectBlock(cursor, ref block) || !UpdateTopChain(cursor))
617 InvalidChainFound(cursor);
621 // Add to current best branch
622 var prevCursor = cursor.prev;
623 prevCursor.next = cursor;
625 if (!UpdateDBCursor(ref prevCursor))
627 return false; // unable to update
630 // Delete redundant memory transactions
631 foreach (var tx in block.vtx)
634 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
640 private bool ConnectBlock(CBlockStoreItem cursor, ref CBlock block, bool fJustCheck = false)
642 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
643 if (!block.CheckBlock(!fJustCheck, !fJustCheck, false))
645 return false; // Invalid block found.
648 bool fScriptChecks = cursor.nHeight >= Checkpoints.TotalBlocksEstimate;
649 var scriptFlags = scriptflag.SCRIPT_VERIFY_NOCACHE | scriptflag.SCRIPT_VERIFY_P2SH;
656 var queuedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
657 var queuedOutputs = new Dictionary<COutPoint, TxOutItem>();
659 for (var nTx = 0; nTx < block.vtx.Length; nTx++)
661 var tx = block.vtx[nTx];
662 var hashTx = tx.Hash;
664 if (!queuedMerkleNodes.ContainsKey(hashTx))
666 var nTxPos = cursor.nBlockPos + block.GetTxOffset(nTx);
667 var mNode = new CMerkleNode(cursor.ItemID, nTxPos, tx);
669 queuedMerkleNodes.Add(hashTx, mNode);
672 Dictionary<COutPoint, TxOutItem> txouts;
673 if (GetOutputs(hashTx, out txouts))
675 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
676 // unless those are already completely spent.
680 nSigOps += tx.LegacySigOpCount;
681 if (nSigOps > CBlock.nMaxSigOps)
683 return false; // too many sigops
686 var inputs = new Dictionary<COutPoint, TxOutItem>();
690 nValueOut += tx.nValueOut;
695 if (!FetchInputs(ref tx, ref queuedOutputs, ref inputs, true, out Invalid))
697 return false; // Unable to fetch some inputs.
700 // Add in sigops done by pay-to-script-hash inputs;
701 // this is to prevent a "rogue miner" from creating
702 // an incredibly-expensive-to-validate block.
703 nSigOps += tx.GetP2SHSigOpCount(ref inputs);
704 if (nSigOps > CBlock.nMaxSigOps)
706 return false; // too many sigops
709 ulong nTxValueIn = tx.GetValueIn(ref inputs);
710 ulong nTxValueOut = tx.nValueOut;
712 nValueIn += nTxValueIn;
713 nValueOut += nTxValueOut;
717 nFees += nTxValueIn - nTxValueOut;
720 if (!ConnectInputs(ref tx, ref inputs, ref queuedOutputs, ref cursor, true, fScriptChecks, scriptFlags))
726 for (var i = 0u; i < tx.vout.Length; i++)
728 var outKey = new COutPoint(hashTx, i);
729 var outData = new TxOutItem()
732 nValue = tx.vout[i].nValue,
733 scriptPubKey = tx.vout[i].scriptPubKey,
738 queuedOutputs.Add(outKey, outData);
742 if (!block.IsProofOfStake)
744 ulong nBlockReward = CBlock.GetProofOfWorkReward(cursor.nBits, nFees);
746 // Check coinbase reward
747 if (block.vtx[0].nValueOut > nBlockReward)
749 return false; // coinbase reward exceeded
753 cursor.nMint = (long)(nValueOut - nValueIn + nFees);
754 cursor.nMoneySupply = (cursor.prev != null ? cursor.prev.nMoneySupply : 0) + (long)nValueOut - (long)nValueIn;
756 if (!UpdateDBCursor(ref cursor))
758 return false; // Unable to commit changes
766 // Flush merkle nodes.
767 var savedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
768 foreach (var merklePair in queuedMerkleNodes)
770 var merkleNode = merklePair.Value;
772 if (!SaveMerkleNode(ref merkleNode))
774 // Unable to save merkle tree cursor.
778 savedMerkleNodes.Add(merklePair.Key, merkleNode);
781 // Write queued transaction changes
782 var newOutpointItems = new List<TxOutItem>();
783 var updatedOutpointItems = new List<TxOutItem>();
784 foreach (var outPair in queuedOutputs)
786 var outItem = outPair.Value;
788 if (outItem.nMerkleNodeID == -1)
790 // This outpoint doesn't exist yet, adding to insert list.
792 outItem.nMerkleNodeID = savedMerkleNodes[outPair.Key.hash].nMerkleNodeID;
793 newOutpointItems.Add(outItem);
797 // This outpount already exists, adding to update list.
799 updatedOutpointItems.Add(outItem);
803 if (updatedOutpointItems.Count != 0 && !UpdateOutpoints(ref updatedOutpointItems))
805 return false; // Unable to update outpoints
808 if (newOutpointItems.Count != 0 && !InsertOutpoints(ref newOutpointItems))
810 return false; // Unable to insert outpoints
817 /// Insert set of new outpoints
819 /// <param name="newOutpointItems">List of TxOutItem objects.</param>
820 /// <returns>Result</returns>
821 private bool InsertOutpoints(ref List<TxOutItem> newOutpointItems)
823 return (dbConn.InsertAll(newOutpointItems, false) != 0);
828 /// Update set of outpoints
830 /// <param name="queuedOutpointItems">List of TxOutItem objects.</param>
831 /// <returns>Result</returns>
832 private bool UpdateOutpoints(ref List<TxOutItem> updatedOutpointItems)
834 return (dbConn.UpdateAll(updatedOutpointItems, false) != 0);
838 /// Insert merkle node into db and set actual record id value.
840 /// <param name="merkleNode">Merkle node object reference.</param>
841 /// <returns>Result</returns>
842 private bool SaveMerkleNode(ref CMerkleNode merkleNode)
844 if (dbConn.Insert(merkleNode) == 0)
849 merkleNode.nMerkleNodeID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
854 private bool ConnectInputs(ref CTransaction tx, ref Dictionary<COutPoint, TxOutItem> inputs, ref Dictionary<COutPoint, TxOutItem> queued, ref CBlockStoreItem cursorBlock, bool fBlock, bool fScriptChecks, scriptflag scriptFlags)
856 // Take over previous transactions' spent items
857 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
863 for (uint i = 0; i < tx.vin.Length; i++)
865 var prevout = tx.vin[i].prevout;
866 Contract.Assert(inputs.ContainsKey(prevout));
867 var input = inputs[prevout];
869 CBlockStoreItem parentBlockCursor;
871 if (input.nMerkleNodeID == -1)
873 // This input seems as is confirmed by the same block.
875 if (!queued.ContainsKey(prevout))
877 return false; // No such output has been queued by this block.
880 // TODO: Ensure that neither coinbase nor coinstake outputs are
881 // available for spending in the generation block.
885 // This input has been confirmed by one of the earlier accepted blocks.
887 var merkleItem = GetMerkleCursor(input, out parentBlockCursor);
889 if (merkleItem == null)
891 return false; // Unable to find merkle node
894 // If prev is coinbase or coinstake, check that it's matured
895 if (merkleItem.IsCoinBase || merkleItem.IsCoinStake)
897 if (cursorBlock.nHeight - parentBlockCursor.nHeight < NetInfo.nGeneratedMaturity)
899 return false; // tried to spend non-matured generation input.
903 // check transaction timestamp
904 if (merkleItem.nTime > tx.nTime)
906 return false; // transaction timestamp earlier than input transaction
910 // Check for negative or overflow input values
911 nValueIn += input.nValue;
912 if (!CTransaction.MoneyRange(input.nValue) || !CTransaction.MoneyRange(nValueIn))
914 return false; // txin values out of range
919 // The first loop above does all the inexpensive checks.
920 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
921 // Helps prevent CPU exhaustion attacks.
922 for (int i = 0; i < tx.vin.Length; i++)
924 var prevout = tx.vin[i].prevout;
925 Contract.Assert(inputs.ContainsKey(prevout));
926 var input = inputs[prevout];
928 // Check for conflicts (double-spend)
934 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
935 // before the last blockchain checkpoint. This is safe because block merkle hashes are
936 // still computed and checked, and any change will be caught at the next checkpoint.
940 if (!ScriptCode.VerifyScript(tx.vin[i].scriptSig, input.scriptPubKey, tx, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
942 return false; // VerifyScript failed.
946 // Mark outpoint as spent
947 input.IsSpent = true;
948 inputs[prevout] = input;
953 if (input.nMerkleNodeID != -1)
955 // Input has been confirmed earlier.
956 queued.Add(prevout, input);
960 // Input has been confirmed by current block.
961 queued[prevout] = input;
968 // ppcoin: coin stake tx earns reward instead of paying fee
970 if (!tx.GetCoinAge(ref inputs, out nCoinAge))
972 return false; // unable to get coin age for coinstake
975 ulong nReward = tx.nValueOut - nValueIn;
977 ulong nCalculatedReward = CBlock.GetProofOfStakeReward(nCoinAge, cursorBlock.nBits, tx.nTime) - tx.GetMinFee(1, false, CTransaction.MinFeeMode.GMF_BLOCK) + CTransaction.nCent;
979 if (nReward > nCalculatedReward)
981 return false; // coinstake pays too much
986 if (nValueIn < tx.nValueOut)
988 return false; // value in < value out
991 // Tally transaction fees
992 ulong nTxFee = nValueIn - tx.nValueOut;
995 return false; // nTxFee < 0
1000 if (!CTransaction.MoneyRange(nFees))
1002 return false; // nFees out of range
1013 /// Set new top node or current best chain.
1015 /// <param name="cursor"></param>
1016 /// <returns></returns>
1017 private bool UpdateTopChain(CBlockStoreItem cursor)
1019 ChainParams.HashBestChain = cursor.Hash;
1020 ChainParams.nBestChainTrust = cursor.nChainTrust;
1021 ChainParams.nBestHeight = cursor.nHeight;
1023 return dbConn.Update(ChainParams) != 0;
1027 /// Try to find proof-of-stake hash in the map.
1029 /// <param name="blockHash">Block hash</param>
1030 /// <param name="hashProofOfStake">Proof-of-stake hash</param>
1031 /// <returns>Proof-of-Stake hash value</returns>
1032 private bool GetProofOfStakeHash(ref uint256 blockHash, out uint256 hashProofOfStake)
1034 return mapProofOfStake.TryGetValue(blockHash, out hashProofOfStake);
1037 public bool AcceptBlock(ref CBlock block)
1039 uint256 nHash = block.header.Hash;
1041 if (blockMap.ContainsKey(nHash))
1043 // Already have this block.
1047 CBlockStoreItem prevBlockCursor;
1048 if (!blockMap.TryGetValue(block.header.prevHash, out prevBlockCursor))
1050 // Unable to get the cursor.
1054 var prevBlockHeader = prevBlockCursor.BlockHeader;
1056 // TODO: proof-of-work/proof-of-stake verification
1057 uint nHeight = prevBlockCursor.nHeight + 1;
1059 // Check timestamp against prev
1060 if (NetInfo.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
1062 // block's timestamp is too early
1066 // Check that all transactions are finalized
1067 foreach (var tx in block.vtx)
1069 if (!tx.IsFinal(nHeight, block.header.nTime))
1075 // TODO: Enforce rule that the coinbase starts with serialized block height
1077 // Write block to file.
1078 var itemTemplate = new CBlockStoreItem()
1083 itemTemplate.FillHeader(block.header);
1085 if (!AddItemToIndex(ref itemTemplate, ref block))
1096 /// GEt block by hash.
1098 /// <param name="blockHash">Block hash</param>
1099 /// <param name="block">Block object reference</param>
1100 /// <param name="nBlockPos">Block position reference</param>
1101 /// <returns>Result</returns>
1102 public bool GetBlock(uint256 blockHash, ref CBlock block, ref long nBlockPos)
1104 CBlockStoreItem cursor;
1106 if (!blockMap.TryGetValue(blockHash, out cursor))
1108 return false; // Unable to fetch block cursor
1111 nBlockPos = cursor.nBlockPos;
1113 return cursor.ReadFromFile(ref fStreamReadWrite, out block);
1117 /// Get block and transaction by transaction hash.
1119 /// <param name="TxID">Transaction hash</param>
1120 /// <param name="block">Block reference</param>
1121 /// <param name="nBlockPos">Block position reference</param>
1122 /// <returns>Result of operation</returns>
1123 public bool GetBlockByTransactionID(uint256 TxID, out CBlock block, out long nBlockPos)
1128 var queryResult = dbConn.Query<CBlockStoreItem>("select b.* from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
1130 if (queryResult.Count == 1)
1132 CBlockStoreItem blockCursor = queryResult[0];
1134 nBlockPos = blockCursor.nBlockPos;
1136 return blockCursor.ReadFromFile(ref fStreamReadWrite, out block);
1144 public bool GetOutputs(uint256 transactionHash, out Dictionary<COutPoint, TxOutItem> txouts, bool fUnspentOnly=true)
1148 var queryParams = new object[] { (byte[])transactionHash, fUnspentOnly ? OutputFlags.AVAILABLE : (OutputFlags.AVAILABLE | OutputFlags.SPENT) };
1149 var queryResult = dbConn.Query<TxOutItem>("select o.* from [Outputs] o left join [MerkleNodes] m on m.[nMerkleNodeID] = o.[nMerkleNodeID] where m.[TransactionHash] = ? and outputFlags = ?", queryParams);
1151 if (queryResult.Count != 0)
1153 txouts = new Dictionary<COutPoint, TxOutItem>();
1155 foreach (var o in queryResult)
1157 var outpointKey = new COutPoint(transactionHash, o.nOut);
1158 var outpointData = o;
1160 txouts.Add(outpointKey, outpointData);
1163 // There are some unspent inputs.
1167 // This transaction has been spent completely.
1172 /// Get block cursor from map.
1174 /// <param name="blockHash">block hash</param>
1175 /// <returns>Cursor or null</returns>
1176 public CBlockStoreItem GetMapCursor(uint256 blockHash)
1180 // Genesis block has zero prevHash and no parent.
1184 CBlockStoreItem cursor = null;
1185 blockMap.TryGetValue(blockHash, out cursor);
1191 /// Get merkle node cursor by output metadata.
1193 /// <param name="item">Output metadata object</param>
1194 /// <returns>Merkle node cursor or null</returns>
1195 public CMerkleNode GetMerkleCursor(TxOutItem item, out CBlockStoreItem blockCursor)
1199 // Trying to get cursor from the database.
1200 var QueryMerkleCursor = dbConn.Query<CMerkleNode>("select * from [MerkleNodes] where [nMerkleNodeID] = ?", item.nMerkleNodeID);
1202 if (QueryMerkleCursor.Count == 1)
1204 var merkleNode = QueryMerkleCursor[0];
1207 var results = blockMap.Where(x => x.Value.ItemID == merkleNode.nParentBlockID).Select(x => x.Value).ToArray();
1209 blockCursor = results[0];
1219 /// Load cursor from database.
1221 /// <param name="blockHash">Block hash</param>
1222 /// <returns>Block cursor object</returns>
1223 public CBlockStoreItem GetDBCursor(uint256 blockHash)
1225 // Trying to get cursor from the database.
1226 var QueryBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
1228 if (QueryBlockCursor.Count == 1)
1230 return QueryBlockCursor[0];
1238 /// Update cursor in memory and on disk.
1240 /// <param name="cursor">Block cursor</param>
1241 /// <returns>Result</returns>
1242 public bool UpdateMapCursor(CBlockStoreItem cursor)
1244 var original = blockMap[cursor.Hash];
1245 return blockMap.TryUpdate(cursor.Hash, cursor, original);
1249 /// Update cursor record in database.
1251 /// <param name="cursor">Block cursor object</param>
1252 /// <returns>Result</returns>
1253 public bool UpdateDBCursor(ref CBlockStoreItem cursor)
1255 return dbConn.Update(cursor) != 0;
1258 public bool ProcessBlock(ref CBlock block)
1260 var blockHash = block.header.Hash;
1262 if (blockMap.ContainsKey(blockHash))
1264 // We already have this block.
1268 if (orphanMap.ContainsKey(blockHash))
1270 // We already have block in the list of orphans.
1274 // TODO: Limited duplicity on stake and reserialization of block signature
1276 if (!block.CheckBlock(true, true, true))
1278 // Preliminary checks failure.
1282 if (block.IsProofOfStake)
1284 if (!block.SignatureOK)
1286 // Proof-of-Stake signature validation failure.
1290 // TODO: proof-of-stake validation
1292 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1293 if (!StakeModifier.CheckProofOfStake(block.vtx[1], block.header.nBits, out hashProofOfStake, out targetProofOfStake))
1295 return false; // do not error here as we expect this during initial block download
1297 if (!mapProofOfStake.ContainsKey(blockHash))
1299 // add to mapProofOfStake
1300 mapProofOfStake.TryAdd(blockHash, hashProofOfStake);
1305 // TODO: difficulty verification
1307 // If don't already have its previous block, shunt it off to holding area until we get it
1308 if (!blockMap.ContainsKey(block.header.prevHash))
1310 if (block.IsProofOfStake)
1312 // TODO: limit duplicity on stake
1315 var block2 = new CBlock(block);
1316 orphanMap.TryAdd(blockHash, block2);
1317 orphanMapByPrev.TryAdd(blockHash, block2);
1322 // Store block to disk
1323 if (!AcceptBlock(ref block))
1329 // Recursively process any orphan blocks that depended on this one
1330 var orphansQueue = new List<uint256>();
1331 orphansQueue.Add(blockHash);
1333 for (int i = 0; i < orphansQueue.Count; i++)
1335 var hashPrev = orphansQueue[i];
1337 foreach (var pair in orphanMap)
1339 var orphanBlock = pair.Value;
1341 if (orphanBlock.header.prevHash == blockHash)
1343 if (AcceptBlock(ref orphanBlock))
1345 orphansQueue.Add(pair.Key);
1349 orphanMap.TryRemove(pair.Key, out dummy1);
1354 orphanMap.TryRemove(hashPrev, out dummy2);
1360 public bool ParseBlockFile(string BlockFile = "bootstrap.dat")
1362 // TODO: Rewrite completely.
1366 var buffer = new byte[CBlock.nMaxBlockSize]; // Max block size is 1Mb
1367 var intBuffer = new byte[4];
1369 var fStream2 = File.OpenRead(BlockFile);
1371 fStream2.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
1373 while (fStream2.Read(buffer, 0, 4) == 4) // Read magic number
1375 var nMagic = BitConverter.ToUInt32(buffer, 0);
1376 if (nMagic != 0xe5e9e8e4)
1378 throw new Exception("Incorrect magic number.");
1381 var nBytesRead = fStream2.Read(buffer, 0, 4);
1382 if (nBytesRead != 4)
1384 throw new Exception("BLKSZ EOF");
1387 var nBlockSize = BitConverter.ToInt32(buffer, 0);
1389 nOffset = fStream2.Position;
1391 nBytesRead = fStream2.Read(buffer, 0, nBlockSize);
1393 if (nBytesRead == 0 || nBytesRead != nBlockSize)
1395 throw new Exception("BLK EOF");
1398 var block = new CBlock(buffer);
1399 var hash = block.header.Hash;
1401 if (blockMap.ContainsKey(hash))
1406 if (!ProcessBlock(ref block))
1408 throw new Exception("Invalid block: " + block.header.Hash);
1411 int nCount = blockMap.Count;
1412 Console.WriteLine("nCount={0}, Hash={1}, NumTx={2}, Time={3}", nCount, block.header.Hash, block.vtx.Length, DateTime.Now);
1423 public void Dispose()
1426 GC.SuppressFinalize(this);
1429 protected virtual void Dispose(bool disposing)
1435 // Free other state (managed objects).
1437 fStreamReadWrite.Dispose();