Coverage Report

Created: 2026-05-16 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/bitcoin-core/src/uint256.h
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#ifndef BITCOIN_UINT256_H
7
#define BITCOIN_UINT256_H
8
9
#include <crypto/common.h>
10
#include <crypto/hex_base.h>
11
#include <span.h>
12
#include <util/strencodings.h>
13
#include <util/string.h>
14
15
#include <algorithm>
16
#include <array>
17
#include <cassert>
18
#include <cstdint>
19
#include <cstring>
20
#include <optional>
21
#include <string>
22
#include <string_view>
23
24
/** Template base class for fixed-sized opaque blobs. */
25
template<unsigned int BITS>
26
class base_blob
27
{
28
protected:
29
    static constexpr int WIDTH = BITS / 8;
30
    static_assert(BITS % 8 == 0, "base_blob currently only supports whole bytes.");
31
    std::array<uint8_t, WIDTH> m_data;
32
    static_assert(WIDTH == sizeof(m_data), "Sanity check");
33
34
public:
35
    /* construct 0 value by default */
36
8.49G
    constexpr base_blob() : m_data() {}
base_blob<160u>::base_blob()
Line
Count
Source
36
60.3M
    constexpr base_blob() : m_data() {}
base_blob<256u>::base_blob()
Line
Count
Source
36
8.43G
    constexpr base_blob() : m_data() {}
37
38
    /* constructor for constants between 1 and 255 */
39
95.3k
    constexpr explicit base_blob(uint8_t v) : m_data{v} {}
40
41
    constexpr explicit base_blob(std::span<const unsigned char> vch)
42
9.10M
    {
43
9.10M
        assert(vch.size() == WIDTH);
44
9.10M
        std::copy(vch.begin(), vch.end(), m_data.begin());
45
9.10M
    }
base_blob<160u>::base_blob(std::__1::span<unsigned char const, 18446744073709551615ul>)
Line
Count
Source
42
896k
    {
43
896k
        assert(vch.size() == WIDTH);
44
896k
        std::copy(vch.begin(), vch.end(), m_data.begin());
45
896k
    }
base_blob<256u>::base_blob(std::__1::span<unsigned char const, 18446744073709551615ul>)
Line
Count
Source
42
8.20M
    {
43
8.20M
        assert(vch.size() == WIDTH);
44
8.20M
        std::copy(vch.begin(), vch.end(), m_data.begin());
45
8.20M
    }
46
47
    consteval explicit base_blob(std::string_view hex_str);
48
49
    constexpr bool IsNull() const
50
72.2M
    {
51
810M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
52
810M
            return val == 0;
53
810M
        });
base_blob<160u>::IsNull() const::{lambda(unsigned char)#1}::operator()(unsigned char) const
Line
Count
Source
51
431k
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
52
431k
            return val == 0;
53
431k
        });
base_blob<256u>::IsNull() const::{lambda(unsigned char)#1}::operator()(unsigned char) const
Line
Count
Source
51
810M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
52
810M
            return val == 0;
53
810M
        });
54
72.2M
    }
base_blob<160u>::IsNull() const
Line
Count
Source
50
31.5k
    {
51
31.5k
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
52
31.5k
            return val == 0;
53
31.5k
        });
54
31.5k
    }
base_blob<256u>::IsNull() const
Line
Count
Source
50
72.1M
    {
51
72.1M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
52
72.1M
            return val == 0;
53
72.1M
        });
54
72.1M
    }
55
56
    constexpr void SetNull()
57
19.5M
    {
58
19.5M
        std::fill(m_data.begin(), m_data.end(), 0);
59
19.5M
    }
base_blob<160u>::SetNull()
Line
Count
Source
57
247k
    {
58
247k
        std::fill(m_data.begin(), m_data.end(), 0);
59
247k
    }
base_blob<256u>::SetNull()
Line
Count
Source
57
19.2M
    {
58
19.2M
        std::fill(m_data.begin(), m_data.end(), 0);
59
19.2M
    }
60
61
    /** Lexicographic ordering
62
     * @note Does NOT match the ordering on the corresponding \ref
63
     *       base_uint::CompareTo, which starts comparing from the end.
64
     */
65
7.77G
    constexpr int Compare(const base_blob& other) const { return std::memcmp(m_data.data(), other.m_data.data(), WIDTH); }
base_blob<160u>::Compare(base_blob<160u> const&) const
Line
Count
Source
65
251M
    constexpr int Compare(const base_blob& other) const { return std::memcmp(m_data.data(), other.m_data.data(), WIDTH); }
