Coverage Report

Created: 2026-08-05 14:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/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 <compare>
19
#include <cstdint>
20
#include <cstring>
21
#include <optional>
22
#include <string>
23
#include <string_view>
24
25
/** Template base class for fixed-sized opaque blobs. */
26
template<unsigned int BITS>
27
class base_blob
28
{
29
protected:
30
    static constexpr int WIDTH = BITS / 8;
31
    static_assert(BITS % 8 == 0, "base_blob currently only supports whole bytes.");
32
    std::array<uint8_t, WIDTH> m_data;
33
    static_assert(WIDTH == sizeof(m_data), "Sanity check");
34
35
public:
36
    /* construct 0 value by default */
37
1.37G
    constexpr base_blob() : m_data() {}
base_blob<256u>::base_blob()
Line
Count
Source
37
1.36G
    constexpr base_blob() : m_data() {}
base_blob<160u>::base_blob()
Line
Count
Source
37
7.62M
    constexpr base_blob() : m_data() {}
38
39
    /* constructor for constants between 1 and 255 */
40
907
    constexpr explicit base_blob(uint8_t v) : m_data{v} {}
41
42
    constexpr explicit base_blob(std::span<const unsigned char> vch)
43
2.45M
    {
44
2.45M
        assert(vch.size() == WIDTH);
45
2.45M
        std::copy(vch.begin(), vch.end(), m_data.begin());
46
2.45M
    }
base_blob<256u>::base_blob(std::span<unsigned char const, 18446744073709551615ul>)
Line
Count
Source
43
2.08M
    {
44
2.08M
        assert(vch.size() == WIDTH);
45
2.08M
        std::copy(vch.begin(), vch.end(), m_data.begin());
46
2.08M
    }
base_blob<160u>::base_blob(std::span<unsigned char const, 18446744073709551615ul>)
Line
Count
Source
43
373k
    {
44
373k
        assert(vch.size() == WIDTH);
45
373k
        std::copy(vch.begin(), vch.end(), m_data.begin());
46
373k
    }
47
48
    consteval explicit base_blob(std::string_view hex_str);
49
50
    constexpr bool IsNull() const
51
30.8M
    {
52
136M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
136M
            return val == 0;
54
136M
        });
base_blob<256u>::IsNull() const::'lambda'(unsigned char)::operator()(unsigned char) const
Line
Count
Source
52
136M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
136M
            return val == 0;
54
136M
        });
base_blob<160u>::IsNull() const::'lambda'(unsigned char)::operator()(unsigned char) const
Line
Count
Source
52
1.28k
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
1.28k
            return val == 0;
54
1.28k
        });
55
30.8M
    }
base_blob<256u>::IsNull() const
Line
Count
Source
51
30.8M
    {
52
30.8M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
30.8M
            return val == 0;
54
30.8M
        });
55
30.8M
    }
base_blob<160u>::IsNull() const
Line
Count
Source
51
500
    {
52
500
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
500
            return val == 0;
54
500
        });
55
500
    }
56
57
    constexpr void SetNull()
58
5.80M
    {
59
5.80M
        std::fill(m_data.begin(), m_data.end(), 0);
60
5.80M
    }
base_blob<256u>::SetNull()
Line
Count
Source
58
5.79M
    {
59
5.79M
        std::fill(m_data.begin(), m_data.end(), 0);
60
5.79M
    }
base_blob<160u>::SetNull()
Line
Count
Source
58
1.53k
    {
59
1.53k
        std::fill(m_data.begin(), m_data.end(), 0);
60
1.53k
    }
61
62
    /** Lexicographic ordering
63
     * @note Does NOT match the ordering on the corresponding \ref
64
     *       base_uint::CompareTo, which starts comparing from the end.
65
     */
66
847M
    constexpr int Compare(const base_blob& other) const {
67
847M
        auto cmp = m_data <=> other.m_data;
68
847M
        if (cmp < 0) return -1;
69
517M
        if (cmp > 0) return 1;
70
182M
        return 0;
71
517M
    }
base_blob<256u>::Compare(base_blob<256u> const&) const
Line
Count
Source
66
835M
    constexpr int Compare(const base_blob& other) const {
67
835M
        auto cmp = m_data <=> other.m_data;
68
835M
        if (cmp < 0) return -1;
69
508M
        if (cmp > 0) return 1;
70
176M
        return 0;
71
508M
    }
