1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447 |
- // ECOin - Copyright (c) - 2014/2022 - GPLv3 - epsylon@riseup.net (https://03c8.net)
- #ifndef ECOIN_MAIN_H
- #define ECOIN_MAIN_H
- #include "bignum.h"
- #include "sync.h"
- #include "net.h"
- #include "script.h"
- #include "scrypt.h"
- #include "zerocoin/Zerocoin.h"
- #include "base58.h"
- #include <list>
- class CWallet;
- class CBlock;
- class CBlockIndex;
- class CKeyItem;
- class CReserveKey;
- class COutPoint;
- class CAddress;
- class CInv;
- class CRequestTracker;
- class CNode;
- static const unsigned int MAX_BLOCK_SIZE = 1000000;
- static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
- static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
- static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
- static const unsigned int MAX_INV_SZ = 50000;
- static const int64 MIN_TX_FEE = CENT;
- static const int64 MIN_RELAY_TX_FEE = CENT;
- static const int64 MAX_MONEY = 50000000000LL * COIN;
- static const int64 MAX_MINT_PROOF_OF_WORK = 10000 * COIN;
- static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
- static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
- static const unsigned int ENTROPY_SWITCH_TIME = 1420070399; // Dec 31 2014, 23:59:59 PM GMT
- static const unsigned int FORK_FINAL = 1397936903;
- string SearchTerm(const char *chAddress);
- string SearchTermV2(const char *chAddress);
- bool fAddrMiner (const char *chHash, const char *chTerm);
- inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
- static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
- #ifdef USE_UPNP
- static const int fHaveUPnP = true;
- #else
- static const int fHaveUPnP = false;
- #endif
- static const uint256 hashGenesisBlock("0x000003e158b5cdd1a1bf05dac19d9c171998f9a9c62307adac2cb842029b0dbd"); // ECOIN - Genesis Hash
- static const uint256 hashGenesisBlockTestNet("0x0000568ef00493151a15b68b6d12713ec52df65077d4bdd8235f98420da6cc33"); // ECOIN - TestNet Genesis Hash
- inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
- inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
- extern libzerocoin::Params* ZCParams;
- extern CScript COINBASE_FLAGS;
- extern CCriticalSection cs_main;
- extern std::map<uint256, CBlockIndex*> mapBlockIndex;
- extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
- extern CBlockIndex* pindexGenesisBlock;
- extern unsigned int nStakeMinAge;
- extern unsigned int nNodeLifespan;
- extern int nCoinbaseMaturity;
- extern int nBestHeight;
- extern uint256 nBestChainTrust;
- extern uint256 nBestInvalidTrust;
- extern uint256 hashBestChain;
- extern CBlockIndex* pindexBest;
- extern unsigned int nTransactionsUpdated;
- extern uint64 nLastBlockTx;
- extern uint64 nLastBlockSize;
- extern int64 nLastCoinStakeSearchInterval;
- extern const std::string strMessageMagic;
- extern int64 nTimeBestReceived;
- extern CCriticalSection cs_setpwalletRegistered;
- extern std::set<CWallet*> setpwalletRegistered;
- extern unsigned char pchMessageStart[4];
- extern std::map<uint256, CBlock*> mapOrphanBlocks;
- // Settings
- extern int64 nTransactionFee;
- extern int64 nMinimumInputValue;
- extern bool fUseFastIndex;
- extern unsigned int nDerivationMethodIndex;
- extern bool fEnforceCanonical;
- // Minimum disk space required - used in CheckDiskSpace()
- static const uint64 nMinDiskSpace = 52428800;
- class CReserveKey;
- class CTxDB;
- class CTxIndex;
- void RegisterWallet(CWallet* pwalletIn);
- void UnregisterWallet(CWallet* pwalletIn);
- void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
- bool ProcessBlock(CNode* pfrom, CBlock* pblock);
- bool CheckDiskSpace(uint64 nAdditionalBytes=0);
- FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
- FILE* AppendBlockFile(unsigned int& nFileRet);
- bool LoadBlockIndex(bool fAllowNew=true);
- void PrintBlockTree();
- CBlockIndex* FindBlockByHeight(int nHeight);
- bool ProcessMessages(CNode* pfrom);
- bool SendMessages(CNode* pto, bool fSendTrickle);
- bool LoadExternalBlockFile(FILE* fileIn);
- bool CheckProofOfWork(uint256 hash, unsigned int nBits);
- unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
- int64 GetProofOfWorkReward(unsigned int nHeight, uint256 hashSeed);
- int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
- unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
- unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
- int GetNumBlocksOfPeers();
- bool IsInitialBlockDownload();
- std::string GetWarnings(std::string strFor);
- bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
- uint256 WantedByOrphan(const CBlock* pblockOrphan);
- const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
- void StakeMiner(CWallet *pwallet);
- void ResendWalletTransactions(bool fForce = false);
- bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
- /** Position on disk for a particular transaction. */
- class CDiskTxPos
- {
- public:
- unsigned int nFile;
- unsigned int nBlockPos;
- unsigned int nTxPos;
- CDiskTxPos()
- {
- SetNull();
- }
- CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
- {
- nFile = nFileIn;
- nBlockPos = nBlockPosIn;
- nTxPos = nTxPosIn;
- }
- IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
- void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
- bool IsNull() const { return (nFile == (unsigned int) -1); }
- friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
- {
- return (a.nFile == b.nFile &&
- a.nBlockPos == b.nBlockPos &&
- a.nTxPos == b.nTxPos);
- }
- friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
- {
- return !(a == b);
- }
- std::string ToString() const
- {
- if (IsNull())
- return "null";
- else
- return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
- }
- void print() const
- {
- printf("%s", ToString().c_str());
- }
- };
- class CInPoint
- {
- public:
- CTransaction* ptx;
- unsigned int n;
- CInPoint() { SetNull(); }
- CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
- void SetNull() { ptx = NULL; n = (unsigned int) -1; }
- bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
- };
- class COutPoint
- {
- public:
- uint256 hash;
- unsigned int n;
- COutPoint() { SetNull(); }
- COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
- IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
- void SetNull() { hash = 0; n = (unsigned int) -1; }
- bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
- friend bool operator<(const COutPoint& a, const COutPoint& b)
- {
- return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
- }
- friend bool operator==(const COutPoint& a, const COutPoint& b)
- {
- return (a.hash == b.hash && a.n == b.n);
- }
- friend bool operator!=(const COutPoint& a, const COutPoint& b)
- {
- return !(a == b);
- }
- std::string ToString() const
- {
- return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
- }
- void print() const
- {
- printf("%s\n", ToString().c_str());
- }
- };
- class CTxIn
- {
- public:
- COutPoint prevout;
- CScript scriptSig;
- unsigned int nSequence;
- CTxIn()
- {
- nSequence = std::numeric_limits<unsigned int>::max();
- }
- explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
- {
- prevout = prevoutIn;
- scriptSig = scriptSigIn;
- nSequence = nSequenceIn;
- }
- CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
- {
- prevout = COutPoint(hashPrevTx, nOut);
- scriptSig = scriptSigIn;
- nSequence = nSequenceIn;
- }
- IMPLEMENT_SERIALIZE
- (
- READWRITE(prevout);
- READWRITE(scriptSig);
- READWRITE(nSequence);
- )
- bool IsFinal() const
- {
- return (nSequence == std::numeric_limits<unsigned int>::max());
- }
- friend bool operator==(const CTxIn& a, const CTxIn& b)
- {
- return (a.prevout == b.prevout &&
- a.scriptSig == b.scriptSig &&
- a.nSequence == b.nSequence);
- }
- friend bool operator!=(const CTxIn& a, const CTxIn& b)
- {
- return !(a == b);
- }
- std::string ToStringShort() const
- {
- return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
- }
- std::string ToString() const
- {
- std::string str;
- str += "CTxIn(";
- str += prevout.ToString();
- if (prevout.IsNull())
- str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
- else
- str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
- if (nSequence != std::numeric_limits<unsigned int>::max())
- str += strprintf(", nSequence=%u", nSequence);
- str += ")";
- return str;
- }
- void print() const
- {
- printf("%s\n", ToString().c_str());
- }
- };
- class CTxOut
- {
- public:
- int64 nValue;
- CScript scriptPubKey;
- CTxOut()
- {
- SetNull();
- }
- CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
- {
- nValue = nValueIn;
- scriptPubKey = scriptPubKeyIn;
- }
- IMPLEMENT_SERIALIZE
- (
- READWRITE(nValue);
- READWRITE(scriptPubKey);
- )
- void SetNull()
- {
- nValue = -1;
- scriptPubKey.clear();
- }
- bool IsNull()
- {
- return (nValue == -1);
- }
- void SetEmpty()
- {
- nValue = 0;
- scriptPubKey.clear();
- }
- bool IsEmpty() const
- {
- return (nValue == 0 && scriptPubKey.empty());
- }
- uint256 GetHash() const
- {
- return SerializeHash(*this);
- }
- friend bool operator==(const CTxOut& a, const CTxOut& b)
- {
- return (a.nValue == b.nValue &&
- a.scriptPubKey == b.scriptPubKey);
- }
- friend bool operator!=(const CTxOut& a, const CTxOut& b)
- {
- return !(a == b);
- }
- std::string ToStringShort() const
- {
- return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
- }
- std::string ToString() const
- {
- if (IsEmpty()) return "CTxOut(empty)";
- if (scriptPubKey.size() < 6)
- return "CTxOut(error)";
- return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
- }
- void print() const
- {
- printf("%s\n", ToString().c_str());
- }
- };
- enum GetMinFee_mode
- {
- GMF_BLOCK,
- GMF_RELAY,
- GMF_SEND,
- };
- typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
- class CTransaction
- {
- public:
- static const int CURRENT_VERSION=1;
- int nVersion;
- unsigned int nTime;
- std::vector<CTxIn> vin;
- std::vector<CTxOut> vout;
- unsigned int nLockTime;
- mutable int nDoS;
- bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
- CTransaction()
- {
- SetNull();
- }
- IMPLEMENT_SERIALIZE
- (
- READWRITE(this->nVersion);
- nVersion = this->nVersion;
- READWRITE(nTime);
- READWRITE(vin);
- READWRITE(vout);
- READWRITE(nLockTime);
- )
- void SetNull()
- {
- nVersion = CTransaction::CURRENT_VERSION;
- nTime = GetAdjustedTime();
- vin.clear();
- vout.clear();
- nLockTime = 0;
- nDoS = 0; // Denial-of-service prevention
- }
- bool IsNull() const
- {
- return (vin.empty() && vout.empty());
- }
- uint256 GetHash() const
- {
- return SerializeHash(*this);
- }
- bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
- {
- if (nLockTime == 0)
- return true;
- if (nBlockHeight == 0)
- nBlockHeight = nBestHeight;
- if (nBlockTime == 0)
- nBlockTime = GetAdjustedTime();
- if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
- return true;
- BOOST_FOREACH(const CTxIn& txin, vin)
- if (!txin.IsFinal())
- return false;
- return true;
- }
- bool IsNewerThan(const CTransaction& old) const
- {
- if (vin.size() != old.vin.size())
- return false;
- for (unsigned int i = 0; i < vin.size(); i++)
- if (vin[i].prevout != old.vin[i].prevout)
- return false;
- bool fNewer = false;
- unsigned int nLowest = std::numeric_limits<unsigned int>::max();
- for (unsigned int i = 0; i < vin.size(); i++)
- {
- if (vin[i].nSequence != old.vin[i].nSequence)
- {
- if (vin[i].nSequence <= nLowest)
- {
- fNewer = false;
- nLowest = vin[i].nSequence;
- }
- if (old.vin[i].nSequence < nLowest)
- {
- fNewer = true;
- nLowest = old.vin[i].nSequence;
- }
- }
- }
- return fNewer;
- }
- bool IsCoinBase() const
- {
- return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
- }
- bool IsCoinStake() const
- {
- // ecoin: the coin stake transaction is marked with the first output empty
- return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
- }
- bool IsStandard() const;
- bool AreInputsStandard(const MapPrevTx& mapInputs) const;
- unsigned int GetLegacySigOpCount() const;
- unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
- int64 GetValueOut() const
- {
- int64 nValueOut = 0;
- BOOST_FOREACH(const CTxOut& txout, vout)
- {
- nValueOut += txout.nValue;
- if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
- throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
- }
- return nValueOut;
- }
- int64 GetValueIn(const MapPrevTx& mapInputs) const;
- static bool AllowFree(double dPriority)
- {
- return dPriority > COIN * 720 / 250;
- }
- int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
- bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
- {
- CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
- if (!filein)
- return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
- // Read transaction
- if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
- return error("CTransaction::ReadFromDisk() : fseek failed");
- try {
- filein >> *this;
- }
- catch (std::exception &e) {
- return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
- }
- // Return file pointer
- if (pfileRet)
- {
- if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
- return error("CTransaction::ReadFromDisk() : second fseek failed");
- *pfileRet = filein.release();
- }
- return true;
- }
- friend bool operator==(const CTransaction& a, const CTransaction& b)
- {
- return (a.nVersion == b.nVersion &&
- a.nTime == b.nTime &&
- a.vin == b.vin &&
- a.vout == b.vout &&
- a.nLockTime == b.nLockTime);
- }
- friend bool operator!=(const CTransaction& a, const CTransaction& b)
- {
- return !(a == b);
- }
- std::string ToStringShort() const
- {
- std::string str;
- str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
- return str;
- }
- std::string ToString() const
- {
- std::string str;
- str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
- str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu", vout.size=%" PRIszu", nLockTime=%d)\n",
- GetHash().ToString().substr(0,10).c_str(),
- nTime,
- nVersion,
- vin.size(),
- vout.size(),
- nLockTime);
- for (unsigned int i = 0; i < vin.size(); i++)
- str += " " + vin[i].ToString() + "\n";
- for (unsigned int i = 0; i < vout.size(); i++)
- str += " " + vout[i].ToString() + "\n";
- return str;
- }
- void print() const
- {
- printf("%s", ToString().c_str());
- }
- bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
- bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
- bool ReadFromDisk(COutPoint prevout);
- bool DisconnectInputs(CTxDB& txdb);
- bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
- bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
- bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
- std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
- const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
- bool ClientConnectInputs();
- bool CheckTransaction() const;
- bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
- bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ecoin: get transaction coin age
- protected:
- const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
- };
- class CMerkleTx : public CTransaction
- {
- public:
- uint256 hashBlock;
- std::vector<uint256> vMerkleBranch;
- int nIndex;
- mutable bool fMerkleVerified;
- CMerkleTx()
- {
- Init();
- }
- CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
- {
- Init();
- }
- void Init()
- {
- hashBlock = 0;
- nIndex = -1;
- fMerkleVerified = false;
- }
- IMPLEMENT_SERIALIZE
- (
- nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
- nVersion = this->nVersion;
- READWRITE(hashBlock);
- READWRITE(vMerkleBranch);
- READWRITE(nIndex);
- )
- int SetMerkleBranch(const CBlock* pblock=NULL);
- int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
- int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
- bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
- int GetBlocksToMaturity() const;
- bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
- bool AcceptToMemoryPool();
- };
- class CTxIndex
- {
- public:
- CDiskTxPos pos;
- std::vector<CDiskTxPos> vSpent;
- CTxIndex()
- {
- SetNull();
- }
- CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
- {
- pos = posIn;
- vSpent.resize(nOutputs);
- }
- IMPLEMENT_SERIALIZE
- (
- if (!(nType & SER_GETHASH))
- READWRITE(nVersion);
- READWRITE(pos);
- READWRITE(vSpent);
- )
- void SetNull()
- {
- pos.SetNull();
- vSpent.clear();
- }
- bool IsNull()
- {
- return pos.IsNull();
- }
- friend bool operator==(const CTxIndex& a, const CTxIndex& b)
- {
- return (a.pos == b.pos &&
- a.vSpent == b.vSpent);
- }
- friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
- {
- return !(a == b);
- }
- int GetDepthInMainChain() const;
- };
- class CBlock
- {
- public:
- // header
- static const int CURRENT_VERSION=6;
- int nVersion;
- uint256 hashPrevBlock;
- uint256 hashMerkleRoot;
- unsigned int nTime;
- unsigned int nBits;
- unsigned int nNonce;
- // network and disk
- std::vector<CTransaction> vtx;
- // ecoin: block signature - signed by one of the coin base txout[N]'s owner
- std::vector<unsigned char> vchBlockSig;
- // memory only
- mutable std::vector<uint256> vMerkleTree;
- // Denial-of-service detection:
- mutable int nDoS;
- bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
- CBlock()
- {
- SetNull();
- }
- IMPLEMENT_SERIALIZE
- (
- READWRITE(this->nVersion);
- nVersion = this->nVersion;
- READWRITE(hashPrevBlock);
- READWRITE(hashMerkleRoot);
- READWRITE(nTime);
- READWRITE(nBits);
- READWRITE(nNonce);
- // ConnectBlock depends on vtx following header to generate CDiskTxPos
- if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
- {
- READWRITE(vtx);
- READWRITE(vchBlockSig);
- }
- else if (fRead)
- {
- const_cast<CBlock*>(this)->vtx.clear();
- const_cast<CBlock*>(this)->vchBlockSig.clear();
- }
- )
- void SetNull()
- {
- nVersion = CBlock::CURRENT_VERSION;
- hashPrevBlock = 0;
- hashMerkleRoot = 0;
- nTime = 0;
- nBits = 0;
- nNonce = 0;
- vtx.clear();
- vchBlockSig.clear();
- vMerkleTree.clear();
- nDoS = 0;
- }
- bool IsNull() const
- {
- return (nBits == 0);
- }
- uint256 GetHash() const
- {
- return scrypt_blockhash(CVOIDBEGIN(nVersion));
- }
- int64 GetBlockTime() const
- {
- return (int64)nTime;
- }
- void UpdateTime(const CBlockIndex* pindexPrev);
- // ecoin: entropy bit for stake modifier if chosen by modifier
- unsigned int GetStakeEntropyBit(unsigned int nTime) const
- {
- // Take last bit of block hash as entropy bit
- unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
- if (fDebug && GetBoolArg("-printstakemodifier"))
- printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
- return nEntropyBit;
- }
- // ecoin: two types of block: proof-of-work or proof-of-stake
- bool IsProofOfStake() const
- {
- return (vtx.size() > 1 && vtx[1].IsCoinStake());
- }
- bool IsProofOfWork() const
- {
- return !IsProofOfStake();
- }
- std::pair<COutPoint, unsigned int> GetProofOfStake() const
- {
- return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
- }
- // ecoin: get max transaction timestamp
- int64 GetMaxTransactionTime() const
- {
- int64 maxTransactionTime = 0;
- BOOST_FOREACH(const CTransaction& tx, vtx)
- maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
- return maxTransactionTime;
- }
- uint256 BuildMerkleTree() const
- {
- vMerkleTree.clear();
- BOOST_FOREACH(const CTransaction& tx, vtx)
- vMerkleTree.push_back(tx.GetHash());
- int j = 0;
- for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
- {
- for (int i = 0; i < nSize; i += 2)
- {
- int i2 = std::min(i+1, nSize-1);
- vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
- BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
- }
- j += nSize;
- }
- return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
- }
- std::vector<uint256> GetMerkleBranch(int nIndex) const
- {
- if (vMerkleTree.empty())
- BuildMerkleTree();
- std::vector<uint256> vMerkleBranch;
- int j = 0;
- for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
- {
- int i = std::min(nIndex^1, nSize-1);
- vMerkleBranch.push_back(vMerkleTree[j+i]);
- nIndex >>= 1;
- j += nSize;
- }
- return vMerkleBranch;
- }
- static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
- {
- if (nIndex == -1)
- return 0;
- BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
- {
- if (nIndex & 1)
- hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
- else
- hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
- nIndex >>= 1;
- }
- return hash;
- }
- bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
- {
- // Open history file to append
- CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
- if (!fileout)
- return error("CBlock::WriteToDisk() : AppendBlockFile failed");
- // Write index header
- unsigned int nSize = fileout.GetSerializeSize(*this);
- fileout << FLATDATA(pchMessageStart) << nSize;
- // Write block
- long fileOutPos = ftell(fileout);
- if (fileOutPos < 0)
- return error("CBlock::WriteToDisk() : ftell failed");
- nBlockPosRet = fileOutPos;
- fileout << *this;
- // Flush stdio buffers and commit to disk before returning
- fflush(fileout);
- if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
- FileCommit(fileout);
- return true;
- }
- bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
- {
- SetNull();
- // Open history file to read
- CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
- if (!filein)
- return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
- if (!fReadTransactions)
- filein.nType |= SER_BLOCKHEADERONLY;
- // Read block
- try {
- filein >> *this;
- }
- catch (std::exception &e) {
- return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
- }
- // Check the header
- if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
- return error("CBlock::ReadFromDisk() : errors in block header");
- return true;
- }
- void print() const
- {
- printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu", vchBlockSig=%s)\n",
- GetHash().ToString().c_str(),
- nVersion,
- hashPrevBlock.ToString().c_str(),
- hashMerkleRoot.ToString().c_str(),
- nTime, nBits, nNonce,
- vtx.size(),
- HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
- for (unsigned int i = 0; i < vtx.size(); i++)
- {
- printf(" ");
- vtx[i].print();
- }
- printf(" vMerkleTree: ");
- for (unsigned int i = 0; i < vMerkleTree.size(); i++)
- printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
- printf("\n");
- }
- bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
- bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
- bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
- bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
- bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
- bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
- bool AcceptBlock();
- bool GetCoinAge(uint64& nCoinAge) const; // ecoin: calculate total coin age spent in block
- bool SignBlock(CWallet& keystore);
- bool CheckBlockSignature(bool fProofOfStake) const;
- private:
- bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
- };
- class CBlockIndex
- {
- public:
- const uint256* phashBlock;
- CBlockIndex* pprev;
- CBlockIndex* pnext;
- unsigned int nFile;
- unsigned int nBlockPos;
- uint256 nChainTrust; // ecoin: trust score of block chain
- int nHeight;
- int64 nMint;
- int64 nMoneySupply;
- unsigned int nFlags; // ecoin: block index flags
- enum
- {
- 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
- };
- uint64 nStakeModifier; // hash modifier for proof-of-stake
- unsigned int nStakeModifierChecksum; // checksum of index; in-memory only
- // proof-of-stake specific fields
- COutPoint prevoutStake;
- unsigned int nStakeTime;
- uint256 hashProofOfStake;
- // block header
- int nVersion;
- uint256 hashMerkleRoot;
- unsigned int nTime;
- unsigned int nBits;
- unsigned int nNonce;
- CBlockIndex()
- {
- phashBlock = NULL;
- pprev = NULL;
- pnext = NULL;
- nFile = 0;
- nBlockPos = 0;
- nHeight = 0;
- nChainTrust = 0;
- nMint = 0;
- nMoneySupply = 0;
- nFlags = 0;
- nStakeModifier = 0;
- nStakeModifierChecksum = 0;
- hashProofOfStake = 0;
- prevoutStake.SetNull();
- nStakeTime = 0;
- nVersion = 0;
- hashMerkleRoot = 0;
- nTime = 0;
- nBits = 0;
- nNonce = 0;
- }
- CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
- {
- phashBlock = NULL;
- pprev = NULL;
- pnext = NULL;
- nFile = nFileIn;
- nBlockPos = nBlockPosIn;
- nHeight = 0;
- nChainTrust = 0;
- nMint = 0;
- nMoneySupply = 0;
- nFlags = 0;
- nStakeModifier = 0;
- nStakeModifierChecksum = 0;
- hashProofOfStake = 0;
- if (block.IsProofOfStake())
- {
- SetProofOfStake();
- prevoutStake = block.vtx[1].vin[0].prevout;
- nStakeTime = block.vtx[1].nTime;
- }
- else
- {
- prevoutStake.SetNull();
- nStakeTime = 0;
- }
- nVersion = block.nVersion;
- hashMerkleRoot = block.hashMerkleRoot;
- nTime = block.nTime;
- nBits = block.nBits;
- nNonce = block.nNonce;
- }
- CBlock GetBlockHeader() const
- {
- CBlock block;
- block.nVersion = nVersion;
- if (pprev)
- block.hashPrevBlock = pprev->GetBlockHash();
- block.hashMerkleRoot = hashMerkleRoot;
- block.nTime = nTime;
- block.nBits = nBits;
- block.nNonce = nNonce;
- return block;
- }
- uint256 GetBlockHash() const
- {
- return *phashBlock;
- }
- int64 GetBlockTime() const
- {
- return (int64)nTime;
- }
- uint256 GetBlockTrust() const;
- bool IsInMainChain() const
- {
- return (pnext || this == pindexBest);
- }
- bool CheckIndex() const
- {
- return true;
- }
- enum { nMedianTimeSpan=11 };
- int64 GetMedianTimePast() const
- {
- int64 pmedian[nMedianTimeSpan];
- int64* pbegin = &pmedian[nMedianTimeSpan];
- int64* pend = &pmedian[nMedianTimeSpan];
- const CBlockIndex* pindex = this;
- for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
- *(--pbegin) = pindex->GetBlockTime();
- std::sort(pbegin, pend);
- return pbegin[(pend - pbegin)/2];
- }
- int64 GetMedianTime() const
- {
- const CBlockIndex* pindex = this;
- for (int i = 0; i < nMedianTimeSpan/2; i++)
- {
- if (!pindex->pnext)
- return GetBlockTime();
- pindex = pindex->pnext;
- }
- return pindex->GetMedianTimePast();
- }
- static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
- unsigned int nRequired, unsigned int nToCheck);
- bool IsProofOfWork() const
- {
- return !(nFlags & BLOCK_PROOF_OF_STAKE);
- }
- bool IsProofOfStake() const
- {
- return (nFlags & BLOCK_PROOF_OF_STAKE);
- }
- void SetProofOfStake()
- {
- nFlags |= BLOCK_PROOF_OF_STAKE;
- }
- unsigned int GetStakeEntropyBit() const
- {
- return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
- }
- bool SetStakeEntropyBit(unsigned int nEntropyBit)
- {
- if (nEntropyBit > 1)
- return false;
- nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
- return true;
- }
- bool GeneratedStakeModifier() const
- {
- return (nFlags & BLOCK_STAKE_MODIFIER);
- }
- void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
- {
- nStakeModifier = nModifier;
- if (fGeneratedStakeModifier)
- nFlags |= BLOCK_STAKE_MODIFIER;
- }
- std::string ToString() const
- {
- return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016" PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
- pprev, pnext, nFile, nBlockPos, nHeight,
- FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
- GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
- nStakeModifier, nStakeModifierChecksum,
- hashProofOfStake.ToString().c_str(),
- prevoutStake.ToString().c_str(), nStakeTime,
- hashMerkleRoot.ToString().c_str(),
- GetBlockHash().ToString().c_str());
- }
- void print() const
- {
- printf("%s\n", ToString().c_str());
- }
- };
- class CDiskBlockIndex : public CBlockIndex
- {
- private:
- uint256 blockHash;
- public:
- uint256 hashPrev;
- uint256 hashNext;
- CDiskBlockIndex()
- {
- hashPrev = 0;
- hashNext = 0;
- blockHash = 0;
- }
- explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
- {
- hashPrev = (pprev ? pprev->GetBlockHash() : 0);
- hashNext = (pnext ? pnext->GetBlockHash() : 0);
- }
- IMPLEMENT_SERIALIZE
- (
- if (!(nType & SER_GETHASH))
- READWRITE(nVersion);
- READWRITE(hashNext);
- READWRITE(nFile);
- READWRITE(nBlockPos);
- READWRITE(nHeight);
- READWRITE(nMint);
- READWRITE(nMoneySupply);
- READWRITE(nFlags);
- READWRITE(nStakeModifier);
- if (IsProofOfStake())
- {
- READWRITE(prevoutStake);
- READWRITE(nStakeTime);
- READWRITE(hashProofOfStake);
- }
- else if (fRead)
- {
- const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
- const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
- const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
- }
- // block header
- READWRITE(this->nVersion);
- READWRITE(hashPrev);
- READWRITE(hashMerkleRoot);
- READWRITE(nTime);
- READWRITE(nBits);
- READWRITE(nNonce);
- READWRITE(blockHash);
- )
- uint256 GetBlockHash() const
- {
- if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
- return blockHash;
- CBlock block;
- block.nVersion = nVersion;
- block.hashPrevBlock = hashPrev;
- block.hashMerkleRoot = hashMerkleRoot;
- block.nTime = nTime;
- block.nBits = nBits;
- block.nNonce = nNonce;
- const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
- return blockHash;
- }
- std::string ToString() const
- {
- std::string str = "CDiskBlockIndex(";
- str += CBlockIndex::ToString();
- str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
- GetBlockHash().ToString().c_str(),
- hashPrev.ToString().c_str(),
- hashNext.ToString().c_str());
- return str;
- }
- void print() const
- {
- printf("%s\n", ToString().c_str());
- }
- };
- class CBlockLocator
- {
- protected:
- std::vector<uint256> vHave;
- public:
- CBlockLocator()
- {
- }
- explicit CBlockLocator(const CBlockIndex* pindex)
- {
- Set(pindex);
- }
- explicit CBlockLocator(uint256 hashBlock)
- {
- std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
- if (mi != mapBlockIndex.end())
- Set((*mi).second);
- }
- CBlockLocator(const std::vector<uint256>& vHaveIn)
- {
- vHave = vHaveIn;
- }
- IMPLEMENT_SERIALIZE
- (
- if (!(nType & SER_GETHASH))
- READWRITE(nVersion);
- READWRITE(vHave);
- )
- void SetNull()
- {
- vHave.clear();
- }
- bool IsNull()
- {
- return vHave.empty();
- }
- void Set(const CBlockIndex* pindex)
- {
- vHave.clear();
- int nStep = 1;
- while (pindex)
- {
- vHave.push_back(pindex->GetBlockHash());
- // Exponentially larger steps back
- for (int i = 0; pindex && i < nStep; i++)
- pindex = pindex->pprev;
- if (vHave.size() > 10)
- nStep *= 2;
- }
- vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
- }
- int GetDistanceBack()
- {
- // Retrace how far back it was in the sender's branch
- int nDistance = 0;
- int nStep = 1;
- BOOST_FOREACH(const uint256& hash, vHave)
- {
- std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
- if (mi != mapBlockIndex.end())
- {
- CBlockIndex* pindex = (*mi).second;
- if (pindex->IsInMainChain())
- return nDistance;
- }
- nDistance += nStep;
- if (nDistance > 10)
- nStep *= 2;
- }
- return nDistance;
- }
- CBlockIndex* GetBlockIndex()
- {
- // Find the first block the caller has in the main chain
- BOOST_FOREACH(const uint256& hash, vHave)
- {
- std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
- if (mi != mapBlockIndex.end())
- {
- CBlockIndex* pindex = (*mi).second;
- if (pindex->IsInMainChain())
- return pindex;
- }
- }
- return pindexGenesisBlock;
- }
- uint256 GetBlockHash()
- {
- // Find the first block the caller has in the main chain
- BOOST_FOREACH(const uint256& hash, vHave)
- {
- std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
- if (mi != mapBlockIndex.end())
- {
- CBlockIndex* pindex = (*mi).second;
- if (pindex->IsInMainChain())
- return hash;
- }
- }
- return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
- }
- int GetHeight()
- {
- CBlockIndex* pindex = GetBlockIndex();
- if (!pindex)
- return 0;
- return pindex->nHeight;
- }
- };
- class CTxMemPool
- {
- public:
- mutable CCriticalSection cs;
- std::map<uint256, CTransaction> mapTx;
- std::map<COutPoint, CInPoint> mapNextTx;
- bool accept(CTxDB& txdb, CTransaction &tx,
- bool fCheckInputs, bool* pfMissingInputs);
- bool addUnchecked(const uint256& hash, CTransaction &tx);
- bool remove(CTransaction &tx);
- void clear();
- void queryHashes(std::vector<uint256>& vtxid);
- unsigned long size()
- {
- LOCK(cs);
- return mapTx.size();
- }
- bool exists(uint256 hash)
- {
- return (mapTx.count(hash) != 0);
- }
- CTransaction& lookup(uint256 hash)
- {
- return mapTx[hash];
- }
- };
- extern CTxMemPool mempool;
- #endif
|