Skip to content

Commit 080268d

Browse files
committed
refactor: Replace std::optional<bilingual_str> with util::Result
1 parent 3a7b06c commit 080268d

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
@@ -181,10 +181,10 @@ void ReadFromStream(AddrMan& addr, CDataStream& ssPeers)
181181
DeserializeDB(ssPeers, addr, false);
182182
}
183183

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

189189
const auto start{SteadyClock::now()};
190190
const auto path_addr{args.GetDataDirNet() / "peers.dat"};
@@ -198,19 +198,17 @@ std::optional<bilingual_str> LoadAddrman(const NetGroupManager& netgroupman, con
198198
DumpPeerAddresses(args, *addrman);
199199
} catch (const InvalidAddrManVersionError&) {
200200
if (!RenameOver(path_addr, (fs::path)path_addr + ".bak")) {
201-
addrman = nullptr;
202-
return strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."));
201+
return util::Error{strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."))};
203202
}
204203
// Addrman can be in an inconsistent state after failure, reset it
205204
addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman);
206205
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)));
207206
DumpPeerAddresses(args, *addrman);
208207
} catch (const std::exception& e) {
209-
addrman = nullptr;
210-
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."),
211-
e.what(), PACKAGE_BUGREPORT, fs::quoted(fs::PathToString(path_addr)));
208+
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."),
209+
e.what(), PACKAGE_BUGREPORT, fs::quoted(fs::PathToString(path_addr)))};
212210
}
213-
return std::nullopt;
211+
return addrman;
214212
}
215213

216214
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));
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
@@ -1077,8 +1077,9 @@ static bool LockDataDirectory(bool probeOnly)
10771077
bool AppInitSanityChecks(const kernel::Context& kernel)
10781078
{
10791079
// ********************************************************* Step 4: sanity checks
1080-
if (auto error = kernel::SanityChecks(kernel)) {
1081-
InitError(*error);
1080+
auto result = kernel::SanityChecks(kernel);
1081+
if (!result) {
1082+
InitError(util::ErrorString(result));
10821083
return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME));
10831084
}
10841085

@@ -1253,9 +1254,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
12531254
// Initialize addrman
12541255
assert(!node.addrman);
12551256
uiInterface.InitMessage(_("Loading P2P addresses…").translated);
1256-
if (const auto error{LoadAddrman(*node.netgroupman, args, node.addrman)}) {
1257-
return InitError(*error);
1258-
}
1257+
auto addrman = LoadAddrman(*node.netgroupman, args);
1258+
if (!addrman) return InitError(util::ErrorString(addrman));
1259+
node.addrman = std::move(*addrman);
12591260
}
12601261

12611262
assert(!node.banman);
@@ -1475,8 +1476,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
14751476
.estimator = node.fee_estimator.get(),
14761477
.check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
14771478
};
1478-
if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
1479-
return InitError(*err);
1479+
auto result = ApplyArgsManOptions(args, chainparams, mempool_opts);
1480+
if (!result) {
1481+
return InitError(util::ErrorString(result));
14801482
}
14811483
mempool_opts.check_ratio = std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
14821484

@@ -1572,8 +1574,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
15721574

15731575
// ********************************************************* Step 8: start indexers
15741576
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1575-
if (const auto error{WITH_LOCK(cs_main, return CheckLegacyTxindex(*Assert(chainman.m_blockman.m_block_tree_db)))}) {
1576-
return InitError(*error);
1577+
auto result = WITH_LOCK(cs_main, return CheckLegacyTxindex(*Assert(chainman.m_blockman.m_block_tree_db)));
1578+
if (!result) {
1579+
return InitError(util::ErrorString(result));
15771580
}
15781581

15791582
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/txmempool.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ CTxMemPool::Options MemPoolOptionsForTest(const NodeContext& node)
2222
// chainparams.DefaultConsistencyChecks for tests
2323
.check_ratio = 1,
2424
};
25-
const auto err{ApplyArgsManOptions(*node.args, ::Params(), mempool_opts)};
26-
Assert(!err);
25+
const auto result{ApplyArgsManOptions(*node.args, ::Params(), mempool_opts)};
26+
Assert(result);
2727
return mempool_opts;
2828
}
2929

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)