1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_BIGNUM_H
6 #define BITCOIN_BIGNUM_H
10 #include <openssl/bn.h>
13 /** Errors thrown by the bignum class */
14 class bignum_error : public std::runtime_error
17 explicit bignum_error(const std::string& str) : std::runtime_error(str) {}
21 /** RAII encapsulated BN_CTX (OpenSSL bignum context) */
26 BN_CTX* operator=(BN_CTX* pnew) { return pctx = pnew; }
33 throw bignum_error("CAutoBN_CTX : BN_CTX_new() returned NULL");
42 operator BN_CTX*() { return pctx; }
43 BN_CTX& operator*() { return *pctx; }
44 BN_CTX** operator&() { return &pctx; }
45 bool operator!() { return (pctx == NULL); }
49 /** C++ wrapper for BIGNUM (OpenSSL bignum) */
50 class CBigNum : public BIGNUM
58 CBigNum(const CBigNum& b)
61 if (!BN_copy(this, &b))
64 throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_copy failed");
68 CBigNum& operator=(const CBigNum& b)
70 if (!BN_copy(this, &b))
71 throw bignum_error("CBigNum::operator= : BN_copy failed");
80 CBigNum(int8_t n) { BN_init(this); if (n >= 0) setuint32(n); else setint64(n); }
81 CBigNum(int16_t n) { BN_init(this); if (n >= 0) setuint32(n); else setint64(n); }
82 CBigNum(int32_t n) { BN_init(this); if (n >= 0) setuint32(n); else setint64(n); }
83 CBigNum(int64_t n) { BN_init(this); if (n >= 0) setuint64(n); else setint64(n); }
85 CBigNum(uint8_t n) { BN_init(this); setuint32(n); }
86 CBigNum(uint16_t n) { BN_init(this); setuint32(n); }
87 CBigNum(uint32_t n) { BN_init(this); setuint32(n); }
88 CBigNum(uint64_t n) { BN_init(this); setuint64(n); }
90 explicit CBigNum(uint256 n) { BN_init(this); setuint256(n); }
91 explicit CBigNum(const std::vector<uint8_t>& vch)
97 /** Generates a cryptographically secure random number between zero and range exclusive
98 * i.e. 0 < returned number < range
99 * @param range The upper bound on the number.
102 static CBigNum randBignum(const CBigNum& range) {
104 if(!BN_rand_range(&ret, &range)){
105 throw bignum_error("CBigNum:rand element : BN_rand_range failed");
110 /** Generates a cryptographically secure random k-bit number
111 * @param k The bit length of the number.
114 static CBigNum RandKBitBigum(const uint32_t k){
116 if(!BN_rand(&ret, k, -1, 0)){
117 throw bignum_error("CBigNum:rand element : BN_rand failed");
122 /**Returns the size in bits of the underlying bignum.
127 return BN_num_bits(this);
131 void setuint32(uint32_t n)
133 if (!BN_set_word(this, n))
134 throw bignum_error("CBigNum conversion from uint32_t : BN_set_word failed");
137 uint32_t getuint32() const
139 return BN_get_word(this);
142 int32_t getint32() const
144 uint64_t n = BN_get_word(this);
145 if (!BN_is_negative(this))
146 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::max() : (int32_t)n);
148 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::min() : -(int32_t)n);
151 void setint64(int64_t sn)
153 uint8_t pch[sizeof(sn) + 6];
154 uint8_t* p = pch + 4;
160 // Since the minimum signed integer cannot be represented as positive so long as its type is signed, and it's not well-defined what happens if you make it unsigned before negating it, we instead increment the negative integer by 1, convert it, then increment the (now positive) unsigned integer by 1 to compensate
169 bool fLeadingZeroes = true;
170 for (int i = 0; i < 8; i++)
172 uint8_t c = (n >> 56) & 0xff;
179 *p++ = (fNegative ? 0x80 : 0);
182 fLeadingZeroes = false;
186 uint32_t nSize = (uint32_t) (p - (pch + 4));
187 pch[0] = (nSize >> 24) & 0xff;
188 pch[1] = (nSize >> 16) & 0xff;
189 pch[2] = (nSize >> 8) & 0xff;
190 pch[3] = (nSize) & 0xff;
191 BN_mpi2bn(pch, (int)(p - pch), this);
196 return (int64_t) getuint64();
201 size_t nSize = BN_bn2mpi(this, NULL);
204 std::vector<uint8_t> vch(nSize);
205 BN_bn2mpi(this, &vch[0]);
209 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
210 ((uint8_t*)&n)[i] = vch[j];
214 //supress msvc C4127: conditional expression is constant
215 inline bool check(bool value) {return value;}
217 void setuint64(uint64_t n)
219 // Use BN_set_word if word size is sufficient for uint64_t
220 if (check(sizeof(n) <= sizeof(BN_ULONG)))
222 if (!BN_set_word(this, (BN_ULONG)n))
223 throw bignum_error("CBigNum conversion from uint64_t : BN_set_word failed");
227 uint8_t pch[sizeof(n) + 6];
228 uint8_t* p = pch + 4;
229 bool fLeadingZeroes = true;
230 for (int i = 0; i < 8; i++)
232 uint8_t c = (n >> 56) & 0xff;
240 fLeadingZeroes = false;
244 uint32_t nSize = (uint32_t) (p - (pch + 4));
245 pch[0] = (nSize >> 24) & 0xff;
246 pch[1] = (nSize >> 16) & 0xff;
247 pch[2] = (nSize >> 8) & 0xff;
248 pch[3] = (nSize) & 0xff;
249 BN_mpi2bn(pch, (int)(p - pch), this);
252 void setuint160(uint160 n)
254 uint8_t pch[sizeof(n) + 6];
255 uint8_t* p = pch + 4;
256 bool fLeadingZeroes = true;
257 uint8_t* pbegin = (uint8_t*)&n;
258 uint8_t* psrc = pbegin + sizeof(n);
259 while (psrc != pbegin)
261 uint8_t c = *(--psrc);
268 fLeadingZeroes = false;
272 uint32_t nSize = (uint32_t) (p - (pch + 4));
273 pch[0] = (nSize >> 24) & 0xff;
274 pch[1] = (nSize >> 16) & 0xff;
275 pch[2] = (nSize >> 8) & 0xff;
276 pch[3] = (nSize >> 0) & 0xff;
277 BN_mpi2bn(pch, (int) (p - pch), this);
280 uint160 getuint160() const
282 unsigned int nSize = BN_bn2mpi(this, NULL);
285 std::vector<uint8_t> vch(nSize);
286 BN_bn2mpi(this, &vch[0]);
290 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
291 ((uint8_t*)&n)[i] = vch[j];
295 void setuint256(uint256 n)
297 uint8_t pch[sizeof(n) + 6];
298 uint8_t* p = pch + 4;
299 bool fLeadingZeroes = true;
300 uint8_t* pbegin = (uint8_t*)&n;
301 uint8_t* psrc = pbegin + sizeof(n);
302 while (psrc != pbegin)
304 uint8_t c = *(--psrc);
311 fLeadingZeroes = false;
315 uint32_t nSize = (uint32_t) (p - (pch + 4));
316 pch[0] = (nSize >> 24) & 0xff;
317 pch[1] = (nSize >> 16) & 0xff;
318 pch[2] = (nSize >> 8) & 0xff;
319 pch[3] = (nSize >> 0) & 0xff;
320 BN_mpi2bn(pch, (int) (p - pch), this);
323 uint256 getuint256() const
325 unsigned int nSize = BN_bn2mpi(this, NULL);
328 std::vector<uint8_t> vch(nSize);
329 BN_bn2mpi(this, &vch[0]);
333 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
334 ((uint8_t*)&n)[i] = vch[j];
338 void setBytes(const std::vector<uint8_t>& vchBytes)
340 BN_bin2bn(&vchBytes[0], (int) vchBytes.size(), this);
343 std::vector<uint8_t> getBytes() const
345 int nBytes = BN_num_bytes(this);
347 std::vector<uint8_t> vchBytes(nBytes);
349 int n = BN_bn2bin(this, &vchBytes[0]);
351 throw bignum_error("CBigNum::getBytes : BN_bn2bin failed");
357 void setvch(const std::vector<uint8_t>& vch)
359 std::vector<uint8_t> vch2(vch.size() + 4);
360 uint32_t nSize = (uint32_t) vch.size();
361 // BIGNUM's byte stream format expects 4 bytes of
362 // big endian size data info at the front
363 vch2[0] = (nSize >> 24) & 0xff;
364 vch2[1] = (nSize >> 16) & 0xff;
365 vch2[2] = (nSize >> 8) & 0xff;
366 vch2[3] = (nSize >> 0) & 0xff;
367 // swap data to big endian
368 reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4);
369 BN_mpi2bn(&vch2[0], (int) vch2.size(), this);
372 std::vector<uint8_t> getvch() const
374 unsigned int nSize = BN_bn2mpi(this, NULL);
376 return std::vector<uint8_t>();
377 std::vector<uint8_t> vch(nSize);
378 BN_bn2mpi(this, &vch[0]);
379 vch.erase(vch.begin(), vch.begin() + 4);
380 reverse(vch.begin(), vch.end());
384 CBigNum& SetCompact(uint32_t nCompact)
386 uint32_t nSize = nCompact >> 24;
387 std::vector<uint8_t> vch(4 + nSize);
389 if (nSize >= 1) vch[4] = (nCompact >> 16) & 0xff;
390 if (nSize >= 2) vch[5] = (nCompact >> 8) & 0xff;
391 if (nSize >= 3) vch[6] = (nCompact >> 0) & 0xff;
392 BN_mpi2bn(&vch[0], (int) vch.size(), this);
396 uint32_t GetCompact() const
398 uint32_t nSize = BN_bn2mpi(this, NULL);
399 std::vector<uint8_t> vch(nSize);
401 BN_bn2mpi(this, &vch[0]);
402 uint32_t nCompact = nSize << 24;
403 if (nSize >= 1) nCompact |= (vch[4] << 16);
404 if (nSize >= 2) nCompact |= (vch[5] << 8);
405 if (nSize >= 3) nCompact |= (vch[6] << 0);
409 void SetHex(const std::string& str)
412 const char* psz = str.c_str();
413 while (isspace(*psz))
415 bool fNegative = false;
421 if (psz[0] == '0' && tolower(psz[1]) == 'x')
423 while (isspace(*psz))
426 // hex string to bignum
427 static const signed char phexdigit[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0, 0,0xa,0xb,0xc,0xd,0xe,0xf,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0xa,0xb,0xc,0xd,0xe,0xf,0,0,0,0,0,0,0,0,0 };
429 while (isxdigit(*psz))
432 int n = phexdigit[(uint8_t)*psz++];
439 std::string ToString(int nBase=10) const
442 CBigNum bnBase = nBase;
446 BN_set_negative(&bn, false);
449 if (BN_cmp(&bn, &bn0) == 0)
451 while (BN_cmp(&bn, &bn0) > 0)
453 if (!BN_div(&dv, &rem, &bn, &bnBase, pctx))
454 throw bignum_error("CBigNum::ToString() : BN_div failed");
456 uint32_t c = rem.getuint32();
457 str += "0123456789abcdef"[c];
459 if (BN_is_negative(this))
461 reverse(str.begin(), str.end());
465 std::string GetHex() const
470 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
472 return ::GetSerializeSize(getvch(), nType, nVersion);
475 template<typename Stream>
476 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
478 ::Serialize(s, getvch(), nType, nVersion);
481 template<typename Stream>
482 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
484 std::vector<uint8_t> vch;
485 ::Unserialize(s, vch, nType, nVersion);
490 * exponentiation with an int. this^e
491 * @param e the exponent as an int
494 CBigNum pow(const int e) const {
495 return this->pow(CBigNum(e));
499 * exponentiation this^e
500 * @param e the exponent
503 CBigNum pow(const CBigNum& e) const {
506 if (!BN_exp(&ret, this, &e, pctx))
507 throw bignum_error("CBigNum::pow : BN_exp failed");
512 * modular multiplication: (this * b) mod m
516 CBigNum mul_mod(const CBigNum& b, const CBigNum& m) const {
519 if (!BN_mod_mul(&ret, this, &b, &m, pctx))
520 throw bignum_error("CBigNum::mul_mod : BN_mod_mul failed");
526 * modular exponentiation: this^e mod n
530 CBigNum pow_mod(const CBigNum& e, const CBigNum& m) const {
535 CBigNum inv = this->inverse(m);
536 CBigNum posE = e * -1;
537 if (!BN_mod_exp(&ret, &inv, &posE, &m, pctx))
538 throw bignum_error("CBigNum::pow_mod: BN_mod_exp failed on negative exponent");
540 if (!BN_mod_exp(&ret, this, &e, &m, pctx))
541 throw bignum_error("CBigNum::pow_mod : BN_mod_exp failed");
547 * Calculates the inverse of this element mod m.
548 * i.e. i such this*i = 1 mod m
550 * @return the inverse
552 CBigNum inverse(const CBigNum& m) const {
555 if (!BN_mod_inverse(&ret, this, &m, pctx))
556 throw bignum_error("CBigNum::inverse*= :BN_mod_inverse");
561 * Generates a random (safe) prime of numBits bits
562 * @param numBits the number of bits
563 * @param safe true for a safe prime
566 static CBigNum generatePrime(const unsigned int numBits, bool safe = false) {
568 if(!BN_generate_prime_ex(&ret, numBits, (safe == true), NULL, NULL, NULL))
569 throw bignum_error("CBigNum::generatePrime*= :BN_generate_prime_ex");
574 * Calculates the greatest common divisor (GCD) of two numbers.
575 * @param m the second element
578 CBigNum gcd( const CBigNum& b) const{
581 if (!BN_gcd(&ret, this, &b, pctx))
582 throw bignum_error("CBigNum::gcd*= :BN_gcd");
587 * Miller-Rabin primality test on this element
588 * @param checks: optional, the number of Miller-Rabin tests to run
589 * default causes error rate of 2^-80.
590 * @return true if prime
592 bool isPrime(const int checks=BN_prime_checks) const {
594 int ret = BN_is_prime(this, checks, NULL, pctx, NULL);
596 throw bignum_error("CBigNum::isPrime :BN_is_prime");
602 return BN_is_one(this);
606 bool operator!() const
608 return BN_is_zero(this);
611 CBigNum& operator+=(const CBigNum& b)
613 if (!BN_add(this, this, &b))
614 throw bignum_error("CBigNum::operator+= : BN_add failed");
618 CBigNum& operator-=(const CBigNum& b)
624 CBigNum& operator*=(const CBigNum& b)
627 if (!BN_mul(this, this, &b, pctx))
628 throw bignum_error("CBigNum::operator*= : BN_mul failed");
632 CBigNum& operator/=(const CBigNum& b)
638 CBigNum& operator%=(const CBigNum& b)
644 CBigNum& operator<<=(unsigned int shift)
646 if (!BN_lshift(this, this, shift))
647 throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
651 CBigNum& operator>>=(unsigned int shift)
653 // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number
654 // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL
657 if (BN_cmp(&a, this) > 0)
663 if (!BN_rshift(this, this, shift))
664 throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
669 CBigNum& operator++()
672 if (!BN_add(this, this, BN_value_one()))
673 throw bignum_error("CBigNum::operator++ : BN_add failed");
677 const CBigNum operator++(int)
680 const CBigNum ret = *this;
685 CBigNum& operator--()
689 if (!BN_sub(&r, this, BN_value_one()))
690 throw bignum_error("CBigNum::operator-- : BN_sub failed");
695 const CBigNum operator--(int)
698 const CBigNum ret = *this;
704 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
705 friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b);
706 friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b);
707 friend inline const CBigNum operator*(const CBigNum& a, const CBigNum& b);
708 friend inline bool operator<(const CBigNum& a, const CBigNum& b);
713 inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
716 if (!BN_add(&r, &a, &b))
717 throw bignum_error("CBigNum::operator+ : BN_add failed");
721 inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
724 if (!BN_sub(&r, &a, &b))
725 throw bignum_error("CBigNum::operator- : BN_sub failed");
729 inline const CBigNum operator-(const CBigNum& a)
732 BN_set_negative(&r, !BN_is_negative(&r));
736 inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
740 if (!BN_mul(&r, &a, &b, pctx))
741 throw bignum_error("CBigNum::operator* : BN_mul failed");
745 inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
749 if (!BN_div(&r, NULL, &a, &b, pctx))
750 throw bignum_error("CBigNum::operator/ : BN_div failed");
754 inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
758 if (!BN_nnmod(&r, &a, &b, pctx))
759 throw bignum_error("CBigNum::operator% : BN_div failed");
763 inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
766 if (!BN_lshift(&r, &a, shift))
767 throw bignum_error("CBigNum:operator<< : BN_lshift failed");
771 inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
778 inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) == 0); }
779 inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) != 0); }
780 inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) <= 0); }
781 inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) >= 0); }
782 inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) < 0); }
783 inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) > 0); }
785 inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b) { return strm << b.ToString(10); }
787 typedef CBigNum Bignum;