Skip to content

Commit 9d3918d

Browse files
committed
refactor: Replace std::optional<bilingual_str> with util::Result
1 parent 09eb583 commit 9d3918d

File tree

11 files changed

+45
-42
lines changed

11 files changed

+45
-42
lines changed

src/addrdb.cpp

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -182,10 +182,10 @@ void ReadFromStream(AddrMan& addr, CDataStream& ssPeers)
182182
DeserializeDB(ssPeers, addr, false);
183183
}
184184

185-
std::optional<bilingual_str> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args, std::unique_ptr<AddrMan>& addrman)
185+
util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args)
186186
{
187187
auto check_addrman = std::clamp<int32_t>(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000);
188-
addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman);
188+
auto addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman);
189189

190190
int64_t nStart = GetTimeMillis();
191191
const auto path_addr{args.GetDataDirNet() / "peers.dat"};
@@ -199,19 +199,17 @@ std::optional<bilingual_str> LoadAddrman(const NetGroupManager& netgroupman, con
199199
DumpPeerAddresses(args, *addrman);
200200
} catch (const InvalidAddrManVersionError&) {
201201
if (!RenameOver(path_addr, (fs::path)path_addr + ".bak")) {
202-
addrman = nullptr;
203-
return strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."));
202+
return util::Error{strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."))};
204203
}
205204
// Addrman can be in an inconsistent state after failure, reset it
206205
addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman);
207206
LogPrintf("Creating new peers.dat because the file version was not compatible (%s). Original backed up to peers.dat.bak\n", fs::quoted(fs::PathToString(path_addr)));
208207
DumpPeerAddresses(args, *addrman);
209208
} catch (const std::exception& e) {
210-
addrman = nullptr;
211-
return strprintf(_("Invalid or corrupt peers.dat (%s). If you believe this is a bug, please report it to %s. As a workaround, you can move the file (%s) out of the way (rename, move, or delete) to have a new one created on the next start."),
212-
e.what(), PACKAGE_BUGREPORT, fs::quoted(fs::PathToString(path_addr)));
209+
return util::Error{strprintf(_("Invalid or corrupt peers.dat (%s). If you believe this is a bug, please report it to %s. As a workaround, you can move the file (%s) out of the way (rename, move, or delete) to have a new one created on the next start."),
210+
e.what(), PACKAGE_BUGREPORT, fs::quoted(fs::PathToString(path_addr)))};
213211
}
214-
return std::nullopt;
212+
return addrman;
215213
}
216214

217215
void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors)

src/addrdb.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <fs.h>
1010
#include <net_types.h> // For banmap_t
1111
#include <univalue.h>
12+
#include <util/result.h>
1213

1314
#include <optional>
1415
#include <vector>
@@ -49,7 +50,7 @@ class CBanDB
4950
};
5051

5152
/** Returns an error string on failure */
52-
std::optional<bilingual_str> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args, std::unique_ptr<AddrMan>& addrman);
53+
util::Result<std::unique_ptr<AddrMan>> LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args);
5354