base_blob<160u>::Compare(base_blob<160u> const&) const
Line
Count
Source
66
12.0M
    constexpr int Compare(const base_blob& other) const {
67
12.0M
        auto cmp = m_data <=> other.m_data;
68
12.0M
        if (cmp < 0) return -1;
69
8.77M
        if (cmp > 0) return 1;
70
6.26M
        return 0;
71
8.77M
    }
72
73
29.1M
    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
73
29.1M
    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
73
8.75k
    friend constexpr bool operator==(const base_blob& a, const base_blob& b) { return a.Compare(b) == 0; }
74
54.8M
    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
74
42.7M
    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
74
12.0M
    friend constexpr bool operator<(const base_blob& a, const base_blob& b) { return a.Compare(b) < 0; }
75
76
    /** @name Hex representation
77
     *
78
     * The hex representation used by GetHex(), ToString(), and FromHex()
79
     * is unusual, since it shows bytes of the base_blob in reverse order.
80
     * For example, a 4-byte blob {0x12, 0x34, 0x56, 0x78} is represented
81
     * as "78563412" instead of the more typical "12345678" representation
82
     * that would be shown in a hex editor or used by typical
83
     * byte-array / hex conversion functions like python's bytes.hex() and
84
     * bytes.fromhex().
85
     *
86
     * The nice thing about the reverse-byte representation, even though it is
87
     * unusual, is that if a blob contains an arithmetic number in little endian
88
     * format (with least significant bytes first, and most significant bytes
89
     * last), the GetHex() output will match the way the number would normally
90
     * be written in base-16 (with most significant digits first and least
91
     * significant digits last).
92
     *
93
     * This means, for example, that ArithToUint256(num).GetHex() can be used to
94
     * display an arith_uint256 num value as a number, because
95
     * ArithToUint256() converts the number to a blob in little-endian format,
96
     * so the arith_uint256 class doesn't need to have its own number parsing
97
     * and formatting functions.
98
     *
99
     * @{*/
100
    std::string GetHex() const;
101
    std::string ToString() const;
102
    /**@}*/
103
104
8.25M
    constexpr const unsigned char* data() const { return m_data.data(); }
base_blob<160u>::data() const
Line
Count
Source
104
1.75k
    constexpr const unsigned char* data() const { return m_data.data(); }
base_blob<256u>::data() const
Line
Count
Source
104
8.25M
    constexpr const unsigned char* data() const { return m_data.data(); }
105
30.6M
    constexpr unsigned char* data() { return m_data.data(); }
base_blob<160u>::data()
Line
Count
Source
105
6.11M
    constexpr unsigned char* data() { return m_data.data(); }
base_blob<256u>::data()
Line
Count
Source
105
24.5M
    constexpr unsigned char* data() { return m_data.data(); }
106
107
98.2M
    constexpr unsigned char* begin() { return m_data.data(); }
base_blob<160u>::begin()
Line
Count
Source
107
68.8k
    constexpr unsigned char* begin() { return m_data.data(); }
base_blob<256u>::begin()
Line
Count
Source
107
98.2M
    constexpr unsigned char* begin() { return m_data.data(); }
108
44.2k
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
base_blob<160u>::end()
Line
Count
Source
108
608
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
base_blob<256u>::end()
Line
Count
Source
108
43.6k
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
109
110
254M
    constexpr const unsigned char* begin() const { return m_data.data(); }
base_blob<160u>::begin() const
Line
Count
Source
110
3.36M
    constexpr const unsigned char* begin() const { return m_data.data(); }
base_blob<256u>::begin() const
Line
Count
Source
110
251M
    constexpr const unsigned char* begin() const { return m_data.data(); }
111
2.58M
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
base_blob<160u>::end() const
Line
Count
Source
111
805k
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
base_blob<256u>::end() const
Line
Count
Source
111
1.78M
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
112
113
39.5M
    static constexpr unsigned int size() { return WIDTH; }
base_blob<160u>::size()
Line
Count
Source
113
6.14M
    static constexpr unsigned int size() { return WIDTH; }
base_blob<256u>::size()
Line
Count
Source
113
33.3M
    static constexpr unsigned int size() { return WIDTH; }
114
115
1.30G
    constexpr uint64_t GetUint64(int pos) const { return ReadLE64(m_data.data() + pos * 8); }
116
117
    template<typename Stream>
118
    void Serialize(Stream& s) const
119
92.8M
    {
120
92.8M
        s << std::span(m_data);
121
92.8M
    }
