From 4d480c8a3fe3c58eeb083ea544c6f9e991606692 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Sat, 19 Apr 2014 23:25:44 +0200 Subject: [PATCH] Exception instead of assigning 0 in case of wrong vector length --- src/test/uint256_tests.cpp | 10 +++++----- src/uint256.h | 15 ++++++++++----- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/test/uint256_tests.cpp b/src/test/uint256_tests.cpp index 815babf10..8e4b63c8b 100644 --- a/src/test/uint256_tests.cpp +++ b/src/test/uint256_tests.cpp @@ -160,11 +160,11 @@ BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality tmpS = ~R2S; BOOST_CHECK(tmpS == ~R2S); tmpS = ~MaxS; BOOST_CHECK(tmpS == ~MaxS); - // Wrong length must give 0 - BOOST_CHECK(uint256(std::vector(OneArray,OneArray+31)) == 0); - BOOST_CHECK(uint256(std::vector(OneArray,OneArray+20)) == 0); - BOOST_CHECK(uint160(std::vector(OneArray,OneArray+32)) == 0); - BOOST_CHECK(uint160(std::vector(OneArray,OneArray+19)) == 0); + // Wrong length must throw exception. + BOOST_CHECK_THROW(uint256(std::vector(OneArray,OneArray+31)), uint_error); + BOOST_CHECK_THROW(uint256(std::vector(OneArray,OneArray+20)), uint_error); + BOOST_CHECK_THROW(uint160(std::vector(OneArray,OneArray+32)), uint_error); + BOOST_CHECK_THROW(uint160(std::vector(OneArray,OneArray+19)), uint_error); } void shiftArrayRight(unsigned char* to, const unsigned char* from, unsigned int arrayLength, unsigned int bitsToShift) diff --git a/src/uint256.h b/src/uint256.h index a3f783587..b6365bb36 100644 --- a/src/uint256.h +++ b/src/uint256.h @@ -6,6 +6,8 @@ #ifndef BITCOIN_UINT256_H #define BITCOIN_UINT256_H +#include +#include #include #include #include @@ -19,6 +21,11 @@ inline signed char HexDigit(char c) return p_util_hexdigit[(unsigned char)c]; } +class uint_error : public std::runtime_error { +public: + explicit uint_error(const std::string& str) : std::runtime_error(str) {} +}; + /** Template base class for unsigned big integers. */ template class base_uint @@ -62,11 +69,9 @@ public: explicit base_uint(const std::vector& vch) { - if (vch.size() == sizeof(pn)) { - memcpy(pn, &vch[0], sizeof(pn)); - } else { - *this = 0; - } + if (vch.size() != sizeof(pn)) + throw uint_error("Converting vector of wrong size to base_uint"); + memcpy(pn, &vch[0], sizeof(pn)); } bool operator!() const