Browse Source

Merge #9243: Clean up mapArgs and mapMultiArgs Usage

c2f61be Add a ForceSetArg method for testing (Matt Corallo)
4e04814 Lock mapArgs/mapMultiArgs access in util (Matt Corallo)
4cd373a Un-expose mapArgs from utils.h (Matt Corallo)
71fde55 Get rid of mapArgs direct access in ZMQ construction (Matt Corallo)
0cf86a6 Introduce (and use) an IsArgSet accessor method (Matt Corallo)
2b5f085 Fix non-const mapMultiArgs[] access after init. (Matt Corallo)
c8042a4 Remove arguments to ParseConfigFile (Matt Corallo)
0.14
Pieter Wuille 8 years ago
parent
commit
7aa700424c
No known key found for this signature in database
GPG Key ID: DBA1A67379A1A931
  1. 12
      src/bitcoin-cli.cpp
  2. 2
      src/bitcoin-tx.cpp
  3. 8
      src/bitcoind.cpp
  4. 6
      src/httprpc.cpp
  5. 10
      src/httpserver.cpp
  6. 86
      src/init.cpp
  7. 4
      src/miner.cpp
  8. 9
      src/net.cpp
  9. 2
      src/net_processing.cpp
  10. 10
      src/qt/bitcoin.cpp
  11. 4
      src/qt/optionsmodel.cpp
  12. 2
      src/qt/test/rpcnestedtests.cpp
  13. 5
      src/test/DoS_tests.cpp
  14. 2
      src/test/test_bitcoin.cpp
  15. 8
      src/test/util_tests.cpp
  16. 71
      src/util.cpp
  17. 16
      src/util.h
  18. 30
      src/wallet/wallet.cpp
  19. 8
      src/zmq/zmqnotificationinterface.cpp
  20. 2
      src/zmq/zmqnotificationinterface.h

12
src/bitcoin-cli.cpp

@ -76,9 +76,9 @@ static int AppInitRPC(int argc, char* argv[])
// Parameters // Parameters
// //
ParseParameters(argc, argv); ParseParameters(argc, argv);
if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) { if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n"; std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!mapArgs.count("-version")) { if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" + strUsage += "\n" + _("Usage:") + "\n" +
" bitcoin-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" + " bitcoin-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" +
" bitcoin-cli [options] help " + _("List commands") + "\n" + " bitcoin-cli [options] help " + _("List commands") + "\n" +
@ -95,11 +95,11 @@ static int AppInitRPC(int argc, char* argv[])
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
if (!boost::filesystem::is_directory(GetDataDir(false))) { if (!boost::filesystem::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return EXIT_FAILURE; return EXIT_FAILURE;
} }
try { try {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME), mapArgs, mapMultiArgs); ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) { } catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what()); fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE; return EXIT_FAILURE;
@ -211,7 +211,7 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
// Get credentials // Get credentials
std::string strRPCUserColonPass; std::string strRPCUserColonPass;
if (mapArgs["-rpcpassword"] == "") { if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided // Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) { if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf( throw std::runtime_error(strprintf(
@ -220,7 +220,7 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)
} }
} else { } else {
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
} }
struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req); struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req);

2
src/bitcoin-tx.cpp

