diff --git a/build-aux/m4/ax_cxx_compile_stdcxx.m4 b/build-aux/m4/ax_cxx_compile_stdcxx.m4 index f147cee3b1..43087b2e68 100644 --- a/build-aux/m4/ax_cxx_compile_stdcxx.m4 +++ b/build-aux/m4/ax_cxx_compile_stdcxx.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html +# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html # =========================================================================== # # SYNOPSIS @@ -33,21 +33,23 @@ # Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov # Copyright (c) 2015 Paul Norman # Copyright (c) 2015 Moritz Klammler +# Copyright (c) 2016, 2018 Krzesimir Nowak +# Copyright (c) 2019 Enji Cooper # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 4 +#serial 11 dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro dnl (serial version number 13). AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl - m4_if([$1], [11], [], - [$1], [14], [], - [$1], [17], [m4_fatal([support for C++17 not yet implemented in AX_CXX_COMPILE_STDCXX])], + m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], + [$1], [14], [ax_cxx_compile_alternatives="14 1y"], + [$1], [17], [ax_cxx_compile_alternatives="17 1z"], [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl m4_if([$2], [], [], [$2], [ext], [], @@ -57,26 +59,13 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl [$3], [mandatory], [ax_cxx_compile_cxx$1_required=true], [$3], [optional], [ax_cxx_compile_cxx$1_required=false], [m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])]) - m4_if([$4], [], [ax_cxx_compile_cxx$1_try_default=true], - [$4], [default], [ax_cxx_compile_cxx$1_try_default=true], - [$4], [nodefault], [ax_cxx_compile_cxx$1_try_default=false], - [m4_fatal([invalid fourth argument `$4' to AX_CXX_COMPILE_STDCXX])]) AC_LANG_PUSH([C++])dnl ac_success=no - m4_if([$4], [nodefault], [], [dnl - AC_CACHE_CHECK(whether $CXX supports C++$1 features by default, - ax_cv_cxx_compile_cxx$1, - [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], - [ax_cv_cxx_compile_cxx$1=yes], - [ax_cv_cxx_compile_cxx$1=no])]) - if test x$ax_cv_cxx_compile_cxx$1 = xyes; then - ac_success=yes - fi]) - m4_if([$2], [noext], [], [dnl if test x$ac_success = xno; then - for switch in -std=gnu++$1 -std=gnu++0x; do + for alternative in ${ax_cxx_compile_alternatives}; do + switch="-std=gnu++${alternative}" cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, $cachevar, @@ -102,22 +91,27 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl dnl HP's aCC needs +std=c++11 according to: dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf dnl Cray's crayCC needs "-h std=c++11" - for switch in -std=c++$1 -std=c++0x +std=c++$1 "-h std=c++$1"; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, - $cachevar, - [ac_save_CXX="$CXX" - CXX="$CXX $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXX="$ac_save_CXX"]) - if eval test x\$$cachevar = xyes; then - CXX="$CXX $switch" - if test -n "$CXXCPP" ; then - CXXCPP="$CXXCPP $switch" + for alternative in ${ax_cxx_compile_alternatives}; do + for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, + $cachevar, + [ac_save_CXX="$CXX" + CXX="$CXX $switch" + AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [eval $cachevar=yes], + [eval $cachevar=no]) + CXX="$ac_save_CXX"]) + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break fi - ac_success=yes + done + if test x$ac_success = xyes; then break fi done @@ -154,6 +148,11 @@ m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 ) +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 +) dnl Tests for new features in C++11 @@ -191,11 +190,13 @@ namespace cxx11 struct Base { + virtual ~Base() {} virtual void f() {} }; struct Derived : public Base { + virtual ~Derived() override {} virtual void f() override {} }; @@ -524,7 +525,7 @@ namespace cxx14 } - namespace test_digit_seperators + namespace test_digit_separators { constexpr auto ten_million = 100'000'000; @@ -566,3 +567,385 @@ namespace cxx14 #endif // __cplusplus >= 201402L ]]) + + +dnl Tests for new features in C++17 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ + +// If the compiler admits that it is not ready for C++17, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201703L + +#error "This is not a C++17 compiler" + +#else + +#include +#include +#include + +namespace cxx17 +{ + + namespace test_constexpr_lambdas + { + + constexpr int foo = [](){return 42;}(); + + } + + namespace test::nested_namespace::definitions + { + + } + + namespace test_fold_expression + { + + template + int multiply(Args... args) + { + return (args * ... * 1); + } + + template + bool all(Args... args) + { + return (args && ...); + } + + } + + namespace test_extended_static_assert + { + + static_assert (true); + + } + + namespace test_auto_brace_init_list + { + + auto foo = {5}; + auto bar {5}; + + static_assert(std::is_same, decltype(foo)>::value); + static_assert(std::is_same::value); + } + + namespace test_typename_in_template_template_parameter + { + + template typename X> struct D; + + } + + namespace test_fallthrough_nodiscard_maybe_unused_attributes + { + + int f1() + { + return 42; + } + + [[nodiscard]] int f2() + { + [[maybe_unused]] auto unused = f1(); + + switch (f1()) + { + case 17: + f1(); + [[fallthrough]]; + case 42: + f1(); + } + return f1(); + } + + } + + namespace test_extended_aggregate_initialization + { + + struct base1 + { + int b1, b2 = 42; + }; + + struct base2 + { + base2() { + b3 = 42; + } + int b3; + }; + + struct derived : base1, base2 + { + int d; + }; + + derived d1 {{1, 2}, {}, 4}; // full initialization + derived d2 {{}, {}, 4}; // value-initialized bases + + } + + namespace test_general_range_based_for_loop + { + + struct iter + { + int i; + + int& operator* () + { + return i; + } + + const int& operator* () const + { + return i; + } + + iter& operator++() + { + ++i; + return *this; + } + }; + + struct sentinel + { + int i; + }; + + bool operator== (const iter& i, const sentinel& s) + { + return i.i == s.i; + } + + bool operator!= (const iter& i, const sentinel& s) + { + return !(i == s); + } + + struct range + { + iter begin() const + { + return {0}; + } + + sentinel end() const + { + return {5}; + } + }; + + void f() + { + range r {}; + + for (auto i : r) + { + [[maybe_unused]] auto v = i; + } + } + + } + + namespace test_lambda_capture_asterisk_this_by_value + { + + struct t + { + int i; + int foo() + { + return [*this]() + { + return i; + }(); + } + }; + + } + + namespace test_enum_class_construction + { + + enum class byte : unsigned char + {}; + + byte foo {42}; + + } + + namespace test_constexpr_if + { + + template + int f () + { + if constexpr(cond) + { + return 13; + } + else + { + return 42; + } + } + + } + + namespace test_selection_statement_with_initializer + { + + int f() + { + return 13; + } + + int f2() + { + if (auto i = f(); i > 0) + { + return 3; + } + + switch (auto i = f(); i + 4) + { + case 17: + return 2; + + default: + return 1; + } + } + + } + + namespace test_template_argument_deduction_for_class_templates + { + + template + struct pair + { + pair (T1 p1, T2 p2) + : m1 {p1}, + m2 {p2} + {} + + T1 m1; + T2 m2; + }; + + void f() + { + [[maybe_unused]] auto p = pair{13, 42u}; + } + + } + + namespace test_non_type_auto_template_parameters + { + + template + struct B + {}; + + B<5> b1; + B<'a'> b2; + + } + + namespace test_structured_bindings + { + + int arr[2] = { 1, 2 }; + std::pair pr = { 1, 2 }; + + auto f1() -> int(&)[2] + { + return arr; + } + + auto f2() -> std::pair& + { + return pr; + } + + struct S + { + int x1 : 2; + volatile double y1; + }; + + S f3() + { + return {}; + } + + auto [ x1, y1 ] = f1(); + auto& [ xr1, yr1 ] = f1(); + auto [ x2, y2 ] = f2(); + auto& [ xr2, yr2 ] = f2(); + const auto [ x3, y3 ] = f3(); + + } + + namespace test_exception_spec_type_system + { + + struct Good {}; + struct Bad {}; + + void g1() noexcept; + void g2(); + + template + Bad + f(T*, T*); + + template + Good + f(T1*, T2*); + + static_assert (std::is_same_v); + + } + + namespace test_inline_variables + { + + template void f(T) + {} + + template inline T g(T) + { + return T{}; + } + + template<> inline void f<>(int) + {} + + template<> int g<>(int) + { + return 5; + } + + } + +} // namespace cxx17 + +#endif // __cplusplus < 201703L + +]]) diff --git a/ci/test/00_setup_env_native_old.sh b/ci/test/00_setup_env_native_old.sh index 47f33089ba..4afc05d32d 100755 --- a/ci/test/00_setup_env_native_old.sh +++ b/ci/test/00_setup_env_native_old.sh @@ -7,7 +7,7 @@ export LC_ALL=C.UTF-8 export CONTAINER_NAME=ci_native_old -export DOCKER_NAME_TAG=ubuntu:16.04 +export DOCKER_NAME_TAG=ubuntu:18.04 export PACKAGES="libqt5gui5 libqt5core5a qtbase5-dev libqt5dbus5 qttools5-dev qttools5-dev-tools libssl-dev libevent-dev bsdmainutils libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-iostreams-dev libboost-program-options-dev libboost-test-dev libboost-thread-dev libdb5.3++-dev libminiupnpc-dev libqrencode-dev libzip-dev zlib1g zlib1g-dev libcurl4-openssl-dev" export RUN_UNIT_TESTS=true # export RUN_FUNCTIONAL_TESTS=false diff --git a/configure.ac b/configure.ac index 8544370865..6c25599089 100755 --- a/configure.ac +++ b/configure.ac @@ -59,8 +59,9 @@ case $host in lt_cv_deplibs_check_method="pass_all" ;; esac -dnl Require C++11 compiler (no GNU extensions) -AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory], [nodefault]) + +dnl Require C++17 compiler (no GNU extensions) +AX_CXX_COMPILE_STDCXX([17], [noext], [mandatory], [nodefault]) dnl Check if -latomic is required for CHECK_ATOMIC diff --git a/depends/packages/bdb.mk b/depends/packages/bdb.mk index 05da9acf6a..8c7f825571 100644 --- a/depends/packages/bdb.mk +++ b/depends/packages/bdb.mk @@ -11,7 +11,7 @@ define $(package)_set_vars $(package)_config_opts+=--libdir=$($($(package)_type)_prefix)/lib $(package)_config_opts_mingw32=--enable-mingw $(package)_config_opts_linux=--with-pic - $(package)_cxxflags=-std=c++11 + $(package)_cxxflags=-std=c++17 $(package)_cxxflags_aarch64_linux = $(GCCFLAGS) $(package)_cflags_aarch64_linux = $(GCCFLAGS) $(package)_cxxflags_arm_linux = $(GCCFLAGS) diff --git a/depends/packages/bdb53.mk b/depends/packages/bdb53.mk index 2a9af2010d..1229c70f9c 100644 --- a/depends/packages/bdb53.mk +++ b/depends/packages/bdb53.mk @@ -11,7 +11,7 @@ define $(package)_set_vars $(package)_config_opts+=--libdir=$($($(package)_type)_prefix)/lib $(package)_config_opts_mingw32=--enable-mingw $(package)_config_opts_linux=--with-pic - $(package)_cxxflags=-std=c++11 + $(package)_cxxflags=-std=c++17 $(package)_cxxflags_aarch64_linux = $(GCCFLAGS) $(package)_cflags_aarch64_linux = $(GCCFLAGS) $(package)_cxxflags_arm_linux = $(GCCFLAGS) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 6c8922fda0..118981c1f3 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -28,7 +28,7 @@ ifneq (,$(findstring clang,$($(package)_cxx))) endif $(package)_archiver_$(host_os)=$($(package)_ar) $(package)_config_libraries=chrono,filesystem,program_options,system,thread,test,iostreams -$(package)_cxxflags=-std=c++11 -fvisibility=hidden +$(package)_cxxflags=-std=c++17 -fvisibility=hidden $(package)_cxxflags_linux=-fPIC $(package)_cxxflags_android=-fPIC endef diff --git a/depends/packages/qt.mk b/depends/packages/qt.mk index 625ca60757..39f501bf5d 100644 --- a/depends/packages/qt.mk +++ b/depends/packages/qt.mk @@ -36,7 +36,7 @@ define $(package)_set_vars $(package)_config_opts_release = -release $(package)_config_opts_debug = -debug $(package)_config_opts += -bindir $(build_prefix)/bin -$(package)_config_opts += -c++std c++11 +$(package)_config_opts += -c++std c++1z $(package)_config_opts += -confirm-license $(package)_config_opts += -hostprefix $(build_prefix) $(package)_config_opts += -no-compile-examples diff --git a/src/Makefile.am b/src/Makefile.am index 698efa48df..90a9e9fcee 100755 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -70,6 +70,7 @@ GRIDCOIN_CORE_H = \ chainparamsbase.h \ checkpoints.h \ compat.h \ + compat/assumptions.h \ compat/byteswap.h \ compat/endian.h \ consensus/consensus.h \ @@ -168,7 +169,6 @@ GRIDCOIN_CORE_H = \ txdb-leveldb.h \ ui_interface.h \ uint256.h \ - util/memory.h \ util/reverse_iterator.h \ util/strencodings.h \ util/threadnames.h \ diff --git a/src/attributes.h b/src/attributes.h index 45099bd8b8..9957bcd84b 100644 --- a/src/attributes.h +++ b/src/attributes.h @@ -1,22 +1,19 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2018 The Bitcoin Core developers +// Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_ATTRIBUTES_H #define BITCOIN_ATTRIBUTES_H -#if defined(__has_cpp_attribute) -# if __has_cpp_attribute(nodiscard) -# define NODISCARD [[nodiscard]] -# endif -#endif -#ifndef NODISCARD -# if defined(_MSC_VER) && _MSC_VER >= 1700 -# define NODISCARD _Check_return_ +#if defined(__clang__) +# if __has_attribute(lifetimebound) +# define LIFETIMEBOUND [[clang::lifetimebound]] # else -# define NODISCARD __attribute__((warn_unused_result)) +# define LIFETIMEBOUND # endif +#else +# define LIFETIMEBOUND #endif #endif // BITCOIN_ATTRIBUTES_H diff --git a/src/base58.h b/src/base58.h index 665966351f..f8279b2c77 100644 --- a/src/base58.h +++ b/src/base58.h @@ -15,12 +15,14 @@ #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H -#include -#include #include "bignum.h" #include "key.h" #include "script.h" +#include +#include +#include + static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Encode a byte sequence as a base58-encoded string @@ -260,7 +262,7 @@ class CBase58Data * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress; -class CBitcoinAddressVisitor : public boost::static_visitor +class CBitcoinAddressVisitor { private: CBitcoinAddress *addr; @@ -295,7 +297,7 @@ class CBitcoinAddress : public CBase58Data bool Set(const CTxDestination &dest) { - return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); + return std::visit(CBitcoinAddressVisitor(this), dest); } bool IsValid() const diff --git a/src/chainparamsbase.cpp b/src/chainparamsbase.cpp index 83ba2ae87e..962d50d4c7 100644 --- a/src/chainparamsbase.cpp +++ b/src/chainparamsbase.cpp @@ -23,9 +23,9 @@ const CBaseChainParams& BaseParams() std::unique_ptr CreateBaseChainParams(const std::string& chain) { if (chain == CBaseChainParams::MAIN) - return MakeUnique("", 32749); + return std::make_unique("", 32749); else if (chain == CBaseChainParams::TESTNET) - return MakeUnique("testnet", 32748); + return std::make_unique("testnet", 32748); else throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } diff --git a/src/chainparamsbase.h b/src/chainparamsbase.h index 1e9b9df4bb..d0cd6de30b 100644 --- a/src/chainparamsbase.h +++ b/src/chainparamsbase.h @@ -4,7 +4,6 @@ #pragma once -#include "util/memory.h" #include #include diff --git a/src/compat/assumptions.h b/src/compat/assumptions.h new file mode 100644 index 0000000000..5f50cde3ff --- /dev/null +++ b/src/compat/assumptions.h @@ -0,0 +1,62 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2020 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +// Compile-time verification of assumptions we make. + +#ifndef BITCOIN_COMPAT_ASSUMPTIONS_H +#define BITCOIN_COMPAT_ASSUMPTIONS_H + +#include + +// Assumption: We assume that the macro NDEBUG is not defined. +// Example(s): We use assert(...) extensively with the assumption of it never +// being a noop at runtime. +#if defined(NDEBUG) +# error "Bitcoin cannot be compiled without assertions." +#endif + +// Assumption: We assume a C++17 (ISO/IEC 14882:2017) compiler (minimum requirement). +// Example(s): We assume the presence of C++17 features everywhere :-) +// ISO Standard C++17 [cpp.predefined]p1: +// "The name __cplusplus is defined to the value 201703L when compiling a C++ +// translation unit." +static_assert(__cplusplus >= 201703L, "C++17 standard assumed"); + +// Assumption: We assume the floating-point types to fulfill the requirements of +// IEC 559 (IEEE 754) standard. +// Example(s): Floating-point division by zero in ConnectBlock, CreateTransaction +// and EstimateMedianVal. +static_assert(std::numeric_limits::is_iec559, "IEEE 754 float assumed"); +static_assert(std::numeric_limits::is_iec559, "IEEE 754 double assumed"); + +// Assumption: We assume eight bits per byte (obviously, but remember: don't +// trust -- verify!). +// Example(s): Everywhere :-) +static_assert(std::numeric_limits::digits == 8, "8-bit byte assumed"); + +// Assumption: We assume floating-point widths. +// Example(s): Type punning in serialization code (ser_{float,double}_to_uint{32,64}). +static_assert(sizeof(float) == 4, "32-bit float assumed"); +static_assert(sizeof(double) == 8, "64-bit double assumed"); + +// Assumption: We assume integer widths. +// Example(s): GetSizeOfCompactSize and WriteCompactSize in the serialization +// code. +static_assert(sizeof(short) == 2, "16-bit short assumed"); +static_assert(sizeof(int) == 4, "32-bit int assumed"); +static_assert(sizeof(unsigned) == 4, "32-bit unsigned assumed"); + +// Assumption: We assume size_t to be 32-bit or 64-bit. +// Example(s): size_t assumed to be at least 32-bit in ecdsa_signature_parse_der_lax(...). +// size_t assumed to be 32-bit or 64-bit in MallocUsage(...). +static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t assumed to be 32-bit or 64-bit"); +static_assert(sizeof(size_t) == sizeof(void*), "Sizes of size_t and void* assumed to be equal"); + +// Some important things we are NOT assuming (non-exhaustive list): +// * We are NOT assuming a specific value for std::endian::native. +// * We are NOT assuming a specific value for std::locale("").name(). +// * We are NOT assuming a specific value for std::numeric_limits::is_signed. + +#endif // BITCOIN_COMPAT_ASSUMPTIONS_H diff --git a/src/gridcoin/account.h b/src/gridcoin/account.h index bb936547e4..86df8ede24 100644 --- a/src/gridcoin/account.h +++ b/src/gridcoin/account.h @@ -5,7 +5,7 @@ #pragma once #include "amount.h" -#include +#include #include class CBlockIndex; @@ -24,7 +24,7 @@ typedef std::unordered_map ResearchAccountMap; //! \brief An optional type that contains a pointer to a block index object or //! does not. //! -typedef boost::optional BlockPtrOption; +typedef std::optional BlockPtrOption; //! //! \brief Stores the research reward context for a CPID used to calculate @@ -105,7 +105,7 @@ class ResearchAccount BlockPtrOption FirstRewardBlock() const { if (m_first_block_ptr == nullptr) { - return boost::none; + return std::nullopt; } return BlockPtrOption(m_first_block_ptr); @@ -168,7 +168,7 @@ class ResearchAccount BlockPtrOption LastRewardBlock() const { if (m_last_block_ptr == nullptr) { - return boost::none; + return std::nullopt; } return BlockPtrOption(m_last_block_ptr); diff --git a/src/gridcoin/claim.h b/src/gridcoin/claim.h index 53ea268520..d408af48b7 100644 --- a/src/gridcoin/claim.h +++ b/src/gridcoin/claim.h @@ -11,7 +11,7 @@ #include "serialize.h" #include "uint256.h" -#include +#include class CPubKey; diff --git a/src/gridcoin/contract/contract.h b/src/gridcoin/contract/contract.h index a1e30781f3..8bc8a08bf7 100644 --- a/src/gridcoin/contract/contract.h +++ b/src/gridcoin/contract/contract.h @@ -9,7 +9,7 @@ #include "gridcoin/support/enumbytes.h" #include "serialize.h" -#include +#include #include #include diff --git a/src/gridcoin/cpid.cpp b/src/gridcoin/cpid.cpp index 3cbf022edd..8e3749e64f 100644 --- a/src/gridcoin/cpid.cpp +++ b/src/gridcoin/cpid.cpp @@ -6,7 +6,6 @@ #include "util.h" #include -#include #include using namespace GRC; @@ -15,7 +14,7 @@ namespace { //! //! \brief Gets the string representation of a mining ID object. //! -struct MiningIdToStringVisitor : boost::static_visitor +struct MiningIdToStringVisitor { //! //! \brief Call the mining ID variant type's \c ToString() method directly. @@ -117,7 +116,7 @@ MiningId MiningId::Parse(const std::string& input) std::string MiningId::ToString() const { - return boost::apply_visitor(MiningIdToStringVisitor(), m_variant); + return std::visit(MiningIdToStringVisitor(), m_variant); } // ----------------------------------------------------------------------------- diff --git a/src/gridcoin/cpid.h b/src/gridcoin/cpid.h index 41da110c26..033b7e767b 100644 --- a/src/gridcoin/cpid.h +++ b/src/gridcoin/cpid.h @@ -7,11 +7,10 @@ #include "serialize.h" #include -#include -#include -#include +#include #include #include +#include namespace GRC { //! @@ -209,7 +208,7 @@ class Cpid //! \brief An optional type that either contains a reference to some external //! CPID value or does not. //! -typedef boost::optional CpidOption; +typedef std::optional CpidOption; //! //! \brief A variant type that identifies an entity that may receive rewards. @@ -299,12 +298,12 @@ class MiningId //! bool operator==(const MiningId& other) const { - if (m_variant.which() != other.m_variant.which()) { + if (m_variant.index() != other.m_variant.index()) { return false; } if (Which() == Kind::CPID) { - return *this == boost::get(other.m_variant); + return *this == std::get(other.m_variant); } return true; @@ -333,7 +332,7 @@ class MiningId bool operator==(const Cpid& other) const { return Which() == Kind::CPID - && boost::get(m_variant) == other; + && std::get(m_variant) == other; } //! @@ -356,7 +355,7 @@ class MiningId //! Kind Which() const { - return static_cast(m_variant.which()); + return static_cast(m_variant.index()); } //! @@ -378,10 +377,10 @@ class MiningId CpidOption TryCpid() const { if (Which() != Kind::CPID) { - return boost::none; + return std::nullopt; } - return boost::get(m_variant); + return std::get(m_variant); } //! @@ -400,12 +399,12 @@ class MiningId template void Serialize(Stream& stream) const { - unsigned char kind = m_variant.which(); + unsigned char kind = m_variant.index(); ::Serialize(stream, kind); if (static_cast(kind) == Kind::CPID) { - boost::get(m_variant).Serialize(stream); + std::get(m_variant).Serialize(stream); } } @@ -443,7 +442,7 @@ class MiningId //! //! \brief Stores the various states that a mining ID may exist in. //! - boost::variant m_variant; + std::variant m_variant; }; // MiningId } // namespace GRC diff --git a/src/gridcoin/gridcoin.cpp b/src/gridcoin/gridcoin.cpp index e4771aea98..7d519b45ae 100644 --- a/src/gridcoin/gridcoin.cpp +++ b/src/gridcoin/gridcoin.cpp @@ -270,9 +270,9 @@ void ThreadScraperSubscriber(void* parg) void InitializeScraper(ThreadHandlerPtr threads) { // Default to 300 sec (5 min), clamp to 60 minimum, 600 maximum - converted to milliseconds. - nScraperSleep = clamp(GetArg("-scrapersleep", 300), 60, 600) * 1000; + nScraperSleep = std::clamp(GetArg("-scrapersleep", 300), 60, 600) * 1000; // Default to 14400 sec (4 hrs), clamp to 300 minimum, 86400 maximum (meaning active all of the time). - nActiveBeforeSB = clamp(GetArg("-activebeforesb", 14400), 300, 86400); + nActiveBeforeSB = std::clamp(GetArg("-activebeforesb", 14400), 300, 86400); // Run the scraper or subscriber housekeeping thread, but not both. The // subscriber housekeeping thread checks if the flag for the scraper thread diff --git a/src/gridcoin/quorum.cpp b/src/gridcoin/quorum.cpp index 94b2be15af..8b6fbb3623 100644 --- a/src/gridcoin/quorum.cpp +++ b/src/gridcoin/quorum.cpp @@ -574,7 +574,7 @@ class SuperblockValidator SuperblockValidator(const SuperblockPtr& superblock, size_t hint_bits = 32) : m_superblock(superblock) , m_quorum_hash(superblock->GetHash()) - , m_hint_shift(32 + clamp(32 - hint_bits, 0, 32)) + , m_hint_shift(32 + std::clamp(32 - hint_bits, 0, 32)) { } @@ -927,10 +927,10 @@ class SuperblockValidator //! \return A convergence to generate a superblock hash from if a new //! combination is possible. //! - boost::optional GetNextConvergence() + std::optional GetNextConvergence() { if (m_current_combination == m_total_combinations) { - return boost::none; + return std::nullopt; } ConvergenceCandidate convergence; @@ -971,7 +971,7 @@ class SuperblockValidator ++m_current_combination; - return boost::make_optional(std::move(convergence)); + return std::make_optional(std::move(convergence)); } private: diff --git a/src/gridcoin/researcher.cpp b/src/gridcoin/researcher.cpp index 045ba1a51d..d895fc2f46 100644 --- a/src/gridcoin/researcher.cpp +++ b/src/gridcoin/researcher.cpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include @@ -269,13 +269,13 @@ bool IsPoolUsername(const std::string& username) //! //! \return The entire client_state.xml file as a string if readable. //! -boost::optional ReadClientStateXml() +std::optional ReadClientStateXml() { const fs::path path = GetBoincDataDir(); std::string contents = GetFileContents(path / "client_state.xml"); if (contents != "-1") { - return boost::make_optional(std::move(contents)); + return std::make_optional(std::move(contents)); } LogPrintf("WARNING: Unable to obtain BOINC CPIDs."); @@ -288,7 +288,7 @@ boost::optional ReadClientStateXml() "Please specify its current location in gridcoinresearch.conf."); } - return boost::none; + return std::nullopt; } //! @@ -301,7 +301,7 @@ boost::optional ReadClientStateXml() //! std::vector FetchProjectsXml() { - const boost::optional client_state_xml = ReadClientStateXml(); + const std::optional client_state_xml = ReadClientStateXml(); if (!client_state_xml) { return { }; @@ -431,12 +431,12 @@ void TryProjectCpid(MiningId& mining_id, const MiningProject& project) //! \return The computed external CPID if the hash of the configured email //! address matches the supplied email address hash. //! -boost::optional FallbackToCpidByEmail( +std::optional FallbackToCpidByEmail( const std::string& email_hash, const std::string& internal_cpid) { if (email_hash.empty() || internal_cpid.empty()) { - return boost::none; + return std::nullopt; } const std::string email = Researcher::Email(); @@ -447,7 +447,7 @@ boost::optional FallbackToCpidByEmail( email_hash_bytes.data()); if (HexStr(email_hash_bytes) != email_hash) { - return boost::none; + return std::nullopt; } return Cpid::Hash(internal_cpid, email); @@ -868,7 +868,7 @@ MiningProject MiningProject::Parse(const std::string& xml) // CPID of the project from the internal CPID and email address: // if (external_cpid.empty()) { - if (const boost::optional cpid = FallbackToCpidByEmail( + if (const std::optional cpid = FallbackToCpidByEmail( ExtractXML(xml, "", ""), ExtractXML(xml, "", ""))) { @@ -1048,8 +1048,8 @@ AdvertiseBeaconResult::AdvertiseBeaconResult(const BeaconError error) CPubKey* AdvertiseBeaconResult::TryPublicKey() { - if (m_result.which() == 0) { - return &boost::get(m_result); + if (m_result.index() == 0) { + return &std::get(m_result); } return nullptr; @@ -1057,8 +1057,8 @@ CPubKey* AdvertiseBeaconResult::TryPublicKey() const CPubKey* AdvertiseBeaconResult::TryPublicKey() const { - if (m_result.which() == 0) { - return &boost::get(m_result); + if (m_result.index() == 0) { + return &std::get(m_result); } return nullptr; @@ -1066,8 +1066,8 @@ const CPubKey* AdvertiseBeaconResult::TryPublicKey() const BeaconError AdvertiseBeaconResult::Error() const { - if (m_result.which() > 0) { - return boost::get(m_result); + if (m_result.index() > 0) { + return std::get(m_result); } return BeaconError::NONE; @@ -1344,12 +1344,12 @@ ResearcherStatus Researcher::Status() const return ResearcherStatus::INVESTOR; } -boost::optional Researcher::TryBeacon() const +std::optional Researcher::TryBeacon() const { const CpidOption cpid = m_mining_id.TryCpid(); if (!cpid) { - return boost::none; + return std::nullopt; } LOCK(cs_main); @@ -1357,18 +1357,18 @@ boost::optional Researcher::TryBeacon() const const BeaconOption beacon = GetBeaconRegistry().Try(*cpid); if (!beacon) { - return boost::none; + return std::nullopt; } return *beacon; } -boost::optional Researcher::TryPendingBeacon() const +std::optional Researcher::TryPendingBeacon() const { const CpidOption cpid = m_mining_id.TryCpid(); if (!cpid) { - return boost::none; + return std::nullopt; } LOCK(cs_main); @@ -1376,7 +1376,7 @@ boost::optional Researcher::TryPendingBeacon() const const PendingBeacon* pending_beacon = g_recent_beacons.Try(*cpid); if (!pending_beacon) { - return boost::none; + return std::nullopt; } return *pending_beacon; diff --git a/src/gridcoin/researcher.h b/src/gridcoin/researcher.h index 31d3e1f15b..cfa68e262c 100644 --- a/src/gridcoin/researcher.h +++ b/src/gridcoin/researcher.h @@ -8,8 +8,6 @@ #include "key.h" #include "gridcoin/cpid.h" -#include -#include #include #include #include @@ -309,7 +307,7 @@ class AdvertiseBeaconResult //! \brief Contains the beacon public key if advertisement succeeded or //! the error result if it did not. //! - boost::variant m_result; + std::variant m_result; }; //! @@ -515,14 +513,14 @@ class Researcher //! //! \return Contains the beacon for the CPID or does not. //! - boost::optional TryBeacon() const; + std::optional TryBeacon() const; //! //! \brief Get the pending beacon for the current CPID if it exists. //! //! \return Contains the pending beacon for the CPID or does not. //! - boost::optional TryPendingBeacon() const; + std::optional TryPendingBeacon() const; //! //! \brief Get the error from the last beacon advertisement, if any. diff --git a/src/gridcoin/staking/chain_trust.h b/src/gridcoin/staking/chain_trust.h index a6825aea6f..2c9e3c15f2 100644 --- a/src/gridcoin/staking/chain_trust.h +++ b/src/gridcoin/staking/chain_trust.h @@ -195,7 +195,7 @@ class ChainTrustCache //! //! \return Either contains a trust value for the block or does not. //! - boost::optional Try(const CBlockIndex* const pindex) const + std::optional Try(const CBlockIndex* const pindex) const { for (size_t i = 0; i < SIZE; ++i) { if (m_index_cache[i] == pindex) { @@ -203,7 +203,7 @@ class ChainTrustCache } } - return boost::none; + return std::nullopt; } //! diff --git a/src/gridcoin/staking/difficulty.cpp b/src/gridcoin/staking/difficulty.cpp index dd72815af5..7a48935892 100644 --- a/src/gridcoin/staking/difficulty.cpp +++ b/src/gridcoin/staking/difficulty.cpp @@ -206,9 +206,9 @@ double GRC::GetSmoothedDifficulty(int64_t nStakeableBalance) // familiar with the thumbrule for ETTS, ETTS = 10000 / Balance * Diff should recognize it in the below // expression. Note that the actual constant is 9942.2056 (from the bluepaper, eq. 12), but it suffices to // use the rounded thumbrule value here. - unsigned int nEstAppropriateDiffSpan = clamp(10000.0 * BLOCKS_PER_DAY * COIN - / nStakeableBalance * dDiff, - 40, 960); + unsigned int nEstAppropriateDiffSpan = std::clamp(10000.0 * BLOCKS_PER_DAY * COIN + / nStakeableBalance * dDiff, + 40, 960); LogPrint(BCLog::LogFlags::NOISY, "GetSmoothedDifficulty debug: nStakeableBalance: %u", nStakeableBalance); LogPrint(BCLog::LogFlags::NOISY, "GetSmoothedDifficulty debug: nEstAppropriateDiffSpan: %u", nEstAppropriateDiffSpan); diff --git a/src/gridcoin/staking/kernel.cpp b/src/gridcoin/staking/kernel.cpp index b1d256b0d2..8939bec462 100644 --- a/src/gridcoin/staking/kernel.cpp +++ b/src/gridcoin/staking/kernel.cpp @@ -33,7 +33,7 @@ class StakeModifierCandidate //! can potentially compare this hash many times. By caching the hash value //! here, we avoid recomputing it for each iteration of the selection loop. //! - mutable boost::optional m_selection_hash; + mutable std::optional m_selection_hash; //! //! \brief Initialize a new candidate entry. diff --git a/src/gridcoin/staking/reward.cpp b/src/gridcoin/staking/reward.cpp index f07b42b022..45d0e08712 100644 --- a/src/gridcoin/staking/reward.cpp +++ b/src/gridcoin/staking/reward.cpp @@ -49,7 +49,7 @@ CAmount GRC::GetConstantBlockReward(const CBlockIndex* index) reward = atoi64(oCBReward.value); } - reward = clamp(reward, MIN_CBR, MAX_CBR); + reward = std::clamp(reward, MIN_CBR, MAX_CBR); return reward; } diff --git a/src/gridcoin/superblock.cpp b/src/gridcoin/superblock.cpp index cece6622e4..4731297f2c 100644 --- a/src/gridcoin/superblock.cpp +++ b/src/gridcoin/superblock.cpp @@ -11,7 +11,6 @@ #include "util.h" #include "util/reverse_iterator.h" -#include #include using namespace GRC; @@ -475,7 +474,7 @@ class LegacySuperblockParser //! //! \brief Gets the string representation of a quorum hash object. //! -struct QuorumHashToStringVisitor : boost::static_visitor +struct QuorumHashToStringVisitor { //! //! \brief Get the string representation of an invalid or empty quorum hash. @@ -900,7 +899,7 @@ Superblock::ProjectIndex::Try(const std::string& name) const [](const ProjectPair& a, const std::string& b) { return a.first < b; }); if (iter == m_projects.end() || iter->first != name) { - return boost::none; + return std::nullopt; } return iter->second; @@ -1016,7 +1015,7 @@ QuorumHash::QuorumHash(const std::vector& bytes) : QuorumHash() m_hash = uint256(bytes); } else if (bytes.size() == sizeof(Md5Sum)) { m_hash = Md5Sum(); - std::copy(bytes.begin(), bytes.end(), boost::get(m_hash).begin()); + std::copy(bytes.begin(), bytes.end(), std::get(m_hash).begin()); } } @@ -1081,7 +1080,7 @@ QuorumHash QuorumHash::Parse(const std::string& hex) bool QuorumHash::operator==(const QuorumHash& other) const { - if (m_hash.which() != other.m_hash.which()) { + if (m_hash.index() != other.m_hash.index()) { return false; } @@ -1090,12 +1089,12 @@ bool QuorumHash::operator==(const QuorumHash& other) const return true; case Kind::SHA256: - return boost::get(m_hash) - == boost::get(other.m_hash); + return std::get(m_hash) + == std::get(other.m_hash); case Kind::MD5: - return boost::get(m_hash) - == boost::get(other.m_hash); + return std::get(m_hash) + == std::get(other.m_hash); } return false; @@ -1109,7 +1108,7 @@ bool QuorumHash::operator!=(const QuorumHash& other) const bool QuorumHash::operator==(const uint256& other) const { return Which() == Kind::SHA256 - && boost::get(m_hash) == other; + && std::get(m_hash) == other; } bool QuorumHash::operator!=(const uint256& other) const @@ -1125,13 +1124,13 @@ bool QuorumHash::operator==(const std::string& other) const case Kind::SHA256: return other.size() == sizeof(uint256) * 2 - && boost::get(m_hash) == uint256S(other); + && std::get(m_hash) == uint256S(other); case Kind::MD5: return other.size() == sizeof(Md5Sum) * 2 && std::equal( - boost::get(m_hash).begin(), - boost::get(m_hash).end(), + std::get(m_hash).begin(), + std::get(m_hash).end(), ParseHex(other).begin()); } @@ -1145,7 +1144,7 @@ bool QuorumHash::operator!=(const std::string&other) const QuorumHash::Kind QuorumHash::Which() const { - return static_cast(m_hash.which()); + return static_cast(m_hash.index()); } bool QuorumHash::Valid() const @@ -1159,9 +1158,9 @@ const unsigned char* QuorumHash::Raw() const case Kind::INVALID: return nullptr; case Kind::SHA256: - return boost::get(m_hash).begin(); + return std::get(m_hash).begin(); case Kind::MD5: - return boost::get(m_hash).data(); + return std::get(m_hash).data(); } return nullptr; @@ -1169,5 +1168,5 @@ const unsigned char* QuorumHash::Raw() const std::string QuorumHash::ToString() const { - return boost::apply_visitor(QuorumHashToStringVisitor(), m_hash); + return std::visit(QuorumHashToStringVisitor(), m_hash); } diff --git a/src/gridcoin/superblock.h b/src/gridcoin/superblock.h index 17400f20a6..9d40d97160 100644 --- a/src/gridcoin/superblock.h +++ b/src/gridcoin/superblock.h @@ -10,8 +10,7 @@ #include "serialize.h" #include "uint256.h" -#include -#include +#include #include #include #include @@ -171,7 +170,7 @@ class QuorumHash template void Serialize(Stream& stream) const { - unsigned char kind = m_hash.which(); + unsigned char kind = m_hash.index(); ::Serialize(stream, kind); @@ -180,11 +179,11 @@ class QuorumHash break; // Suppress warning. case Kind::SHA256: - boost::get(m_hash).Serialize(stream); + std::get(m_hash).Serialize(stream); break; case Kind::MD5: { - const Md5Sum& hash = boost::get(m_hash); + const Md5Sum& hash = std::get(m_hash); stream.write(CharCast(hash.data()), hash.size()); break; @@ -234,7 +233,7 @@ class QuorumHash //! CONSENSUS: Do not remove or reorder the types in this variant. This //! class relies on the type ordinality to tag serialized values. //! - boost::variant m_hash; + std::variant m_hash; }; // QuorumHash //! @@ -359,7 +358,7 @@ class Superblock //! //! \return The CPID's magnitude at normal scale. //! - boost::optional MagnitudeOf(const Cpid& cpid) const + std::optional MagnitudeOf(const Cpid& cpid) const { const auto iter = std::lower_bound( m_magnitudes.begin(), @@ -368,7 +367,7 @@ class Superblock CompareCpidOfPairLessThan); if (iter == m_magnitudes.end() || iter->first != cpid) { - return boost::none; + return std::nullopt; } return Magnitude::FromScaled(iter->second * Scale); @@ -1001,7 +1000,7 @@ class Superblock //! \brief An optional type that either contains some project statistics or //! does not. //! - typedef boost::optional ProjectStatsOption; + typedef std::optional ProjectStatsOption; //! //! \brief Contains aggregated project statistics. diff --git a/src/gridcoin/tally.cpp b/src/gridcoin/tally.cpp index 0def673741..985c497b34 100644 --- a/src/gridcoin/tally.cpp +++ b/src/gridcoin/tally.cpp @@ -1119,7 +1119,7 @@ AccrualComputer Tally::GetComputer( const CBlockIndex* const last_block_ptr) { if (!last_block_ptr) { - return MakeUnique(); + return std::make_unique(); } if (last_block_ptr->nVersion >= 11) { @@ -1136,7 +1136,7 @@ AccrualComputer Tally::GetSnapshotComputer( const CBlockIndex* const last_block_ptr, const SuperblockPtr superblock) { - return MakeUnique( + return std::make_unique( cpid, account, payment_time, @@ -1165,7 +1165,7 @@ AccrualComputer Tally::GetLegacyComputer( const ResearchAccount& account = GetAccount(cpid); if (!account.IsActive(last_block_ptr->nHeight)) { - return MakeUnique( + return std::make_unique( cpid, account, payment_time, @@ -1173,7 +1173,7 @@ AccrualComputer Tally::GetLegacyComputer( Quorum::CurrentSuperblock()->m_cpids.MagnitudeOf(cpid).Floating()); } - return MakeUnique( + return std::make_unique( cpid, account, Quorum::CurrentSuperblock()->m_cpids.MagnitudeOf(cpid).Floating(), diff --git a/src/gridcoin/voting/builders.cpp b/src/gridcoin/voting/builders.cpp index 5e9bd66572..30acae1cfb 100644 --- a/src/gridcoin/voting/builders.cpp +++ b/src/gridcoin/voting/builders.cpp @@ -147,7 +147,7 @@ class CoinPicker //! \brief Adds outputs for an address only when an address represents //! a pay-to-public-key or pay-to-public-key-hash destination. //! - class PubkeyDestinationFilter : public boost::static_visitor + class PubkeyDestinationFilter { public: //! @@ -232,7 +232,7 @@ class CoinPicker // more advanced redemption scripts like multisig yet: // auto filter = std::bind(pubkey_filter, std::placeholders::_1, txo); - boost::apply_visitor(filter, dest); + std::visit(filter, dest); } return by_address; @@ -293,7 +293,7 @@ class AddressClaimBuilder //! //! \return An address claim for the provided outputs. //! - boost::optional TryBuildClaim(AddressOutputs address_outputs) const + std::optional TryBuildClaim(AddressOutputs address_outputs) const { AddressClaim claim(std::move(address_outputs.m_outpoints)); @@ -302,7 +302,7 @@ class AddressClaimBuilder __func__, DestinationToAddressString(address_outputs.m_key_id)); - return boost::none; + return std::nullopt; } // An address claim must submit outputs in ascending order. This @@ -493,7 +493,7 @@ class MagnitudeClaimBuilder return; } - const boost::optional beacon = m_researcher->TryBeacon(); + const std::optional beacon = m_researcher->TryBeacon(); // Avoid building a claim for a beacon that will expire soon: if (!beacon || beacon->Expired(GetAdjustedTime() + 15 * 60)) { @@ -501,7 +501,7 @@ class MagnitudeClaimBuilder return; } - const boost::optional beacon_txid = FindBeaconTxid(*beacon); + const std::optional beacon_txid = FindBeaconTxid(*beacon); if (!beacon_txid) { LogPrint(LogFlags::VOTE, "%s: beacon tx not found", __func__); @@ -527,7 +527,7 @@ class MagnitudeClaimBuilder return true; } - const boost::optional beacon = m_researcher->TryBeacon(); + const std::optional beacon = m_researcher->TryBeacon(); if (!beacon) { // Should never happen: @@ -569,7 +569,7 @@ class MagnitudeClaimBuilder //! //! \return The hash of the transaction for the beacon contract if found. //! - boost::optional FindBeaconTxid(const Beacon& beacon) const + std::optional FindBeaconTxid(const Beacon& beacon) const { // TODO: This is rather slow, but we only need to do it once per vote. // Store a reference to a wallet's beacon transactions and rewrite the @@ -578,7 +578,7 @@ class MagnitudeClaimBuilder const CBlockIndex* pindex = pindexBest; if (!pindex) { - return boost::none; + return std::nullopt; } const int64_t max_time = FutureDrift(beacon.m_timestamp, 0); @@ -611,7 +611,7 @@ class MagnitudeClaimBuilder } } - return boost::none; + return std::nullopt; } }; // MagnitudeClaimBuilder @@ -872,7 +872,7 @@ void GRC::SendVoteContract(VoteBuilder builder) // Class: PollBuilder // ----------------------------------------------------------------------------- -PollBuilder::PollBuilder() : m_poll(MakeUnique()) +PollBuilder::PollBuilder() : m_poll(std::make_unique()) { } @@ -1115,7 +1115,7 @@ CWalletTx PollBuilder::BuildContractTx(CWallet* const pwallet) VoteBuilder::VoteBuilder(const Poll& poll, const uint256 poll_txid) : m_poll(&poll) - , m_vote(MakeUnique()) + , m_vote(std::make_unique()) { m_vote->m_poll_txid = poll_txid; } @@ -1206,7 +1206,7 @@ VoteBuilder VoteBuilder::AddResponse(const uint8_t offset) VoteBuilder VoteBuilder::AddResponse(const std::string& label) { - if (boost::optional offset = m_poll->Choices().OffsetOf(label)) { + if (std::optional offset = m_poll->Choices().OffsetOf(label)) { return AddResponse(*offset); } diff --git a/src/gridcoin/voting/fwd.h b/src/gridcoin/voting/fwd.h index 99a29fb49c..ed7c136ce7 100644 --- a/src/gridcoin/voting/fwd.h +++ b/src/gridcoin/voting/fwd.h @@ -6,7 +6,6 @@ #include "amount.h" -#include namespace GRC { @@ -15,8 +14,8 @@ class PollReference; class PollResult; class Vote; -using PollOption = boost::optional; -using PollResultOption = boost::optional; +using PollOption = std::optional; +using PollResultOption = std::optional; //! //! \brief The unspent amount that a poll creator must hold in an address. diff --git a/src/gridcoin/voting/poll.cpp b/src/gridcoin/voting/poll.cpp index e185943efe..68ff722279 100644 --- a/src/gridcoin/voting/poll.cpp +++ b/src/gridcoin/voting/poll.cpp @@ -291,7 +291,7 @@ bool ChoiceList::LabelExists(const std::string& label) const return OffsetOf(label).operator bool(); } -boost::optional ChoiceList::OffsetOf(const std::string& label) const +std::optional ChoiceList::OffsetOf(const std::string& label) const { const auto iter = std::find_if( m_choices.begin(), @@ -299,7 +299,7 @@ boost::optional ChoiceList::OffsetOf(const std::string& label) const [&](const Choice& choice) { return choice.m_label == label; }); if (iter == m_choices.end()) { - return boost::none; + return std::nullopt; } return std::distance(m_choices.begin(), iter); diff --git a/src/gridcoin/voting/poll.h b/src/gridcoin/voting/poll.h index fcec48f0bf..bc62ff4a12 100644 --- a/src/gridcoin/voting/poll.h +++ b/src/gridcoin/voting/poll.h @@ -169,7 +169,7 @@ class Poll //! \return An object that either contains the offset of the label or //! does not when no choice contains a matching label. //! - boost::optional OffsetOf(const std::string& label) const; + std::optional OffsetOf(const std::string& label) const; //! //! \brief Get the poll choice at the specified offset. diff --git a/src/gridcoin/voting/registry.cpp b/src/gridcoin/voting/registry.cpp index dc24f89464..4eb5ff24b6 100644 --- a/src/gridcoin/voting/registry.cpp +++ b/src/gridcoin/voting/registry.cpp @@ -241,7 +241,7 @@ PollOption PollReference::TryReadFromDisk(CTxDB& txdb) const if (!txdb.ReadDiskTx(*m_ptxid, tx)) { error("%s: failed to read poll tx from disk", __func__); - return boost::none; + return std::nullopt; } for (auto& contract : tx.PullContracts()) { @@ -255,7 +255,7 @@ PollOption PollReference::TryReadFromDisk(CTxDB& txdb) const error("%s: transaction does not contain a poll contract", __func__); - return boost::none; + return std::nullopt; } PollOption PollReference::TryReadFromDisk() const diff --git a/src/gridcoin/voting/result.cpp b/src/gridcoin/voting/result.cpp index 173810838d..4582d1c128 100644 --- a/src/gridcoin/voting/result.cpp +++ b/src/gridcoin/voting/result.cpp @@ -13,7 +13,7 @@ #include "txdb.h" #include "util/reverse_iterator.h" -#include +#include #include #include @@ -1091,7 +1091,7 @@ PollResultOption PollResult::BuildFor(const PollReference& poll_ref) return result; } - return boost::none; + return std::nullopt; } size_t PollResult::Winner() const diff --git a/src/init.cpp b/src/init.cpp index de68e694df..2fae42b68b 100755 --- a/src/init.cpp +++ b/src/init.cpp @@ -1080,7 +1080,7 @@ bool AppInit2(ThreadHandlerPtr threads) // Ban manager instance should not already be instantiated assert(!g_banman); // Create ban manager instance. - g_banman = MakeUnique(GetDataDir() / "banlist.dat", &uiInterface, GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); + g_banman = std::make_unique(GetDataDir() / "banlist.dat", &uiInterface, GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); uiInterface.InitMessage(_("Loading addresses...")); LogPrint(BCLog::LogFlags::NOISY, "Loading addresses..."); diff --git a/src/main.cpp b/src/main.cpp index c09332dd81..a37f4d9338 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4214,7 +4214,7 @@ GRC::ClaimOption GetClaimByIndex(const CBlockIndex* const pblockindex) if (!pblockindex || !pblockindex->IsInMainChain() || !block.ReadFromDisk(pblockindex)) { - return boost::none; + return std::nullopt; } return block.PullClaim(); diff --git a/src/main.h b/src/main.h index 572d79ee4e..84226720e5 100644 --- a/src/main.h +++ b/src/main.h @@ -44,7 +44,7 @@ class SuperblockPtr; //! //! \brief An optional type that either contains some claim object or does not. //! -typedef boost::optional ClaimOption; +typedef std::optional ClaimOption; } static const int64_t DEFAULT_CBR = 10 * COIN; diff --git a/src/miner.cpp b/src/miner.cpp index b528dc529d..2691c82521 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -193,7 +193,7 @@ class TxPriorityCompare } }; -boost::optional GetLastStake(CWallet& wallet) +std::optional GetLastStake(CWallet& wallet) { CWalletTx stake_tx; uint256 cached_stake_tx_hash; @@ -217,7 +217,7 @@ boost::optional GetLastStake(CWallet& wallet) LOCK2(cs_main, wallet.cs_wallet); if (wallet.mapWallet.empty()) { - return boost::none; + return std::nullopt; } auto latest_iter = wallet.mapWallet.cbegin(); @@ -233,7 +233,7 @@ boost::optional GetLastStake(CWallet& wallet) if (latest_iter == wallet.mapWallet.cbegin() && !is_my_confirmed_stake(latest_iter->second)) { - return boost::none; + return std::nullopt; } cached_stake_tx_hash = latest_iter->first; @@ -268,7 +268,7 @@ bool CreateRestOfTheBlock(CBlock &block, CBlockIndex* pindexPrev) // Largest block you're willing to create: unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2); // Limit to between 1K and MAX_BLOCK_SIZE-1K for sanity: - nBlockMaxSize = clamp(nBlockMaxSize, 1000, MAX_BLOCK_SIZE - 1000); + nBlockMaxSize = std::clamp(nBlockMaxSize, 1000, MAX_BLOCK_SIZE - 1000); // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay diff --git a/src/miner.h b/src/miner.h index d851291d4d..343920bea5 100644 --- a/src/miner.h +++ b/src/miner.h @@ -8,7 +8,6 @@ #include "main.h" -#include class CWallet; class CWalletTx; @@ -22,7 +21,7 @@ extern unsigned int nMinerSleep; // It will be converted to Halfords in GetNumberOfStakeOutputs by multiplying by COIN. static const int64_t MIN_STAKE_SPLIT_VALUE_GRC = 800; -boost::optional GetLastStake(CWallet& wallet); +std::optional GetLastStake(CWallet& wallet); void SplitCoinStakeOutput(CBlock &blocknew, int64_t &nReward, bool &fEnableStakeSplit, bool &fEnableSideStaking, SideStakeAlloc &vSideStakeAlloc, double &dEfficiency); unsigned int GetNumberOfStakeOutputs(int64_t &nValue, int64_t &nMinStakeSplitValue, double &dEfficiency); diff --git a/src/net.cpp b/src/net.cpp index 4e7f95033d..d3df270f51 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -1307,13 +1307,13 @@ void ThreadDNSAddressSeed2(void* parg) { LogPrint(BCLog::LogFlags::NET, "Loading addresses from DNS seeds (could take a while)"); - for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) { + for (const auto& seed : strDNSSeed) { if (HaveNameProxy()) { - AddOneShot(strDNSSeed[seed_idx][1]); + AddOneShot(seed[1]); } else { vector vaddr; vector vAdd; - if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) + if (LookupHost(seed[1], vaddr)) { for (auto const& ip : vaddr) { @@ -1324,7 +1324,7 @@ void ThreadDNSAddressSeed2(void* parg) found++; } } - addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); + addrman.Add(vAdd, CNetAddr(seed[0], true)); } } } @@ -1526,7 +1526,7 @@ void ThreadOpenConnections2(void* parg) if (addrman.size()==0 && (GetAdjustedTime() - nStart > 60) && !fTestNet) { std::vector vAdd; - for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) + for (const auto& seed : pnSeed) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. @@ -1534,9 +1534,9 @@ void ThreadOpenConnections2(void* parg) // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; - memcpy(&ip, &pnSeed[i], sizeof(ip)); + memcpy(&ip, &seed, sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); - addr.nTime = GetAdjustedTime()-GetRand(nOneWeek)-nOneWeek; + addr.nTime = GetAdjustedTime() - GetRand(nOneWeek) - nOneWeek; vAdd.push_back(addr); } addrman.Add(vAdd, CNetAddr("127.0.0.1")); diff --git a/src/protocol.cpp b/src/protocol.cpp index 87bc4495d0..7db42fc240 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -91,7 +91,7 @@ CInv::CInv(int typeIn, const uint256& hashIn) : type(typeIn), hash(hashIn) {} CInv::CInv(const std::string& strType, const uint256& hashIn) { unsigned int i; - for (i = 1; i < ARRAYLEN(ppszTypeName); i++) + for (i = 1; i < std::size(ppszTypeName); i++) { if (strType == ppszTypeName[i]) { @@ -99,7 +99,7 @@ CInv::CInv(const std::string& strType, const uint256& hashIn) break; } } - if (i == ARRAYLEN(ppszTypeName)) + if (i == std::size(ppszTypeName)) throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType)); hash = hashIn; } @@ -111,7 +111,7 @@ bool operator<(const CInv& a, const CInv& b) bool CInv::IsKnownType() const { - return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName)); + return (type >= 1 && type < (int)std::size(ppszTypeName)); } const char* CInv::GetCommand() const diff --git a/src/qt/coincontroldialog.cpp b/src/qt/coincontroldialog.cpp index b297a1a45f..e6919488aa 100644 --- a/src/qt/coincontroldialog.cpp +++ b/src/qt/coincontroldialog.cpp @@ -464,14 +464,17 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) // Bytes CTxDestination address; - if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) + if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; - CKeyID *keyid = boost::get< CKeyID >(&address); - if (keyid && model->getPubKey(*keyid, pubkey)) - nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); - else - nBytesInputs += 148; // in all error cases, simply assume 148 here + try { + if (model->getPubKey(std::get(address), pubkey)) + nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); + else + nBytesInputs += 148; // in all error cases, simply assume 148 here + } catch (const std::bad_variant_access&) { + nBytesInputs += 148; + } } else nBytesInputs += 148; } @@ -636,7 +639,7 @@ void CoinControlDialog::updateView() // address CTxDestination outputAddress; QString sAddress = ""; - if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) + if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = CBitcoinAddress(outputAddress).ToString().c_str(); @@ -645,9 +648,10 @@ void CoinControlDialog::updateView() itemOutput->setText(COLUMN_ADDRESS, sAddress); CPubKey pubkey; - CKeyID *keyid = boost::get< CKeyID >(&outputAddress); - if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) - nInputSize = 180; + try { + if (model->getPubKey(std::get(outputAddress), pubkey) && !pubkey.IsCompressed()) + nInputSize = 180; + } catch (const std::bad_variant_access&) {} } // label diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index b7195b3d22..dc0f6dd21a 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -247,12 +247,9 @@ class CRPCConvertTable CRPCConvertTable::CRPCConvertTable() { - const unsigned int n_elem = - (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); - - for (unsigned int i = 0; i < n_elem; i++) { - members.insert(std::make_pair(vRPCConvertParams[i].methodName, - vRPCConvertParams[i].paramIdx)); + for (const auto& elem : vRPCConvertParams) { + members.insert(std::make_pair(elem.methodName, + elem.paramIdx)); } } diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 35d66dac27..5deb0e517b 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -174,7 +174,7 @@ UniValue getlaststake(const UniValue& params, bool fHelp) "\n" "Fetch information about this wallet's last staked block.\n"); - const boost::optional stake_tx = GetLastStake(*pwalletMain); + const std::optional stake_tx = GetLastStake(*pwalletMain); if (!stake_tx) { throw JSONRPCError(RPC_WALLET_ERROR, "No prior staked blocks found."); @@ -384,7 +384,7 @@ UniValue auditsnapshotaccrual(const UniValue& params, bool fHelp) const AccrualSnapshot snapshot = AccrualSnapshotReader(snapshot_path).Read(); int64_t accrual = 0; - auto entry = snapshot.m_records.find(cpid.get()); + auto entry = snapshot.m_records.find(cpid.value()); if (entry != snapshot.m_records.end()) { diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 84d54f8355..5ef4f1f4fb 100755 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -711,17 +711,20 @@ UniValue consolidateunspent(const UniValue& params, bool fHelp) // For fee calculation. This is similar to the calculation in coincontroldialog.cpp. CTxDestination address; - if(ExtractDestination(out.second.tx->vout[out.second.i].scriptPubKey, address)) + if (ExtractDestination(out.second.tx->vout[out.second.i].scriptPubKey, address)) { CPubKey pubkey; - CKeyID *keyid = boost::get(&address); - if (keyid && pwalletMain->GetPubKey(*keyid, pubkey)) - { - nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); - } - // in all error cases, simply assume 148 here - else - { + try { + if (pwalletMain->GetPubKey(std::get(address), pubkey)) + { + nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); + } + // in all error cases, simply assume 148 here + else + { + nBytesInputs += 148; + } + } catch (const std::bad_variant_access&) { nBytesInputs += 148; } } diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index ef075b57e1..95bd223126 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -461,13 +461,9 @@ static constexpr const char* DEPRECATED_RPCS[] { CRPCTable::CRPCTable() { - unsigned int vcidx; - for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) + for (const auto& cmd : vRPCCommands) { - const CRPCCommand *pcmd; - - pcmd = &vRPCCommands[vcidx]; - mapCommands[pcmd->name] = pcmd; + mapCommands[cmd.name] = &cmd; } } diff --git a/src/script.cpp b/src/script.cpp index 65a4eb3aab..2521507514 100644 --- a/src/script.cpp +++ b/src/script.cpp @@ -1533,7 +1533,7 @@ unsigned int HaveKeys(const vector& pubkeys, const CKeyStore& keystore) return nResult; } -class CKeyStoreIsMineVisitor : public boost::static_visitor +class CKeyStoreIsMineVisitor { private: const CKeyStore *keystore; @@ -1546,7 +1546,7 @@ class CKeyStoreIsMineVisitor : public boost::static_visitor isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest) { - if (boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest)) + if (std::visit(CKeyStoreIsMineVisitor(&keystore), dest)) { return ISMINE_SPENDABLE; } @@ -1648,7 +1648,7 @@ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) return false; } -class CAffectedKeysVisitor : public boost::static_visitor { +class CAffectedKeysVisitor { private: const CKeyStore &keystore; std::vector &vKeys; @@ -1662,7 +1662,7 @@ class CAffectedKeysVisitor : public boost::static_visitor { int nRequired; if (ExtractDestinations(script, type, vDest, nRequired)) { for (auto const &dest : vDest) - boost::apply_visitor(*this, dest); + std::visit(*this, dest); } } @@ -2023,7 +2023,7 @@ bool CScript::HasCanonicalPushes() const return true; } -class CScriptVisitor : public boost::static_visitor +class CScriptVisitor { private: CScript *script; @@ -2050,7 +2050,7 @@ class CScriptVisitor : public boost::static_visitor void CScript::SetDestination(const CTxDestination& dest) { - boost::apply_visitor(CScriptVisitor(this), dest); + std::visit(CScriptVisitor(this), dest); } void CScript::SetMultisig(int nRequired, const std::vector& keys) diff --git a/src/script.h b/src/script.h index 2b0043d1f8..ceb22cecae 100644 --- a/src/script.h +++ b/src/script.h @@ -7,11 +7,11 @@ #define H_BITCOIN_SCRIPT #include +#include #include #include -#include #include "keystore.h" #include "bignum.h" @@ -72,6 +72,7 @@ enum txnouttype class CNoDestination { public: friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; } + friend bool operator!=(const CNoDestination &a, const CNoDestination &b) { return false; } friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; } }; @@ -81,7 +82,7 @@ class CNoDestination { * * CScriptID: TX_SCRIPTHASH destination * A CTxDestination is the internal data type encoded in a CBitcoinAddress */ -typedef boost::variant CTxDestination; +typedef std::variant CTxDestination; const char* GetTxnOutputType(txnouttype t); diff --git a/src/test/allocator_tests.cpp b/src/test/allocator_tests.cpp index 0020f121c3..834dd323f4 100644 --- a/src/test/allocator_tests.cpp +++ b/src/test/allocator_tests.cpp @@ -2,7 +2,6 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include //#include //#include @@ -165,7 +164,7 @@ class TestLockedPageAllocator: public LockedPageAllocator BOOST_AUTO_TEST_CASE(lockedpool_tests_mock) { // Test over three virtual arenas, of which one will succeed being locked - std::unique_ptr x = MakeUnique(3, 1); + std::unique_ptr x = std::make_unique(3, 1); LockedPool pool(std::move(x)); BOOST_CHECK(pool.stats().total == 0); BOOST_CHECK(pool.stats().locked == 0); diff --git a/src/test/base32_tests.cpp b/src/test/base32_tests.cpp index fdf3285913..2766103f12 100644 --- a/src/test/base32_tests.cpp +++ b/src/test/base32_tests.cpp @@ -8,7 +8,7 @@ BOOST_AUTO_TEST_CASE(base32_testvectors) { static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"}; static const std::string vstrOut[] = {"","my======","mzxq====","mzxw6===","mzxw6yq=","mzxw6ytb","mzxw6ytboi======"}; - for (unsigned int i=0; i +class TestAddrTypeVisitor { private: std::string exp_addrType; @@ -79,7 +79,7 @@ class TestAddrTypeVisitor : public boost::static_visitor }; // Visitor to check address payload -class TestPayloadVisitor : public boost::static_visitor +class TestPayloadVisitor { private: std::vector exp_payload; @@ -148,7 +148,7 @@ BOOST_AUTO_TEST_CASE(base58_keys_valid_parse) BOOST_CHECK_MESSAGE(addr.IsValid(), "!IsValid:" + strTest); BOOST_CHECK_MESSAGE(addr.IsScript() == (exp_addrType == "script"), "isScript mismatch" + strTest); CTxDestination dest = addr.Get(); - BOOST_CHECK_MESSAGE(boost::apply_visitor(TestAddrTypeVisitor(exp_addrType), dest), "addrType mismatch" + strTest); + BOOST_CHECK_MESSAGE(std::visit(TestAddrTypeVisitor(exp_addrType), dest), "addrType mismatch" + strTest); // Public key must be invalid private key secret.SetString(exp_base58string); @@ -209,7 +209,7 @@ BOOST_AUTO_TEST_CASE(base58_keys_valid_gen) continue; } CBitcoinAddress addrOut; - BOOST_CHECK_MESSAGE(boost::apply_visitor(CBitcoinAddressVisitor(&addrOut), dest), "encode dest: " + strTest); + BOOST_CHECK_MESSAGE(std::visit(CBitcoinAddressVisitor(&addrOut), dest), "encode dest: " + strTest); BOOST_CHECK_MESSAGE(addrOut.ToString() == exp_base58string, "mismatch: " + strTest + addrOut.ToString()); } } @@ -217,7 +217,7 @@ BOOST_AUTO_TEST_CASE(base58_keys_valid_gen) // Visiting a CNoDestination must fail CBitcoinAddress dummyAddr; CTxDestination nodest = CNoDestination(); - BOOST_CHECK(!boost::apply_visitor(CBitcoinAddressVisitor(&dummyAddr), nodest)); + BOOST_CHECK(!std::visit(CBitcoinAddressVisitor(&dummyAddr), nodest)); // Restore global state fTestNet = fTestNet_stored; diff --git a/src/test/base64_tests.cpp b/src/test/base64_tests.cpp index d89ef81bb3..6ff23c2e74 100644 --- a/src/test/base64_tests.cpp +++ b/src/test/base64_tests.cpp @@ -10,7 +10,7 @@ BOOST_AUTO_TEST_CASE(base64_testvectors) { static const std::string vstrIn[] = {"","f","fo","foo","foob","fooba","foobar"}; static const std::string vstrOut[] = {"","Zg==","Zm8=","Zm9v","Zm9vYg==","Zm9vYmE=","Zm9vYmFy"}; - for (unsigned int i=0; i(GetDataDir() / "banlist.dat", &uiInterface, GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); + g_banman = std::make_unique(GetDataDir() / "banlist.dat", &uiInterface, GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); } ~TestingSetup() { diff --git a/src/ui_interface.h b/src/ui_interface.h index a1b285af0f..66dc144f5e 100644 --- a/src/ui_interface.h +++ b/src/ui_interface.h @@ -121,12 +121,12 @@ class CClientUIInterface extern CClientUIInterface uiInterface; /** - * Translation function: Call Translate signal on UI interface, which returns a boost::optional result. + * Translation function: Call Translate signal on UI interface, which returns a std::optional result. * If no translation slot is registered, nothing is returned, and simply return the input. */ inline std::string _(const char* psz) { - boost::optional rv = uiInterface.Translate(psz); + auto rv = uiInterface.Translate(psz); return rv ? (*rv) : psz; } diff --git a/src/util.cpp b/src/util.cpp index f2c15c58d2..9f095d2c60 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -9,7 +9,6 @@ #include "version.h" #include "ui_interface.h" #include "util.h" -#include "util/memory.h" #include // for to_lower() #include @@ -836,7 +835,7 @@ bool LockDirectory(const fs::path& directory, const std::string lockfile_name, b // Create empty lock file if it doesn't exist. FILE* file = fsbridge::fopen(pathLockFile, "a"); if (file) fclose(file); - auto lock = MakeUnique(pathLockFile); + auto lock = std::make_unique(pathLockFile); if (!lock->TryLock()) { return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason()); } diff --git a/src/util.h b/src/util.h index c70fe621bc..bd932e7eb3 100644 --- a/src/util.h +++ b/src/util.h @@ -27,6 +27,7 @@ #include #include +#include "compat/assumptions.h" // After merging some more of Bitcoin's utilities, we can split them out // of this file to reduce the header load: @@ -244,20 +245,6 @@ inline std::string leftTrim(std::string src, char chr) return src; } -// This is effectively straight out of C++ 17 . When we move to C++ 17 we -// can get rid of this and use std::clamp. -template -constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp) -{ - return assert(!comp(hi, lo)), comp(v, lo) ? lo : comp(hi, v) ? hi : v; -} - -template -constexpr const T& clamp(const T& v, const T& lo, const T& hi) -{ - return clamp(v, lo, hi, std::less()); -} - inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; diff --git a/src/util/memory.h b/src/util/memory.h deleted file mode 100644 index 15ecf8f80d..0000000000 --- a/src/util/memory.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2018 The Bitcoin Core developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#ifndef BITCOIN_UTIL_MEMORY_H -#define BITCOIN_UTIL_MEMORY_H - -#include -#include - -//! Substitute for C++14 std::make_unique. -template -std::unique_ptr MakeUnique(Args&&... args) -{ - return std::unique_ptr(new T(std::forward(args)...)); -} - -#endif diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index 1e7d24c71c..4c2f713cc9 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -263,7 +263,7 @@ std::string DecodeBase32(const std::string& str, bool* pf_invalid) return std::string((const char*)vchRet.data(), vchRet.size()); } -NODISCARD static bool ParsePrechecks(const std::string& str) +[[nodiscard]] static bool ParsePrechecks(const std::string& str) { if (str.empty()) // No empty string allowed return false; diff --git a/src/util/strencodings.h b/src/util/strencodings.h index e35b2ab857..9b9ac6fa58 100644 --- a/src/util/strencodings.h +++ b/src/util/strencodings.h @@ -16,8 +16,6 @@ #include #include -#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) - /** Used by SanitizeString() */ enum SafeChars { @@ -91,35 +89,35 @@ constexpr inline bool IsSpace(char c) noexcept { * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ -NODISCARD bool ParseInt32(const std::string& str, int32_t *out); +[[nodiscard]] bool ParseInt32(const std::string& str, int32_t *out); /** * Convert string to signed 64-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ -NODISCARD bool ParseInt64(const std::string& str, int64_t *out); +[[nodiscard]] bool ParseInt64(const std::string& str, int64_t *out); /** * Convert decimal string to unsigned 32-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ -NODISCARD bool ParseUInt32(const std::string& str, uint32_t *out); +[[nodiscard]] bool ParseUInt32(const std::string& str, uint32_t *out); /** * Convert decimal string to unsigned 64-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ -NODISCARD bool ParseUInt64(const std::string& str, uint64_t *out); +[[nodiscard]] bool ParseUInt64(const std::string& str, uint64_t *out); /** * Convert string to double with strict parse error feedback. * @returns true if the entire string could be parsed as valid double, * false if not the entire string could be parsed or when overflow or underflow occurred. */ -NODISCARD bool ParseDouble(const std::string& str, double *out); +[[nodiscard]] bool ParseDouble(const std::string& str, double *out); template std::string HexStr(const T itbegin, const T itend) @@ -169,7 +167,7 @@ bool TimingResistantEqual(const T& a, const T& b) * @returns true on success, false on error. * @note The result must be in the range (-10^18,10^18), otherwise an overflow error will trigger. */ -NODISCARD bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out); +[[nodiscard]] bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out); /** Convert from one power-of-2 number base to another. */ template diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 2852f79296..f76261794f 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -10,7 +10,6 @@ #include "base58.h" #include -#include #include using namespace std; @@ -29,8 +28,6 @@ const std::locale formats[] = { std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d")) }; -const size_t formats_n = sizeof(formats)/sizeof(formats[0]); - std::time_t pt_to_time_t(const bt::ptime& pt) { bt::ptime timet_start(boost::gregorian::date(1970,1,1)); @@ -42,10 +39,10 @@ int64_t DecodeDumpTime(const std::string& s) { bt::ptime pt; - for(size_t i=0; i> pt; if(pt != bt::ptime()) break; } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e4b46f6dab..9be81c5933 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -20,6 +20,7 @@ #include "wallet/ismine.h" #include +#include using namespace std; @@ -2294,7 +2295,7 @@ UniValue encryptwallet(const UniValue& params, bool fHelp) return "wallet encrypted; Gridcoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } -class DescribeAddressVisitor : public boost::static_visitor +class DescribeAddressVisitor { public: UniValue operator()(const CNoDestination &dest) const { return UniValue(); } @@ -2353,7 +2354,7 @@ UniValue validateaddress(const UniValue& params, bool fHelp) bool fMine = IsMine(*pwalletMain, dest) != ISMINE_NO; ret.pushKV("ismine", fMine); if (fMine) { - UniValue detail = boost::apply_visitor(DescribeAddressVisitor(), dest); + UniValue detail = std::visit(DescribeAddressVisitor(), dest); ret.pushKVs(detail); } if (pwalletMain->mapAddressBook.count(dest)) @@ -2394,7 +2395,7 @@ UniValue validatepubkey(const UniValue& params, bool fHelp) ret.pushKV("ismine", fMine); ret.pushKV("iscompressed", isCompressed); if (fMine) { - UniValue detail = boost::apply_visitor(DescribeAddressVisitor(), dest); + UniValue detail = std::visit(DescribeAddressVisitor(), dest); ret.pushKVs(detail); } if (pwalletMain->mapAddressBook.count(dest)) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 17152a6383..936df1d14f 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -15,7 +15,6 @@ #include "rpc/server.h" #include "rpc/client.h" #include "rpc/protocol.h" -#include #include #include "main.h" #include "util.h" @@ -1532,7 +1531,8 @@ bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, vector > > vValue; int64_t nTotalLower = 0; - random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); + auto seed = static_cast(GetTimeMicros()); + std::shuffle(vCoins.begin(), vCoins.end(), std::default_random_engine(seed)); for (auto output : vCoins) { @@ -1966,7 +1966,7 @@ bool CWallet::CreateTransaction(const vector >& vecSend, CScript scriptChange; // coin control: send change to custom address - if (coinControl && !boost::get(&coinControl->destChange)) + if (coinControl && !std::get_if(&coinControl->destChange)) scriptChange.SetDestination(coinControl->destChange); // no coin control: send change to newly generated address diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp index 4c3f9a5518..eaaf7313ba 100644 --- a/src/wallet/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -8,6 +8,8 @@ #include "wallet/wallet.h" #include "init.h" +#include + using namespace std; static uint64_t nAccountingEntryNumber = 0; diff --git a/test/lint/lint-includes.sh b/test/lint/lint-includes.sh index 4c872564a9..7a0bc43334 100755 --- a/test/lint/lint-includes.sh +++ b/test/lint/lint-includes.sh @@ -60,7 +60,6 @@ EXPECTED_BOOST_INCLUDES=( boost/multi_index/ordered_index.hpp boost/multi_index/sequenced_index.hpp boost/multi_index_container.hpp - boost/optional.hpp boost/preprocessor/cat.hpp boost/preprocessor/stringize.hpp boost/process.hpp @@ -72,9 +71,6 @@ EXPECTED_BOOST_INCLUDES=( boost/thread/mutex.hpp boost/thread/shared_mutex.hpp boost/thread/thread.hpp - boost/variant.hpp - boost/variant/apply_visitor.hpp - boost/variant/static_visitor.hpp ) #for BOOST_INCLUDE in $(git grep '^#include ' | sort -u); do