refactor: Enforce lowercase hex digits for consteval uint256

Also changes compile-time asserts with comments into throws.
This commit is contained in:
Hodlinator 2024-08-19 14:45:54 +02:00
parent 4ee1940e84
commit 7e1d9a8468
No known key found for this signature in database
3 changed files with 5 additions and 6 deletions

View file

@ -177,7 +177,7 @@ void sanity_check_chainparams(const ArgsManager& args, ChainType chain_type)
// check max target * 4*nPowTargetTimespan doesn't overflow -- see pow.cpp:CalculateNextWorkRequired()
if (!consensus.fPowNoRetargeting) {
arith_uint256 targ_max{UintToArith256(uint256{"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"})};
arith_uint256 targ_max{UintToArith256(uint256{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"})};
targ_max /= consensus.nPowTargetTimespan*4;
BOOST_CHECK(UintToArith256(consensus.powLimit) < targ_max);
}

View file

@ -431,7 +431,7 @@ BOOST_AUTO_TEST_CASE( check_ONE )
BOOST_AUTO_TEST_CASE(FromHex_vs_uint256)
{
auto runtime_uint{uint256::FromHex("4A5E1E4BAAB89F3A32518A88C31BC87F618f76673e2cc77ab2127b7afdeda33b").value()};
constexpr uint256 consteval_uint{ "4a5e1e4baab89f3a32518a88c31bc87f618F76673E2CC77AB2127B7AFDEDA33B"};
constexpr uint256 consteval_uint{ "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"};
BOOST_CHECK_EQUAL(consteval_uint, runtime_uint);
}

View file

@ -130,13 +130,12 @@ consteval base_blob<BITS>::base_blob(std::string_view hex_str)
// Non-lookup table version of HexDigit().
auto from_hex = [](const char c) -> int8_t {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 0xA;
if (c >= 'A' && c <= 'F') return c - 'A' + 0xA;
if (c >= 'a' && c <= 'f') return c - 'a' + 0xa;
assert(false); // Reached if ctor is called with an invalid hex digit.
throw "Only lowercase hex digits are allowed, for consistency";
};
assert(hex_str.length() == m_data.size() * 2); // 2 hex digits per byte.
if (hex_str.length() != m_data.size() * 2) throw "Hex string must fit exactly";
auto str_it = hex_str.rbegin();
for (auto& elem : m_data) {
auto lo = from_hex(*(str_it++));