@ -51,7 +51,7 @@ static int AppInitRawTx(int argc, char* argv[])
fCreateBlank = GetBoolArg("-create", false); fCreateBlank = GetBoolArg("-create", false);
if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help")) if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help"))
{ {
// First part of help message is specific to this utility // First part of help message is specific to this utility
std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" + std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +

8
src/bitcoind.cpp

@ -75,11 +75,11 @@ bool AppInit(int argc, char* argv[])
ParseParameters(argc, argv); ParseParameters(argc, argv);
// Process help and version before taking care about datadir // Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
{ {
std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version")) if (IsArgSet("-version"))
{ {
strUsage += FormatParagraph(LicenseInfo()); strUsage += FormatParagraph(LicenseInfo());
} }
@ -99,12 +99,12 @@ bool AppInit(int argc, char* argv[])
{ {
if (!boost::filesystem::is_directory(GetDataDir(false))) if (!boost::filesystem::is_directory(GetDataDir(false)))
{ {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return false; return false;
} }
try try
{ {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME), mapArgs, mapMultiArgs); ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) { } catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what()); fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false; return false;

6
src/httprpc.cpp

@ -95,7 +95,7 @@ static bool multiUserAuthorized(std::string strUserPass)
if (mapMultiArgs.count("-rpcauth") > 0) { if (mapMultiArgs.count("-rpcauth") > 0) {
//Search for multi-user login/pass "rpcauth" from config //Search for multi-user login/pass "rpcauth" from config
BOOST_FOREACH(std::string strRPCAuth, mapMultiArgs["-rpcauth"]) BOOST_FOREACH(std::string strRPCAuth, mapMultiArgs.at("-rpcauth"))
{ {
std::vector<std::string> vFields; std::vector<std::string> vFields;
boost::split(vFields, strRPCAuth, boost::is_any_of(":$")); boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
@ -215,7 +215,7 @@ static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
static bool InitRPCAuthentication() static bool InitRPCAuthentication()
{ {
if (mapArgs["-rpcpassword"] == "") if (GetArg("-rpcpassword", "") == "")
{ {
LogPrintf("No rpcpassword set - using random cookie authentication\n"); LogPrintf("No rpcpassword set - using random cookie authentication\n");
if (!GenerateAuthCookie(&strRPCUserColonPass)) { if (!GenerateAuthCookie(&strRPCUserColonPass)) {
@ -226,7 +226,7 @@ static bool InitRPCAuthentication()
} }
} else { } else {
LogPrintf("Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share/rpcuser for rpcauth auth generation.\n"); LogPrintf("Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share/rpcuser for rpcauth auth generation.\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
} }
return true; return true;
} }

10
src/httpserver.cpp

@ -204,7 +204,7 @@ static bool InitHTTPAllowList()
rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
if (mapMultiArgs.count("-rpcallowip")) { if (mapMultiArgs.count("-rpcallowip")) {
const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"]; const std::vector<std::string>& vAllow = mapMultiArgs.at("-rpcallowip");
for (std::string strAllow : vAllow) { for (std::string strAllow : vAllow) {
CSubNet subnet; CSubNet subnet;
LookupSubNet(strAllow.c_str(), subnet); LookupSubNet(strAllow.c_str(), subnet);
@ -322,14 +322,14 @@ static bool HTTPBindAddresses(struct evhttp* http)
std::vector<std::pair<std::string, uint16_t> > endpoints; std::vector<std::pair<std::string, uint16_t> > endpoints;
// Determine what addresses to bind to // Determine what addresses to bind to
if (!mapArgs.count("-rpcallowip")) { // Default to loopback if not allowing external IPs if (!IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
endpoints.push_back(std::make_pair("::1", defaultPort)); endpoints.push_back(std::make_pair("::1", defaultPort));
endpoints.push_back(std::make_pair("127.0.0.1", defaultPort)); endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
if (mapArgs.count("-rpcbind")) { if (IsArgSet("-rpcbind")) {
LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
} }
} else if (mapArgs.count("-rpcbind")) { // Specific bind address } else if (mapMultiArgs.count("-rpcbind")) { // Specific bind address
const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"]; const std::vector<std::string>& vbind = mapMultiArgs.at("-rpcbind");
for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) { for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
int port = defaultPort; int port = defaultPort;
std::string host; std::string host;

86
src/init.cpp

@ -708,16 +708,16 @@ void InitParameterInteraction()
{ {
// when specifying an explicit binding address, you want to listen on it // when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified // even when -connect or -proxy is specified
if (mapArgs.count("-bind")) { if (IsArgSet("-bind")) {
if (SoftSetBoolArg("-listen", true)) if (SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__); LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
} }
if (mapArgs.count("-whitebind")) { if (IsArgSet("-whitebind")) {
if (SoftSetBoolArg("-listen", true)) if (SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
} }
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default // when only connecting to trusted nodes, do not seed via DNS, or listen by default
if (SoftSetBoolArg("-dnsseed", false)) if (SoftSetBoolArg("-dnsseed", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__); LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
@ -725,7 +725,7 @@ void InitParameterInteraction()
LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__); LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
} }
if (mapArgs.count("-proxy")) { if (IsArgSet("-proxy")) {
// to protect privacy, do not listen by default if a default proxy server is specified // to protect privacy, do not listen by default if a default proxy server is specified
if (SoftSetBoolArg("-listen", false)) if (SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
@ -748,7 +748,7 @@ void InitParameterInteraction()
LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__); LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
} }
if (mapArgs.count("-externalip")) { if (IsArgSet("-externalip")) {
// if an explicit public IP is specified, do not try to find others // if an explicit public IP is specified, do not try to find others
if (SoftSetBoolArg("-discover", false)) if (SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
@ -880,17 +880,19 @@ bool AppInitParameterInteraction()
// ********************************************************* Step 3: parameter-to-internal-flags // ********************************************************* Step 3: parameter-to-internal-flags
fDebug = !mapMultiArgs["-debug"].empty(); fDebug = mapMultiArgs.count("-debug");
// Special-case: if -debug=0/-nodebug is set, turn off debugging messages // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
const vector<string>& categories = mapMultiArgs["-debug"]; if (fDebug) {
if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) const vector<string>& categories = mapMultiArgs.at("-debug");
fDebug = false; if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
fDebug = false;
}
// Check for -debugnet // Check for -debugnet
if (GetBoolArg("-debugnet", false)) if (GetBoolArg("-debugnet", false))
InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net.")); InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
// Check for -socks - as this is a privacy risk to continue, exit here // Check for -socks - as this is a privacy risk to continue, exit here
if (mapArgs.count("-socks")) if (IsArgSet("-socks"))
return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
// Check for -tor - as this is a privacy risk to continue, exit here // Check for -tor - as this is a privacy risk to continue, exit here
if (GetBoolArg("-tor", false)) if (GetBoolArg("-tor", false))
@ -902,7 +904,7 @@ bool AppInitParameterInteraction()
if (GetBoolArg("-whitelistalwaysrelay", false)) if (GetBoolArg("-whitelistalwaysrelay", false))
InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.")); InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
if (mapArgs.count("-blockminsize")) if (IsArgSet("-blockminsize"))
InitWarning("Unsupported argument -blockminsize ignored."); InitWarning("Unsupported argument -blockminsize ignored.");
// Checkmempool and checkblockindex default to true in regtest mode // Checkmempool and checkblockindex default to true in regtest mode
@ -957,11 +959,11 @@ bool AppInitParameterInteraction()
// a transaction spammer can cheaply fill blocks using // a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real // 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction. // cost to you of processing a transaction.
if (mapArgs.count("-minrelaytxfee")) if (IsArgSet("-minrelaytxfee"))
{ {
CAmount n = 0; CAmount n = 0;
if (!ParseMoney(mapArgs["-minrelaytxfee"], n) || 0 == n) if (!ParseMoney(GetArg("-minrelaytxfee", ""), n) || 0 == n)
return InitError(AmountErrMsg("minrelaytxfee", mapArgs["-minrelaytxfee"])); return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
// High fee check is done afterward in CWallet::ParameterInteraction() // High fee check is done afterward in CWallet::ParameterInteraction()
::minRelayTxFee = CFeeRate(n); ::minRelayTxFee = CFeeRate(n);
} }
@ -995,7 +997,7 @@ bool AppInitParameterInteraction()
nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE); nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT); fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
if ((!fEnableReplacement) && mapArgs.count("-mempoolreplacement")) { if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
// Minimal effort at forwards compatibility // Minimal effort at forwards compatibility
std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
std::vector<std::string> vstrReplacementModes; std::vector<std::string> vstrReplacementModes;
@ -1003,12 +1005,12 @@ bool AppInitParameterInteraction()
fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end()); fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
} }
if (!mapMultiArgs["-bip9params"].empty()) { if (mapMultiArgs.count("-bip9params")) {
// Allow overriding BIP9 parameters for testing // Allow overriding BIP9 parameters for testing
if (!chainparams.MineBlocksOnDemand()) { if (!chainparams.MineBlocksOnDemand()) {
return InitError("BIP9 parameters may only be overridden on regtest."); return InitError("BIP9 parameters may only be overridden on regtest.");
} }
const vector<string>& deployments = mapMultiArgs["-bip9params"]; const vector<string>& deployments = mapMultiArgs.at("-bip9params");
for (auto i : deployments) { for (auto i : deployments) {
std::vector<std::string> vDeploymentParams; std::vector<std::string> vDeploymentParams;
boost::split(vDeploymentParams, i, boost::is_any_of(":")); boost::split(vDeploymentParams, i, boost::is_any_of(":"));
@ -1154,11 +1156,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// sanitize comments per BIP-0014, format user agent and check total size // sanitize comments per BIP-0014, format user agent and check total size
std::vector<string> uacomments; std::vector<string> uacomments;
BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"]) if (mapMultiArgs.count("-uacomment")) {
{ BOOST_FOREACH(string cmt, mapMultiArgs.at("-uacomment"))
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)); return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
uacomments.push_back(cmt);
}
} }
strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments); strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
@ -1166,9 +1170,9 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
strSubVersion.size(), MAX_SUBVERSION_LENGTH)); strSubVersion.size(), MAX_SUBVERSION_LENGTH));
} }
if (mapArgs.count("-onlynet")) { if (mapMultiArgs.count("-onlynet")) {
std::set<enum Network> nets; std::set<enum Network> nets;
BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) { BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) {
enum Network net = ParseNetwork(snet); enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE) if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
@ -1181,8 +1185,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
} }
} }
if (mapArgs.count("-whitelist")) { if (mapMultiArgs.count("-whitelist")) {
BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) { BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) {
CSubNet subnet; CSubNet subnet;
LookupSubNet(net.c_str(), subnet); LookupSubNet(net.c_str(), subnet);
if (!subnet.IsValid()) if (!subnet.IsValid())
@ -1234,14 +1238,16 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
if (fListen) { if (fListen) {
bool fBound = false; bool fBound = false;
if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { if (mapMultiArgs.count("-bind")) {
BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) { BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) {
CService addrBind; CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(ResolveErrMsg("bind", strBind)); return InitError(ResolveErrMsg("bind", strBind));
fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
} }
BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) { }
if (mapMultiArgs.count("-whitebind")) {
BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) {
CService addrBind; CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, 0, false)) if (!Lookup(strBind.c_str(), addrBind, 0, false))
return InitError(ResolveErrMsg("whitebind", strBind)); return InitError(ResolveErrMsg("whitebind", strBind));
@ -1250,7 +1256,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST)); fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
} }
} }
else { if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) {
struct in_addr inaddr_any; struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY; inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE); fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
@ -1260,8 +1266,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
} }
if (mapArgs.count("-externalip")) { if (mapMultiArgs.count("-externalip")) {
BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) { BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) {
CService addrLocal; CService addrLocal;
if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid()) if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
AddLocal(addrLocal, LOCAL_MANUAL); AddLocal(addrLocal, LOCAL_MANUAL);
@ -1270,11 +1276,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
} }
} }
BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"]) if (mapMultiArgs.count("-seednode")) {
connman.AddOneShot(strDest); BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode"))
connman.AddOneShot(strDest);
}
#if ENABLE_ZMQ #if ENABLE_ZMQ
pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs); pzmqNotificationInterface = CZMQNotificationInterface::Create();
if (pzmqNotificationInterface) { if (pzmqNotificationInterface) {
RegisterValidationInterface(pzmqNotificationInterface); RegisterValidationInterface(pzmqNotificationInterface);
@ -1283,7 +1291,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME; uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
if (mapArgs.count("-maxuploadtarget")) { if (IsArgSet("-maxuploadtarget")) {
nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024; nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
} }
@ -1515,13 +1523,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
fHaveGenesis = true; fHaveGenesis = true;
} }
if (mapArgs.count("-blocknotify")) if (IsArgSet("-blocknotify"))
uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
std::vector<boost::filesystem::path> vImportFiles; std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock")) if (mapMultiArgs.count("-loadblock"))
{ {
BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"]) BOOST_FOREACH(const std::string& strFile, mapMultiArgs.at("-loadblock"))
vImportFiles.push_back(strFile); vImportFiles.push_back(strFile);
} }