base_blob<256u>::Compare(base_blob<256u> const&) const
Line
Count
Source
65
7.52G
    constexpr int Compare(const base_blob& other) const { return std::memcmp(m_data.data(), other.m_data.data(), WIDTH); }
66
67
83.3M
    friend constexpr bool operator==(const base_blob& a, const base_blob& b) { return a.Compare(b) == 0; }
operator==(base_blob<160u> const&, base_blob<160u> const&)
Line
Count
Source
67
156k
    friend constexpr bool operator==(const base_blob& a, const base_blob& b) { return a.Compare(b) == 0; }
operator==(base_blob<256u> const&, base_blob<256u> const&)
Line
Count
Source
67
83.1M
    friend constexpr bool operator==(const base_blob& a, const base_blob& b) { return a.Compare(b) == 0; }
68
766M
    friend constexpr bool operator<(const base_blob& a, const base_blob& b) { return a.Compare(b) < 0; }
operator<(base_blob<160u> const&, base_blob<160u> const&)
Line
Count
Source
68
250M
    friend constexpr bool operator<(const base_blob& a, const base_blob& b) { return a.Compare(b) < 0; }
operator<(base_blob<256u> const&, base_blob<256u> const&)
Line
Count
Source
68
515M
    friend constexpr bool operator<(const base_blob& a, const base_blob& b) { return a.Compare(b) < 0; }
69
70
    /** @name Hex representation
71
     *
72
     * The hex representation used by GetHex(), ToString(), and FromHex()
73
     * is unusual, since it shows bytes of the base_blob in reverse order.
74
     * For example, a 4-byte blob {0x12, 0x34, 0x56, 0x78} is represented
75
     * as "78563412" instead of the more typical "12345678" representation
76
     * that would be shown in a hex editor or used by typical
77
     * byte-array / hex conversion functions like python's bytes.hex() and
78
     * bytes.fromhex().
79
     *
80
     * The nice thing about the reverse-byte representation, even though it is
81
     * unusual, is that if a blob contains an arithmetic number in little endian
82
     * format (with least significant bytes first, and most significant bytes
83
     * last), the GetHex() output will match the way the number would normally
84
     * be written in base-16 (with most significant digits first and least
85
     * significant digits last).
86
     *
87
     * This means, for example, that ArithToUint256(num).GetHex() can be used to
88
     * display an arith_uint256 num value as a number, because
89
     * ArithToUint256() converts the number to a blob in little-endian format,
90
     * so the arith_uint256 class doesn't need to have its own number parsing
91
     * and formatting functions.
92
     *
93
     * @{*/
94
    std::string GetHex() const;
95
    std::string ToString() const;
96
    /**@}*/
97
98
131M
    constexpr const unsigned char* data() const { return m_data.data(); }
base_blob<160u>::data() const
Line
Count
Source
98
41.7k
    constexpr const unsigned char* data() const { return m_data.data(); }
base_blob<256u>::data() const
Line
Count
Source
98
130M
    constexpr const unsigned char* data() const { return m_data.data(); }
99
141M
    constexpr unsigned char* data() { return m_data.data(); }
base_blob<256u>::data()
Line
Count
Source
99
91.1M
    constexpr unsigned char* data() { return m_data.data(); }
base_blob<160u>::data()
Line
Count
Source
99
50.5M
    constexpr unsigned char* data() { return m_data.data(); }
100
101
785M
    constexpr unsigned char* begin() { return m_data.data(); }
base_blob<160u>::begin()
Line
Count
Source
101
27.8M
    constexpr unsigned char* begin() { return m_data.data(); }
base_blob<256u>::begin()
Line
Count
Source
101
757M
    constexpr unsigned char* begin() { return m_data.data(); }
102
23.6k
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
base_blob<160u>::end()
Line
Count
Source
102
12.0k
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
base_blob<256u>::end()
Line
Count
Source
102
11.5k
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
103
104
89.6M
    constexpr const unsigned char* begin() const { return m_data.data(); }
base_blob<160u>::begin() const
Line
Count
Source
104
1.27M
    constexpr const unsigned char* begin() const { return m_data.data(); }
base_blob<256u>::begin() const
Line
Count
Source
104
88.3M
    constexpr const unsigned char* begin() const { return m_data.data(); }
105
11.9M
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
base_blob<160u>::end() const
Line
Count
Source
105
1.27M
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
base_blob<256u>::end() const
Line
Count
Source
105
10.6M
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
106
107
254M
    static constexpr unsigned int size() { return WIDTH; }