void base_blob<256u>::Serialize<ParamsStream<SizeComputer&, TransactionSerParams>>(ParamsStream<SizeComputer&, TransactionSerParams>&) const
Line
Count
Source
119
4.41M
    {
120
4.41M
        s << std::span(m_data);
121
4.41M
    }
void base_blob<256u>::Serialize<DataStream>(DataStream&) const
Line
Count
Source
119
6.84M
    {
120
6.84M
        s << std::span(m_data);
121
6.84M
    }
void base_blob<256u>::Serialize<ParamsStream<DataStream&, TransactionSerParams>>(ParamsStream<DataStream&, TransactionSerParams>&) const
Line
Count
Source
119
131k
    {
120
131k
        s << std::span(m_data);
121
131k
    }
void base_blob<256u>::Serialize<ParamsStream<HashWriter&, TransactionSerParams>>(ParamsStream<HashWriter&, TransactionSerParams>&) const
Line
Count
Source
119
1.93M
    {
120
1.93M
        s << std::span(m_data);
121
1.93M
    }
void base_blob<256u>::Serialize<HashWriter>(HashWriter&) const
Line
Count
Source
119
77.8M
    {
120
77.8M
        s << std::span(m_data);
121
77.8M
    }
void base_blob<256u>::Serialize<SizeComputer>(SizeComputer&) const
Line
Count
Source
119
81.7k
    {
120
81.7k
        s << std::span(m_data);
121
81.7k
    }
void base_blob<160u>::Serialize<SizeComputer>(SizeComputer&) const
Line
Count
Source
119
2
    {
120
2
        s << std::span(m_data);
121
2
    }
void base_blob<160u>::Serialize<DataStream>(DataStream&) const
Line
Count
Source
119
3
    {
120
3
        s << std::span(m_data);
121
3
    }
void base_blob<256u>::Serialize<VectorWriter>(VectorWriter&) const
Line
Count
Source
119
179k
    {
120
179k
        s << std::span(m_data);
121
179k
    }
void base_blob<256u>::Serialize<AutoFile>(AutoFile&) const
Line
Count
Source
119
16.4k
    {
120
16.4k
        s << std::span(m_data);
121
16.4k
    }
void base_blob<256u>::Serialize<ParamsStream<HashedSourceWriter<AutoFile>&, CAddress::SerParams>>(ParamsStream<HashedSourceWriter<AutoFile>&, CAddress::SerParams>&) const
Line
Count
Source
119
3.06k
    {
120
3.06k
        s << std::span(m_data);
121
3.06k
    }
void base_blob<256u>::Serialize<ParamsStream<DataStream&, CAddress::SerParams>>(ParamsStream<DataStream&, CAddress::SerParams>&) const
Line
Count
Source
119
14
    {
120
14
        s << std::span(m_data);
121
14
    }
void base_blob<256u>::Serialize<ParamsStream<VectorWriter&, TransactionSerParams>>(ParamsStream<VectorWriter&, TransactionSerParams>&) const
Line
Count
Source
119
869k
    {
120
869k
        s << std::span(m_data);
121
869k
    }
void base_blob<256u>::Serialize<BufferedWriter<AutoFile>>(BufferedWriter<AutoFile>&) const
Line
Count
Source
119
106k
    {
120
106k
        s << std::span(m_data);
121
106k
    }
void base_blob<256u>::Serialize<ParamsStream<BufferedWriter<AutoFile>&, TransactionSerParams>>(ParamsStream<BufferedWriter<AutoFile>&, TransactionSerParams>&) const
Line
Count
Source
119
408k
    {
120
408k
        s << std::span(m_data);
121
408k
    }
void base_blob<256u>::Serialize<ParamsStream<AutoFile&, TransactionSerParams>>(ParamsStream<AutoFile&, TransactionSerParams>&) const
Line
Count
Source
119
2.50k
    {
120
2.50k
        s << std::span(m_data);
121
2.50k
    }
122
123
    template<typename Stream>
124
    void Unserialize(Stream& s)
125
2.80M
    {
126
2.80M
        s.read(MakeWritableByteSpan(m_data));
127
2.80M
    }
void base_blob<256u>::Unserialize<DataStream>(DataStream&)
Line
Count
Source
125
1.47M
    {
126
1.47M
        s.read(MakeWritableByteSpan(m_data));
127
1.47M
    }
