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 byte[] Height { get; set; }
131 /// Block position in file, encoded in VarInt format
134 public byte[] BlockPos { get; set; }
137 /// Block size in bytes, encoded in VarInt format
139 [Column("BlockSize")]
140 public byte[] BlockSize { get; set; }
144 /// Accessor and mutator for BlockPos value.
147 public long nBlockPos
149 get { return (long)VarInt.DecodeVarInt(BlockPos); }
150 set { BlockPos = VarInt.EncodeVarInt(value); }
154 /// Accessor and mutator for BlockSize value.
157 public int nBlockSize
159 get { return (int)VarInt.DecodeVarInt(BlockSize); }
160 set { BlockSize = VarInt.EncodeVarInt(value); }
164 /// Accessor and mutator for Height value.
169 get { return (uint)VarInt.DecodeVarInt(Height); }
170 set { Height = VarInt.EncodeVarInt(value); }
175 /// Fill database item with data from given block header.
177 /// <param name="header">Block header</param>
178 /// <returns>Header hash</returns>
179 public uint256 FillHeader(CBlockHeader header)
181 uint256 _hash = header.Hash;
185 nVersion = header.nVersion;
186 prevHash = header.prevHash;
187 merkleRoot = header.merkleRoot;
188 nTime = header.nTime;
189 nBits = header.nBits;
190 nNonce = header.nNonce;
196 /// Reconstruct block header from item data.
198 public CBlockHeader BlockHeader
202 CBlockHeader header = new CBlockHeader();
204 header.nVersion = nVersion;
205 header.prevHash = prevHash;
206 header.merkleRoot = merkleRoot;
207 header.nTime = nTime;
208 header.nBits = nBits;
209 header.nNonce = nNonce;
216 /// Read block from file.
218 /// <param name="reader">Stream with read access.</param>
219 /// <param name="reader">CBlock reference.</param>
220 /// <returns>Result</returns>
221 public bool ReadFromFile(ref Stream reader, out CBlock block)
223 var buffer = new byte[nBlockSize];
228 reader.Seek(nBlockPos, SeekOrigin.Begin);
230 if (nBlockSize != reader.Read(buffer, 0, nBlockSize))
235 block = new CBlock(buffer);
244 catch (BlockException)
246 // Constructor exception
252 /// Writes given block to file and prepares cursor object for insertion into the database.
254 /// <param name="writer">Stream with write access.</param>
255 /// <param name="block">CBlock reference.</param>
256 /// <returns>Result</returns>
257 public bool WriteToFile(ref Stream writer, ref CBlock block)
261 byte[] blockBytes = block;
263 var magicBytes = BitConverter.GetBytes(CBlockStore.nMagicNumber);
264 var blkLenBytes = BitConverter.GetBytes(blockBytes.Length);
266 // Seek to the end and then append magic bytes there.
267 writer.Seek(0, SeekOrigin.End);
268 writer.Write(magicBytes, 0, magicBytes.Length);
269 writer.Write(blkLenBytes, 0, blkLenBytes.Length);
271 // Save block size and current position in the block cursor fields.
272 nBlockPos = writer.Position;
273 nBlockSize = blockBytes.Length;
275 // Write block and flush the stream.
276 writer.Write(blockBytes, 0, blockBytes.Length);
288 // Some serialization error
294 /// Previous block cursor
297 public CBlockStoreItem prev {
298 get { return CBlockStore.Instance.GetCursor(prevHash); }
302 /// Next block cursor
305 public CBlockStoreItem next
309 if (nextHash == null)
314 return CBlockStore.Instance.GetCursor(nextHash);
318 CBlockStoreItem newCursor = this;
319 newCursor.nextHash = value.Hash;
321 CBlockStore.Instance.UpdateCursor(this, ref newCursor);
328 get { return (next != null); }
332 /// STake modifier generation flag
335 public bool GeneratedStakeModifier
337 get { return (BlockTypeFlag & BlockType.BLOCK_STAKE_MODIFIER) != 0; }
341 /// Stake entropy bit
344 public uint StakeEntropyBit
346 get { return ((uint)(BlockTypeFlag & BlockType.BLOCK_STAKE_ENTROPY) >> 1); }
350 /// Sets stake modifier and flag.
352 /// <param name="nModifier">New stake modifier.</param>
353 /// <param name="fGeneratedStakeModifier">Set generation flag?</param>
354 public void SetStakeModifier(long nModifier, bool fGeneratedStakeModifier)
356 nStakeModifier = nModifier;
357 if (fGeneratedStakeModifier)
358 BlockTypeFlag |= BlockType.BLOCK_STAKE_MODIFIER;
364 /// <param name="nEntropyBit">Entropy bit value (0 or 1).</param>
365 /// <returns>False if value is our of range.</returns>
366 public bool SetStakeEntropyBit(byte nEntropyBit)
370 BlockTypeFlag |= (nEntropyBit != 0 ? BlockType.BLOCK_STAKE_ENTROPY : 0);
375 /// Set proof-of-stake flag.
377 public void SetProofOfStake()
379 BlockTypeFlag |= BlockType.BLOCK_PROOF_OF_STAKE;
383 /// Block has no proof-of-stake flag.
386 public bool IsProofOfWork
388 get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) == 0; }
392 /// Block has proof-of-stake flag set.
395 public bool IsProofOfStake
397 get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) != 0; }
401 /// Block trust score.
404 public uint256 nBlockTrust
409 nTarget.Compact = nBits;
412 if (nTime < NetUtils.nChainChecksSwitchTime)
414 return IsProofOfStake ? (new uint256(1) << 256) / (nTarget + 1) : 1;
419 // Calculate work amount for block
420 var nPoWTrust = NetUtils.nPoWBase / (nTarget + 1);
422 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
423 nPoWTrust = (IsProofOfStake || !nPoWTrust) ? 1 : nPoWTrust;
425 // Return nPoWTrust for the first 12 blocks
426 if (prev == null || prev.nHeight < 12)
429 CBlockStoreItem currentIndex = prev;
433 var nNewTrust = (new uint256(1) << 256) / (nTarget + 1);
435 // Return 1/3 of score if parent block is not the PoW block
436 if (!prev.IsProofOfWork)
438 return nNewTrust / 3;
443 // Check last 12 blocks type
444 while (prev.nHeight - currentIndex.nHeight < 12)
446 if (currentIndex.IsProofOfWork)
450 currentIndex = currentIndex.prev;
453 // Return 1/3 of score if less than 3 PoW blocks found
456 return nNewTrust / 3;
463 var nLastBlockTrust = prev.nChainTrust - prev.prev.nChainTrust;
465 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
466 if (!prev.IsProofOfStake || !prev.prev.IsProofOfStake)
468 return nPoWTrust + (2 * nLastBlockTrust / 3);
473 // Check last 12 blocks type
474 while (prev.nHeight - currentIndex.nHeight < 12)
476 if (currentIndex.IsProofOfStake)
480 currentIndex = currentIndex.prev;
483 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
486 return nPoWTrust + (2 * nLastBlockTrust / 3);
489 nTarget.Compact = prev.nBits;
496 var nNewTrust = (new uint256(1) << 256) / (nTarget + 1);
498 // Return nPoWTrust + full trust score for previous block nBits
499 return nPoWTrust + nNewTrust;
505 /// Stake modifier checksum.
507 public uint nStakeModifierChecksum;
510 /// Chain trust score
512 public uint256 nChainTrust;
518 public enum BlockType
520 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
521 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
522 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
526 /// Transaction type.
528 public enum TxFlags : byte
538 public enum OutputFlags : byte
540 AVAILABLE, // Unspent output
541 SPENT // Spent output
544 [Table("MerkleNodes")]
545 public class CMerkleNode : IMerkleNode
551 [PrimaryKey, AutoIncrement]
552 public long nMerkleNodeID { get; set; }
555 /// Reference to parent block database item.
557 [ForeignKey(typeof(CBlockStoreItem), Name = "ItemId")]
558 public long nParentBlockID { get; set; }
561 /// Transaction type flag
563 [Column("TransactionFlags")]
564 public TxFlags TransactionFlags { get; set; }
569 [Column("TransactionHash")]
570 public byte[] TransactionHash { get; set; }
573 /// Transaction offset from the beginning of block header, encoded in VarInt format.
576 public byte[] TxOffset { get; set; }
579 /// Transaction size, encoded in VarInt format.
582 public byte[] TxSize { get; set; }
586 /// Read transaction from file.
588 /// <param name="reader">Stream with read access.</param>
589 /// <param name="tx">CTransaction reference.</param>
590 /// <returns>Result</returns>
591 public bool ReadFromFile(ref Stream reader, long nBlockPos, out CTransaction tx)
593 var buffer = new byte[CTransaction.nMaxTxSize];
599 reader.Seek(nBlockPos + nTxOffset, SeekOrigin.Begin); // Seek to transaction offset
601 if (nTxSize != reader.Read(buffer, 0, nTxSize))
606 tx = new CTransaction(buffer);
615 catch (TransactionConstructorException)
623 /// Transaction offset accessor
626 public long nTxOffset
628 get { return (long) VarInt.DecodeVarInt(TxOffset); }
632 /// Transaction size accessor
637 get { return (int)VarInt.DecodeVarInt(TxSize); }
643 public class TxOutItem : ITxOutItem
646 /// Reference to transaction item.
648 [ForeignKey(typeof(CMerkleNode), Name = "nMerkleNodeID")]
649 public long nMerkleNodeID { get; set; }
654 public OutputFlags outputFlags { get; set; }
657 /// Output number in VarInt format.
659 public byte[] OutputNumber { get; set; }
662 /// Output value in VarInt format.
664 public byte[] OutputValue { get; set; }
667 /// Second half of script which contains spending instructions.
669 public byte[] scriptPubKey { get; set; }
672 /// Getter for output number.
676 get { return (uint)VarInt.DecodeVarInt(OutputNumber); }
680 /// Getter for output value.
684 get { return VarInt.DecodeVarInt(OutputValue); }
688 /// Getter ans setter for IsSpent flag.
692 get { return (outputFlags & OutputFlags.SPENT) != 0; }
693 set { outputFlags |= value ? OutputFlags.SPENT : OutputFlags.AVAILABLE; }
697 public class CBlockStore : IDisposable
699 public const uint nMagicNumber = 0xe5e9e8e4;
701 private bool disposed = false;
702 private object LockObj = new object();
705 /// SQLite connection object.
707 private SQLiteConnection dbConn;
712 private string strBlockFile;
715 /// Index database file.
717 private string strDbFile;
720 /// Map of block tree nodes.
722 /// blockHash => CBlockStoreItem
724 private ConcurrentDictionary<uint256, CBlockStoreItem> blockMap = new ConcurrentDictionary<uint256, CBlockStoreItem>();
727 /// Orphaned blocks map.
729 private ConcurrentDictionary<uint256, CBlock> orphanMap = new ConcurrentDictionary<uint256, CBlock>();
730 private ConcurrentDictionary<uint256, CBlock> orphanMapByPrev = new ConcurrentDictionary<uint256, CBlock>();
733 /// Unconfirmed transactions.
735 /// TxID => Transaction
737 private ConcurrentDictionary<uint256, CTransaction> mapUnconfirmedTx = new ConcurrentDictionary<uint256, CTransaction>();
740 /// Map of the proof-of-stake hashes. This is necessary for stake duplication checks.
742 private ConcurrentDictionary<uint256, uint256> mapProofOfStake = new ConcurrentDictionary<uint256, uint256>();
745 private ConcurrentDictionary<COutPoint, uint> mapStakeSeen = new ConcurrentDictionary<COutPoint, uint>();
746 private ConcurrentDictionary<COutPoint, uint> mapStakeSeenOrphan = new ConcurrentDictionary<COutPoint, uint>();
749 /// Trust score for the longest chain.
751 private uint256 nBestChainTrust = 0;
754 /// Top block of the best chain.
756 private uint256 nHashBestChain = 0;
759 /// Cursor which is pointing us to the end of best chain.
761 private CBlockStoreItem bestBlockCursor = null;
764 /// Cursor which is always pointing us to genesis block.
766 private CBlockStoreItem genesisBlockCursor = null;
769 /// Current and the only instance of block storage manager. Should be a property with private setter though it's enough for the beginning.
771 public static CBlockStore Instance = null;
774 /// Block file stream with read/write access
776 private Stream fStreamReadWrite;
779 /// Init the block storage manager.
781 /// <param name="IndexDB">Path to index database</param>
782 /// <param name="BlockFile">Path to block file</param>
783 public CBlockStore(string IndexDB = "blockstore.dat", string BlockFile = "blk0001.dat")
786 strBlockFile = BlockFile;
788 bool firstInit = !File.Exists(strDbFile);
789 dbConn = new SQLiteConnection(new SQLitePlatformGeneric(), strDbFile);
791 fStreamReadWrite = File.Open(strBlockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
800 dbConn.CreateTable<CBlockStoreItem>(CreateFlags.AutoIncPK);
801 dbConn.CreateTable<CMerkleNode>(CreateFlags.AutoIncPK);
802 dbConn.CreateTable<TxOutItem>(CreateFlags.ImplicitPK);
804 var genesisBlock = new CBlock(
806 "01000000" + // nVersion=1
807 "0000000000000000000000000000000000000000000000000000000000000000" + // prevhash is zero
808 "7b0502ad2f9f675528183f83d6385794fbcaa914e6d385c6cb1d866a3b3bb34c" + // merkle root
809 "398e1151" + // nTime=1360105017
810 "ffff0f1e" + // nBits=0x1e0fffff
811 "d3091800" + // nNonce=1575379
813 "01000000" + // nVersion=1
814 "398e1151" + // nTime=1360105017
816 "0000000000000000000000000000000000000000000000000000000000000000" + // input txid is zero
817 "ffffffff" + // n=uint.maxValue
818 "4d" + // scriptSigLen=77
819 "04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936" + // scriptSig
820 "ffffffff" + // nSequence=uint.maxValue
822 "0000000000000000" + // nValue=0
823 "00" + // scriptPubkeyLen=0
824 "00000000" + // nLockTime=0
828 // Write block to file.
829 var itemTemplate = new CBlockStoreItem()
834 itemTemplate.FillHeader(genesisBlock.header);
836 if (!AddItemToIndex(ref itemTemplate, ref genesisBlock))
838 throw new Exception("Unable to write genesis block");
844 var blockTreeItems = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] order by [ItemId] asc");
846 // Init list of block items
847 foreach (var item in blockTreeItems)
849 blockMap.TryAdd(item.Hash, item);
851 if (item.IsProofOfStake)
853 // build mapStakeSeen
854 mapStakeSeen.TryAdd(item.prevoutStake, item.nStakeTime);
860 public bool GetTxOutCursor(COutPoint outpoint, ref TxOutItem txOutCursor)
862 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);
864 if (queryResults.Count == 1)
866 txOutCursor = queryResults[0];
876 public bool FetchInputs(ref CTransaction tx, ref Dictionary<uint256, TxOutItem> queued, out TxOutItem[] inputs, bool IsBlock, out bool Invalid)
881 StringBuilder queryBuilder = new StringBuilder();
883 queryBuilder.Append("select o.* from [Outputs] o left join [MerkleNodes] m on (m.[nMerkleNodeID] = o.[nMerkleNodeID]) where ");
885 for (var i = 0; i < tx.vin.Length; i++)
887 queryBuilder.AppendFormat(" {0} (m.[TransactionHash] = x'{1}' and o.[OutputNumber] = x'{2}')",
888 (i > 0 ? "or" : string.Empty), Interop.ToHex(tx.vin[i].prevout.hash),
889 Interop.ToHex(VarInt.EncodeVarInt(tx.vin[i].prevout.n)
893 var queryResults = dbConn.Query<TxOutItem>(queryBuilder.ToString());
895 if (queryResults.Count < tx.vin.Length)
897 // It seems than some transactions are being spent in the same block.
905 // TODO: use mapUnconfirmed
911 inputs = queryResults.ToArray();
917 private bool AddItemToIndex(ref CBlockStoreItem itemTemplate, ref CBlock block)
919 var writer = new BinaryWriter(fStreamReadWrite).BaseStream;
920 uint256 blockHash = itemTemplate.Hash;
922 if (blockMap.ContainsKey(blockHash))
924 // Already have this block.
928 // Compute chain trust score
929 itemTemplate.nChainTrust = (itemTemplate.prev != null ? itemTemplate.prev.nChainTrust : 0) + itemTemplate.nBlockTrust;
931 if (!itemTemplate.SetStakeEntropyBit(Entropy.GetStakeEntropyBit(itemTemplate.nHeight, blockHash)))
933 return false; // SetStakeEntropyBit() failed
936 // Save proof-of-stake hash value
937 if (itemTemplate.IsProofOfStake)
939 uint256 hashProofOfStake;
940 if (!GetProofOfStakeHash(blockHash, out hashProofOfStake))
942 return false; // hashProofOfStake not found
944 itemTemplate.hashProofOfStake = hashProofOfStake;
947 // compute stake modifier
948 long nStakeModifier = 0;
949 bool fGeneratedStakeModifier = false;
950 if (!StakeModifier.ComputeNextStakeModifier(itemTemplate, ref nStakeModifier, ref fGeneratedStakeModifier))
952 return false; // ComputeNextStakeModifier() failed
955 itemTemplate.SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
956 itemTemplate.nStakeModifierChecksum = StakeModifier.GetStakeModifierChecksum(itemTemplate);
958 // TODO: verify stake modifier checkpoints
961 if (block.IsProofOfStake)
963 itemTemplate.SetProofOfStake();
965 itemTemplate.prevoutStake = block.vtx[1].vin[0].prevout;
966 itemTemplate.nStakeTime = block.vtx[1].nTime;
969 if (!itemTemplate.WriteToFile(ref writer, ref block))
974 if (dbConn.Insert(itemTemplate) == 0 || !blockMap.TryAdd(blockHash, itemTemplate))
979 if (itemTemplate.nChainTrust > nBestChainTrust)
983 // TODO: SetBestChain implementation
986 if (!SetBestChain(ref itemTemplate))
988 return false; // SetBestChain failed.
996 private bool SetBestChain(ref CBlockStoreItem cursor)
998 dbConn.BeginTransaction();
1000 uint256 hashBlock = cursor.Hash;
1002 if (genesisBlockCursor == null && hashBlock == NetUtils.nHashGenesisBlock)
1004 genesisBlockCursor = cursor;
1006 else if (nHashBestChain == (uint256)cursor.prevHash)
1008 if (!SetBestChainInner(cursor))
1015 // the first block in the new chain that will cause it to become the new best chain
1016 CBlockStoreItem cursorIntermediate = cursor;
1018 // list of blocks that need to be connected afterwards
1019 List<CBlockStoreItem> secondary = new List<CBlockStoreItem>();
1021 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1022 // Try to limit how much needs to be done inside
1023 while (cursorIntermediate.prev != null && cursorIntermediate.prev.nChainTrust > bestBlockCursor.nChainTrust)
1025 secondary.Add(cursorIntermediate);
1026 cursorIntermediate = cursorIntermediate.prev;
1029 // Switch to new best branch
1030 if (!Reorganize(cursorIntermediate))
1033 InvalidChainFound(cursor);
1034 return false; // reorganize failed
1041 throw new NotImplementedException();
1044 private void InvalidChainFound(CBlockStoreItem cursor)
1046 throw new NotImplementedException();
1049 private bool Reorganize(CBlockStoreItem cursorIntermediate)
1051 throw new NotImplementedException();
1054 private bool SetBestChainInner(CBlockStoreItem cursor)
1056 uint256 hash = cursor.Hash;
1059 // Adding to current best branch
1060 if (!ConnectBlock(cursor, false, out block) || !WriteHashBestChain(hash))
1063 InvalidChainFound(cursor);
1067 // Add to current best branch
1068 cursor.prev.next = cursor;
1072 // Delete redundant memory transactions
1073 foreach (var tx in block.vtx)
1076 mapUnconfirmedTx.TryRemove(tx.Hash, out dummy);
1082 private bool ConnectBlock(CBlockStoreItem cursor, bool fJustCheck, out CBlock block)
1084 var reader = new BinaryReader(fStreamReadWrite).BaseStream;
1085 if (cursor.ReadFromFile(ref reader, out block))
1087 return false; // Unable to read block from file.
1090 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1091 if (!block.CheckBlock(!fJustCheck, !fJustCheck, false))
1093 return false; // Invalid block found.
1096 // TODO: the remaining stuff lol :D
1098 throw new NotImplementedException();
1101 private bool WriteHashBestChain(uint256 hash)
1103 throw new NotImplementedException();
1107 /// Try to find proof-of-stake hash in the map.
1109 /// <param name="blockHash">Block hash</param>
1110 /// <param name="hashProofOfStake">Proof-of-stake hash</param>
1111 /// <returns>Proof-of-Stake hash value</returns>
1112 private bool GetProofOfStakeHash(uint256 blockHash, out uint256 hashProofOfStake)
1114 return mapProofOfStake.TryGetValue(blockHash, out hashProofOfStake);
1117 public bool AcceptBlock(ref CBlock block)
1119 uint256 nHash = block.header.Hash;
1121 if (blockMap.ContainsKey(nHash))
1123 // Already have this block.
1127 CBlockStoreItem prevBlockCursor = null;
1128 if (!blockMap.TryGetValue(block.header.prevHash, out prevBlockCursor))
1130 // Unable to get the cursor.
1134 var prevBlockHeader = prevBlockCursor.BlockHeader;
1136 // TODO: proof-of-work/proof-of-stake verification
1137 uint nHeight = prevBlockCursor.nHeight + 1;
1139 // Check timestamp against prev
1140 if (NetUtils.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
1142 // block's timestamp is too early
1146 // Check that all transactions are finalized
1147 foreach (var tx in block.vtx)
1149 if (!tx.IsFinal(nHeight, block.header.nTime))
1155 // TODO: Enforce rule that the coinbase starts with serialized block height
1157 // Write block to file.
1158 var itemTemplate = new CBlockStoreItem()
1163 itemTemplate.FillHeader(block.header);
1165 if (!AddItemToIndex(ref itemTemplate, ref block))
1173 public bool GetBlock(uint256 blockHash, ref CBlock block, ref long nBlockPos)
1175 var reader = new BinaryReader(fStreamReadWrite).BaseStream;
1177 var QueryBlock = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
1179 if (QueryBlock.Count == 1)
1181 nBlockPos = QueryBlock[0].nBlockPos;
1182 return QueryBlock[0].ReadFromFile(ref reader, out block);
1192 /// Interface for join
1194 interface IBlockJoinMerkle : IBlockStorageItem, IMerkleNode
1199 /// Get block and transaction by transaction hash.
1201 /// <param name="TxID">Transaction hash</param>
1202 /// <param name="block">Block reference</param>
1203 /// <param name="tx">Transaction reference</param>
1204 /// <param name="nBlockPos">Block position reference</param>
1205 /// <param name="nTxPos">Transaction position reference</param>
1206 /// <returns>Result of operation</returns>
1207 public bool GetBlockByTransactionID(uint256 TxID, ref CBlock block, ref CTransaction tx, ref long nBlockPos, ref long nTxPos)
1209 var queryResult = dbConn.Query<IBlockJoinMerkle>("select *, from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
1211 if (queryResult.Count == 1)
1213 CBlockStoreItem blockCursor = (CBlockStoreItem) queryResult[0];
1214 CMerkleNode txCursor = (CMerkleNode)queryResult[0];
1216 var reader = new BinaryReader(fStreamReadWrite).BaseStream;
1218 if (!txCursor.ReadFromFile(ref reader, blockCursor.nBlockPos, out tx))
1220 return false; // Unable to read transaction
1223 return blockCursor.ReadFromFile(ref reader, out block);
1232 /// Get block cursor from map.
1234 /// <param name="blockHash">block hash</param>
1235 /// <returns>Cursor or null</returns>
1236 public CBlockStoreItem GetCursor(uint256 blockHash)
1240 // Genesis block has zero prevHash and no parent.
1244 // First, check our block map.
1245 CBlockStoreItem item = null;
1246 if (blockMap.TryGetValue(blockHash, out item))
1251 // Trying to get cursor from the database.
1252 var QueryBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
1254 if (QueryBlockCursor.Count == 1)
1256 blockMap.TryAdd(blockHash, QueryBlockCursor[0]);
1258 return QueryBlockCursor[0];
1266 /// Update cursor in memory and on disk.
1268 /// <param name="originalItem">Original cursor</param>
1269 /// <param name="newItem">New cursor</param>
1270 /// <returns></returns>
1271 public bool UpdateCursor(CBlockStoreItem originalItem, ref CBlockStoreItem newItem)
1273 if (blockMap.TryUpdate(originalItem.Hash, newItem, originalItem))
1275 return dbConn.Update(newItem) != 0;
1281 public bool ProcessBlock(ref CBlock block)
1283 var blockHash = block.header.Hash;
1285 if (blockMap.ContainsKey(blockHash))
1287 // We already have this block.
1291 if (orphanMap.ContainsKey(blockHash))
1293 // We already have block in the list of orphans.
1297 // TODO: Limited duplicity on stake and reserialization of block signature
1299 if (!block.CheckBlock(true, true, true))
1301 // Preliminary checks failure.
1305 if (block.IsProofOfStake)
1307 if (!block.SignatureOK)
1309 // Proof-of-Stake signature validation failure.
1313 // TODO: proof-of-stake validation
1315 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1316 if (!StakeModifier.CheckProofOfStake(block.vtx[1], block.header.nBits, ref hashProofOfStake, ref targetProofOfStake))
1318 return false; // do not error here as we expect this during initial block download
1320 if (!mapProofOfStake.ContainsKey(blockHash))
1322 // add to mapProofOfStake
1323 mapProofOfStake.TryAdd(blockHash, hashProofOfStake);
1328 // TODO: difficulty verification
1330 // If don't already have its previous block, shunt it off to holding area until we get it
1331 if (!blockMap.ContainsKey(block.header.prevHash))
1333 if (block.IsProofOfStake)
1335 // TODO: limit duplicity on stake
1338 var block2 = new CBlock(block);
1339 orphanMap.TryAdd(blockHash, block2);
1340 orphanMapByPrev.TryAdd(blockHash, block2);
1345 // Store block to disk
1346 if (!AcceptBlock(ref block))
1352 // Recursively process any orphan blocks that depended on this one
1353 var orphansQueue = new List<uint256>();
1354 orphansQueue.Add(blockHash);
1356 for (int i = 0; i < orphansQueue.Count; i++)
1358 var hashPrev = orphansQueue[i];
1360 foreach (var pair in orphanMap)
1362 var orphanBlock = pair.Value;
1364 if (orphanBlock.header.prevHash == blockHash)
1366 if (AcceptBlock(ref orphanBlock))
1368 orphansQueue.Add(pair.Key);
1372 orphanMap.TryRemove(pair.Key, out dummy1);
1377 orphanMap.TryRemove(hashPrev, out dummy2);
1383 public bool ParseBlockFile(string BlockFile = "bootstrap.dat")
1385 // TODO: Rewrite completely.
1389 var buffer = new byte[CBlock.nMaxBlockSize]; // Max block size is 1Mb
1390 var intBuffer = new byte[4];
1392 var fStream2 = File.OpenRead(BlockFile);
1393 var readerForBlocks = new BinaryReader(fStream2).BaseStream;
1395 readerForBlocks.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
1397 dbConn.BeginTransaction();
1399 while (readerForBlocks.Read(buffer, 0, 4) == 4) // Read magic number
1401 var nMagic = BitConverter.ToUInt32(buffer, 0);
1402 if (nMagic != 0xe5e9e8e4)
1404 throw new Exception("Incorrect magic number.");
1407 var nBytesRead = readerForBlocks.Read(buffer, 0, 4);
1408 if (nBytesRead != 4)
1410 throw new Exception("BLKSZ EOF");
1413 var nBlockSize = BitConverter.ToInt32(buffer, 0);
1415 nOffset = readerForBlocks.Position;
1417 nBytesRead = readerForBlocks.Read(buffer, 0, nBlockSize);
1419 if (nBytesRead == 0 || nBytesRead != nBlockSize)
1421 throw new Exception("BLK EOF");
1424 var block = new CBlock(buffer);
1425 var hash = block.header.Hash;
1427 if (blockMap.ContainsKey(hash))
1432 if (!ProcessBlock(ref block))
1434 throw new Exception("Invalid block: " + block.header.Hash);
1437 int nCount = blockMap.Count;
1438 Console.WriteLine("nCount={0}, Hash={1}, Time={2}", nCount, block.header.Hash, DateTime.Now); // Commit on each 100th block
1440 if (nCount % 100 == 0 && nCount != 0)
1442 Console.WriteLine("Commit...");
1444 dbConn.BeginTransaction();
1458 public void Dispose()
1461 GC.SuppressFinalize(this);
1464 protected virtual void Dispose(bool disposing)
1470 // Free other state (managed objects).
1472 fStreamReadWrite.Dispose();