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<Tuple<COutPoint, uint>, uint256> mapStakeSeenOrphan = new ConcurrentDictionary<Tuple<COutPoint, uint>, uint256>();
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 rootCursor = new CBlockStoreItem()
185 rootCursor.FillHeader(genesisBlock.header);
187 if (!AddItemToIndex(ref rootCursor, 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 item.nStakeModifierChecksum = StakeModifier.GetModifierChecksum(item);
202 blockMap.TryAdd(item.Hash, item);
204 if (item.IsProofOfStake)
206 // build mapStakeSeen
207 mapStakeSeen.TryAdd(item.prevoutStake, item.nStakeTime);
211 // Load data about the top node.
212 ChainParams = dbConn.Table<ChainState>().First();
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();
219 public bool GetTxOutCursor(COutPoint outpoint, out TxOutItem txOutCursor)
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);
223 if (queryResults.Count == 1)
225 txOutCursor = queryResults[0];
237 public bool FetchInputs(ref CTransaction tx, ref Dictionary<COutPoint, TxOutItem> queued, ref Dictionary<COutPoint, TxOutItem> inputs, bool IsBlock, out bool Invalid)
243 // Coinbase transactions have no inputs to fetch.
247 StringBuilder queryBuilder = new StringBuilder();
249 queryBuilder.Append("select o.*, m.[TransactionHash] from [Outputs] o left join [MerkleNodes] m on (m.[nMerkleNodeID] = o.[nMerkleNodeID]) where ");
251 for (var i = 0; i < tx.vin.Length; i++)
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)
259 var queryResults = dbConn.Query<InputsJoin>(queryBuilder.ToString());
261 foreach (var item in queryResults)
265 return false; // Already spent
268 var inputsKey = new COutPoint(item.TransactionHash, item.nOut);
270 // Add output data to dictionary
271 inputs.Add(inputsKey, item.getTxOutItem());
274 if (queryResults.Count < tx.vin.Length)
278 // It seems that some transactions are being spent in the same block.
280 foreach (var txin in tx.vin)
282 var outPoint = txin.prevout;
284 if (inputs.ContainsKey(outPoint))
286 continue; // We have already seen this input.
289 if (!queued.ContainsKey(outPoint))
291 return false; // No such transaction
294 // Add output data to dictionary
295 inputs.Add(outPoint, queued[outPoint]);
297 // Mark output as spent
298 // queued[outPoint].IsSpent = true;
303 // Unconfirmed transaction
305 foreach (var txin in tx.vin)
307 var outPoint = txin.prevout;
310 if (!mapUnconfirmedTx.TryGetValue(outPoint.hash, out txPrev))
312 return false; // No such transaction
315 if (outPoint.n > txPrev.vout.Length)
319 return false; // nOut is out of range
322 // TODO: return inputs from map
323 throw new NotImplementedException();
334 private bool AddItemToIndex(ref CBlockStoreItem newCursor, ref CBlock block)
336 uint256 blockHash = newCursor.Hash;
338 if (blockMap.ContainsKey(blockHash))
340 // Already have this block.
345 dbConn.BeginTransaction();
347 // Compute chain trust score
348 newCursor.nChainTrust = (newCursor.prev != null ? newCursor.prev.nChainTrust : 0) + newCursor.nBlockTrust;
350 if (!newCursor.SetStakeEntropyBit(Entropy.GetStakeEntropyBit(newCursor.nHeight, blockHash)))
352 return false; // SetStakeEntropyBit() failed
355 // compute stake modifier
356 long nStakeModifier = 0;
357 bool fGeneratedStakeModifier = false;
358 if (!StakeModifier.ComputeNextStakeModifier(ref newCursor, ref nStakeModifier, ref fGeneratedStakeModifier))
360 return false; // ComputeNextStakeModifier() failed
363 newCursor.SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
364 newCursor.nStakeModifierChecksum = StakeModifier.GetModifierChecksum(newCursor);
366 if (!ModifierCheckpoints.Verify(newCursor.nHeight, newCursor.nStakeModifierChecksum))
368 return false; // Stake modifier checkpoints mismatch
372 if (block.IsProofOfStake)
374 newCursor.SetProofOfStake();
376 newCursor.prevoutStake = block.vtx[1].vin[0].prevout;
377 newCursor.nStakeTime = block.vtx[1].nTime;
379 // Save proof-of-stake hash value
380 uint256 hashProofOfStake;
381 if (!GetProofOfStakeHash(ref blockHash, out hashProofOfStake))
383 return false; // hashProofOfStake not found
385 newCursor.hashProofOfStake = hashProofOfStake;
388 if (!newCursor.WriteToFile(ref fStreamReadWrite, ref block))
393 if (dbConn.Insert(newCursor) == 0)
395 return false; // Insert failed
399 newCursor.ItemID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
401 if (!blockMap.TryAdd(blockHash, newCursor))
403 return false; // blockMap add failed
406 if (newCursor.nChainTrust > ChainParams.nBestChainTrust)
410 if (!SetBestChain(ref newCursor))
412 return false; // SetBestChain failed.
416 // Commit transaction
422 private bool SetBestChain(ref CBlockStoreItem cursor)
424 uint256 hashBlock = cursor.Hash;
426 if (genesisBlockCursor == null && hashBlock == NetInfo.nHashGenesisBlock)
428 genesisBlockCursor = cursor;
430 else if (ChainParams.nHashBestChain == (uint256)cursor.prevHash)
432 if (!SetBestChainInner(cursor))
439 // the first block in the new chain that will cause it to become the new best chain
440 var cursorIntermediate = cursor;
442 // list of blocks that need to be connected afterwards
443 var secondary = new List<CBlockStoreItem>();
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)
449 secondary.Add(cursorIntermediate);
450 cursorIntermediate = cursorIntermediate.prev;
453 // Switch to new best branch
454 if (!Reorganize(cursorIntermediate))
456 InvalidChainFound(cursor);
457 return false; // reorganize failed
460 // Connect further blocks
461 foreach (var currentCursor in secondary)
464 if (!currentCursor.ReadFromFile(ref fStreamReadWrite, out block))
466 // ReadFromDisk failed
470 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
471 if (!SetBestChainInner(currentCursor))
478 bestBlockCursor = cursor;
479 nTimeBestReceived = Interop.GetTime();
480 nTransactionsUpdated++;
482 if (!UpdateTopChain(cursor))
484 return false; // unable to set top chain node.
490 private void InvalidChainFound(CBlockStoreItem cursor)
492 throw new NotImplementedException();
495 private bool Reorganize(CBlockStoreItem cursorIntermediate)
498 var fork = bestBlockCursor;
499 var longer = cursorIntermediate;
501 while (fork.ItemID != longer.ItemID)
503 while (longer.nHeight > fork.nHeight)
505 if ((longer = longer.prev) == null)
507 return false; // longer.prev is null
511 if (fork.ItemID == longer.ItemID)
516 if ((fork = fork.prev) == null)
518 return false; // fork.prev is null
522 // List of what to disconnect
523 var disconnect = new List<CBlockStoreItem>();
524 for (var cursor = bestBlockCursor; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
526 disconnect.Add(cursor);
529 // List of what to connect
530 var connect = new List<CBlockStoreItem>();
531 for (var cursor = cursorIntermediate; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
537 // Disconnect shorter branch
538 var txResurrect = new List<CTransaction>();
539 foreach (var blockCursor in disconnect)
542 if (!blockCursor.ReadFromFile(ref fStreamReadWrite, out block))
544 return false; // ReadFromFile for disconnect failed.
546 if (!DisconnectBlock(blockCursor, ref block))
548 return false; // DisconnectBlock failed.
551 // Queue memory transactions to resurrect
552 foreach (var tx in block.vtx)
554 if (!tx.IsCoinBase && !tx.IsCoinStake)
561 // Connect longer branch
562 var txDelete = new List<CTransaction>();
563 foreach (var cursor in connect)
566 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
568 return false; // ReadFromDisk for connect failed
571 if (!ConnectBlock(cursor, ref block))
574 return false; // ConnectBlock failed
577 // Queue memory transactions to delete
578 foreach (var tx in block.vtx)
584 if (!UpdateTopChain(cursorIntermediate))
586 return false; // UpdateTopChain failed
589 // Resurrect memory transactions that were in the disconnected branch
590 foreach (var tx in txResurrect)
592 mapUnconfirmedTx.TryAdd(tx.Hash, tx);
595 // Delete redundant memory transactions that are in the connected branch
596 foreach (var tx in txDelete)
599 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
605 private bool DisconnectBlock(CBlockStoreItem blockCursor, ref CBlock block)
607 throw new NotImplementedException();
610 private bool SetBestChainInner(CBlockStoreItem cursor)
612 uint256 hash = cursor.Hash;
614 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
616 return false; // Unable to read block from file.
619 // Adding to current best branch
620 if (!ConnectBlock(cursor, ref block) || !UpdateTopChain(cursor))
622 InvalidChainFound(cursor);
626 // Add to current best branch
627 var prevCursor = cursor.prev;
628 prevCursor.next = cursor;
630 if (!UpdateDBCursor(ref prevCursor))
632 return false; // unable to update
635 // Delete redundant memory transactions
636 foreach (var tx in block.vtx)
639 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
645 private bool ConnectBlock(CBlockStoreItem cursor, ref CBlock block, bool fJustCheck = false)
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))
650 return false; // Invalid block found.
653 bool fScriptChecks = cursor.nHeight >= HashCheckpoints.TotalBlocksEstimate;
654 var scriptFlags = scriptflag.SCRIPT_VERIFY_NOCACHE | scriptflag.SCRIPT_VERIFY_P2SH;
661 var queuedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
662 var queuedOutputs = new Dictionary<COutPoint, TxOutItem>();
664 for (var nTx = 0; nTx < block.vtx.Length; nTx++)
666 var tx = block.vtx[nTx];
667 var hashTx = tx.Hash;
669 if (!queuedMerkleNodes.ContainsKey(hashTx))
671 var nTxPos = cursor.nBlockPos + block.GetTxOffset(nTx);
672 var mNode = new CMerkleNode(cursor.ItemID, nTxPos, tx);
674 queuedMerkleNodes.Add(hashTx, mNode);
677 Dictionary<COutPoint, TxOutItem> txouts;
678 if (GetOutputs(hashTx, out txouts))
680 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
681 // unless those are already completely spent.
685 nSigOps += tx.LegacySigOpCount;
686 if (nSigOps > CBlock.nMaxSigOps)
688 return false; // too many sigops
691 var inputs = new Dictionary<COutPoint, TxOutItem>();
695 nValueOut += tx.nValueOut;
700 if (!FetchInputs(ref tx, ref queuedOutputs, ref inputs, true, out Invalid))
702 return false; // Unable to fetch some inputs.
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)
711 return false; // too many sigops
714 long nTxValueIn = tx.GetValueIn(ref inputs);
715 long nTxValueOut = tx.nValueOut;
717 nValueIn += nTxValueIn;
718 nValueOut += nTxValueOut;
722 nFees += nTxValueIn - nTxValueOut;
725 if (!ConnectInputs(ref tx, ref inputs, ref queuedOutputs, ref cursor, true, fScriptChecks, scriptFlags))
731 for (var i = 0u; i < tx.vout.Length; i++)
733 var outKey = new COutPoint(hashTx, i);
734 var outData = new TxOutItem()
737 nValue = tx.vout[i].nValue,
738 scriptPubKey = tx.vout[i].scriptPubKey,
743 queuedOutputs.Add(outKey, outData);
747 if (!block.IsProofOfStake)
749 long nBlockReward = CBlock.GetProofOfWorkReward(cursor.nBits, nFees);
751 // Check coinbase reward
752 if (block.vtx[0].nValueOut > nBlockReward)
754 return false; // coinbase reward exceeded
758 cursor.nMint = nValueOut - nValueIn + nFees;
759 cursor.nMoneySupply = (cursor.prev != null ? cursor.prev.nMoneySupply : 0) + nValueOut - nValueIn;
761 if (!UpdateDBCursor(ref cursor))
763 return false; // Unable to commit changes
771 // Flush merkle nodes.
772 var savedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
773 foreach (var merklePair in queuedMerkleNodes)
775 var merkleNode = merklePair.Value;
777 if (!SaveMerkleNode(ref merkleNode))
779 // Unable to save merkle tree cursor.
783 savedMerkleNodes.Add(merklePair.Key, merkleNode);
786 // Write queued transaction changes
787 var newOutpointItems = new List<TxOutItem>();
788 var updatedOutpointItems = new List<TxOutItem>();
789 foreach (var outPair in queuedOutputs)
791 var outItem = outPair.Value;
793 if (outItem.nMerkleNodeID == -1)
795 // This outpoint doesn't exist yet, adding to insert list.
797 outItem.nMerkleNodeID = savedMerkleNodes[outPair.Key.hash].nMerkleNodeID;
798 newOutpointItems.Add(outItem);
802 // This outpount already exists, adding to update list.
804 updatedOutpointItems.Add(outItem);
808 if (updatedOutpointItems.Count != 0 && !UpdateOutpoints(ref updatedOutpointItems))
810 return false; // Unable to update outpoints
813 if (newOutpointItems.Count != 0 && !InsertOutpoints(ref newOutpointItems))
815 return false; // Unable to insert outpoints
822 /// Insert set of new outpoints
824 /// <param name="newOutpointItems">List of TxOutItem objects.</param>
825 /// <returns>Result</returns>
826 private bool InsertOutpoints(ref List<TxOutItem> newOutpointItems)
828 return (dbConn.InsertAll(newOutpointItems, false) != 0);
833 /// Update set of outpoints
835 /// <param name="queuedOutpointItems">List of TxOutItem objects.</param>
836 /// <returns>Result</returns>
837 private bool UpdateOutpoints(ref List<TxOutItem> updatedOutpointItems)
839 return (dbConn.UpdateAll(updatedOutpointItems, false) != 0);
843 /// Insert merkle node into db and set actual record id value.
845 /// <param name="merkleNode">Merkle node object reference.</param>
846 /// <returns>Result</returns>
847 private bool SaveMerkleNode(ref CMerkleNode merkleNode)
849 if (dbConn.Insert(merkleNode) == 0)
854 merkleNode.nMerkleNodeID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
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)
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
868 for (uint i = 0; i < tx.vin.Length; i++)
870 var prevout = tx.vin[i].prevout;
871 Contract.Assert(inputs.ContainsKey(prevout));
872 var input = inputs[prevout];
874 CBlockStoreItem parentBlockCursor;
876 if (input.nMerkleNodeID == -1)
878 // This input seems as is confirmed by the same block.
880 if (!queued.ContainsKey(prevout))
882 return false; // No such output has been queued by this block.
885 // TODO: Ensure that neither coinbase nor coinstake outputs are
886 // available for spending in the generation block.
890 // This input has been confirmed by one of the earlier accepted blocks.
892 var merkleItem = GetMerkleCursor(input, out parentBlockCursor);
894 if (merkleItem == null)
896 return false; // Unable to find merkle node
899 // If prev is coinbase or coinstake, check that it's matured
900 if (merkleItem.IsCoinBase || merkleItem.IsCoinStake)
902 if (cursorBlock.nHeight - parentBlockCursor.nHeight < NetInfo.nGeneratedMaturity)
904 return false; // tried to spend non-matured generation input.
908 // check transaction timestamp
909 if (merkleItem.nTime > tx.nTime)
911 return false; // transaction timestamp earlier than input transaction
915 // Check for negative or overflow input values
916 nValueIn += input.nValue;
917 if (!CTransaction.MoneyRange(input.nValue) || !CTransaction.MoneyRange(nValueIn))
919 return false; // txin values out of range
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++)
929 var prevout = tx.vin[i].prevout;
930 Contract.Assert(inputs.ContainsKey(prevout));
931 var input = inputs[prevout];
933 // Check for conflicts (double-spend)
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.
945 if (!ScriptCode.VerifyScript(tx.vin[i].scriptSig, input.scriptPubKey, tx, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
947 return false; // VerifyScript failed.
951 // Mark outpoint as spent
952 input.IsSpent = true;
953 inputs[prevout] = input;
958 if (input.nMerkleNodeID != -1)
960 // Input has been confirmed earlier.
961 queued.Add(prevout, input);
965 // Input has been confirmed by current block.
966 queued[prevout] = input;
973 // Coin stake tx earns reward instead of paying fee
975 if (!tx.GetCoinAge(ref inputs, out nCoinAge))
977 return false; // unable to get coin age for coinstake
980 long nReward = tx.nValueOut - nValueIn;
982 long nCalculatedReward = CBlock.GetProofOfStakeReward(nCoinAge, cursorBlock.nBits, tx.nTime) - tx.GetMinFee(1, false, CTransaction.MinFeeMode.GMF_BLOCK) + CTransaction.nCent;
984 if (nReward > nCalculatedReward)
986 return false; // coinstake pays too much
991 if (nValueIn < tx.nValueOut)
993 return false; // value in < value out
996 // Tally transaction fees
997 long nTxFee = nValueIn - tx.nValueOut;
1000 return false; // nTxFee < 0
1005 if (!CTransaction.MoneyRange(nFees))
1007 return false; // nFees out of range
1018 /// Set new top node or current best chain.
1020 /// <param name="cursor"></param>
1021 /// <returns></returns>
1022 private bool UpdateTopChain(CBlockStoreItem cursor)
1024 ChainParams.HashBestChain = cursor.Hash;
1025 ChainParams.nBestChainTrust = cursor.nChainTrust;
1026 ChainParams.nBestHeight = cursor.nHeight;
1028 return dbConn.Update(ChainParams) != 0;
1032 /// Try to find proof-of-stake hash in the map.
1034 /// <param name="blockHash">Block hash</param>
1035 /// <param name="hashProofOfStake">Proof-of-stake hash</param>
1036 /// <returns>Proof-of-Stake hash value</returns>
1037 private bool GetProofOfStakeHash(ref uint256 blockHash, out uint256 hashProofOfStake)
1039 return mapProofOfStake.TryGetValue(blockHash, out hashProofOfStake);
1042 public bool AcceptBlock(ref CBlock block)
1044 uint256 nHash = block.header.Hash;
1046 if (blockMap.ContainsKey(nHash))
1048 // Already have this block.
1052 CBlockStoreItem prevBlockCursor;
1053 if (!blockMap.TryGetValue(block.header.prevHash, out prevBlockCursor))
1055 // Unable to get the cursor.
1059 var prevBlockHeader = prevBlockCursor.BlockHeader;
1061 uint nHeight = prevBlockCursor.nHeight + 1;
1063 // Check timestamp against prev
1064 if (NetInfo.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
1066 // block's timestamp is too early
1070 // Check that all transactions are finalized
1071 foreach (var tx in block.vtx)
1073 if (!tx.IsFinal(nHeight, block.header.nTime))
1079 // Check that the block chain matches the known block chain up to a checkpoint
1080 if (!HashCheckpoints.Verify(nHeight, nHash))
1082 return false; // rejected by checkpoint lock-in
1085 // Enforce rule that the coinbase starts with serialized block height
1086 var expect = new CScript();
1087 expect.AddNumber((int)nHeight);
1089 byte[] expectBytes = expect;
1090 byte[] scriptSig = block.vtx[0].vin[0].scriptSig;
1092 if (!expectBytes.SequenceEqual(scriptSig.Take(expectBytes.Length)))
1094 return false; // coinbase doesn't start with serialized height.
1097 // Write block to file.
1098 var newCursor = new CBlockStoreItem()
1103 newCursor.FillHeader(block.header);
1105 if (!AddItemToIndex(ref newCursor, ref block))
1116 /// Get block by hash.
1118 /// <param name="blockHash">Block hash</param>
1119 /// <param name="block">Block object reference</param>
1120 /// <param name="nBlockPos">Block position reference</param>
1121 /// <returns>Result</returns>
1122 public bool GetBlock(uint256 blockHash, ref CBlock block, ref long nBlockPos)
1124 CBlockStoreItem cursor;
1126 if (!blockMap.TryGetValue(blockHash, out cursor))
1128 return false; // Unable to fetch block cursor
1131 nBlockPos = cursor.nBlockPos;
1133 return cursor.ReadFromFile(ref fStreamReadWrite, out block);
1137 /// Get block and transaction by transaction hash.
1139 /// <param name="TxID">Transaction hash</param>
1140 /// <param name="block">Block reference</param>
1141 /// <param name="nBlockPos">Block position reference</param>
1142 /// <returns>Result of operation</returns>
1143 public bool GetBlockByTransactionID(uint256 TxID, out CBlock block, out long nBlockPos)
1148 var queryResult = dbConn.Query<CBlockStoreItem>("select b.* from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
1150 if (queryResult.Count == 1)
1152 CBlockStoreItem blockCursor = queryResult[0];
1154 nBlockPos = blockCursor.nBlockPos;
1156 return blockCursor.ReadFromFile(ref fStreamReadWrite, out block);
1164 public bool GetOutputs(uint256 transactionHash, out Dictionary<COutPoint, TxOutItem> txouts, bool fUnspentOnly=true)
1168 var queryParams = new object[] { (byte[])transactionHash, fUnspentOnly ? OutputFlags.AVAILABLE : (OutputFlags.AVAILABLE | OutputFlags.SPENT) };
1169 var queryResult = dbConn.Query<TxOutItem>("select o.* from [Outputs] o left join [MerkleNodes] m on m.[nMerkleNodeID] = o.[nMerkleNodeID] where m.[TransactionHash] = ? and outputFlags = ?", queryParams);
1171 if (queryResult.Count != 0)
1173 txouts = new Dictionary<COutPoint, TxOutItem>();
1175 foreach (var o in queryResult)
1177 var outpointKey = new COutPoint(transactionHash, o.nOut);
1178 var outpointData = o;
1180 txouts.Add(outpointKey, outpointData);
1183 // There are some unspent inputs.
1187 // This transaction has been spent completely.
1192 /// Get block cursor from map.
1194 /// <param name="blockHash">block hash</param>
1195 /// <returns>Cursor or null</returns>
1196 public CBlockStoreItem GetMapCursor(uint256 blockHash)
1200 // Genesis block has zero prevHash and no parent.
1204 CBlockStoreItem cursor = null;
1205 blockMap.TryGetValue(blockHash, out cursor);
1211 /// Get merkle node cursor by output metadata.
1213 /// <param name="item">Output metadata object</param>
1214 /// <returns>Merkle node cursor or null</returns>
1215 public CMerkleNode GetMerkleCursor(TxOutItem item, out CBlockStoreItem blockCursor)
1219 // Trying to get cursor from the database.
1220 var QueryMerkleCursor = dbConn.Query<CMerkleNode>("select * from [MerkleNodes] where [nMerkleNodeID] = ?", item.nMerkleNodeID);
1222 if (QueryMerkleCursor.Count == 1)
1224 var merkleNode = QueryMerkleCursor[0];
1227 var results = blockMap.Where(x => x.Value.ItemID == merkleNode.nParentBlockID).Select(x => x.Value).ToArray();
1229 blockCursor = results[0];
1239 /// Load cursor from database.
1241 /// <param name="blockHash">Block hash</param>
1242 /// <returns>Block cursor object</returns>
1243 public CBlockStoreItem GetDBCursor(uint256 blockHash)
1245 // Trying to get cursor from the database.
1246 var QueryBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
1248 if (QueryBlockCursor.Count == 1)
1250 return QueryBlockCursor[0];
1258 /// Update cursor in memory and on disk.
1260 /// <param name="cursor">Block cursor</param>
1261 /// <returns>Result</returns>
1262 public bool UpdateMapCursor(CBlockStoreItem cursor)
1264 var original = blockMap[cursor.Hash];
1265 return blockMap.TryUpdate(cursor.Hash, cursor, original);
1269 /// Update cursor record in database.
1271 /// <param name="cursor">Block cursor object</param>
1272 /// <returns>Result</returns>
1273 public bool UpdateDBCursor(ref CBlockStoreItem cursor)
1275 return dbConn.Update(cursor) != 0;
1278 public bool ProcessBlock(ref CBlock block)
1280 var blockHash = block.header.Hash;
1282 if (blockMap.ContainsKey(blockHash))
1284 // We already have this block.
1288 if (orphanMap.ContainsKey(blockHash))
1290 // We already have block in the list of orphans.
1294 // TODO: Limited duplicity on stake and reserialization of block signature
1296 if (!block.CheckBlock(true, true, true))
1298 // Preliminary checks failure.
1302 if (block.IsProofOfStake)
1304 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1305 if (!StakeModifier.CheckProofOfStake(block.vtx[1], block.header.nBits, out hashProofOfStake, out targetProofOfStake))
1307 return false; // do not error here as we expect this during initial block download
1309 if (!mapProofOfStake.ContainsKey(blockHash))
1311 // add to mapProofOfStake
1312 mapProofOfStake.TryAdd(blockHash, hashProofOfStake);
1317 // TODO: difficulty verification
1319 // If don't already have its previous block, shunt it off to holding area until we get it
1320 if (!blockMap.ContainsKey(block.header.prevHash))
1322 if (block.IsProofOfStake)
1324 var proof = block.ProofOfStake;
1326 // Limited duplicity on stake: prevents block flood attack
1327 // Duplicate stake allowed only when there is orphan child block
1328 if (mapStakeSeenOrphan.ContainsKey(proof) && !orphanMapByPrev.ContainsKey(blockHash))
1330 return false; // duplicate proof-of-stake
1334 mapStakeSeenOrphan.TryAdd(proof, blockHash);
1338 orphanMap.TryAdd(blockHash, block);
1339 orphanMapByPrev.TryAdd(blockHash, block);
1344 // Store block to disk
1345 if (!AcceptBlock(ref block))
1351 if (orphanMapByPrev.Count > 0)
1353 // Recursively process any orphan blocks that depended on this one
1355 var orphansQueue = new List<uint256>();
1356 orphansQueue.Add(blockHash);
1358 for (int i = 0; i < orphansQueue.Count; i++)
1360 var hashPrev = orphansQueue[i];
1362 foreach (var pair in orphanMapByPrev)
1364 var orphanBlock = pair.Value;
1366 if (orphanBlock.header.prevHash == blockHash)
1368 if (AcceptBlock(ref orphanBlock))
1370 orphansQueue.Add(pair.Key);
1374 orphanMap.TryRemove(pair.Key, out dummy1);
1377 mapStakeSeenOrphan.TryRemove(orphanBlock.ProofOfStake, out dummyHash);
1382 orphanMapByPrev.TryRemove(hashPrev, out dummy2);
1389 public bool ParseBlockFile(string BlockFile = "bootstrap.dat")
1391 // TODO: Rewrite completely.
1395 var buffer = new byte[CBlock.nMaxBlockSize]; // Max block size is 1Mb
1396 var intBuffer = new byte[4];
1398 var fStream2 = File.OpenRead(BlockFile);
1400 fStream2.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
1402 while (fStream2.Read(buffer, 0, 4) == 4) // Read magic number
1404 var nMagic = BitConverter.ToUInt32(buffer, 0);
1405 if (nMagic != 0xe5e9e8e4)
1407 throw new Exception("Incorrect magic number.");
1410 var nBytesRead = fStream2.Read(buffer, 0, 4);
1411 if (nBytesRead != 4)
1413 throw new Exception("BLKSZ EOF");
1416 var nBlockSize = BitConverter.ToInt32(buffer, 0);
1418 nOffset = fStream2.Position;
1420 nBytesRead = fStream2.Read(buffer, 0, nBlockSize);
1422 if (nBytesRead == 0 || nBytesRead != nBlockSize)
1424 throw new Exception("BLK EOF");
1427 var block = new CBlock(buffer);
1428 var hash = block.header.Hash;
1430 if (blockMap.ContainsKey(hash))
1435 if (!ProcessBlock(ref block))
1437 throw new Exception("Invalid block: " + block.header.Hash);
1440 int nCount = blockMap.Count;
1441 Console.WriteLine("nCount={0}, Hash={1}, NumTx={2}, Time={3}", nCount, block.header.Hash, block.vtx.Length, DateTime.Now);
1452 public void Dispose()
1455 GC.SuppressFinalize(this);
1458 protected virtual void Dispose(bool disposing)
1464 // Free other state (managed objects).
1466 fStreamReadWrite.Dispose();