void base_blob<256u>::Unserialize<ParamsStream<DataStream&, TransactionSerParams>>(ParamsStream<DataStream&, TransactionSerParams>&)
Line
Count
Source
125
216k
    {
126
216k
        s.read(MakeWritableByteSpan(m_data));
127
216k
    }
void base_blob<256u>::Unserialize<SpanReader>(SpanReader&)
Line
Count
Source
125
446k
    {
126
446k
        s.read(MakeWritableByteSpan(m_data));
127
446k
    }
void base_blob<256u>::Unserialize<ParamsStream<SpanReader&, TransactionSerParams>>(ParamsStream<SpanReader&, TransactionSerParams>&)
Line
Count
Source
125
610k
    {
126
610k
        s.read(MakeWritableByteSpan(m_data));
127
610k
    }
void base_blob<160u>::Unserialize<DataStream>(DataStream&)
Line
Count
Source
125
402
    {
126
402
        s.read(MakeWritableByteSpan(m_data));
127
402
    }
void base_blob<256u>::Unserialize<AutoFile>(AutoFile&)
Line
Count
Source
125
8.95k
    {
126
8.95k
        s.read(MakeWritableByteSpan(m_data));
127
8.95k
    }
Unexecuted instantiation: void base_blob<256u>::Unserialize<ParamsStream<AutoFile&, CAddress::SerParams>>(ParamsStream<AutoFile&, CAddress::SerParams>&)
void base_blob<256u>::Unserialize<ParamsStream<HashVerifier<AutoFile>&, CAddress::SerParams>>(ParamsStream<HashVerifier<AutoFile>&, CAddress::SerParams>&)
Line
Count
Source
125
1.15k
    {
126
1.15k
        s.read(MakeWritableByteSpan(m_data));
127
1.15k
    }
void base_blob<256u>::Unserialize<ParamsStream<DataStream&, CAddress::SerParams>>(ParamsStream<DataStream&, CAddress::SerParams>&)
Line
Count
Source
125
13
    {
126
13
        s.read(MakeWritableByteSpan(m_data));
127
13
    }
void base_blob<256u>::Unserialize<ParamsStream<HashVerifier<DataStream>&, CAddress::SerParams>>(ParamsStream<HashVerifier<DataStream>&, CAddress::SerParams>&)
Line
Count
Source
125
3
    {
126
3
        s.read(MakeWritableByteSpan(m_data));
127
3
    }
void base_blob<256u>::Unserialize<ParamsStream<AutoFile&, TransactionSerParams>>(ParamsStream<AutoFile&, TransactionSerParams>&)
Line
Count
Source
125
474
    {
126
474
        s.read(MakeWritableByteSpan(m_data));
127
474
    }
void base_blob<256u>::Unserialize<BufferedReader<AutoFile>>(BufferedReader<AutoFile>&)
Line
Count
Source
125
36.4k
    {
126
36.4k
        s.read(MakeWritableByteSpan(m_data));
127
36.4k
    }
void base_blob<256u>::Unserialize<BufferedFile>(BufferedFile&)
Line
Count
Source
125
4.35k
    {
126
4.35k
        s.read(MakeWritableByteSpan(m_data));
127
4.35k
    }
void base_blob<256u>::Unserialize<ParamsStream<BufferedFile&, TransactionSerParams>>(ParamsStream<BufferedFile&, TransactionSerParams>&)
Line
Count
Source
125
6.29k
    {
126
6.29k
        s.read(MakeWritableByteSpan(m_data));
127
6.29k
    }
