From 08b17def58d4135c1dc904a6068670c3c92a3768 Mon Sep 17 00:00:00 2001 From: Karl-Johan Alm Date: Mon, 26 Feb 2018 15:34:53 +0900 Subject: [arith_uint256] Do not destroy *this content if passed-in operator may reference it --- src/arith_uint256.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/arith_uint256.cpp b/src/arith_uint256.cpp index 65de632306..c7ddb17eb0 100644 --- a/src/arith_uint256.cpp +++ b/src/arith_uint256.cpp @@ -69,16 +69,16 @@ base_uint& base_uint::operator*=(uint32_t b32) template base_uint& base_uint::operator*=(const base_uint& b) { - base_uint a = *this; - *this = 0; + base_uint a; for (int j = 0; j < WIDTH; j++) { uint64_t carry = 0; for (int i = 0; i + j < WIDTH; i++) { - uint64_t n = carry + pn[i + j] + (uint64_t)a.pn[j] * b.pn[i]; - pn[i + j] = n & 0xffffffff; + uint64_t n = carry + a.pn[i + j] + (uint64_t)pn[j] * b.pn[i]; + a.pn[i + j] = n & 0xffffffff; carry = n >> 32; } } + *this = a; return *this; } -- cgit v1.2.3 From b120f7bdbee83c00e46a9ec6d0cd09a816631f45 Mon Sep 17 00:00:00 2001 From: Karl-Johan Alm Date: Mon, 26 Feb 2018 15:34:11 +0900 Subject: [test] Add tests for self usage in arith_uint256 --- src/test/uint256_tests.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/test/uint256_tests.cpp b/src/test/uint256_tests.cpp index ad5478e829..20ed29f59b 100644 --- a/src/test/uint256_tests.cpp +++ b/src/test/uint256_tests.cpp @@ -266,4 +266,17 @@ BOOST_AUTO_TEST_CASE( conversion ) BOOST_CHECK(R2L.GetHex() == UintToArith256(R2L).GetHex()); } +BOOST_AUTO_TEST_CASE( operator_with_self ) +{ + arith_uint256 v = UintToArith256(uint256S("02")); + v *= v; + BOOST_CHECK(v == UintToArith256(uint256S("04"))); + v /= v; + BOOST_CHECK(v == UintToArith256(uint256S("01"))); + v += v; + BOOST_CHECK(v == UintToArith256(uint256S("02"))); + v -= v; + BOOST_CHECK(v == UintToArith256(uint256S("0"))); +} + BOOST_AUTO_TEST_SUITE_END() -- cgit v1.2.3