Skip to content

Commit 2748e87

Browse files
author
pierrenn
committed
script: prevent UB when computing abs value for num opcode serialize
1 parent 1b151e3 commit 2748e87

File tree

3 files changed

+3
-11
lines changed

3 files changed

+3
-11
lines changed

src/script/script.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ class CScriptNum
329329

330330
std::vector<unsigned char> result;
331331
const bool neg = value < 0;
332-
uint64_t absvalue = neg ? -value : value;
332+
uint64_t absvalue = neg ? ~static_cast<uint64_t>(value) + 1 : static_cast<uint64_t>(value);
333333

334334
while(absvalue)
335335
{

src/test/fuzz/integer.cpp

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
135135

136136
const CScriptNum script_num{i64};
137137
(void)script_num.getint();
138-
// Avoid negation failure:
139-
// script/script.h:332:35: runtime error: negation of -9223372036854775808 cannot be represented in type 'int64_t' (aka 'long'); cast to an unsigned type to negate this value to itself
140-
if (script_num != CScriptNum{std::numeric_limits<int64_t>::min()}) {
141-
(void)script_num.getvch();
142-
}
138+
(void)script_num.getvch();
143139

144140
const arith_uint256 au256 = UintToArith256(u256);
145141
assert(ArithToUint256(au256) == u256);

src/test/fuzz/scriptnum_ops.cpp

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,6 @@ void test_one_input(const std::vector<uint8_t>& buffer)
129129
break;
130130
}
131131
(void)script_num.getint();
132-
// Avoid negation failure:
133-
// script/script.h:332:35: runtime error: negation of -9223372036854775808 cannot be represented in type 'int64_t' (aka 'long'); cast to an unsigned type to negate this value to itself
134-
if (script_num != CScriptNum{std::numeric_limits<int64_t>::min()}) {
135-
(void)script_num.getvch();
136-
}
132+
(void)script_num.getvch();
137133
}
138134
}

0 commit comments

Comments
 (0)