Skip to content

Commit

Permalink
Merge bitcoin#9243: Clean up mapArgs and mapMultiArgs Usage
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
sipa committed Dec 27, 2016
2 parents dbc8a8c + c2f61be commit 7aa7004
Show file tree
Hide file tree
Showing 20 changed files with 173 additions and 124 deletions.
12 changes: 6 additions & 6 deletions src/bitcoin-cli.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ static int AppInitRPC(int argc, char* argv[])
// Parameters
//
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";
if (!mapArgs.count("-version")) {
if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoin-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" +
" bitcoin-cli [options] help " + _("List commands") + "\n" +
Expand All @@ -95,11 +95,11 @@ static int AppInitRPC(int argc, char* argv[])
return EXIT_SUCCESS;
}
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;
}
try {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME), mapArgs, mapMultiArgs);
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
Expand Down Expand Up @@ -211,7 +211,7 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)

// Get credentials
std::string strRPCUserColonPass;
if (mapArgs["-rpcpassword"] == "") {
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
Expand All @@ -220,7 +220,7 @@ UniValue CallRPC(const std::string& strMethod, const UniValue& params)

}
} else {
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}

struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req);
Expand Down
2 changes: 1 addition & 1 deletion src/bitcoin-tx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ static int AppInitRawTx(int argc, char* argv[])

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
std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
Expand Down
8 changes: 4 additions & 4 deletions src/bitcoind.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@ bool AppInit(int argc, char* argv[])
ParseParameters(argc, argv);

// 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";

if (mapArgs.count("-version"))
if (IsArgSet("-version"))
{
strUsage += FormatParagraph(LicenseInfo());
}
Expand All @@ -99,12 +99,12 @@ bool AppInit(int argc, char* argv[])
{
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;
}
try
{
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME), mapArgs, mapMultiArgs);
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
Expand Down
6 changes: 3 additions & 3 deletions src/httprpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ static bool multiUserAuthorized(std::string strUserPass)

if (mapMultiArgs.count("-rpcauth") > 0) {
//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;
boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
Expand Down Expand Up @@ -215,7 +215,7 @@ static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)

