Bitcoin Core  24.99.0
P2P Digital Currency
integer.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <arith_uint256.h>
6 #include <compressor.h>
7 #include <consensus/amount.h>
8 #include <consensus/merkle.h>
9 #include <core_io.h>
10 #include <crypto/common.h>
11 #include <crypto/siphash.h>
12 #include <key_io.h>
13 #include <memusage.h>
14 #include <netbase.h>
15 #include <policy/policy.h>
16 #include <policy/settings.h>
17 #include <pow.h>
18 #include <protocol.h>
19 #include <pubkey.h>
20 #include <script/standard.h>
21 #include <serialize.h>
22 #include <streams.h>
24 #include <test/fuzz/fuzz.h>
25 #include <test/fuzz/util.h>
26 #include <uint256.h>
27 #include <univalue.h>
28 #include <util/check.h>
29 #include <util/moneystr.h>
30 #include <util/overflow.h>
31 #include <util/strencodings.h>
32 #include <util/string.h>
33 #include <util/system.h>
34 #include <version.h>
35 
36 #include <cassert>
37 #include <chrono>
38 #include <limits>
39 #include <set>
40 #include <vector>
41 
43 {
45 }
46 
48 {
49  if (buffer.size() < sizeof(uint256) + sizeof(uint160)) {
50  return;
51  }
52  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
53  const uint256 u256(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint256)));
54  const uint160 u160(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint160)));
55  const uint64_t u64 = fuzzed_data_provider.ConsumeIntegral<uint64_t>();
56  const int64_t i64 = fuzzed_data_provider.ConsumeIntegral<int64_t>();
57  const uint32_t u32 = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
58  const int32_t i32 = fuzzed_data_provider.ConsumeIntegral<int32_t>();
59  const uint16_t u16 = fuzzed_data_provider.ConsumeIntegral<uint16_t>();
60  const int16_t i16 = fuzzed_data_provider.ConsumeIntegral<int16_t>();
61  const uint8_t u8 = fuzzed_data_provider.ConsumeIntegral<uint8_t>();
62  const int8_t i8 = fuzzed_data_provider.ConsumeIntegral<int8_t>();
63  // We cannot assume a specific value of std::is_signed<char>::value:
64  // ConsumeIntegral<char>() instead of casting from {u,}int8_t.
65  const char ch = fuzzed_data_provider.ConsumeIntegral<char>();
66  const bool b = fuzzed_data_provider.ConsumeBool();
67 
68  const Consensus::Params& consensus_params = Params().GetConsensus();
69  (void)CheckProofOfWork(u256, u32, consensus_params);
70  if (u64 <= MAX_MONEY) {
71  const uint64_t compressed_money_amount = CompressAmount(u64);
72  assert(u64 == DecompressAmount(compressed_money_amount));
73  static const uint64_t compressed_money_amount_max = CompressAmount(MAX_MONEY - 1);
74  assert(compressed_money_amount <= compressed_money_amount_max);
75  } else {
76  (void)CompressAmount(u64);
77  }
78  static const uint256 u256_min(uint256S("0000000000000000000000000000000000000000000000000000000000000000"));
79  static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
80  const std::vector<uint256> v256{u256, u256_min, u256_max};
81  (void)ComputeMerkleRoot(v256);
82  (void)CountBits(u64);
83  (void)DecompressAmount(u64);
84  {
85  if (std::optional<CAmount> parsed = ParseMoney(FormatMoney(i64))) {
86  assert(parsed.value() == i64);
87  }
88  }
89  (void)GetSizeOfCompactSize(u64);
91  if (!MultiplicationOverflow(i64, static_cast<int64_t>(u32)) && !AdditionOverflow(i64, static_cast<int64_t>(4)) && !AdditionOverflow(i64 * u32, static_cast<int64_t>(4))) {
92  (void)GetVirtualTransactionSize(i64, i64, u32);
93  }
94  (void)HexDigit(ch);
95  (void)MoneyRange(i64);
96  (void)ToString(i64);
97  (void)IsDigit(ch);
98  (void)IsSpace(ch);
99  (void)IsSwitchChar(ch);
100  (void)memusage::DynamicUsage(ch);
101  (void)memusage::DynamicUsage(i16);
102  (void)memusage::DynamicUsage(i32);
103  (void)memusage::DynamicUsage(i64);
104  (void)memusage::DynamicUsage(i8);
105  (void)memusage::DynamicUsage(u16);
107  (void)memusage::DynamicUsage(u64);
108  (void)memusage::DynamicUsage(u8);
109  const unsigned char uch = static_cast<unsigned char>(u8);
110  (void)memusage::DynamicUsage(uch);
111  {
112  const std::set<int64_t> i64s{i64, static_cast<int64_t>(u64)};
113  const size_t dynamic_usage = memusage::DynamicUsage(i64s);
114  const size_t incremental_dynamic_usage = memusage::IncrementalDynamicUsage(i64s);
115  assert(dynamic_usage == incremental_dynamic_usage * i64s.size());
116  }
117  (void)MillisToTimeval(i64);
118  (void)SighashToStr(uch);
119  (void)SipHashUint256(u64, u64, u256);
120  (void)SipHashUint256Extra(u64, u64, u256, u32);
121  (void)ToLower(ch);
122  (void)ToUpper(ch);
123  {
124  if (std::optional<CAmount> parsed = ParseMoney(ValueFromAmount(i64).getValStr())) {
125  assert(parsed.value() == i64);
126  }
127  }
128  if (i32 >= 0 && i32 <= 16) {
130  }
131 
132  const std::chrono::seconds seconds{i64};
133  assert(count_seconds(seconds) == i64);
134 
135  const CScriptNum script_num{i64};
136  (void)script_num.getint();
137  (void)script_num.getvch();
138 
139  const arith_uint256 au256 = UintToArith256(u256);
140  assert(ArithToUint256(au256) == u256);
141  assert(uint256S(au256.GetHex()) == u256);
142  (void)au256.bits();
143  (void)au256.GetCompact(/* fNegative= */ false);
144  (void)au256.GetCompact(/* fNegative= */ true);
145  (void)au256.getdouble();
146  (void)au256.GetHex();
147  (void)au256.GetLow64();
148  (void)au256.size();
149  (void)au256.ToString();
150 
151  const CKeyID key_id{u160};
152  const CScriptID script_id{u160};
153 
154  {
155  DataStream stream{};
156 
157  uint256 deserialized_u256;
158  stream << u256;
159  stream >> deserialized_u256;
160  assert(u256 == deserialized_u256 && stream.empty());
161 
162  uint160 deserialized_u160;
163  stream << u160;
164  stream >> deserialized_u160;
165  assert(u160 == deserialized_u160 && stream.empty());
166 
167  uint64_t deserialized_u64;
168  stream << u64;
169  stream >> deserialized_u64;
170  assert(u64 == deserialized_u64 && stream.empty());
171 
172  int64_t deserialized_i64;
173  stream << i64;
174  stream >> deserialized_i64;
175  assert(i64 == deserialized_i64 && stream.empty());
176 
177  uint32_t deserialized_u32;
178  stream << u32;
179  stream >> deserialized_u32;
180  assert(u32 == deserialized_u32 && stream.empty());
181 
182  int32_t deserialized_i32;
183  stream << i32;
184  stream >> deserialized_i32;
185  assert(i32 == deserialized_i32 && stream.empty());
186 
187  uint16_t deserialized_u16;
188  stream << u16;
189  stream >> deserialized_u16;
190  assert(u16 == deserialized_u16 && stream.empty());
191 
192  int16_t deserialized_i16;
193  stream << i16;
194  stream >> deserialized_i16;
195  assert(i16 == deserialized_i16 && stream.empty());
196 
197  uint8_t deserialized_u8;
198  stream << u8;
199  stream >> deserialized_u8;
200  assert(u8 == deserialized_u8 && stream.empty());
201 
202  int8_t deserialized_i8;
203  stream << i8;
204  stream >> deserialized_i8;
205  assert(i8 == deserialized_i8 && stream.empty());
206 
207  bool deserialized_b;
208  stream << b;
209  stream >> deserialized_b;
210  assert(b == deserialized_b && stream.empty());
211  }
212 
213  {
214  const ServiceFlags service_flags = (ServiceFlags)u64;
215  (void)HasAllDesirableServiceFlags(service_flags);
216  (void)MayHaveUsefulAddressDB(service_flags);
217  }
218 
219  {
220  DataStream stream{};
221 
222  ser_writedata64(stream, u64);
223  const uint64_t deserialized_u64 = ser_readdata64(stream);
224  assert(u64 == deserialized_u64 && stream.empty());
225 
226  ser_writedata32(stream, u32);
227  const uint32_t deserialized_u32 = ser_readdata32(stream);
228  assert(u32 == deserialized_u32 && stream.empty());
229 
230  ser_writedata32be(stream, u32);
231  const uint32_t deserialized_u32be = ser_readdata32be(stream);
232  assert(u32 == deserialized_u32be && stream.empty());
233 
234  ser_writedata16(stream, u16);
235  const uint16_t deserialized_u16 = ser_readdata16(stream);
236  assert(u16 == deserialized_u16 && stream.empty());
237 
238  ser_writedata16be(stream, u16);
239  const uint16_t deserialized_u16be = ser_readdata16be(stream);
240  assert(u16 == deserialized_u16be && stream.empty());
241 
242  ser_writedata8(stream, u8);
243  const uint8_t deserialized_u8 = ser_readdata8(stream);
244  assert(u8 == deserialized_u8 && stream.empty());
245  }
246 
247  {
248  DataStream stream{};
249 
250  WriteCompactSize(stream, u64);
251  try {
252  const uint64_t deserialized_u64 = ReadCompactSize(stream);
253  assert(u64 == deserialized_u64 && stream.empty());
254  } catch (const std::ios_base::failure&) {
255  }
256  }
257 
258  try {
259  CHECK_NONFATAL(b);
260  } catch (const NonFatalCheckError&) {
261  }
262 }
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
arith_uint256 UintToArith256(const uint256 &a)
uint256 ArithToUint256(const arith_uint256 &a)
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:46
static const std::string REGTEST
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
static int DecodeOP_N(opcodetype opcode)
Encode/decode small integers:
Definition: script.h:503
static opcodetype EncodeOP_N(int n)
Definition: script.h:510
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:27
int getint() const
Definition: script.h:329
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:186
std::vector< T > ConsumeBytes(size_t num_bytes)
const std::string & getValStr() const
Definition: univalue.h:64
256-bit unsigned big integer.
uint32_t GetCompact(bool fNegative=false) const
unsigned int size() const
double getdouble() const
std::string ToString() const
uint64_t GetLow64() const
std::string GetHex() const
unsigned int bits() const
Returns the position of the highest bit set plus one, or zero if the value is zero.
160-bit opaque blob.
Definition: uint256.h:94
256-bit opaque blob.
Definition: uint256.h:105
uint64_t DecompressAmount(uint64_t x)
Definition: compressor.cpp:168
uint64_t CompressAmount(uint64_t n)
Compress amount.
Definition: compressor.cpp:149
unsigned int GetSpecialScriptSize(unsigned int nSize)
Definition: compressor.cpp:86
std::string SighashToStr(unsigned char sighash_type)
Definition: core_write.cpp:84
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:26
static uint64_t CountBits(uint64_t x)
Return the smallest number n such that (x >> n) == 0 (or 64 if the highest bit in x is set.
Definition: common.h:90
unsigned int u32
unsigned char u8
void initialize_integer()
Definition: integer.cpp:42
FUZZ_TARGET_INIT(integer, initialize_integer)
Definition: integer.cpp:47
uint256 ComputeMerkleRoot(std::vector< uint256 > hashes, bool *mutated)
Definition: merkle.cpp:45
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:16
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:42
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:28
static size_t IncrementalDynamicUsage(const std::set< X, Y > &s)
Definition: memusage.h:104
bool AdditionOverflow(const T i, const T j) noexcept
Definition: overflow.h:13
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:295
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:125
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition: protocol.h:345
ServiceFlags
nServices flags
Definition: protocol.h:273
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
Definition: protocol.h:354
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:82
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:72
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:67
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:233
void ser_writedata16(Stream &s, uint16_t obj)
Definition: serialize.h:57
void ser_writedata16be(Stream &s, uint16_t obj)
Definition: serialize.h:62
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:88
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:112
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:53
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:275
uint32_t ser_readdata32(Stream &s)
Definition: serialize.h:100
uint16_t ser_readdata16be(Stream &s)
Definition: serialize.h:94
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:77
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:106
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1103
uint64_t SipHashUint256Extra(uint64_t k0, uint64_t k1, const uint256 &val, uint32_t extra)
Definition: siphash.cpp:134
uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256 &val)
Optimized SipHash-2-4 implementation for uint256.
Definition: siphash.cpp:94
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:146
constexpr bool IsSpace(char c) noexcept
Tests if the given character is a whitespace character.
Definition: strencodings.h:162
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
Parameters that influence chain consensus.
Definition: params.h:74
bool IsSwitchChar(char c)
Definition: system.h:121
bool MultiplicationOverflow(const T i, const T j) noexcept
Definition: util.h:166
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:143
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:54
uint256 uint256S(const char *str)
Definition: uint256.h:118
std::string ToUpper(std::string_view str)
Returns the uppercase equivalent of the given string.
signed char HexDigit(char c)
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
assert(!tx.IsCoinBase())