Coverage Report

Created: 2026-08-14 20:23

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.38G
    constexpr base_blob() : m_data() {}
base_blob<256u>::base_blob()
Line
Count
Source
37
1.38G
    constexpr base_blob() : m_data() {}
base_blob<160u>::base_blob()
Line
Count
Source
37
7.60M
    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.07M
    {
44
2.07M
        assert(vch.size() == WIDTH);
45
2.07M
        std::copy(vch.begin(), vch.end(), m_data.begin());
46
2.07M
    }
base_blob<160u>::base_blob(std::span<unsigned char const, 18446744073709551615ul>)
Line
Count
Source
43
376k
    {
44
376k
        assert(vch.size() == WIDTH);
45
376k
        std::copy(vch.begin(), vch.end(), m_data.begin());
46
376k
    }
47
48
    consteval explicit base_blob(std::string_view hex_str);
49
50
    constexpr bool IsNull() const
51
32.0M
    {
52
138M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
138M
            return val == 0;
54
138M
        });
base_blob<256u>::IsNull() const::'lambda'(unsigned char)::operator()(unsigned char) const
Line
Count
Source
52
138M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
138M
            return val == 0;
54
138M
        });
base_blob<160u>::IsNull() const::'lambda'(unsigned char)::operator()(unsigned char) const
Line
Count
Source
52
3.39k
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
3.39k
            return val == 0;
54
3.39k
        });
55
32.0M
    }
base_blob<256u>::IsNull() const
Line
Count
Source
51
32.0M
    {
52
32.0M
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
32.0M
            return val == 0;
54
32.0M
        });
55
32.0M
    }
base_blob<160u>::IsNull() const
Line
Count
Source
51
713
    {
52
713
        return std::all_of(m_data.begin(), m_data.end(), [](uint8_t val) {
53
713
            return val == 0;
54
713
        });
55
713
    }
56
57
    constexpr void SetNull()
58
6.34M
    {
59
6.34M
        std::fill(m_data.begin(), m_data.end(), 0);
60
6.34M
    }
base_blob<256u>::SetNull()
Line
Count
Source
58
6.34M
    {
59
6.34M
        std::fill(m_data.begin(), m_data.end(), 0);
60
6.34M
    }
base_blob<160u>::SetNull()
Line
Count
Source
58
1.88k
    {
59
1.88k
        std::fill(m_data.begin(), m_data.end(), 0);
60
1.88k
    }
61
62
198M
    constexpr bool operator==(const base_blob&) const = default;
base_blob<256u>::operator==(base_blob<256u> const&) const
Line
Count
Source
62
198M
    constexpr bool operator==(const base_blob&) const = default;
base_blob<160u>::operator==(base_blob<160u> const&) const
Line
Count
Source
62
9.26k
    constexpr bool operator==(const base_blob&) const = default;
63
64
    /** Lexicographic ordering
65
     * @note Does NOT match the ordering on the corresponding \ref
66
     *       base_uint::CompareTo, which starts comparing from the end.
67
     */
68
1.28G
    constexpr std::strong_ordering operator<=>(const base_blob& other) const = default;
base_blob<256u>::operator<=>(base_blob<256u> const&) const
Line
Count
Source
68
1.26G
    constexpr std::strong_ordering operator<=>(const base_blob& other) const = default;
base_blob<160u>::operator<=>(base_blob<160u> const&) const
Line
Count
Source
68
18.1M
    constexpr std::strong_ordering operator<=>(const base_blob& other) const = default;
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
9.80M
    constexpr const unsigned char* data() const { return m_data.data(); }
base_blob<160u>::data() const
Line
Count
Source
98
1.86k
    constexpr const unsigned char* data() const { return m_data.data(); }
base_blob<256u>::data() const
Line
Count
Source
98
9.80M
    constexpr const unsigned char* data() const { return m_data.data(); }
99
31.1M
    constexpr unsigned char* data() { return m_data.data(); }
base_blob<160u>::data()
Line
Count
Source
99
6.09M
    constexpr unsigned char* data() { return m_data.data(); }
base_blob<256u>::data()
Line
Count
Source
99
25.0M
    constexpr unsigned char* data() { return m_data.data(); }
