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) */
60 CBigNum(const CBigNum& b)
62 BIGNUM *dup = BN_dup(b.bn);
65 throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_dup failed");
70 CBigNum& operator=(const CBigNum& b)
72 BIGNUM *dup = BN_dup(b.bn);
75 throw bignum_error("CBigNum::operator= : BN_dup failed");
86 CBigNum(int8_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
87 CBigNum(int16_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
88 CBigNum(int32_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
89 CBigNum(int64_t n) { bn = BN_new(); if (n >= 0) setuint64(n); else setint64(n); }
91 CBigNum(uint8_t n) { bn = BN_new(); setuint32(n); }
92 CBigNum(uint16_t n) { bn = BN_new(); setuint32(n); }
93 CBigNum(uint32_t n) { bn = BN_new(); setuint32(n); }
94 CBigNum(uint64_t n) { bn = BN_new(); setuint64(n); }
96 explicit CBigNum(uint256 n) { bn = BN_new(); setuint256(n); }
97 explicit CBigNum(const std::vector<uint8_t>& vch)
103 /** Generates a cryptographically secure random number between zero and range exclusive
104 * i.e. 0 < returned number < range
105 * @param range The upper bound on the number.
108 static CBigNum randBignum(const CBigNum& range) {
110 if(!BN_rand_range(ret.bn, range.bn)){
111 throw bignum_error("CBigNum:rand element : BN_rand_range failed");
116 /** Generates a cryptographically secure random k-bit number
117 * @param k The bit length of the number.
120 static CBigNum RandKBitBigum(const uint32_t k){
122 if(!BN_rand(ret.bn, k, -1, 0)){
123 throw bignum_error("CBigNum:rand element : BN_rand failed");
128 /**Returns the size in bits of the underlying bignum.
133 return BN_num_bits(bn);
137 void setuint32(uint32_t n)
139 if (!BN_set_word(bn, n))
140 throw bignum_error("CBigNum conversion from uint32_t : BN_set_word failed");
143 uint32_t getuint32() const
145 return BN_get_word(bn);
148 int32_t getint32() const
150 uint64_t n = BN_get_word(bn);
151 if (!BN_is_negative(bn))
152 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::max() : (int32_t)n);
154 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::min() : -(int32_t)n);
157 void setint64(int64_t sn)
159 uint8_t pch[sizeof(sn) + 6];
160 uint8_t* p = pch + 4;
166 // 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
175 bool fLeadingZeroes = true;
176 for (int i = 0; i < 8; i++)
178 uint8_t c = (n >> 56) & 0xff;
185 *p++ = (fNegative ? 0x80 : 0);
188 fLeadingZeroes = false;
192 uint32_t nSize = (uint32_t) (p - (pch + 4));
193 pch[0] = (nSize >> 24) & 0xff;
194 pch[1] = (nSize >> 16) & 0xff;
195 pch[2] = (nSize >> 8) & 0xff;
196 pch[3] = (nSize) & 0xff;
197 BN_mpi2bn(pch, (int)(p - pch), bn);
202 size_t nSize = BN_bn2mpi(bn, NULL);
205 std::vector<uint8_t> vch(nSize);
206 BN_bn2mpi(bn, &vch[0]);
210 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
211 ((uint8_t*)&n)[i] = vch[j];
215 //supress msvc C4127: conditional expression is constant
216 inline bool check(bool value) {return value;}
218 void setuint64(uint64_t n)
220 // Use BN_set_word if word size is sufficient for uint64_t
221 if (check(sizeof(n) <= sizeof(BN_ULONG)))
223 if (!BN_set_word(bn, (BN_ULONG)n))
224 throw bignum_error("CBigNum conversion from uint64_t : BN_set_word failed");
228 uint8_t pch[sizeof(n) + 6];
229 uint8_t* p = pch + 4;
230 bool fLeadingZeroes = true;
231 for (int i = 0; i < 8; i++)
233 uint8_t c = (n >> 56) & 0xff;
241 fLeadingZeroes = false;
245 uint32_t nSize = (uint32_t) (p - (pch + 4));
246 pch[0] = (nSize >> 24) & 0xff;
247 pch[1] = (nSize >> 16) & 0xff;
248 pch[2] = (nSize >> 8) & 0xff;
249 pch[3] = (nSize) & 0xff;
250 BN_mpi2bn(pch, (int)(p - pch), bn);
253 void setuint160(uint160 n)
255 uint8_t pch[sizeof(n) + 6];
256 uint8_t* p = pch + 4;
257 bool fLeadingZeroes = true;
258 uint8_t* pbegin = (uint8_t*)&n;
259 uint8_t* psrc = pbegin + sizeof(n);
260 while (psrc != pbegin)
262 uint8_t c = *(--psrc);
269 fLeadingZeroes = false;
273 uint32_t nSize = (uint32_t) (p - (pch + 4));
274 pch[0] = (nSize >> 24) & 0xff;
275 pch[1] = (nSize >> 16) & 0xff;
276 pch[2] = (nSize >> 8) & 0xff;
277 pch[3] = (nSize >> 0) & 0xff;
278 BN_mpi2bn(pch, (int) (p - pch), bn);
281 uint160 getuint160() const
283 unsigned int nSize = BN_bn2mpi(bn, NULL);
286 std::vector<uint8_t> vch(nSize);
287 BN_bn2mpi(bn, &vch[0]);
291 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
292 ((uint8_t*)&n)[i] = vch[j];
296 void setuint256(uint256 n)
298 uint8_t pch[sizeof(n) + 6];
299 uint8_t* p = pch + 4;
300 bool fLeadingZeroes = true;
301 uint8_t* pbegin = (uint8_t*)&n;
302 uint8_t* psrc = pbegin + sizeof(n);
303 while (psrc != pbegin)
305 uint8_t c = *(--psrc);
312 fLeadingZeroes = false;
316 uint32_t nSize = (uint32_t) (p - (pch + 4));
317 pch[0] = (nSize >> 24) & 0xff;
318 pch[1] = (nSize >> 16) & 0xff;
319 pch[2] = (nSize >> 8) & 0xff;
320 pch[3] = (nSize >> 0) & 0xff;
321 BN_mpi2bn(pch, (int) (p - pch), bn);
324 uint256 getuint256() const
326 unsigned int nSize = BN_bn2mpi(bn, NULL);
329 std::vector<uint8_t> vch(nSize);
330 BN_bn2mpi(bn, &vch[0]);
334 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
335 ((uint8_t*)&n)[i] = vch[j];
339 void setBytes(const std::vector<uint8_t>& vchBytes)
341 BN_bin2bn(&vchBytes[0], (int) vchBytes.size(), bn);
344 std::vector<uint8_t> getBytes() const
346 int nBytes = BN_num_bytes(bn);
348 std::vector<uint8_t> vchBytes(nBytes);
350 int n = BN_bn2bin(bn, &vchBytes[0]);
352 throw bignum_error("CBigNum::getBytes : BN_bn2bin failed");
358 void setvch(const std::vector<uint8_t>& vch)
360 std::vector<uint8_t> vch2(vch.size() + 4);
361 uint32_t nSize = (uint32_t) vch.size();
362 // BIGNUM's byte stream format expects 4 bytes of
363 // big endian size data info at the front
364 vch2[0] = (nSize >> 24) & 0xff;
365 vch2[1] = (nSize >> 16) & 0xff;
366 vch2[2] = (nSize >> 8) & 0xff;
367 vch2[3] = (nSize >> 0) & 0xff;
368 // swap data to big endian
369 reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4);
370 BN_mpi2bn(&vch2[0], (int) vch2.size(), bn);
373 std::vector<uint8_t> getvch() const
375 unsigned int nSize = BN_bn2mpi(bn, NULL);
377 return std::vector<uint8_t>();
378 std::vector<uint8_t> vch(nSize);
379 BN_bn2mpi(bn, &vch[0]);
380 vch.erase(vch.begin(), vch.begin() + 4);
381 reverse(vch.begin(), vch.end());
385 CBigNum& SetCompact(uint32_t nCompact)
387 uint32_t nSize = nCompact >> 24;
388 std::vector<uint8_t> vch(4 + nSize);
390 if (nSize >= 1) vch[4] = (nCompact >> 16) & 0xff;
391 if (nSize >= 2) vch[5] = (nCompact >> 8) & 0xff;
392 if (nSize >= 3) vch[6] = (nCompact >> 0) & 0xff;
393 BN_mpi2bn(&vch[0], (int) vch.size(), bn);
397 uint32_t GetCompact() const
399 uint32_t nSize = BN_bn2mpi(bn, NULL);
400 std::vector<uint8_t> vch(nSize);
402 BN_bn2mpi(bn, &vch[0]);
403 uint32_t nCompact = nSize << 24;
404 if (nSize >= 1) nCompact |= (vch[4] << 16);
405 if (nSize >= 2) nCompact |= (vch[5] << 8);
406 if (nSize >= 3) nCompact |= (vch[6] << 0);
410 void SetHex(const std::string& str)
413 const char* psz = str.c_str();
414 while (isspace(*psz))
416 bool fNegative = false;
422 if (psz[0] == '0' && tolower(psz[1]) == 'x')
424 while (isspace(*psz))
427 // hex string to bignum
428 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 };
430 while (isxdigit(*psz))
433 int n = phexdigit[(uint8_t)*psz++];
440 std::string ToString(int nBase=10) const
443 CBigNum bnBase = nBase;
447 BN_set_negative(bn.bn, false);
450 if (BN_cmp(bn.bn, bn0.bn) == 0)
452 while (BN_cmp(bn.bn, bn0.bn) > 0)
454 if (!BN_div(dv.bn, rem.bn, bn.bn, bnBase.bn, pctx))
455 throw bignum_error("CBigNum::ToString() : BN_div failed");
457 uint32_t c = rem.getuint32();
458 str += "0123456789abcdef"[c];
460 if (BN_is_negative(bn.bn))
462 reverse(str.begin(), str.end());
466 std::string GetHex() const
471 const BIGNUM* get() const {
479 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
481 return ::GetSerializeSize(getvch(), nType, nVersion);
484 template<typename Stream>
485 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
487 ::Serialize(s, getvch(), nType, nVersion);
490 template<typename Stream>
491 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
493 std::vector<uint8_t> vch;
494 ::Unserialize(s, vch, nType, nVersion);
499 * exponentiation with an int. this^e
500 * @param e the exponent as an int
503 CBigNum pow(const int e) const {
504 return this->pow(CBigNum(e));
508 * exponentiation this^e
509 * @param e the exponent
512 CBigNum pow(const CBigNum& e) const {
515 if (!BN_exp(ret.bn, bn, e.bn, pctx))
516 throw bignum_error("CBigNum::pow : BN_exp failed");
521 * modular multiplication: (this * b) mod m
525 CBigNum mul_mod(const CBigNum& b, const CBigNum& m) const {
528 if (!BN_mod_mul(ret.bn, bn, b.bn, m.bn, pctx))
529 throw bignum_error("CBigNum::mul_mod : BN_mod_mul failed");
535 * modular exponentiation: this^e mod n
539 CBigNum pow_mod(const CBigNum& e, const CBigNum& m) const {
544 CBigNum inv = this->inverse(m);
545 CBigNum posE = e * -1;
546 if (!BN_mod_exp(ret.bn, inv.bn, posE.bn, m.bn, pctx))
547 throw bignum_error("CBigNum::pow_mod: BN_mod_exp failed on negative exponent");
549 if (!BN_mod_exp(ret.bn, bn, e.bn, m.bn, pctx))
550 throw bignum_error("CBigNum::pow_mod : BN_mod_exp failed");
556 * Calculates the inverse of this element mod m.
557 * i.e. i such this*i = 1 mod m
559 * @return the inverse
561 CBigNum inverse(const CBigNum& m) const {
564 if (!BN_mod_inverse(ret.bn, bn, m.bn, pctx))
565 throw bignum_error("CBigNum::inverse*= :BN_mod_inverse");
570 * Generates a random (safe) prime of numBits bits
571 * @param numBits the number of bits
572 * @param safe true for a safe prime
575 static CBigNum generatePrime(const unsigned int numBits, bool safe = false) {
577 if(!BN_generate_prime_ex(ret.bn, numBits, (safe == true), NULL, NULL, NULL))
578 throw bignum_error("CBigNum::generatePrime*= :BN_generate_prime_ex");
583 * Calculates the greatest common divisor (GCD) of two numbers.
584 * @param m the second element
587 CBigNum gcd( const CBigNum& b) const{
590 if (!BN_gcd(ret.bn, bn, b.bn, pctx))
591 throw bignum_error("CBigNum::gcd*= :BN_gcd");
596 * Miller-Rabin primality test on this element
597 * @param checks: optional, the number of Miller-Rabin tests to run
598 * default causes error rate of 2^-80.
599 * @return true if prime
601 bool isPrime(const int checks=BN_prime_checks) const {
603 int ret = BN_is_prime(bn, checks, NULL, pctx, NULL);
605 throw bignum_error("CBigNum::isPrime :BN_is_prime");
611 return BN_is_one(bn);
615 bool operator!() const
617 return BN_is_zero(bn);
620 CBigNum& operator+=(const CBigNum& b)
622 if (!BN_add(bn, bn, b.bn))
623 throw bignum_error("CBigNum::operator+= : BN_add failed");
627 CBigNum& operator-=(const CBigNum& b)
633 CBigNum& operator*=(const CBigNum& b)
636 if (!BN_mul(bn, bn, b.bn, pctx))
637 throw bignum_error("CBigNum::operator*= : BN_mul failed");
641 CBigNum& operator/=(const CBigNum& b)
647 CBigNum& operator%=(const CBigNum& b)
653 CBigNum& operator<<=(unsigned int shift)
655 if (!BN_lshift(bn, bn, shift))
656 throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
660 CBigNum& operator>>=(unsigned int shift)
662 // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number
663 // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL
666 if (BN_cmp(a.bn, bn) > 0)
672 if (!BN_rshift(bn, bn, shift))
673 throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
678 CBigNum& operator++()
681 if (!BN_add(bn, bn, BN_value_one()))
682 throw bignum_error("CBigNum::operator++ : BN_add failed");
686 const CBigNum operator++(int)
689 const CBigNum ret = *this;
694 CBigNum& operator--()
698 if (!BN_sub(r.bn, bn, BN_value_one()))
699 throw bignum_error("CBigNum::operator-- : BN_sub failed");
704 const CBigNum operator--(int)
707 const CBigNum ret = *this;
712 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
713 friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b);
714 friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b);
715 friend inline const CBigNum operator*(const CBigNum& a, const CBigNum& b);
716 friend inline bool operator<(const CBigNum& a, const CBigNum& b);
717 friend inline const CBigNum operator+(const CBigNum& a, const CBigNum& b);
718 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
719 friend inline const CBigNum operator*(const CBigNum& a);
721 friend inline const CBigNum operator-(const CBigNum& a);
722 friend inline const CBigNum operator<<(const CBigNum& a, unsigned int shift);
724 friend inline bool operator==(const CBigNum& a, const CBigNum& b);
725 friend inline bool operator!=(const CBigNum& a, const CBigNum& b);
726 friend inline bool operator<=(const CBigNum& a, const CBigNum& b);
727 friend inline bool operator>=(const CBigNum& a, const CBigNum& b);
728 friend inline bool operator<(const CBigNum& a, const CBigNum& b);
729 friend inline bool operator>(const CBigNum& a, const CBigNum& b);
730 friend inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b);
735 inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
738 if (!BN_add(r.bn, a.bn, b.bn))
739 throw bignum_error("CBigNum::operator+ : BN_add failed");
743 inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
746 if (!BN_sub(r.bn, a.bn, b.bn))
747 throw bignum_error("CBigNum::operator- : BN_sub failed");
751 inline const CBigNum operator-(const CBigNum& a)
754 BN_set_negative(r.bn, !BN_is_negative(r.bn));
758 inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
762 if (!BN_mul(r.bn, a.bn, b.bn, pctx))
763 throw bignum_error("CBigNum::operator* : BN_mul failed");
767 inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
771 if (!BN_div(r.bn, NULL, a.bn, b.bn, pctx))
772 throw bignum_error("CBigNum::operator/ : BN_div failed");
776 inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
780 if (!BN_nnmod(r.bn, a.bn, b.bn, pctx))
781 throw bignum_error("CBigNum::operator% : BN_div failed");
785 inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
788 if (!BN_lshift(r.bn, a.bn, shift))
789 throw bignum_error("CBigNum:operator<< : BN_lshift failed");
793 inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
800 inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) == 0); }
801 inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) != 0); }
802 inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) <= 0); }
803 inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) >= 0); }
804 inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) < 0); }
805 inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) > 0); }
807 inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b) { return strm << b.ToString(10); }
809 typedef CBigNum Bignum;