diff --git a/src/budget/budgetmanager.cpp b/src/budget/budgetmanager.cpp index 057863b2d35c..64dc151a5ed1 100644 --- a/src/budget/budgetmanager.cpp +++ b/src/budget/budgetmanager.cpp @@ -59,7 +59,7 @@ uint256 CBudgetManager::SubmitFinalBudget() // Submit final budget during the last 2 days (2880 blocks) before payment for Mainnet, about 9 minutes (9 blocks) for Testnet int finalizationWindow = ((nBlocksPerCycle / 30) * 2); - if (Params().NetworkID() == CBaseChainParams::TESTNET) { + if (Params().IsTestnet()) { // NOTE: 9 blocks for testnet is way to short to have any masternode submit an automatic vote on the finalized(!) budget, // because those votes are only submitted/relayed once every 56 blocks in CFinalizedBudget::AutoCheck() @@ -878,7 +878,7 @@ void CBudgetManager::NewBlock(int height) int CBudgetManager::ProcessBudgetVoteSync(const uint256& nProp, CNode* pfrom) { - if (Params().NetworkID() == CBaseChainParams::MAIN) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (nProp.IsNull()) { if (pfrom->HasFulfilledRequest("budgetvotesync")) { LogPrint(BCLog::MNBUDGET, "mnvs - peer already asked me for the list\n"); diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 205261730950..321b31c82f8f 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -9,7 +9,7 @@ #include "chainparamsseeds.h" #include "consensus/merkle.h" -#include "util.h" +#include "tinyformat.h" #include "utilstrencodings.h" #include @@ -35,6 +35,13 @@ static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesi return genesis; } +void CChainParams::UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight) +{ + assert(IsRegTestNet()); // only available for regtest + assert(idx > Consensus::BASE_NETWORK && idx < Consensus::MAX_NETWORK_UPGRADES); + consensus.vUpgrades[idx].nActivationHeight = nActivationHeight; +} + /** * Build the genesis block. Note that the output of the genesis coinbase cannot * be spent as it did not originally exist in the database. @@ -85,7 +92,7 @@ static Checkpoints::MapCheckpoints mapCheckpoints = { {2153200, uint256S("14e477e597d24549cac5e59d97d32155e6ec2861c1003b42d0566f9bf39b65d5")}, //!< First v7 block {2356049, uint256S("62e80d8e193bca84655fb78893b20f54a79f2d71124c4ea37b7ef51a0d5451c4")}, //!< Network split here {2365700, uint256S("b5d0beead57735539abc2db2b0b08cd65db3e5928efd3c3bf3182d5bf013f36c")}, //!< PIVX v4.1.1 enforced - {2678402, uint256S("580a26ff0a45177a7a6f387f009c5b26140ea48b4790a857d9a796f8b3c25899")}, //!< Network split here} + {2678402, uint256S("580a26ff0a45177a7a6f387f009c5b26140ea48b4790a857d9a796f8b3c25899")}, //!< Network split here }; static const Checkpoints::CCheckpointData data = { @@ -119,7 +126,6 @@ class CMainParams : public CChainParams public: CMainParams() { - networkID = CBaseChainParams::MAIN; strNetworkID = "main"; genesis = CreateGenesisBlock(1454124731, 2402015, 0x1e0ffff0, 1, 250 * COIN); @@ -248,17 +254,15 @@ class CMainParams : public CChainParams } }; -static CMainParams mainParams; /** * Testnet (v5) */ -class CTestNetParams : public CMainParams +class CTestNetParams : public CChainParams { public: CTestNetParams() { - networkID = CBaseChainParams::TESTNET; strNetworkID = "test"; genesis = CreateGenesisBlock(1454124731, 2402015, 0x1e0ffff0, 1, 250 * COIN); @@ -273,6 +277,11 @@ class CTestNetParams : public CMainParams consensus.nBudgetCycleBlocks = 144; // approx 10 cycles per day consensus.nBudgetFeeConfirmations = 3; // (only 8-blocks window for finalization on testnet) consensus.nCoinbaseMaturity = 15; + consensus.nFutureTimeDriftPoW = 7200; + consensus.nFutureTimeDriftPoS = 180; + consensus.nMasternodeCountDrift = 20; // num of MN we allow the see-saw payments to be off by + consensus.nMaxMoneyOut = 21000000 * COIN; + consensus.nPoolMaxTransactions = 3; consensus.nProposalEstablishmentTime = 60 * 5; // at least 5 min old to make it into a budget consensus.nStakeMinAge = 60 * 60; consensus.nStakeMinDepth = 100; @@ -285,6 +294,8 @@ class CTestNetParams : public CMainParams // spork keys consensus.strSporkPubKey = "04677c34726c491117265f4b1c83cef085684f36c8df5a97a3a42fc499316d0c4e63959c9eca0dba239d9aaaf72011afffeb3ef9f51b9017811dec686e412eb504"; consensus.strSporkPubKeyOld = "04E88BB455E2A04E65FCC41D88CD367E9CCE1F5A409BE94D8C2B4B35D223DED9C8E2F4E061349BA3A38839282508066B6DC4DB72DD432AC4067991E6BF20176127"; + consensus.nTime_EnforceNewSporkKey = 1608512400; //!> December 21, 2020 01:00:00 AM GMT + consensus.nTime_RejectOldSporkKey = 1614560400; //!> March 1, 2021 01:00:00 AM GMT // height based activations consensus.height_last_ZC_AccumCheckpoint = -1; @@ -294,6 +305,20 @@ class CTestNetParams : public CMainParams consensus.height_start_ZC_SerialRangeCheck = 1; consensus.height_ZC_RecalcAccumulators = 999999999; + // Zerocoin-related params + consensus.ZC_Modulus = "25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784" + "4069182906412495150821892985591491761845028084891200728449926873928072877767359714183472702618963750149718246911" + "6507761337985909570009733045974880842840179742910064245869181719511874612151517265463228221686998754918242243363" + "7259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133" + "8441436038339044149526344321901146575444541784240209246165157233507787077498171257724679629263863563732899121548" + "31438167899885040445364023527381951378636564391212010397122822120720357"; + consensus.ZC_MaxPublicSpendsPerTx = 637; // Assume about 220 bytes each input + consensus.ZC_MaxSpendsPerTx = 7; // Assume about 20kb each input + consensus.ZC_MinMintConfirmations = 20; + consensus.ZC_MinMintFee = 1 * CENT; + consensus.ZC_MinStakeDepth = 200; + consensus.ZC_TimeStart = 1508214600; // October 17, 2017 4:30:00 AM + // Network upgrades consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight = Consensus::NetworkUpgrade::ALWAYS_ACTIVE; @@ -314,15 +339,12 @@ class CTestNetParams : public CMainParams * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 4-byte int at any alignment. */ - pchMessageStart[0] = 0xf5; pchMessageStart[1] = 0xe6; pchMessageStart[2] = 0xd5; pchMessageStart[3] = 0xca; nDefaultPort = 51474; - vFixedSeeds.clear(); - vSeeds.clear(); // nodes with support for servicebits filtering should be at the top vSeeds.emplace_back("fuzzbawls.pw", "pivx-testnet.seed.fuzzbawls.pw", true); vSeeds.emplace_back("fuzzbawls.pw", "pivx-testnet.seed2.fuzzbawls.pw", true); @@ -353,17 +375,15 @@ class CTestNetParams : public CMainParams return dataTestnet; } }; -static CTestNetParams testNetParams; /** * Regression test */ -class CRegTestParams : public CTestNetParams +class CRegTestParams : public CChainParams { public: CRegTestParams() { - networkID = CBaseChainParams::REGTEST; strNetworkID = "regtest"; genesis = CreateGenesisBlock(1454124731, 2402015, 0x1e0ffff0, 1, 250 * COIN); @@ -390,6 +410,7 @@ class CRegTestParams : public CTestNetParams consensus.nTargetTimespanV2 = 30 * 60; consensus.nTargetSpacing = 1 * 60; consensus.nTimeSlotLength = 15; + consensus.nMaxProposalPayments = 20; /* Spork Key for RegTest: WIF private key: 932HEevBSujW2ud7RfB1YF91AFygbBRQj3de3LyaCRqNzKKgWXi @@ -445,70 +466,63 @@ class CRegTestParams : public CTestNetParams * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 4-byte int at any alignment. */ - pchMessageStart[0] = 0xa1; pchMessageStart[1] = 0xcf; pchMessageStart[2] = 0x7e; pchMessageStart[3] = 0xac; nDefaultPort = 51476; - vFixedSeeds.clear(); //! Testnet mode doesn't have any fixed seeds. - vSeeds.clear(); //! Testnet mode doesn't have any DNS seeds. + base58Prefixes[PUBKEY_ADDRESS] = std::vector(1, 139); // Testnet pivx addresses start with 'x' or 'y' + base58Prefixes[SCRIPT_ADDRESS] = std::vector(1, 19); // Testnet pivx script addresses start with '8' or '9' + base58Prefixes[STAKING_ADDRESS] = std::vector(1, 73); // starting with 'W' + base58Prefixes[SECRET_KEY] = std::vector(1, 239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) + // Testnet pivx BIP32 pubkeys start with 'DRKV' + base58Prefixes[EXT_PUBLIC_KEY] = {0x3a, 0x80, 0x61, 0xa0}; + // Testnet pivx BIP32 prvkeys start with 'DRKP' + base58Prefixes[EXT_SECRET_KEY] = {0x3a, 0x80, 0x58, 0x37}; + // Testnet pivx BIP44 coin type is '1' (All coin's testnet default) + base58Prefixes[EXT_COIN_TYPE] = {0x80, 0x00, 0x00, 0x01}; + + // Sapling + bech32HRPs[SAPLING_PAYMENT_ADDRESS] = "ptestsapling"; + bech32HRPs[SAPLING_FULL_VIEWING_KEY] = "pviewtestsapling"; + bech32HRPs[SAPLING_INCOMING_VIEWING_KEY] = "pivktestsapling"; + bech32HRPs[SAPLING_EXTENDED_SPEND_KEY] = "p-secret-spending-key-test"; + bech32HRPs[SAPLING_EXTENDED_FVK] = "pxviewtestsapling"; } const Checkpoints::CCheckpointData& Checkpoints() const { return dataRegtest; } - - void UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight) - { - assert(idx > Consensus::BASE_NETWORK && idx < Consensus::MAX_NETWORK_UPGRADES); - consensus.vUpgrades[idx].nActivationHeight = nActivationHeight; - } }; -static CRegTestParams regTestParams; -static CChainParams* pCurrentParams = 0; +static std::unique_ptr globalChainParams; -const CChainParams& Params() +const CChainParams &Params() { - assert(pCurrentParams); - return *pCurrentParams; + assert(globalChainParams); + return *globalChainParams; } -CChainParams& Params(CBaseChainParams::Network network) +std::unique_ptr CreateChainParams(const std::string& chain) { - switch (network) { - case CBaseChainParams::MAIN: - return mainParams; - case CBaseChainParams::TESTNET: - return testNetParams; - case CBaseChainParams::REGTEST: - return regTestParams; - default: - assert(false && "Unimplemented network"); - return mainParams; - } + if (chain == CBaseChainParams::MAIN) + return std::unique_ptr(new CMainParams()); + else if (chain == CBaseChainParams::TESTNET) + return std::unique_ptr(new CTestNetParams()); + else if (chain == CBaseChainParams::REGTEST) + return std::unique_ptr(new CRegTestParams()); + throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } -void SelectParams(CBaseChainParams::Network network) +void SelectParams(const std::string& network) { SelectBaseParams(network); - pCurrentParams = &Params(network); -} - -bool SelectParamsFromCommandLine() -{ - CBaseChainParams::Network network = NetworkIdFromCommandLine(); - if (network == CBaseChainParams::MAX_NETWORK_TYPES) - return false; - - SelectParams(network); - return true; + globalChainParams = CreateChainParams(network); } void UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight) { - regTestParams.UpdateNetworkUpgradeParameters(idx, nActivationHeight); + globalChainParams->UpdateNetworkUpgradeParameters(idx, nActivationHeight); } diff --git a/src/chainparams.h b/src/chainparams.h index 0b11fab023c4..85401ebb710b 100644 --- a/src/chainparams.h +++ b/src/chainparams.h @@ -15,6 +15,7 @@ #include "protocol.h" #include "uint256.h" +#include #include struct CDNSSeedData { @@ -38,6 +39,7 @@ struct SeedSpec6 { class CChainParams { public: + virtual ~CChainParams() {} enum Base58Type { PUBKEY_ADDRESS, SCRIPT_ADDRESS, @@ -81,14 +83,13 @@ class CChainParams const std::vector& FixedSeeds() const { return vFixedSeeds; } virtual const Checkpoints::CCheckpointData& Checkpoints() const = 0; - CBaseChainParams::Network NetworkID() const { return networkID; } - bool IsRegTestNet() const { return NetworkID() == CBaseChainParams::REGTEST; } - + bool IsRegTestNet() const { return NetworkIDString() == CBaseChainParams::REGTEST; } + bool IsTestnet() const { return NetworkIDString() == CBaseChainParams::TESTNET; } + void UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight); protected: CChainParams() {} - CBaseChainParams::Network networkID; std::string strNetworkID; CBlock genesis; Consensus::Params consensus; @@ -101,22 +102,23 @@ class CChainParams }; /** - * Return the currently selected parameters. This won't change after app startup - * outside of the unit tests. + * Creates and returns a std::unique_ptr of the chosen chain. + * @returns a CChainParams* of the chosen chain. + * @throws a std::runtime_error if the chain is not supported. */ -const CChainParams& Params(); - -/** Return parameters for the given network. */ -CChainParams& Params(CBaseChainParams::Network network); +std::unique_ptr CreateChainParams(const std::string& chain); -/** Sets the params returned by Params() to those for the given network. */ -void SelectParams(CBaseChainParams::Network network); +/** + * Return the currently selected parameters. This won't change after app + * startup, except for unit tests. + */ +const CChainParams& Params(); /** - * Looks for -regtest or -testnet and then calls SelectParams as appropriate. - * Returns false if an invalid combination is given. + * Sets the params returned by Params() to those for the given BIP70 chain name. + * @throws std::runtime_error when the chain is not supported. */ -bool SelectParamsFromCommandLine(); +void SelectParams(const std::string& chain); /** * Allows modifying the network upgrade regtest parameters. diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp index ef4e0704a42e..a9f2ff9606ae 100644 --- a/src/chainparamsbase.cpp +++ b/src/chainparamsbase.cpp @@ -6,10 +6,25 @@ #include "chainparamsbase.h" +#include "tinyformat.h" #include "util.h" #include +const std::string CBaseChainParams::MAIN = "main"; +const std::string CBaseChainParams::TESTNET = "test"; +const std::string CBaseChainParams::REGTEST = "regtest"; + +void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp) +{ + strUsage += HelpMessageGroup(_("Chain selection options:")); + strUsage += HelpMessageOpt("-testnet", _("Use the test chain")); + if (debugHelp) { + strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. " + "This is intended for regression testing tools and app development."); + } +} + /** * Main network */ @@ -18,94 +33,71 @@ class CBaseMainParams : public CBaseChainParams public: CBaseMainParams() { - networkID = CBaseChainParams::MAIN; nRPCPort = 51473; } }; -static CBaseMainParams mainParams; /** * Testnet (v5) */ -class CBaseTestNetParams : public CBaseMainParams +class CBaseTestNetParams : public CBaseChainParams { public: CBaseTestNetParams() { - networkID = CBaseChainParams::TESTNET; nRPCPort = 51475; strDataDir = "testnet5"; } }; -static CBaseTestNetParams testNetParams; /* * Regression test */ -class CBaseRegTestParams : public CBaseTestNetParams +class CBaseRegTestParams : public CBaseChainParams { public: CBaseRegTestParams() { - networkID = CBaseChainParams::REGTEST; + nRPCPort = 51475; strDataDir = "regtest"; } }; -static CBaseRegTestParams regTestParams; -static CBaseChainParams* pCurrentBaseParams = 0; +static std::unique_ptr globalChainBaseParams; const CBaseChainParams& BaseParams() { - assert(pCurrentBaseParams); - return *pCurrentBaseParams; + assert(globalChainBaseParams); + return *globalChainBaseParams; } -CBaseChainParams& BaseParams(CBaseChainParams::Network network) +std::unique_ptr CreateBaseChainParams(const std::string& chain) { - switch (network) { - case CBaseChainParams::MAIN: - return mainParams; - case CBaseChainParams::TESTNET: - return testNetParams; - case CBaseChainParams::REGTEST: - return regTestParams; - default: - assert(false && "Unimplemented network"); - return mainParams; - } + if (chain == CBaseChainParams::MAIN) + return std::unique_ptr(new CBaseMainParams()); + else if (chain == CBaseChainParams::TESTNET) + return std::unique_ptr(new CBaseTestNetParams()); + else if (chain == CBaseChainParams::REGTEST) + return std::unique_ptr(new CBaseRegTestParams()); + else + throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } -void SelectBaseParams(CBaseChainParams::Network network) +void SelectBaseParams(const std::string& chain) { - pCurrentBaseParams = &BaseParams(network); + globalChainBaseParams = CreateBaseChainParams(chain); } -CBaseChainParams::Network NetworkIdFromCommandLine() +std::string ChainNameFromCommandLine() { bool fRegTest = gArgs.GetBoolArg("-regtest", false); bool fTestNet = gArgs.GetBoolArg("-testnet", false); if (fTestNet && fRegTest) - return CBaseChainParams::MAX_NETWORK_TYPES; + throw std::runtime_error("Invalid combination of -regtest and -testnet."); if (fRegTest) return CBaseChainParams::REGTEST; if (fTestNet) return CBaseChainParams::TESTNET; return CBaseChainParams::MAIN; } - -bool SelectBaseParamsFromCommandLine() -{ - CBaseChainParams::Network network = NetworkIdFromCommandLine(); - if (network == CBaseChainParams::MAX_NETWORK_TYPES) - return false; - - SelectBaseParams(network); - return true; -} - -bool AreBaseParamsConfigured() -{ - return pCurrentBaseParams != NULL; -} diff --git a/src/chainparamsbase.h b/src/chainparamsbase.h index 2b416e9435c9..1b9483db6c00 100644 --- a/src/chainparamsbase.h +++ b/src/chainparamsbase.h @@ -6,6 +6,7 @@ #ifndef BITCOIN_CHAINPARAMSBASE_H #define BITCOIN_CHAINPARAMSBASE_H +#include #include #include @@ -16,13 +17,10 @@ class CBaseChainParams { public: - enum Network { - MAIN, - TESTNET, - REGTEST, - - MAX_NETWORK_TYPES - }; + /** BIP70 chain name strings (main, test or regtest) */ + static const std::string MAIN; + static const std::string TESTNET; + static const std::string REGTEST; const std::string& DataDir() const { return strDataDir; } int RPCPort() const { return nRPCPort; } @@ -32,39 +30,34 @@ class CBaseChainParams int nRPCPort; std::string strDataDir; - Network networkID; }; /** - * Return the currently selected parameters. This won't change after app startup - * outside of the unit tests. + * Creates and returns a std::unique_ptr of the chosen chain. + * @returns a CBaseChainParams* of the chosen chain. + * @throws a std::runtime_error if the chain is not supported. */ -const CBaseChainParams& BaseParams(); +std::unique_ptr CreateBaseChainParams(const std::string& chain); /** - * Return parameters for the given network. + * Append the help messages for the chainparams options to the + * parameter string. */ -CBaseChainParams& BaseParams(CBaseChainParams::Network network); - -/** Sets the params returned by Params() to those for the given network. */ -void SelectBaseParams(CBaseChainParams::Network network); +void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp=true); /** - * Looks for -regtest or -testnet and returns the appropriate Network ID. - * Returns MAX_NETWORK_TYPES if an invalid combination is given. + * Return the currently selected parameters. This won't change after app startup + * startup, except for unit tests. */ -CBaseChainParams::Network NetworkIdFromCommandLine(); +const CBaseChainParams& BaseParams(); -/** - * Calls NetworkIdFromCommandLine() and then calls SelectParams as appropriate. - * Returns false if an invalid combination is given. - */ -bool SelectBaseParamsFromCommandLine(); +/** Sets the params returned by Params() to those for the given network. */ +void SelectBaseParams(const std::string& chain); /** - * Return true if SelectBaseParamsFromCommandLine() has been called to select - * a network. + * Looks for -regtest, -testnet and returns the appropriate BIP70 chain name. + * @return CBaseChainParams::MAX_NETWORK_TYPES if an invalid combination is given. CBaseChainParams::MAIN by default. */ -bool AreBaseParamsConfigured(); +std::string ChainNameFromCommandLine(); #endif // BITCOIN_CHAINPARAMSBASE_H diff --git a/src/consensus/zerocoin_verify.cpp b/src/consensus/zerocoin_verify.cpp index 51b7e696a9ee..df84490c881b 100644 --- a/src/consensus/zerocoin_verify.cpp +++ b/src/consensus/zerocoin_verify.cpp @@ -105,7 +105,7 @@ bool CheckZerocoinSpend(const CTransaction& tx, bool fVerifySignature, CValidati bool isBlockBetweenFakeSerialAttackRange(int nHeight) { - if (Params().NetworkID() != CBaseChainParams::MAIN) + if (Params().NetworkIDString() != CBaseChainParams::MAIN) return false; return nHeight <= Params().GetConsensus().height_last_ZC_WrappedSerials; diff --git a/src/dbwrapper.h b/src/dbwrapper.h index b73693c83f84..4700d3b453be 100644 --- a/src/dbwrapper.h +++ b/src/dbwrapper.h @@ -145,7 +145,7 @@ class CDBIterator try { CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); ssKey >> key; - } catch(std::exception &e) { + } catch(const std::exception& e) { return false; } return true; @@ -160,7 +160,7 @@ class CDBIterator try { CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); ssValue >> value; - } catch(std::exception &e) { + } catch(const std::exception& e) { return false; } return true; diff --git a/src/init.cpp b/src/init.cpp index bef8284eba5f..ce86de3c3da2 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -396,6 +396,10 @@ void OnRPCPreCommand(const CRPCCommand& cmd) std::string HelpMessage(HelpMessageMode mode) { + const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN); + const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET); + const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN); + const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET); const bool showDebug = gArgs.GetBoolArg("-help-debug", false); // When adding new options to the categories, please keep and ensure alphabetical ordering. @@ -455,7 +459,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-onlynet=", _("Only connect to nodes in network (ipv4, ipv6 or onion)")); strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG)); strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS)); - strUsage += HelpMessageOpt("-port=", strprintf(_("Listen for connections on (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort())); + strUsage += HelpMessageOpt("-port=", strprintf(_("Listen for connections on (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort())); strUsage += HelpMessageOpt("-proxy=", _("Connect through SOCKS5 proxy")); strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE)); strUsage += HelpMessageOpt("-seednode=", _("Connect to a node to retrieve peer addresses, and disconnect")); @@ -486,8 +490,8 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageGroup(_("Debugging/Testing options:")); strUsage += HelpMessageOpt("-uacomment=", _("Append comment to the user agent string")); if (showDebug) { - strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks())); - strUsage += HelpMessageOpt("-checkmempool=", strprintf("Run checks every transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks())); + strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks())); + strUsage += HelpMessageOpt("-checkmempool=", strprintf("Run checks every transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks())); strUsage += HelpMessageOpt("-checkpoints", strprintf(_("Only accept block chain matching built-in checkpoints (default: %u)"), DEFAULT_CHECKPOINTS_ENABLED)); strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE)); strUsage += HelpMessageOpt("-testsafemode", strprintf(_("Force safe mode (default: %u)"), DEFAULT_TESTSAFEMODE)); @@ -523,12 +527,9 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-printtoconsole", strprintf(_("Send trace/debug info to console instead of debug.log file (default: %u)"), 0)); if (showDebug) { strUsage += HelpMessageOpt("-printpriority", strprintf(_("Log transaction priority and fee per kB when mining blocks (default: %u)"), DEFAULT_PRINTPRIORITY)); - strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.") + " " + - _("This is intended for regression testing tools and app development.") + " " + - _("In this mode -genproclimit controls how many blocks are generated immediately.")); } strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)")); - strUsage += HelpMessageOpt("-testnet", _("Use the test network")); + AppendParamsHelpMessages(strUsage, showDebug); strUsage += HelpMessageOpt("-litemode=", strprintf(_("Disable all PIVX specific functionality (Masternodes, Budgeting) (0-1, default: %u)"), 0)); strUsage += HelpMessageGroup(_("Masternode options:")); @@ -558,7 +559,7 @@ std::string HelpMessage(HelpMessageMode mode) strUsage += HelpMessageOpt("-rpccookiefile=", _("Location of the auth cookie (default: data dir)")); strUsage += HelpMessageOpt("-rpcuser=", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=", _("Password for JSON-RPC connections")); - strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Listen for JSON-RPC connections on (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort())); + strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Listen for JSON-RPC connections on (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort())); strUsage += HelpMessageOpt("-rpcallowip=", _("Allow JSON-RPC connections from specified source. Valid for are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times")); strUsage += HelpMessageOpt("-rpcthreads=", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS)); if (showDebug) { diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 563833b07750..9fbcacfd7f88 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -217,7 +217,7 @@ bool IsBlockValueValid(int nHeight, CAmount& nExpectedValue, CAmount nMinted) //there is no budget data to use to check anything //super blocks will always be on these blocks, max 100 per budgeting if (nHeight % Params().GetConsensus().nBudgetCycleBlocks < 100) { - if (Params().NetworkID() == CBaseChainParams::TESTNET) { + if (Params().IsTestnet()) { return true; } nExpectedValue += g_budgetman.GetTotalBudget(nHeight); @@ -380,7 +380,7 @@ void CMasternodePayments::ProcessMessageMasternodePayments(CNode* pfrom, std::st int nCountNeeded; vRecv >> nCountNeeded; - if (Params().NetworkID() == CBaseChainParams::MAIN) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (pfrom->HasFulfilledRequest(NetMsgType::GETMNWINNERS)) { LogPrintf("CMasternodePayments::ProcessMessageMasternodePayments() : mnget - peer already asked me for the list\n"); LOCK(cs_main); diff --git a/src/masternode.cpp b/src/masternode.cpp index e10cdebae885..f2dfd0c89832 100644 --- a/src/masternode.cpp +++ b/src/masternode.cpp @@ -419,7 +419,7 @@ bool CMasternodeBroadcast::CheckAndUpdate(int& nDos) return error("%s : Got bad Masternode address signature", __func__); } - if (Params().NetworkID() == CBaseChainParams::MAIN) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (addr.GetPort() != 51472) return false; } else if (addr.GetPort() == 51472) return false; diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index 2880878eefd4..7acc42024fbe 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -406,7 +406,7 @@ void CMasternodeMan::DsegUpdate(CNode* pnode) { LOCK(cs); - if (Params().NetworkID() == CBaseChainParams::MAIN) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (!(pnode->addr.IsRFC1918() || pnode->addr.IsLocal())) { std::map::iterator it = mWeAskedForMasternodeList.find(pnode->addr); if (it != mWeAskedForMasternodeList.end()) { @@ -719,7 +719,7 @@ int CMasternodeMan::ProcessGetMNList(CNode* pfrom, CTxIn& vin) //local network bool isLocal = (pfrom->addr.IsRFC1918() || pfrom->addr.IsLocal()); - if (!isLocal && Params().NetworkID() == CBaseChainParams::MAIN) { + if (!isLocal && Params().NetworkIDString() == CBaseChainParams::MAIN) { std::map::iterator i = mAskedUsForMasternodeList.find(pfrom->addr); if (i != mAskedUsForMasternodeList.end()) { int64_t t = (*i).second; diff --git a/src/pivx-cli.cpp b/src/pivx-cli.cpp index fa9a3636621a..ea9bd8844fa6 100644 --- a/src/pivx-cli.cpp +++ b/src/pivx-cli.cpp @@ -27,16 +27,16 @@ static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900; std::string HelpMessageCli() { + const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN); + const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET); std::string strUsage; strUsage += HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-conf=", strprintf(_("Specify configuration file (default: %s)"), PIVX_CONF_FILENAME)); strUsage += HelpMessageOpt("-datadir=", _("Specify data directory")); - strUsage += HelpMessageOpt("-testnet", _("Use the test network")); - strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be " - "solved instantly. This is intended for regression testing tools and app development.")); + AppendParamsHelpMessages(strUsage); strUsage += HelpMessageOpt("-rpcconnect=", strprintf(_("Send commands to node running on (default: %s)"), DEFAULT_RPCCONNECT)); - strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Connect to JSON-RPC on (default: %u or testnet: %u)"), 51473, 51475)); + strUsage += HelpMessageOpt("-rpcport=", strprintf(_("Listen for JSON-RPC connections on (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort())); strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start")); strUsage += HelpMessageOpt("-rpcuser=", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=", _("Password for JSON-RPC connections")); @@ -93,8 +93,10 @@ static bool AppInitRPC(int argc, char* argv[]) return false; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) - if (!SelectBaseParamsFromCommandLine()) { - fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); + try { + SelectBaseParams(ChainNameFromCommandLine()); + } catch(const std::exception& e) { + fprintf(stderr, "Error: %s\n", e.what()); return false; } if (gArgs.GetBoolArg("-rpcssl", false)) diff --git a/src/pivx-tx.cpp b/src/pivx-tx.cpp index b2aa7f312262..21ef09d3ef38 100644 --- a/src/pivx-tx.cpp +++ b/src/pivx-tx.cpp @@ -33,8 +33,10 @@ static bool AppInitRawTx(int argc, char* argv[]) gArgs.ParseParameters(argc, argv); // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) - if (!SelectParamsFromCommandLine()) { - fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); + try { + SelectParams(ChainNameFromCommandLine()); + } catch(const std::exception& e) { + fprintf(stderr, "Error: %s\n", e.what()); return false; } diff --git a/src/pivxd.cpp b/src/pivxd.cpp index d7d057a4d4b8..888fb52ac35b 100644 --- a/src/pivxd.cpp +++ b/src/pivxd.cpp @@ -88,8 +88,10 @@ bool AppInit(int argc, char* argv[]) return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) - if (!SelectParamsFromCommandLine()) { - fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); + try { + SelectParams(ChainNameFromCommandLine()); + } catch(const std::exception& e) { + fprintf(stderr, "Error: %s\n", e.what()); return false; } diff --git a/src/qt/bitcoinunits.cpp b/src/qt/bitcoinunits.cpp index da95deb9e6bc..c6a8cbbe1c01 100644 --- a/src/qt/bitcoinunits.cpp +++ b/src/qt/bitcoinunits.cpp @@ -59,7 +59,7 @@ QString BitcoinUnits::name(int unit, bool isZpiv) const QString CURR_UNIT = QString(CURRENCY_UNIT.c_str()); QString z = ""; if(isZpiv) z = "z"; - if (Params().NetworkID() == CBaseChainParams::MAIN) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { switch (unit) { case PIV: return z + CURR_UNIT; @@ -87,7 +87,7 @@ QString BitcoinUnits::name(int unit, bool isZpiv) QString BitcoinUnits::description(int unit) { const QString CURR_UNIT = QString(CURRENCY_UNIT.c_str()); - if (Params().NetworkID() == CBaseChainParams::MAIN) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { switch (unit) { case PIV: return CURR_UNIT; diff --git a/src/qt/paymentserver.cpp b/src/qt/paymentserver.cpp index c96cc46b3c6e..8fc8e129e5c9 100644 --- a/src/qt/paymentserver.cpp +++ b/src/qt/paymentserver.cpp @@ -194,9 +194,9 @@ void PaymentServer::ipcParseCommandLine(int argc, char* argv[]) SendCoinsRecipient r; if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty()) { - if (IsValidDestinationString(r.address.toStdString(), false, Params(CBaseChainParams::MAIN))) { + if (IsValidDestinationString(r.address.toStdString(), false, *CreateChainParams(CBaseChainParams::MAIN))) { SelectParams(CBaseChainParams::MAIN); - } else if (IsValidDestinationString(r.address.toStdString(), false, Params(CBaseChainParams::TESTNET))) { + } else if (IsValidDestinationString(r.address.toStdString(), false, *CreateChainParams(CBaseChainParams::TESTNET))) { SelectParams(CBaseChainParams::TESTNET); } } diff --git a/src/qt/pivx.cpp b/src/qt/pivx.cpp index b80003d535e6..9ac7ef50f26f 100644 --- a/src/qt/pivx.cpp +++ b/src/qt/pivx.cpp @@ -619,8 +619,10 @@ int main(int argc, char* argv[]) // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) - if (!SelectParamsFromCommandLine()) { - QMessageBox::critical(0, QObject::tr("PIVX Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet.")); + try { + SelectParams(ChainNameFromCommandLine()); + } catch(const std::exception& e) { + QMessageBox::critical(0, QObject::tr("PIVX Core"), QObject::tr("Error: %1").arg(e.what())); return 1; } #ifdef ENABLE_WALLET diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index 3faf1d77eb0d..a606aa4a2b4c 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -59,7 +59,7 @@ WalletModel::~WalletModel() bool WalletModel::isTestNetwork() const { - return Params().NetworkID() == CBaseChainParams::TESTNET; + return Params().IsTestnet(); } bool WalletModel::isRegTestNetwork() const diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 1f3fb17b63c8..9c8ad36bf38d 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -309,7 +309,7 @@ UniValue getmininginfo(const JSONRPCRequest& request) obj.pushKV("genproclimit", (int)gArgs.GetArg("-genproclimit", -1)); obj.pushKV("networkhashps", getnetworkhashps(request)); obj.pushKV("pooledtx", (uint64_t)mempool.size()); - obj.pushKV("testnet", Params().NetworkID() == CBaseChainParams::TESTNET); + obj.pushKV("testnet", Params().IsTestnet()); obj.pushKV("chain", Params().NetworkIDString()); #ifdef ENABLE_WALLET obj.pushKV("generate", getgenerate(request)); diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index c7e83c968a7d..0033c334c04b 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -126,7 +126,7 @@ UniValue getinfo(const JSONRPCRequest& request) obj.pushKV("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)); obj.pushKV("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())); obj.pushKV("difficulty", (double)GetDifficulty()); - obj.pushKV("testnet", Params().NetworkID() == CBaseChainParams::TESTNET); + obj.pushKV("testnet", Params().IsTestnet()); // Add (cached) money supply via getsupplyinfo RPC UniValue supply_info = getsupplyinfo(JSONRPCRequest()); diff --git a/src/validation.cpp b/src/validation.cpp index b6355813de7b..b5c6be80f066 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -797,7 +797,7 @@ CAmount GetBlockValue(int nHeight) return 250 * COIN; } // Testnet high-inflation blocks [2, 200] with value 250k PIV - const bool isTestnet = Params().NetworkID() == CBaseChainParams::TESTNET; + const bool isTestnet = Params().IsTestnet(); if (isTestnet && nHeight < 201 && nHeight > 1) { return 250000 * COIN; } diff --git a/src/zpiv/zerocoin.cpp b/src/zpiv/zerocoin.cpp index b1d0fde10a09..4f0fc81b0d0f 100644 --- a/src/zpiv/zerocoin.cpp +++ b/src/zpiv/zerocoin.cpp @@ -2,23 +2,9 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include #include "zerocoin.h" +#include "streams.h" #include "hash.h" -#include "util.h" -#include "utilstrencodings.h" - -bool CMintMeta::operator <(const CMintMeta& a) const -{ - return this->hashPubcoin < a.hashPubcoin; -} - -uint256 GetSerialHash(const CBigNum& bnSerial) -{ - CDataStream ss(SER_GETHASH, 0); - ss << bnSerial; - return Hash(ss.begin(), ss.end()); -} uint256 GetPubCoinHash(const CBigNum& bnValue) { @@ -26,91 +12,3 @@ uint256 GetPubCoinHash(const CBigNum& bnValue) ss << bnValue; return Hash(ss.begin(), ss.end()); } - -bool CZerocoinMint::GetKeyPair(CKey &key) const -{ - if (version < STAKABLE_VERSION) - return error("%s: version is %d", __func__, version); - - if (privkey.empty()) - return error("%s: empty privkey %s", __func__, privkey.data()); - - return key.SetPrivKey(privkey, true); -} - -std::string CZerocoinMint::ToString() const -{ - std::string str = strprintf("\n ZerocoinMint:\n version=%d \ntxfrom=%s \nheight=%d \n randomness: %s \n serial %s \n privkey %s\n", - version, txid.GetHex(), nHeight, randomness.GetHex(), serialNumber.GetHex(), HexStr(privkey)); - return str; -} - -void CZerocoinSpendReceipt::AddSpend(const CZerocoinSpend& spend) -{ - vSpends.emplace_back(spend); -} - -std::vector CZerocoinSpendReceipt::GetSpends() -{ - return vSpends; -} - -void CZerocoinSpendReceipt::SetStatus(std::string strStatus, int nStatus, int nNeededSpends) -{ - strStatusMessage = strStatus; - this->nStatus = nStatus; - this->nNeededSpends = nNeededSpends; -} - -std::string CZerocoinSpendReceipt::GetStatusMessage() -{ - return strStatusMessage; -} - -int CZerocoinSpendReceipt::GetStatus() -{ - return nStatus; -} - -int CZerocoinSpendReceipt::GetNeededSpends() -{ - return nNeededSpends; -} - - -int GetWrapppedSerialInflation(libzerocoin::CoinDenomination denom){ - if(Params().NetworkID() == CBaseChainParams::MAIN) { - switch (denom) { - case libzerocoin::CoinDenomination::ZQ_ONE: - return 7; - case libzerocoin::CoinDenomination::ZQ_FIVE: - return 6; - case libzerocoin::CoinDenomination::ZQ_TEN: - return 36; - case libzerocoin::CoinDenomination::ZQ_FIFTY: - return 22; - case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: - return 244; - case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: - return 22; - case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: - return 42; - case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: - return 98; - default: - throw std::runtime_error("GetWrapSerialInflation :: Invalid denom"); - } - }else{ - // Testnet/Regtest is ok. - return 0; - } -} - -int64_t GetWrapppedSerialInflationAmount(){ - int64_t amount = 0; - for (auto& denom : libzerocoin::zerocoinDenomList){ - amount += GetWrapppedSerialInflation(denom) * libzerocoin::ZerocoinDenominationToAmount(denom); - } - return amount; -} - diff --git a/src/zpiv/zerocoin.h b/src/zpiv/zerocoin.h index 68d70289884d..db748478f8a0 100644 --- a/src/zpiv/zerocoin.h +++ b/src/zpiv/zerocoin.h @@ -5,262 +5,9 @@ #ifndef PIVX_ZEROCOIN_H #define PIVX_ZEROCOIN_H -#include -#include -#include +#include "uint256.h" #include "libzerocoin/bignum.h" -#include "libzerocoin/Denominations.h" -#include "key.h" -#include "serialize.h" -//struct that is safe to store essential mint data, without holding any information that allows for actual spending (serial, randomness, private key) -struct CMintMeta -{ - int nHeight; - uint256 hashSerial; - uint256 hashPubcoin; - uint256 hashStake; //requires different hashing method than hashSerial above - uint8_t nVersion; - libzerocoin::CoinDenomination denom; - uint256 txid; - bool isUsed; - bool isArchived; - bool isDeterministic; - bool isSeedCorrect; - - bool operator <(const CMintMeta& a) const; -}; - -uint256 GetSerialHash(const CBigNum& bnSerial); uint256 GetPubCoinHash(const CBigNum& bnValue); -class CZerocoinMint -{ -private: - libzerocoin::CoinDenomination denomination; - int nHeight; - CBigNum value; - CBigNum randomness; - CBigNum serialNumber; - uint256 txid; - int outputIndex = -1; - CPrivKey privkey; - uint8_t version; - bool isUsed; - -public: - static const int STAKABLE_VERSION = 2; - static const int CURRENT_VERSION = 2; - - CZerocoinMint() - { - SetNull(); - } - - CZerocoinMint(libzerocoin::CoinDenomination denom, const CBigNum& value, const CBigNum& randomness, const CBigNum& serialNumber, bool isUsed, const uint8_t& nVersion, CPrivKey* privkey = nullptr) - { - SetNull(); - this->denomination = denom; - this->value = value; - this->randomness = randomness; - this->serialNumber = serialNumber; - this->isUsed = isUsed; - this->version = nVersion; - if (nVersion >= 2 && privkey) - this->privkey = *privkey; - } - - void SetNull() - { - isUsed = false; - randomness = 0; - value = 0; - denomination = libzerocoin::ZQ_ERROR; - nHeight = 0; - txid.SetNull(); - version = 1; - privkey.clear(); - } - - uint256 GetHash() const; - - CBigNum GetValue() const { return value; } - void SetValue(CBigNum value){ this->value = value; } - libzerocoin::CoinDenomination GetDenomination() const { return denomination; } - int64_t GetDenominationAsAmount() const { return denomination * COIN; } - void SetDenomination(libzerocoin::CoinDenomination denom){ this->denomination = denom; } - int GetHeight() const { return nHeight; } - void SetHeight(int nHeight){ this->nHeight = nHeight; } - bool IsUsed() const { return this->isUsed; } - void SetUsed(bool isUsed){ this->isUsed = isUsed; } - CBigNum GetRandomness() const{ return randomness; } - void SetRandomness(CBigNum rand){ this->randomness = rand; } - CBigNum GetSerialNumber() const { return serialNumber; } - void SetSerialNumber(CBigNum serial){ this->serialNumber = serial; } - uint256 GetTxHash() const { return this->txid; } - void SetTxHash(uint256 txid) { this->txid = txid; } - uint8_t GetVersion() const { return this->version; } - void SetVersion(const uint8_t nVersion) { this->version = nVersion; } - CPrivKey GetPrivKey() const { return this->privkey; } - void SetPrivKey(const CPrivKey& privkey) { this->privkey = privkey; } - bool GetKeyPair(CKey& key) const; - - int GetOutputIndex() { return this->outputIndex; } - void SetOutputIndex(int index) { this->outputIndex = index; } - - inline bool operator <(const CZerocoinMint& a) const { return GetHeight() < a.GetHeight(); } - - CZerocoinMint(const CZerocoinMint& other) { - denomination = other.GetDenomination(); - nHeight = other.GetHeight(); - value = other.GetValue(); - randomness = other.GetRandomness(); - serialNumber = other.GetSerialNumber(); - txid = other.GetTxHash(); - isUsed = other.IsUsed(); - version = other.GetVersion(); - privkey = other.privkey; - } - - std::string ToString() const; - - bool operator == (const CZerocoinMint& other) const - { - return this->GetValue() == other.GetValue(); - } - - // Copy another CZerocoinMint - inline CZerocoinMint& operator=(const CZerocoinMint& other) { - denomination = other.GetDenomination(); - nHeight = other.GetHeight(); - value = other.GetValue(); - randomness = other.GetRandomness(); - serialNumber = other.GetSerialNumber(); - txid = other.GetTxHash(); - isUsed = other.IsUsed(); - version = other.GetVersion(); - privkey = other.GetPrivKey(); - return *this; - } - - // why 6 below (SPOCK) - inline bool checkUnused(int denom, int Height) const { - if (IsUsed() == false && GetDenomination() == denomination && GetRandomness() != 0 && GetSerialNumber() != 0 && GetHeight() != -1 && GetHeight() != INT_MAX && GetHeight() >= 1 && (GetHeight() + 6 <= Height)) { - return true; - } else { - return false; - } - } - - ADD_SERIALIZE_METHODS; - - template - inline void SerializationOp(Stream& s, Operation ser_action) { - READWRITE(isUsed); - READWRITE(randomness); - READWRITE(serialNumber); - READWRITE(value); - READWRITE(denomination); - READWRITE(nHeight); - READWRITE(txid); - - bool fVersionedMint = true; - try { - READWRITE(version); - } catch (...) { - fVersionedMint = false; - } - - if (version > CURRENT_VERSION) { - version = 1; - fVersionedMint = false; - } - - if (fVersionedMint) - READWRITE(privkey); - }; -}; - -class CZerocoinSpend -{ -private: - CBigNum coinSerial; - uint256 hashTx; - CBigNum pubCoin; - libzerocoin::CoinDenomination denomination; - unsigned int nAccumulatorChecksum; - int nMintCount; //memory only - the amount of mints that belong to the accumulator this is spent from - -public: - CZerocoinSpend() - { - SetNull(); - } - - CZerocoinSpend(CBigNum coinSerial, uint256 hashTx, CBigNum pubCoin, libzerocoin::CoinDenomination denomination, unsigned int nAccumulatorChecksum) - { - this->coinSerial = coinSerial; - this->hashTx = hashTx; - this->pubCoin = pubCoin; - this->denomination = denomination; - this->nAccumulatorChecksum = nAccumulatorChecksum; - } - - void SetNull() - { - coinSerial = 0; - hashTx.SetNull(); - pubCoin = 0; - denomination = libzerocoin::ZQ_ERROR; - } - - CBigNum GetSerial() const { return coinSerial; } - uint256 GetTxHash() const { return hashTx; } - void SetTxHash(uint256 hash) { this->hashTx = hash; } - CBigNum GetPubCoin() const { return pubCoin; } - libzerocoin::CoinDenomination GetDenomination() const { return denomination; } - unsigned int GetAccumulatorChecksum() const { return this->nAccumulatorChecksum; } - uint256 GetHash() const; - void SetMintCount(int nMintsAdded) { this->nMintCount = nMintsAdded; } - int GetMintCount() const { return nMintCount; } - - ADD_SERIALIZE_METHODS; - - template - inline void SerializationOp(Stream& s, Operation ser_action) { - READWRITE(coinSerial); - READWRITE(hashTx); - READWRITE(pubCoin); - READWRITE(denomination); - READWRITE(nAccumulatorChecksum); - }; -}; - -class CZerocoinSpendReceipt -{ -private: - std::string strStatusMessage; - int nStatus; - int nNeededSpends; - std::vector vSpends; - -public: - void AddSpend(const CZerocoinSpend& spend); - std::vector GetSpends(); - void SetStatus(std::string strStatus, int nStatus, int nNeededSpends = 0); - std::string GetStatusMessage(); - int GetStatus(); - int GetNeededSpends(); -}; - -/** - * Wrapped serials attack inflation, only for mainnet. - * FUTURE: Move this to another file.. - * @param denom - * @return - */ -int GetWrapppedSerialInflation(libzerocoin::CoinDenomination denom); - -int64_t GetWrapppedSerialInflationAmount(); - #endif //PIVX_ZEROCOIN_H diff --git a/src/zpivchain.cpp b/src/zpivchain.cpp index e8e7a1222e60..56940b21a47f 100644 --- a/src/zpivchain.cpp +++ b/src/zpivchain.cpp @@ -12,214 +12,6 @@ // 6 comes from OPCODE (1) + vch.size() (1) + BIGNUM size (4) #define SCRIPT_OFFSET 6 -// For Script size (BIGNUM/Uint256 size) -#define BIGNUM_SIZE 4 - -bool BlockToMintValueVector(const CBlock& block, const libzerocoin::CoinDenomination denom, std::vector& vValues) -{ - for (const auto& txIn : block.vtx) { - const CTransaction& tx = *txIn; - if(!tx.HasZerocoinMintOutputs()) - continue; - - for (const CTxOut& txOut : tx.vout) { - if(!txOut.IsZerocoinMint()) - continue; - - CValidationState state; - libzerocoin::PublicCoin coin(Params().GetConsensus().Zerocoin_Params(false)); - if(!TxOutToPublicCoin(txOut, coin, state)) - return false; - - if (coin.getDenomination() != denom) - continue; - - vValues.push_back(coin.getValue()); - } - } - - return true; -} - -bool BlockToPubcoinList(const CBlock& block, std::list& listPubcoins, bool fFilterInvalid) -{ - for (const auto& txIn : block.vtx) { - const CTransaction& tx = *txIn; - if(!tx.HasZerocoinMintOutputs()) - continue; - - // Filter out mints that have used invalid outpoints - if (fFilterInvalid) { - bool fValid = true; - for (const CTxIn& in : tx.vin) { - if (!ValidOutPoint(in.prevout, INT_MAX)) { - fValid = false; - break; - } - } - if (!fValid) - continue; - } - - uint256 txHash = tx.GetHash(); - for (unsigned int i = 0; i < tx.vout.size(); i++) { - //Filter out mints that use invalid outpoints - edge case: invalid spend with minted change - if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX)) - break; - - const CTxOut txOut = tx.vout[i]; - if(!txOut.IsZerocoinMint()) - continue; - - CValidationState state; - libzerocoin::PublicCoin pubCoin(Params().GetConsensus().Zerocoin_Params(false)); - if(!TxOutToPublicCoin(txOut, pubCoin, state)) - return false; - - listPubcoins.emplace_back(pubCoin); - } - } - - return true; -} - -//return a list of zerocoin mints contained in a specific block -bool BlockToZerocoinMintList(const CBlock& block, std::list& vMints, bool fFilterInvalid) -{ - for (const auto& txIn : block.vtx) { - const CTransaction& tx = *txIn; - if(!tx.HasZerocoinMintOutputs()) - continue; - - // Filter out mints that have used invalid outpoints - if (fFilterInvalid) { - bool fValid = true; - for (const CTxIn& in : tx.vin) { - if (!ValidOutPoint(in.prevout, INT_MAX)) { - fValid = false; - break; - } - } - if (!fValid) - continue; - } - - uint256 txHash = tx.GetHash(); - for (unsigned int i = 0; i < tx.vout.size(); i++) { - //Filter out mints that use invalid outpoints - edge case: invalid spend with minted change - if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX)) - break; - - const CTxOut txOut = tx.vout[i]; - if(!txOut.IsZerocoinMint()) - continue; - - CValidationState state; - libzerocoin::PublicCoin pubCoin(Params().GetConsensus().Zerocoin_Params(false)); - if(!TxOutToPublicCoin(txOut, pubCoin, state)) - return false; - - //version should not actually matter here since it is just a reference to the pubcoin, not to the privcoin - uint8_t version = 1; - CZerocoinMint mint = CZerocoinMint(pubCoin.getDenomination(), pubCoin.getValue(), 0, 0, false, version, nullptr); - mint.SetTxHash(tx.GetHash()); - vMints.push_back(mint); - } - } - - return true; -} - -void FindMints(std::vector vMintsToFind, std::vector& vMintsToUpdate, std::vector& vMissingMints) -{ - // see which mints are in our public zerocoin database. The mint should be here if it exists, unless - // something went wrong - for (CMintMeta meta : vMintsToFind) { - uint256 txHash; - if (!zerocoinDB->ReadCoinMint(meta.hashPubcoin, txHash)) { - vMissingMints.push_back(meta); - continue; - } - - // make sure the txhash and block height meta data are correct for this mint - CTransaction tx; - uint256 hashBlock; - if (!GetTransaction(txHash, tx, hashBlock, true)) { - LogPrintf("%s : cannot find tx %s\n", __func__, txHash.GetHex()); - vMissingMints.push_back(meta); - continue; - } - - if (!mapBlockIndex.count(hashBlock)) { - LogPrintf("%s : cannot find block %s\n", __func__, hashBlock.GetHex()); - vMissingMints.push_back(meta); - continue; - } - - //see if this mint is spent - uint256 hashTxSpend; - bool fSpent = zerocoinDB->ReadCoinSpend(meta.hashSerial, hashTxSpend); - - //if marked as spent, check that it actually made it into the chain - CTransaction txSpend; - uint256 hashBlockSpend; - if (fSpent && !GetTransaction(hashTxSpend, txSpend, hashBlockSpend, true)) { - LogPrintf("%s : cannot find spend tx %s\n", __func__, hashTxSpend.GetHex()); - meta.isUsed = false; - vMintsToUpdate.push_back(meta); - continue; - } - - //The mint has been incorrectly labelled as spent in zerocoinDB and needs to be undone - int nHeightTx = 0; - uint256 hashSerial = meta.hashSerial; - uint256 txidSpend; - if (fSpent && !IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend)) { - LogPrintf("%s : cannot find block %s. Erasing coinspend from zerocoinDB.\n", __func__, hashBlockSpend.GetHex()); - meta.isUsed = false; - vMintsToUpdate.push_back(meta); - continue; - } - - // is the denomination correct? - for (auto& out : tx.vout) { - if (!out.IsZerocoinMint()) - continue; - libzerocoin::PublicCoin pubcoin(Params().GetConsensus().Zerocoin_Params(meta.nVersion < libzerocoin::PrivateCoin::PUBKEY_VERSION)); - CValidationState state; - TxOutToPublicCoin(out, pubcoin, state); - if (GetPubCoinHash(pubcoin.getValue()) == meta.hashPubcoin && pubcoin.getDenomination() != meta.denom) { - LogPrintf("%s: found mismatched denom pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex()); - meta.denom = pubcoin.getDenomination(); - vMintsToUpdate.emplace_back(meta); - } - } - - // if meta data is correct, then no need to update - if (meta.txid == txHash && meta.nHeight == mapBlockIndex[hashBlock]->nHeight && meta.isUsed == fSpent) - continue; - - //mark this mint for update - meta.txid = txHash; - meta.nHeight = mapBlockIndex[hashBlock]->nHeight; - meta.isUsed = fSpent; - LogPrintf("%s: found updates for pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex()); - - vMintsToUpdate.push_back(meta); - } -} - -bool GetZerocoinMint(const CBigNum& bnPubcoin, uint256& txHash) -{ - txHash = UINT256_ZERO; - return zerocoinDB->ReadCoinMint(bnPubcoin, txHash); -} - -bool IsPubcoinInBlockchain(const uint256& hashPubcoin, uint256& txid) -{ - txid.SetNull(); - return zerocoinDB->ReadCoinMint(hashPubcoin, txid); -} bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx) { @@ -231,27 +23,6 @@ bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx) return IsTransactionInChain(txHash, nHeightTx); } -bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend) -{ - CTransaction tx; - return IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend, tx); -} - -bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend, CTransaction& tx) -{ - txidSpend.SetNull(); - // if not in zerocoinDB then its not in the blockchain - if (!zerocoinDB->ReadCoinSpend(hashSerial, txidSpend)) - return false; - - return IsTransactionInChain(txidSpend, nHeightTx, tx); -} - -bool RemoveSerialFromDB(const CBigNum& bnSerial) -{ - return zerocoinDB->EraseCoinSpend(bnSerial); -} - libzerocoin::CoinSpend TxInToZerocoinSpend(const CTxIn& txin) { CDataStream serializedCoinSpend = ZPIVModule::ScriptSigToSerializedSpend(txin.scriptSig); @@ -277,30 +48,4 @@ bool TxOutToPublicCoin(const CTxOut& txout, libzerocoin::PublicCoin& pubCoin, CV return true; } -//return a list of zerocoin spends contained in a specific block, list may have many denominations -std::list ZerocoinSpendListFromBlock(const CBlock& block, bool fFilterInvalid) -{ - std::list vSpends; - for (const auto& txIn : block.vtx) { - const CTransaction& tx = *txIn; - if (!tx.HasZerocoinSpendInputs()) - continue; - - for (const CTxIn& txin : tx.vin) { - bool isPublicSpend = txin.IsZerocoinPublicSpend(); - if (!txin.IsZerocoinSpend() && !isPublicSpend) - continue; - - if (fFilterInvalid && !isPublicSpend) { - libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin); - if (invalid_out::ContainsSerial(spend.getCoinSerialNumber())) - continue; - } - - libzerocoin::CoinDenomination c = libzerocoin::IntToZerocoinDenomination(txin.nSequence); - vSpends.push_back(c); - } - } - return vSpends; -} diff --git a/src/zpivchain.h b/src/zpivchain.h index d9c9ff634a1a..37a3ed9612b9 100644 --- a/src/zpivchain.h +++ b/src/zpivchain.h @@ -15,26 +15,14 @@ class CBlock; class CBlockIndex; class CBigNum; -struct CMintMeta; class CTransaction; class CTxIn; class CTxOut; class CValidationState; -class CZerocoinMint; class uint256; -bool BlockToMintValueVector(const CBlock& block, const libzerocoin::CoinDenomination denom, std::vector& vValues); -bool BlockToPubcoinList(const CBlock& block, std::list& listPubcoins, bool fFilterInvalid); -bool BlockToZerocoinMintList(const CBlock& block, std::list& vMints, bool fFilterInvalid); -void FindMints(std::vector vMintsToFind, std::vector& vMintsToUpdate, std::vector& vMissingMints); -bool GetZerocoinMint(const CBigNum& bnPubcoin, uint256& txHash); -bool IsPubcoinInBlockchain(const uint256& hashPubcoin, uint256& txid); bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx); -bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend); -bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend, CTransaction& tx); -bool RemoveSerialFromDB(const CBigNum& bnSerial); libzerocoin::CoinSpend TxInToZerocoinSpend(const CTxIn& txin); bool TxOutToPublicCoin(const CTxOut& txout, libzerocoin::PublicCoin& pubCoin, CValidationState& state); -std::list ZerocoinSpendListFromBlock(const CBlock& block, bool fFilterInvalid); #endif //PIVX_ZPIVCHAIN_H