#include <boost/assign/list_of.hpp>
#include "kernel.h"
-#include "txdb.h"
+#include "db.h"
using namespace std;
extern int nStakeMaxAge;
extern int nStakeTargetSpacing;
+// Protocol switch time for fixed kernel modifier interval
+unsigned int nModifierSwitchTime = 1402531200; // Thu, 12 Jun 2014 00:00:00 GMT
+unsigned int nModifierTestSwitchTime = 1397520000; // Tue, 15 Apr 2014 00:00:00 GMT
+//
+// Note: user must upgrade before the protocol switch deadline, otherwise it's required to
+// re-download the blockchain. The timestamp of upgrade is recorded in the blockchain
+// database.
+unsigned int nModifierUpgradeTime = 0;
+
typedef std::map<int, unsigned int> MapModifierCheckpoints;
// Hard checkpoints of stake modifiers to ensure they are deterministic
static std::map<int, unsigned int> mapStakeModifierCheckpoints =
boost::assign::map_list_of
( 0, 0x0e00670bu )
- ( 9690, 0x97dcdafau )
- ( 12661, 0x5d84115du )
- ( 37092, 0xd230afccu )
- ( 44200, 0x05370164u )
- ( 65000, 0xc8e7be6au )
+ ( 68600, 0x73a8cc4cu )
+ ( 92161, 0xe21a911au )
+ ( 98661, 0xd20c44d4u )
;
// Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
( 0, 0x0e00670bu )
;
+// Get time weight
+int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
+{
+ // Kernel hash weight starts from 0 at the 30-day min age
+ // this change increases active coins participating the hash and helps
+ // to secure the network when proof-of-stake difficulty is low
+ //
+ // Maximum TimeWeight is 90 days.
+
+ return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
+}
+
+// Whether the given block is subject to new modifier protocol
+bool IsFixedModifierInterval(unsigned int nTimeBlock)
+{
+ return (nTimeBlock >= (fTestNet? nModifierTestSwitchTime : nModifierSwitchTime));
+}
+
// Get the last stake modifier and its generation time from a given block
static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
{
// block. This is to make it difficult for an attacker to gain control of
// additional bits in the stake modifier, even after generating a chain of
// blocks.
-bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
+bool ComputeNextStakeModifier(const CBlockIndex* pindexCurrent, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
{
nStakeModifier = 0;
fGeneratedStakeModifier = false;
+ const CBlockIndex* pindexPrev = pindexCurrent->pprev;
if (!pindexPrev)
{
fGeneratedStakeModifier = true;
return true; // genesis block's modifier is 0
}
+
// First find current stake modifier and its generation block time
// if it's not old enough, return the same stake modifier
int64 nModifierTime = 0;
return error("ComputeNextStakeModifier: unable to get last modifier");
if (fDebug)
{
- printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
+ printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s epoch=%u\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str(), (unsigned int)nModifierTime);
}
if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
+ {
+ if (fDebug)
+ {
+ printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexPrev nHeight=%d nTime=%u\n", pindexPrev->nHeight, (unsigned int)pindexPrev->GetBlockTime());
+ }
return true;
+ }
+ if (nModifierTime / nModifierInterval >= pindexCurrent->GetBlockTime() / nModifierInterval)
+ {
+ // fixed interval protocol requires current block timestamp also be in a different modifier interval
+ if (IsFixedModifierInterval(pindexCurrent->nTime))
+ {
+ if (fDebug)
+ {
+ printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
+ }
+ return true;
+ }
+ else
+ {
+ if (fDebug)
+ {
+ printf("ComputeNextStakeModifier: old modifier at block %s not meeting fixed modifier interval: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->GetBlockHash().ToString().c_str(), pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
+ }
+ }
+ }
// Sort candidate blocks by timestamp
vector<pair<int64, uint256> > vSortedByTimestamp;
// quantities so as to generate blocks faster, degrading the system back into
// a proof-of-work situation.
//
-bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake)
+bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool& fFatal, bool fMiner, bool fPrintProofOfStake)
{
if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
+ {
+ fFatal = true;
return error("CheckStakeKernelHash() : nTime violation");
+ }
unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
+ {
+ fFatal = true;
return error("CheckStakeKernelHash() : min age violation");
+ }
CBigNum bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
int64 nValueIn = txPrev.vout[prevout.n].nValue;
- int64 nTimeWeight;
uint256 hashBlockFrom = blockFrom.GetHash();
- // Kernel hash weight starts from 0 at the 30-day min age
- // this change increases active coins participating the hash and helps
- // to secure the network when proof-of-stake difficulty is low
- //
- // Maximum TimeWeight is 90 days.
- nTimeWeight = min((int64)nTimeTx - txPrev.nTime - nStakeMinAge, (int64)nStakeMaxAge);
-
- CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
+ CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
// Calculate hash
ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
hashProofOfStake = Hash(ss.begin(), ss.end());
+
if (fPrintProofOfStake)
{
printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
// Now check if proof-of-stake hash meets target protocol
if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
- return false;
+ {
+ fFatal = true;
+ return !fMiner? error("CheckStakeKernelHash() : proof-of-stake not meeting target") : false;
+ }
+
if (fDebug && !fPrintProofOfStake)
{
printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
}
// Check kernel hash target and coinstake signature
-bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
+bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake, bool& fFatal, bool fMiner)
{
if (!tx.IsCoinStake())
+ {
+ fFatal = true;
return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
+ }
// Kernel (input 0) must match the stake hash target per coin age (nBits)
const CTxIn& txin = tx.vin[0];
+ unsigned nTxPos;
- // First try finding the previous transaction in database
- CTxDB txdb("r");
CTransaction txPrev;
- CTxIndex txindex;
- if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
- return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
+ CCoins coins;
+ CCoinsViewCache &view = *pcoinsTip;
-#ifndef USE_LEVELDB
- txdb.Close();
-#endif
+ if (!view.GetCoinsReadOnly(txin.prevout.hash, coins))
+ return fDebug? error("CheckProofOfStake() : INFO: read coins for txPrev failed") : false; // previous transaction not in main chain, may occur during initial download
- // Verify signature
- if (!VerifySignature(txPrev, tx, 0, true, 0))
- return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
+ CBlockIndex* pindex = FindBlockByHeight(coins.nHeight);
- // Read block header
+ // Read block and scan it to find txPrev
CBlock block;
- if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
+ if (block.ReadFromDisk(pindex)) {
+ nTxPos = GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
+ BOOST_FOREACH(const CTransaction &tx, block.vtx) {
+ if (tx.GetHash() == txin.prevout.hash) {
+ txPrev = tx;
+ break;
+ }
+ nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
+ }
+ }
+ else
return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
- if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
- return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync
+ const CTxOut& txout = txPrev.vout[txin.prevout.n];
+
+ // Check transaction consistency
+ if (txin.prevout.n >= txPrev.vout.size())
+ {
+ fFatal = true;
+ return error("CheckProofOfStake() : invalid prevout found in coinstake %s", tx.GetHash().ToString().c_str());
+ }
+
+ // Verify script
+ if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, tx, 0, true, false, 0))
+ {
+ fFatal = true;
+ return error("CheckProofOfStake() : VerifyScript failed on coinstake %s", tx.GetHash().ToString().c_str());
+ }
+
+ if (!CheckStakeKernelHash(nBits, block, nTxPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fFatal, fMiner, fDebug))
+ {
+ if (fFatal)
+ return false;
+ // may occur during initial download or if behind on block chain sync
+ return fDebug? error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str()) : false;
+ }
return true;
}