From aa1567f868b7a12587d0ed42efc4ec3d48579cbd Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 17 Jul 2020 18:29:04 +1200 Subject: [PATCH] Replace boost::optional with std::optional --- src/chain.h | 27 ++-- src/chainparams.cpp | 3 +- src/consensus/funding.cpp | 6 +- src/consensus/params.h | 9 +- src/consensus/upgrades.cpp | 12 +- src/consensus/upgrades.h | 10 +- src/crypto/equihash.cpp | 9 +- src/experimental_features.cpp | 4 +- src/experimental_features.h | 4 +- src/gtest/test_checktransaction.cpp | 4 +- src/gtest/test_foundersreward.cpp | 4 +- src/gtest/test_mempoollimit.cpp | 8 +- src/gtest/test_noteencryption.cpp | 35 ++--- src/gtest/test_pow.cpp | 2 +- src/gtest/test_sapling_note.cpp | 2 +- src/gtest/test_upgrades.cpp | 50 +++---- src/gtest/test_validation.cpp | 16 ++- src/gtest/test_zip32.cpp | 2 +- src/init.cpp | 2 +- src/main.cpp | 32 ++--- src/main.h | 3 +- src/mempool_limit.cpp | 4 +- src/mempool_limit.h | 4 +- src/metrics.cpp | 6 +- src/metrics.h | 3 +- src/miner.cpp | 8 +- src/miner.h | 1 - src/net.cpp | 2 +- src/pow.cpp | 4 +- src/rpc/blockchain.cpp | 9 +- src/serialize.h | 13 +- src/test/serialize_tests.cpp | 10 +- src/transaction_builder.cpp | 40 +++--- src/transaction_builder.h | 14 +- src/txmempool.cpp | 8 +- src/utiltest.cpp | 2 +- src/validationinterface.cpp | 2 +- src/validationinterface.h | 6 +- src/wallet/asyncrpcoperation_common.cpp | 12 +- src/wallet/asyncrpcoperation_common.h | 13 +- .../asyncrpcoperation_mergetoaddress.cpp | 38 +++--- src/wallet/asyncrpcoperation_mergetoaddress.h | 9 +- .../asyncrpcoperation_saplingmigration.cpp | 7 +- src/wallet/asyncrpcoperation_sendmany.cpp | 30 ++--- src/wallet/asyncrpcoperation_sendmany.h | 9 +- .../asyncrpcoperation_shieldcoinbase.cpp | 5 +- src/wallet/gtest/test_wallet.cpp | 70 +++++----- src/wallet/gtest/test_wallet_zkeys.cpp | 6 +- src/wallet/rpcdump.cpp | 9 +- src/wallet/rpcwallet.cpp | 11 +- src/wallet/test/rpc_wallet_tests.cpp | 49 +++---- src/wallet/wallet.cpp | 124 +++++++++--------- src/wallet/wallet.h | 48 +++---- src/zcash/IncrementalMerkleTree.cpp | 16 +-- src/zcash/IncrementalMerkleTree.hpp | 11 +- src/zcash/Note.cpp | 84 ++++++------ src/zcash/Note.hpp | 24 ++-- src/zcash/NoteEncryption.cpp | 24 ++-- src/zcash/NoteEncryption.hpp | 11 +- src/zcash/address/sapling.cpp | 6 +- src/zcash/address/sapling.hpp | 4 +- src/zcash/address/zip32.cpp | 10 +- src/zcash/address/zip32.h | 6 +- src/zcbenchmarks.cpp | 6 +- 64 files changed, 531 insertions(+), 491 deletions(-) diff --git a/src/chain.h b/src/chain.h index 06052986b..01dbf090d 100644 --- a/src/chain.h +++ b/src/chain.h @@ -12,6 +12,7 @@ #include "tinyformat.h" #include "uint256.h" +#include #include static const int SPROUT_VALUE_VERSION = 1001400; @@ -228,7 +229,7 @@ class CBlockIndex //! Branch ID corresponding to the consensus rules used to validate this block. //! Only cached if block validity is BLOCK_VALID_CONSENSUS. //! Persisted at each activation height, memory-only for intervening blocks. - boost::optional nCachedBranchId; + std::optional nCachedBranchId; //! The anchor for the tree state up to the start of this block uint256 hashSproutAnchor; @@ -237,22 +238,22 @@ class CBlockIndex uint256 hashFinalSproutRoot; //! Change in value held by the Sprout circuit over this block. - //! Will be boost::none for older blocks on old nodes until a reindex has taken place. - boost::optional nSproutValue; + //! Will be std::nullopt for older blocks on old nodes until a reindex has taken place. + std::optional nSproutValue; //! (memory only) Total value held by the Sprout circuit up to and including this block. - //! Will be boost::none for on old nodes until a reindex has taken place. - //! Will be boost::none if nChainTx is zero. - boost::optional nChainSproutValue; + //! Will be std::nullopt for on old nodes until a reindex has taken place. + //! Will be std::nullopt if nChainTx is zero. + std::optional nChainSproutValue; //! Change in value held by the Sapling circuit over this block. - //! Not a boost::optional because this was added before Sapling activated, so we can + //! Not a std::optional because this was added before Sapling activated, so we can //! rely on the invariant that every block before this was added had nSaplingValue = 0. CAmount nSaplingValue; //! (memory only) Total value held by the Sapling circuit up to and including this block. - //! Will be boost::none if nChainTx is zero. - boost::optional nChainSaplingValue; + //! Will be std::nullopt if nChainTx is zero. + std::optional nChainSaplingValue; //! Root of the Sapling commitment tree as of the end of this block. //! @@ -295,14 +296,14 @@ class CBlockIndex nTx = 0; nChainTx = 0; nStatus = 0; - nCachedBranchId = boost::none; + nCachedBranchId = std::nullopt; hashSproutAnchor = uint256(); hashFinalSproutRoot = uint256(); nSequenceId = 0; - nSproutValue = boost::none; - nChainSproutValue = boost::none; + nSproutValue = std::nullopt; + nChainSproutValue = std::nullopt; nSaplingValue = 0; - nChainSaplingValue = boost::none; + nChainSaplingValue = std::nullopt; nVersion = 0; hashMerkleRoot = uint256(); diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 033db870e..3d39006e4 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -13,6 +13,7 @@ #include "utilstrencodings.h" #include +#include #include #include @@ -104,7 +105,7 @@ class CMainParams : public CChainParams { consensus.nPowMaxAdjustUp = 16; // 16% adjustment up consensus.nPreBlossomPowTargetSpacing = Consensus::PRE_BLOSSOM_POW_TARGET_SPACING; consensus.nPostBlossomPowTargetSpacing = Consensus::POST_BLOSSOM_POW_TARGET_SPACING; - consensus.nPowAllowMinDifficultyBlocksAfterHeight = boost::none; + consensus.nPowAllowMinDifficultyBlocksAfterHeight = std::nullopt; consensus.vUpgrades[Consensus::BASE_SPROUT].nProtocolVersion = 170002; consensus.vUpgrades[Consensus::BASE_SPROUT].nActivationHeight = Consensus::NetworkUpgrade::ALWAYS_ACTIVE; diff --git a/src/consensus/funding.cpp b/src/consensus/funding.cpp index 79dffb631..4b32d3fd8 100644 --- a/src/consensus/funding.cpp +++ b/src/consensus/funding.cpp @@ -48,9 +48,9 @@ std::set GetActiveFundingStreamElements( // in the definition of vFundingStreams. auto fs = params.vFundingStreams[idx]; // Funding period is [startHeight, endHeight) - if (fs && nHeight >= fs.get().GetStartHeight() && nHeight < fs.get().GetEndHeight()) { + if (fs && nHeight >= fs.value().GetStartHeight() && nHeight < fs.value().GetEndHeight()) { requiredElements.insert(std::make_pair( - fs.get().RecipientAddress(params, nHeight), + fs.value().RecipientAddress(params, nHeight), FundingStreamInfo[idx].Value(blockSubsidy))); } } @@ -64,7 +64,7 @@ std::vector GetActiveFundingStreams( std::vector activeStreams; for (uint32_t idx = Consensus::FIRST_FUNDING_STREAM; idx < Consensus::MAX_FUNDING_STREAMS; idx++) { auto fs = params.vFundingStreams[idx]; - if (fs && nHeight >= fs.get().GetStartHeight() && nHeight < fs.get().GetEndHeight()) { + if (fs && nHeight >= fs.value().GetStartHeight() && nHeight < fs.value().GetEndHeight()) { activeStreams.push_back(FundingStreamInfo[idx]); } } diff --git a/src/consensus/params.h b/src/consensus/params.h index 7ff4a3c2d..9e13625ac 100644 --- a/src/consensus/params.h +++ b/src/consensus/params.h @@ -11,10 +11,9 @@ #include "key_constants.h" #include +#include #include -#include - namespace Consensus { // Early declaration to ensure it is accessible. @@ -80,7 +79,7 @@ struct NetworkUpgrade { * scrutiny than regular releases. nMinimumChainWork MUST be set to at least the chain * work of this block, otherwise this detection will have false positives. */ - boost::optional hashActivationBlock; + std::optional hashActivationBlock; }; typedef std::variant FundingStreamAddress; @@ -211,7 +210,7 @@ struct Params { NetworkUpgrade vUpgrades[MAX_NETWORK_UPGRADES]; int nFundingPeriodLength; - boost::optional vFundingStreams[MAX_FUNDING_STREAMS]; + std::optional vFundingStreams[MAX_FUNDING_STREAMS]; void AddZIP207FundingStream( const KeyConstants& keyConstants, FundingStreamIndex idx, @@ -263,7 +262,7 @@ struct Params { unsigned int nEquihashN = 0; unsigned int nEquihashK = 0; uint256 powLimit; - boost::optional nPowAllowMinDifficultyBlocksAfterHeight; + std::optional nPowAllowMinDifficultyBlocksAfterHeight; int64_t nPowAveragingWindow; int64_t nPowMaxAdjustDown; int64_t nPowMaxAdjustUp; diff --git a/src/consensus/upgrades.cpp b/src/consensus/upgrades.cpp index 1825e9f8a..29f8acce7 100644 --- a/src/consensus/upgrades.cpp +++ b/src/consensus/upgrades.cpp @@ -140,9 +140,9 @@ bool IsActivationHeightForAnyUpgrade( return false; } -boost::optional NextEpoch(int nHeight, const Consensus::Params& params) { +std::optional NextEpoch(int nHeight, const Consensus::Params& params) { if (nHeight < 0) { - return boost::none; + return std::nullopt; } // Sprout is never pending @@ -152,16 +152,16 @@ boost::optional NextEpoch(int nHeight, const Consensus::Params& params) { } } - return boost::none; + return std::nullopt; } -boost::optional NextActivationHeight( +std::optional NextActivationHeight( int nHeight, const Consensus::Params& params) { auto idx = NextEpoch(nHeight, params); if (idx) { - return params.vUpgrades[idx.get()].nActivationHeight; + return params.vUpgrades[idx.value()].nActivationHeight; } - return boost::none; + return std::nullopt; } diff --git a/src/consensus/upgrades.h b/src/consensus/upgrades.h index e8ed40daa..812c0ad18 100644 --- a/src/consensus/upgrades.h +++ b/src/consensus/upgrades.h @@ -7,7 +7,7 @@ #include "consensus/params.h" -#include +#include enum UpgradeState { UPGRADE_DISABLED, @@ -83,15 +83,15 @@ bool IsActivationHeightForAnyUpgrade( /** * Returns the index of the next upgrade after the given block height, or - * boost::none if there are no more known upgrades. + * std::nullopt if there are no more known upgrades. */ -boost::optional NextEpoch(int nHeight, const Consensus::Params& params); +std::optional NextEpoch(int nHeight, const Consensus::Params& params); /** * Returns the activation height for the next upgrade after the given block height, - * or boost::none if there are no more known upgrades. + * or std::nullopt if there are no more known upgrades. */ -boost::optional NextActivationHeight( +std::optional NextActivationHeight( int nHeight, const Consensus::Params& params); diff --git a/src/crypto/equihash.cpp b/src/crypto/equihash.cpp index c00fd6ffa..c7ea9ba58 100644 --- a/src/crypto/equihash.cpp +++ b/src/crypto/equihash.cpp @@ -24,10 +24,9 @@ #include #include +#include #include -#include - static EhSolverCancelledException solver_cancelled; eh_HashState::eh_HashState( @@ -657,7 +656,7 @@ bool Equihash::OptimisedSolve(const eh_HashState& base_state, size_t hashLen; size_t lenIndices; unsigned char tmpHash[HashOutput]; - std::vector>>> X; + std::vector>>> X; X.reserve(K+1); // 3) Repeat steps 1 and 2 for each partial index @@ -675,7 +674,7 @@ bool Equihash::OptimisedSolve(const eh_HashState& base_state, N/8, HashLength, CollisionBitLength, newIndex); if (cancelled(PartialGeneration)) throw solver_cancelled; } - boost::optional>> ic = icv; + std::optional>> ic = icv; // 2a) For each pair of lists: hashLen = HashLength; @@ -700,7 +699,7 @@ bool Equihash::OptimisedSolve(const eh_HashState& base_state, if (ic->size() == 0) goto invalidsolution; - X[r] = boost::none; + X[r] = std::nullopt; hashLen -= CollisionByteLength; lenIndices *= 2; rti = lti; diff --git a/src/experimental_features.cpp b/src/experimental_features.cpp index 93a4fd2ed..67afbf7fc 100644 --- a/src/experimental_features.cpp +++ b/src/experimental_features.cpp @@ -12,7 +12,7 @@ bool fExperimentalPaymentDisclosure = false; bool fExperimentalInsightExplorer = false; bool fExperimentalLightWalletd = false; -boost::optional InitExperimentalMode() +std::optional InitExperimentalMode() { auto fExperimentalMode = GetBoolArg("-experimentalfeatures", false); fExperimentalDeveloperEncryptWallet = GetBoolArg("-developerencryptwallet", false); @@ -35,7 +35,7 @@ boost::optional InitExperimentalMode() return _("Light Walletd requires -experimentalfeatures."); } } - return boost::none; + return std::nullopt; } std::vector GetExperimentalFeatures() diff --git a/src/experimental_features.h b/src/experimental_features.h index 6511022c6..390cb7d0e 100644 --- a/src/experimental_features.h +++ b/src/experimental_features.h @@ -2,9 +2,9 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php . +#include #include #include -#include extern bool fExperimentalDeveloperEncryptWallet; extern bool fExperimentalDeveloperSetPoolSizeZero; @@ -12,5 +12,5 @@ extern bool fExperimentalPaymentDisclosure; extern bool fExperimentalInsightExplorer; extern bool fExperimentalLightWalletd; -boost::optional InitExperimentalMode(); +std::optional InitExperimentalMode(); std::vector GetExperimentalFeatures(); diff --git a/src/gtest/test_checktransaction.cpp b/src/gtest/test_checktransaction.cpp index 31945a6cf..1e2338be9 100644 --- a/src/gtest/test_checktransaction.cpp +++ b/src/gtest/test_checktransaction.cpp @@ -1138,7 +1138,7 @@ TEST(ChecktransactionTests, HeartwoodAcceptsShieldedCoinbase) { auto output = OutputDescriptionInfo(ovk, note, {{0xF6}}); auto ctx = librustzcash_sapling_proving_ctx_init(); - auto odesc = output.Build(ctx).get(); + auto odesc = output.Build(ctx).value(); librustzcash_sapling_proving_ctx_free(ctx); CMutableTransaction mtx = GetValidTransaction(); @@ -1244,7 +1244,7 @@ TEST(ChecktransactionTests, HeartwoodEnforcesSaplingRulesOnShieldedCoinbase) { // Add a Sapling output. auto ctx = librustzcash_sapling_proving_ctx_init(); - auto odesc = output.Build(ctx).get(); + auto odesc = output.Build(ctx).value(); librustzcash_sapling_proving_ctx_free(ctx); mtx.vShieldedOutput.push_back(odesc); diff --git a/src/gtest/test_foundersreward.cpp b/src/gtest/test_foundersreward.cpp index 72bdc9fe7..498b15fbd 100644 --- a/src/gtest/test_foundersreward.cpp +++ b/src/gtest/test_foundersreward.cpp @@ -105,8 +105,8 @@ void checkNumberOfUniqueAddresses(int nUnique) { int GetMaxFundingStreamHeight(const Consensus::Params& params) { int result = 0; for (auto fs : params.vFundingStreams) { - if (fs && result < fs.get().GetEndHeight() - 1) { - result = fs.get().GetEndHeight() - 1; + if (fs && result < fs.value().GetEndHeight() - 1) { + result = fs.value().GetEndHeight() - 1; } } diff --git a/src/gtest/test_mempoollimit.cpp b/src/gtest/test_mempoollimit.cpp index 380bb3097..c62aa609f 100644 --- a/src/gtest/test_mempoollimit.cpp +++ b/src/gtest/test_mempoollimit.cpp @@ -94,13 +94,13 @@ TEST(MempoolLimitTests, WeightedTxTreeCheckSizeAfterDropping) tree.add(WeightedTxInfo(TX_ID2, TxWeight(MIN_TX_COST, MIN_TX_COST))); EXPECT_EQ(8000, tree.getTotalWeight().cost); EXPECT_EQ(8000, tree.getTotalWeight().evictionWeight); - EXPECT_FALSE(tree.maybeDropRandom().is_initialized()); + EXPECT_FALSE(tree.maybeDropRandom().has_value()); tree.add(WeightedTxInfo(TX_ID3, TxWeight(MIN_TX_COST, MIN_TX_COST + LOW_FEE_PENALTY))); EXPECT_EQ(12000, tree.getTotalWeight().cost); EXPECT_EQ(12000 + LOW_FEE_PENALTY, tree.getTotalWeight().evictionWeight); - boost::optional drop = tree.maybeDropRandom(); - ASSERT_TRUE(drop.is_initialized()); - uint256 txid = drop.get(); + auto drop = tree.maybeDropRandom(); + ASSERT_TRUE(drop.has_value()); + uint256 txid = drop.value(); testedDropping.insert(txid); // Do not continue to test if a particular trial fails ASSERT_EQ(8000, tree.getTotalWeight().cost); diff --git a/src/gtest/test_noteencryption.cpp b/src/gtest/test_noteencryption.cpp index a9b19f184..5e46fa9b8 100644 --- a/src/gtest/test_noteencryption.cpp +++ b/src/gtest/test_noteencryption.cpp @@ -2,6 +2,7 @@ #include "sodium.h" #include +#include #include #include "zcash/Note.hpp" @@ -50,7 +51,7 @@ TEST(NoteEncryption, NotePlaintext) if (!cmu_opt) { FAIL(); } - uint256 cmu = cmu_opt.get(); + uint256 cmu = cmu_opt.value(); SaplingNotePlaintext pt(note, memo); auto res = pt.encrypt(addr.pk_d); @@ -58,7 +59,7 @@ TEST(NoteEncryption, NotePlaintext) FAIL(); } - auto enc = res.get(); + auto enc = res.value(); auto ct = enc.first; auto encryptor = enc.second; @@ -88,7 +89,7 @@ TEST(NoteEncryption, NotePlaintext) FAIL(); } - auto bar = foo.get(); + auto bar = foo.value(); ASSERT_TRUE(bar.value() == pt.value()); ASSERT_TRUE(bar.memo() == pt.memo()); @@ -101,7 +102,7 @@ TEST(NoteEncryption, NotePlaintext) FAIL(); } - auto new_note = foobar.get(); + auto new_note = foobar.value(); ASSERT_TRUE(note.value() == new_note.value()); ASSERT_TRUE(note.d == new_note.d); @@ -136,7 +137,7 @@ TEST(NoteEncryption, NotePlaintext) FAIL(); } - auto decrypted_out_ct_unwrapped = decrypted_out_ct.get(); + auto decrypted_out_ct_unwrapped = decrypted_out_ct.value(); ASSERT_TRUE(decrypted_out_ct_unwrapped.pk_d == out_pt.pk_d); ASSERT_TRUE(decrypted_out_ct_unwrapped.esk == out_pt.esk); @@ -169,7 +170,7 @@ TEST(NoteEncryption, NotePlaintext) FAIL(); } - bar = foo.get(); + bar = foo.value(); ASSERT_TRUE(bar.value() == pt.value()); ASSERT_TRUE(bar.memo() == pt.memo()); @@ -210,7 +211,7 @@ TEST(NoteEncryption, RejectsInvalidNoteZip212Enabled) if (!cmu_opt) { FAIL(); } - uint256 cmu = cmu_opt.get(); + uint256 cmu = cmu_opt.value(); SaplingNotePlaintext pt(note, memo); auto res = pt.encrypt(addr.pk_d); @@ -218,7 +219,7 @@ TEST(NoteEncryption, RejectsInvalidNoteZip212Enabled) FAIL(); } - auto enc = res.get(); + auto enc = res.value(); auto ct = enc.first; auto encryptor = enc.second; @@ -241,7 +242,7 @@ TEST(NoteEncryption, RejectsInvalidNoteZip212Enabled) if (!cmu_opt) { FAIL(); } - uint256 cmu = cmu_opt.get(); + uint256 cmu = cmu_opt.value(); SaplingNotePlaintext pt(note, memo); auto res = pt.encrypt(addr.pk_d); @@ -249,7 +250,7 @@ TEST(NoteEncryption, RejectsInvalidNoteZip212Enabled) FAIL(); } - auto enc = res.get(); + auto enc = res.value(); auto ct = enc.first; auto encryptor = enc.second; @@ -301,7 +302,7 @@ TEST(NoteEncryption, AcceptsValidNoteZip212Enabled) if (!cmu_opt) { FAIL(); } - uint256 cmu = cmu_opt.get(); + uint256 cmu = cmu_opt.value(); SaplingNotePlaintext pt(note, memo); auto res = pt.encrypt(addr.pk_d); @@ -309,7 +310,7 @@ TEST(NoteEncryption, AcceptsValidNoteZip212Enabled) FAIL(); } - auto enc = res.get(); + auto enc = res.value(); auto ct = enc.first; auto encryptor = enc.second; @@ -343,7 +344,7 @@ TEST(NoteEncryption, AcceptsValidNoteZip212Enabled) if (!cmu_opt) { FAIL(); } - uint256 cmu = cmu_opt.get(); + uint256 cmu = cmu_opt.value(); SaplingNotePlaintext pt(note, memo); auto res = pt.encrypt(addr.pk_d); @@ -351,7 +352,7 @@ TEST(NoteEncryption, AcceptsValidNoteZip212Enabled) FAIL(); } - auto enc = res.get(); + auto enc = res.value(); auto ct = enc.first; auto encryptor = enc.second; @@ -380,7 +381,7 @@ TEST(NoteEncryption, AcceptsValidNoteZip212Enabled) if (!cmu_opt) { FAIL(); } - uint256 cmu = cmu_opt.get(); + uint256 cmu = cmu_opt.value(); SaplingNotePlaintext pt(note, memo); auto res = pt.encrypt(addr.pk_d); @@ -388,7 +389,7 @@ TEST(NoteEncryption, AcceptsValidNoteZip212Enabled) FAIL(); } - auto enc = res.get(); + auto enc = res.value(); auto ct = enc.first; auto encryptor = enc.second; @@ -442,7 +443,7 @@ TEST(NoteEncryption, SaplingApi) librustzcash_sapling_generate_r(esk.begin()); // Invalid diversifier - ASSERT_EQ(boost::none, SaplingNoteEncryption::FromDiversifier({1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, esk)); + ASSERT_EQ(std::nullopt, SaplingNoteEncryption::FromDiversifier({1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, esk)); // Encrypt to pk_1 auto enc = *SaplingNoteEncryption::FromDiversifier(pk_1.d, esk); diff --git a/src/gtest/test_pow.cpp b/src/gtest/test_pow.cpp index 709296f78..ba5e05607 100644 --- a/src/gtest/test_pow.cpp +++ b/src/gtest/test_pow.cpp @@ -93,7 +93,7 @@ TEST(PoW, MinDifficultyRules) { std::vector blocks(lastBlk+1); for (int i = 0; i <= lastBlk; i++) { blocks[i].pprev = i ? &blocks[i - 1] : nullptr; - blocks[i].nHeight = params.nPowAllowMinDifficultyBlocksAfterHeight.get() + i; + blocks[i].nHeight = params.nPowAllowMinDifficultyBlocksAfterHeight.value() + i; blocks[i].nTime = i ? blocks[i - 1].nTime + params.PoWTargetSpacing(i) : 1269211443; blocks[i].nBits = 0x1e7fffff; /* target 0x007fffff000... */ blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0); diff --git a/src/gtest/test_sapling_note.cpp b/src/gtest/test_sapling_note.cpp index ca1fece7c..5eeb2fa83 100644 --- a/src/gtest/test_sapling_note.cpp +++ b/src/gtest/test_sapling_note.cpp @@ -45,7 +45,7 @@ TEST(SaplingNote, TestVectors) // Test commitment SaplingNote note = SaplingNote(diversifier, pk_d, v, r, Zip212Enabled::BeforeZip212); - ASSERT_EQ(note.cmu().get(), cm); + ASSERT_EQ(note.cmu().value(), cm); // Test nullifier SaplingSpendingKey spendingKey(sk); diff --git a/src/gtest/test_upgrades.cpp b/src/gtest/test_upgrades.cpp index b33317288..d7ff0d791 100644 --- a/src/gtest/test_upgrades.cpp +++ b/src/gtest/test_upgrades.cpp @@ -3,7 +3,7 @@ #include "chainparams.h" #include "consensus/upgrades.h" -#include +#include class UpgradesTest : public ::testing::Test { protected: @@ -148,28 +148,28 @@ TEST_F(UpgradesTest, NextEpoch) { const Consensus::Params& params = Params().GetConsensus(); // Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT - EXPECT_EQ(NextEpoch(-1, params), boost::none); - EXPECT_EQ(NextEpoch(0, params), boost::none); - EXPECT_EQ(NextEpoch(1, params), boost::none); - EXPECT_EQ(NextEpoch(1000000, params), boost::none); + EXPECT_EQ(NextEpoch(-1, params), std::nullopt); + EXPECT_EQ(NextEpoch(0, params), std::nullopt); + EXPECT_EQ(NextEpoch(1, params), std::nullopt); + EXPECT_EQ(NextEpoch(1000000, params), std::nullopt); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, Consensus::NetworkUpgrade::ALWAYS_ACTIVE); - EXPECT_EQ(NextEpoch(-1, params), boost::none); - EXPECT_EQ(NextEpoch(0, params), boost::none); - EXPECT_EQ(NextEpoch(1, params), boost::none); - EXPECT_EQ(NextEpoch(1000000, params), boost::none); + EXPECT_EQ(NextEpoch(-1, params), std::nullopt); + EXPECT_EQ(NextEpoch(0, params), std::nullopt); + EXPECT_EQ(NextEpoch(1, params), std::nullopt); + EXPECT_EQ(NextEpoch(1000000, params), std::nullopt); int nActivationHeight = 100; UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, nActivationHeight); - EXPECT_EQ(NextEpoch(-1, params), boost::none); + EXPECT_EQ(NextEpoch(-1, params), std::nullopt); EXPECT_EQ(NextEpoch(0, params), static_cast(Consensus::UPGRADE_TESTDUMMY)); EXPECT_EQ(NextEpoch(1, params), static_cast(Consensus::UPGRADE_TESTDUMMY)); EXPECT_EQ(NextEpoch(nActivationHeight - 1, params), static_cast(Consensus::UPGRADE_TESTDUMMY)); - EXPECT_EQ(NextEpoch(nActivationHeight, params), boost::none); - EXPECT_EQ(NextEpoch(nActivationHeight + 1, params), boost::none); - EXPECT_EQ(NextEpoch(1000000, params), boost::none); + EXPECT_EQ(NextEpoch(nActivationHeight, params), std::nullopt); + EXPECT_EQ(NextEpoch(nActivationHeight + 1, params), std::nullopt); + EXPECT_EQ(NextEpoch(1000000, params), std::nullopt); } TEST_F(UpgradesTest, NextActivationHeight) { @@ -177,26 +177,26 @@ TEST_F(UpgradesTest, NextActivationHeight) { const Consensus::Params& params = Params().GetConsensus(); // Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT - EXPECT_EQ(NextActivationHeight(-1, params), boost::none); - EXPECT_EQ(NextActivationHeight(0, params), boost::none); - EXPECT_EQ(NextActivationHeight(1, params), boost::none); - EXPECT_EQ(NextActivationHeight(1000000, params), boost::none); + EXPECT_EQ(NextActivationHeight(-1, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(0, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(1, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(1000000, params), std::nullopt); UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, Consensus::NetworkUpgrade::ALWAYS_ACTIVE); - EXPECT_EQ(NextActivationHeight(-1, params), boost::none); - EXPECT_EQ(NextActivationHeight(0, params), boost::none); - EXPECT_EQ(NextActivationHeight(1, params), boost::none); - EXPECT_EQ(NextActivationHeight(1000000, params), boost::none); + EXPECT_EQ(NextActivationHeight(-1, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(0, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(1, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(1000000, params), std::nullopt); int nActivationHeight = 100; UpdateNetworkUpgradeParameters(Consensus::UPGRADE_TESTDUMMY, nActivationHeight); - EXPECT_EQ(NextActivationHeight(-1, params), boost::none); + EXPECT_EQ(NextActivationHeight(-1, params), std::nullopt); EXPECT_EQ(NextActivationHeight(0, params), nActivationHeight); EXPECT_EQ(NextActivationHeight(1, params), nActivationHeight); EXPECT_EQ(NextActivationHeight(nActivationHeight - 1, params), nActivationHeight); - EXPECT_EQ(NextActivationHeight(nActivationHeight, params), boost::none); - EXPECT_EQ(NextActivationHeight(nActivationHeight + 1, params), boost::none); - EXPECT_EQ(NextActivationHeight(1000000, params), boost::none); + EXPECT_EQ(NextActivationHeight(nActivationHeight, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(nActivationHeight + 1, params), std::nullopt); + EXPECT_EQ(NextActivationHeight(1000000, params), std::nullopt); } diff --git a/src/gtest/test_validation.cpp b/src/gtest/test_validation.cpp index fd48b49ed..f809a02b6 100644 --- a/src/gtest/test_validation.cpp +++ b/src/gtest/test_validation.cpp @@ -7,6 +7,8 @@ #include "transaction_builder.h" #include "utiltest.h" +#include + extern bool ReceivedBlockTransactions( const CBlock &block, CValidationState& state, @@ -14,7 +16,7 @@ extern bool ReceivedBlockTransactions( CBlockIndex *pindexNew, const CDiskBlockPos& pos); -void ExpectOptionalAmount(CAmount expected, boost::optional actual) { +void ExpectOptionalAmount(CAmount expected, std::optional actual) { EXPECT_TRUE((bool)actual); if (actual) { EXPECT_EQ(expected, *actual); @@ -24,7 +26,7 @@ void ExpectOptionalAmount(CAmount expected, boost::optional actual) { // Fake a view that optionally contains a single coin. class ValidationFakeCoinsViewDB : public CCoinsView { public: - boost::optional, std::pair>> coin; + std::optional, std::pair>> coin; ValidationFakeCoinsViewDB() {} ValidationFakeCoinsViewDB(uint256 blockHash, uint256 txid, CTxOut txOut, int nHeight) : @@ -43,11 +45,11 @@ class ValidationFakeCoinsViewDB : public CCoinsView { } bool GetCoins(const uint256 &txid, CCoins &coins) const { - if (coin && txid == coin.get().first.second) { + if (coin && txid == coin.value().first.second) { CCoins newCoins; newCoins.vout.resize(2); - newCoins.vout[0] = coin.get().second.first; - newCoins.nHeight = coin.get().second.second; + newCoins.vout[0] = coin.value().second.first; + newCoins.nHeight = coin.value().second.second; coins.swap(newCoins); return true; } else { @@ -56,7 +58,7 @@ class ValidationFakeCoinsViewDB : public CCoinsView { } bool HaveCoins(const uint256 &txid) const { - if (coin && txid == coin.get().first.second) { + if (coin && txid == coin.value().first.second) { return true; } else { return false; @@ -65,7 +67,7 @@ class ValidationFakeCoinsViewDB : public CCoinsView { uint256 GetBestBlock() const { if (coin) { - return coin.get().first.first; + return coin.value().first.first; } else { uint256 a; return a; diff --git a/src/gtest/test_zip32.cpp b/src/gtest/test_zip32.cpp index e7715fd03..c8ee5a335 100644 --- a/src/gtest/test_zip32.cpp +++ b/src/gtest/test_zip32.cpp @@ -109,7 +109,7 @@ TEST(ZIP32, TestVectors) { auto maybe_m_1_2hv_3 = m_1_2hv.Derive(3); EXPECT_TRUE(maybe_m_1_2hv_3); - auto m_1_2hv_3 = maybe_m_1_2hv_3.get(); + auto m_1_2hv_3 = maybe_m_1_2hv_3.value(); EXPECT_EQ(m_1_2hv_3.depth, 3); EXPECT_EQ(m_1_2hv_3.parentFVKTag, 0x7583c148); EXPECT_EQ(m_1_2hv_3.childIndex, 3); diff --git a/src/init.cpp b/src/init.cpp index a134755ca..9f005a438 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -935,7 +935,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) // Set this early so that experimental features are correctly enabled/disabled auto err = InitExperimentalMode(); if (err) { - return InitError(err.get()); + return InitError(err.value()); } // Make sure enough file descriptors are available diff --git a/src/main.cpp b/src/main.cpp index 3d92b028b..42ec6c108 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -87,7 +87,7 @@ uint64_t nPruneTarget = 0; bool fAlerts = DEFAULT_ALERTS; int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE; -boost::optional expiryDeltaArg = boost::none; +std::optional expiryDeltaArg = std::nullopt; CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE); CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE; @@ -1948,7 +1948,7 @@ bool IsInitialBlockDownload(const CChainParams& chainParams) // If an upgrade is active, we must be past its activation height. assert(chainActive[upgrade.nActivationHeight]); - if (chainActive[upgrade.nActivationHeight]->GetBlockHash() != upgrade.hashActivationBlock.get()) { + if (chainActive[upgrade.nActivationHeight]->GetBlockHash() != upgrade.hashActivationBlock.value()) { AbortNode( strprintf( "%s: We are on a chain with sufficient work, but the activation block hash for the %s network upgrade is not as expected.\n" @@ -1960,7 +1960,7 @@ bool IsInitialBlockDownload(const CChainParams& chainParams) chainParams.GetConsensus().nMinimumChainWork.GetHex(), chainActive.Height(), upgrade.nActivationHeight, - upgrade.hashActivationBlock.get().GetHex(), + upgrade.hashActivationBlock.value().GetHex(), chainActive[upgrade.nActivationHeight]->GetBlockHash().GetHex()), _("We are on a chain with sufficient work, but the network upgrade checkpoints do not match. Your node may be under attack! Shutting down for safety.")); return true; @@ -2548,7 +2548,7 @@ static DisconnectResult DisconnectBlock(const CBlock& block, CValidationState& s // This is guaranteed to be filled by LoadBlockIndex. assert(pindex->nCachedBranchId); - auto consensusBranchId = pindex->nCachedBranchId.get(); + auto consensusBranchId = pindex->nCachedBranchId.value(); if (chainparams.GetConsensus().NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_HEARTWOOD)) { view.PopHistoryNode(consensusBranchId); @@ -2749,7 +2749,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin // Sapling // // If we've reached ConnectBlock, we have all transactions of - // parents and can expect nChainSaplingValue not to be boost::none. + // parents and can expect nChainSaplingValue not to be std::nullopt. // However, the miner and mining RPCs may not have populated this // value and will call `TestBlockValidity`. So, we act // conditionally. @@ -3787,7 +3787,7 @@ void FallbackSproutValuePoolBalance( assert(*pindex->nChainSproutValue == chainparams.SproutValuePoolCheckpointBalance()); // And we should expect non-none for the delta stored in the block index here, // or the checkpoint is too early. - assert(pindex->nSproutValue != boost::none); + assert(pindex->nSproutValue != std::nullopt); } } else { LogPrintf( @@ -3823,9 +3823,9 @@ bool ReceivedBlockTransactions( } } pindexNew->nSproutValue = sproutValue; - pindexNew->nChainSproutValue = boost::none; + pindexNew->nChainSproutValue = std::nullopt; pindexNew->nSaplingValue = saplingValue; - pindexNew->nChainSaplingValue = boost::none; + pindexNew->nChainSaplingValue = std::nullopt; pindexNew->nFile = pos.nFile; pindexNew->nDataPos = pos.nPos; pindexNew->nUndoPos = 0; @@ -3847,12 +3847,12 @@ bool ReceivedBlockTransactions( if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) { pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue; } else { - pindex->nChainSproutValue = boost::none; + pindex->nChainSproutValue = std::nullopt; } if (pindex->pprev->nChainSaplingValue) { pindex->nChainSaplingValue = *pindex->pprev->nChainSaplingValue + pindex->nSaplingValue; } else { - pindex->nChainSaplingValue = boost::none; + pindex->nChainSaplingValue = std::nullopt; } } else { pindex->nChainSproutValue = pindex->nSproutValue; @@ -4579,17 +4579,17 @@ bool static LoadBlockIndexDB() if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) { pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue; } else { - pindex->nChainSproutValue = boost::none; + pindex->nChainSproutValue = std::nullopt; } if (pindex->pprev->nChainSaplingValue) { pindex->nChainSaplingValue = *pindex->pprev->nChainSaplingValue + pindex->nSaplingValue; } else { - pindex->nChainSaplingValue = boost::none; + pindex->nChainSaplingValue = std::nullopt; } } else { pindex->nChainTx = 0; - pindex->nChainSproutValue = boost::none; - pindex->nChainSaplingValue = boost::none; + pindex->nChainSproutValue = std::nullopt; + pindex->nChainSaplingValue = std::nullopt; mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex)); } } else { @@ -6893,7 +6893,7 @@ CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Para bool blossomActive = consensusParams.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_BLOSSOM); unsigned int defaultExpiryDelta = blossomActive ? DEFAULT_POST_BLOSSOM_TX_EXPIRY_DELTA : DEFAULT_PRE_BLOSSOM_TX_EXPIRY_DELTA; - mtx.nExpiryHeight = nHeight + (expiryDeltaArg ? expiryDeltaArg.get() : defaultExpiryDelta); + mtx.nExpiryHeight = nHeight + (expiryDeltaArg ? expiryDeltaArg.value() : defaultExpiryDelta); // mtx.nExpiryHeight == 0 is valid for coinbase transactions if (mtx.nExpiryHeight <= 0 || mtx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) { @@ -6905,7 +6905,7 @@ CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Para // TX_EXPIRING_SOON_THRESHOLD (3) blocks (for DoS mitigation) based on the current height. auto nextActivationHeight = NextActivationHeight(nHeight, consensusParams); if (nextActivationHeight) { - mtx.nExpiryHeight = std::min(mtx.nExpiryHeight, static_cast(nextActivationHeight.get()) - 1); + mtx.nExpiryHeight = std::min(mtx.nExpiryHeight, static_cast(nextActivationHeight.value()) - 1); } } return mtx; diff --git a/src/main.h b/src/main.h index fb0703273..ba44a49bf 100644 --- a/src/main.h +++ b/src/main.h @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -127,7 +128,7 @@ struct BlockHasher size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); } }; -extern boost::optional expiryDeltaArg; +extern std::optional expiryDeltaArg; extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern CTxMemPool mempool; diff --git a/src/mempool_limit.cpp b/src/mempool_limit.cpp index efa15a8c5..78c6e7320 100644 --- a/src/mempool_limit.cpp +++ b/src/mempool_limit.cpp @@ -118,11 +118,11 @@ void WeightedTxTree::remove(const uint256& txId) childWeights.pop_back(); } -boost::optional WeightedTxTree::maybeDropRandom() +std::optional WeightedTxTree::maybeDropRandom() { TxWeight totalTxWeight = getTotalWeight(); if (totalTxWeight.cost <= capacity) { - return boost::none; + return std::nullopt; } LogPrint("mempool", "Mempool cost limit exceeded (cost=%d, limit=%d)\n", totalTxWeight.cost, capacity); int randomWeight = GetRand(totalTxWeight.evictionWeight); diff --git a/src/mempool_limit.h b/src/mempool_limit.h index 3c4d77e13..e2b7c7147 100644 --- a/src/mempool_limit.h +++ b/src/mempool_limit.h @@ -7,10 +7,10 @@ #include #include +#include #include #include -#include "boost/optional.hpp" #include "primitives/transaction.h" #include "uint256.h" @@ -123,7 +123,7 @@ class WeightedTxTree // If the total cost limit is exceeded, pick a random number based on the total cost // of the collection and remove the associated transaction. - boost::optional maybeDropRandom(); + std::optional maybeDropRandom(); }; diff --git a/src/metrics.cpp b/src/metrics.cpp index 454960046..19807ea81 100644 --- a/src/metrics.cpp +++ b/src/metrics.cpp @@ -256,13 +256,13 @@ std::string DisplaySize(size_t value) return strprintf(_("%.2f TiB"), value / coef); } -boost::optional SecondsLeftToNextEpoch(const Consensus::Params& params, int currentHeight) +std::optional SecondsLeftToNextEpoch(const Consensus::Params& params, int currentHeight) { auto nextHeight = NextActivationHeight(currentHeight, params); if (nextHeight) { - return (nextHeight.get() - currentHeight) * params.PoWTargetSpacing(nextHeight.get() - 1); + return (nextHeight.value() - currentHeight) * params.PoWTargetSpacing(nextHeight.value() - 1); } else { - return boost::none; + return std::nullopt; } } diff --git a/src/metrics.h b/src/metrics.h index 2b21e1b6d..959601632 100644 --- a/src/metrics.h +++ b/src/metrics.h @@ -7,6 +7,7 @@ #include #include +#include #include struct AtomicCounter { @@ -72,7 +73,7 @@ void TrackMinedBlock(uint256 hash); void MarkStartTime(); double GetLocalSolPS(); int EstimateNetHeight(const Consensus::Params& params, int currentBlockHeight, int64_t currentBlockTime); -boost::optional SecondsLeftToNextEpoch(const Consensus::Params& params, int currentHeight); +std::optional SecondsLeftToNextEpoch(const Consensus::Params& params, int currentHeight); std::string DisplayDuration(int64_t time, DurationFormat format); void TriggerRefresh(); diff --git a/src/miner.cpp b/src/miner.cpp index 553ad13ca..f83142641 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -111,7 +111,7 @@ void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, pblock->nTime = nTime; // Updating time can change work required on testnet: - if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) { + if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != std::nullopt) { pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); } } @@ -141,7 +141,7 @@ class AddFundingStreamValueToTx auto odesc = output.Build(ctx); if (odesc) { - mtx.vShieldedOutput.push_back(odesc.get()); + mtx.vShieldedOutput.push_back(odesc.value()); mtx.valueBalance -= fundingStreamValue; return true; } else { @@ -258,7 +258,7 @@ class AddOutputsToCoinbaseTxAndSign librustzcash_sapling_proving_ctx_free(ctx); throw new std::runtime_error("Failed to create shielded output for miner"); } - mtx.vShieldedOutput.push_back(odesc.get()); + mtx.vShieldedOutput.push_back(odesc.value()); ComputeBindingSig(ctx); @@ -916,7 +916,7 @@ void static BitcoinMiner(const CChainParams& chainparams) // Update nNonce and nTime pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); - if (chainparams.GetConsensus().nPowAllowMinDifficultyBlocksAfterHeight != boost::none) + if (chainparams.GetConsensus().nPowAllowMinDifficultyBlocksAfterHeight != std::nullopt) { // Changing pblock->nTime can change work required on testnet: hashTarget.SetCompact(pblock->nBits); diff --git a/src/miner.h b/src/miner.h index 41fbd70b0..96a083540 100644 --- a/src/miner.h +++ b/src/miner.h @@ -8,7 +8,6 @@ #include "primitives/block.h" -#include #include #include diff --git a/src/net.cpp b/src/net.cpp index 42afd7b60..5b8cf713b 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -823,7 +823,7 @@ static bool AttemptToEvictConnection(bool fPreferNewConnection) { const Consensus::Params& params = Params().GetConsensus(); auto nextEpoch = NextEpoch(height, params); if (nextEpoch) { - auto idx = nextEpoch.get(); + auto idx = nextEpoch.value(); int nActivationHeight = params.vUpgrades[idx].nActivationHeight; if (nActivationHeight > 0 && diff --git a/src/pow.cpp b/src/pow.cpp index 3c875a6eb..b9d7020c0 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -26,8 +26,8 @@ unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHead { // Comparing to pindexLast->nHeight with >= because this function // returns the work required for the block after pindexLast. - if (params.nPowAllowMinDifficultyBlocksAfterHeight != boost::none && - pindexLast->nHeight >= params.nPowAllowMinDifficultyBlocksAfterHeight.get()) + if (params.nPowAllowMinDifficultyBlocksAfterHeight != std::nullopt && + pindexLast->nHeight >= params.nPowAllowMinDifficultyBlocksAfterHeight.value()) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 6 * block interval minutes diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 307572341..696f0ae45 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -22,6 +22,7 @@ #include +#include #include using namespace std; @@ -83,8 +84,8 @@ double GetNetworkDifficulty(const CBlockIndex* blockindex) static UniValue ValuePoolDesc( const std::string &name, - const boost::optional chainValue, - const boost::optional valueDelta) + const std::optional chainValue, + const std::optional valueDelta) { UniValue rv(UniValue::VOBJ); rv.pushKV("id", name); @@ -1058,8 +1059,8 @@ UniValue getblockchaininfo(const UniValue& params, bool fHelp) CBlockIndex* tip = chainActive.Tip(); UniValue valuePools(UniValue::VARR); - valuePools.push_back(ValuePoolDesc("sprout", tip->nChainSproutValue, boost::none)); - valuePools.push_back(ValuePoolDesc("sapling", tip->nChainSaplingValue, boost::none)); + valuePools.push_back(ValuePoolDesc("sprout", tip->nChainSproutValue, std::nullopt)); + valuePools.push_back(ValuePoolDesc("sapling", tip->nChainSaplingValue, std::nullopt)); obj.pushKV("valuePools", valuePools); const Consensus::Params& consensusParams = Params().GetConsensus(); diff --git a/src/serialize.h b/src/serialize.h index 1ed18ebf7..db8b16134 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -23,8 +24,6 @@ #include #include -#include - #include "prevector.h" static const unsigned int MAX_SIZE = 0x02000000; @@ -536,8 +535,8 @@ template inline void Unserialize(Stream /** * optional */ -template void Serialize(Stream& os, const boost::optional& item); -template void Unserialize(Stream& is, boost::optional& item); +template void Serialize(Stream& os, const std::optional& item); +template void Unserialize(Stream& is, std::optional& item); /** * array @@ -764,7 +763,7 @@ inline void Unserialize(Stream& is, std::vector& v) * optional */ template -void Serialize(Stream& os, const boost::optional& item) +void Serialize(Stream& os, const std::optional& item) { // If the value is there, put 0x01 and then serialize the value. // If it's not, put 0x00. @@ -779,13 +778,13 @@ void Serialize(Stream& os, const boost::optional& item) } template -void Unserialize(Stream& is, boost::optional& item) +void Unserialize(Stream& is, std::optional& item) { unsigned char discriminant = 0x00; Unserialize(is, discriminant); if (discriminant == 0x00) { - item = boost::none; + item = std::nullopt; } else if (discriminant == 0x01) { T object; Unserialize(is, object); diff --git a/src/test/serialize_tests.cpp b/src/test/serialize_tests.cpp index bed934000..b00fa69a4 100644 --- a/src/test/serialize_tests.cpp +++ b/src/test/serialize_tests.cpp @@ -9,10 +9,10 @@ #include "utilstrencodings.h" #include +#include #include #include -#include using namespace std; @@ -83,15 +83,15 @@ class CSerializeMethodsTestMany : public CSerializeMethodsTestSingle BOOST_AUTO_TEST_CASE(boost_optional) { - check_ser_rep>(0xff, {0x01, 0xff}); - check_ser_rep>(boost::none, {0x00}); - check_ser_rep>(std::string("Test"), {0x01, 0x04, 'T', 'e', 's', 't'}); + check_ser_rep>(0xff, {0x01, 0xff}); + check_ser_rep>(std::nullopt, {0x00}); + check_ser_rep>(std::string("Test"), {0x01, 0x04, 'T', 'e', 's', 't'}); { // Ensure that canonical optional discriminant is used CDataStream ss(SER_DISK, 0); ss.write("\x02\x04Test", 6); - boost::optional into; + std::optional into; BOOST_CHECK_THROW(ss >> into, std::ios_base::failure); } diff --git a/src/transaction_builder.cpp b/src/transaction_builder.cpp index bec5081ab..63b0c1495 100644 --- a/src/transaction_builder.cpp +++ b/src/transaction_builder.cpp @@ -23,19 +23,19 @@ SpendDescriptionInfo::SpendDescriptionInfo( librustzcash_sapling_generate_r(alpha.begin()); } -boost::optional OutputDescriptionInfo::Build(void* ctx) { +std::optional OutputDescriptionInfo::Build(void* ctx) { auto cmu = this->note.cmu(); if (!cmu) { - return boost::none; + return std::nullopt; } libzcash::SaplingNotePlaintext notePlaintext(this->note, this->memo); auto res = notePlaintext.encrypt(this->note.pk_d); if (!res) { - return boost::none; + return std::nullopt; } - auto enc = res.get(); + auto enc = res.value(); auto encryptor = enc.second; libzcash::SaplingPaymentAddress address(this->note.d, this->note.pk_d); @@ -53,7 +53,7 @@ boost::optional OutputDescriptionInfo::Build(void* ctx) { this->note.value(), odesc.cv.begin(), odesc.zkproof.begin())) { - return boost::none; + return std::nullopt; } odesc.cmu = *cmu; @@ -125,13 +125,13 @@ TransactionBuilderResult::TransactionBuilderResult(const CTransaction& tx) : may TransactionBuilderResult::TransactionBuilderResult(const std::string& error) : maybeError(error) {} -bool TransactionBuilderResult::IsTx() { return maybeTx != boost::none; } +bool TransactionBuilderResult::IsTx() { return maybeTx != std::nullopt; } -bool TransactionBuilderResult::IsError() { return maybeError != boost::none; } +bool TransactionBuilderResult::IsError() { return maybeError != std::nullopt; } CTransaction TransactionBuilderResult::GetTxOrThrow() { if (maybeTx) { - return maybeTx.get(); + return maybeTx.value(); } else { throw JSONRPCError(RPC_WALLET_ERROR, "Failed to build transaction: " + GetError()); } @@ -139,7 +139,7 @@ CTransaction TransactionBuilderResult::GetTxOrThrow() { std::string TransactionBuilderResult::GetError() { if (maybeError) { - return maybeError.get(); + return maybeError.value(); } else { // This can only happen if isTx() is true in which case we should not call getError() throw std::runtime_error("getError() was called in TransactionBuilderResult, but the result was not initialized as an error."); @@ -277,15 +277,15 @@ void TransactionBuilder::SetFee(CAmount fee) void TransactionBuilder::SendChangeTo(libzcash::SaplingPaymentAddress changeAddr, uint256 ovk) { saplingChangeAddr = std::make_pair(ovk, changeAddr); - sproutChangeAddr = boost::none; - tChangeAddr = boost::none; + sproutChangeAddr = std::nullopt; + tChangeAddr = std::nullopt; } void TransactionBuilder::SendChangeTo(libzcash::SproutPaymentAddress changeAddr) { sproutChangeAddr = changeAddr; - saplingChangeAddr = boost::none; - tChangeAddr = boost::none; + saplingChangeAddr = std::nullopt; + tChangeAddr = std::nullopt; } void TransactionBuilder::SendChangeTo(CTxDestination& changeAddr) @@ -295,8 +295,8 @@ void TransactionBuilder::SendChangeTo(CTxDestination& changeAddr) } tChangeAddr = changeAddr; - saplingChangeAddr = boost::none; - sproutChangeAddr = boost::none; + saplingChangeAddr = std::nullopt; + sproutChangeAddr = std::nullopt; } TransactionBuilderResult TransactionBuilder::Build() @@ -335,7 +335,7 @@ TransactionBuilderResult TransactionBuilder::Build() if (saplingChangeAddr) { AddSaplingOutput(saplingChangeAddr->first, saplingChangeAddr->second, change); } else if (sproutChangeAddr) { - AddSproutOutput(sproutChangeAddr.get(), change); + AddSproutOutput(sproutChangeAddr.value(), change); } else if (tChangeAddr) { // tChangeAddr has already been validated. AddTransparentOutput(tChangeAddr.value(), change); @@ -410,7 +410,7 @@ TransactionBuilderResult TransactionBuilder::Build() return TransactionBuilderResult("Failed to create output description"); } - mtx.vShieldedOutput.push_back(odesc.get()); + mtx.vShieldedOutput.push_back(odesc.value()); } // @@ -616,7 +616,7 @@ void TransactionBuilder::CreateJSDescriptions() assert(changeOutputIndex != -1); assert(changeOutputIndex < prevJoinSplit.commitments.size()); - boost::optional changeWitness; + std::optional changeWitness; int n = 0; for (const uint256& commitment : prevJoinSplit.commitments) { tree.append(commitment); @@ -624,7 +624,7 @@ void TransactionBuilder::CreateJSDescriptions() if (!changeWitness && changeOutputIndex == n++) { changeWitness = tree.witness(); } else if (changeWitness) { - changeWitness.get().append(commitment); + changeWitness.value().append(commitment); } } assert(changeWitness.has_value()); @@ -646,7 +646,7 @@ void TransactionBuilder::CreateJSDescriptions() (unsigned char)changeOutputIndex); auto note = plaintext.note(changeAddress); - vjsin[0] = libzcash::JSInput(changeWitness.get(), note, changeKey); + vjsin[0] = libzcash::JSInput(changeWitness.value(), note, changeKey); jsInputValue += plaintext.value(); diff --git a/src/transaction_builder.h b/src/transaction_builder.h index ccaad89f7..379eeb2ee 100644 --- a/src/transaction_builder.h +++ b/src/transaction_builder.h @@ -19,7 +19,7 @@ #include "zcash/Note.hpp" #include "zcash/NoteEncryption.hpp" -#include +#include #define NO_MEMO {{0xF6}} @@ -47,7 +47,7 @@ struct OutputDescriptionInfo { libzcash::SaplingNote note, std::array memo) : ovk(ovk), note(note), memo(memo) {} - boost::optional Build(void* ctx); + std::optional Build(void* ctx); }; struct JSDescriptionInfo { @@ -91,8 +91,8 @@ struct TransparentInputInfo { class TransactionBuilderResult { private: - boost::optional maybeTx; - boost::optional maybeError; + std::optional maybeTx; + std::optional maybeError; public: TransactionBuilderResult() = delete; TransactionBuilderResult(const CTransaction& tx); @@ -120,9 +120,9 @@ class TransactionBuilder std::vector jsOutputs; std::vector tIns; - boost::optional> saplingChangeAddr; - boost::optional sproutChangeAddr; - boost::optional tChangeAddr; + std::optional> saplingChangeAddr; + std::optional sproutChangeAddr; + std::optional tChangeAddr; public: TransactionBuilder() {} diff --git a/src/txmempool.cpp b/src/txmempool.cpp index 1236288b8..bf291dece 100644 --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -17,6 +17,8 @@ #include "validationinterface.h" #include "version.h" +#include + using namespace std; CTxMemPoolEntry::CTxMemPoolEntry(): @@ -839,9 +841,9 @@ bool CTxMemPool::IsRecentlyEvicted(const uint256& txId) { void CTxMemPool::EnsureSizeLimit() { AssertLockHeld(cs); - boost::optional maybeDropTxId; - while ((maybeDropTxId = weightedTxTree->maybeDropRandom()).is_initialized()) { - uint256 txId = maybeDropTxId.get(); + std::optional maybeDropTxId; + while ((maybeDropTxId = weightedTxTree->maybeDropRandom()).has_value()) { + uint256 txId = maybeDropTxId.value(); recentlyEvicted->add(txId); std::list removed; remove(mapTx.find(txId)->GetTx(), removed, true); diff --git a/src/utiltest.cpp b/src/utiltest.cpp index c4030910f..d875ae7b5 100644 --- a/src/utiltest.cpp +++ b/src/utiltest.cpp @@ -295,7 +295,7 @@ CKey AddTestCKeyToKeyStore(CBasicKeyStore& keyStore) { TestSaplingNote GetTestSaplingNote(const libzcash::SaplingPaymentAddress& pa, CAmount value) { // Generate dummy Sapling note libzcash::SaplingNote note(pa, value, libzcash::Zip212Enabled::BeforeZip212); - uint256 cm = note.cmu().get(); + uint256 cm = note.cmu().value(); SaplingMerkleTree tree; tree.append(cm); return { note, tree }; diff --git a/src/validationinterface.cpp b/src/validationinterface.cpp index db9f8e47e..e0e5dfd64 100644 --- a/src/validationinterface.cpp +++ b/src/validationinterface.cpp @@ -190,7 +190,7 @@ void ThreadNotifyWallets(CBlockIndex *pindexLastTip) SyncWithWallets(tx, NULL, pindexLastTip->nHeight); } // Update cached incremental witnesses - GetMainSignals().ChainTip(pindexLastTip, &block, boost::none); + GetMainSignals().ChainTip(pindexLastTip, &block, std::nullopt); // On to the next block! pindexLastTip = pindexLastTip->pprev; diff --git a/src/validationinterface.h b/src/validationinterface.h index f1694a313..00aa882dc 100644 --- a/src/validationinterface.h +++ b/src/validationinterface.h @@ -6,6 +6,8 @@ #ifndef BITCOIN_VALIDATIONINTERFACE_H #define BITCOIN_VALIDATIONINTERFACE_H +#include + #include #include @@ -35,7 +37,7 @@ class CValidationInterface { virtual void UpdatedBlockTip(const CBlockIndex *pindex) {} virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock, const int nHeight) {} virtual void EraseFromWallet(const uint256 &hash) {} - virtual void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, boost::optional> added) {} + virtual void ChainTip(const CBlockIndex *pindex, const CBlock *pblock, std::optional> added) {} virtual void SetBestChain(const CBlockLocator &locator) {} virtual void UpdatedTransaction(const uint256 &hash) {} virtual void Inventory(const uint256 &hash) {} @@ -58,7 +60,7 @@ struct CMainSignals { /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal UpdatedTransaction; /** Notifies listeners of a change to the tip of the active block chain. */ - boost::signals2::signal>)> ChainTip; + boost::signals2::signal>)> ChainTip; /** Notifies listeners of a new active block chain. */ boost::signals2::signal SetBestChain; /** Notifies listeners about an inventory item being seen on the network. */ diff --git a/src/wallet/asyncrpcoperation_common.cpp b/src/wallet/asyncrpcoperation_common.cpp index d3c911f84..199039ce2 100644 --- a/src/wallet/asyncrpcoperation_common.cpp +++ b/src/wallet/asyncrpcoperation_common.cpp @@ -6,7 +6,11 @@ extern UniValue signrawtransaction(const UniValue& params, bool fHelp); -UniValue SendTransaction(CTransaction& tx, boost::optional reservekey, bool testmode) { +UniValue SendTransaction( + CTransaction& tx, + std::optional> reservekey, + bool testmode) +{ UniValue o(UniValue::VOBJ); // Send the transaction if (!testmode) { @@ -25,7 +29,11 @@ UniValue SendTransaction(CTransaction& tx, boost::optional reserve return o; } -std::pair SignSendRawTransaction(UniValue obj, boost::optional reservekey, bool testmode) { +std::pair SignSendRawTransaction( + UniValue obj, + std::optional> reservekey, + bool testmode) +{ // Sign the raw transaction UniValue rawtxnValue = find_value(obj, "rawtxn"); if (rawtxnValue.isNull()) { diff --git a/src/wallet/asyncrpcoperation_common.h b/src/wallet/asyncrpcoperation_common.h index 0b27d2952..ec2f5794f 100644 --- a/src/wallet/asyncrpcoperation_common.h +++ b/src/wallet/asyncrpcoperation_common.h @@ -9,6 +9,9 @@ #include "univalue.h" #include "wallet.h" +#include +#include + /** * Sends a given transaction. * @@ -18,7 +21,10 @@ * If testmode is true, do not commit the transaction, * return {"test": 1, "txid": tx.GetHash().ToString(), "hex": EncodeHexTx(tx)} */ -UniValue SendTransaction(CTransaction& tx, boost::optional reservekey, bool testmode); +UniValue SendTransaction( + CTransaction& tx, + std::optional> reservekey, + bool testmode); /** * Sign and send a raw transaction. @@ -26,6 +32,9 @@ UniValue SendTransaction(CTransaction& tx, boost::optional reserve * * Returns a pair of (the parsed transaction, and the result of sending) */ -std::pair SignSendRawTransaction(UniValue obj, boost::optional reservekey, bool testmode); +std::pair SignSendRawTransaction( + UniValue obj, + std::optional> reservekey, + bool testmode); #endif /* ASYNCRPCOPERATION_COMMON_H */ diff --git a/src/wallet/asyncrpcoperation_mergetoaddress.cpp b/src/wallet/asyncrpcoperation_mergetoaddress.cpp index 752b63382..181326727 100644 --- a/src/wallet/asyncrpcoperation_mergetoaddress.cpp +++ b/src/wallet/asyncrpcoperation_mergetoaddress.cpp @@ -57,7 +57,7 @@ int mta_find_output(UniValue obj, int n) } AsyncRPCOperation_mergetoaddress::AsyncRPCOperation_mergetoaddress( - boost::optional builder, + std::optional builder, CMutableTransaction contextualTx, std::vector utxoInputs, std::vector sproutNoteInputs, @@ -91,7 +91,7 @@ AsyncRPCOperation_mergetoaddress::AsyncRPCOperation_mergetoaddress( isUsingBuilder_ = false; if (builder) { isUsingBuilder_ = true; - builder_ = builder.get(); + builder_ = builder.value(); } KeyIO keyIO(Params()); @@ -291,7 +291,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() builder_.AddTransparentInput(outPoint, scriptPubKey, amount); } - boost::optional ovk; + std::optional ovk; // Select Sapling notes std::vector saplingOPs; std::vector saplingNotes; @@ -308,7 +308,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() // Fetch Sapling anchor and witnesses uint256 anchor; - std::vector> witnesses; + std::vector> witnesses; { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->GetSaplingNoteWitnesses(saplingOPs, witnesses, anchor); @@ -319,7 +319,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() if (!witnesses[i]) { throw JSONRPCError(RPC_WALLET_ERROR, "Missing witness for Sapling note"); } - builder_.AddSaplingSpend(expsks[i], saplingNotes[i], anchor, witnesses[i].get()); + builder_.AddSaplingSpend(expsks[i], saplingNotes[i], anchor, witnesses[i].value()); } if (isToTaddr_) { @@ -344,13 +344,13 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() if (!ovk) { throw JSONRPCError(RPC_WALLET_ERROR, "Sending to a Sapling address requires an ovk."); } - builder_.AddSaplingOutput(ovk.get(), *saplingPaymentAddress, sendAmount, hexMemo); + builder_.AddSaplingOutput(ovk.value(), *saplingPaymentAddress, sendAmount, hexMemo); } // Build the transaction tx_ = builder_.Build().GetTxOrThrow(); - UniValue sendResult = SendTransaction(tx_, boost::none, testmode); + UniValue sendResult = SendTransaction(tx_, std::nullopt, testmode); set_result(sendResult); return true; @@ -370,7 +370,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() if (isPureTaddrOnlyTx) { UniValue obj(UniValue::VOBJ); obj.pushKV("rawtxn", EncodeHexTx(tx_)); - auto txAndResult = SignSendRawTransaction(obj, boost::none, testmode); + auto txAndResult = SignSendRawTransaction(obj, std::nullopt, testmode); tx_ = txAndResult.first; set_result(txAndResult.second); return true; @@ -408,7 +408,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() info.vjsout.push_back(jso); UniValue obj = perform_joinsplit(info); - auto txAndResult = SignSendRawTransaction(obj, boost::none, testmode); + auto txAndResult = SignSendRawTransaction(obj, std::nullopt, testmode); tx_ = txAndResult.first; set_result(txAndResult.second); return true; @@ -433,7 +433,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() JSOutPoint jso = std::get<0>(t); std::vector vOutPoints = {jso}; uint256 inputAnchor; - std::vector> vInputWitnesses; + std::vector> vInputWitnesses; pwalletMain->GetSproutNoteWitnesses(vOutPoints, vInputWitnesses, inputAnchor); jsopWitnessAnchorMap[jso.ToString()] = MergeToAddressWitnessAnchorData{vInputWitnesses[0], inputAnchor}; } @@ -497,7 +497,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() CAmount jsInputValue = 0; uint256 jsAnchor; - std::vector> witnesses; + std::vector> witnesses; JSDescription prevJoinSplit; @@ -528,7 +528,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() } assert(changeOutputIndex != -1); - boost::optional changeWitness; + std::optional changeWitness; int n = 0; for (const uint256& commitment : prevJoinSplit.commitments) { tree.append(commitment); @@ -536,7 +536,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() if (!changeWitness && changeOutputIndex == n++) { changeWitness = tree.witness(); } else if (changeWitness) { - changeWitness.get().append(commitment); + changeWitness.value().append(commitment); } } if (changeWitness) { @@ -581,7 +581,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() std::vector vInputNotes; std::vector vInputZKeys; std::vector vOutPoints; - std::vector> vInputWitnesses; + std::vector> vInputWitnesses; uint256 inputAnchor; int numInputsNeeded = (jsChange > 0) ? 1 : 0; while (numInputsNeeded++ < ZC_NUM_JS_INPUTS && zInputsDeque.size() > 0) { @@ -638,7 +638,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() if (!optionalWitness) { throw JSONRPCError(RPC_WALLET_ERROR, "Witness for note commitment is null"); } - SproutWitness w = *optionalWitness; // could use .get(); + SproutWitness w = *optionalWitness; // could use .value(); if (jsChange > 0) { for (const uint256& commitment : previousCommitments) { w.append(commitment); @@ -712,7 +712,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() assert(zInputsDeque.size() == 0); assert(vpubNewProcessed); - auto txAndResult = SignSendRawTransaction(obj, boost::none, testmode); + auto txAndResult = SignSendRawTransaction(obj, std::nullopt, testmode); tx_ = txAndResult.first; set_result(txAndResult.second); return true; @@ -721,7 +721,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl() UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(MergeToAddressJSInfo& info) { - std::vector> witnesses; + std::vector> witnesses; uint256 anchor; { LOCK(cs_main); @@ -733,7 +733,7 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(MergeToAddressJSInf UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(MergeToAddressJSInfo& info, std::vector& outPoints) { - std::vector> witnesses; + std::vector> witnesses; uint256 anchor; { LOCK(cs_main); @@ -744,7 +744,7 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(MergeToAddressJSInf UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit( MergeToAddressJSInfo& info, - std::vector> witnesses, + std::vector> witnesses, uint256 anchor) { if (anchor.IsNull()) { diff --git a/src/wallet/asyncrpcoperation_mergetoaddress.h b/src/wallet/asyncrpcoperation_mergetoaddress.h index ff82124b5..25874d7cd 100644 --- a/src/wallet/asyncrpcoperation_mergetoaddress.h +++ b/src/wallet/asyncrpcoperation_mergetoaddress.h @@ -15,6 +15,7 @@ #include "zcash/JoinSplit.hpp" #include +#include #include #include @@ -48,7 +49,7 @@ struct MergeToAddressJSInfo { // A struct to help us track the witness and anchor for a given JSOutPoint struct MergeToAddressWitnessAnchorData { - boost::optional witness; + std::optional witness; uint256 anchor; }; @@ -56,7 +57,7 @@ class AsyncRPCOperation_mergetoaddress : public AsyncRPCOperation { public: AsyncRPCOperation_mergetoaddress( - boost::optional builder, + std::optional builder, CMutableTransaction contextualTx, std::vector utxoInputs, std::vector sproutNoteInputs, @@ -120,7 +121,7 @@ class AsyncRPCOperation_mergetoaddress : public AsyncRPCOperation // JoinSplit where you have the witnesses and anchor UniValue perform_joinsplit( MergeToAddressJSInfo& info, - std::vector> witnesses, + std::vector> witnesses, uint256 anchor); void lock_utxos(); @@ -178,7 +179,7 @@ class TEST_FRIEND_AsyncRPCOperation_mergetoaddress UniValue perform_joinsplit( MergeToAddressJSInfo& info, - std::vector> witnesses, + std::vector> witnesses, uint256 anchor) { return delegate->perform_joinsplit(info, witnesses, anchor); diff --git a/src/wallet/asyncrpcoperation_saplingmigration.cpp b/src/wallet/asyncrpcoperation_saplingmigration.cpp index 0a12819d3..10c85cbb5 100644 --- a/src/wallet/asyncrpcoperation_saplingmigration.cpp +++ b/src/wallet/asyncrpcoperation_saplingmigration.cpp @@ -11,6 +11,7 @@ #include "utilmoneystr.h" #include "wallet.h" +#include #include const CAmount FEE = 10000; @@ -72,7 +73,7 @@ bool AsyncRPCOperation_saplingmigration::main_impl() { LogPrint("zrpcunsafe", "%s: Beginning AsyncRPCOperation_saplingmigration.\n", getId()); auto consensusParams = Params().GetConsensus(); auto nextActivationHeight = NextActivationHeight(targetHeight_, consensusParams); - if (nextActivationHeight && targetHeight_ + MIGRATION_EXPIRY_DELTA >= nextActivationHeight.get()) { + if (nextActivationHeight && targetHeight_ + MIGRATION_EXPIRY_DELTA >= nextActivationHeight.value()) { LogPrint("zrpcunsafe", "%s: Migration txs would be created before a NU activation but may expire after. Skipping this round.\n", getId()); setMigrationResult(0, 0, std::vector()); return true; @@ -139,9 +140,9 @@ bool AsyncRPCOperation_saplingmigration::main_impl() { // for each Sprout JoinSplit description // TODO: the above functionality (in comment) is not implemented in zcashd uint256 inputAnchor; - std::vector> vInputWitnesses; + std::vector> vInputWitnesses; pwalletMain->GetSproutNoteWitnesses(vOutPoints, vInputWitnesses, inputAnchor); - builder.AddSproutInput(sproutSk, sproutEntry.note, vInputWitnesses[0].get()); + builder.AddSproutInput(sproutSk, sproutEntry.note, vInputWitnesses[0].value()); } // The amount chosen *includes* the 0.0001 ZEC fee for this transaction, i.e. // the value of the Sapling output will be 0.0001 ZEC less. diff --git a/src/wallet/asyncrpcoperation_sendmany.cpp b/src/wallet/asyncrpcoperation_sendmany.cpp index 583d87138..9683c0472 100644 --- a/src/wallet/asyncrpcoperation_sendmany.cpp +++ b/src/wallet/asyncrpcoperation_sendmany.cpp @@ -58,7 +58,7 @@ int find_output(UniValue obj, int n) { } AsyncRPCOperation_sendmany::AsyncRPCOperation_sendmany( - boost::optional builder, + std::optional builder, CMutableTransaction contextualTx, std::string fromAddress, std::vector tOutputs, @@ -85,7 +85,7 @@ AsyncRPCOperation_sendmany::AsyncRPCOperation_sendmany( isUsingBuilder_ = false; if (builder) { isUsingBuilder_ = true; - builder_ = builder.get(); + builder_ = builder.value(); } KeyIO keyIO(Params()); @@ -104,7 +104,7 @@ AsyncRPCOperation_sendmany::AsyncRPCOperation_sendmany( isfromzaddr_ = true; frompaymentaddress_ = address; - spendingkey_ = std::visit(GetSpendingKeyForPaymentAddress(pwalletMain), address).get(); + spendingkey_ = std::visit(GetSpendingKeyForPaymentAddress(pwalletMain), address).value(); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid from address"); } @@ -410,7 +410,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { // Fetch Sapling anchor and witnesses uint256 anchor; - std::vector> witnesses; + std::vector> witnesses; { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->GetSaplingNoteWitnesses(ops, witnesses, anchor); @@ -421,7 +421,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { if (!witnesses[i]) { throw JSONRPCError(RPC_WALLET_ERROR, "Missing witness for Sapling note"); } - builder_.AddSaplingSpend(expsk, notes[i], anchor, witnesses[i].get()); + builder_.AddSaplingSpend(expsk, notes[i], anchor, witnesses[i].value()); } // Add Sapling outputs @@ -533,7 +533,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { JSOutPoint jso = t.point; std::vector vOutPoints = { jso }; uint256 inputAnchor; - std::vector> vInputWitnesses; + std::vector> vInputWitnesses; pwalletMain->GetSproutNoteWitnesses(vOutPoints, vInputWitnesses, inputAnchor); jsopWitnessAnchorMap[ jso.ToString() ] = WitnessAnchorData{ vInputWitnesses[0], inputAnchor }; } @@ -644,7 +644,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { CAmount jsInputValue = 0; uint256 jsAnchor; - std::vector> witnesses; + std::vector> witnesses; JSDescription prevJoinSplit; @@ -675,7 +675,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { } assert(changeOutputIndex != -1); - boost::optional changeWitness; + std::optional changeWitness; int n = 0; for (const uint256& commitment : prevJoinSplit.commitments) { tree.append(commitment); @@ -683,7 +683,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { if (!changeWitness && changeOutputIndex == n++) { changeWitness = tree.witness(); } else if (changeWitness) { - changeWitness.get().append(commitment); + changeWitness.value().append(commitment); } } if (changeWitness) { @@ -727,7 +727,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { // std::vector vInputNotes; std::vector vOutPoints; - std::vector> vInputWitnesses; + std::vector> vInputWitnesses; uint256 inputAnchor; int numInputsNeeded = (jsChange>0) ? 1 : 0; while (numInputsNeeded++ < ZC_NUM_JS_INPUTS && zInputsDeque.size() > 0) { @@ -784,7 +784,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { if (!optionalWitness) { throw JSONRPCError(RPC_WALLET_ERROR, "Witness for note commitment is null"); } - SproutWitness w = *optionalWitness; // could use .get(); + SproutWitness w = *optionalWitness; // could use .value(); if (jsChange > 0) { for (const uint256& commitment : previousCommitments) { w.append(commitment); @@ -885,7 +885,7 @@ bool AsyncRPCOperation_sendmany::main_impl() { assert(zOutputsDeque.size() == 0); assert(vpubNewProcessed); - auto txAndResult = SignSendRawTransaction(obj, boost::none, testmode); + auto txAndResult = SignSendRawTransaction(obj, std::nullopt, testmode); tx_ = txAndResult.first; set_result(txAndResult.second); return true; @@ -1000,7 +1000,7 @@ bool AsyncRPCOperation_sendmany::find_unspent_notes() { } UniValue AsyncRPCOperation_sendmany::perform_joinsplit(AsyncJoinSplitInfo & info) { - std::vector> witnesses; + std::vector> witnesses; uint256 anchor; { LOCK(cs_main); @@ -1011,7 +1011,7 @@ UniValue AsyncRPCOperation_sendmany::perform_joinsplit(AsyncJoinSplitInfo & info UniValue AsyncRPCOperation_sendmany::perform_joinsplit(AsyncJoinSplitInfo & info, std::vector & outPoints) { - std::vector> witnesses; + std::vector> witnesses; uint256 anchor; { LOCK(cs_main); @@ -1022,7 +1022,7 @@ UniValue AsyncRPCOperation_sendmany::perform_joinsplit(AsyncJoinSplitInfo & info UniValue AsyncRPCOperation_sendmany::perform_joinsplit( AsyncJoinSplitInfo & info, - std::vector> witnesses, + std::vector> witnesses, uint256 anchor) { if (anchor.IsNull()) { diff --git a/src/wallet/asyncrpcoperation_sendmany.h b/src/wallet/asyncrpcoperation_sendmany.h index 9e8e39593..38989e51d 100644 --- a/src/wallet/asyncrpcoperation_sendmany.h +++ b/src/wallet/asyncrpcoperation_sendmany.h @@ -15,6 +15,7 @@ #include "wallet/paymentdisclosure.h" #include +#include #include #include @@ -68,14 +69,14 @@ struct AsyncJoinSplitInfo // A struct to help us track the witness and anchor for a given JSOutPoint struct WitnessAnchorData { - boost::optional witness; + std::optional witness; uint256 anchor; }; class AsyncRPCOperation_sendmany : public AsyncRPCOperation { public: AsyncRPCOperation_sendmany( - boost::optional builder, + std::optional builder, CMutableTransaction contextualTx, std::string fromAddress, std::vector tOutputs, @@ -146,7 +147,7 @@ class AsyncRPCOperation_sendmany : public AsyncRPCOperation { // JoinSplit where you have the witnesses and anchor UniValue perform_joinsplit( AsyncJoinSplitInfo & info, - std::vector> witnesses, + std::vector> witnesses, uint256 anchor); // payment disclosure! @@ -205,7 +206,7 @@ class TEST_FRIEND_AsyncRPCOperation_sendmany { UniValue perform_joinsplit( AsyncJoinSplitInfo & info, - std::vector> witnesses, + std::vector> witnesses, uint256 anchor) { return delegate->perform_joinsplit(info, witnesses, anchor); diff --git a/src/wallet/asyncrpcoperation_shieldcoinbase.cpp b/src/wallet/asyncrpcoperation_shieldcoinbase.cpp index 6c2fb86ed..9ec5f92de 100644 --- a/src/wallet/asyncrpcoperation_shieldcoinbase.cpp +++ b/src/wallet/asyncrpcoperation_shieldcoinbase.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -223,7 +224,7 @@ bool ShieldToAddress::operator()(const libzcash::SproutPaymentAddress &zaddr) co info.vjsout.push_back(jso); UniValue obj = m_op->perform_joinsplit(info); - auto txAndResult = SignSendRawTransaction(obj, boost::none, m_op->testmode); + auto txAndResult = SignSendRawTransaction(obj, std::nullopt, m_op->testmode); m_op->tx_ = txAndResult.first; m_op->set_result(txAndResult.second); return true; @@ -251,7 +252,7 @@ bool ShieldToAddress::operator()(const libzcash::SaplingPaymentAddress &zaddr) c // Build the transaction m_op->tx_ = m_op->builder_.Build().GetTxOrThrow(); - UniValue sendResult = SendTransaction(m_op->tx_, boost::none, m_op->testmode); + UniValue sendResult = SendTransaction(m_op->tx_, std::nullopt, m_op->testmode); m_op->set_result(sendResult); return true; diff --git a/src/wallet/gtest/test_wallet.cpp b/src/wallet/gtest/test_wallet.cpp index 3d893a9a3..0e22f910d 100644 --- a/src/wallet/gtest/test_wallet.cpp +++ b/src/wallet/gtest/test_wallet.cpp @@ -15,6 +15,8 @@ #include "zcash/Note.hpp" #include "zcash/NoteEncryption.hpp" +#include + #include using ::testing::Return; @@ -106,8 +108,8 @@ std::pair CreateValidBlock(TestWallet& wallet, std::pair GetWitnessesAndAnchors(TestWallet& wallet, std::vector& sproutNotes, std::vector& saplingNotes, - std::vector>& sproutWitnesses, - std::vector>& saplingWitnesses) { + std::vector>& sproutWitnesses, + std::vector>& saplingWitnesses) { sproutWitnesses.clear(); saplingWitnesses.clear(); uint256 sproutAnchor; @@ -363,7 +365,7 @@ TEST(WalletTests, SetSaplingNoteAddrsInCWalletTx) { auto pk = sk.DefaultAddress(); libzcash::SaplingNote note(pk, 50000, zip_212_enabled[ver]); - auto cm = note.cmu().get(); + auto cm = note.cmu().value(); SaplingMerkleTree tree; tree.append(cm); auto anchor = tree.root(); @@ -371,7 +373,7 @@ TEST(WalletTests, SetSaplingNoteAddrsInCWalletTx) { auto nf = note.nullifier(fvk, witness.position()); ASSERT_TRUE(nf); - uint256 nullifier = nf.get(); + uint256 nullifier = nf.value(); auto builder = TransactionBuilder(consensusParams, 1); builder.AddSaplingSpend(expsk, note, anchor, witness); @@ -643,7 +645,7 @@ TEST(WalletTests, GetConflictedSaplingNotes) { // Generate note A libzcash::SaplingNote note(pk, 50000, zip_212_enabled[ver]); - auto cm = note.cmu().get(); + auto cm = note.cmu().value(); SaplingMerkleTree saplingTree; saplingTree.append(cm); auto anchor = saplingTree.root(); @@ -693,15 +695,15 @@ TEST(WalletTests, GetConflictedSaplingNotes) { wtx.vShieldedOutput[0].ephemeralKey, wtx.vShieldedOutput[0].cmu); ASSERT_EQ(static_cast(maybe_pt), true); - auto maybe_note = maybe_pt.get().note(ivk); + auto maybe_note = maybe_pt.value().note(ivk); ASSERT_EQ(static_cast(maybe_note), true); - auto note2 = maybe_note.get(); + auto note2 = maybe_note.value(); SaplingOutPoint sop0(wtx.GetHash(), 0); auto spend_note_witness = wtx.mapSaplingNoteData[sop0].witnesses.front(); auto maybe_nf = note2.nullifier(extfvk.fvk, spend_note_witness.position()); ASSERT_EQ(static_cast(maybe_nf), true); - auto nullifier2 = maybe_nf.get(); + auto nullifier2 = maybe_nf.value(); anchor = saplingTree.root(); @@ -813,7 +815,7 @@ TEST(WalletTests, SaplingNullifierIsSpent) { // Manually compute the nullifier based on the known position auto nf = testNote.note.nullifier(extfvk.fvk, testNote.tree.witness().position()); ASSERT_TRUE(nf); - uint256 nullifier = nf.get(); + uint256 nullifier = nf.value(); // Verify note has not been spent EXPECT_FALSE(wallet.IsSaplingSpent(nullifier)); @@ -898,7 +900,7 @@ TEST(WalletTests, NavigateFromSaplingNullifierToNote) { // Manually compute the nullifier based on the expected position auto nf = testNote.note.nullifier(extfvk.fvk, testNote.tree.witness().position()); ASSERT_TRUE(nf); - uint256 nullifier = nf.get(); + uint256 nullifier = nf.value(); // Verify dummy note is unspent EXPECT_FALSE(wallet.IsSaplingSpent(nullifier)); @@ -950,7 +952,7 @@ TEST(WalletTests, NavigateFromSaplingNullifierToNote) { EXPECT_EQ(hash, op.hash); EXPECT_EQ(1, nd.witnesses.size()); ASSERT_TRUE(nd.nullifier); - auto nf = nd.nullifier.get(); + auto nf = nd.nullifier.value(); EXPECT_EQ(1, wallet.mapSaplingNullifiersToNotes.count(nf)); EXPECT_EQ(op.hash, wallet.mapSaplingNullifiersToNotes[nf].hash); EXPECT_EQ(op.n, wallet.mapSaplingNullifiersToNotes[nf].n); @@ -1016,7 +1018,7 @@ TEST(WalletTests, SpentSaplingNoteIsFromMe) { // Generate Sapling note A libzcash::SaplingNote note(pk, 50000, zip_212_enabled[ver]); - auto cm = note.cmu().get(); + auto cm = note.cmu().value(); SaplingMerkleTree saplingTree; saplingTree.append(cm); auto anchor = saplingTree.root(); @@ -1068,7 +1070,7 @@ TEST(WalletTests, SpentSaplingNoteIsFromMe) { // Manually compute the nullifier and check map entry does not exist auto nf = note.nullifier(extfvk.fvk, witness.position()); ASSERT_TRUE(nf); - ASSERT_FALSE(wallet.mapSaplingNullifiersToNotes.count(nf.get())); + ASSERT_FALSE(wallet.mapSaplingNullifiersToNotes.count(nf.value())); // Decrypt note B auto maybe_pt = libzcash::SaplingNotePlaintext::decrypt( @@ -1079,16 +1081,16 @@ TEST(WalletTests, SpentSaplingNoteIsFromMe) { wtx.vShieldedOutput[0].ephemeralKey, wtx.vShieldedOutput[0].cmu); ASSERT_EQ(static_cast(maybe_pt), true); - auto maybe_note = maybe_pt.get().note(ivk); + auto maybe_note = maybe_pt.value().note(ivk); ASSERT_EQ(static_cast(maybe_note), true); - auto note2 = maybe_note.get(); + auto note2 = maybe_note.value(); // Get witness to retrieve position of note B we want to spend SaplingOutPoint sop0(wtx.GetHash(), 0); auto spend_note_witness = wtx.mapSaplingNoteData[sop0].witnesses.front(); auto maybe_nf = note2.nullifier(extfvk.fvk, spend_note_witness.position()); ASSERT_EQ(static_cast(maybe_nf), true); - auto nullifier2 = maybe_nf.get(); + auto nullifier2 = maybe_nf.value(); // NOTE: Not updating the anchor results in a core dump. Shouldn't builder just return error? // *** Error in `./zcash-gtest': double free or corruption (out): 0x00007ffd8755d990 *** @@ -1168,8 +1170,8 @@ TEST(WalletTests, CachedWitnessesEmptyChain) { std::vector sproutNotes {jsoutpt, jsoutpt2}; std::vector saplingNotes = SetSaplingNoteData(wtx); - std::vector> sproutWitnesses; - std::vector> saplingWitnesses; + std::vector> sproutWitnesses; + std::vector> saplingWitnesses; ::GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses); @@ -1223,8 +1225,8 @@ TEST(WalletTests, CachedWitnessesChainTip) { // Called to fetch anchor std::vector sproutNotes {outpts.first}; std::vector saplingNotes {outpts.second}; - std::vector> sproutWitnesses; - std::vector> saplingWitnesses; + std::vector> sproutWitnesses; + std::vector> saplingWitnesses; anchors1 = GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses); EXPECT_NE(anchors1.first, anchors1.second); @@ -1245,8 +1247,8 @@ TEST(WalletTests, CachedWitnessesChainTip) { wallet.AddToWallet(wtx, true, NULL); std::vector sproutNotes {jsoutpt}; - std::vector> sproutWitnesses; - std::vector> saplingWitnesses; + std::vector> sproutWitnesses; + std::vector> saplingWitnesses; GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses); @@ -1293,8 +1295,8 @@ TEST(WalletTests, CachedWitnessesChainTip) { // Incrementing with the same block again should not change the cache wallet.IncrementNoteWitnesses(&index2, &block2, sproutTree, saplingTree); - std::vector> sproutWitnesses5; - std::vector> saplingWitnesses5; + std::vector> sproutWitnesses5; + std::vector> saplingWitnesses5; auto anchors5 = GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses5, saplingWitnesses5); EXPECT_NE(anchors5.first, anchors5.second); @@ -1335,8 +1337,8 @@ TEST(WalletTests, CachedWitnessesDecrementFirst) { // Called to fetch anchor std::vector sproutNotes {outpts.first}; std::vector saplingNotes {outpts.second}; - std::vector> sproutWitnesses; - std::vector> saplingWitnesses; + std::vector> sproutWitnesses; + std::vector> saplingWitnesses; anchors2 = GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses); } @@ -1355,8 +1357,8 @@ TEST(WalletTests, CachedWitnessesDecrementFirst) { wallet.AddToWallet(wtx, true, NULL); std::vector sproutNotes {jsoutpt}; - std::vector> sproutWitnesses; - std::vector> saplingWitnesses; + std::vector> sproutWitnesses; + std::vector> saplingWitnesses; auto anchors3 = GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses); @@ -1400,8 +1402,8 @@ TEST(WalletTests, CachedWitnessesCleanIndex) { SproutMerkleTree sproutRiTree = sproutTree; SaplingMerkleTree saplingTree; SaplingMerkleTree saplingRiTree = saplingTree; - std::vector> sproutWitnesses; - std::vector> saplingWitnesses; + std::vector> sproutWitnesses; + std::vector> saplingWitnesses; auto sk = libzcash::SproutSpendingKey::random(); wallet.AddSproutSpendingKey(sk); @@ -1517,8 +1519,8 @@ TEST(WalletTests, ClearNoteWitnessCache) { saplingNotes.emplace_back(wtx.GetHash(), 1); ASSERT_EQ(saplingNotes.size(), 2); - std::vector> sproutWitnesses; - std::vector> saplingWitnesses; + std::vector> sproutWitnesses; + std::vector> saplingWitnesses; // Before clearing, we should have a witness for one note GetWitnessesAndAnchors(wallet, sproutNotes, saplingNotes, sproutWitnesses, saplingWitnesses); @@ -2006,9 +2008,9 @@ TEST(WalletTests, MarkAffectedSaplingTransactionsDirty) { // Prepare to spend the note that was just created auto maybe_pt = libzcash::SaplingNotePlaintext::decrypt(consensusParams, fakeIndex.nHeight, tx1.vShieldedOutput[0].encCiphertext, ivk, tx1.vShieldedOutput[0].ephemeralKey, tx1.vShieldedOutput[0].cmu); ASSERT_EQ(static_cast(maybe_pt), true); - auto maybe_note = maybe_pt.get().note(ivk); + auto maybe_note = maybe_pt.value().note(ivk); ASSERT_EQ(static_cast(maybe_note), true); - auto note = maybe_note.get(); + auto note = maybe_note.value(); auto anchor = saplingTree.root(); auto witness = saplingTree.witness(); diff --git a/src/wallet/gtest/test_wallet_zkeys.cpp b/src/wallet/gtest/test_wallet_zkeys.cpp index fc205589a..baa4a0d98 100644 --- a/src/wallet/gtest/test_wallet_zkeys.cpp +++ b/src/wallet/gtest/test_wallet_zkeys.cpp @@ -71,7 +71,7 @@ TEST(WalletZkeysTest, StoreAndLoadSaplingZkeys) { // If we can't get an early diversified address, we are very unlucky blob88 diversifier; diversifier.begin()[0] = 10; - auto dpa = sk.ToXFVK().Address(diversifier).get().second; + auto dpa = sk.ToXFVK().Address(diversifier).value().second; // verify wallet only has the default address EXPECT_TRUE(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress())); @@ -99,7 +99,7 @@ TEST(WalletZkeysTest, StoreAndLoadSaplingZkeys) { ASSERT_EQ(wallet.mapSaplingZKeyMetadata[ivk2].nCreateTime, now); // Load a diversified address for the third key into the wallet - auto dpa2 = sk2.ToXFVK().Address(diversifier).get().second; + auto dpa2 = sk2.ToXFVK().Address(diversifier).value().second; EXPECT_TRUE(wallet.HaveSaplingIncomingViewingKey(sk2.DefaultAddress())); EXPECT_FALSE(wallet.HaveSaplingIncomingViewingKey(dpa2)); EXPECT_TRUE(wallet.LoadSaplingPaymentAddress(dpa2, ivk2)); @@ -451,7 +451,7 @@ TEST(wallet_zkeys_tests, WriteCryptedSaplingZkeyDirectToDb) { EXPECT_TRUE(wallet.GetSaplingExtendedSpendingKey(address, extsk)); blob88 diversifier; diversifier.begin()[0] = 10; - auto dpa = extsk.ToXFVK().Address(diversifier).get().second; + auto dpa = extsk.ToXFVK().Address(diversifier).value().second; // Add diversified address to the wallet auto ivk = extsk.expsk.full_viewing_key().in_viewing_key(); diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 5f4e92f2a..f69dbd999 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -15,6 +15,7 @@ #include "wallet.h" #include +#include #include #include @@ -397,8 +398,8 @@ UniValue importwallet_impl(const UniValue& params, bool fImportZKeys) auto spendingkey = keyIO.DecodeSpendingKey(vstr[0]); int64_t nTime = DecodeDumpTime(vstr[1]); // Only include hdKeypath and seedFpStr if we have both - boost::optional hdKeypath = (vstr.size() > 3) ? boost::optional(vstr[2]) : boost::none; - boost::optional seedFpStr = (vstr.size() > 3) ? boost::optional(vstr[3]) : boost::none; + std::optional hdKeypath = (vstr.size() > 3) ? std::optional(vstr[2]) : std::nullopt; + std::optional seedFpStr = (vstr.size() > 3) ? std::optional(vstr[3]) : std::nullopt; if (IsValidSpendingKey(spendingkey)) { auto addResult = std::visit( AddSpendingKeyToWallet(pwalletMain, Params().GetConsensus(), nTime, hdKeypath, seedFpStr, true), spendingkey); @@ -912,7 +913,7 @@ UniValue z_exportkey(const UniValue& params, bool fHelp) if (!sk) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet does not hold private zkey for this zaddr"); } - return keyIO.EncodeSpendingKey(sk.get()); + return keyIO.EncodeSpendingKey(sk.value()); } UniValue z_exportviewingkey(const UniValue& params, bool fHelp) @@ -948,7 +949,7 @@ UniValue z_exportviewingkey(const UniValue& params, bool fHelp) auto vk = std::visit(GetViewingKeyForPaymentAddress(pwalletMain), address); if (vk) { - return keyIO.EncodeViewingKey(vk.get()); + return keyIO.EncodeViewingKey(vk.value()); } else { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet does not hold private key or viewing key for this zaddr"); } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 02215d6ce..dc15a7e2c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -44,6 +44,7 @@ #include #include +#include #include using namespace std; @@ -2975,7 +2976,7 @@ UniValue zc_raw_receive(const UniValue& params, bool fHelp) SproutNote decrypted_note = npt.note(payment_addr); assert(pwalletMain != NULL); - std::vector> witnesses; + std::vector> witnesses; uint256 anchor; uint256 commitment = decrypted_note.cm(); pwalletMain->WitnessNoteCommitment( @@ -3084,7 +3085,7 @@ UniValue zc_raw_joinsplit(const UniValue& params, bool fHelp) } uint256 anchor; - std::vector> witnesses; + std::vector> witnesses; pwalletMain->WitnessNoteCommitment(commitments, witnesses, anchor); assert(witnesses.size() == notes.size()); @@ -3805,7 +3806,7 @@ UniValue z_viewtransaction(const UniValue& params, bool fHelp) // We don't need to check the leadbyte here: if wtx exists in // the wallet, it must have already passed the leadbyte check - auto decrypted = wtxPrev.DecryptSaplingNoteWithoutLeadByteCheck(op).get(); + auto decrypted = wtxPrev.DecryptSaplingNoteWithoutLeadByteCheck(op).value(); auto notePt = decrypted.first; auto pa = decrypted.second; @@ -4257,7 +4258,7 @@ UniValue z_sendmany(const UniValue& params, bool fHelp) } // Builder (used if Sapling addresses are involved) - boost::optional builder; + std::optional builder; if (noSproutAddrs) { builder = TransactionBuilder(Params().GetConsensus(), nextBlockHeight, pwalletMain); } @@ -5035,7 +5036,7 @@ UniValue z_mergetoaddress(const UniValue& params, bool fHelp) } // Builder (used if Sapling addresses are involved) - boost::optional builder; + std::optional builder; if (isToSaplingZaddr || saplingNoteInputs.size() > 0) { builder = TransactionBuilder(Params().GetConsensus(), nextBlockHeight, pwalletMain); } diff --git a/src/wallet/test/rpc_wallet_tests.cpp b/src/wallet/test/rpc_wallet_tests.cpp index a3f778f2b..498e7f6a5 100644 --- a/src/wallet/test/rpc_wallet_tests.cpp +++ b/src/wallet/test/rpc_wallet_tests.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include @@ -1093,26 +1094,26 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_parameters) // Test constructor of AsyncRPCOperation_sendmany try { - std::shared_ptr operation(new AsyncRPCOperation_sendmany(boost::none, mtx, "",{}, {}, -1)); + std::shared_ptr operation(new AsyncRPCOperation_sendmany(std::nullopt, mtx, "",{}, {}, -1)); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "Minconf cannot be negative")); } try { - std::shared_ptr operation(new AsyncRPCOperation_sendmany(boost::none, mtx, "",{}, {}, 1)); + std::shared_ptr operation(new AsyncRPCOperation_sendmany(std::nullopt, mtx, "",{}, {}, 1)); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "From address parameter missing")); } try { - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, "tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ", {}, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, "tmRr6yJonqGK23UVhrKuyvTpF8qxQQjKigJ", {}, {}, 1) ); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "No recipients")); } try { std::vector recipients = { SendManyRecipient("dummy",1.0, "") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, "INVALID", recipients, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, "INVALID", recipients, {}, 1) ); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "Invalid from address")); } @@ -1120,7 +1121,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_parameters) // Testnet payment addresses begin with 'zt'. This test detects an incorrect prefix. try { std::vector recipients = { SendManyRecipient("dummy",1.0, "") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, "zcMuhvq8sEkHALuSU2i4NbNQxshSAYrpCExec45ZjtivYPbuiFPwk6WHy4SvsbeZ4siy1WheuRGjtaJmoD1J8bFqNXhsG6U", recipients, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, "zcMuhvq8sEkHALuSU2i4NbNQxshSAYrpCExec45ZjtivYPbuiFPwk6WHy4SvsbeZ4siy1WheuRGjtaJmoD1J8bFqNXhsG6U", recipients, {}, 1) ); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "Invalid from address")); } @@ -1129,7 +1130,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_parameters) // invokes a method on pwalletMain, which is undefined in the google test environment. try { std::vector recipients = { SendManyRecipient("dummy",1.0, "") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, "ztjiDe569DPNbyTE6TSdJTaSDhoXEHLGvYoUnBU1wfVNU52TEyT6berYtySkd21njAeEoh8fFJUT42kua9r8EnhBaEKqCpP", recipients, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, "ztjiDe569DPNbyTE6TSdJTaSDhoXEHLGvYoUnBU1wfVNU52TEyT6berYtySkd21njAeEoh8fFJUT42kua9r8EnhBaEKqCpP", recipients, {}, 1) ); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "no spending key found for zaddr")); } @@ -1141,7 +1142,7 @@ BOOST_AUTO_TEST_CASE(asyncrpcoperation_sign_send_raw_transaction) { UniValue obj(UniValue::VOBJ); obj.pushKV("rawtxn", raw); // Verify test mode is returning output (since no input taddrs, signed and unsigned are the same). - std::pair txAndResult = SignSendRawTransaction(obj, boost::none, true); + std::pair txAndResult = SignSendRawTransaction(obj, std::nullopt, true); UniValue resultObj = txAndResult.second.get_obj(); std::string hex = find_value(resultObj, "hex").get_str(); BOOST_CHECK_EQUAL(hex, raw); @@ -1176,7 +1177,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) // there are no utxos to spend { std::vector recipients = { SendManyRecipient(zaddr1,100.0, "DEADBEEF") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, taddr1, {}, recipients, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, taddr1, {}, recipients, 1) ); operation->main(); BOOST_CHECK(operation->isFailed()); std::string msg = operation->getErrorMessage(); @@ -1187,7 +1188,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) { try { std::vector recipients = {SendManyRecipient(taddr1, 100.0, "DEADBEEF")}; - std::shared_ptr operation(new AsyncRPCOperation_sendmany(boost::none, mtx, zaddr1, recipients, {}, 0)); + std::shared_ptr operation(new AsyncRPCOperation_sendmany(std::nullopt, mtx, zaddr1, recipients, {}, 0)); BOOST_CHECK(false); // Fail test if an exception is not thrown } catch (const UniValue& objError) { BOOST_CHECK(find_error(objError, "Minconf cannot be zero when sending from zaddr")); @@ -1198,7 +1199,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) // there are no unspent notes to spend { std::vector recipients = { SendManyRecipient(taddr1,100.0, "DEADBEEF") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, zaddr1, recipients, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, zaddr1, recipients, {}, 1) ); operation->main(); BOOST_CHECK(operation->isFailed()); std::string msg = operation->getErrorMessage(); @@ -1208,7 +1209,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) // get_memo_from_hex_string()) { std::vector recipients = { SendManyRecipient(zaddr1,100.0, "DEADBEEF") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, zaddr1, recipients, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, zaddr1, recipients, {}, 1) ); std::shared_ptr ptr = std::dynamic_pointer_cast (operation); TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr); @@ -1259,7 +1260,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) // add_taddr_change_output_to_tx() will append a vout to a raw transaction { std::vector recipients = { SendManyRecipient(zaddr1,100.0, "DEADBEEF") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, zaddr1, recipients, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, zaddr1, recipients, {}, 1) ); std::shared_ptr ptr = std::dynamic_pointer_cast (operation); TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr); @@ -1289,7 +1290,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) SendManyRecipient("tmUSbHz3vxnwLvRyNDXbwkZxjVyDodMJEhh",CAmount(4.56), ""), SendManyRecipient("tmYZAXYPCP56Xa5JQWWPZuK7o7bfUQW6kkd",CAmount(7.89), ""), }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, zaddr1, recipients, {}, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, zaddr1, recipients, {}, 1) ); std::shared_ptr ptr = std::dynamic_pointer_cast (operation); TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr); @@ -1307,7 +1308,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) // Dummy input so the operation object can be instantiated. std::vector recipients = { SendManyRecipient(zaddr1, 0.0005, "ABCD") }; - std::shared_ptr operation( new AsyncRPCOperation_sendmany(boost::none, mtx, zaddr1, {}, recipients, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_sendmany(std::nullopt, mtx, zaddr1, {}, recipients, 1) ); std::shared_ptr ptr = std::dynamic_pointer_cast (operation); TEST_FRIEND_AsyncRPCOperation_sendmany proxy(ptr); @@ -1315,7 +1316,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_sendmany_internals) static_cast(operation.get())->testmode = true; AsyncJoinSplitInfo info; - std::vector> witnesses; + std::vector> witnesses; uint256 anchor; try { proxy.perform_joinsplit(info, witnesses, anchor); @@ -1854,14 +1855,14 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_parameters) "mainnet memo"); try { - std::shared_ptr operation(new AsyncRPCOperation_mergetoaddress(boost::none, mtx, {}, {}, {}, testnetzaddr, -1 )); + std::shared_ptr operation(new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, {}, {}, {}, testnetzaddr, -1 )); BOOST_FAIL("Should have caused an error"); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "Fee is out of range")); } try { - std::shared_ptr operation(new AsyncRPCOperation_mergetoaddress(boost::none, mtx, {}, {}, {}, testnetzaddr, 1)); + std::shared_ptr operation(new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, {}, {}, {}, testnetzaddr, 1)); BOOST_FAIL("Should have caused an error"); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "No inputs")); @@ -1871,7 +1872,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_parameters) try { MergeToAddressRecipient badaddr("", "memo"); - std::shared_ptr operation(new AsyncRPCOperation_mergetoaddress(boost::none, mtx, inputs, {}, {}, badaddr, 1)); + std::shared_ptr operation(new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, inputs, {}, {}, badaddr, 1)); BOOST_FAIL("Should have caused an error"); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "Recipient parameter missing")); @@ -1884,7 +1885,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_parameters) // Sprout and Sapling inputs -> throw try { - auto operation = new AsyncRPCOperation_mergetoaddress(boost::none, mtx, inputs, sproutNoteInputs, saplingNoteInputs, testnetzaddr, 1); + auto operation = new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, inputs, sproutNoteInputs, saplingNoteInputs, testnetzaddr, 1); BOOST_FAIL("Should have caused an error"); } catch (const UniValue& objError) { BOOST_CHECK(find_error(objError, "Cannot send from both Sprout and Sapling addresses using z_mergetoaddress")); @@ -1900,7 +1901,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_parameters) // Testnet payment addresses begin with 'zt'. This test detects an incorrect prefix. try { std::vector inputs = { MergeToAddressInputUTXO{ COutPoint{uint256(), 0}, 0, CScript()} }; - std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(boost::none, mtx, inputs, {}, {}, mainnetzaddr, 1) ); + std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, inputs, {}, {}, mainnetzaddr, 1) ); BOOST_FAIL("Should have caused an error"); } catch (const UniValue& objError) { BOOST_CHECK( find_error(objError, "Invalid recipient address")); @@ -1934,7 +1935,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_internals) // Insufficient funds { std::vector inputs = { MergeToAddressInputUTXO{COutPoint{uint256(),0},0, CScript()} }; - std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(boost::none, mtx, inputs, {}, {}, zaddr1) ); + std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, inputs, {}, {}, zaddr1) ); operation->main(); BOOST_CHECK(operation->isFailed()); std::string msg = operation->getErrorMessage(); @@ -1944,7 +1945,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_internals) // get_memo_from_hex_string()) { std::vector inputs = { MergeToAddressInputUTXO{COutPoint{uint256(),0},100000, CScript()} }; - std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(boost::none, mtx, inputs, {}, {}, zaddr1) ); + std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, inputs, {}, {}, zaddr1) ); std::shared_ptr ptr = std::dynamic_pointer_cast (operation); TEST_FRIEND_AsyncRPCOperation_mergetoaddress proxy(ptr); @@ -1998,7 +1999,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_internals) { // Dummy input so the operation object can be instantiated. std::vector inputs = { MergeToAddressInputUTXO{COutPoint{uint256(),0},100000, CScript()} }; - std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(boost::none, mtx, inputs, {}, {}, zaddr1) ); + std::shared_ptr operation( new AsyncRPCOperation_mergetoaddress(std::nullopt, mtx, inputs, {}, {}, zaddr1) ); std::shared_ptr ptr = std::dynamic_pointer_cast (operation); TEST_FRIEND_AsyncRPCOperation_mergetoaddress proxy(ptr); @@ -2006,7 +2007,7 @@ BOOST_AUTO_TEST_CASE(rpc_z_mergetoaddress_internals) static_cast(operation.get())->testmode = true; MergeToAddressJSInfo info; - std::vector> witnesses; + std::vector> witnesses; uint256 anchor; try { proxy.perform_joinsplit(info, witnesses, anchor); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 3014b4230..31fb5d920 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -605,7 +605,7 @@ void CWallet::ChainTipAdded(const CBlockIndex *pindex, void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock, - boost::optional> added) + std::optional> added) { if (added) { ChainTipAdded(pindex, pblock, added->first, added->second); @@ -656,7 +656,7 @@ void CWallet::RunSaplingMigration(int blockHeight) { for (const CTransaction& transaction : pendingSaplingMigrationTxs) { // Send the transaction CWalletTx wtx(this, transaction); - CommitTransaction(wtx, boost::none); + CommitTransaction(wtx, std::nullopt); } pendingSaplingMigrationTxs.clear(); } @@ -695,7 +695,7 @@ std::set> CWallet::GetNullifiersFor auto & nullifier = noteData.nullifier; auto & address = noteData.address; if (nullifier && addresses.count(address)) { - nullifierSet.insert(std::make_pair(address, nullifier.get())); + nullifierSet.insert(std::make_pair(address, nullifier.value())); } } // Sapling @@ -705,7 +705,7 @@ std::set> CWallet::GetNullifiersFor auto & ivk = noteData.ivk; if (nullifier && ivkMap.count(ivk)) { for (const auto & addr : ivkMap[ivk]) { - nullifierSet.insert(std::make_pair(addr, nullifier.get())); + nullifierSet.insert(std::make_pair(addr, nullifier.value())); } } } @@ -1506,9 +1506,9 @@ void CWallet::UpdateSaplingNullifierNoteMapWithTx(CWalletTx& wtx) { if (nd.witnesses.empty()) { // If there are no witnesses, erase the nullifier and associated mapping. if (item.second.nullifier) { - mapSaplingNullifiersToNotes.erase(item.second.nullifier.get()); + mapSaplingNullifiersToNotes.erase(item.second.nullifier.value()); } - item.second.nullifier = boost::none; + item.second.nullifier = std::nullopt; } else { uint64_t position = nd.witnesses.front().position(); @@ -1519,21 +1519,21 @@ void CWallet::UpdateSaplingNullifierNoteMapWithTx(CWalletTx& wtx) { // The transaction would not have entered the wallet unless // its plaintext had been successfully decrypted previously. - assert(optDeserialized != boost::none); + assert(optDeserialized != std::nullopt); auto optPlaintext = SaplingNotePlaintext::plaintext_checks_without_height(*optDeserialized, nd.ivk, output.ephemeralKey, output.cmu); // An item in mapSaplingNoteData must have already been successfully decrypted, // otherwise the item would not exist in the first place. - assert(optPlaintext != boost::none); + assert(optPlaintext != std::nullopt); - auto optNote = optPlaintext.get().note(nd.ivk); - assert(optNote != boost::none); + auto optNote = optPlaintext.value().note(nd.ivk); + assert(optNote != std::nullopt); - auto optNullifier = optNote.get().nullifier(extfvk.fvk, position); + auto optNullifier = optNote.value().nullifier(extfvk.fvk, position); // This should not happen. If it does, maybe the position has been corrupted or miscalculated? - assert(optNullifier != boost::none); - uint256 nullifier = optNullifier.get(); + assert(optNullifier != std::nullopt); + uint256 nullifier = optNullifier.value(); mapSaplingNullifiersToNotes[nullifier] = op; item.second.nullifier = nullifier; } @@ -1825,13 +1825,13 @@ void CWallet::EraseFromWallet(const uint256 &hash) * Returns a nullifier if the SpendingKey is available * Throws std::runtime_error if the decryptor doesn't match this note */ -boost::optional CWallet::GetSproutNoteNullifier(const JSDescription &jsdesc, +std::optional CWallet::GetSproutNoteNullifier(const JSDescription &jsdesc, const libzcash::SproutPaymentAddress &address, const ZCNoteDecryption &dec, const uint256 &hSig, uint8_t n) const { - boost::optional ret; + std::optional ret; auto note_pt = libzcash::SproutNotePlaintext::decrypt( dec, jsdesc.ciphertexts[n], @@ -1932,9 +1932,9 @@ std::pair CWallet::FindMySap if (!result) { continue; } - auto address = ivk.address(result.get().d); - if (address && mapSaplingIncomingViewingKeys.count(address.get()) == 0) { - viewingKeysToAdd[address.get()] = ivk; + auto address = ivk.address(result.value().d); + if (address && mapSaplingIncomingViewingKeys.count(address.value()) == 0) { + viewingKeysToAdd[address.value()] = ivk; } // We don't cache the nullifier here as computing it requires knowledge of the note position // in the commitment tree, which can only be determined when the transaction has been mined. @@ -1974,12 +1974,12 @@ bool CWallet::IsSaplingNullifierFromMe(const uint256& nullifier) const } void CWallet::GetSproutNoteWitnesses(std::vector notes, - std::vector>& witnesses, + std::vector>& witnesses, uint256 &final_anchor) { LOCK(cs_wallet); witnesses.resize(notes.size()); - boost::optional rt; + std::optional rt; int i = 0; for (JSOutPoint note : notes) { if (mapWallet.count(note.hash) && @@ -2001,12 +2001,12 @@ void CWallet::GetSproutNoteWitnesses(std::vector notes, } void CWallet::GetSaplingNoteWitnesses(std::vector notes, - std::vector>& witnesses, + std::vector>& witnesses, uint256 &final_anchor) { LOCK(cs_wallet); witnesses.resize(notes.size()); - boost::optional rt; + std::optional rt; int i = 0; for (SaplingOutPoint note : notes) { if (mapWallet.count(note.hash) && @@ -2329,13 +2329,13 @@ std::pair CWalletTx::DecryptSproutNot } } -boost::optional> CWalletTx::DecryptSaplingNote(const Consensus::Params& params, int height, SaplingOutPoint op) const { // Check whether we can decrypt this SaplingOutPoint if (this->mapSaplingNoteData.count(op) == 0) { - return boost::none; + return std::nullopt; } auto output = this->vShieldedOutput[op.n]; @@ -2348,23 +2348,23 @@ boost::optional> CWalletTx::DecryptSaplingNoteWithoutLeadByteCheck(SaplingOutPoint op) const { // Check whether we can decrypt this SaplingOutPoint if (this->mapSaplingNoteData.count(op) == 0) { - return boost::none; + return std::nullopt; } auto output = this->vShieldedOutput[op.n]; @@ -2374,24 +2374,24 @@ boost::optional(maybe_pa)); - auto pa = maybe_pa.get(); + auto pa = maybe_pa.value(); return std::make_pair(notePt, pa); } -boost::optional> CWalletTx::RecoverSaplingNote(const Consensus::Params& params, int height, SaplingOutPoint op, std::set& ovks) const { @@ -2418,16 +2418,16 @@ boost::optionalpk_d, output.cmu); assert(static_cast(maybe_pt)); - auto notePt = maybe_pt.get(); + auto notePt = maybe_pt.value(); return std::make_pair(notePt, SaplingPaymentAddress(notePt.d, outPt->pk_d)); } // Couldn't recover with any of the provided OutgoingViewingKeys - return boost::none; + return std::nullopt; } -boost::optional> CWalletTx::RecoverSaplingNoteWithoutLeadByteCheck(SaplingOutPoint op, std::set& ovks) const { @@ -2449,7 +2449,7 @@ boost::optionalpk_d, output.cmu); assert(static_cast(maybe_pt)); - auto notePt = maybe_pt.get(); + auto notePt = maybe_pt.value(); return std::make_pair(notePt, SaplingPaymentAddress(notePt.d, outPt->pk_d)); } // Couldn't recover with any of the provided OutgoingViewingKeys - return boost::none; + return std::nullopt; } int64_t CWalletTx::GetTxTime() const @@ -2670,7 +2670,7 @@ bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb) } void CWallet::WitnessNoteCommitment(std::vector commitments, - std::vector>& witnesses, + std::vector>& witnesses, uint256 &final_anchor) { witnesses.resize(commitments.size()); @@ -2689,7 +2689,7 @@ void CWallet::WitnessNoteCommitment(std::vector commitments, { tree.append(note_commitment); - BOOST_FOREACH(boost::optional& wit, witnesses) { + BOOST_FOREACH(std::optional& wit, witnesses) { if (wit) { wit->append(note_commitment); } @@ -2719,7 +2719,7 @@ void CWallet::WitnessNoteCommitment(std::vector commitments, // TODO: #93; Select a root via some heuristic. final_anchor = tree.root(); - BOOST_FOREACH(boost::optional& wit, witnesses) { + BOOST_FOREACH(std::optional& wit, witnesses) { if (wit) { assert(final_anchor == wit->root()); } @@ -3834,7 +3834,7 @@ bool CWallet::CreateTransaction(const vector& vecSend, CWalletTx& wt /** * Call after CreateTransaction unless you want to abort */ -bool CWallet::CommitTransaction(CWalletTx& wtxNew, boost::optional reservekey) +bool CWallet::CommitTransaction(CWalletTx& wtxNew, std::optional> reservekey) { { LOCK2(cs_main, cs_wallet); @@ -3847,7 +3847,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, boost::optional if (reservekey) { // Take key pair from key pool so it won't be used again - reservekey.get().KeepKey(); + reservekey.value().get().KeepKey(); } // Add tx to wallet, because if it has change it's also ours, @@ -5091,12 +5091,12 @@ void CWallet::GetFilteredNotes( // The transaction would not have entered the wallet unless // its plaintext had been successfully decrypted previously. - assert(optDeserialized != boost::none); + assert(optDeserialized != std::nullopt); - auto notePt = optDeserialized.get(); + auto notePt = optDeserialized.value(); auto maybe_pa = nd.ivk.address(notePt.d); assert(static_cast(maybe_pa)); - auto pa = maybe_pa.get(); + auto pa = maybe_pa.value(); // skip notes which belong to a different payment address in the wallet if (!(filterAddresses.empty() || filterAddresses.count(pa))) { @@ -5117,7 +5117,7 @@ void CWallet::GetFilteredNotes( continue; } - auto note = notePt.note(nd.ivk).get(); + auto note = notePt.note(nd.ivk).value(); saplingEntries.push_back(SaplingNoteEntry { op, pa, note, notePt.memo(), wtx.GetDepthInMainChain() }); } @@ -5149,21 +5149,21 @@ bool PaymentAddressBelongsToWallet::operator()(const libzcash::InvalidEncoding& return false; } -boost::optional GetViewingKeyForPaymentAddress::operator()( +std::optional GetViewingKeyForPaymentAddress::operator()( const libzcash::SproutPaymentAddress &zaddr) const { libzcash::SproutViewingKey vk; if (!m_wallet->GetSproutViewingKey(zaddr, vk)) { libzcash::SproutSpendingKey k; if (!m_wallet->GetSproutSpendingKey(zaddr, k)) { - return boost::none; + return std::nullopt; } vk = k.viewing_key(); } return libzcash::ViewingKey(vk); } -boost::optional GetViewingKeyForPaymentAddress::operator()( +std::optional GetViewingKeyForPaymentAddress::operator()( const libzcash::SaplingPaymentAddress &zaddr) const { libzcash::SaplingIncomingViewingKey ivk; @@ -5174,11 +5174,11 @@ boost::optional GetViewingKeyForPaymentAddress::operator() { return libzcash::ViewingKey(extfvk); } else { - return boost::none; + return std::nullopt; } } -boost::optional GetViewingKeyForPaymentAddress::operator()( +std::optional GetViewingKeyForPaymentAddress::operator()( const libzcash::InvalidEncoding& no) const { // Defaults to InvalidEncoding @@ -5205,29 +5205,29 @@ bool HaveSpendingKeyForPaymentAddress::operator()(const libzcash::InvalidEncodin return false; } -boost::optional GetSpendingKeyForPaymentAddress::operator()( +std::optional GetSpendingKeyForPaymentAddress::operator()( const libzcash::SproutPaymentAddress &zaddr) const { libzcash::SproutSpendingKey k; if (m_wallet->GetSproutSpendingKey(zaddr, k)) { return libzcash::SpendingKey(k); } else { - return boost::none; + return std::nullopt; } } -boost::optional GetSpendingKeyForPaymentAddress::operator()( +std::optional GetSpendingKeyForPaymentAddress::operator()( const libzcash::SaplingPaymentAddress &zaddr) const { libzcash::SaplingExtendedSpendingKey extsk; if (m_wallet->GetSaplingExtendedSpendingKey(zaddr, extsk)) { return libzcash::SpendingKey(extsk); } else { - return boost::none; + return std::nullopt; } } -boost::optional GetSpendingKeyForPaymentAddress::operator()( +std::optional GetSpendingKeyForPaymentAddress::operator()( const libzcash::InvalidEncoding& no) const { // Defaults to InvalidEncoding @@ -5304,11 +5304,11 @@ KeyAddResult AddSpendingKeyToWallet::operator()(const libzcash::SaplingExtendedS m_wallet->mapSaplingZKeyMetadata[ivk].nCreateTime = std::max((int64_t) 154051200, nTime); } if (hdKeypath) { - m_wallet->mapSaplingZKeyMetadata[ivk].hdKeypath = hdKeypath.get(); + m_wallet->mapSaplingZKeyMetadata[ivk].hdKeypath = hdKeypath.value(); } if (seedFpStr) { uint256 seedFp; - seedFp.SetHex(seedFpStr.get()); + seedFp.SetHex(seedFpStr.value()); m_wallet->mapSaplingZKeyMetadata[ivk].seedFp = seedFp; } return KeyAdded; diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index fe7eb9321..1605645ba 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -28,7 +28,9 @@ #include "base58.h" #include +#include #include +#include #include #include #include @@ -228,7 +230,7 @@ class SproutNoteData * transactions they are spent in. This is the same security semantics as * for transparent addresses. */ - boost::optional nullifier; + std::optional nullifier; /** * Cached incremental witnesses for spendable Notes. @@ -291,7 +293,7 @@ class SaplingNoteData std::list witnesses; int witnessHeight; libzcash::SaplingIncomingViewingKey ivk; - boost::optional nullifier; + std::optional nullifier; ADD_SERIALIZE_METHODS; @@ -565,17 +567,17 @@ class CWalletTx : public CMerkleTx std::pair DecryptSproutNote( JSOutPoint jsop) const; - boost::optional> DecryptSaplingNote(const Consensus::Params& params, int height, SaplingOutPoint op) const; - boost::optional> DecryptSaplingNoteWithoutLeadByteCheck(SaplingOutPoint op) const; - boost::optional> RecoverSaplingNote(const Consensus::Params& params, int height, SaplingOutPoint op, std::set& ovks) const; - boost::optional> RecoverSaplingNoteWithoutLeadByteCheck(SaplingOutPoint op, std::set& ovks) const; @@ -1170,7 +1172,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface void EraseFromWallet(const uint256 &hash); void WitnessNoteCommitment( std::vector commitments, - std::vector>& witnesses, + std::vector>& witnesses, uint256 &final_anchor); int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false); void ReacceptWalletTransactions(); @@ -1195,7 +1197,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface */ bool CreateTransaction(const std::vector& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true); - bool CommitTransaction(CWalletTx& wtxNew, boost::optional reservekey); + bool CommitTransaction(CWalletTx& wtxNew, std::optional> reservekey); static CFeeRate minTxFee; /** @@ -1223,7 +1225,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface std::set GetAccountAddresses(const std::string& strAccount) const; - boost::optional GetSproutNoteNullifier( + std::optional GetSproutNoteNullifier( const JSDescription& jsdesc, const libzcash::SproutPaymentAddress& address, const ZCNoteDecryption& dec, @@ -1236,11 +1238,11 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface void GetSproutNoteWitnesses( std::vector notes, - std::vector>& witnesses, + std::vector>& witnesses, uint256 &final_anchor); void GetSaplingNoteWitnesses( std::vector notes, - std::vector>& witnesses, + std::vector>& witnesses, uint256 &final_anchor); isminetype IsMine(const CTxIn& txin) const; @@ -1258,7 +1260,7 @@ class CWallet : public CCryptoKeyStore, public CValidationInterface void ChainTip( const CBlockIndex *pindex, const CBlock *pblock, - boost::optional> added); + std::optional> added); void RunSaplingMigration(int blockHeight); void AddPendingSaplingMigrationTx(const CTransaction& tx); /** Saves witness caches and best block locator to disk. */ @@ -1478,9 +1480,9 @@ class GetViewingKeyForPaymentAddress public: GetViewingKeyForPaymentAddress(CWallet *wallet) : m_wallet(wallet) {} - boost::optional operator()(const libzcash::SproutPaymentAddress &zaddr) const; - boost::optional operator()(const libzcash::SaplingPaymentAddress &zaddr) const; - boost::optional operator()(const libzcash::InvalidEncoding& no) const; + std::optional operator()(const libzcash::SproutPaymentAddress &zaddr) const; + std::optional operator()(const libzcash::SaplingPaymentAddress &zaddr) const; + std::optional operator()(const libzcash::InvalidEncoding& no) const; }; class HaveSpendingKeyForPaymentAddress @@ -1502,9 +1504,9 @@ class GetSpendingKeyForPaymentAddress public: GetSpendingKeyForPaymentAddress(CWallet *wallet) : m_wallet(wallet) {} - boost::optional operator()(const libzcash::SproutPaymentAddress &zaddr) const; - boost::optional operator()(const libzcash::SaplingPaymentAddress &zaddr) const; - boost::optional operator()(const libzcash::InvalidEncoding& no) const; + std::optional operator()(const libzcash::SproutPaymentAddress &zaddr) const; + std::optional operator()(const libzcash::SaplingPaymentAddress &zaddr) const; + std::optional operator()(const libzcash::InvalidEncoding& no) const; }; enum KeyAddResult { @@ -1532,18 +1534,18 @@ class AddSpendingKeyToWallet CWallet *m_wallet; const Consensus::Params ¶ms; int64_t nTime; - boost::optional hdKeypath; // currently sapling only - boost::optional seedFpStr; // currently sapling only + std::optional hdKeypath; // currently sapling only + std::optional seedFpStr; // currently sapling only bool log; public: AddSpendingKeyToWallet(CWallet *wallet, const Consensus::Params ¶ms) : - m_wallet(wallet), params(params), nTime(1), hdKeypath(boost::none), seedFpStr(boost::none), log(false) {} + m_wallet(wallet), params(params), nTime(1), hdKeypath(std::nullopt), seedFpStr(std::nullopt), log(false) {} AddSpendingKeyToWallet( CWallet *wallet, const Consensus::Params ¶ms, int64_t _nTime, - boost::optional _hdKeypath, - boost::optional _seedFp, + std::optional _hdKeypath, + std::optional _seedFp, bool _log ) : m_wallet(wallet), params(params), nTime(_nTime), hdKeypath(_hdKeypath), seedFpStr(_seedFp), log(_log) {} diff --git a/src/zcash/IncrementalMerkleTree.cpp b/src/zcash/IncrementalMerkleTree.cpp index b8b3cd183..855f0b527 100644 --- a/src/zcash/IncrementalMerkleTree.cpp +++ b/src/zcash/IncrementalMerkleTree.cpp @@ -930,17 +930,17 @@ void IncrementalMerkleTree::append(Hash obj) { right = obj; } else { // Combine the leaves and propagate it up the tree - boost::optional combined = Hash::combine(*left, *right, 0); + std::optional combined = Hash::combine(*left, *right, 0); // Set the "left" leaf to the object and make the "right" leaf none left = obj; - right = boost::none; + right = std::nullopt; for (size_t i = 0; i < Depth; i++) { if (i < parents.size()) { if (parents[i]) { combined = Hash::combine(*parents[i], *combined, i+1); - parents[i] = boost::none; + parents[i] = std::nullopt; } else { parents[i] = *combined; break; @@ -966,7 +966,7 @@ bool IncrementalMerkleTree::is_complete(size_t depth) const { return false; } - BOOST_FOREACH(const boost::optional& parent, parents) { + BOOST_FOREACH(const std::optional& parent, parents) { if (!parent) { return false; } @@ -997,7 +997,7 @@ size_t IncrementalMerkleTree::next_depth(size_t skip) const { size_t d = 1; - BOOST_FOREACH(const boost::optional& parent, parents) { + BOOST_FOREACH(const std::optional& parent, parents) { if (!parent) { if (skip) { skip--; @@ -1025,7 +1025,7 @@ Hash IncrementalMerkleTree::root(size_t depth, size_t d = 1; - BOOST_FOREACH(const boost::optional& parent, parents) { + BOOST_FOREACH(const std::optional& parent, parents) { if (parent) { root = Hash::combine(*parent, root, d); } else { @@ -1068,7 +1068,7 @@ MerklePath IncrementalMerkleTree::path(std::deque filler_hash size_t d = 1; - BOOST_FOREACH(const boost::optional& parent, parents) { + BOOST_FOREACH(const std::optional& parent, parents) { if (parent) { index.push_back(true); path.push_back(*parent); @@ -1118,7 +1118,7 @@ void IncrementalWitness::append(Hash obj) { if (cursor->is_complete(cursor_depth)) { filled.push_back(cursor->root(cursor_depth)); - cursor = boost::none; + cursor = std::nullopt; } } else { cursor_depth = tree.next_depth(filled.size()); diff --git a/src/zcash/IncrementalMerkleTree.hpp b/src/zcash/IncrementalMerkleTree.hpp index 1ebb2b499..9ee9a8336 100644 --- a/src/zcash/IncrementalMerkleTree.hpp +++ b/src/zcash/IncrementalMerkleTree.hpp @@ -3,7 +3,8 @@ #include #include -#include +#include + #include #include "uint256.h" @@ -126,11 +127,11 @@ friend class IncrementalWitness; private: static EmptyMerkleRoots emptyroots; - boost::optional left; - boost::optional right; + std::optional left; + std::optional right; // Collapsed "left" subtrees ordered toward the root of the tree. - std::vector> parents; + std::vector> parents; MerklePath path(std::deque filler_hashes = std::deque()) const; Hash root(size_t depth, std::deque filler_hashes = std::deque()) const; bool is_complete(size_t depth = Depth) const; @@ -193,7 +194,7 @@ friend class IncrementalMerkleTree; private: IncrementalMerkleTree tree; std::vector filled; - boost::optional> cursor; + std::optional> cursor; size_t cursor_depth = 0; std::deque partial_path() const; IncrementalWitness(IncrementalMerkleTree tree) : tree(tree) {} diff --git a/src/zcash/Note.cpp b/src/zcash/Note.cpp index 23320c07a..938926287 100644 --- a/src/zcash/Note.cpp +++ b/src/zcash/Note.cpp @@ -59,7 +59,7 @@ SaplingNote::SaplingNote( } // Call librustzcash to compute the commitment -boost::optional SaplingNote::cmu() const { +std::optional SaplingNote::cmu() const { uint256 result; uint256 rcm_tmp = rcm(); if (!librustzcash_sapling_compute_cm( @@ -70,14 +70,14 @@ boost::optional SaplingNote::cmu() const { result.begin() )) { - return boost::none; + return std::nullopt; } return result; } // Call librustzcash to compute the nullifier -boost::optional SaplingNote::nullifier(const SaplingFullViewingKey& vk, const uint64_t position) const +std::optional SaplingNote::nullifier(const SaplingFullViewingKey& vk, const uint64_t position) const { auto ak = vk.ak; auto nk = vk.nk; @@ -95,7 +95,7 @@ boost::optional SaplingNote::nullifier(const SaplingFullViewingKey& vk, result.begin() )) { - return boost::none; + return std::nullopt; } return result; @@ -167,7 +167,7 @@ SaplingNotePlaintext::SaplingNotePlaintext( } -boost::optional SaplingNotePlaintext::note(const SaplingIncomingViewingKey& ivk) const +std::optional SaplingNotePlaintext::note(const SaplingIncomingViewingKey& ivk) const { auto addr = ivk.address(d); if (addr) { @@ -175,14 +175,14 @@ boost::optional SaplingNotePlaintext::note(const SaplingIncomingVie if (leadbyte != 0x01) { zip_212_enabled = Zip212Enabled::AfterZip212; }; - auto tmp = SaplingNote(d, addr.get().pk_d, value_, rseed, zip_212_enabled); + auto tmp = SaplingNote(d, addr.value().pk_d, value_, rseed, zip_212_enabled); return tmp; } else { - return boost::none; + return std::nullopt; } } -boost::optional SaplingOutgoingPlaintext::decrypt( +std::optional SaplingOutgoingPlaintext::decrypt( const SaplingOutCiphertext &ciphertext, const uint256& ovk, const uint256& cv, @@ -192,13 +192,13 @@ boost::optional SaplingOutgoingPlaintext::decrypt( { auto pt = AttemptSaplingOutDecryption(ciphertext, ovk, cv, cm, epk); if (!pt) { - return boost::none; + return std::nullopt; } // Deserialize from the plaintext try { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); - ss << pt.get(); + ss << pt.value(); SaplingOutgoingPlaintext ret; ss >> ret; assert(ss.size() == 0); @@ -206,11 +206,11 @@ boost::optional SaplingOutgoingPlaintext::decrypt( } catch (const boost::thread_interrupted&) { throw; } catch (...) { - return boost::none; + return std::nullopt; } } -boost::optional SaplingNotePlaintext::decrypt( +std::optional SaplingNotePlaintext::decrypt( const Consensus::Params& params, int height, const SaplingEncCiphertext &ciphertext, @@ -222,20 +222,20 @@ boost::optional SaplingNotePlaintext::decrypt( auto ret = attempt_sapling_enc_decryption_deserialization(ciphertext, ivk, epk); if (!ret) { - return boost::none; + return std::nullopt; } else { const SaplingNotePlaintext plaintext = *ret; // Check leadbyte is allowed at block height if (!plaintext_version_is_valid(params, height, plaintext.get_leadbyte())) { - return boost::none; + return std::nullopt; } return plaintext_checks_without_height(plaintext, ivk, epk, cmu); } } -boost::optional SaplingNotePlaintext::attempt_sapling_enc_decryption_deserialization( +std::optional SaplingNotePlaintext::attempt_sapling_enc_decryption_deserialization( const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk @@ -244,25 +244,25 @@ boost::optional SaplingNotePlaintext::attempt_sapling_enc_ auto encPlaintext = AttemptSaplingEncDecryption(ciphertext, ivk, epk); if (!encPlaintext) { - return boost::none; + return std::nullopt; } // Deserialize from the plaintext SaplingNotePlaintext ret; try { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); - ss << encPlaintext.get(); + ss << encPlaintext.value(); ss >> ret; assert(ss.size() == 0); return ret; } catch (const boost::thread_interrupted&) { throw; } catch (...) { - return boost::none; + return std::nullopt; } } -boost::optional SaplingNotePlaintext::plaintext_checks_without_height( +std::optional SaplingNotePlaintext::plaintext_checks_without_height( const SaplingNotePlaintext &plaintext, const uint256 &ivk, const uint256 &epk, @@ -271,7 +271,7 @@ boost::optional SaplingNotePlaintext::plaintext_checks_wit { uint256 pk_d; if (!librustzcash_ivk_to_pkd(ivk.begin(), plaintext.d.data(), pk_d.begin())) { - return boost::none; + return std::nullopt; } uint256 cmu_expected; @@ -284,11 +284,11 @@ boost::optional SaplingNotePlaintext::plaintext_checks_wit cmu_expected.begin() )) { - return boost::none; + return std::nullopt; } if (cmu_expected != cmu) { - return boost::none; + return std::nullopt; } if (plaintext.get_leadbyte() != 0x01) { @@ -297,17 +297,17 @@ boost::optional SaplingNotePlaintext::plaintext_checks_wit uint256 expected_epk; uint256 esk = plaintext.generate_or_derive_esk(); if (!librustzcash_sapling_ka_derivepublic(plaintext.d.data(), esk.begin(), expected_epk.begin())) { - return boost::none; + return std::nullopt; } if (expected_epk != epk) { - return boost::none; + return std::nullopt; } } return plaintext; } -boost::optional SaplingNotePlaintext::decrypt( +std::optional SaplingNotePlaintext::decrypt( const Consensus::Params& params, int height, const SaplingEncCiphertext &ciphertext, @@ -320,20 +320,20 @@ boost::optional SaplingNotePlaintext::decrypt( auto ret = attempt_sapling_enc_decryption_deserialization(ciphertext, epk, esk, pk_d); if (!ret) { - return boost::none; + return std::nullopt; } else { SaplingNotePlaintext plaintext = *ret; // Check leadbyte is allowed at block height if (!plaintext_version_is_valid(params, height, plaintext.get_leadbyte())) { - return boost::none; + return std::nullopt; } return plaintext_checks_without_height(plaintext, epk, esk, pk_d, cmu); } } -boost::optional SaplingNotePlaintext::attempt_sapling_enc_decryption_deserialization( +std::optional SaplingNotePlaintext::attempt_sapling_enc_decryption_deserialization( const SaplingEncCiphertext &ciphertext, const uint256 &epk, const uint256 &esk, @@ -343,25 +343,25 @@ boost::optional SaplingNotePlaintext::attempt_sapling_enc_ auto encPlaintext = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d); if (!encPlaintext) { - return boost::none; + return std::nullopt; }; // Deserialize from the plaintext SaplingNotePlaintext ret; try { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); - ss << encPlaintext.get(); + ss << encPlaintext.value(); ss >> ret; assert(ss.size() == 0); return ret; } catch (const boost::thread_interrupted&) { throw; } catch (...) { - return boost::none; + return std::nullopt; } } -boost::optional SaplingNotePlaintext::plaintext_checks_without_height( +std::optional SaplingNotePlaintext::plaintext_checks_without_height( const SaplingNotePlaintext &plaintext, const uint256 &epk, const uint256 &esk, @@ -372,10 +372,10 @@ boost::optional SaplingNotePlaintext::plaintext_checks_wit // Check that epk is consistent with esk uint256 expected_epk; if (!librustzcash_sapling_ka_derivepublic(plaintext.d.data(), esk.begin(), expected_epk.begin())) { - return boost::none; + return std::nullopt; } if (expected_epk != epk) { - return boost::none; + return std::nullopt; } uint256 cmu_expected; @@ -388,32 +388,32 @@ boost::optional SaplingNotePlaintext::plaintext_checks_wit cmu_expected.begin() )) { - return boost::none; + return std::nullopt; } if (cmu_expected != cmu) { - return boost::none; + return std::nullopt; } if (plaintext.get_leadbyte() != 0x01) { // ZIP 212: Additionally check that the esk provided to this function // is consistent with the esk we can derive if (esk != plaintext.generate_or_derive_esk()) { - return boost::none; + return std::nullopt; } } return plaintext; } -boost::optional SaplingNotePlaintext::encrypt(const uint256& pk_d) const +std::optional SaplingNotePlaintext::encrypt(const uint256& pk_d) const { // Get the encryptor auto sne = SaplingNoteEncryption::FromDiversifier(d, generate_or_derive_esk()); if (!sne) { - return boost::none; + return std::nullopt; } - auto enc = sne.get(); + auto enc = sne.value(); // Create the plaintext CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); @@ -425,9 +425,9 @@ boost::optional SaplingNotePlaintext::encr // Encrypt the plaintext auto encciphertext = enc.encrypt_to_recipient(pk_d, pt); if (!encciphertext) { - return boost::none; + return std::nullopt; } - return SaplingNotePlaintextEncryptionResult(encciphertext.get(), enc); + return SaplingNotePlaintextEncryptionResult(encciphertext.value(), enc); } diff --git a/src/zcash/Note.hpp b/src/zcash/Note.hpp index 34eaafb7d..ed231f411 100644 --- a/src/zcash/Note.hpp +++ b/src/zcash/Note.hpp @@ -9,7 +9,7 @@ #include "consensus/consensus.h" #include -#include +#include namespace libzcash { @@ -82,8 +82,8 @@ class SaplingNote : public BaseNote { virtual ~SaplingNote() {}; - boost::optional cmu() const; - boost::optional nullifier(const SaplingFullViewingKey &vk, const uint64_t position) const; + std::optional cmu() const; + std::optional nullifier(const SaplingFullViewingKey &vk, const uint64_t position) const; uint256 rcm() const; Zip212Enabled get_zip_212_enabled() const { @@ -160,7 +160,7 @@ class SaplingNotePlaintext : public BaseNotePlaintext { SaplingNotePlaintext(const SaplingNote& note, std::array memo); - static boost::optional decrypt( + static std::optional decrypt( const Consensus::Params& params, int height, const SaplingEncCiphertext &ciphertext, @@ -169,20 +169,20 @@ class SaplingNotePlaintext : public BaseNotePlaintext { const uint256 &cmu ); - static boost::optional plaintext_checks_without_height( + static std::optional plaintext_checks_without_height( const SaplingNotePlaintext &plaintext, const uint256 &ivk, const uint256 &epk, const uint256 &cmu ); - static boost::optional attempt_sapling_enc_decryption_deserialization( + static std::optional attempt_sapling_enc_decryption_deserialization( const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk ); - static boost::optional decrypt( + static std::optional decrypt( const Consensus::Params& params, int height, const SaplingEncCiphertext &ciphertext, @@ -192,7 +192,7 @@ class SaplingNotePlaintext : public BaseNotePlaintext { const uint256 &cmu ); - static boost::optional plaintext_checks_without_height( + static std::optional plaintext_checks_without_height( const SaplingNotePlaintext &plaintext, const uint256 &epk, const uint256 &esk, @@ -200,14 +200,14 @@ class SaplingNotePlaintext : public BaseNotePlaintext { const uint256 &cmu ); - static boost::optional attempt_sapling_enc_decryption_deserialization( + static std::optional attempt_sapling_enc_decryption_deserialization( const SaplingEncCiphertext &ciphertext, const uint256 &epk, const uint256 &esk, const uint256 &pk_d ); - boost::optional note(const SaplingIncomingViewingKey& ivk) const; + std::optional note(const SaplingIncomingViewingKey& ivk) const; virtual ~SaplingNotePlaintext() {} @@ -227,7 +227,7 @@ class SaplingNotePlaintext : public BaseNotePlaintext { READWRITE(memo_); // 512 bytes } - boost::optional encrypt(const uint256& pk_d) const; + std::optional encrypt(const uint256& pk_d) const; uint256 rcm() const; uint256 generate_or_derive_esk() const; @@ -254,7 +254,7 @@ class SaplingOutgoingPlaintext READWRITE(esk); // 8 bytes } - static boost::optional decrypt( + static std::optional decrypt( const SaplingOutCiphertext &ciphertext, const uint256& ovk, const uint256& cv, diff --git a/src/zcash/NoteEncryption.cpp b/src/zcash/NoteEncryption.cpp index 76b6f380d..dbecdc911 100644 --- a/src/zcash/NoteEncryption.cpp +++ b/src/zcash/NoteEncryption.cpp @@ -91,7 +91,7 @@ void KDF(unsigned char K[NOTEENCRYPTION_CIPHER_KEYSIZE], namespace libzcash { -boost::optional SaplingNoteEncryption::FromDiversifier( +std::optional SaplingNoteEncryption::FromDiversifier( diversifier_t d, uint256 esk ) @@ -100,13 +100,13 @@ boost::optional SaplingNoteEncryption::FromDiversifier( // Compute epk given the diversifier if (!librustzcash_sapling_ka_derivepublic(d.begin(), esk.begin(), epk.begin())) { - return boost::none; + return std::nullopt; } return SaplingNoteEncryption(epk, esk); } -boost::optional SaplingNoteEncryption::encrypt_to_recipient( +std::optional SaplingNoteEncryption::encrypt_to_recipient( const uint256 &pk_d, const SaplingEncPlaintext &message ) @@ -118,7 +118,7 @@ boost::optional SaplingNoteEncryption::encrypt_to_recipien uint256 dhsecret; if (!librustzcash_sapling_ka_agree(pk_d.begin(), esk.begin(), dhsecret.begin())) { - return boost::none; + return std::nullopt; } // Construct the symmetric key @@ -142,7 +142,7 @@ boost::optional SaplingNoteEncryption::encrypt_to_recipien return ciphertext; } -boost::optional AttemptSaplingEncDecryption( +std::optional AttemptSaplingEncDecryption( const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk @@ -151,7 +151,7 @@ boost::optional AttemptSaplingEncDecryption( uint256 dhsecret; if (!librustzcash_sapling_ka_agree(epk.begin(), ivk.begin(), dhsecret.begin())) { - return boost::none; + return std::nullopt; } // Construct the symmetric key @@ -171,13 +171,13 @@ boost::optional AttemptSaplingEncDecryption( 0, cipher_nonce, K) != 0) { - return boost::none; + return std::nullopt; } return plaintext; } -boost::optional AttemptSaplingEncDecryption ( +std::optional AttemptSaplingEncDecryption ( const SaplingEncCiphertext &ciphertext, const uint256 &epk, const uint256 &esk, @@ -187,7 +187,7 @@ boost::optional AttemptSaplingEncDecryption ( uint256 dhsecret; if (!librustzcash_sapling_ka_agree(pk_d.begin(), esk.begin(), dhsecret.begin())) { - return boost::none; + return std::nullopt; } // Construct the symmetric key @@ -207,7 +207,7 @@ boost::optional AttemptSaplingEncDecryption ( 0, cipher_nonce, K) != 0) { - return boost::none; + return std::nullopt; } return plaintext; @@ -246,7 +246,7 @@ SaplingOutCiphertext SaplingNoteEncryption::encrypt_to_ourselves( return ciphertext; } -boost::optional AttemptSaplingOutDecryption( +std::optional AttemptSaplingOutDecryption( const SaplingOutCiphertext &ciphertext, const uint256 &ovk, const uint256 &cv, @@ -271,7 +271,7 @@ boost::optional AttemptSaplingOutDecryption( 0, cipher_nonce, K) != 0) { - return boost::none; + return std::nullopt; } return plaintext; diff --git a/src/zcash/NoteEncryption.hpp b/src/zcash/NoteEncryption.hpp index 308d81dc1..a4484004b 100644 --- a/src/zcash/NoteEncryption.hpp +++ b/src/zcash/NoteEncryption.hpp @@ -13,6 +13,7 @@ See the Zcash protocol specification for more information. #include "zcash/Address.hpp" #include +#include namespace libzcash { @@ -42,9 +43,9 @@ class SaplingNoteEncryption { public: - static boost::optional FromDiversifier(diversifier_t d, uint256 esk); + static std::optional FromDiversifier(diversifier_t d, uint256 esk); - boost::optional encrypt_to_recipient( + std::optional encrypt_to_recipient( const uint256 &pk_d, const SaplingEncPlaintext &message ); @@ -67,7 +68,7 @@ class SaplingNoteEncryption { // Attempts to decrypt a Sapling note. This will not check that the contents // of the ciphertext are correct. -boost::optional AttemptSaplingEncDecryption( +std::optional AttemptSaplingEncDecryption( const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk @@ -75,7 +76,7 @@ boost::optional AttemptSaplingEncDecryption( // Attempts to decrypt a Sapling note using outgoing plaintext. // This will not check that the contents of the ciphertext are correct. -boost::optional AttemptSaplingEncDecryption ( +std::optional AttemptSaplingEncDecryption ( const SaplingEncCiphertext &ciphertext, const uint256 &epk, const uint256 &esk, @@ -84,7 +85,7 @@ boost::optional AttemptSaplingEncDecryption ( // Attempts to decrypt a Sapling note. This will not check that the contents // of the ciphertext are correct. -boost::optional AttemptSaplingOutDecryption( +std::optional AttemptSaplingOutDecryption( const SaplingOutCiphertext &ciphertext, const uint256 &ovk, const uint256 &cv, diff --git a/src/zcash/address/sapling.cpp b/src/zcash/address/sapling.cpp index 30aa77348..2a49f0461 100644 --- a/src/zcash/address/sapling.cpp +++ b/src/zcash/address/sapling.cpp @@ -23,13 +23,13 @@ uint256 SaplingPaymentAddress::GetHash() const { return Hash(ss.begin(), ss.end()); } -boost::optional SaplingIncomingViewingKey::address(diversifier_t d) const { +std::optional SaplingIncomingViewingKey::address(diversifier_t d) const { uint256 pk_d; if (librustzcash_check_diversifier(d.data())) { librustzcash_ivk_to_pkd(this->begin(), d.data(), pk_d.begin()); return SaplingPaymentAddress(d, pk_d); } else { - return boost::none; + return std::nullopt; } } @@ -79,7 +79,7 @@ SaplingFullViewingKey SaplingSpendingKey::full_viewing_key() const { SaplingPaymentAddress SaplingSpendingKey::default_address() const { // Iterates within default_diversifier to ensure a valid address is returned auto addrOpt = full_viewing_key().in_viewing_key().address(default_diversifier(*this)); - assert(addrOpt != boost::none); + assert(addrOpt != std::nullopt); return addrOpt.value(); } diff --git a/src/zcash/address/sapling.hpp b/src/zcash/address/sapling.hpp index 477474126..b4cccd0f1 100644 --- a/src/zcash/address/sapling.hpp +++ b/src/zcash/address/sapling.hpp @@ -9,6 +9,8 @@ #include "uint256.h" #include "zcash/Zcash.h" +#include + namespace libzcash { const size_t SerializedSaplingPaymentAddressSize = 43; @@ -53,7 +55,7 @@ class SaplingIncomingViewingKey : public uint256 { SaplingIncomingViewingKey(uint256 ivk) : uint256(ivk) { } // Can pass in diversifier for Sapling addr - boost::optional address(diversifier_t d) const; + std::optional address(diversifier_t d) const; }; class SaplingFullViewingKey { diff --git a/src/zcash/address/zip32.cpp b/src/zcash/address/zip32.cpp index 430126dfe..0f7d98e01 100644 --- a/src/zcash/address/zip32.cpp +++ b/src/zcash/address/zip32.cpp @@ -54,7 +54,7 @@ uint256 ovkForShieldingFromTaddr(HDSeed& seed) { namespace libzcash { -boost::optional SaplingExtendedFullViewingKey::Derive(uint32_t i) const +std::optional SaplingExtendedFullViewingKey::Derive(uint32_t i) const { CDataStream ss_p(SER_NETWORK, PROTOCOL_VERSION); ss_p << *this; @@ -71,11 +71,11 @@ boost::optional SaplingExtendedFullViewingKey::De ss_i >> xfvk_i; return xfvk_i; } else { - return boost::none; + return std::nullopt; } } -boost::optional> +std::optional> SaplingExtendedFullViewingKey::Address(diversifier_index_t j) const { CDataStream ss_xfvk(SER_NETWORK, PROTOCOL_VERSION); @@ -93,7 +93,7 @@ boost::optional> ss_addr >> addr; return std::make_pair(j_ret, addr); } else { - return boost::none; + return std::nullopt; } } @@ -105,7 +105,7 @@ libzcash::SaplingPaymentAddress SaplingExtendedFullViewingKey::DefaultAddress() if (!addr) { throw std::runtime_error("SaplingExtendedFullViewingKey::DefaultAddress(): No valid diversifiers out of 2^88!"); } - return addr.get().second; + return addr.value().second; } SaplingExtendedSpendingKey SaplingExtendedSpendingKey::Master(const HDSeed& seed) diff --git a/src/zcash/address/zip32.h b/src/zcash/address/zip32.h index d087bccb6..449204d5b 100644 --- a/src/zcash/address/zip32.h +++ b/src/zcash/address/zip32.h @@ -10,7 +10,7 @@ #include "uint256.h" #include "zcash/address/sapling.hpp" -#include +#include const uint32_t ZIP32_HARDENED_KEY_LIMIT = 0x80000000; const size_t ZIP32_XFVK_SIZE = 169; @@ -69,12 +69,12 @@ struct SaplingExtendedFullViewingKey { READWRITE(dk); } - boost::optional Derive(uint32_t i) const; + std::optional Derive(uint32_t i) const; // Returns the first index starting from j that generates a valid // payment address, along with the corresponding address. Returns // an error if the diversifier space is exhausted. - boost::optional> + std::optional> Address(diversifier_index_t j) const; libzcash::SaplingPaymentAddress DefaultAddress() const; diff --git a/src/zcbenchmarks.cpp b/src/zcbenchmarks.cpp index 9098a0ad8..35c92a1ad 100644 --- a/src/zcbenchmarks.cpp +++ b/src/zcbenchmarks.cpp @@ -374,7 +374,7 @@ CWalletTx CreateSaplingTxWithNoteData(const Consensus::Params& consensusParams, auto wtx = GetValidSaplingReceive(consensusParams, keyStore, sk, 10); auto testNote = GetTestSaplingNote(sk.DefaultAddress(), 10); auto fvk = sk.expsk.full_viewing_key(); - auto nullifier = testNote.note.nullifier(fvk, testNote.tree.witness().position()).get(); + auto nullifier = testNote.note.nullifier(fvk, testNote.tree.witness().position()).value(); mapSaplingNoteData_t noteDataMap; SaplingOutPoint outPoint {wtx.GetHash(), 0}; @@ -595,7 +595,7 @@ double benchmark_create_sapling_spend() SaplingNote note(address, GetRand(MAX_MONEY), libzcash::Zip212Enabled::BeforeZip212); SaplingMerkleTree tree; auto maybe_cmu = note.cmu(); - tree.append(maybe_cmu.get()); + tree.append(maybe_cmu.value()); auto anchor = tree.root(); auto witness = tree.witness(); auto maybe_nf = note.nullifier(expsk.full_viewing_key(), witness.position()); @@ -653,7 +653,7 @@ double benchmark_create_sapling_output() throw JSONRPCError(RPC_INTERNAL_ERROR, "SaplingNotePlaintext::encrypt() failed"); } - auto enc = res.get(); + auto enc = res.value(); auto encryptor = enc.second; CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);