4
src/miner.cpp

@ -84,12 +84,12 @@ BlockAssembler::BlockAssembler(const CChainParams& _chainparams)
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT; nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE; nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
bool fWeightSet = false; bool fWeightSet = false;
if (mapArgs.count("-blockmaxweight")) { if (IsArgSet("-blockmaxweight")) {
nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT); nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE; nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
fWeightSet = true; fWeightSet = true;
} }
if (mapArgs.count("-blockmaxsize")) { if (IsArgSet("-blockmaxsize")) {
nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
if (!fWeightSet) { if (!fWeightSet) {
nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR; nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR;

9
src/net.cpp

@ -1569,12 +1569,12 @@ void CConnman::ProcessOneShot()
void CConnman::ThreadOpenConnections() void CConnman::ThreadOpenConnections()
{ {
// Connect to specific addresses // Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0)
{ {
for (int64_t nLoop = 0;; nLoop++) for (int64_t nLoop = 0;; nLoop++)
{ {
ProcessOneShot(); ProcessOneShot();
BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-connect"]) BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-connect"))
{ {
CAddress addr(CService(), NODE_NONE); CAddress addr(CService(), NODE_NONE);
OpenNetworkConnection(addr, false, NULL, strAddr.c_str()); OpenNetworkConnection(addr, false, NULL, strAddr.c_str());
@ -1765,7 +1765,8 @@ void CConnman::ThreadOpenAddedConnections()
{ {
{ {
LOCK(cs_vAddedNodes); LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"]; if (mapMultiArgs.count("-addnode"))
vAddedNodes = mapMultiArgs.at("-addnode");
} }
for (unsigned int i = 0; true; i++) for (unsigned int i = 0; true; i++)
@ -2157,7 +2158,7 @@ bool CConnman::Start(boost::thread_group& threadGroup, CScheduler& scheduler, st
threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "addcon", boost::function<void()>(boost::bind(&CConnman::ThreadOpenAddedConnections, this)))); threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "addcon", boost::function<void()>(boost::bind(&CConnman::ThreadOpenAddedConnections, this))));
// Initiate outbound connections unless connect=0 // Initiate outbound connections unless connect=0
if (!mapArgs.count("-connect") || mapMultiArgs["-connect"].size() != 1 || mapMultiArgs["-connect"][0] != "0") if (!mapMultiArgs.count("-connect") || mapMultiArgs.at("-connect").size() != 1 || mapMultiArgs.at("-connect")[0] != "0")
threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "opencon", boost::function<void()>(boost::bind(&CConnman::ThreadOpenConnections, this)))); threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "opencon", boost::function<void()>(boost::bind(&CConnman::ThreadOpenConnections, this))));
// Process messages // Process messages

2
src/net_processing.cpp

@ -1060,7 +1060,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv,
unsigned int nMaxSendBufferSize = connman.GetSendBufferSize(); unsigned int nMaxSendBufferSize = connman.GetSendBufferSize();
LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id); LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
{ {
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n"); LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true; return true;

10
src/qt/bitcoin.cpp

@ -587,9 +587,9 @@ int main(int argc, char *argv[])
// Show help message immediately after parsing command-line options (for "-lang") and setting locale, // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen. // but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version")) if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
{ {
HelpMessageDialog help(NULL, mapArgs.count("-version")); HelpMessageDialog help(NULL, IsArgSet("-version"));
help.showOrPrint(); help.showOrPrint();
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
@ -604,11 +604,11 @@ int main(int argc, char *argv[])
if (!boost::filesystem::is_directory(GetDataDir(false))) if (!boost::filesystem::is_directory(GetDataDir(false)))
{ {
QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QMessageBox::critical(0, QObject::tr(PACKAGE_NAME),
QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(GetArg("-datadir", ""))));
return EXIT_FAILURE; return EXIT_FAILURE;
} }
try { try {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME), mapArgs, mapMultiArgs); ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) { } catch (const std::exception& e) {
QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QMessageBox::critical(0, QObject::tr(PACKAGE_NAME),
QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what()));
@ -672,7 +672,7 @@ int main(int argc, char *argv[])
// Allow parameter interaction before we create the options model // Allow parameter interaction before we create the options model
app.parameterSetup(); app.parameterSetup();
// Load GUI settings from QSettings // Load GUI settings from QSettings
app.createOptionsModel(mapArgs.count("-resetguisettings") != 0); app.createOptionsModel(IsArgSet("-resetguisettings"));
// Subscribe to global signals from core // Subscribe to global signals from core
uiInterface.InitMessage.connect(InitMessage); uiInterface.InitMessage.connect(InitMessage);

4
src/qt/optionsmodel.cpp

@ -36,7 +36,7 @@ OptionsModel::OptionsModel(QObject *parent, bool resetSettings) :
void OptionsModel::addOverriddenOption(const std::string &option) void OptionsModel::addOverriddenOption(const std::string &option)
{ {
strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " "; strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(GetArg(option, "")) + " ";
} }
// Writes all missing QSettings with their default values // Writes all missing QSettings with their default values
@ -464,4 +464,4 @@ void OptionsModel::checkAndMigrate()
settings.setValue(strSettingsVersionKey, CLIENT_VERSION); settings.setValue(strSettingsVersionKey, CLIENT_VERSION);
} }
} }

2
src/qt/test/rpcnestedtests.cpp

@ -45,7 +45,7 @@ void RPCNestedTests::rpcNestedTests()
std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
QDir dir(QString::fromStdString(path)); QDir dir(QString::fromStdString(path));
dir.mkpath("."); dir.mkpath(".");
mapArgs["-datadir"] = path; ForceSetArg("-datadir", path);
//mempool.setSanityCheck(1.0); //mempool.setSanityCheck(1.0);
pblocktree = new CBlockTreeDB(1 << 20, true); pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true);

5
src/test/DoS_tests.cpp

@ -12,6 +12,7 @@
#include "script/sign.h" #include "script/sign.h"
#include "serialize.h" #include "serialize.h"
#include "util.h" #include "util.h"
#include "validation.h"
#include "test/test_bitcoin.h" #include "test/test_bitcoin.h"
@ -74,7 +75,7 @@ BOOST_AUTO_TEST_CASE(DoS_banning)
BOOST_AUTO_TEST_CASE(DoS_banscore) BOOST_AUTO_TEST_CASE(DoS_banscore)
{ {
connman->ClearBanned(); connman->ClearBanned();
mapArgs["-banscore"] = "111"; // because 11 is my favorite number ForceSetArg("-banscore", "111"); // because 11 is my favorite number
CAddress addr1(ip(0xa0b0c001), NODE_NONE); CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true); CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION); dummyNode1.SetSendVersion(PROTOCOL_VERSION);
@ -89,7 +90,7 @@ BOOST_AUTO_TEST_CASE(DoS_banscore)
Misbehaving(dummyNode1.GetId(), 1); Misbehaving(dummyNode1.GetId(), 1);
SendMessages(&dummyNode1, *connman); SendMessages(&dummyNode1, *connman);
BOOST_CHECK(connman->IsBanned(addr1)); BOOST_CHECK(connman->IsBanned(addr1));
mapArgs.erase("-banscore"); ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
} }
BOOST_AUTO_TEST_CASE(DoS_bantime) BOOST_AUTO_TEST_CASE(DoS_bantime)