5455
/**
5556
* Dump the anchor IP address database (anchors.dat)

src/bitcoin-chainstate.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ int main(int argc, char* argv[])
5858
// We can't use a goto here, but we can use an assert since none of the
5959
// things instantiated so far requires running the epilogue to be torn down
6060
// properly
61-
assert(!kernel::SanityChecks(kernel_context).has_value());
61+
assert(kernel::SanityChecks(kernel_context).has_value());
6262

6363
// Necessary for CheckInputScripts (eventually called by ProcessNewBlock),
6464
// which will try the script cache first and fall back to actually

src/init.cpp

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,8 +1059,9 @@ static bool LockDataDirectory(bool probeOnly)
10591059
bool AppInitSanityChecks(const kernel::Context& kernel)
10601060
{
10611061
// ********************************************************* Step 4: sanity checks
1062-
if (auto error = kernel::SanityChecks(kernel)) {
1063-
InitError(*error);
1062+
auto result = kernel::SanityChecks(kernel);
1063+
if (!result) {
1064+
InitError(util::ErrorString(result));
10641065
return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME));
10651066
}
10661067

@@ -1236,9 +1237,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
12361237
// Initialize addrman
12371238
assert(!node.addrman);
12381239
uiInterface.InitMessage(_("Loading P2P addresses…").translated);
1239-
if (const auto error{LoadAddrman(*node.netgroupman, args, node.addrman)}) {
1240-
return InitError(*error);
1241-
}
1240+
auto addrman = LoadAddrman(*node.netgroupman, args);
1241+
if (!addrman) return InitError(util::ErrorString(addrman));
1242+
node.addrman = std::move(*addrman);
12421243
}
12431244

12441245
assert(!node.banman);
@@ -1386,8 +1387,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
13861387
.estimator = node.fee_estimator.get(),
13871388
.check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
13881389
};
1389-
if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
1390-
return InitError(*err);
1390+
auto result = ApplyArgsManOptions(args, chainparams, mempool_opts);
1391+
if (!result) {
1392+
return InitError(util::ErrorString(result));
13911393
}
13921394
mempool_opts.check_ratio = std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
13931395

@@ -1487,8 +1489,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14871489

14881490
// ********************************************************* Step 8: start indexers
14891491
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1490-
if (const auto error{WITH_LOCK(cs_main, return CheckLegacyTxindex(*Assert(chainman.m_blockman.m_block_tree_db)))}) {
1491-
return InitError(*error);
1492+
auto result = WITH_LOCK(cs_main, return CheckLegacyTxindex(*Assert(chainman.m_blockman.m_block_tree_db)));
1493+
if (!result) {
1494+
return InitError(util::ErrorString(result));
14921495
}
14931496

14941497
g_txindex = std::make_unique<TxIndex>(interfaces::MakeChain(node), cache_sizes.tx_index, false, fReindex);

src/kernel/checks.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,21 +13,21 @@
1313

1414
namespace kernel {
1515

16-
std::optional<bilingual_str> SanityChecks(const Context&)
16+
util::Result<void> SanityChecks(const Context&)
1717
{
1818
if (!ECC_InitSanityCheck()) {
19-
return Untranslated("Elliptic curve cryptography sanity check failure. Aborting.");
19+
return util::Error{Untranslated("Elliptic curve cryptography sanity check failure. Aborting.")};
2020
}
2121

2222
if (!Random_SanityCheck()) {
23-
return Untranslated("OS cryptographic RNG sanity check failure. Aborting.");
23+
return util::Error{Untranslated("OS cryptographic RNG sanity check failure. Aborting.")};
2424
}
2525

2626
if (!ChronoSanityCheck()) {
27-
return Untranslated("Clock epoch mismatch. Aborting.");
27+
return util::Error{Untranslated("Clock epoch mismatch. Aborting.")};
2828
}
2929

30-
return std::nullopt;
30+
return {};
3131
}
3232

3333
}

src/kernel/checks.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
#ifndef BITCOIN_KERNEL_CHECKS_H
66
#define BITCOIN_KERNEL_CHECKS_H
77

8-
#include <optional>
8+
#include <util/result.h>
99

1010
struct bilingual_str;
1111

@@ -16,7 +16,7 @@ struct Context;
1616
/**
1717
* Ensure a usable environment with all necessary library support.
1818
*/
19-
std::optional<bilingual_str> SanityChecks(const Context&);
19+
util::Result<void> SanityChecks(const Context&);
2020

2121
}
2222

src/node/mempool_args.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ void ApplyArgsManOptions(const ArgsManager& argsman, MemPoolLimits& mempool_limi
3838
}
3939
}
4040

41-
std::optional<bilingual_str> ApplyArgsManOptions(const ArgsManager& argsman, const CChainParams& chainparams, MemPoolOptions& mempool_opts)
41+
util::Result<void> ApplyArgsManOptions(const ArgsManager& argsman, const CChainParams& chainparams, MemPoolOptions& mempool_opts)
4242
{
4343
mempool_opts.check_ratio = argsman.GetIntArg("-checkmempool", mempool_opts.check_ratio);
4444

@@ -52,7 +52,7 @@ std::optional<bilingual_str> ApplyArgsManOptions(const ArgsManager& argsman, con
5252
if (std::optional<CAmount> inc_relay_fee = ParseMoney(argsman.GetArg("-incrementalrelayfee", ""))) {
5353
mempool_opts.incremental_relay_feerate = CFeeRate{inc_relay_fee.value()};
5454
} else {
55-
return AmountErrMsg("incrementalrelayfee", argsman.GetArg("-incrementalrelayfee", ""));
55+
return util::Error{AmountErrMsg("incrementalrelayfee", argsman.GetArg("-incrementalrelayfee", ""))};
5656
}
5757
}
5858

@@ -61,7 +61,7 @@ std::optional<bilingual_str> ApplyArgsManOptions(const ArgsManager& argsman, con
6161
// High fee check is done afterward in CWallet::Create()
6262
mempool_opts.min_relay_feerate = CFeeRate{min_relay_feerate.value()};
6363
} else {
64-
return AmountErrMsg("minrelaytxfee", argsman.GetArg("-minrelaytxfee", ""));
64+
return util::Error{AmountErrMsg("minrelaytxfee", argsman.GetArg("-minrelaytxfee", ""))};
6565
}
6666
} else if (mempool_opts.incremental_relay_feerate > mempool_opts.min_relay_feerate) {
6767
// Allow only setting incremental fee to control both
@@ -75,7 +75,7 @@ std::optional<bilingual_str> ApplyArgsManOptions(const ArgsManager& argsman, con
7575
if (std::optional<CAmount> parsed = ParseMoney(argsman.GetArg("-dustrelayfee", ""))) {
7676
mempool_opts.dust_relay_feerate = CFeeRate{parsed.value()};
7777
} else {
78-
return AmountErrMsg("dustrelayfee", argsman.GetArg("-dustrelayfee", ""));
78+
return util::Error{AmountErrMsg("dustrelayfee", argsman.GetArg("-dustrelayfee", ""))};
7979
}
8080
}
8181

@@ -89,12 +89,12 @@ std::optional<bilingual_str> ApplyArgsManOptions(const ArgsManager& argsman, con
8989

9090
mempool_opts.require_standard = !argsman.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
9191
if (!chainparams.IsTestChain() && !mempool_opts.require_standard) {
92-
return strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString());
92+
return util::Error{strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString())};
9393
}
9494

