Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constrain constant values to a single location in code #6349

Closed
wants to merge 6 commits into from
9 changes: 5 additions & 4 deletions src/bitcoin-cli.cpp
Expand Up @@ -22,20 +22,21 @@

using namespace std;

static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;

std::string HelpMessageCli()
{
string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "bitcoin.conf"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("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."));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), "127.0.0.1"));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), 8332, 18332));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
Expand Down Expand Up @@ -141,7 +142,7 @@ static void http_request_done(struct evhttp_request *req, void *ctx)

UniValue CallRPC(const string& strMethod, const UniValue& params)
{
std::string host = GetArg("-rpcconnect", "127.0.0.1");
std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT);
int port = GetArg("-rpcport", BaseParams().RPCPort());

// Create event base
Expand Down
29 changes: 15 additions & 14 deletions src/chainparamsbase.cpp
Expand Up @@ -71,24 +71,25 @@ const CBaseChainParams& BaseParams()
return *pCurrentBaseParams;
}

void SelectBaseParams(CBaseChainParams::Network network)
{
CBaseChainParams &BaseParams(CBaseChainParams::Network network) {
switch (network) {
case CBaseChainParams::MAIN:
pCurrentBaseParams = &mainParams;
break;
case CBaseChainParams::TESTNET:
pCurrentBaseParams = &testNetParams;
break;
case CBaseChainParams::REGTEST:
pCurrentBaseParams = &regTestParams;
break;
default:
assert(false && "Unimplemented network");
return;
case CBaseChainParams::MAIN:
return mainParams;
case CBaseChainParams::TESTNET:
return testNetParams;
case CBaseChainParams::REGTEST:
return regTestParams;
default:
assert(false && "Unimplemented network");
return mainParams;
}
}

void SelectBaseParams(CBaseChainParams::Network network)
{
pCurrentBaseParams = &BaseParams(network);
}

CBaseChainParams::Network NetworkIdFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
Expand Down
2 changes: 2 additions & 0 deletions src/chainparamsbase.h
Expand Up @@ -39,6 +39,8 @@ class CBaseChainParams
*/
const CBaseChainParams& BaseParams();

CBaseChainParams &BaseParams(CBaseChainParams::Network);

/** Sets the params returned by Params() to those for the given network. */
void SelectBaseParams(CBaseChainParams::Network network);

Expand Down
136 changes: 74 additions & 62 deletions src/init.cpp

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions src/main.cpp
Expand Up @@ -889,7 +889,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
strprintf("%d < %d", nFees, txMinFee));

// Require that free transactions have sufficient priority to be mined in the next block.
if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
}

Expand All @@ -910,7 +910,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
if (dFreeCount >= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000)
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
Expand Down Expand Up @@ -1207,7 +1207,7 @@ void Misbehaving(NodeId pnode, int howmuch)
return;

state->nMisbehavior += howmuch;
int banscore = GetArg("-banscore", 100);
int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
{
LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
Expand Down Expand Up @@ -3316,7 +3316,7 @@ bool InitBlockIndex() {
return true;

// Use the provided setting for -txindex in the new database
fTxIndex = GetBoolArg("-txindex", false);
fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
pblocktree->WriteFlag("txindex", fTxIndex);
LogPrintf("Initializing databases...\n");

Expand Down Expand Up @@ -3651,7 +3651,7 @@ std::string GetWarnings(const std::string& strFor)
if (!CLIENT_VERSION_IS_RELEASE)
strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");

if (GetBoolArg("-testsafemode", false))
if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE))
strStatusBar = strRPC = "testsafemode enabled";

// Misc warnings like out of disk space and clock is wrong
Expand Down
10 changes: 10 additions & 0 deletions src/main.h
Expand Up @@ -79,6 +79,13 @@ static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
/** Maximum length of reject messages. */
static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
static const unsigned int DEFAULT_LIMITFREERELAY = 15;
static const bool DEFAULT_RELAYPRIORITY = true;

static const bool DEFAULT_TXINDEX = false;
static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;

static const bool DEFAULT_TESTSAFEMODE = false;