base_blob<160u>::size()
Line
Count
Source
107
50.5M
    static constexpr unsigned int size() { return WIDTH; }
base_blob<256u>::size()
Line
Count
Source
107
203M
    static constexpr unsigned int size() { return WIDTH; }
108
109
2.32G
    constexpr uint64_t GetUint64(int pos) const { return ReadLE64(m_data.data() + pos * 8); }
110
111
    template<typename Stream>
112
    void Serialize(Stream& s) const
113
13.8G
    {
114
13.8G
        s << std::span(m_data);
115
13.8G
    }
void base_blob<256u>::Serialize<ParamsStream<ParamsStream<VectorWriter&, TransactionSerParams>&, TransactionSerParams> >(ParamsStream<ParamsStream<VectorWriter&, TransactionSerParams>&, TransactionSerParams>&) const
Line
Count
Source
113
4.28k
    {
114
4.28k
        s << std::span(m_data);
115
4.28k
    }
void base_blob<160u>::Serialize<DataStream>(DataStream&) const
Line
Count
Source
113
1.94k
    {
114
1.94k
        s << std::span(m_data);
115
1.94k
    }
Unexecuted instantiation: void base_blob<256u>::Serialize<ParamsStream<HashedSourceWriter<AutoFile>&, CAddress::SerParams> >(ParamsStream<HashedSourceWriter<AutoFile>&, CAddress::SerParams>&) const
void base_blob<256u>::Serialize<ParamsStream<DataStream&, CAddress::SerParams> >(ParamsStream<DataStream&, CAddress::SerParams>&) const
Line
Count
Source
113
19.7k
    {
114
19.7k
        s << std::span(m_data);
115
19.7k
    }
void base_blob<256u>::Serialize<ParamsStream<VectorWriter&, TransactionSerParams> >(ParamsStream<VectorWriter&, TransactionSerParams>&) const
Line
Count
Source
113
1.51M
    {
114
1.51M
        s << std::span(m_data);
115
1.51M
    }
void base_blob<256u>::Serialize<BufferedWriter<AutoFile> >(BufferedWriter<AutoFile>&) const
Line
Count
Source
113
856k
    {
114
856k
        s << std::span(m_data);
115
856k
    }
void base_blob<256u>::Serialize<ParamsStream<BufferedWriter<AutoFile>&, TransactionSerParams> >(ParamsStream<BufferedWriter<AutoFile>&, TransactionSerParams>&) const
Line
Count
Source
113
2.64M
    {
114
2.64M
        s << std::span(m_data);
115
2.64M
    }
Unexecuted instantiation: void base_blob<256u>::Serialize<ParamsStream<AutoFile&, TransactionSerParams> >(ParamsStream<AutoFile&, TransactionSerParams>&) const
void base_blob<256u>::Serialize<ParamsStream<DataStream&, TransactionSerParams> >(ParamsStream<DataStream&, TransactionSerParams>&) const
Line
Count
Source
113
485k
    {
114
485k
        s << std::span(m_data);
115
485k
    }
void base_blob<256u>::Serialize<SizeComputer>(SizeComputer&) const
Line
Count
Source
113
46.4k
    {
114
46.4k
        s << std::span(m_data);
115
46.4k
    }
void base_blob<256u>::Serialize<VectorWriter>(VectorWriter&) const
Line
Count
Source
113
538k
    {
114
538k
        s << std::span(m_data);
115
538k
    }
void base_blob<256u>::Serialize<DataStream>(DataStream&) const
Line
Count
Source
113
26.7M
    {
114
26.7M
        s << std::span(m_data);
115
26.7M
    }
void base_blob<256u>::Serialize<AutoFile>(AutoFile&) const
Line
Count
Source
113
268k
    {
114
268k
        s << std::span(m_data);
115
268k
    }
void base_blob<256u>::Serialize<ParamsStream<SizeComputer&, TransactionSerParams> >(ParamsStream<SizeComputer&, TransactionSerParams>&) const
Line
Count
Source
113
13.5G
    {
114
13.5G
        s << std::span(m_data);
115
13.5G
    }
void base_blob<256u>::Serialize<ParamsStream<HashWriter&, TransactionSerParams> >(ParamsStream<HashWriter&, TransactionSerParams>&) const
Line
Count
Source
113
89.2M
    {
114
89.2M
        s << std::span(m_data);
115
89.2M
    }
