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