2
src/test/test_bitcoin.cpp

@ -64,7 +64,7 @@ TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(cha
ClearDatadirCache(); ClearDatadirCache();
pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); pathTemp = GetTempPath() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp); boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string(); ForceSetArg("-datadir", pathTemp.string());
mempool.setSanityCheck(1.0); mempool.setSanityCheck(1.0);
pblocktree = new CBlockTreeDB(1 << 20, true); pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true);

8
src/test/util_tests.cpp

@ -19,6 +19,8 @@
using namespace std; using namespace std;
extern map<string, string> mapArgs;
BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup) BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(util_criticalsection) BOOST_AUTO_TEST_CASE(util_criticalsection)
@ -115,13 +117,13 @@ BOOST_AUTO_TEST_CASE(util_ParseParameters)
// -a, -b and -ccc end up in map, -d ignored because it is after // -a, -b and -ccc end up in map, -d ignored because it is after
// a non-option argument (non-GNU option parsing) // a non-option argument (non-GNU option parsing)
BOOST_CHECK(mapArgs.size() == 3 && mapMultiArgs.size() == 3); BOOST_CHECK(mapArgs.size() == 3 && mapMultiArgs.size() == 3);
BOOST_CHECK(mapArgs.count("-a") && mapArgs.count("-b") && mapArgs.count("-ccc") BOOST_CHECK(IsArgSet("-a") && IsArgSet("-b") && IsArgSet("-ccc")
&& !mapArgs.count("f") && !mapArgs.count("-d")); && !IsArgSet("f") && !IsArgSet("-d"));
BOOST_CHECK(mapMultiArgs.count("-a") && mapMultiArgs.count("-b") && mapMultiArgs.count("-ccc") BOOST_CHECK(mapMultiArgs.count("-a") && mapMultiArgs.count("-b") && mapMultiArgs.count("-ccc")
&& !mapMultiArgs.count("f") && !mapMultiArgs.count("-d")); && !mapMultiArgs.count("f") && !mapMultiArgs.count("-d"));
BOOST_CHECK(mapArgs["-a"] == "" && mapArgs["-ccc"] == "multiple"); BOOST_CHECK(mapArgs["-a"] == "" && mapArgs["-ccc"] == "multiple");
BOOST_CHECK(mapMultiArgs["-ccc"].size() == 2); BOOST_CHECK(mapMultiArgs.at("-ccc").size() == 2);
} }
BOOST_AUTO_TEST_CASE(util_GetArg) BOOST_AUTO_TEST_CASE(util_GetArg)