static bool InitRPCAuthentication()
{
if (mapArgs["-rpcpassword"] == "")
if (GetArg("-rpcpassword", "") == "")
{
LogPrintf("No rpcpassword set - using random cookie authentication\n");
if (!GenerateAuthCookie(&strRPCUserColonPass)) {
Expand All @@ -226,7 +226,7 @@ static bool InitRPCAuthentication()
}
} 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");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
return true;
}
Expand Down
10 changes: 5 additions & 5 deletions src/httpserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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(localv6)); // always allow IPv6 localhost
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) {
CSubNet subnet;
LookupSubNet(strAllow.c_str(), subnet);
Expand Down Expand Up @@ -322,14 +322,14 @@ static bool HTTPBindAddresses(struct evhttp* http)
std::vector<std::pair<std::string, uint16_t> > endpoints;

// 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("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");
}
} else if (mapArgs.count("-rpcbind")) { // Specific bind address
const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"];
} else if (mapMultiArgs.count("-rpcbind")) { // Specific bind address
const std::vector<std::string>& vbind = mapMultiArgs.at("-rpcbind");
for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
int port = defaultPort;
std::string host;
Expand Down
86 changes: 47 additions & 39 deletions src/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -708,24 +708,24 @@ void InitParameterInteraction()
{
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
if (mapArgs.count("-bind")) {
if (IsArgSet("-bind")) {
if (SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
}
if (mapArgs.count("-whitebind")) {
if (IsArgSet("-whitebind")) {
if (SoftSetBoolArg("-listen", true))
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
if (SoftSetBoolArg("-dnsseed", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
if (SoftSetBoolArg("-listen", false))
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
if (SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
Expand All @@ -748,7 +748,7 @@ void InitParameterInteraction()
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 (SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
Expand Down Expand Up @@ -880,17 +880,19 @@ bool AppInitParameterInteraction()

// ********************************************************* 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
const vector<string>& categories = mapMultiArgs["-debug"];
if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
fDebug = false;
if (fDebug) {
const vector<string>& categories = mapMultiArgs.at("-debug");
if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
fDebug = false;
}

// Check for -debugnet
if (GetBoolArg("-debugnet", false))
InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
// 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."));
// Check for -tor - as this is a privacy risk to continue, exit here
if (GetBoolArg("-tor", false))
Expand All @@ -902,7 +904,7 @@ bool AppInitParameterInteraction()
if (GetBoolArg("-whitelistalwaysrelay", false))
InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));

if (mapArgs.count("-blockminsize"))
if (IsArgSet("-blockminsize"))
InitWarning("Unsupported argument -blockminsize ignored.");

// Checkmempool and checkblockindex default to true in regtest mode
Expand Down Expand Up @@ -957,11 +959,11 @@ bool AppInitParameterInteraction()
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-minrelaytxfee"))
if (IsArgSet("-minrelaytxfee"))
{
CAmount n = 0;
if (!ParseMoney(mapArgs["-minrelaytxfee"], n) || 0 == n)
return InitError(AmountErrMsg("minrelaytxfee", mapArgs["-minrelaytxfee"]));
if (!ParseMoney(GetArg("-minrelaytxfee", ""), n) || 0 == n)
return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
// High fee check is done afterward in CWallet::ParameterInteraction()
::minRelayTxFee = CFeeRate(n);
}
Expand Down Expand Up @@ -995,20 +997,20 @@ bool AppInitParameterInteraction()
nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);

fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
if ((!fEnableReplacement) && mapArgs.count("-mempoolreplacement")) {
if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
// Minimal effort at forwards compatibility
std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
std::vector<std::string> vstrReplacementModes;
boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
}

if (!mapMultiArgs["-bip9params"].empty()) {
if (mapMultiArgs.count("-bip9params")) {
// Allow overriding BIP9 parameters for testing
if (!chainparams.MineBlocksOnDemand()) {
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) {
std::vector<std::string> vDeploymentParams;
boost::split(vDeploymentParams, i, boost::is_any_of(":"));
Expand Down Expand Up @@ -1154,21 +1156,23 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)

// sanitize comments per BIP-0014, format user agent and check total size
std::vector<string> uacomments;
BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"])
{
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT));
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));
uacomments.push_back(cmt);
}
}
strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
strSubVersion.size(), MAX_SUBVERSION_LENGTH));
}

if (mapArgs.count("-onlynet")) {
if (mapMultiArgs.count("-onlynet")) {
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);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
Expand All @@ -1181,8 +1185,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
}

if (mapArgs.count("-whitelist")) {
BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
if (mapMultiArgs.count("-whitelist")) {
BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) {
CSubNet subnet;
LookupSubNet(net.c_str(), subnet);
if (!subnet.IsValid())
Expand Down Expand Up @@ -1234,14 +1238,16 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)

if (fListen) {
bool fBound = false;
if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
if (mapMultiArgs.count("-bind")) {
BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(ResolveErrMsg("bind", strBind));
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;
if (!Lookup(strBind.c_str(), addrBind, 0, false))
return InitError(ResolveErrMsg("whitebind", strBind));
Expand All @@ -1250,7 +1256,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
}
}
else {
if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
Expand All @@ -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."));
}

if (mapArgs.count("-externalip")) {
BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
if (mapMultiArgs.count("-externalip")) {
BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) {
CService addrLocal;
if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
AddLocal(addrLocal, LOCAL_MANUAL);
Expand All @@ -1270,11 +1276,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
}
}

BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
connman.AddOneShot(strDest);
if (mapMultiArgs.count("-seednode")) {
BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode"))
connman.AddOneShot(strDest);
}

#if ENABLE_ZMQ
pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
pzmqNotificationInterface = CZMQNotificationInterface::Create();

if (pzmqNotificationInterface) {
RegisterValidationInterface(pzmqNotificationInterface);
Expand All @@ -1283,7 +1291,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;

if (mapArgs.count("-maxuploadtarget")) {
if (IsArgSet("-maxuploadtarget")) {
nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
}

Expand Down Expand Up @@ -1515,13 +1523,13 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
fHaveGenesis = true;
}

if (mapArgs.count("-blocknotify"))
if (IsArgSet("-blocknotify"))
uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);

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);
}

Expand Down
4 changes: 2 additions & 2 deletions src/miner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,12 @@ BlockAssembler::BlockAssembler(const CChainParams& _chainparams)
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
bool fWeightSet = false;
if (mapArgs.count("-blockmaxweight")) {
if (IsArgSet("-blockmaxweight")) {
nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
fWeightSet = true;
}
if (mapArgs.count("-blockmaxsize")) {
if (IsArgSet("-blockmaxsize")) {
nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
if (!fWeightSet) {
nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR;
Expand Down
Loading

0 comments on commit 7aa7004

Please sign in to comment.