struct BlockHasher
{
Expand Down Expand Up @@ -123,6 +130,9 @@ extern uint64_t nPruneTarget;
/** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
static const unsigned int MIN_BLOCKS_TO_KEEP = 288;

static const signed int DEFAULT_CHECKBLOCKS = MIN_BLOCKS_TO_KEEP;
static const unsigned int DEFAULT_CHECKLEVEL = 3;

// Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
// At 1MB per block, 288 blocks = 288MB.
// Add 15% for Undo data = 331MB
Expand Down
2 changes: 1 addition & 1 deletion src/miner.cpp
Expand Up @@ -153,7 +153,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
bool fPrintPriority = GetBoolArg("-printpriority", false);
bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);

// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
Expand Down
5 changes: 5 additions & 0 deletions src/miner.h
Expand Up @@ -17,6 +17,11 @@ class CScript;
class CWallet;
namespace Consensus { struct Params; };

static const bool DEFAULT_GENERATE = false;
static const int DEFAULT_GENERATE_THREADS = 1;

static const bool DEFAULT_PRINTPRIORITY = false;

struct CBlockTemplate
{
CBlock block;
Expand Down
9 changes: 4 additions & 5 deletions src/net.cpp
Expand Up @@ -506,12 +506,11 @@ void CNode::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t banti
banEntry.banReason = banReason;
if (bantimeoffset <= 0)
{
bantimeoffset = GetArg("-bantime", 60*60*24); // Default 24-hour ban
bantimeoffset = GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
sinceUnixEpoch = false;
}
banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;


LOCK(cs_setBanned);
if (setBanned[subNet].nBanUntil < banEntry.nBanUntil)
setBanned[subNet] = banEntry;
Expand Down Expand Up @@ -1389,7 +1388,7 @@ void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
(!GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
MilliSleep(11 * 1000);

LOCK(cs_vNodes);
Expand Down Expand Up @@ -2221,8 +2220,8 @@ bool CAddrDB::Read(CAddrMan& addr)
return true;
}

unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); }
unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); }

CNode::CNode(SOCKET hSocketIn, const CAddress& addrIn, const std::string& addrNameIn, bool fInboundIn) :
ssSend(SER_NETWORK, INIT_PROTO_VERSION),
Expand Down
7 changes: 7 additions & 0 deletions src/net.h
Expand Up @@ -61,6 +61,13 @@ static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
/** The maximum number of peer connections to maintain. */
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;

static const bool DEFAULT_FORCEDNSSEED = false;
static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;

// NOTE: When adjusting this, update rpcnet:setban's help ("24h")
static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban

unsigned int ReceiveFloodSize();
unsigned int SendBufferSize();

Expand Down
2 changes: 1 addition & 1 deletion src/netbase.cpp
Expand Up @@ -40,7 +40,7 @@ static proxyType proxyInfo[NET_MAX];
static proxyType nameProxy;
static CCriticalSection cs_proxyInfos;
int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
bool fNameLookup = false;
bool fNameLookup = true;

static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };

Expand Down
2 changes: 1 addition & 1 deletion src/policy/policy.cpp
Expand Up @@ -50,7 +50,7 @@ bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
if (m < 1 || m > n)
return false;
} else if (whichType == TX_NULL_DATA &&
(!GetBoolArg("-datacarrier", true) || scriptPubKey.size() > nMaxDatacarrierBytes))
(!fAcceptDatacarrier || scriptPubKey.size() > nMaxDatacarrierBytes))
return false;

return whichType != TX_NONSTANDARD;
Expand Down
22 changes: 13 additions & 9 deletions src/qt/bitcoin.cpp
Expand Up @@ -309,14 +309,8 @@ BitcoinApplication::BitcoinApplication(int &argc, char **argv):
// UI per-platform customization
// This must be done inside the BitcoinApplication constructor, or after it, because
// PlatformStyle::instantiate requires a QApplication
#if defined(Q_OS_MAC)
std::string platformName = "macosx";
#elif defined(Q_OS_WIN)
std::string platformName = "windows";
#else
std::string platformName = "other";
#endif
platformName = GetArg("-uiplatform", platformName);
std::string platformName;
platformName = GetArg("-uiplatform", uiInterface.DefaultUIPlatform);
platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName));
if (!platformStyle) // Fall back to "other" if specified name not found
platformStyle = PlatformStyle::instantiate("other");
Expand Down Expand Up @@ -509,6 +503,16 @@ int main(int argc, char *argv[])
{
SetupEnvironment();

uiInterface.DefaultUIPlatform =
#if defined(Q_OS_MAC)
"macosx"
#elif defined(Q_OS_WIN)
"windows"
#else
"other"
#endif
;

/// 1. Parse command-line options. These take precedence over anything else.
// Command-line options take precedence:
ParseParameters(argc, argv);
Expand Down Expand Up @@ -648,7 +652,7 @@ int main(int argc, char *argv[])
// Subscribe to global signals from core
uiInterface.InitMessage.connect(InitMessage);

if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false))
if (GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !GetBoolArg("-min", false))
app.createSplashScreen(networkStyle.data());

try
Expand Down
2 changes: 1 addition & 1 deletion src/qt/intro.cpp
Expand Up @@ -162,7 +162,7 @@ void Intro::pickDataDirectory()
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();