100
101
114M
    constexpr unsigned char* begin() { return m_data.data(); }
base_blob<160u>::begin()
Line
Count
Source
101
69.4k
    constexpr unsigned char* begin() { return m_data.data(); }
base_blob<256u>::begin()
Line
Count
Source
101
114M
    constexpr unsigned char* begin() { return m_data.data(); }
102
43.8k
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
base_blob<160u>::end()
Line
Count
Source
102
608
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
base_blob<256u>::end()
Line
Count
Source
102
43.2k
    constexpr unsigned char* end() { return m_data.data() + WIDTH; }
103
104
301M
    constexpr const unsigned char* begin() const { return m_data.data(); }
base_blob<160u>::begin() const
Line
Count
Source
104
3.36M
    constexpr const unsigned char* begin() const { return m_data.data(); }
base_blob<256u>::begin() const
Line
Count
Source
104
298M
    constexpr const unsigned char* begin() const { return m_data.data(); }
105
2.56M
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
base_blob<160u>::end() const
Line
Count
Source
105
809k
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
base_blob<256u>::end() const
Line
Count
Source
105
1.75M
    constexpr const unsigned char* end() const { return m_data.data() + WIDTH; }
106
107
41.6M
    static constexpr unsigned int size() { return WIDTH; }
base_blob<160u>::size()
Line
Count
Source
107
6.11M
    static constexpr unsigned int size() { return WIDTH; }
base_blob<256u>::size()
Line
Count
Source
107
35.5M
    static constexpr unsigned int size() { return WIDTH; }
108
109
1.43G
    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
105M
    {
114
105M
        s << std::span(m_data);
115
105M
    }
void base_blob<256u>::Serialize<ParamsStream<SizeComputer&, TransactionSerParams>>(ParamsStream<SizeComputer&, TransactionSerParams>&) const
Line
Count
Source
113
4.45M
    {
114
4.45M
        s << std::span(m_data);
115
4.45M
    }
void base_blob<256u>::Serialize<DataStream>(DataStream&) const
Line
Count
Source
113
8.32M
    {
114
8.32M
        s << std::span(m_data);
115
8.32M
    }
void base_blob<256u>::Serialize<ParamsStream<DataStream&, TransactionSerParams>>(ParamsStream<DataStream&, TransactionSerParams>&) const
Line
Count
Source
113
130k
    {
114
130k
        s << std::span(m_data);
115
130k
    }
void base_blob<256u>::Serialize<ParamsStream<HashWriter&, TransactionSerParams>>(ParamsStream<HashWriter&, TransactionSerParams>&) const
Line
Count
Source
113
1.93M
    {
114
1.93M
        s << std::span(m_data);
115
1.93M
    }
void base_blob<256u>::Serialize<HashWriter>(HashWriter&) const
Line
Count
Source
113
88.7M
    {
114
88.7M
        s << std::span(m_data);
115
88.7M
    }
void base_blob<256u>::Serialize<SizeComputer>(SizeComputer&) const
Line
Count
Source
113
90.7k
    {
114
90.7k
        s << std::span(m_data);
115
90.7k
    }
void base_blob<160u>::Serialize<SizeComputer>(SizeComputer&) const
Line
Count
Source
113
2
    {
114
2
        s << std::span(m_data);
115
2
    }
void base_blob<160u>::Serialize<DataStream>(DataStream&) const
Line
Count
Source
113
63
    {
114
63
        s << std::span(m_data);
115
63
    }
void base_blob<256u>::Serialize<VectorWriter>(VectorWriter&) const
Line
Count
Source
113
185k
    {
114
185k
        s << std::span(m_data);
115
185k
    }
void base_blob<256u>::Serialize<AutoFile>(AutoFile&) const
Line
Count
Source
113
16.9k
    {
114
16.9k
        s << std::span(m_data);
115
16.9k
    }
void base_blob<256u>::Serialize<ParamsStream<HashedSourceWriter<AutoFile>&, CAddress::SerParams>>(ParamsStream<HashedSourceWriter<AutoFile>&, CAddress::SerParams>&) const
Line
Count
Source
113
3.08k
    {
114
3.08k
        s << std::span(m_data);
115
3.08k
    }