71
src/util.cpp

@ -102,8 +102,10 @@ using namespace std;
const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf"; const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
const char * const BITCOIN_PID_FILENAME = "bitcoind.pid"; const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";
CCriticalSection cs_args;
map<string, string> mapArgs; map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs; static map<string, vector<string> > _mapMultiArgs;
const map<string, vector<string> >& mapMultiArgs = _mapMultiArgs;
bool fDebug = false; bool fDebug = false;
bool fPrintToConsole = false; bool fPrintToConsole = false;
bool fPrintToDebugLog = true; bool fPrintToDebugLog = true;
@ -238,9 +240,12 @@ bool LogAcceptCategory(const char* category)
static boost::thread_specific_ptr<set<string> > ptrCategory; static boost::thread_specific_ptr<set<string> > ptrCategory;
if (ptrCategory.get() == NULL) if (ptrCategory.get() == NULL)
{ {
const vector<string>& categories = mapMultiArgs["-debug"]; if (mapMultiArgs.count("-debug")) {
ptrCategory.reset(new set<string>(categories.begin(), categories.end())); const vector<string>& categories = mapMultiArgs.at("-debug");
// thread_specific_ptr automatically deletes the set when the thread ends. ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
// thread_specific_ptr automatically deletes the set when the thread ends.
} else
ptrCategory.reset(new set<string>());
} }
const set<string>& setCategories = *ptrCategory.get(); const set<string>& setCategories = *ptrCategory.get();
@ -342,8 +347,9 @@ static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
void ParseParameters(int argc, const char* const argv[]) void ParseParameters(int argc, const char* const argv[])
{ {
LOCK(cs_args);
mapArgs.clear(); mapArgs.clear();
mapMultiArgs.clear(); _mapMultiArgs.clear();
for (int i = 1; i < argc; i++) for (int i = 1; i < argc; i++)
{ {
@ -371,12 +377,19 @@ void ParseParameters(int argc, const char* const argv[])
InterpretNegativeSetting(str, strValue); InterpretNegativeSetting(str, strValue);
mapArgs[str] = strValue; mapArgs[str] = strValue;
mapMultiArgs[str].push_back(strValue); _mapMultiArgs[str].push_back(strValue);
} }
} }
bool IsArgSet(const std::string& strArg)
{
LOCK(cs_args);
return mapArgs.count(strArg);
}
std::string GetArg(const std::string& strArg, const std::string& strDefault) std::string GetArg(const std::string& strArg, const std::string& strDefault)
{ {
LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
return mapArgs[strArg]; return mapArgs[strArg];
return strDefault; return strDefault;
@ -384,6 +397,7 @@ std::string GetArg(const std::string& strArg, const std::string& strDefault)
int64_t GetArg(const std::string& strArg, int64_t nDefault) int64_t GetArg(const std::string& strArg, int64_t nDefault)
{ {
LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]); return atoi64(mapArgs[strArg]);
return nDefault; return nDefault;
@ -391,6 +405,7 @@ int64_t GetArg(const std::string& strArg, int64_t nDefault)
bool GetBoolArg(const std::string& strArg, bool fDefault) bool GetBoolArg(const std::string& strArg, bool fDefault)
{ {
LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
return InterpretBool(mapArgs[strArg]); return InterpretBool(mapArgs[strArg]);
return fDefault; return fDefault;
@ -398,6 +413,7 @@ bool GetBoolArg(const std::string& strArg, bool fDefault)
bool SoftSetArg(const std::string& strArg, const std::string& strValue) bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{ {
LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
return false; return false;
mapArgs[strArg] = strValue; mapArgs[strArg] = strValue;
@ -412,6 +428,14 @@ bool SoftSetBoolArg(const std::string& strArg, bool fValue)
return SoftSetArg(strArg, std::string("0")); return SoftSetArg(strArg, std::string("0"));
} }
void ForceSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
mapArgs[strArg] = strValue;
}
static const int screenWidth = 79; static const int screenWidth = 79;
static const int optIndent = 2; static const int optIndent = 2;
static const int msgIndent = 7; static const int msgIndent = 7;
@ -494,8 +518,8 @@ const boost::filesystem::path &GetDataDir(bool fNetSpecific)
if (!path.empty()) if (!path.empty())
return path; return path;
if (mapArgs.count("-datadir")) { if (IsArgSet("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]); path = fs::system_complete(GetArg("-datadir", ""));
if (!fs::is_directory(path)) { if (!fs::is_directory(path)) {
path = ""; path = "";
return path; return path;
@ -513,6 +537,8 @@ const boost::filesystem::path &GetDataDir(bool fNetSpecific)
void ClearDatadirCache() void ClearDatadirCache()
{ {
LOCK(csPathCached);
pathCached = boost::filesystem::path(); pathCached = boost::filesystem::path();
pathCachedNetSpecific = boost::filesystem::path(); pathCachedNetSpecific = boost::filesystem::path();
} }
@ -526,26 +552,27 @@ boost::filesystem::path GetConfigFile(const std::string& confPath)
return pathConfigFile; return pathConfigFile;
} }
void ReadConfigFile(const std::string& confPath, void ReadConfigFile(const std::string& confPath)
map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{ {
boost::filesystem::ifstream streamConfig(GetConfigFile(confPath)); boost::filesystem::ifstream streamConfig(GetConfigFile(confPath));
if (!streamConfig.good()) if (!streamConfig.good())
return; // No bitcoin.conf file is OK return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{ {
// Don't overwrite existing settings so command line settings override bitcoin.conf LOCK(cs_args);
string strKey = string("-") + it->string_key; set<string> setOptions;
string strValue = it->value[0]; setOptions.insert("*");
InterpretNegativeSetting(strKey, strValue);
if (mapSettingsRet.count(strKey) == 0) for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
mapSettingsRet[strKey] = strValue; {
mapMultiSettingsRet[strKey].push_back(strValue); // Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
string strValue = it->value[0];
InterpretNegativeSetting(strKey, strValue);
if (mapArgs.count(strKey) == 0)
mapArgs[strKey] = strValue;
_mapMultiArgs[strKey].push_back(strValue);
}
} }
// If datadir is changed in .conf file: // If datadir is changed in .conf file:
ClearDatadirCache(); ClearDatadirCache();

16
src/util.h

@ -41,8 +41,7 @@ public:
boost::signals2::signal<std::string (const char* psz)> Translate; boost::signals2::signal<std::string (const char* psz)> Translate;
}; };
extern std::map<std::string, std::string> mapArgs; extern const std::map<std::string, std::vector<std::string> >& mapMultiArgs;
extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
extern bool fDebug; extern bool fDebug;
extern bool fPrintToConsole; extern bool fPrintToConsole;
extern bool fPrintToDebugLog; extern bool fPrintToDebugLog;
@ -106,7 +105,7 @@ boost::filesystem::path GetConfigFile(const std::string& confPath);
boost::filesystem::path GetPidFile(); boost::filesystem::path GetPidFile();
void CreatePidFile(const boost::filesystem::path &path, pid_t pid); void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
#endif #endif
void ReadConfigFile(const std::string& confPath, std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); void ReadConfigFile(const std::string& confPath);
#ifdef WIN32 #ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
#endif #endif
@ -123,6 +122,14 @@ inline bool IsSwitchChar(char c)
#endif #endif
} }
/**
* Return true if the given argument has been manually set
*
* @param strArg Argument to get (e.g. "-foo")
* @return true if the argument has been set
*/
bool IsArgSet(const std::string& strArg);
/** /**
* Return string argument or default value * Return string argument or default value
* *
@ -168,6 +175,9 @@ bool SoftSetArg(const std::string& strArg, const std::string& strValue);
*/ */
bool SoftSetBoolArg(const std::string& strArg, bool fValue); bool SoftSetBoolArg(const std::string& strArg, bool fValue);
// Forces a arg setting, used only in testing
void ForceSetArg(const std::string& strArg, const std::string& strValue);
/** /**
* Format a string to be used as group of options in help messages * Format a string to be used as group of options in help messages
* *

30
src/wallet/wallet.cpp

@ -3494,7 +3494,7 @@ bool CWallet::InitLoadWallet()
walletInstance->SetBestChain(chainActive.GetLocator()); walletInstance->SetBestChain(chainActive.GetLocator());
} }
else if (mapArgs.count("-usehd")) { else if (IsArgSet("-usehd")) {
bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET); bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
if (walletInstance->IsHDEnabled() && !useHD) if (walletInstance->IsHDEnabled() && !useHD)
return InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile)); return InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
@ -3618,31 +3618,31 @@ bool CWallet::ParameterInteraction()
InitWarning(AmountHighWarn("-minrelaytxfee") + " " + InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
_("The wallet will avoid paying less than the minimum relay fee.")); _("The wallet will avoid paying less than the minimum relay fee."));
if (mapArgs.count("-mintxfee")) if (IsArgSet("-mintxfee"))
{ {
CAmount n = 0; CAmount n = 0;
if (!ParseMoney(mapArgs["-mintxfee"], n) || 0 == n) if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
return InitError(AmountErrMsg("mintxfee", mapArgs["-mintxfee"])); return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
if (n > HIGH_TX_FEE_PER_KB) if (n > HIGH_TX_FEE_PER_KB)
InitWarning(AmountHighWarn("-mintxfee") + " " + InitWarning(AmountHighWarn("-mintxfee") + " " +
_("This is the minimum transaction fee you pay on every transaction.")); _("This is the minimum transaction fee you pay on every transaction."));
CWallet::minTxFee = CFeeRate(n); CWallet::minTxFee = CFeeRate(n);
} }
if (mapArgs.count("-fallbackfee")) if (IsArgSet("-fallbackfee"))
{ {
CAmount nFeePerK = 0; CAmount nFeePerK = 0;
if (!ParseMoney(mapArgs["-fallbackfee"], nFeePerK)) if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), mapArgs["-fallbackfee"])); return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
if (nFeePerK > HIGH_TX_FEE_PER_KB) if (nFeePerK > HIGH_TX_FEE_PER_KB)
InitWarning(AmountHighWarn("-fallbackfee") + " " + InitWarning(AmountHighWarn("-fallbackfee") + " " +
_("This is the transaction fee you may pay when fee estimates are not available.")); _("This is the transaction fee you may pay when fee estimates are not available."));
CWallet::fallbackFee = CFeeRate(nFeePerK); CWallet::fallbackFee = CFeeRate(nFeePerK);
} }
if (mapArgs.count("-paytxfee")) if (IsArgSet("-paytxfee"))
{ {
CAmount nFeePerK = 0; CAmount nFeePerK = 0;
if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK)) if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
return InitError(AmountErrMsg("paytxfee", mapArgs["-paytxfee"])); return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
if (nFeePerK > HIGH_TX_FEE_PER_KB) if (nFeePerK > HIGH_TX_FEE_PER_KB)
InitWarning(AmountHighWarn("-paytxfee") + " " + InitWarning(AmountHighWarn("-paytxfee") + " " +
_("This is the transaction fee you will pay if you send a transaction.")); _("This is the transaction fee you will pay if you send a transaction."));
@ -3651,21 +3651,21 @@ bool CWallet::ParameterInteraction()
if (payTxFee < ::minRelayTxFee) if (payTxFee < ::minRelayTxFee)
{ {
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
mapArgs["-paytxfee"], ::minRelayTxFee.ToString())); GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
} }
} }
if (mapArgs.count("-maxtxfee")) if (IsArgSet("-maxtxfee"))
{ {
CAmount nMaxFee = 0; CAmount nMaxFee = 0;
if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee)) if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
return InitError(AmountErrMsg("maxtxfee", mapArgs["-maxtxfee"])); return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
if (nMaxFee > HIGH_MAX_TX_FEE) if (nMaxFee > HIGH_MAX_TX_FEE)
InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction.")); InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
maxTxFee = nMaxFee; maxTxFee = nMaxFee;
if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee) if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
{ {
return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"), return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
mapArgs["-maxtxfee"], ::minRelayTxFee.ToString())); GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
} }
} }
nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET); nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);

8
src/zmq/zmqnotificationinterface.cpp

@ -29,7 +29,7 @@ CZMQNotificationInterface::~CZMQNotificationInterface()
} }
} }
CZMQNotificationInterface* CZMQNotificationInterface::CreateWithArguments(const std::map<std::string, std::string> &args) CZMQNotificationInterface* CZMQNotificationInterface::Create()
{ {
CZMQNotificationInterface* notificationInterface = NULL; CZMQNotificationInterface* notificationInterface = NULL;
std::map<std::string, CZMQNotifierFactory> factories; std::map<std::string, CZMQNotifierFactory> factories;
@ -42,11 +42,11 @@ CZMQNotificationInterface* CZMQNotificationInterface::CreateWithArguments(const
for (std::map<std::string, CZMQNotifierFactory>::const_iterator i=factories.begin(); i!=factories.end(); ++i) for (std::map<std::string, CZMQNotifierFactory>::const_iterator i=factories.begin(); i!=factories.end(); ++i)
{ {
std::map<std::string, std::string>::const_iterator j = args.find("-zmq" + i->first); std::string arg("-zmq" + i->first);
if (j!=args.end()) if (IsArgSet(arg))
{ {
CZMQNotifierFactory factory = i->second; CZMQNotifierFactory factory = i->second;
std::string address = j->second; std::string address = GetArg(arg, "");
CZMQAbstractNotifier *notifier = factory(); CZMQAbstractNotifier *notifier = factory();
notifier->SetType(i->first); notifier->SetType(i->first);
notifier->SetAddress(address); notifier->SetAddress(address);

2
src/zmq/zmqnotificationinterface.h

@ -17,7 +17,7 @@ class CZMQNotificationInterface : public CValidationInterface
public: public:
virtual ~CZMQNotificationInterface(); virtual ~CZMQNotificationInterface();
static CZMQNotificationInterface* CreateWithArguments(const std::map<std::string, std::string> &args); static CZMQNotificationInterface* Create();
protected: protected:
bool Initialize(); bool Initialize();

Loading…
Cancel
Save