void base_blob<256u>::Serialize<HashWriter>(HashWriter&) const
Line
Count
Source
113
199M
    {
114
199M
        s << std::span(m_data);
115
199M
    }
116
117
    template<typename Stream>
118
    void Unserialize(Stream& s)
119
22.8M
    {
120
22.8M
        s.read(MakeWritableByteSpan(m_data));
121
22.8M
    }
void base_blob<160u>::Unserialize<SpanReader>(SpanReader&)
Line
Count
Source
119
71
    {
120
71
        s.read(MakeWritableByteSpan(m_data));
121
71
    }
void base_blob<160u>::Unserialize<DataStream>(DataStream&)
Line
Count
Source
119
1.88k
    {
120
1.88k
        s.read(MakeWritableByteSpan(m_data));
121
1.88k
    }
Unexecuted instantiation: void base_blob<256u>::Unserialize<ParamsStream<AutoFile&, CAddress::SerParams> >(ParamsStream<AutoFile&, CAddress::SerParams>&)
Unexecuted instantiation: void base_blob<256u>::Unserialize<ParamsStream<HashVerifier<AutoFile>&, CAddress::SerParams> >(ParamsStream<HashVerifier<AutoFile>&, CAddress::SerParams>&)
void base_blob<256u>::Unserialize<ParamsStream<DataStream&, CAddress::SerParams> >(ParamsStream<DataStream&, CAddress::SerParams>&)
Line
Count
Source
119
10.2k
    {
120
10.2k
        s.read(MakeWritableByteSpan(m_data));
121
10.2k
    }
void base_blob<256u>::Unserialize<ParamsStream<HashVerifier<DataStream>&, CAddress::SerParams> >(ParamsStream<HashVerifier<DataStream>&, CAddress::SerParams>&)
Line
Count
Source
119
4.18k
    {
120
4.18k
        s.read(MakeWritableByteSpan(m_data));
121
4.18k
    }
void base_blob<256u>::Unserialize<ParamsStream<DataStream&, TransactionSerParams> >(ParamsStream<DataStream&, TransactionSerParams>&)
Line
Count
Source
119
225k
    {
120
225k
        s.read(MakeWritableByteSpan(m_data));
121
225k
    }
Unexecuted instantiation: void base_blob<256u>::Unserialize<BufferedReader<AutoFile> >(BufferedReader<AutoFile>&)
void base_blob<256u>::Unserialize<ParamsStream<AutoFile&, TransactionSerParams> >(ParamsStream<AutoFile&, TransactionSerParams>&)
Line
Count
Source
119
406k
    {
120
406k
        s.read(MakeWritableByteSpan(m_data));
121
406k
    }
void base_blob<256u>::Unserialize<DataStream>(DataStream&)
Line
Count
Source
119
2.38M
    {
120
2.38M
        s.read(MakeWritableByteSpan(m_data));
121
2.38M
    }
void base_blob<256u>::Unserialize<ParamsStream<SpanReader&, TransactionSerParams> >(ParamsStream<SpanReader&, TransactionSerParams>&)
Line
Count
Source
119
6.29M
    {
120
6.29M
        s.read(MakeWritableByteSpan(m_data));
121
6.29M
    }
void base_blob<256u>::Unserialize<SpanReader>(SpanReader&)
Line
Count
Source
119
12.4M
    {
120
12.4M
        s.read(MakeWritableByteSpan(m_data));
121
12.4M
    }
void base_blob<256u>::Unserialize<BufferedFile>(BufferedFile&)
Line
Count
Source
119
489k
    {
120
489k
        s.read(MakeWritableByteSpan(m_data));
121
489k
    }
void base_blob<256u>::Unserialize<ParamsStream<BufferedFile&, TransactionSerParams> >(ParamsStream<BufferedFile&, TransactionSerParams>&)
Line
Count
Source
119
224k
    {
120
224k
        s.read(MakeWritableByteSpan(m_data));
121
224k
    }
void base_blob<256u>::Unserialize<AutoFile>(AutoFile&)
Line
Count
Source
119
362k
    {
120
362k
        s.read(MakeWritableByteSpan(m_data));
121
362k
    }