void base_blob<256u>::Serialize<ParamsStream<DataStream&, CAddress::SerParams>>(ParamsStream<DataStream&, CAddress::SerParams>&) const
Line
Count
Source
113
14
    {
114
14
        s << std::span(m_data);
115
14
    }
void base_blob<256u>::Serialize<ParamsStream<VectorWriter&, TransactionSerParams>>(ParamsStream<VectorWriter&, TransactionSerParams>&) const
Line
Count
Source
113
994k
    {
114
994k
        s << std::span(m_data);
115
994k
    }
void base_blob<256u>::Serialize<BufferedWriter<AutoFile>>(BufferedWriter<AutoFile>&) const
Line
Count
Source
113
108k
    {
114
108k
        s << std::span(m_data);
115
108k
    }
void base_blob<256u>::Serialize<ParamsStream<BufferedWriter<AutoFile>&, TransactionSerParams>>(ParamsStream<BufferedWriter<AutoFile>&, TransactionSerParams>&) const
Line
Count
Source
113
413k
    {
114
413k
        s << std::span(m_data);
115
413k
    }
void base_blob<256u>::Serialize<ParamsStream<AutoFile&, TransactionSerParams>>(ParamsStream<AutoFile&, TransactionSerParams>&) const
Line
Count
Source
113
2.46k
    {
114
2.46k
        s << std::span(m_data);
115
2.46k
    }
116
117
    template<typename Stream>
118
    void Unserialize(Stream& s)
119
2.94M
    {
120
2.94M
        s.read(MakeWritableByteSpan(m_data));
121
2.94M
    }
void base_blob<256u>::Unserialize<DataStream>(DataStream&)
Line
Count
Source
119
1.60M
    {
120
1.60M
        s.read(MakeWritableByteSpan(m_data));
121
1.60M
    }
void base_blob<256u>::Unserialize<ParamsStream<DataStream&, TransactionSerParams>>(ParamsStream<DataStream&, TransactionSerParams>&)
Line
Count
Source
119
214k
    {
120
214k
        s.read(MakeWritableByteSpan(m_data));
121
214k
    }
void base_blob<256u>::Unserialize<SpanReader>(SpanReader&)
Line
Count
Source
119
442k
    {
120
442k
        s.read(MakeWritableByteSpan(m_data));
121
442k
    }
void base_blob<256u>::Unserialize<ParamsStream<SpanReader&, TransactionSerParams>>(ParamsStream<SpanReader&, TransactionSerParams>&)
Line
Count
Source
119
618k
    {
120
618k
        s.read(MakeWritableByteSpan(m_data));
121
618k
    }
void base_blob<160u>::Unserialize<DataStream>(DataStream&)
Line
Count
Source
119
511
    {
120
511
        s.read(MakeWritableByteSpan(m_data));
121
511
    }
void base_blob<256u>::Unserialize<AutoFile>(AutoFile&)
Line
Count
Source
119
8.96k
    {
120
8.96k
        s.read(MakeWritableByteSpan(m_data));
121
8.96k
    }
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
119
1.15k
    {
120
1.15k
        s.read(MakeWritableByteSpan(m_data));
121
1.15k
    }
void base_blob<256u>::Unserialize<ParamsStream<DataStream&, CAddress::SerParams>>(ParamsStream<DataStream&, CAddress::SerParams>&)
Line
Count
Source
119
13
    {
120
13
        s.read(MakeWritableByteSpan(m_data));
121
13
    }
void base_blob<256u>::Unserialize<ParamsStream<HashVerifier<DataStream>&, CAddress::SerParams>>(ParamsStream<HashVerifier<DataStream>&, CAddress::SerParams>&)
Line
Count
Source
119
3
    {
120
3
        s.read(MakeWritableByteSpan(m_data));
121
3
    }
void base_blob<256u>::Unserialize<ParamsStream<AutoFile&, TransactionSerParams>>(ParamsStream<AutoFile&, TransactionSerParams>&)
Line
Count
Source
119
477
    {
120
477
        s.read(MakeWritableByteSpan(m_data));
121
477
    }