9595
mempool_opts.full_rbf = argsman.GetBoolArg("-mempoolfullrbf", mempool_opts.full_rbf);
9696

9797
ApplyArgsManOptions(argsman, mempool_opts.limits);
9898

99-
return std::nullopt;
99+
return {};
100100
}

src/node/mempool_args.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
#ifndef BITCOIN_NODE_MEMPOOL_ARGS_H
66
#define BITCOIN_NODE_MEMPOOL_ARGS_H
77

8-
#include <optional>
8+
#include <util/result.h>
99

1010
class ArgsManager;
1111
class CChainParams;
@@ -21,7 +21,7 @@ struct MemPoolOptions;
2121
* @param[in] argsman The ArgsManager in which to check set options.
2222
* @param[in,out] mempool_opts The MemPoolOptions to modify according to \p argsman.
2323
*/
24-
[[nodiscard]] std::optional<bilingual_str> ApplyArgsManOptions(const ArgsManager& argsman, const CChainParams& chainparams, kernel::MemPoolOptions& mempool_opts);
24+
[[nodiscard]] util::Result<void> ApplyArgsManOptions(const ArgsManager& argsman, const CChainParams& chainparams, kernel::MemPoolOptions& mempool_opts);
2525

2626

2727
#endif // BITCOIN_NODE_MEMPOOL_ARGS_H

src/test/util/setup_common.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,8 @@ CTxMemPool::Options MemPoolOptionsForTest(const NodeContext& node)
169169
// chainparams.DefaultConsistencyChecks for tests
170170
.check_ratio = 1,
171171
};
172-
const auto err{ApplyArgsManOptions(*node.args, ::Params(), mempool_opts)};
173-
Assert(!err);
172+
auto result = ApplyArgsManOptions(*node.args, ::Params(), mempool_opts);
173+
Assert(result);
174174
return mempool_opts;
175175
}
176176

src/txdb.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,22 @@ static constexpr uint8_t DB_COINS{'c'};
3131
static constexpr uint8_t DB_TXINDEX_BLOCK{'T'};
3232
// uint8_t DB_TXINDEX{'t'}
3333

34-
std::optional<bilingual_str> CheckLegacyTxindex(CBlockTreeDB& block_tree_db)
34+
util::Result<void> CheckLegacyTxindex(CBlockTreeDB& block_tree_db)
3535
{
3636
CBlockLocator ignored{};
3737
if (block_tree_db.Read(DB_TXINDEX_BLOCK, ignored)) {
38-
return _("The -txindex upgrade started by a previous version cannot be completed. Restart with the previous version or run a full -reindex.");
38+
return util::Error{_("The -txindex upgrade started by a previous version cannot be completed. Restart with the previous version or run a full -reindex.")};
3939
}
4040
bool txindex_legacy_flag{false};
4141
block_tree_db.ReadFlag("txindex", txindex_legacy_flag);
4242
if (txindex_legacy_flag) {
4343
// Disable legacy txindex and warn once about occupied disk space
4444
if (!block_tree_db.WriteFlag("txindex", false)) {
45-
return Untranslated("Failed to write block index db flag 'txindex'='0'");
45+
return util::Error{Untranslated("Failed to write block index db flag 'txindex'='0'")};
4646
}
47-
return _("The block index db contains a legacy 'txindex'. To clear the occupied disk space, run a full -reindex, otherwise ignore this error. This error message will not be displayed again.");
47+
return util::Error{_("The block index db contains a legacy 'txindex'. To clear the occupied disk space, run a full -reindex, otherwise ignore this error. This error message will not be displayed again.")};
4848
}
49-
return std::nullopt;
49+
return {};
5050
}
5151

5252
bool CCoinsViewDB::NeedsUpgrade()

0 commit comments

Comments
 (0)