122
};
123
124
template <unsigned int BITS>
125
consteval base_blob<BITS>::base_blob(std::string_view hex_str)
126
{
127
    if (hex_str.length() != m_data.size() * 2) throw "Hex string must fit exactly";
128
    auto str_it = hex_str.rbegin();
129
    for (auto& elem : m_data) {
130
        auto lo = util::ConstevalHexDigit(*(str_it++));
131
        elem = (util::ConstevalHexDigit(*(str_it++)) << 4) | lo;
132
    }
133
}
134
135
namespace detail {
136
/**
137
 * Writes the hex string (in reverse byte order) into a new uintN_t object
138
 * and only returns a value iff all of the checks pass:
139
 *   - Input length is uintN_t::size()*2
140
 *   - All characters are hex
141
 */
142
template <class uintN_t>
143
std::optional<uintN_t> FromHex(std::string_view str)
144
26.2k
{
145
26.2k
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
146
2.47k
    uintN_t rv;
147
2.47k
    unsigned char* p1 = rv.begin();
148
2.47k
    unsigned char* pend = rv.end();
149
2.47k
    size_t digits = str.size();
150
81.5k
    while (digits > 0 && p1 < pend) {
151
79.0k
        *p1 = ::HexDigit(str[--digits]);
152
79.0k
        if (digits > 0) {
153
79.0k
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
154
79.0k
            p1++;
155
79.0k
        }
156
79.0k
    }
157
2.47k
    return rv;
158
26.2k
}
std::__1::optional<uint256> detail::FromHex<uint256>(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
Line
Count
Source
144
26.2k
{
145
26.2k
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
146
2.47k
    uintN_t rv;
147
2.47k
    unsigned char* p1 = rv.begin();
148
2.47k
    unsigned char* pend = rv.end();
149
2.47k
    size_t digits = str.size();
150
81.5k
    while (digits > 0 && p1 < pend) {
151
79.0k
        *p1 = ::HexDigit(str[--digits]);
152
79.0k
        if (digits > 0) {
153
79.0k
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
154
79.0k
            p1++;
155
79.0k
        }
156
79.0k
    }
157
2.47k
    return rv;
158
26.2k
}
Unexecuted instantiation: std::__1::optional<uint160> detail::FromHex<uint160>(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
159
/**
160
 * @brief Like FromHex(std::string_view str), but allows an "0x" prefix
161
 *        and pads the input with leading zeroes if it is shorter than
162
 *        the expected length of uintN_t::size()*2.
163
 *
164
 *        Designed to be used when dealing with user input.
165
 */
166
template <class uintN_t>
167
std::optional<uintN_t> FromUserHex(std::string_view input)
168
2.00k
{
169
2.00k
    input = util::RemovePrefixView(input, "0x");
170
2.00k
    constexpr auto expected_size{uintN_t::size() * 2};
171
2.00k
    if (input.size() < expected_size) {
172
184
        auto padded = std::string(expected_size, '0');
173
184
        std::copy(input.begin(), input.end(), padded.begin() + expected_size - input.size());
174
184
        return FromHex<uintN_t>(padded);
175
184
    }
176
1.82k
    return FromHex<uintN_t>(input);
177
2.00k
}
178
} // namespace detail
179
180
/** 160-bit opaque blob.
181
 * @note This type is called uint160 for historical reasons only. It is an opaque
182
 * blob of 160 bits and has no integer operations.
183
 */
184
class uint160 : public base_blob<160> {
185
public:
186
0
    static std::optional<uint160> FromHex(std::string_view str) { return detail::FromHex<uint160>(str); }
187
60.3M
    constexpr uint160() = default;
188
896k
    constexpr explicit uint160(std::span<const unsigned char> vch) : base_blob<160>(vch) {}
189
};
190
191
/** 256-bit opaque blob.
192
 * @note This type is called uint256 for historical reasons only. It is an
193
 * opaque blob of 256 bits and has no integer operations. Use arith_uint256 if
194
 * those are required.
195
 */
196
class uint256 : public base_blob<256> {
197
public:
198
24.2k
    static std::optional<uint256> FromHex(std::string_view str) { return detail::FromHex<uint256>(str); }
199
2.00k
    static std::optional<uint256> FromUserHex(std::string_view str) { return detail::FromUserHex<uint256>(str); }
200
8.43G
    constexpr uint256() = default;
201
0
    consteval explicit uint256(std::string_view hex_str) : base_blob<256>(hex_str) {}
202
95.3k
    constexpr explicit uint256(uint8_t v) : base_blob<256>(v) {}
203
8.20M
    constexpr explicit uint256(std::span<const unsigned char> vch) : base_blob<256>(vch) {}
204
    static const uint256 ZERO;
205
    static const uint256 ONE;
206
};
207
208
#endif // BITCOIN_UINT256_H