/// Block headers table
/// </summary>
[Table("BlockStorage")]
- class CBlockStoreItem
+ public class CBlockStoreItem
{
/// <summary>
/// Item ID in the database
public uint nNonce { get; set; }
/// <summary>
+ /// Next block hash.
+ /// </summary>
+ public byte[] nextHash { get; set; }
+
+ /// <summary>
/// Block type flags
/// </summary>
public BlockType BlockTypeFlag { get; set; }
public long nStakeModifier { get; set; }
/// <summary>
- /// Stake entropy bit
+ /// Chain trust score
/// </summary>
- public byte nEntropyBit { get; set; }
+ public byte[] ChainTrust { get; set; }
/// <summary>
- /// Next block hash
+ /// Proof-of-Stake hash
/// </summary>
- public byte[] NextHash { get; set; }
+ public byte[] hashProofOfStake { get; set; }
/// <summary>
/// Block height
/// </summary>
/// <param name="header">Block header</param>
/// <returns>Header hash</returns>
- public ScryptHash256 FillHeader(CBlockHeader header)
+ public uint256 FillHeader(CBlockHeader header)
{
- ScryptHash256 _hash;
+ uint256 _hash;
Hash = _hash = header.Hash;
nVersion = header.nVersion;
CBlockHeader header = new CBlockHeader();
header.nVersion = nVersion;
- header.prevHash = new ScryptHash256(prevHash);
- header.merkleRoot = new Hash256(merkleRoot);
+ header.prevHash = prevHash;
+ header.merkleRoot = merkleRoot;
header.nTime = nTime;
header.nBits = nBits;
header.nNonce = nNonce;
return false;
}
}
+
+ /// <summary>
+ /// Previous block cursor
+ /// </summary>
+ [Ignore]
+ public CBlockStoreItem prev {
+ get { return CBlockStore.Instance.GetCursor(prevHash); }
+ }
+
+ /// <summary>
+ /// Next block cursor
+ /// </summary>
+ [Ignore]
+ public CBlockStoreItem next
+ {
+ get { return CBlockStore.Instance.GetCursor(nextHash); }
+ }
+
+ [Ignore]
+ bool IsInMainChain
+ {
+ get { return (next != null); }
+ }
+
+ /// <summary>
+ /// STake modifier generation flag
+ /// </summary>
+ [Ignore]
+ public bool GeneratedStakeModifier
+ {
+ get { return (BlockTypeFlag & BlockType.BLOCK_STAKE_MODIFIER) != 0; }
+ }
+
+ /// <summary>
+ /// Stake entropy bit
+ /// </summary>
+ [Ignore]
+ public uint StakeEntropyBit
+ {
+ get { return ((uint)(BlockTypeFlag & BlockType.BLOCK_STAKE_ENTROPY) >> 1); }
+ }
+
+ /// <summary>
+ /// Sets stake modifier and flag.
+ /// </summary>
+ /// <param name="nModifier">New stake modifier.</param>
+ /// <param name="fGeneratedStakeModifier">Set generation flag?</param>
+ public void SetStakeModifier(long nModifier, bool fGeneratedStakeModifier)
+ {
+ nStakeModifier = nModifier;
+ if (fGeneratedStakeModifier)
+ BlockTypeFlag |= BlockType.BLOCK_STAKE_MODIFIER;
+ }
+
+ /// <summary>
+ /// Set entropy bit.
+ /// </summary>
+ /// <param name="nEntropyBit">Entropy bit value (0 or 1).</param>
+ /// <returns>False if value is our of range.</returns>
+ public bool SetStakeEntropyBit(byte nEntropyBit)
+ {
+ if (nEntropyBit > 1)
+ return false;
+ BlockTypeFlag |= (nEntropyBit != 0 ? BlockType.BLOCK_STAKE_ENTROPY : 0);
+ return true;
+ }
+
+ /// <summary>
+ /// Set proof-of-stake flag.
+ /// </summary>
+ public void SetProofOfStake()
+ {
+ BlockTypeFlag |= BlockType.BLOCK_PROOF_OF_STAKE;
+ }
+
+ /// <summary>
+ /// Block has no proof-of-stake flag.
+ /// </summary>
+ [Ignore]
+ public bool IsProofOfWork
+ {
+ get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) == 0; }
+ }
+
+ /// <summary>
+ /// Block has proof-of-stake flag set.
+ /// </summary>
+ [Ignore]
+ public bool IsProofOfStake
+ {
+ get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) != 0; }
+ }
+
+ /// <summary>
+ /// Chain trust score.
+ /// </summary>
+ [Ignore]
+ public uint256 nChainTrust {
+ get
+ {
+ if (ChainTrust.Length != 32)
+ {
+ byte[] tmp = ChainTrust;
+ Array.Resize(ref tmp, 32);
+ ChainTrust = tmp;
+ }
+
+ return ChainTrust;
+ }
+ set { ChainTrust = Interop.TrimArray(value); }
+ }
+
+ /// <summary>
+ /// Block trust score.
+ /// </summary>
+ [Ignore]
+ public uint256 nBlockTrust
+ {
+ get
+ {
+ uint256 nTarget = 0;
+ nTarget.Compact = nBits;
+
+ /* Old protocol */
+ if (nTime < NetUtils.nChainChecksSwitchTime)
+ {
+ return IsProofOfStake ? (new uint256(1) << 256) / (nTarget + 1) : 1;
+ }
+
+ /* New protocol */
+
+ // Calculate work amount for block
+ var nPoWTrust = NetUtils.nPoWBase / (nTarget + 1);
+
+ // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
+ nPoWTrust = (IsProofOfStake || !nPoWTrust) ? 1 : nPoWTrust;
+
+ // Return nPoWTrust for the first 12 blocks
+ if (prev == null || prev.nHeight < 12)
+ return nPoWTrust;
+
+ CBlockStoreItem currentIndex = prev;
+
+ if (IsProofOfStake)
+ {
+ var nNewTrust = (new uint256(1) << 256) / (nTarget + 1);
+
+ // Return 1/3 of score if parent block is not the PoW block
+ if (!prev.IsProofOfWork)
+ {
+ return nNewTrust / 3;
+ }
+
+ int nPoWCount = 0;
+
+ // Check last 12 blocks type
+ while (prev.nHeight - currentIndex.nHeight < 12)
+ {
+ if (currentIndex.IsProofOfWork)
+ {
+ nPoWCount++;
+ }
+ currentIndex = currentIndex.prev;
+ }
+
+ // Return 1/3 of score if less than 3 PoW blocks found
+ if (nPoWCount < 3)
+ {
+ return nNewTrust / 3;
+ }
+
+ return nNewTrust;
+ }
+ else
+ {
+ var nLastBlockTrust = prev.nChainTrust - prev.prev.nChainTrust;
+
+ // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
+ if (!prev.IsProofOfStake || !prev.prev.IsProofOfStake)
+ {
+ return nPoWTrust + (2 * nLastBlockTrust / 3);
+ }
+
+ int nPoSCount = 0;
+
+ // Check last 12 blocks type
+ while (prev.nHeight - currentIndex.nHeight < 12)
+ {
+ if (currentIndex.IsProofOfStake)
+ {
+ nPoSCount++;
+ }
+ currentIndex = currentIndex.prev;
+ }
+
+ // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
+ if (nPoSCount < 7)
+ {
+ return nPoWTrust + (2 * nLastBlockTrust / 3);
+ }
+
+ nTarget.Compact = prev.nBits;
+
+ if (!nTarget)
+ {
+ return 0;
+ }
+
+ var nNewTrust = (new uint256(1) << 256) / (nTarget + 1);
+
+ // Return nPoWTrust + full trust score for previous block nBits
+ return nPoWTrust + nNewTrust;
+ }
+ }
+ }
+
}
/// <summary>
/// </summary>
public enum BlockType
{
- PROOF_OF_WORK,
- PROOF_OF_WORK_MODIFIER,
- PROOF_OF_STAKE,
- PROOF_OF_STAKE_MODIFIER
+ BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
+ BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
+ BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
/// <summary>
/// <returns>Result</returns>
public bool ReadFromFile(ref Stream reader, out CTransaction tx)
{
- var buffer = new byte[250000]; // Max transaction size is 250kB
+ var buffer = new byte[CTransaction.nMaxTxSize];
tx = null;
try
/// <summary>
/// Map of block tree nodes.
/// </summary>
- private ConcurrentDictionary<ScryptHash256, CBlockStoreItem> blockMap = new ConcurrentDictionary<ScryptHash256, CBlockStoreItem>();
+ private ConcurrentDictionary<uint256, CBlockStoreItem> blockMap = new ConcurrentDictionary<uint256, CBlockStoreItem>();
/// <summary>
/// Orphaned blocks map.
/// </summary>
- private ConcurrentDictionary<ScryptHash256, CBlock> orphanMap = new ConcurrentDictionary<ScryptHash256, CBlock>();
- private ConcurrentDictionary<ScryptHash256, CBlock> orphanMapByPrev = new ConcurrentDictionary<ScryptHash256, CBlock>();
+ private ConcurrentDictionary<uint256, CBlock> orphanMap = new ConcurrentDictionary<uint256, CBlock>();
+ private ConcurrentDictionary<uint256, CBlock> orphanMapByPrev = new ConcurrentDictionary<uint256, CBlock>();
/// <summary>
/// Map of unspent items.
/// </summary>
- private ConcurrentDictionary<Hash256, CTransactionStoreItem> txMap = new ConcurrentDictionary<Hash256, CTransactionStoreItem>();
-
- private CBlock genesisBlock = new CBlock(
- Interop.HexToArray(
- "01000000" + // nVersion=1
- "0000000000000000000000000000000000000000000000000000000000000000" + // prevhash is zero
- "7b0502ad2f9f675528183f83d6385794fbcaa914e6d385c6cb1d866a3b3bb34c" + // merkle root
- "398e1151" + // nTime=1360105017
- "ffff0f1e" + // nBits=0x1e0fffff
- "d3091800" + // nNonce=1575379
- "01" + // nTxCount=1
- "01000000" + // nVersion=1
- "398e1151" + // nTime=1360105017
- "01" + // nInputs=1
- "0000000000000000000000000000000000000000000000000000000000000000" + // input txid is zero
- "ffffffff" + // n=uint.maxValue
- "4d" + // scriptSigLen=77
- "04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936" + // scriptSig
- "ffffffff" + // nSequence=uint.maxValue
- "01" + // nOutputs=1
- "0000000000000000" + // nValue=0
- "00" + // scriptPubkeyLen=0
- "00000000" + // nLockTime=0
- "00" // sigLen=0
- ));
+ private ConcurrentDictionary<uint256, CTransactionStoreItem> txMap = new ConcurrentDictionary<uint256, CTransactionStoreItem>();
public static CBlockStore Instance;
fStreamReadWrite = File.Open(strBlockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+ Instance = this;
+
if (firstInit)
{
lock (LockObj)
dbConn.CreateTable<CBlockStoreItem>(CreateFlags.AutoIncPK);
dbConn.CreateTable<CTransactionStoreItem>(CreateFlags.ImplicitPK);
+ var genesisBlock = new CBlock(
+ Interop.HexToArray(
+ "01000000" + // nVersion=1
+ "0000000000000000000000000000000000000000000000000000000000000000" + // prevhash is zero
+ "7b0502ad2f9f675528183f83d6385794fbcaa914e6d385c6cb1d866a3b3bb34c" + // merkle root
+ "398e1151" + // nTime=1360105017
+ "ffff0f1e" + // nBits=0x1e0fffff
+ "d3091800" + // nNonce=1575379
+ "01" + // nTxCount=1
+ "01000000" + // nVersion=1
+ "398e1151" + // nTime=1360105017
+ "01" + // nInputs=1
+ "0000000000000000000000000000000000000000000000000000000000000000" + // input txid is zero
+ "ffffffff" + // n=uint.maxValue
+ "4d" + // scriptSigLen=77
+ "04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936" + // scriptSig
+ "ffffffff" + // nSequence=uint.maxValue
+ "01" + // nOutputs=1
+ "0000000000000000" + // nValue=0
+ "00" + // scriptPubkeyLen=0
+ "00000000" + // nLockTime=0
+ "00" // sigLen=0
+ ));
+
// Write block to file.
var itemTemplate = new CBlockStoreItem()
{
// Init list of block items
foreach (var item in blockTreeItems)
{
- blockMap.TryAdd(new ScryptHash256(item.Hash), item);
+ blockMap.TryAdd(item.Hash, item);
}
}
-
- Instance = this;
}
- public bool GetTransaction(Hash256 TxID, ref CTransaction tx)
+ public bool GetTransaction(uint256 TxID, ref CTransaction tx)
{
var reader = new BinaryReader(fStreamReadWrite).BaseStream;
var QueryTx = dbConn.Query<CTransactionStoreItem>("select * from [TransactionStorage] where [TransactionHash] = ?", (byte[])TxID);
private bool AddItemToIndex(ref CBlockStoreItem itemTemplate, ref CBlock block)
{
var writer = new BinaryWriter(fStreamReadWrite).BaseStream;
- var blockHash = new ScryptHash256(itemTemplate.Hash);
+ uint256 blockHash = itemTemplate.Hash;
if (blockMap.ContainsKey(blockHash))
{
return false;
}
- // TODO: compute chain trust, set stake entropy bit, record proof-of-stake hash value
+ // Compute chain trust score
+ itemTemplate.nChainTrust = (itemTemplate.prev != null ? itemTemplate.prev.nChainTrust : 0) + itemTemplate.nBlockTrust;
+
+ if (!itemTemplate.SetStakeEntropyBit(Entropy.GetStakeEntropyBit(itemTemplate.nHeight, blockHash)))
+ {
+ return false; // SetStakeEntropyBit() failed
+ }
+
+ // TODO: set stake entropy bit, record proof-of-stake hash value
// TODO: compute stake modifier
// Add to index
- itemTemplate.BlockTypeFlag = block.IsProofOfStake ? BlockType.PROOF_OF_STAKE : BlockType.PROOF_OF_WORK;
+ if (block.IsProofOfStake)
+ {
+ itemTemplate.SetProofOfStake();
+ }
if (!itemTemplate.WriteToFile(ref writer, ref block))
{
public bool AcceptBlock(ref CBlock block)
{
- ScryptHash256 hash = block.header.Hash;
+ uint256 nHash = block.header.Hash;
- if (blockMap.ContainsKey(hash))
+ if (blockMap.ContainsKey(nHash))
{
// Already have this block.
return false;
// Write block to file.
var itemTemplate = new CBlockStoreItem()
{
- nHeight = nHeight
+ nHeight = nHeight,
};
itemTemplate.FillHeader(block.header);
return true;
}
- public bool GetBlock(ScryptHash256 blockHash, ref CBlock block)
+ public bool GetBlock(uint256 blockHash, ref CBlock block)
{
var reader = new BinaryReader(fStreamReadWrite).BaseStream;
return false;
}
+ /// <summary>
+ /// Get block cursor from map.
+ /// </summary>
+ /// <param name="blockHash">block hash</param>
+ /// <returns>Cursor or null</returns>
+ public CBlockStoreItem GetCursor(uint256 blockHash)
+ {
+ if (blockHash == 0)
+ {
+ // Genesis block has zero prevHash and no parent.
+ return null;
+ }
+
+ // First, check our block map.
+ CBlockStoreItem item = null;
+ if (blockMap.TryGetValue(blockHash, out item))
+ {
+ return item;
+ }
+
+ // Trying to get cursor from the database.
+ var QueryBlockCursor = dbConn.Query<CBlockStoreItem>("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
+
+ if (QueryBlockCursor.Count == 1)
+ {
+ return QueryBlockCursor[0];
+ }
+
+ // Nothing found.
+ return null;
+ }
+
public bool ProcessBlock(ref CBlock block)
{
- ScryptHash256 blockHash = block.header.Hash;
+ var blockHash = block.header.Hash;
if (blockMap.ContainsKey(blockHash))
{
// TODO: Limited duplicity on stake and reserialization of block signature
- // Preliminary checks
if (!block.CheckBlock(true, true, true))
{
- return true;
+ // Preliminary checks failure.
+ return false;
}
if (block.IsProofOfStake)
{
+ if (!block.SignatureOK || !block.vtx[1].VerifyScripts())
+ {
+ // Proof-of-Stake signature validation failure.
+ return false;
+ }
+
// TODO: proof-of-stake validation
}
}
// Recursively process any orphan blocks that depended on this one
- var orphansQueue = new List<ScryptHash256>();
+ var orphansQueue = new List<uint256>();
orphansQueue.Add(blockHash);
for (int i = 0; i < orphansQueue.Count; i++)
{
- ScryptHash256 hashPrev = orphansQueue[i];
+ var hashPrev = orphansQueue[i];
foreach (var pair in orphanMap)
{
var nOffset = 0L;
- var buffer = new byte[1000000]; // Max block size is 1Mb
+ var buffer = new byte[CBlock.nMaxBlockSize]; // Max block size is 1Mb
var intBuffer = new byte[4];
var fStream2 = File.OpenRead(BlockFile);