X-Git-Url: https://git.novaco.in/?a=blobdiff_plain;f=Novacoin%2FCBlockStore.cs;h=fee329809a81156ac23bba0f6f7ebd68beef9450;hb=86473a10fbebca1b501bd140a5589f08a39311da;hp=a4466abf6dc697e8ae4bad0a0abaac04304af89b;hpb=bbc180adad56adde0fd4421c9b8b49bca27397a4;p=NovacoinLibrary.git
diff --git a/Novacoin/CBlockStore.cs b/Novacoin/CBlockStore.cs
index a4466ab..fee3298 100644
--- a/Novacoin/CBlockStore.cs
+++ b/Novacoin/CBlockStore.cs
@@ -19,680 +19,16 @@
using System;
using System.IO;
-using System.Linq;
using System.Collections.Concurrent;
using SQLite.Net;
-using SQLite.Net.Attributes;
using SQLite.Net.Interop;
using SQLite.Net.Platform.Generic;
-using SQLiteNetExtensions.Attributes;
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
using System.Text;
namespace Novacoin
{
- [Table("BlockStorage")]
- public class CBlockStoreItem : IBlockStorageItem
- {
- #region IBlockStorageItem
- ///
- /// Item ID in the database
- ///
- [PrimaryKey, AutoIncrement]
- public long ItemID { get; set; }
-
- ///
- /// PBKDF2+Salsa20 of block hash
- ///
- [Unique]
- public byte[] Hash { get; set; }
-
- ///
- /// Version of block schema
- ///
- [Column("nVersion")]
- public uint nVersion { get; set; }
-
- ///
- /// Previous block hash.
- ///
- [Column("prevHash")]
- public byte[] prevHash { get; set; }
-
- ///
- /// Merkle root hash.
- ///
- [Column("merkleRoot")]
- public byte[] merkleRoot { get; set; }
-
- ///
- /// Block timestamp.
- ///
- [Column("nTime")]
- public uint nTime { get; set; }
-
- ///
- /// Compressed difficulty representation.
- ///
- [Column("nBits")]
- public uint nBits { get; set; }
-
- ///
- /// Nonce counter.
- ///
- [Column("nNonce")]
- public uint nNonce { get; set; }
-
- ///
- /// Next block hash.
- ///
- [Column("nextHash")]
- public byte[] nextHash { get; set; }
-
- ///
- /// Block type flags
- ///
- [Column("BlockTypeFlag")]
- public BlockType BlockTypeFlag { get; set; }
-
- ///
- /// Stake modifier
- ///
- [Column("nStakeModifier")]
- public long nStakeModifier { get; set; }
-
- ///
- /// Proof-of-Stake hash
- ///
- [Column("hashProofOfStake")]
- public byte[] hashProofOfStake { get; set; }
-
- ///
- /// Stake generation outpoint.
- ///
- [Column("prevoutStake")]
- public byte[] prevoutStake { get; set; }
-
- ///
- /// Stake generation time.
- ///
- [Column("nStakeTime")]
- public uint nStakeTime { get; set; }
-
- ///
- /// Block height, encoded in VarInt format
- ///
- [Column("nHeight")]
- public uint nHeight { get; set; }
-
- ///
- /// Chain trust score, serialized and trimmed uint256 representation.
- ///
- [Column("ChainTrust")]
- public byte[] ChainTrust { get; set; }
-
- ///
- /// Block position in file, encoded in VarInt format
- ///
- [Column("BlockPos")]
- public byte[] BlockPos { get; set; }
-
- ///
- /// Block size in bytes, encoded in VarInt format
- ///
- [Column("BlockSize")]
- public byte[] BlockSize { get; set; }
- #endregion
-
- ///
- /// Accessor and mutator for BlockPos value.
- ///
- [Ignore]
- public long nBlockPos
- {
- get { return (long)VarInt.DecodeVarInt(BlockPos); }
- set { BlockPos = VarInt.EncodeVarInt(value); }
- }
-
- ///
- /// Accessor and mutator for BlockSize value.
- ///
- [Ignore]
- public int nBlockSize
- {
- get { return (int)VarInt.DecodeVarInt(BlockSize); }
- set { BlockSize = VarInt.EncodeVarInt(value); }
- }
-
- ///
- /// Fill database item with data from given block header.
- ///
- /// Block header
- /// Header hash
- public uint256 FillHeader(CBlockHeader header)
- {
- uint256 _hash = header.Hash;
-
- Hash = _hash;
-
- nVersion = header.nVersion;
- prevHash = header.prevHash;
- merkleRoot = header.merkleRoot;
- nTime = header.nTime;
- nBits = header.nBits;
- nNonce = header.nNonce;
-
- return _hash;
- }
-
- ///
- /// Reconstruct block header from item data.
- ///
- public CBlockHeader BlockHeader
- {
- get
- {
- CBlockHeader header = new CBlockHeader();
-
- header.nVersion = nVersion;
- header.prevHash = prevHash;
- header.merkleRoot = merkleRoot;
- header.nTime = nTime;
- header.nBits = nBits;
- header.nNonce = nNonce;
-
- return header;
- }
- }
-
- ///
- /// Read block from file.
- ///
- /// Stream with read access.
- /// CBlock reference.
- /// Result
- public bool ReadFromFile(ref Stream reader, out CBlock block)
- {
- var buffer = new byte[nBlockSize];
- block = null;
-
- try
- {
- reader.Seek(nBlockPos, SeekOrigin.Begin);
-
- if (nBlockSize != reader.Read(buffer, 0, nBlockSize))
- {
- return false;
- }
-
- block = new CBlock(buffer);
-
- return true;
- }
- catch (IOException)
- {
- // I/O error
- return false;
- }
- catch (BlockException)
- {
- // Constructor exception
- return false;
- }
- }
-
- ///
- /// Writes given block to file and prepares cursor object for insertion into the database.
- ///
- /// Stream with write access.
- /// CBlock reference.
- /// Result
- public bool WriteToFile(ref Stream writer, ref CBlock block)
- {
- try
- {
- byte[] blockBytes = block;
-
- var magicBytes = BitConverter.GetBytes(CBlockStore.nMagicNumber);
- var blkLenBytes = BitConverter.GetBytes(blockBytes.Length);
-
- // Seek to the end and then append magic bytes there.
- writer.Seek(0, SeekOrigin.End);
- writer.Write(magicBytes, 0, magicBytes.Length);
- writer.Write(blkLenBytes, 0, blkLenBytes.Length);
-
- // Save block size and current position in the block cursor fields.
- nBlockPos = writer.Position;
- nBlockSize = blockBytes.Length;
-
- // Write block and flush the stream.
- writer.Write(blockBytes, 0, blockBytes.Length);
- writer.Flush();
-
- return true;
- }
- catch (IOException)
- {
- // I/O error
- return false;
- }
- catch (Exception)
- {
- // Some serialization error
- return false;
- }
- }
-
- ///
- /// Previous block cursor
- ///
- [Ignore]
- public CBlockStoreItem prev {
- get { return CBlockStore.Instance.GetCursor(prevHash); }
- }
-
- ///
- /// Next block cursor
- ///
- [Ignore]
- public CBlockStoreItem next
- {
- get
- {
- if (nextHash == null)
- {
- return null;
- }
-
- return CBlockStore.Instance.GetCursor(nextHash);
- }
- set
- {
- CBlockStoreItem newCursor = this;
- newCursor.nextHash = value.Hash;
-
- CBlockStore.Instance.UpdateCursor(this, ref newCursor);
- }
- }
-
- [Ignore]
- bool IsInMainChain
- {
- get { return (next != null); }
- }
-
- ///
- /// STake modifier generation flag
- ///
- [Ignore]
- public bool GeneratedStakeModifier
- {
- get { return (BlockTypeFlag & BlockType.BLOCK_STAKE_MODIFIER) != 0; }
- }
-
- ///
- /// Stake entropy bit
- ///
- [Ignore]
- public uint StakeEntropyBit
- {
- get { return ((uint)(BlockTypeFlag & BlockType.BLOCK_STAKE_ENTROPY) >> 1); }
- }
-
- ///
- /// Sets stake modifier and flag.
- ///
- /// New stake modifier.
- /// Set generation flag?
- public void SetStakeModifier(long nModifier, bool fGeneratedStakeModifier)
- {
- nStakeModifier = nModifier;
- if (fGeneratedStakeModifier)
- BlockTypeFlag |= BlockType.BLOCK_STAKE_MODIFIER;
- }
-
- ///
- /// Set entropy bit.
- ///
- /// Entropy bit value (0 or 1).
- /// False if value is our of range.
- public bool SetStakeEntropyBit(byte nEntropyBit)
- {
- if (nEntropyBit > 1)
- return false;
- BlockTypeFlag |= (nEntropyBit != 0 ? BlockType.BLOCK_STAKE_ENTROPY : 0);
- return true;
- }
-
- ///
- /// Set proof-of-stake flag.
- ///
- public void SetProofOfStake()
- {
- BlockTypeFlag |= BlockType.BLOCK_PROOF_OF_STAKE;
- }
-
- ///
- /// Block has no proof-of-stake flag.
- ///
- [Ignore]
- public bool IsProofOfWork
- {
- get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) == 0; }
- }
-
- ///
- /// Block has proof-of-stake flag set.
- ///
- [Ignore]
- public bool IsProofOfStake
- {
- get { return (BlockTypeFlag & BlockType.BLOCK_PROOF_OF_STAKE) != 0; }
- }
-
- ///
- /// Block trust score.
- ///
- [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;
- }
- }
- }
-
- ///
- /// Stake modifier checksum.
- ///
- public uint nStakeModifierChecksum;
-
- ///
- /// Chain trust score
- ///
- [Ignore]
- public uint256 nChainTrust {
- get { return Interop.AppendWithZeros(ChainTrust); }
- set { ChainTrust = Interop.TrimArray(value); }
- }
- }
-
- ///
- /// Block type.
- ///
- public enum BlockType
- {
- 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
- };
-
- ///
- /// Transaction type.
- ///
- public enum TxFlags : byte
- {
- TX_COINBASE,
- TX_COINSTAKE,
- TX_USER
- }
-
- ///
- /// Output flags.
- ///
- public enum OutputFlags : byte
- {
- AVAILABLE, // Unspent output
- SPENT // Spent output
- }
-
- [Table("MerkleNodes")]
- public class CMerkleNode : IMerkleNode
- {
- #region IMerkleNode
- ///
- /// Node identifier
- ///
- [PrimaryKey, AutoIncrement]
- public long nMerkleNodeID { get; set; }
-
- ///
- /// Reference to parent block database item.
- ///
- [ForeignKey(typeof(CBlockStoreItem), Name = "ItemId")]
- public long nParentBlockID { get; set; }
-
- ///
- /// Transaction type flag
- ///
- [Column("TransactionFlags")]
- public TxFlags TransactionFlags { get; set; }
-
- ///
- /// Transaction hash
- ///
- [Column("TransactionHash")]
- public byte[] TransactionHash { get; set; }
-
- ///
- /// Transaction offset from the beginning of block header, encoded in VarInt format.
- ///
- [Column("TxOffset")]
- public byte[] TxOffset { get; set; }
-
- ///
- /// Transaction size, encoded in VarInt format.
- ///
- [Column("TxSize")]
- public byte[] TxSize { get; set; }
- #endregion
-
- ///
- /// Read transaction from file.
- ///
- /// Stream with read access.
- /// CTransaction reference.
- /// Result
- public bool ReadFromFile(ref Stream reader, long nBlockPos, out CTransaction tx)
- {
- var buffer = new byte[CTransaction.nMaxTxSize];
-
- tx = null;
-
- try
- {
- reader.Seek(nBlockPos + nTxOffset, SeekOrigin.Begin); // Seek to transaction offset
-
- if (nTxSize != reader.Read(buffer, 0, nTxSize))
- {
- return false;
- }
-
- tx = new CTransaction(buffer);
-
- return true;
- }
- catch (IOException)
- {
- // I/O error
- return false;
- }
- catch (TransactionConstructorException)
- {
- // Constructor error
- return false;
- }
- }
-
- ///
- /// Transaction offset accessor
- ///
- [Ignore]
- public long nTxOffset
- {
- get { return (long) VarInt.DecodeVarInt(TxOffset); }
- }
-
- ///
- /// Transaction size accessor
- ///
- [Ignore]
- public int nTxSize
- {
- get { return (int)VarInt.DecodeVarInt(TxSize); }
- }
-
- }
-
- [Table("Outputs")]
- public class TxOutItem : ITxOutItem
- {
- ///
- /// Reference to transaction item.
- ///
- [ForeignKey(typeof(CMerkleNode), Name = "nMerkleNodeID")]
- public long nMerkleNodeID { get; set; }
-
- ///
- /// Output flags
- ///
- public OutputFlags outputFlags { get; set; }
-
- ///
- /// Output number in VarInt format.
- ///
- public byte[] OutputNumber { get; set; }
-
- ///
- /// Output value in VarInt format.
- ///
- public byte[] OutputValue { get; set; }
-
- ///
- /// Second half of script which contains spending instructions.
- ///
- public byte[] scriptPubKey { get; set; }
-
- ///
- /// Getter for output number.
- ///
- public uint nOut
- {
- get { return (uint)VarInt.DecodeVarInt(OutputNumber); }
- }
-
- ///
- /// Getter for output value.
- ///
- public ulong nValue
- {
- get { return VarInt.DecodeVarInt(OutputValue); }
- }
-
- ///
- /// Getter ans setter for IsSpent flag.
- ///
- public bool IsSpent
- {
- get { return (outputFlags & OutputFlags.SPENT) != 0; }
- set { outputFlags |= value ? OutputFlags.SPENT : OutputFlags.AVAILABLE; }
- }
- }
-
public class CBlockStore : IDisposable
{
public const uint nMagicNumber = 0xe5e9e8e4;
@@ -749,15 +85,11 @@ namespace Novacoin
private ConcurrentDictionary mapStakeSeen = new ConcurrentDictionary();
private ConcurrentDictionary mapStakeSeenOrphan = new ConcurrentDictionary();
- ///
- /// Trust score for the longest chain.
- ///
- private uint256 nBestChainTrust = 0;
///
- /// Top block of the best chain.
+ /// Copy of chain state object.
///
- private uint256 nHashBestChain = 0;
+ private ChainState ChainParams;
///
/// Cursor which is pointing us to the end of best chain.
@@ -778,7 +110,6 @@ namespace Novacoin
/// Block file stream with read/write access
///
private Stream fStreamReadWrite;
- private uint nBestHeight;
private uint nTimeBestReceived;
private int nTransactionsUpdated;
@@ -808,6 +139,16 @@ namespace Novacoin
dbConn.CreateTable(CreateFlags.AutoIncPK);
dbConn.CreateTable(CreateFlags.AutoIncPK);
dbConn.CreateTable(CreateFlags.ImplicitPK);
+ dbConn.CreateTable(CreateFlags.AutoIncPK);
+
+ ChainParams = new ChainState()
+ {
+ nBestChainTrust = 0,
+ nBestHeight = 0,
+ nHashBestChain = 0
+ };
+
+ dbConn.Insert(ChainParams);
var genesisBlock = new CBlock(
Interop.HexToArray(
@@ -862,6 +203,9 @@ namespace Novacoin
mapStakeSeen.TryAdd(item.prevoutStake, item.nStakeTime);
}
}
+
+ // Load data about the top node.
+ ChainParams = dbConn.Table().First();
}
}
@@ -881,12 +225,8 @@ namespace Novacoin
return false;
}
- interface InputsJoin : ITxOutItem
- {
- byte[] TransactionHash { get; set; }
- }
- public bool FetchInputs(ref CTransaction tx, ref Dictionary queued, ref Dictionary inputs, bool IsBlock, out bool Invalid)
+ public bool FetchInputs(CTransaction tx, ref Dictionary queued, ref Dictionary inputs, bool IsBlock, out bool Invalid)
{
Invalid = false;
@@ -919,8 +259,10 @@ namespace Novacoin
var inputsKey = new COutPoint(item.TransactionHash, item.nOut);
+ item.IsSpent = true;
+
// Add output data to dictionary
- inputs[inputsKey] = new CTxOut(item.nValue, item.scriptPubKey);
+ inputs.Add(inputsKey, (TxOutItem) item);
}
if (queryResults.Count < tx.vin.Length)
@@ -939,10 +281,10 @@ namespace Novacoin
}
// Add output data to dictionary
- inputs[outPoint] = queued[outPoint];
+ inputs.Add(outPoint, queued[outPoint]);
- // And remove it from queued data
- queued.Remove(outPoint);
+ // Mark output as spent
+ queued[outPoint].IsSpent = true;
}
}
else
@@ -965,8 +307,10 @@ namespace Novacoin
return false; // nOut is out of range
}
+
+ // TODO: return inputs from map
+ throw new NotImplementedException();
- inputs[outPoint] = txPrev.vout[outPoint.n];
}
return false;
@@ -978,7 +322,6 @@ namespace Novacoin
private bool AddItemToIndex(ref CBlockStoreItem itemTemplate, ref CBlock block)
{
- var writer = new BinaryWriter(fStreamReadWrite).BaseStream;
uint256 blockHash = itemTemplate.Hash;
if (blockMap.ContainsKey(blockHash))
@@ -987,6 +330,9 @@ namespace Novacoin
return false;
}
+ // Begin transaction
+ dbConn.BeginTransaction();
+
// Compute chain trust score
itemTemplate.nChainTrust = (itemTemplate.prev != null ? itemTemplate.prev.nChainTrust : 0) + itemTemplate.nBlockTrust;
@@ -1028,7 +374,7 @@ namespace Novacoin
itemTemplate.nStakeTime = block.vtx[1].nTime;
}
- if (!itemTemplate.WriteToFile(ref writer, ref block))
+ if (!itemTemplate.WriteToFile(ref fStreamReadWrite, ref block))
{
return false;
}
@@ -1046,7 +392,7 @@ namespace Novacoin
return false; // blockMap add failed
}
- if (itemTemplate.nChainTrust > nBestChainTrust)
+ if (itemTemplate.nChainTrust > ChainParams.nBestChainTrust)
{
// New best chain
@@ -1056,6 +402,9 @@ namespace Novacoin
}
}
+ // Commit transaction
+ dbConn.Commit();
+
return true;
}
@@ -1063,11 +412,11 @@ namespace Novacoin
{
uint256 hashBlock = cursor.Hash;
- if (genesisBlockCursor == null && hashBlock == NetUtils.nHashGenesisBlock)
+ if (genesisBlockCursor == null && hashBlock == NetInfo.nHashGenesisBlock)
{
genesisBlockCursor = cursor;
}
- else if (nHashBestChain == (uint256)cursor.prevHash)
+ else if (ChainParams.nHashBestChain == (uint256)cursor.prevHash)
{
if (!SetBestChainInner(cursor))
{
@@ -1115,10 +464,7 @@ namespace Novacoin
}
}
- nHashBestChain = cursor.Hash;
bestBlockCursor = cursor;
- nBestHeight = cursor.nHeight;
- nBestChainTrust = cursor.nChainTrust;
nTimeBestReceived = Interop.GetTime();
nTransactionsUpdated++;
@@ -1220,14 +566,11 @@ namespace Novacoin
}
}
- if (!WriteHashBestChain(cursorIntermediate.Hash))
+ if (!UpdateTopChain(cursorIntermediate))
{
- return false; // WriteHashBestChain failed
+ return false; // UpdateTopChain failed
}
- // Make sure it's successfully written to disk
- dbConn.Commit();
-
// Resurrect memory transactions that were in the disconnected branch
foreach (var tx in txResurrect)
{
@@ -1259,7 +602,7 @@ namespace Novacoin
}
// Adding to current best branch
- if (!ConnectBlock(cursor, ref block) || !WriteHashBestChain(hash))
+ if (!ConnectBlock(cursor, ref block) || !UpdateTopChain(cursor))
{
InvalidChainFound(cursor);
return false;
@@ -1268,8 +611,6 @@ namespace Novacoin
// Add to current best branch
cursor.prev.next = cursor;
- dbConn.Commit();
-
// Delete redundant memory transactions
foreach (var tx in block.vtx)
{
@@ -1288,17 +629,204 @@ namespace Novacoin
return false; // Invalid block found.
}
- // TODO: the remaining stuff lol :D
+ bool fScriptChecks = cursor.nHeight >= Checkpoints.TotalBlocksEstimate;
+ var scriptFlags = scriptflag.SCRIPT_VERIFY_NOCACHE | scriptflag.SCRIPT_VERIFY_P2SH;
- throw new NotImplementedException();
+ ulong nFees = 0;
+ ulong nValueIn = 0;
+ ulong nValueOut = 0;
+ uint nSigOps = 0;
+
+ var queuedMerkleNodes = new Dictionary();
+ var queued = new Dictionary();
+
+ for (var nTx = 0; nTx < block.vtx.Length; nTx++)
+ {
+ var tx = block.vtx[nTx];
+ var hashTx = tx.Hash;
+ var nTxPos = cursor.nBlockPos + block.GetTxOffset(nTx);
+
+ Dictionary txouts;
+ if (GetOutputs(hashTx, out txouts))
+ {
+ // Do not allow blocks that contain transactions which 'overwrite' older transactions,
+ // unless those are already completely spent.
+ return false;
+ }
+
+ nSigOps += tx.LegacySigOpCount;
+ if (nSigOps > CBlock.nMaxSigOps)
+ {
+ return false; // too many sigops
+ }
+
+ var inputs = new Dictionary();
+
+ if (tx.IsCoinBase)
+ {
+ nValueOut += tx.nValueOut;
+ }
+ else
+ {
+ bool Invalid;
+ if (!FetchInputs(tx, ref queued, ref inputs, true, out Invalid))
+ {
+ return false; // Unable to fetch some inputs.
+ }
+
+ // Add in sigops done by pay-to-script-hash inputs;
+ // this is to prevent a "rogue miner" from creating
+ // an incredibly-expensive-to-validate block.
+ nSigOps += tx.GetP2SHSigOpCount(ref inputs);
+ if (nSigOps > CBlock.nMaxSigOps)
+ {
+ return false; // too many sigops
+ }
+
+ ulong nTxValueIn = tx.GetValueIn(ref inputs);
+ ulong nTxValueOut = tx.nValueOut;
+
+ nValueIn += nTxValueIn;
+ nValueOut += nTxValueOut;
+
+ if (!tx.IsCoinStake)
+ {
+ nFees += nTxValueIn - nTxValueOut;
+ }
+
+ if (!ConnectInputs(tx, ref inputs, ref queued, ref cursor, fScriptChecks, scriptFlags))
+ {
+ return false;
+ }
+ }
+
+ for (var i = 0u; i < tx.vout.Length; i++)
+ {
+ var mNode = new CMerkleNode(cursor.ItemID, nTxPos, tx);
+ queuedMerkleNodes.Add(hashTx, mNode);
+
+ var outKey = new COutPoint(hashTx, i);
+ var outData = new TxOutItem();
+
+ outData.nValue = tx.vout[i].nValue;
+ outData.scriptPubKey = tx.vout[i].scriptPubKey;
+ outData.nOut = i;
+
+
+ outData.IsSpent = false;
+
+ queued.Add(outKey, outData);
+ }
+ }
+
+ if (!block.IsProofOfStake)
+ {
+ ulong nBlockReward = CBlock.GetProofOfWorkReward(cursor.nBits, nFees);
+
+ // Check coinbase reward
+ if (block.vtx[0].nValueOut > nBlockReward)
+ {
+ return false; // coinbase reward exceeded
+ }
+ }
+
+ cursor.nMint = (long) (nValueOut - nValueIn + nFees);
+ cursor.nMoneySupply = (cursor.prev != null ? cursor.prev.nMoneySupply : 0) + (long)nValueOut - (long)nValueIn;
+
+ if (!UpdateDBCursor(ref cursor))
+ {
+ return false; // Unable to commit changes
+ }
+
+ if (fJustCheck)
+ {
+ return true;
+ }
+
+ // Write queued transaction changes
+ var actualMerkleNodes = new Dictionary();
+ var queuedOutpointItems = new List();
+ foreach(KeyValuePair outPair in queued)
+ {
+ uint256 txID = outPair.Key.hash;
+ CMerkleNode merkleNode;
+
+ if (actualMerkleNodes.ContainsKey(txID))
+ {
+ merkleNode = actualMerkleNodes[txID];
+ }
+ else
+ {
+ merkleNode = queuedMerkleNodes[txID];
+ if (!SaveMerkleNode(ref merkleNode))
+ {
+ // Unable to save merkle tree cursor.
+ return false;
+ }
+ actualMerkleNodes.Add(txID, merkleNode);
+ }
+
+ var outItem = outPair.Value;
+ outItem.nMerkleNodeID = merkleNode.nMerkleNodeID;
+
+ queuedOutpointItems.Add(outItem);
+ }
+
+ if (!SaveOutpoints(ref queuedOutpointItems))
+ {
+ return false; // Unable to save outpoints
+ }
+
+ return true;
+ }
+
+ ///
+ /// Insert set of outpoints
+ ///
+ /// List of TxOutItem objects.
+ /// Result
+ private bool SaveOutpoints(ref List queuedOutpointItems)
+ {
+ return dbConn.InsertAll(queuedOutpointItems, false) != 0;
+ }
+
+ ///
+ /// Insert merkle node into db and set actual record id value.
+ ///
+ /// Merkle node object reference.
+ /// Result
+ private bool SaveMerkleNode(ref CMerkleNode merkleNode)
+ {
+ if (dbConn.Insert(merkleNode) == 0)
+ {
+ return false;
+ }
+
+ merkleNode.nMerkleNodeID = dbPlatform.SQLiteApi.LastInsertRowid(dbConn.Handle);
+
+ return true;
}
- private bool WriteHashBestChain(uint256 hash)
+ private bool ConnectInputs(CTransaction tx, ref Dictionary inputs, ref Dictionary queued, ref CBlockStoreItem cursor, bool fScriptChecks, scriptflag scriptFlags)
{
throw new NotImplementedException();
}
///
+ /// Set new top node or current best chain.
+ ///
+ ///
+ ///
+ private bool UpdateTopChain(CBlockStoreItem cursor)
+ {
+ ChainParams.HashBestChain = cursor.Hash;
+ ChainParams.nBestChainTrust = cursor.nChainTrust;
+ ChainParams.nBestHeight = cursor.nHeight;
+
+ return dbConn.Update(ChainParams) != 0;
+ }
+
+ ///
/// Try to find proof-of-stake hash in the map.
///
/// Block hash
@@ -1332,7 +860,7 @@ namespace Novacoin
uint nHeight = prevBlockCursor.nHeight + 1;
// Check timestamp against prev
- if (NetUtils.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
+ if (NetInfo.FutureDrift(block.header.nTime) < prevBlockHeader.nTime)
{
// block's timestamp is too early
return false;
@@ -1359,35 +887,33 @@ namespace Novacoin
if (!AddItemToIndex(ref itemTemplate, ref block))
{
+ dbConn.Rollback();
+
return false;
}
return true;
}
+ ///
+ /// GEt block by hash.
+ ///
+ /// Block hash
+ /// Block object reference
+ /// Block position reference
+ /// Result
public bool GetBlock(uint256 blockHash, ref CBlock block, ref long nBlockPos)
{
- var reader = new BinaryReader(fStreamReadWrite).BaseStream;
-
- var QueryBlock = dbConn.Query("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
+ CBlockStoreItem cursor;
- if (QueryBlock.Count == 1)
+ if (!blockMap.TryGetValue(blockHash, out cursor))
{
- nBlockPos = QueryBlock[0].nBlockPos;
- return QueryBlock[0].ReadFromFile(ref reader, out block);
+ return false; // Unable to fetch block cursor
}
- // Block not found
-
- return false;
- }
-
+ nBlockPos = cursor.nBlockPos;
- ///
- /// Interface for join
- ///
- interface IBlockJoinMerkle : IBlockStorageItem, IMerkleNode
- {
+ return cursor.ReadFromFile(ref fStreamReadWrite, out block);
}
///
@@ -1395,40 +921,64 @@ namespace Novacoin
///
/// Transaction hash
/// Block reference
- /// Transaction reference
/// Block position reference
- /// Transaction position reference
/// Result of operation
- public bool GetBlockByTransactionID(uint256 TxID, ref CBlock block, ref CTransaction tx, ref long nBlockPos, ref long nTxPos)
+ public bool GetBlockByTransactionID(uint256 TxID, ref CBlock block, ref long nBlockPos)
{
- var queryResult = dbConn.Query("select *, from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
+ var queryResult = dbConn.Query("select b.* from [BlockStorage] b left join [MerkleNodes] m on (b.[ItemID] = m.[nParentBlockID]) where m.[TransactionHash] = ?", (byte[])TxID);
if (queryResult.Count == 1)
{
- CBlockStoreItem blockCursor = (CBlockStoreItem) queryResult[0];
- CMerkleNode txCursor = (CMerkleNode)queryResult[0];
+ CBlockStoreItem blockCursor = queryResult[0];
+
+ return blockCursor.ReadFromFile(ref fStreamReadWrite, out block);
+ }
+
+ // Tx not found
+
+ return false;
+ }
- var reader = new BinaryReader(fStreamReadWrite).BaseStream;
+ public bool GetOutputs(uint256 transactionHash, out Dictionary txouts, bool fUnspentOnly=true)
+ {
+ txouts = null;
+
+ var queryParams = new object[] { (byte[])transactionHash, fUnspentOnly ? OutputFlags.AVAILABLE : (OutputFlags.AVAILABLE | OutputFlags.SPENT) };
+ var queryResult = dbConn.Query("select o.* from [Outputs] o left join [MerkleNodes] m on m.[nMerkleNodeID] = o.[nMerkleNodeID] where m.[TransactionHash] = ? and outputFlags = ?", queryParams);
+
+ if (queryResult.Count != 0)
+ {
+ txouts = new Dictionary();
- if (!txCursor.ReadFromFile(ref reader, blockCursor.nBlockPos, out tx))
+ foreach (var o in queryResult)
{
- return false; // Unable to read transaction
+ var outpointKey = new COutPoint(transactionHash, o.nOut);
+ var outpointData = o;
+
+ txouts.Add(outpointKey, outpointData);
}
- return blockCursor.ReadFromFile(ref reader, out block);
+ // There are some unspent inputs.
+ return true;
}
- // Tx not found
-
+ // This transaction has been spent completely.
return false;
}
+ public bool WriteNodes(ref CMerkleNode[] merkleNodes)
+ {
+
+
+ return true;
+ }
+
///
/// Get block cursor from map.
///
/// block hash
/// Cursor or null
- public CBlockStoreItem GetCursor(uint256 blockHash)
+ public CBlockStoreItem GetMapCursor(uint256 blockHash)
{
if (blockHash == 0)
{
@@ -1436,20 +986,24 @@ namespace Novacoin
return null;
}
- // First, check our block map.
- CBlockStoreItem item = null;
- if (blockMap.TryGetValue(blockHash, out item))
- {
- return item;
- }
+ CBlockStoreItem cursor = null;
+ blockMap.TryGetValue(blockHash, out cursor);
+ return cursor;
+ }
+
+ ///
+ /// Load cursor from database.
+ ///
+ /// Block hash
+ /// Block cursor object
+ public CBlockStoreItem GetDBCursor(uint256 blockHash)
+ {
// Trying to get cursor from the database.
var QueryBlockCursor = dbConn.Query("select * from [BlockStorage] where [Hash] = ?", (byte[])blockHash);
if (QueryBlockCursor.Count == 1)
{
- blockMap.TryAdd(blockHash, QueryBlockCursor[0]);
-
return QueryBlockCursor[0];
}
@@ -1460,17 +1014,22 @@ namespace Novacoin
///
/// Update cursor in memory and on disk.
///
- /// Original cursor
- /// New cursor
- ///
- public bool UpdateCursor(CBlockStoreItem originalItem, ref CBlockStoreItem newItem)
+ /// Block cursor
+ /// Result
+ public bool UpdateMapCursor(CBlockStoreItem cursor)
{
- if (blockMap.TryUpdate(originalItem.Hash, newItem, originalItem))
- {
- return dbConn.Update(newItem) != 0;
- }
+ var original = blockMap[cursor.Hash];
+ return blockMap.TryUpdate(cursor.Hash, cursor, original);
+ }
- return false;
+ ///
+ /// Update cursor record in database.
+ ///
+ /// Block cursor object
+ /// Result
+ public bool UpdateDBCursor(ref CBlockStoreItem cursor)
+ {
+ return dbConn.Update(cursor) != 0;
}
public bool ProcessBlock(ref CBlock block)
@@ -1585,11 +1144,10 @@ namespace Novacoin
var intBuffer = new byte[4];
var fStream2 = File.OpenRead(BlockFile);
- var readerForBlocks = new BinaryReader(fStream2).BaseStream;
- readerForBlocks.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
+ fStream2.Seek(nOffset, SeekOrigin.Begin); // Seek to previous offset + previous block length
- while (readerForBlocks.Read(buffer, 0, 4) == 4) // Read magic number
+ while (fStream2.Read(buffer, 0, 4) == 4) // Read magic number
{
var nMagic = BitConverter.ToUInt32(buffer, 0);
if (nMagic != 0xe5e9e8e4)
@@ -1597,7 +1155,7 @@ namespace Novacoin
throw new Exception("Incorrect magic number.");
}
- var nBytesRead = readerForBlocks.Read(buffer, 0, 4);
+ var nBytesRead = fStream2.Read(buffer, 0, 4);
if (nBytesRead != 4)
{
throw new Exception("BLKSZ EOF");
@@ -1605,9 +1163,9 @@ namespace Novacoin
var nBlockSize = BitConverter.ToInt32(buffer, 0);
- nOffset = readerForBlocks.Position;
+ nOffset = fStream2.Position;
- nBytesRead = readerForBlocks.Read(buffer, 0, nBlockSize);
+ nBytesRead = fStream2.Read(buffer, 0, nBlockSize);
if (nBytesRead == 0 || nBytesRead != nBlockSize)
{
@@ -1639,8 +1197,6 @@ namespace Novacoin
}*/
}
- dbConn.Commit();
-
return true;
}