void base_blob<256u>::Unserialize<BufferedReader<AutoFile>>(BufferedReader<AutoFile>&)
Line
Count
Source
119
37.8k
    {
120
37.8k
        s.read(MakeWritableByteSpan(m_data));
121
37.8k
    }
void base_blob<256u>::Unserialize<BufferedFile>(BufferedFile&)
Line
Count
Source
119
4.35k
    {
120
4.35k
        s.read(MakeWritableByteSpan(m_data));
121
4.35k
    }
void base_blob<256u>::Unserialize<ParamsStream<BufferedFile&, TransactionSerParams>>(ParamsStream<BufferedFile&, TransactionSerParams>&)
Line
Count
Source
119
6.29k
    {
120
6.29k
        s.read(MakeWritableByteSpan(m_data));
121
6.29k
    }
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
32.0k
{
145
32.0k
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
146
31.5k
    uintN_t rv;
147
31.5k
    unsigned char* p1 = rv.begin();
148
31.5k
    unsigned char* pend = rv.end();
149
31.5k
    size_t digits = str.size();
150
1.04M
    while (digits > 0 && p1 < pend) {
151
1.00M
        *p1 = ::HexDigit(str[--digits]);
152
1.00M
        if (digits > 0) {
153
1.00M
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
154
1.00M
            p1++;
155
1.00M
        }
156
1.00M
    }
157
31.5k
    return rv;
158
32.0k
}
std::optional<uint160> detail::FromHex<uint160>(std::basic_string_view<char, std::char_traits<char>>)
Line
Count
Source
144
93
{
145
93
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
146
11
    uintN_t rv;
147
11
    unsigned char* p1 = rv.begin();
148
11
    unsigned char* pend = rv.end();
149
11
    size_t digits = str.size();
150
231
    while (digits > 0 && p1 < pend) {
151
220
        *p1 = ::HexDigit(str[--digits]);
152
220
        if (digits > 0) {
153
220
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
154
220
            p1++;
155
220
        }
156
220
    }
157
11
    return rv;
158
93
}
std::optional<uint256> detail::FromHex<uint256>(std::basic_string_view<char, std::char_traits<char>>)
Line
Count
Source
144
31.9k
{
145
31.9k
    if (uintN_t::size() * 2 != str.size() || !IsHex(str)) return std::nullopt;
146
31.5k
    uintN_t rv;
147
31.5k
    unsigned char* p1 = rv.begin();
148
31.5k
    unsigned char* pend = rv.end();
149
31.5k
    size_t digits = str.size();
150
1.04M
    while (digits > 0 && p1 < pend) {
151
1.00M
        *p1 = ::HexDigit(str[--digits]);
152
1.00M
        if (digits > 0) {
153
1.00M
            *p1 |= ((unsigned char)::HexDigit(str[--digits]) << 4);
154
1.00M
            p1++;
155
1.00M
        }
156
1.00M
    }
157
31.5k
    return rv;
158
31.9k
}
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
64
{
169
64
    input = util::RemovePrefixView(input, "0x");
170
64
    constexpr auto expected_size{uintN_t::size() * 2};
171
64
    if (input.size() < expected_size) {
172
42
        auto padded = std::string(expected_size, '0');
173
42
        std::copy(input.begin(), input.end(), padded.begin() + expected_size - input.size());
174
42
        return FromHex<uintN_t>(padded);
175
42
    }
176
22
    return FromHex<uintN_t>(input);
177
64
}
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
93
    static std::optional<uint160> FromHex(std::string_view str) { return detail::FromHex<uint160>(str); }
187
7.60M
    constexpr uint160() = default;
188
376k
    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
31.8k
    static std::optional<uint256> FromHex(std::string_view str) { return detail::FromHex<uint256>(str); }
199
64
    static std::optional<uint256> FromUserHex(std::string_view str) { return detail::FromUserHex<uint256>(str); }
200
1.38G
    constexpr uint256() = default;
201
0
    consteval explicit uint256(std::string_view hex_str) : base_blob<256>(hex_str) {}
202
907
    constexpr explicit uint256(uint8_t v) : base_blob<256>(v) {}
203
2.07M
    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