if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false))
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
Expand Down
2 changes: 1 addition & 1 deletion src/qt/paymentrequestplus.cpp
Expand Up @@ -145,7 +145,7 @@ bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) c
int error = X509_STORE_CTX_get_error(store_ctx);
// For testing payment requests, we allow self signed root certs!
// This option is just shown in the UI options, if -help-debug is enabled.
if (!(error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && GetBoolArg("-allowselfsignedrootcertificates", false))) {
if (!(error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && GetBoolArg("-allowselfsignedrootcertificates", DEFAULT_SELFSIGNED_ROOTCERTS))) {
throw SSLVerifyError(X509_verify_cert_error_string(error));
} else {
qDebug() << "PaymentRequestPlus::getMerchant: Allowing self signed root certificate, because -allowselfsignedrootcertificates is true.";
Expand Down
8 changes: 4 additions & 4 deletions src/rpcblockchain.cpp
Expand Up @@ -539,13 +539,15 @@ UniValue gettxout(const UniValue& params, bool fHelp)

UniValue verifychain(const UniValue& params, bool fHelp)
{
int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL);
int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
if (fHelp || params.size() > 2)
throw runtime_error(
"verifychain ( checklevel numblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n"
"2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
"1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
"2. numblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n"
Expand All @@ -555,8 +557,6 @@ UniValue verifychain(const UniValue& params, bool fHelp)

LOCK(cs_main);

int nCheckLevel = GetArg("-checklevel", 3);
int nCheckDepth = GetArg("-checkblocks", 288);
if (params.size() > 0)
nCheckLevel = params[0].get_int();
if (params.size() > 1)
Expand Down
8 changes: 4 additions & 4 deletions src/rpcmining.cpp
Expand Up @@ -99,7 +99,7 @@ UniValue getgenerate(const UniValue& params, bool fHelp)
throw runtime_error(
"getgenerate\n"
"\nReturn if the server is set to generate coins or not. The default is false.\n"
"It is set with the command line argument -gen (or bitcoin.conf setting gen)\n"
"It is set with the command line argument -gen (or " + std::string(BITCOIN_CONF_FILENAME) + " setting gen)\n"
"It can also be set with the setgenerate call.\n"
"\nResult\n"
"true|false (boolean) If the server is set to generate coins or not\n"
Expand All @@ -109,7 +109,7 @@ UniValue getgenerate(const UniValue& params, bool fHelp)
);

LOCK(cs_main);
return GetBoolArg("-gen", false);
return GetBoolArg("-gen", DEFAULT_GENERATE);
}

UniValue generate(const UniValue& params, bool fHelp)
Expand Down Expand Up @@ -211,7 +211,7 @@ UniValue setgenerate(const UniValue& params, bool fHelp)
if (params.size() > 0)
fGenerate = params[0].get_bool();

int nGenProcLimit = -1;
int nGenProcLimit = GetArg("-genproclimit", DEFAULT_GENERATE_THREADS);
if (params.size() > 1)
{
nGenProcLimit = params[1].get_int();
Expand Down Expand Up @@ -259,7 +259,7 @@ UniValue getmininginfo(const UniValue& params, bool fHelp)
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", DEFAULT_GENERATE_THREADS)));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
Expand Down
2 changes: 1 addition & 1 deletion src/script/sigcache.cpp
Expand Up @@ -47,7 +47,7 @@ class CSignatureCache
// (~200 bytes per cache entry times 50,000 entries)
// Since there are a maximum of 20,000 signature operations per block
// 50,000 is a reasonable default.
int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
int64_t nMaxCacheSize = GetArg("-maxsigcachesize", DEFAULT_MAXSIGCACHESIZE);
if (nMaxCacheSize <= 0) return;

boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
Expand Down
2 changes: 2 additions & 0 deletions src/script/sigcache.h
Expand Up @@ -10,6 +10,8 @@

#include <vector>

static const int64_t DEFAULT_MAXSIGCACHESIZE = 50000;

class CPubKey;

class CachingTransactionSignatureChecker : public TransactionSignatureChecker
Expand Down
1 change: 1 addition & 0 deletions src/script/standard.cpp
Expand Up @@ -16,6 +16,7 @@ using namespace std;

typedef vector<unsigned char> valtype;

bool fAcceptDatacarrier = true;
unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY;

CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {}
Expand Down
1 change: 1 addition & 0 deletions src/script/standard.h
Expand Up @@ -26,6 +26,7 @@ class CScriptID : public uint160
};

static const unsigned int MAX_OP_RETURN_RELAY = 83; //! bytes (+1 for OP_RETURN, +2 for the pushdata opcodes)
extern bool fAcceptDatacarrier;
extern unsigned nMaxDatacarrierBytes;

/**
Expand Down