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/>.
23 using System.Collections.Concurrent;
26 using SQLite.Net.Attributes;
27 using SQLite.Net.Interop;
28 using SQLite.Net.Platform.Generic;
29 using SQLiteNetExtensions.Attributes;
30 using System.Collections.Generic;
31 using System.Diagnostics.Contracts;
36 [Table("BlockStorage")]
37 public class CBlockStoreItem : IBlockStorageItem
39 #region IBlockStorageItem
41 /// Item ID in the database
43 [PrimaryKey, AutoIncrement]
44 public long ItemID { get; set; }
47 /// PBKDF2+Salsa20 of block hash
50 public byte[] Hash { get; set; }
53 /// Version of block schema
56 public uint nVersion { get; set; }
59 /// Previous block hash.
62 public byte[] prevHash { get; set; }
67 [Column("merkleRoot")]
68 public byte[] merkleRoot { get; set; }
74 public uint nTime { get; set; }
77 /// Compressed difficulty representation.
80 public uint nBits { get; set; }
86 public uint nNonce { get; set; }
92 public byte[] nextHash { get; set; }
97 [Column("BlockTypeFlag")]
98 public BlockType BlockTypeFlag { get; set; }
103 [Column("nStakeModifier")]
104 public long nStakeModifier { get; set; }
107 /// Proof-of-Stake hash
109 [Column("hashProofOfStake")]
110 public byte[] hashProofOfStake { get; set; }
113 /// Stake generation outpoint.
115 [Column("prevoutStake")]
116 public byte[] prevoutStake { get; set; }
119 /// Stake generation time.
121 [Column("nStakeTime")]
122 public uint nStakeTime { get; set; }
125 /// Block height, encoded in VarInt format
128 public uint nHeight { get; set; }
131 /// Chain trust score, serialized and trimmed uint256 representation.
133 [Column("ChainTrust")]
134 public byte[] ChainTrust { get; set; }
137 /// Block position in file, encoded in VarInt format
140 public byte[] BlockPos { get; set; }
143 /// Block size in bytes, encoded in VarInt format
145 [Column("BlockSize")]
146 public byte[] BlockSize { get; set; }
150 /// Accessor and mutator for BlockPos value.
153 public long nBlockPos
155 get { return (long)VarInt.DecodeVarInt(BlockPos); }
156 set { BlockPos = VarInt.EncodeVarInt(value); }
160 /// Accessor and mutator for BlockSize value.
163 public int nBlockSize
165 get { return (int)VarInt.DecodeVarInt(BlockSize); }
166 set { BlockSize = VarInt.EncodeVarInt(value); }
170 /// Fill database item with data from given block header.
172 /// <param name="header">Block header</param>
173 /// <returns>Header hash</returns>
174 public uint256 FillHeader(CBlockHeader header)
176 uint256 _hash = header.Hash;
180 nVersion = header.nVersion;
181 prevHash = header.prevHash;
182 merkleRoot = header.merkleRoot;
183 nTime = header.nTime;
184 nBits = header.nBits;
185 nNonce = header.nNonce;
191 /// Reconstruct block header from item data.
193 public CBlockHeader BlockHeader
197 CBlockHeader header = new CBlockHeader();
199 header.nVersion = nVersion;
200 header.prevHash = prevHash;
201 header.merkleRoot = merkleRoot;
202 header.nTime = nTime;
203 header.nBits = nBits;
204 header.nNonce = nNonce;
211 /// Read block from file.
213 /// <param name="reader">Stream with read access.</param>
214 /// <param name="reader">CBlock reference.</param>
215 /// <returns>Result</returns>
216 public bool ReadFromFile(ref Stream reader, out CBlock block)
218 var buffer = new byte[nBlockSize];
223 reader.Seek(nBlockPos, SeekOrigin.Begin);
225 if (nBlockSize != reader.Read(buffer, 0, nBlockSize))
230 block = new CBlock(buffer);
239 catch (BlockException)
241 // Constructor exception
247 /// Writes given block to file and prepares cursor object for insertion into the database.
249 /// <param name="writer">Stream with write access.</param>
250 /// <param name="block">CBlock reference.</param>
251 /// <returns>Result</returns>
252 public bool WriteToFile(ref Stream writer, ref CBlock block)
256 byte[] blockBytes = block;
258 var magicBytes = BitConverter.GetBytes(CBlockStore.nMagicNumber);
259 var blkLenBytes = BitConverter.GetBytes(blockBytes.Length);
261 // Seek to the end and then append magic bytes there.
262 writer.Seek(0, SeekOrigin.End);
263 writer.Write(magicBytes, 0, magicBytes.Length);
264 writer.Write(blkLenBytes, 0, blkLenBytes.Length);
266 // Save block size and current position in the block cursor fields.
267 nBlockPos = writer.Position;
268 nBlockSize = blockBytes.Length;
270 // Write block and flush the stream.
271 writer.Write(blockBytes, 0, blockBytes.Length);
283 // Some serialization error
289 /// Previous block cursor
292 public CBlockStoreItem prev
294 get { return CBlockStore.Instance.GetMapCursor(prevHash); }
298 /// Next block cursor
301 public CBlockStoreItem next
305 if (nextHash == null)
310 return CBlockStore.Instance.GetMapCursor(nextHash);
314 nextHash = value.Hash;
316 CBlockStore.Instance.UpdateMapCursor(this);
323 get { return (next != null); }
327 /// STake modifier generation flag
330 public bool GeneratedStakeModifier
332 get { return (BlockTypeFlag & BlockType.BLOCK_STAKE_MODIFIER) != 0; }
336 /// Stake entropy bit
339 public uint StakeEntropyBit
341 get { return ((uint)(BlockTypeFlag & BlockType.BLOCK_STAKE_ENTROPY) >> 1); }
345 /// Sets stake modifier and flag.
347 /// <param name="nModifier">New stake modifier.</param>
348 /// <param name="fGeneratedStakeModifier">Set generation flag?</param>
349 public void SetStakeModifier(long nModifier, bool fGeneratedStakeModifier)
351 nStakeModifier = nModifier;
352 if (fGeneratedStakeModifier)
353 BlockTypeFlag |= BlockType.BLOCK_STAKE_MODIFIER;
359 /// <param name="nEntropyBit">Entropy bit value (0 or 1).</param>
360 /// <returns>False if value is our of range.</returns>
361 public bool SetStakeEntropyBit(byte nEntropyBit)
365 BlockTypeFlag |= (nEntropyBit != 0 ? BlockType.BLOCK_STAKE_ENTROPY : 0);
370 /// Set proof-of-stake flag.
372 public void SetProofOfStake()
374 BlockTypeFlag |= BlockType.BLOCK_PROOF_OF_STAKE;
378 /// Block has no proof-of-stake flag.
381 public bool IsProofOfWork
383 get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) == 0; }
387 /// Block has proof-of-stake flag set.
390 public bool IsProofOfStake
392 get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) != 0; }
396 /// Block trust score.
399 public uint256 nBlockTrust
404 nTarget.Compact = nBits;
407 if (nTime < NetInfo.nChainChecksSwitchTime)
409 return IsProofOfStake ? (new uint256(1) << 256) / (nTarget + 1) : 1;
414 // Calculate work amount for block
415 var nPoWTrust = NetInfo.nPoWBase / (nTarget + 1);
417 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
418 nPoWTrust = (IsProofOfStake || !nPoWTrust) ? 1 : nPoWTrust;
420 // Return nPoWTrust for the first 12 blocks
421 if (prev == null || prev.nHeight < 12)
424 CBlockStoreItem currentIndex = prev;
428 var nNewTrust = (new uint256(1) << 256) / (nTarget + 1);
430 // Return 1/3 of score if parent block is not the PoW block
431 if (!prev.IsProofOfWork)
433 return nNewTrust / 3;
438 // Check last 12 blocks type
439 while (prev.nHeight - currentIndex.nHeight < 12)
441 if (currentIndex.IsProofOfWork)
445 currentIndex = currentIndex.prev;
448 // Return 1/3 of score if less than 3 PoW blocks found
451 return nNewTrust / 3;
458 var nLastBlockTrust = prev.nChainTrust - prev.prev.nChainTrust;
460 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
461 if (!prev.IsProofOfStake || !prev.prev.IsProofOfStake)
463 return nPoWTrust + (2 * nLastBlockTrust / 3);
468 // Check last 12 blocks type
469 while (prev.nHeight - currentIndex.nHeight < 12)
471 if (currentIndex.IsProofOfStake)
475 currentIndex = currentIndex.prev;
478 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
481 return nPoWTrust + (2 * nLastBlockTrust / 3);
484 nTarget.Compact = prev.nBits;
491 var nNewTrust = (new uint256(1) << 256) / (nTarget + 1);
493 // Return nPoWTrust + full trust score for previous block nBits
494 return nPoWTrust + nNewTrust;
500 /// Stake modifier checksum.
502 public uint nStakeModifierChecksum;
505 /// Chain trust score
508 public uint256 nChainTrust {
509 get { return Interop.AppendWithZeros(ChainTrust); }
510 set { ChainTrust = Interop.TrimArray(value); }
513 public long nMint { get; internal set; }
514 public long nMoneySupply { get; internal set; }
520 public enum BlockType
522 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
523 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
524 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
528 /// Transaction type.
530 public enum TxFlags : byte
540 public enum OutputFlags : byte
542 AVAILABLE, // Unspent output
543 SPENT // Spent output
546 [Table("MerkleNodes")]
547 public class CMerkleNode : IMerkleNode
553 [PrimaryKey, AutoIncrement]
554 public long nMerkleNodeID { get; set; }
557 /// Reference to parent block database item.
559 [ForeignKey(typeof(CBlockStoreItem), Name = "ItemId")]
560 public long nParentBlockID { get; set; }
563 /// Transaction type flag
565 [Column("TransactionFlags")]
566 public TxFlags TransactionFlags { get; set; }
571 [Column("TransactionHash")]
572 public byte[] TransactionHash { get; set; }
575 /// Transaction offset from the beginning of block header, encoded in VarInt format.
578 public byte[] TxOffset { get; set; }
581 /// Transaction size, encoded in VarInt format.
584 public byte[] TxSize { get; set; }
588 /// Read transaction from file.
590 /// <param name="reader">Stream with read access.</param>
591 /// <param name="tx">CTransaction reference.</param>
592 /// <returns>Result</returns>
593 public bool ReadFromFile(ref Stream reader, long nBlockPos, out CTransaction tx)
595 var buffer = new byte[CTransaction.nMaxTxSize];
601 reader.Seek(nBlockPos + nTxOffset, SeekOrigin.Begin); // Seek to transaction offset
603 if (nTxSize != reader.Read(buffer, 0, nTxSize))
608 tx = new CTransaction(buffer);
617 catch (TransactionConstructorException)
625 /// Transaction offset accessor
628 public long nTxOffset
630 get { return (long) VarInt.DecodeVarInt(TxOffset); }
631 private set { TxOffset = VarInt.EncodeVarInt(value); }
635 /// Transaction size accessor
640 get { return (int)VarInt.DecodeVarInt(TxSize); }
641 private set { TxSize = VarInt.EncodeVarInt(value); }
644 public CMerkleNode(CTransaction tx)
650 TransactionHash = tx.Hash;
654 TransactionFlags |= TxFlags.TX_COINBASE;
656 else if (tx.IsCoinStake)
658 TransactionFlags |= TxFlags.TX_COINSTAKE;
662 TransactionFlags |= TxFlags.TX_USER;
666 public CMerkleNode(long nBlockId, long nOffset, CTransaction tx)
668 nParentBlockID = nBlockId;
672 TransactionHash = tx.Hash;
676 TransactionFlags |= TxFlags.TX_COINBASE;
678 else if (tx.IsCoinStake)
680 TransactionFlags |= TxFlags.TX_COINSTAKE;
684 TransactionFlags |= TxFlags.TX_USER;
691 public class TxOutItem : ITxOutItem
694 /// Reference to transaction item.
696 [ForeignKey(typeof(CMerkleNode), Name = "nMerkleNodeID")]
697 public long nMerkleNodeID { get; set; }
702 public OutputFlags outputFlags { get; set; }
705 /// Output number in VarInt format.
707 public byte[] OutputNumber { get; set; }
710 /// Output value in VarInt format.
712 public byte[] OutputValue { get; set; }
715 /// Second half of script which contains spending instructions.
717 public byte[] scriptPubKey { get; set; }
720 /// Getter for output number.
725 get { return (uint)VarInt.DecodeVarInt(OutputNumber); }
726 private set { OutputNumber = VarInt.EncodeVarInt(value); }
730 /// Getter for output value.
735 get { return VarInt.DecodeVarInt(OutputValue); }
736 private set { OutputValue = VarInt.EncodeVarInt(value); }
740 /// Getter ans setter for IsSpent flag.
745 get { return (outputFlags & OutputFlags.SPENT) != 0; }
746 set { outputFlags |= value ? OutputFlags.SPENT : OutputFlags.AVAILABLE; }
749 public TxOutItem(CTxOut o, uint nOut)
752 scriptPubKey = o.scriptPubKey;
757 public class CBlockStore : IDisposable
759 public const uint nMagicNumber = 0xe5e9e8e4;
761 private bool disposed = false;
762 private object LockObj = new object();
765 /// SQLite connection object.
767 private SQLiteConnection dbConn;
770 /// Current SQLite platform
772 private ISQLitePlatform dbPlatform;
777 private string strBlockFile;
780 /// Index database file.
782 private string strDbFile;
785 /// Map of block tree nodes.
787 /// blockHash => CBlockStoreItem
789 private ConcurrentDictionary<uint256, CBlockStoreItem> blockMap = new ConcurrentDictionary<uint256, CBlockStoreItem>();
792 /// Orphaned blocks map.
794 private ConcurrentDictionary<uint256, CBlock> orphanMap = new ConcurrentDictionary<uint256, CBlock>();
795 private ConcurrentDictionary<uint256, CBlock> orphanMapByPrev = new ConcurrentDictionary<uint256, CBlock>();
798 /// Unconfirmed transactions.
800 /// TxID => Transaction
802 private ConcurrentDictionary<uint256, CTransaction> mapUnconfirmedTx = new ConcurrentDictionary<uint256, CTransaction>();
805 /// Map of the proof-of-stake hashes. This is necessary for stake duplication checks.
807 private ConcurrentDictionary<uint256, uint256> mapProofOfStake = new ConcurrentDictionary<uint256, uint256>();
810 private ConcurrentDictionary<COutPoint, uint> mapStakeSeen = new ConcurrentDictionary<COutPoint, uint>();
811 private ConcurrentDictionary<COutPoint, uint> mapStakeSeenOrphan = new ConcurrentDictionary<COutPoint, uint>();
814 /// Trust score for the longest chain.
816 private uint256 nBestChainTrust = 0;
819 /// Top block of the best chain.
821 private uint256 nHashBestChain = 0;
824 /// Cursor which is pointing us to the end of best chain.
826 private CBlockStoreItem bestBlockCursor = null;
829 /// Cursor which is always pointing us to genesis block.
831 private CBlockStoreItem genesisBlockCursor = null;
834 /// Current and the only instance of block storage manager. Should be a property with private setter though it's enough for the beginning.
836 public static CBlockStore Instance = null;
839 /// Block file stream with read/write access
841 private Stream fStreamReadWrite;
842 private uint nBestHeight;
843 private uint nTimeBestReceived;
844 private int nTransactionsUpdated;
847 /// Init the block storage manager.
849 /// <param name="IndexDB">Path to index database</param>
850 /// <param name="BlockFile">Path to block file</param>
851 public CBlockStore(string IndexDB = "blockstore.dat", string BlockFile = "blk0001.dat")
854 strBlockFile = BlockFile;
856 bool firstInit = !File.Exists(strDbFile);
857 dbPlatform = new SQLitePlatformGeneric();
858 dbConn = new SQLiteConnection(dbPlatform, strDbFile);
860 fStreamReadWrite = File.Open(strBlockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
869 dbConn.CreateTable<CBlockStoreItem>(CreateFlags.AutoIncPK);
870 dbConn.CreateTable<CMerkleNode>(CreateFlags.AutoIncPK);
871 dbConn.CreateTable<TxOutItem>(CreateFlags.ImplicitPK);
873 var genesisBlock = new CBlock(
875 "01000000" + // nVersion=1
876 "0000000000000000000000000000000000000000000000000000000000000000" + // prevhash is zero
877 "7b0502ad2f9f675528183f83d6385794fbcaa914e6d385c6cb1d866a3b3bb34c" + // merkle root
878 "398e1151" + // nTime=1360105017
879 "ffff0f1e" + // nBits=0x1e0fffff
880 "d3091800" + // nNonce=1575379
882 "01000000" + // nVersion=1
883 "398e1151" + // nTime=1360105017
885 "0000000000000000000000000000000000000000000000000000000000000000" + // input txid is zero
886 "ffffffff" + // n=uint.maxValue
887 "4d" + // scriptSigLen=77
888 "04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936" + // scriptSig
889 "ffffffff" + // nSequence=uint.maxValue
891 "0000000000000000" + // nValue=0
892 "00" + // scriptPubkeyLen=0
893 "00000000" + // nLockTime=0
897 // Write block to file.
898 var itemTemplate = new CBlockStoreItem()
903 itemTemplate.FillHeader(genesisBlock.header);
905 if (!AddItemToIndex(ref itemTemplate, ref genesisBlock))
907 throw new Exception("Unable to write genesis block");
913 var blockTreeItems = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] order by [ItemId] asc");
915 // Init list of block items
916 foreach (var item in blockTreeItems)
918 blockMap.TryAdd(item.Hash, item);
920 if (item.IsProofOfStake)
922 // build mapStakeSeen
923 mapStakeSeen.TryAdd(item.prevoutStake, item.nStakeTime);
929 public bool GetTxOutCursor(COutPoint outpoint, ref TxOutItem txOutCursor)
931 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);
933 if (queryResults.Count == 1)
935 txOutCursor = queryResults[0];
945 interface InputsJoin : ITxOutItem
947 byte[] TransactionHash { get; set; }
950 public bool FetchInputs(CTransaction tx, ref Dictionary<COutPoint, TxOutItem> queued, ref Dictionary<COutPoint, TxOutItem> inputs, bool IsBlock, out bool Invalid)
956 // Coinbase transactions have no inputs to fetch.
960 StringBuilder queryBuilder = new StringBuilder();
962 queryBuilder.Append("select o.*, m.[TransactionHash] from [Outputs] o left join [MerkleNodes] m on (m.[nMerkleNodeID] = o.[nMerkleNodeID]) where ");
964 for (var i = 0; i < tx.vin.Length; i++)
966 queryBuilder.AppendFormat(" {0} (m.[TransactionHash] = x'{1}' and o.[OutputNumber] = x'{2}')",
967 (i > 0 ? "or" : string.Empty), Interop.ToHex(tx.vin[i].prevout.hash),
968 Interop.ToHex(VarInt.EncodeVarInt(tx.vin[i].prevout.n)
972 var queryResults = dbConn.Query<InputsJoin>(queryBuilder.ToString());
974 foreach (var item in queryResults)
978 return false; // Already spent
981 var inputsKey = new COutPoint(item.TransactionHash, item.nOut);
985 // Add output data to dictionary
986 inputs.Add(inputsKey, (TxOutItem) item);
989 if (queryResults.Count < tx.vin.Length)
993 // It seems that some transactions are being spent in the same block.
995 foreach (var txin in tx.vin)
997 var outPoint = txin.prevout;
999 if (!queued.ContainsKey(outPoint))
1001 return false; // No such transaction
1004 // Add output data to dictionary
1005 inputs.Add(outPoint, queued[outPoint]);
1007 // Mark output as spent
1008 queued[outPoint].IsSpent = true;
1013 // Unconfirmed transaction
1015 foreach (var txin in tx.vin)
1017 var outPoint = txin.prevout;
1018 CTransaction txPrev;
1020 if (!mapUnconfirmedTx.TryGetValue(outPoint.hash, out txPrev))
1022 return false; // No such transaction
1025 if (outPoint.n > txPrev.vout.Length)
1029 return false; // nOut is out of range
1032 // TODO: return inputs from map
1033 throw new NotImplementedException();
1044 private bool AddItemToIndex(ref CBlockStoreItem itemTemplate, ref CBlock block)
1046 var writer = new BinaryWriter(fStreamReadWrite).BaseStream;
1047 uint256 blockHash = itemTemplate.Hash;
1049 if (blockMap.ContainsKey(blockHash))
1051 // Already have this block.
1055 // Compute chain trust score
1056 itemTemplate.nChainTrust = (itemTemplate.prev != null ? itemTemplate.prev.nChainTrust : 0) + itemTemplate.nBlockTrust;
1058 if (!itemTemplate.SetStakeEntropyBit(Entropy.GetStakeEntropyBit(itemTemplate.nHeight, blockHash)))
1060 return false; // SetStakeEntropyBit() failed
1063 // Save proof-of-stake hash value
1064 if (itemTemplate.IsProofOfStake)
1066 uint256 hashProofOfStake;
1067 if (!GetProofOfStakeHash(blockHash, out hashProofOfStake))
1069 return false; // hashProofOfStake not found
1071 itemTemplate.hashProofOfStake = hashProofOfStake;
1074 // compute stake modifier
1075 long nStakeModifier = 0;
1076 bool fGeneratedStakeModifier = false;
1077 if (!StakeModifier.ComputeNextStakeModifier(itemTemplate, ref nStakeModifier, ref fGeneratedStakeModifier))
1079 return false; // ComputeNextStakeModifier() failed
1082 itemTemplate.SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
1083 itemTemplate.nStakeModifierChecksum = StakeModifier.GetStakeModifierChecksum(itemTemplate);
1085 // TODO: verify stake modifier checkpoints
1088 if (block.IsProofOfStake)
1090 itemTemplate.SetProofOfStake();
1092 itemTemplate.prevoutStake = block.vtx[1].vin[0].prevout;
1093 itemTemplate.nStakeTime = block.vtx[1].nTime;
1096 if (!itemTemplate.WriteToFile(ref writer, ref block))
1101 if (dbConn.Insert(itemTemplate) == 0)
1103 return false; // Insert failed
1107 itemTemplate.ItemID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
1109 if (!blockMap.TryAdd(blockHash, itemTemplate))
1111 return false; // blockMap add failed
1114 if (itemTemplate.nChainTrust > nBestChainTrust)
1118 if (!SetBestChain(ref itemTemplate))
1120 return false; // SetBestChain failed.
1127 private bool SetBestChain(ref CBlockStoreItem cursor)
1129 uint256 hashBlock = cursor.Hash;
1131 if (genesisBlockCursor == null && hashBlock == NetInfo.nHashGenesisBlock)
1133 genesisBlockCursor = cursor;
1135 else if (nHashBestChain == (uint256)cursor.prevHash)
1137 if (!SetBestChainInner(cursor))
1144 // the first block in the new chain that will cause it to become the new best chain
1145 var cursorIntermediate = cursor;
1147 // list of blocks that need to be connected afterwards
1148 var secondary = new List<CBlockStoreItem>();
1150 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1151 // Try to limit how much needs to be done inside
1152 while (cursorIntermediate.prev != null && cursorIntermediate.prev.nChainTrust > bestBlockCursor.nChainTrust)
1154 secondary.Add(cursorIntermediate);
1155 cursorIntermediate = cursorIntermediate.prev;
1158 // Switch to new best branch
1159 if (!Reorganize(cursorIntermediate))
1161 InvalidChainFound(cursor);
1162 return false; // reorganize failed
1165 // Connect further blocks
1166 foreach (var currentCursor in secondary)
1169 if (!currentCursor.ReadFromFile(ref fStreamReadWrite, out block))
1171 // ReadFromDisk failed
1175 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1176 if (!SetBestChainInner(currentCursor))
1183 nHashBestChain = cursor.Hash;
1184 bestBlockCursor = cursor;
1185 nBestHeight = cursor.nHeight;
1186 nBestChainTrust = cursor.nChainTrust;
1187 nTimeBestReceived = Interop.GetTime();
1188 nTransactionsUpdated++;
1193 private void InvalidChainFound(CBlockStoreItem cursor)
1195 throw new NotImplementedException();
1198 private bool Reorganize(CBlockStoreItem cursorIntermediate)
1201 var fork = bestBlockCursor;
1202 var longer = cursorIntermediate;
1204 while (fork.ItemID != longer.ItemID)
1206 while (longer.nHeight > fork.nHeight)
1208 if ((longer = longer.prev) == null)
1210 return false; // longer.prev is null
1214 if (fork.ItemID == longer.ItemID)
1219 if ((fork = fork.prev) == null)
1221 return false; // fork.prev is null
1225 // List of what to disconnect
1226 var disconnect = new List<CBlockStoreItem>();
1227 for (var cursor = bestBlockCursor; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
1229 disconnect.Add(cursor);
1232 // List of what to connect
1233 var connect = new List<CBlockStoreItem>();
1234 for (var cursor = cursorIntermediate; cursor.ItemID != fork.ItemID; cursor = cursor.prev)
1236 connect.Add(cursor);
1240 // Disconnect shorter branch
1241 var txResurrect = new List<CTransaction>();
1242 foreach (var blockCursor in disconnect)
1245 if (!blockCursor.ReadFromFile(ref fStreamReadWrite, out block))
1247 return false; // ReadFromFile for disconnect failed.
1249 if (!DisconnectBlock(blockCursor, ref block))
1251 return false; // DisconnectBlock failed.
1254 // Queue memory transactions to resurrect
1255 foreach (var tx in block.vtx)
1257 if (!tx.IsCoinBase && !tx.IsCoinStake)
1259 txResurrect.Add(tx);
1265 // Connect longer branch
1266 var txDelete = new List<CTransaction>();
1267 foreach (var cursor in connect)
1270 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
1272 return false; // ReadFromDisk for connect failed
1275 if (!ConnectBlock(cursor, ref block))
1278 return false; // ConnectBlock failed
1281 // Queue memory transactions to delete
1282 foreach (var tx in block.vtx)
1288 if (!WriteHashBestChain(cursorIntermediate.Hash))
1290 return false; // WriteHashBestChain failed
1293 // Make sure it's successfully written to disk
1296 // Resurrect memory transactions that were in the disconnected branch
1297 foreach (var tx in txResurrect)
1299 mapUnconfirmedTx.TryAdd(tx.Hash, tx);
1302 // Delete redundant memory transactions that are in the connected branch
1303 foreach (var tx in txDelete)
1306 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
1309 return true; // Done
1312 private bool DisconnectBlock(CBlockStoreItem blockCursor, ref CBlock block)
1314 throw new NotImplementedException();
1317 private bool SetBestChainInner(CBlockStoreItem cursor)
1319 uint256 hash = cursor.Hash;
1321 if (!cursor.ReadFromFile(ref fStreamReadWrite, out block))
1323 return false; // Unable to read block from file.
1326 // Adding to current best branch
1327 if (!ConnectBlock(cursor, ref block) || !WriteHashBestChain(hash))
1329 InvalidChainFound(cursor);
1333 // Add to current best branch
1334 cursor.prev.next = cursor;
1338 // Delete redundant memory transactions
1339 foreach (var tx in block.vtx)
1342 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
1348 private bool ConnectBlock(CBlockStoreItem cursor, ref CBlock block, bool fJustCheck=false)
1350 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1351 if (!block.CheckBlock(!fJustCheck, !fJustCheck, false))
1353 return false; // Invalid block found.
1356 bool fScriptChecks = cursor.nHeight >= Checkpoints.TotalBlocksEstimate;
1357 var scriptFlags = scriptflag.SCRIPT_VERIFY_NOCACHE | scriptflag.SCRIPT_VERIFY_P2SH;
1361 ulong nValueOut = 0;
1364 var queuedMerkleNodes = new Dictionary<uint256, CMerkleNode>();
1365 var queued = new Dictionary<COutPoint, TxOutItem>();
1367 for (var nTx = 0; nTx < block.vtx.Length; nTx++)
1369 var tx = block.vtx[nTx];
1370 var hashTx = tx.Hash;
1371 var nTxPos = cursor.nBlockPos + block.GetTxOffset(nTx);
1373 Dictionary<COutPoint, TxOutItem> txouts;
1374 if (GetOutputs(hashTx, out txouts))
1376 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1377 // unless those are already completely spent.
1381 nSigOps += tx.LegacySigOpCount;
1382 if (nSigOps > CBlock.nMaxSigOps)
1384 return false; // too many sigops
1387 var inputs = new Dictionary<COutPoint, TxOutItem>();
1391 nValueOut += tx.nValueOut;
1396 if (!FetchInputs(tx, ref queued, ref inputs, true, out Invalid))
1398 return false; // Unable to fetch some inputs.
1401 // Add in sigops done by pay-to-script-hash inputs;
1402 // this is to prevent a "rogue miner" from creating
1403 // an incredibly-expensive-to-validate block.
1404 nSigOps += tx.GetP2SHSigOpCount(inputs);
1405 if (nSigOps > CBlock.nMaxSigOps)
1407 return false; // too many sigops
1410 ulong nTxValueIn = tx.GetValueIn(inputs);
1411 ulong nTxValueOut = tx.nValueOut;
1413 nValueIn += nTxValueIn;
1414 nValueOut += nTxValueOut;
1416 if (!tx.IsCoinStake)
1418 nFees += nTxValueIn - nTxValueOut;
1421 if (!ConnectInputs(tx, inputs, queued, cursor, fScriptChecks, scriptFlags))
1427 for (var i = 0u; i < tx.vout.Length; i++)
1429 var mNode = new CMerkleNode(cursor.ItemID, nTxPos, tx);
1430 queuedMerkleNodes.Add(hashTx, mNode);
1432 var outKey = new COutPoint(hashTx, i);
1433 var outData = new TxOutItem(tx.vout[i], i);
1435 outData.IsSpent = false;
1437 queued.Add(outKey, outData);
1441 if (!block.IsProofOfStake)
1443 ulong nBlockReward = CBlock.GetProofOfWorkReward(cursor.nBits, nFees);
1445 // Check coinbase reward
1446 if (block.vtx[0].nValueOut > nBlockReward)
1448 return false; // coinbase reward exceeded
1452 cursor.nMint = (long) (nValueOut - nValueIn + nFees);
1453 cursor.nMoneySupply = (cursor.prev != null ? cursor.prev.nMoneySupply : 0) + (long)nValueOut - (long)nValueIn;
1455 if (!UpdateDBCursor(ref cursor))
1457 return false; // Unable to commit changes
1465 // Write queued transaction changes
1466 var actualMerkleNodes = new Dictionary<uint256, CMerkleNode>();
1467 var queuedOutpointItems = new List<TxOutItem>();
1468 foreach(KeyValuePair<COutPoint, TxOutItem> outPair in queued)
1470 uint256 txID = outPair.Key.hash;
1471 CMerkleNode merkleNode;
1473 if (actualMerkleNodes.ContainsKey(txID))
1475 merkleNode = actualMerkleNodes[txID];
1479 merkleNode = queuedMerkleNodes[txID];
1480 if (!SaveMerkleNode(ref merkleNode))
1482 // Unable to save merkle tree cursor.
1485 actualMerkleNodes.Add(txID, merkleNode);
1488 var outItem = outPair.Value;
1489 outItem.nMerkleNodeID = merkleNode.nMerkleNodeID;
1491 queuedOutpointItems.Add(outItem);
1494 if (!SaveOutpoints(ref queuedOutpointItems))
1496 return false; // Unable to save outpoints
1499 // TODO: the remaining stuff lol :D
1501 throw new NotImplementedException();
1505 /// Insert set of outpoints
1507 /// <param name="queuedOutpointItems">List of TxOutItem objects.</param>
1508 /// <returns>Result</returns>
1509 private bool SaveOutpoints(ref List<TxOutItem> queuedOutpointItems)
1511 return dbConn.InsertAll(queuedOutpointItems, false) != 0;
1515 /// Insert merkle node into db and set actual record id value.
1517 /// <param name="merkleNode">Merkle node object reference.</param>
1518 /// <returns>Result</returns>
1519 private bool SaveMerkleNode(ref CMerkleNode merkleNode)
1521 if (dbConn.Insert(merkleNode) == 0)
1526 merkleNode.nMerkleNodeID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
1531 private bool ConnectInputs(CTransaction tx, Dictionary<COutPoint, TxOutItem> inputs, Dictionary<COutPoint, TxOutItem> queued, CBlockStoreItem cursor, bool fScriptChecks, scriptflag scriptFlags)
1533 throw new NotImplementedException();
1536 private bool WriteHashBestChain(uint256 hash)
1538 throw new NotImplementedException();
1542 /// Try to find proof-of-stake hash in the map.
1544 /// <param name="blockHash">Block hash</param>
1545 /// <param name="hashProofOfStake">Proof-of-stake hash</param>
1546 /// <returns>Proof-of-Stake hash value</returns>
1547 private bool GetProofOfStakeHash(uint256 blockHash, out uint256 hashProofOfStake)
1549 return mapProofOfStake.TryGetValue(blockHash, out hashProofOfStake);
1552 public bool AcceptBlock(ref CBlock block)
1554 uint256 nHash = block.header.Hash;
1556 if (blockMap.ContainsKey(nHash))
1558 // Already have this block.
1562 CBlockStoreItem prevBlockCursor = null;
1563 if (!blockMap.TryGetValue(block.header.prevHash, out prevBlockCursor))
1565 // Unable to get the cursor.
1569 var prevBlockHeader = prevBlockCursor.BlockHeader;
1571 // TODO: proof-of-work/proof-of-stake verification
1572 uint nHeight = prevBlockCursor.nHeight + 1;
1574 // Check timestamp against prev
1575 if (NetInfo.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
1577 // block's timestamp is too early
1581 // Check that all transactions are finalized
1582 foreach (var tx in block.vtx)
1584 if (!tx.IsFinal(nHeight, block.header.nTime))
1590 // TODO: Enforce rule that the coinbase starts with serialized block height
1592 // Write block to file.
1593 var itemTemplate = new CBlockStoreItem()
1598 itemTemplate.FillHeader(block.header);
1600 if (!AddItemToIndex(ref itemTemplate, ref block))
1609 /// GEt block by hash.
1611 /// <param name="blockHash">Block hash</param>
1612 /// <param name="block">Block object reference</param>
1613 /// <param name="nBlockPos">Block position reference</param>
1614 /// <returns>Result</returns>
1615 public bool GetBlock(uint256 blockHash, ref CBlock block, ref long nBlockPos)
1617 CBlockStoreItem cursor;
1619 if (!blockMap.TryGetValue(blockHash, out cursor))
1621 return false; // Unable to fetch block cursor
1624 nBlockPos = cursor.nBlockPos;
1626 return cursor.ReadFromFile(ref fStreamReadWrite, out block);
1631 /// Interface for join
1633 interface IBlockJoinMerkle : IBlockStorageItem, IMerkleNode
1638 /// Get block and transaction by transaction hash.
1640 /// <param name="TxID">Transaction hash</param>
1641 /// <param name="block">Block reference</param>
1642 /// <param name="tx">Transaction reference</param>
1643 /// <param name="nBlockPos">Block position reference</param>
1644 /// <param name="nTxPos">Transaction position reference</param>
1645 /// <returns>Result of operation</returns>
1646 public bool GetBlockByTransactionID(uint256 TxID, ref CBlock block, ref CTransaction tx, ref long nBlockPos, ref long nTxPos)
1648 var queryResult = dbConn.Query<IBlockJoinMerkle>("select * from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
1650 if (queryResult.Count == 1)
1652 CBlockStoreItem blockCursor = (CBlockStoreItem) queryResult[0];
1653 CMerkleNode txCursor = (CMerkleNode)queryResult[0];
1655 var reader = new BinaryReader(fStreamReadWrite).BaseStream;
1657 if (!txCursor.ReadFromFile(ref reader, blockCursor.nBlockPos, out tx))
1659 return false; // Unable to read transaction
1662 return blockCursor.ReadFromFile(ref reader, out block);
1670 public bool GetOutputs(uint256 transactionHash, out Dictionary<COutPoint, TxOutItem> txouts, bool fUnspentOnly=true)
1674 var queryParams = new object[] { (byte[])transactionHash, fUnspentOnly ? OutputFlags.AVAILABLE : (OutputFlags.AVAILABLE | OutputFlags.SPENT) };
1675 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);
1677 if (queryResult.Count != 0)
1679 txouts = new Dictionary<COutPoint, TxOutItem>();
1681 foreach (var o in queryResult)
1683 var outpointKey = new COutPoint(transactionHash, o.nOut);
1684 var outpointData = o;
1686 txouts.Add(outpointKey, outpointData);
1689 // There are some unspent inputs.
1693 // This transaction has been spent completely.
1697 public bool WriteNodes(ref CMerkleNode[] merkleNodes)
1705 /// Get block cursor from map.
1707 /// <param name="blockHash">block hash</param>
1708 /// <returns>Cursor or null</returns>
1709 public CBlockStoreItem GetMapCursor(uint256 blockHash)
1713 // Genesis block has zero prevHash and no parent.
1717 CBlockStoreItem cursor = null;
1718 blockMap.TryGetValue(blockHash, out cursor);
1724 /// Load cursor from database.
1726 /// <param name="blockHash">Block hash</param>
1727 /// <returns>Block cursor object</returns>
1728 public CBlockStoreItem GetDBCursor(uint256 blockHash)
1730 // Trying to get cursor from the database.
1731 var QueryBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
1733 if (QueryBlockCursor.Count == 1)
1735 return QueryBlockCursor[0];
1743 /// Update cursor in memory and on disk.
1745 /// <param name="cursor">Block cursor</param>
1746 /// <returns>Result</returns>
1747 public bool UpdateMapCursor(CBlockStoreItem cursor)
1749 var original = blockMap[cursor.Hash];
1750 return blockMap.TryUpdate(cursor.Hash, cursor, original);
1754 /// Update cursor record in database.
1756 /// <param name="cursor">Block cursor object</param>
1757 /// <returns>Result</returns>
1758 public bool UpdateDBCursor(ref CBlockStoreItem cursor)
1760 return dbConn.Update(cursor) != 0;
1763 public bool ProcessBlock(ref CBlock block)
1765 var blockHash = block.header.Hash;
1767 if (blockMap.ContainsKey(blockHash))
1769 // We already have this block.
1773 if (orphanMap.ContainsKey(blockHash))
1775 // We already have block in the list of orphans.
1779 // TODO: Limited duplicity on stake and reserialization of block signature
1781 if (!block.CheckBlock(true, true, true))
1783 // Preliminary checks failure.
1787 if (block.IsProofOfStake)
1789 if (!block.SignatureOK)
1791 // Proof-of-Stake signature validation failure.
1795 // TODO: proof-of-stake validation
1797 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1798 if (!StakeModifier.CheckProofOfStake(block.vtx[1], block.header.nBits, ref hashProofOfStake, ref targetProofOfStake))
1800 return false; // do not error here as we expect this during initial block download
1802 if (!mapProofOfStake.ContainsKey(blockHash))
1804 // add to mapProofOfStake
1805 mapProofOfStake.TryAdd(blockHash, hashProofOfStake);
1810 // TODO: difficulty verification
1812 // If don't already have its previous block, shunt it off to holding area until we get it
1813 if (!blockMap.ContainsKey(block.header.prevHash))
1815 if (block.IsProofOfStake)
1817 // TODO: limit duplicity on stake
1820 var block2 = new CBlock(block);
1821 orphanMap.TryAdd(blockHash, block2);
1822 orphanMapByPrev.TryAdd(blockHash, block2);
1827 // Store block to disk
1828 if (!AcceptBlock(ref block))
1834 // Recursively process any orphan blocks that depended on this one
1835 var orphansQueue = new List<uint256>();
1836 orphansQueue.Add(blockHash);
1838 for (int i = 0; i < orphansQueue.Count; i++)
1840 var hashPrev = orphansQueue[i];
1842 foreach (var pair in orphanMap)
1844 var orphanBlock = pair.Value;
1846 if (orphanBlock.header.prevHash == blockHash)
1848 if (AcceptBlock(ref orphanBlock))
1850 orphansQueue.Add(pair.Key);
1854 orphanMap.TryRemove(pair.Key, out dummy1);
1859 orphanMap.TryRemove(hashPrev, out dummy2);
1865 public bool ParseBlockFile(string BlockFile = "bootstrap.dat")
1867 // TODO: Rewrite completely.
1871 var buffer = new byte[CBlock.nMaxBlockSize]; // Max block size is 1Mb
1872 var intBuffer = new byte[4];
1874 var fStream2 = File.OpenRead(BlockFile);
1875 var readerForBlocks = new BinaryReader(fStream2).BaseStream;
1877 readerForBlocks.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
1879 while (readerForBlocks.Read(buffer, 0, 4) == 4) // Read magic number
1881 var nMagic = BitConverter.ToUInt32(buffer, 0);
1882 if (nMagic != 0xe5e9e8e4)
1884 throw new Exception("Incorrect magic number.");
1887 var nBytesRead = readerForBlocks.Read(buffer, 0, 4);
1888 if (nBytesRead != 4)
1890 throw new Exception("BLKSZ EOF");
1893 var nBlockSize = BitConverter.ToInt32(buffer, 0);
1895 nOffset = readerForBlocks.Position;
1897 nBytesRead = readerForBlocks.Read(buffer, 0, nBlockSize);
1899 if (nBytesRead == 0 || nBytesRead != nBlockSize)
1901 throw new Exception("BLK EOF");
1904 var block = new CBlock(buffer);
1905 var hash = block.header.Hash;
1907 if (blockMap.ContainsKey(hash))
1912 if (!ProcessBlock(ref block))
1914 throw new Exception("Invalid block: " + block.header.Hash);
1917 int nCount = blockMap.Count;
1918 Console.WriteLine("nCount={0}, Hash={1}, Time={2}", nCount, block.header.Hash, DateTime.Now); // Commit on each 100th block
1921 if (nCount % 100 == 0 && nCount != 0)
1923 Console.WriteLine("Commit...");
1925 dbConn.BeginTransaction();
1939 public void Dispose()
1942 GC.SuppressFinalize(this);
1945 protected virtual void Dispose(bool disposing)
1951 // Free other state (managed objects).
1953 fStreamReadWrite.Dispose();