128
};
129
130
template <unsigned int BITS>
131
consteval base_blob<BITS>::base_blob(std::string_view hex_str)
132
{
133
    if (hex_str.length() != m_data.size() * 2) throw "Hex string must fit exactly";
134
    auto str_it = hex_str.rbegin();
135
    for (auto& elem : m_data) {
136
        auto lo = util::ConstevalHexDigit(*(str_it++));
137
        elem = (util::ConstevalHexDigit(*(str_it++)) << 4) | lo;
138
    }
139
}
140
141
namespace detail {
142
/**
143
 * Writes the hex string (in reverse byte order) into a new uintN_t object
144
 * and only returns a value iff all of the checks pass:
145
 *   - Input length is uintN_t::size()*2
146
 *   - All characters are hex
147
 */
148
template <class uintN_t>
149
std::optional<uintN_t> FromHex(std::string_view str)
150
32.4k
{
151
32.4k
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
152
31.9k
    uintN_t rv;
153
31.9k
    unsigned char* p1 = rv.begin();
154
31.9k
    unsigned char* pend = rv.end();
155
31.9k
    size_t digits = str.size();
156
1.05M
    while (digits > 0 && p1 < pend) {
157
1.02M
        *p1 = ::HexDigit(str[--digits]);
158
1.02M
        if (digits > 0) {
159
1.02M
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
160
1.02M
            p1++;
161
1.02M
        }
162
1.02M
    }
163
31.9k
    return rv;
164
32.4k
}
std::optional<uint160> detail::FromHex<uint160>(std::basic_string_view<char, std::char_traits<char>>)
Line
Count
Source
150
93
{
151
93
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
152
11
    uintN_t rv;
153
11
    unsigned char* p1 = rv.begin();
154
11
    unsigned char* pend = rv.end();
155
11
    size_t digits = str.size();
156
231
    while (digits > 0 && p1 < pend) {
157
220
        *p1 = ::HexDigit(str[--digits]);
158
220
        if (digits > 0) {
159
220
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
160
220
            p1++;
161
220
        }
162
220
    }
163
11
    return rv;
164
93
}
std::optional<uint256> detail::FromHex<uint256>(std::basic_string_view<char, std::char_traits<char>>)
Line
Count
Source
150
32.3k
{
151
32.3k
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
152
31.9k
    uintN_t rv;
153
31.9k
    unsigned char* p1 = rv.begin();
154
31.9k
    unsigned char* pend = rv.end();
155
31.9k
    size_t digits = str.size();
156
1.05M
    while (digits > 0 && p1 < pend) {
157
1.02M
        *p1 = ::HexDigit(str[--digits]);
158
1.02M
        if (digits > 0) {
159
1.02M
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
160
1.02M
            p1++;
161
1.02M
        }
162
1.02M
    }
163
31.9k
    return rv;
164
32.3k
}
165
/**
166
 * @brief Like FromHex(std::string_view str), but allows an "0x" prefix
167
 *        and pads the input with leading zeroes if it is shorter than
168
 *        the expected length of uintN_t::size()*2.
169
 *
170
 *        Designed to be used when dealing with user input.
171
 */
172
template <class uintN_t>
173
std::optional<uintN_t> FromUserHex(std::string_view input)
174
64
{
175
64
    input = util::RemovePrefixView(input, "0x");
176
64
    constexpr auto expected_size{uintN_t::size() * 2};
177
64
    if (input.size() < expected_size) {
178
42
        auto padded = std::string(expected_size, '0');
179
42
        std::copy(input.begin(), input.end(), padded.begin() + expected_size - input.size());
180
42
        return FromHex<uintN_t>(padded);
181
42
    }
182
22
    return FromHex<uintN_t>(input);
183
64
}
184
} // namespace detail
185
186
/** 160-bit opaque blob.
187
 * @note This type is called uint160 for historical reasons only. It is an opaque
188
 * blob of 160 bits and has no integer operations.
189
 */
190
class uint160 : public base_blob<160> {
191
public:
192
93
    static std::optional<uint160> FromHex(std::string_view str) { return detail::FromHex<uint160>(str); }
193
7.62M
    constexpr uint160() = default;
194
373k
    constexpr explicit uint160(std::span<const unsigned char> vch) : base_blob<160>(vch) {}
195
};
196
197
/** 256-bit opaque blob.
198
 * @note This type is called uint256 for historical reasons only. It is an
199
 * opaque blob of 256 bits and has no integer operations. Use arith_uint256 if
200
 * those are required.
201
 */
202
class uint256 : public base_blob<256> {
203
public:
204
32.2k
    static std::optional<uint256> FromHex(std::string_view str) { return detail::FromHex<uint256>(str); }
205
64
    static std::optional<uint256> FromUserHex(std::string_view str) { return detail::FromUserHex<uint256>(str); }
206
1.36G
    constexpr uint256() = default;
207
0
    consteval explicit uint256(std::string_view hex_str) : base_blob<256>(hex_str) {}
208
907
    constexpr explicit uint256(uint8_t v) : base_blob<256>(v) {}
209
2.08M
    constexpr explicit uint256(std::span<const unsigned char> vch) : base_blob<256>(vch) {}
210
    static const uint256 ZERO;
211
    static const uint256 ONE;
212
};
213
214
#endif // BITCOIN_UINT256_H