Skip to content

Commit

Permalink
refactor: Enforce lowercase hex digits for consteval uint256
Browse files Browse the repository at this point in the history
Also changes compile-time asserts with comments into throws.
  • Loading branch information
hodlinator committed Aug 28, 2024
1 parent 4ee1940 commit 7e1d9a8
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/test/pow_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion src/test/uint256_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
7 changes: 3 additions & 4 deletions src/uint256.h
Original file line number Diff line number Diff line change
Expand Up @@ -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++));
Expand Down

0 comments on commit 7e1d9a8

Please sign in to comment.