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
12 #include <openssl/bn.h>
17 /** Errors thrown by the bignum class */
18 class bignum_error : public std::runtime_error
21 explicit bignum_error(const std::string& str) : std::runtime_error(str) {}
25 /** RAII encapsulated BN_CTX (OpenSSL bignum context) */
30 BN_CTX* operator=(BN_CTX* pnew) { return pctx = pnew; }
37 throw bignum_error("CAutoBN_CTX : BN_CTX_new() returned NULL");
46 operator BN_CTX*() { return pctx; }
47 BN_CTX& operator*() { return *pctx; }
48 BN_CTX** operator&() { return &pctx; }
49 bool operator!() { return (pctx == NULL); }
53 /** C++ wrapper for BIGNUM (OpenSSL bignum) */
64 CBigNum(const CBigNum& b)
66 BIGNUM *dup = BN_dup(b.bn);
69 throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_dup failed");
74 CBigNum& operator=(const CBigNum& b)
76 BIGNUM *dup = BN_dup(b.bn);
79 throw bignum_error("CBigNum::operator= : BN_dup failed");
85 CBigNum(const BIGNUM *bnp) {
86 BIGNUM *dup = BN_dup(bnp);
89 throw bignum_error("CBigNum::CBigNum(const BIGNUM*) : BN_dup failed");
99 CBigNum(bool n) { bn = BN_new(); setuint32(n); }
101 CBigNum(int8_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
102 CBigNum(int16_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
103 CBigNum(int32_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
104 CBigNum(int64_t n) { bn = BN_new(); if (n >= 0) setuint64(n); else setint64(n); }
106 CBigNum(uint8_t n) { bn = BN_new(); setuint32(n); }
107 CBigNum(uint16_t n) { bn = BN_new(); setuint32(n); }
108 CBigNum(uint32_t n) { bn = BN_new(); setuint32(n); }
109 CBigNum(uint64_t n) { bn = BN_new(); setuint64(n); }
111 explicit CBigNum(uint256 n) { bn = BN_new(); setuint256(n); }
112 explicit CBigNum(const std::vector<uint8_t>& vch)
118 /** Generates a cryptographically secure random number between zero and range exclusive
119 * i.e. 0 < returned number < range
120 * @param range The upper bound on the number.
123 static CBigNum randBignum(const CBigNum& range) {
125 if(!BN_rand_range(ret.bn, range.bn)){
126 throw bignum_error("CBigNum:rand element : BN_rand_range failed");
131 /** Generates a cryptographically secure random k-bit number
132 * @param k The bit length of the number.
135 static CBigNum RandKBitBigum(const uint32_t k){
137 if(!BN_rand(ret.bn, k, -1, 0)){
138 throw bignum_error("CBigNum:rand element : BN_rand failed");
143 /**Returns the size in bits of the underlying bignum.
148 return BN_num_bits(bn);
152 void setuint32(uint32_t n)
154 if (!BN_set_word(bn, n))
155 throw bignum_error("CBigNum conversion from uint32_t : BN_set_word failed");
158 uint32_t getuint32() const
160 return BN_get_word(bn);
163 int32_t getint32() const
165 uint64_t n = BN_get_word(bn);
166 if (!BN_is_negative(bn))
167 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::max() : (int32_t)n);
169 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::min() : -(int32_t)n);
172 void setint64(int64_t sn)
174 uint8_t pch[sizeof(sn) + 6];
175 uint8_t* p = pch + 4;
181 // 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
190 bool fLeadingZeroes = true;
191 for (int i = 0; i < 8; i++)
193 uint8_t c = (n >> 56) & 0xff;
200 *p++ = (fNegative ? 0x80 : 0);
203 fLeadingZeroes = false;
207 uint32_t nSize = (uint32_t) (p - (pch + 4));
208 pch[0] = (nSize >> 24) & 0xff;
209 pch[1] = (nSize >> 16) & 0xff;
210 pch[2] = (nSize >> 8) & 0xff;
211 pch[3] = (nSize) & 0xff;
212 BN_mpi2bn(pch, (int)(p - pch), bn);
217 size_t nSize = BN_bn2mpi(bn, NULL);
220 std::vector<uint8_t> vch(nSize);
221 BN_bn2mpi(bn, &vch[0]);
225 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
226 ((uint8_t*)&n)[i] = vch[j];
230 //supress msvc C4127: conditional expression is constant
231 inline bool check(bool value) {return value;}
233 void setuint64(uint64_t n)
235 // Use BN_set_word if word size is sufficient for uint64_t
236 if (check(sizeof(n) <= sizeof(BN_ULONG)))
238 if (!BN_set_word(bn, (BN_ULONG)n))
239 throw bignum_error("CBigNum conversion from uint64_t : BN_set_word failed");
243 uint8_t pch[sizeof(n) + 6];
244 uint8_t* p = pch + 4;
245 bool fLeadingZeroes = true;
246 for (int i = 0; i < 8; i++)
248 uint8_t c = (n >> 56) & 0xff;
256 fLeadingZeroes = false;
260 uint32_t nSize = (uint32_t) (p - (pch + 4));
261 pch[0] = (nSize >> 24) & 0xff;
262 pch[1] = (nSize >> 16) & 0xff;
263 pch[2] = (nSize >> 8) & 0xff;
264 pch[3] = (nSize) & 0xff;
265 BN_mpi2bn(pch, (int)(p - pch), bn);
268 void setuint160(uint160 n)
270 uint8_t pch[sizeof(n) + 6];
271 uint8_t* p = pch + 4;
272 bool fLeadingZeroes = true;
273 uint8_t* pbegin = (uint8_t*)&n;
274 uint8_t* psrc = pbegin + sizeof(n);
275 while (psrc != pbegin)
277 uint8_t c = *(--psrc);
284 fLeadingZeroes = false;
288 uint32_t nSize = (uint32_t) (p - (pch + 4));
289 pch[0] = (nSize >> 24) & 0xff;
290 pch[1] = (nSize >> 16) & 0xff;
291 pch[2] = (nSize >> 8) & 0xff;
292 pch[3] = (nSize >> 0) & 0xff;
293 BN_mpi2bn(pch, (int) (p - pch), bn);
296 uint160 getuint160() const
298 unsigned int nSize = BN_bn2mpi(bn, NULL);
301 std::vector<uint8_t> vch(nSize);
302 BN_bn2mpi(bn, &vch[0]);
306 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
307 ((uint8_t*)&n)[i] = vch[j];
311 void setuint256(uint256 n)
313 uint8_t pch[sizeof(n) + 6];
314 uint8_t* p = pch + 4;
315 bool fLeadingZeroes = true;
316 uint8_t* pbegin = (uint8_t*)&n;
317 uint8_t* psrc = pbegin + sizeof(n);
318 while (psrc != pbegin)
320 uint8_t c = *(--psrc);
327 fLeadingZeroes = false;
331 uint32_t nSize = (uint32_t) (p - (pch + 4));
332 pch[0] = (nSize >> 24) & 0xff;
333 pch[1] = (nSize >> 16) & 0xff;
334 pch[2] = (nSize >> 8) & 0xff;
335 pch[3] = (nSize >> 0) & 0xff;
336 BN_mpi2bn(pch, (int) (p - pch), bn);
339 uint256 getuint256() const
341 unsigned int nSize = BN_bn2mpi(bn, NULL);
344 std::vector<uint8_t> vch(nSize);
345 BN_bn2mpi(bn, &vch[0]);
349 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
350 ((uint8_t*)&n)[i] = vch[j];
354 void setBytes(const std::vector<uint8_t>& vchBytes)
356 BN_bin2bn(&vchBytes[0], (int) vchBytes.size(), bn);
359 std::vector<uint8_t> getBytes() const
361 int nBytes = BN_num_bytes(bn);
363 std::vector<uint8_t> vchBytes(nBytes);
365 int n = BN_bn2bin(bn, &vchBytes[0]);
367 throw bignum_error("CBigNum::getBytes : BN_bn2bin failed");
373 void setvch(const std::vector<uint8_t>& vch)
375 std::vector<uint8_t> vch2(vch.size() + 4);
376 uint32_t nSize = (uint32_t) vch.size();
377 // BIGNUM's byte stream format expects 4 bytes of
378 // big endian size data info at the front
379 vch2[0] = (nSize >> 24) & 0xff;
380 vch2[1] = (nSize >> 16) & 0xff;
381 vch2[2] = (nSize >> 8) & 0xff;
382 vch2[3] = (nSize >> 0) & 0xff;
383 // swap data to big endian
384 reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4);
385 BN_mpi2bn(&vch2[0], (int) vch2.size(), bn);
388 std::vector<uint8_t> getvch() const
390 unsigned int nSize = BN_bn2mpi(bn, NULL);
392 return std::vector<uint8_t>();
393 std::vector<uint8_t> vch(nSize);
394 BN_bn2mpi(bn, &vch[0]);
395 vch.erase(vch.begin(), vch.begin() + 4);
396 reverse(vch.begin(), vch.end());
400 CBigNum& SetCompact(uint32_t nCompact)
402 uint32_t nSize = nCompact >> 24;
403 std::vector<uint8_t> vch(4 + nSize);
405 if (nSize >= 1) vch[4] = (nCompact >> 16) & 0xff;
406 if (nSize >= 2) vch[5] = (nCompact >> 8) & 0xff;
407 if (nSize >= 3) vch[6] = (nCompact >> 0) & 0xff;
408 BN_mpi2bn(&vch[0], (int) vch.size(), bn);
412 uint32_t GetCompact() const
414 uint32_t nSize = BN_bn2mpi(bn, NULL);
415 std::vector<uint8_t> vch(nSize);
417 BN_bn2mpi(bn, &vch[0]);
418 uint32_t nCompact = nSize << 24;
419 if (nSize >= 1) nCompact |= (vch[4] << 16);
420 if (nSize >= 2) nCompact |= (vch[5] << 8);
421 if (nSize >= 3) nCompact |= (vch[6] << 0);
425 void SetHex(const std::string& str)
428 const char* psz = str.c_str();
429 while (isspace(*psz))
431 bool fNegative = false;
437 if (psz[0] == '0' && tolower(psz[1]) == 'x')
439 while (isspace(*psz))
442 // hex string to bignum
443 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 };
445 while (isxdigit(*psz))
448 int n = phexdigit[(uint8_t)*psz++];
455 std::string ToString(int nBase=10) const
458 CBigNum bnBase = nBase;
462 BN_set_negative(bn.bn, false);
465 if (BN_cmp(bn.bn, bn0.bn) == 0)
467 while (BN_cmp(bn.bn, bn0.bn) > 0)
469 if (!BN_div(dv.bn, rem.bn, bn.bn, bnBase.bn, pctx))
470 throw bignum_error("CBigNum::ToString() : BN_div failed");
472 uint32_t c = rem.getuint32();
473 str += "0123456789abcdef"[c];
475 if (BN_is_negative(bn.bn))
477 reverse(str.begin(), str.end());
481 std::string GetHex() const
486 BIGNUM* get() const {
490 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
492 return ::GetSerializeSize(getvch(), nType, nVersion);
495 template<typename Stream>
496 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
498 ::Serialize(s, getvch(), nType, nVersion);
501 template<typename Stream>
502 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
504 std::vector<uint8_t> vch;
505 ::Unserialize(s, vch, nType, nVersion);
510 * exponentiation with an int. this^e
511 * @param e the exponent as an int
514 CBigNum pow(const int e) const {
515 return this->pow(CBigNum(e));
519 * exponentiation this^e
520 * @param e the exponent
523 CBigNum pow(const CBigNum& e) const {
526 if (!BN_exp(ret.bn, bn, e.bn, pctx))
527 throw bignum_error("CBigNum::pow : BN_exp failed");
532 * modular multiplication: (this * b) mod m
536 CBigNum mul_mod(const CBigNum& b, const CBigNum& m) const {
539 if (!BN_mod_mul(ret.bn, bn, b.bn, m.bn, pctx))
540 throw bignum_error("CBigNum::mul_mod : BN_mod_mul failed");
546 * modular exponentiation: this^e mod n
550 CBigNum pow_mod(const CBigNum& e, const CBigNum& m) const {
555 CBigNum inv = this->inverse(m);
556 CBigNum posE = e * -1;
557 if (!BN_mod_exp(ret.bn, inv.bn, posE.bn, m.bn, pctx))
558 throw bignum_error("CBigNum::pow_mod: BN_mod_exp failed on negative exponent");
560 if (!BN_mod_exp(ret.bn, bn, e.bn, m.bn, pctx))
561 throw bignum_error("CBigNum::pow_mod : BN_mod_exp failed");
567 * Calculates the inverse of this element mod m.
568 * i.e. i such this*i = 1 mod m
570 * @return the inverse
572 CBigNum inverse(const CBigNum& m) const {
575 if (!BN_mod_inverse(ret.bn, bn, m.bn, pctx))
576 throw bignum_error("CBigNum::inverse*= :BN_mod_inverse");
581 * Generates a random (safe) prime of numBits bits
582 * @param numBits the number of bits
583 * @param safe true for a safe prime
586 static CBigNum generatePrime(const unsigned int numBits, bool safe = false) {
588 if(!BN_generate_prime_ex(ret.bn, numBits, (safe == true), NULL, NULL, NULL))
589 throw bignum_error("CBigNum::generatePrime*= :BN_generate_prime_ex");
594 * Calculates the greatest common divisor (GCD) of two numbers.
595 * @param m the second element
598 CBigNum gcd( const CBigNum& b) const{
601 if (!BN_gcd(ret.bn, bn, b.bn, pctx))
602 throw bignum_error("CBigNum::gcd*= :BN_gcd");
607 * Miller-Rabin primality test on this element
608 * @param checks: optional, the number of Miller-Rabin tests to run
609 * default causes error rate of 2^-80.
610 * @return true if prime
612 bool isPrime(const int checks=BN_prime_checks) const {
614 int ret = BN_is_prime_ex(bn, checks, pctx, NULL);
616 throw bignum_error("CBigNum::isPrime :BN_is_prime");
622 return BN_is_one(bn);
626 bool operator!() const
628 return BN_is_zero(bn);
631 CBigNum& operator+=(const CBigNum& b)
633 if (!BN_add(bn, bn, b.bn))
634 throw bignum_error("CBigNum::operator+= : BN_add failed");
638 CBigNum& operator-=(const CBigNum& b)
644 CBigNum& operator*=(const CBigNum& b)
647 if (!BN_mul(bn, bn, b.bn, pctx))
648 throw bignum_error("CBigNum::operator*= : BN_mul failed");
652 CBigNum& operator/=(const CBigNum& b)
658 CBigNum& operator%=(const CBigNum& b)
664 CBigNum& operator<<=(unsigned int shift)
666 if (!BN_lshift(bn, bn, shift))
667 throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
671 CBigNum& operator>>=(unsigned int shift)
673 // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number
674 // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL
677 if (BN_cmp(a.bn, bn) > 0)
683 if (!BN_rshift(bn, bn, shift))
684 throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
689 CBigNum& operator++()
692 if (!BN_add(bn, bn, BN_value_one()))
693 throw bignum_error("CBigNum::operator++ : BN_add failed");
697 const CBigNum operator++(int)
700 const CBigNum ret = *this;
705 CBigNum& operator--()
709 if (!BN_sub(r.bn, bn, BN_value_one()))
710 throw bignum_error("CBigNum::operator-- : BN_sub failed");
715 const CBigNum operator--(int)
718 const CBigNum ret = *this;
723 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
724 friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b);
725 friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b);
726 friend inline const CBigNum operator*(const CBigNum& a, const CBigNum& b);
727 friend inline const CBigNum operator+(const CBigNum& a, const CBigNum& b);
728 friend inline const CBigNum operator*(const CBigNum& a);
730 friend inline const CBigNum operator-(const CBigNum& a);
731 friend inline const CBigNum operator<<(const CBigNum& a, unsigned int shift);
733 friend inline bool operator==(const CBigNum& a, const CBigNum& b);
734 friend inline bool operator!=(const CBigNum& a, const CBigNum& b);
735 friend inline bool operator<=(const CBigNum& a, const CBigNum& b);
736 friend inline bool operator>=(const CBigNum& a, const CBigNum& b);
737 friend inline bool operator<(const CBigNum& a, const CBigNum& b);
738 friend inline bool operator>(const CBigNum& a, const CBigNum& b);
739 friend inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b);
744 inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
747 if (!BN_add(r.bn, a.bn, b.bn))
748 throw bignum_error("CBigNum::operator+ : BN_add failed");
752 inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
755 if (!BN_sub(r.bn, a.bn, b.bn))
756 throw bignum_error("CBigNum::operator- : BN_sub failed");
760 inline const CBigNum operator-(const CBigNum& a)
763 BN_set_negative(r.bn, !BN_is_negative(r.bn));
767 inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
771 if (!BN_mul(r.bn, a.bn, b.bn, pctx))
772 throw bignum_error("CBigNum::operator* : BN_mul failed");
776 inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
780 if (!BN_div(r.bn, NULL, a.bn, b.bn, pctx))
781 throw bignum_error("CBigNum::operator/ : BN_div failed");
785 inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
789 if (!BN_nnmod(r.bn, a.bn, b.bn, pctx))
790 throw bignum_error("CBigNum::operator% : BN_div failed");
794 inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
797 if (!BN_lshift(r.bn, a.bn, shift))
798 throw bignum_error("CBigNum:operator<< : BN_lshift failed");
802 inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
809 inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) == 0); }
810 inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) != 0); }
811 inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) <= 0); }
812 inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) >= 0); }
813 inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) < 0); }
814 inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) > 0); }
816 inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b) { return strm << b.ToString(10); }
818 typedef CBigNum Bignum;