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(char n) is not portable. Use 'signed char' or 'unsigned char'.
81 CBigNum(signed char n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
82 CBigNum(short n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
83 CBigNum(int n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
84 CBigNum(long n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
85 CBigNum(unsigned char n) { BN_init(this); setulong(n); }
86 CBigNum(unsigned short n) { BN_init(this); setulong(n); }
87 CBigNum(unsigned int n) { BN_init(this); setulong(n); }
88 CBigNum(unsigned long n) { BN_init(this); setulong(n); }
89 explicit CBigNum(uint256 n) { BN_init(this); setuint256(n); }
91 explicit CBigNum(const std::vector<unsigned char>& 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 setulong(unsigned long n)
133 if (!BN_set_word(this, n))
134 throw bignum_error("CBigNum conversion from unsigned long : BN_set_word failed");
137 unsigned long getulong() const
139 return BN_get_word(this);
142 unsigned int getuint() const
144 return BN_get_word(this);
149 unsigned long n = BN_get_word(this);
150 if (!BN_is_negative(this))
151 return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : n);
153 return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::min() : -(int)n);
156 void setint64(int64_t sn)
158 unsigned char pch[sizeof(sn) + 6];
159 unsigned char* p = pch + 4;
165 // 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
174 bool fLeadingZeroes = true;
175 for (int i = 0; i < 8; i++)
177 unsigned char c = (n >> 56) & 0xff;
184 *p++ = (fNegative ? 0x80 : 0);
187 fLeadingZeroes = false;
191 unsigned int nSize = p - (pch + 4);
192 pch[0] = (nSize >> 24) & 0xff;
193 pch[1] = (nSize >> 16) & 0xff;
194 pch[2] = (nSize >> 8) & 0xff;
195 pch[3] = (nSize) & 0xff;
196 BN_mpi2bn(pch, p - pch, this);
201 unsigned int nSize = BN_bn2mpi(this, NULL);
204 std::vector<unsigned char> vch(nSize);
205 BN_bn2mpi(this, &vch[0]);
209 for (unsigned int i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
210 ((unsigned char*)&n)[i] = vch[j];
214 void setuint64(uint64_t n)
216 unsigned char pch[sizeof(n) + 6];
217 unsigned char* p = pch + 4;
218 bool fLeadingZeroes = true;
219 for (int i = 0; i < 8; i++)
221 unsigned char c = (n >> 56) & 0xff;
229 fLeadingZeroes = false;
233 unsigned int nSize = p - (pch + 4);
234 pch[0] = (nSize >> 24) & 0xff;
235 pch[1] = (nSize >> 16) & 0xff;
236 pch[2] = (nSize >> 8) & 0xff;
237 pch[3] = (nSize) & 0xff;
238 BN_mpi2bn(pch, p - pch, this);
241 void setuint160(uint160 n)
243 unsigned char pch[sizeof(n) + 6];
244 unsigned char* p = pch + 4;
245 bool fLeadingZeroes = true;
246 unsigned char* pbegin = (unsigned char*)&n;
247 unsigned char* psrc = pbegin + sizeof(n);
248 while (psrc != pbegin)
250 unsigned char c = *(--psrc);
257 fLeadingZeroes = false;
261 unsigned int nSize = p - (pch + 4);
262 pch[0] = (nSize >> 24) & 0xff;
263 pch[1] = (nSize >> 16) & 0xff;
264 pch[2] = (nSize >> 8) & 0xff;
265 pch[3] = (nSize >> 0) & 0xff;
266 BN_mpi2bn(pch, p - pch, this);
269 uint160 getuint160() const
271 unsigned int nSize = BN_bn2mpi(this, NULL);
274 std::vector<unsigned char> vch(nSize);
275 BN_bn2mpi(this, &vch[0]);
279 for (unsigned int i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
280 ((unsigned char*)&n)[i] = vch[j];
284 void setuint256(uint256 n)
286 unsigned char pch[sizeof(n) + 6];
287 unsigned char* p = pch + 4;
288 bool fLeadingZeroes = true;
289 unsigned char* pbegin = (unsigned char*)&n;
290 unsigned char* psrc = pbegin + sizeof(n);
291 while (psrc != pbegin)
293 unsigned char c = *(--psrc);
300 fLeadingZeroes = false;
304 unsigned int nSize = p - (pch + 4);
305 pch[0] = (nSize >> 24) & 0xff;
306 pch[1] = (nSize >> 16) & 0xff;
307 pch[2] = (nSize >> 8) & 0xff;
308 pch[3] = (nSize >> 0) & 0xff;
309 BN_mpi2bn(pch, p - pch, this);
312 uint256 getuint256() const
314 unsigned int nSize = BN_bn2mpi(this, NULL);
317 std::vector<unsigned char> vch(nSize);
318 BN_bn2mpi(this, &vch[0]);
322 for (unsigned int i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
323 ((unsigned char*)&n)[i] = vch[j];
327 void setBytes(const std::vector<unsigned char>& vchBytes)
329 BN_bin2bn(&vchBytes[0], vchBytes.size(), this);
332 std::vector<unsigned char> getBytes() const
334 int nBytes = BN_num_bytes(this);
336 std::vector<unsigned char> vchBytes(nBytes);
338 int n = BN_bn2bin(this, &vchBytes[0]);
340 throw bignum_error("CBigNum::getBytes : BN_bn2bin failed");
346 void setvch(const std::vector<unsigned char>& vch)
348 std::vector<unsigned char> vch2(vch.size() + 4);
349 unsigned int nSize = vch.size();
350 // BIGNUM's byte stream format expects 4 bytes of
351 // big endian size data info at the front
352 vch2[0] = (nSize >> 24) & 0xff;
353 vch2[1] = (nSize >> 16) & 0xff;
354 vch2[2] = (nSize >> 8) & 0xff;
355 vch2[3] = (nSize >> 0) & 0xff;
356 // swap data to big endian
357 reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4);
358 BN_mpi2bn(&vch2[0], vch2.size(), this);
361 std::vector<unsigned char> getvch() const
363 unsigned int nSize = BN_bn2mpi(this, NULL);
365 return std::vector<unsigned char>();
366 std::vector<unsigned char> vch(nSize);
367 BN_bn2mpi(this, &vch[0]);
368 vch.erase(vch.begin(), vch.begin() + 4);
369 reverse(vch.begin(), vch.end());
373 CBigNum& SetCompact(unsigned int nCompact)
375 unsigned int nSize = nCompact >> 24;
376 std::vector<unsigned char> vch(4 + nSize);
378 if (nSize >= 1) vch[4] = (nCompact >> 16) & 0xff;
379 if (nSize >= 2) vch[5] = (nCompact >> 8) & 0xff;
380 if (nSize >= 3) vch[6] = (nCompact >> 0) & 0xff;
381 BN_mpi2bn(&vch[0], vch.size(), this);
385 unsigned int GetCompact() const
387 unsigned int nSize = BN_bn2mpi(this, NULL);
388 std::vector<unsigned char> vch(nSize);
390 BN_bn2mpi(this, &vch[0]);
391 unsigned int nCompact = nSize << 24;
392 if (nSize >= 1) nCompact |= (vch[4] << 16);
393 if (nSize >= 2) nCompact |= (vch[5] << 8);
394 if (nSize >= 3) nCompact |= (vch[6] << 0);
398 void SetHex(const std::string& str)
401 const char* psz = str.c_str();
402 while (isspace(*psz))
404 bool fNegative = false;
410 if (psz[0] == '0' && tolower(psz[1]) == 'x')
412 while (isspace(*psz))
415 // hex string to bignum
416 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 };
418 while (isxdigit(*psz))
421 int n = phexdigit[(unsigned char)*psz++];
428 std::string ToString(int nBase=10) const
431 CBigNum bnBase = nBase;
435 BN_set_negative(&bn, false);
438 if (BN_cmp(&bn, &bn0) == 0)
440 while (BN_cmp(&bn, &bn0) > 0)
442 if (!BN_div(&dv, &rem, &bn, &bnBase, pctx))
443 throw bignum_error("CBigNum::ToString() : BN_div failed");
445 unsigned int c = rem.getulong();
446 str += "0123456789abcdef"[c];
448 if (BN_is_negative(this))
450 reverse(str.begin(), str.end());
454 std::string GetHex() const
459 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
461 return ::GetSerializeSize(getvch(), nType, nVersion);
464 template<typename Stream>
465 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
467 ::Serialize(s, getvch(), nType, nVersion);
470 template<typename Stream>
471 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
473 std::vector<unsigned char> vch;
474 ::Unserialize(s, vch, nType, nVersion);
479 * exponentiation with an int. this^e
480 * @param e the exponent as an int
483 CBigNum pow(const int e) const {
484 return this->pow(CBigNum(e));
488 * exponentiation this^e
489 * @param e the exponent
492 CBigNum pow(const CBigNum& e) const {
495 if (!BN_exp(&ret, this, &e, pctx))
496 throw bignum_error("CBigNum::pow : BN_exp failed");
501 * modular multiplication: (this * b) mod m
505 CBigNum mul_mod(const CBigNum& b, const CBigNum& m) const {
508 if (!BN_mod_mul(&ret, this, &b, &m, pctx))
509 throw bignum_error("CBigNum::mul_mod : BN_mod_mul failed");
515 * modular exponentiation: this^e mod n
519 CBigNum pow_mod(const CBigNum& e, const CBigNum& m) const {
524 CBigNum inv = this->inverse(m);
525 CBigNum posE = e * -1;
526 if (!BN_mod_exp(&ret, &inv, &posE, &m, pctx))
527 throw bignum_error("CBigNum::pow_mod: BN_mod_exp failed on negative exponent");
529 if (!BN_mod_exp(&ret, this, &e, &m, pctx))
530 throw bignum_error("CBigNum::pow_mod : BN_mod_exp failed");
536 * Calculates the inverse of this element mod m.
537 * i.e. i such this*i = 1 mod m
539 * @return the inverse
541 CBigNum inverse(const CBigNum& m) const {
544 if (!BN_mod_inverse(&ret, this, &m, pctx))
545 throw bignum_error("CBigNum::inverse*= :BN_mod_inverse");
550 * Generates a random (safe) prime of numBits bits
551 * @param numBits the number of bits
552 * @param safe true for a safe prime
555 static CBigNum generatePrime(const unsigned int numBits, bool safe = false) {
557 if(!BN_generate_prime_ex(&ret, numBits, (safe == true), NULL, NULL, NULL))
558 throw bignum_error("CBigNum::generatePrime*= :BN_generate_prime_ex");
563 * Calculates the greatest common divisor (GCD) of two numbers.
564 * @param m the second element
567 CBigNum gcd( const CBigNum& b) const{
570 if (!BN_gcd(&ret, this, &b, pctx))
571 throw bignum_error("CBigNum::gcd*= :BN_gcd");
576 * Miller-Rabin primality test on this element
577 * @param checks: optional, the number of Miller-Rabin tests to run
578 * default causes error rate of 2^-80.
579 * @return true if prime
581 bool isPrime(const int checks=BN_prime_checks) const {
583 int ret = BN_is_prime(this, checks, NULL, pctx, NULL);
585 throw bignum_error("CBigNum::isPrime :BN_is_prime");
591 return BN_is_one(this);
595 bool operator!() const
597 return BN_is_zero(this);
600 CBigNum& operator+=(const CBigNum& b)
602 if (!BN_add(this, this, &b))
603 throw bignum_error("CBigNum::operator+= : BN_add failed");
607 CBigNum& operator-=(const CBigNum& b)
613 CBigNum& operator*=(const CBigNum& b)
616 if (!BN_mul(this, this, &b, pctx))
617 throw bignum_error("CBigNum::operator*= : BN_mul failed");
621 CBigNum& operator/=(const CBigNum& b)
627 CBigNum& operator%=(const CBigNum& b)
633 CBigNum& operator<<=(unsigned int shift)
635 if (!BN_lshift(this, this, shift))
636 throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
640 CBigNum& operator>>=(unsigned int shift)
642 // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number
643 // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL
646 if (BN_cmp(&a, this) > 0)
652 if (!BN_rshift(this, this, shift))
653 throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
658 CBigNum& operator++()
661 if (!BN_add(this, this, BN_value_one()))
662 throw bignum_error("CBigNum::operator++ : BN_add failed");
666 const CBigNum operator++(int)
669 const CBigNum ret = *this;
674 CBigNum& operator--()
678 if (!BN_sub(&r, this, BN_value_one()))
679 throw bignum_error("CBigNum::operator-- : BN_sub failed");
684 const CBigNum operator--(int)
687 const CBigNum ret = *this;
693 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
694 friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b);
695 friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b);
696 friend inline const CBigNum operator*(const CBigNum& a, const CBigNum& b);
697 friend inline bool operator<(const CBigNum& a, const CBigNum& b);
702 inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
705 if (!BN_add(&r, &a, &b))
706 throw bignum_error("CBigNum::operator+ : BN_add failed");
710 inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
713 if (!BN_sub(&r, &a, &b))
714 throw bignum_error("CBigNum::operator- : BN_sub failed");
718 inline const CBigNum operator-(const CBigNum& a)
721 BN_set_negative(&r, !BN_is_negative(&r));
725 inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
729 if (!BN_mul(&r, &a, &b, pctx))
730 throw bignum_error("CBigNum::operator* : BN_mul failed");
734 inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
738 if (!BN_div(&r, NULL, &a, &b, pctx))
739 throw bignum_error("CBigNum::operator/ : BN_div failed");
743 inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
747 if (!BN_nnmod(&r, &a, &b, pctx))
748 throw bignum_error("CBigNum::operator% : BN_div failed");
752 inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
755 if (!BN_lshift(&r, &a, shift))
756 throw bignum_error("CBigNum:operator<< : BN_lshift failed");
760 inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
767 inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) == 0); }
768 inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) != 0); }
769 inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) <= 0); }
770 inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) >= 0); }
771 inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) < 0); }
772 inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) > 0); }
774 inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b) { return strm << b.ToString(10); }
776 typedef CBigNum Bignum;