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>
18 /** Errors thrown by the bignum class */
19 class bignum_error : public std::runtime_error
22 explicit bignum_error(const std::string& str) : std::runtime_error(str) {}
26 /** RAII encapsulated BN_CTX (OpenSSL bignum context) */
31 BN_CTX* operator=(BN_CTX* pnew) { return pctx = pnew; }
38 throw bignum_error("CAutoBN_CTX : BN_CTX_new() returned NULL");
47 operator BN_CTX*() { return pctx; }
48 BN_CTX& operator*() { return *pctx; }
49 BN_CTX** operator&() { return &pctx; }
50 bool operator!() { return (pctx == NULL); }
54 /** C++ wrapper for BIGNUM (OpenSSL bignum) */
65 CBigNum(const CBigNum& b)
67 BIGNUM *dup = BN_dup(b.bn);
70 throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_dup failed");
75 CBigNum& operator=(const CBigNum& b)
77 BIGNUM *dup = BN_dup(b.bn);
80 throw bignum_error("CBigNum::operator= : BN_dup failed");
86 CBigNum(const BIGNUM *bnp) {
87 BIGNUM *dup = BN_dup(bnp);
90 throw bignum_error("CBigNum::CBigNum(const BIGNUM*) : BN_dup failed");
100 CBigNum(bool n) { bn = BN_new(); setuint32(n); }
102 CBigNum(int8_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
103 CBigNum(int16_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
104 CBigNum(int32_t n) { bn = BN_new(); if (n >= 0) setuint32(n); else setint64(n); }
105 CBigNum(int64_t n) { bn = BN_new(); if (n >= 0) setuint64(n); else setint64(n); }
107 CBigNum(uint8_t n) { bn = BN_new(); setuint32(n); }
108 CBigNum(uint16_t n) { bn = BN_new(); setuint32(n); }
109 CBigNum(uint32_t n) { bn = BN_new(); setuint32(n); }
110 CBigNum(uint64_t n) { bn = BN_new(); setuint64(n); }
112 explicit CBigNum(uint256 n) { bn = BN_new(); setuint256(n); }
113 explicit CBigNum(const std::vector<uint8_t>& vch)
119 void setuint32(uint32_t n)
121 if (!BN_set_word(bn, n))
122 throw bignum_error("CBigNum conversion from uint32_t : BN_set_word failed");
125 uint32_t getuint32() const
127 return BN_get_word(bn);
130 int32_t getint32() const
132 uint64_t n = BN_get_word(bn);
133 if (!BN_is_negative(bn))
134 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::max() : (int32_t)n);
136 return (n > (uint64_t)std::numeric_limits<int32_t>::max() ? std::numeric_limits<int32_t>::min() : -(int32_t)n);
139 void setint64(int64_t sn)
141 uint8_t pch[sizeof(sn) + 6];
142 uint8_t* p = pch + 4;
148 // 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
157 bool fLeadingZeroes = true;
158 for (int i = 0; i < 8; i++)
160 uint8_t c = (n >> 56) & 0xff;
167 *p++ = (fNegative ? 0x80 : 0);
170 fLeadingZeroes = false;
174 uint32_t nSize = (uint32_t) (p - (pch + 4));
175 pch[0] = (nSize >> 24) & 0xff;
176 pch[1] = (nSize >> 16) & 0xff;
177 pch[2] = (nSize >> 8) & 0xff;
178 pch[3] = (nSize) & 0xff;
179 BN_mpi2bn(pch, (int)(p - pch), bn);
184 size_t nSize = BN_bn2mpi(bn, NULL);
187 std::vector<uint8_t> vch(nSize);
188 BN_bn2mpi(bn, &vch[0]);
192 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
193 ((uint8_t*)&n)[i] = vch[j];
197 //supress msvc C4127: conditional expression is constant
198 inline bool check(bool value) {return value;}
200 void setuint64(uint64_t n)
202 // Use BN_set_word if word size is sufficient for uint64_t
203 if (check(sizeof(n) <= sizeof(BN_ULONG)))
205 if (!BN_set_word(bn, (BN_ULONG)n))
206 throw bignum_error("CBigNum conversion from uint64_t : BN_set_word failed");
210 uint8_t pch[sizeof(n) + 6];
211 uint8_t* p = pch + 4;
212 bool fLeadingZeroes = true;
213 for (int i = 0; i < 8; i++)
215 uint8_t c = (n >> 56) & 0xff;
223 fLeadingZeroes = false;
227 uint32_t nSize = (uint32_t) (p - (pch + 4));
228 pch[0] = (nSize >> 24) & 0xff;
229 pch[1] = (nSize >> 16) & 0xff;
230 pch[2] = (nSize >> 8) & 0xff;
231 pch[3] = (nSize) & 0xff;
232 BN_mpi2bn(pch, (int)(p - pch), bn);
235 void setuint160(uint160 n)
237 uint8_t pch[sizeof(n) + 6];
238 uint8_t* p = pch + 4;
239 bool fLeadingZeroes = true;
240 uint8_t* pbegin = (uint8_t*)&n;
241 uint8_t* psrc = pbegin + sizeof(n);
242 while (psrc != pbegin)
244 uint8_t c = *(--psrc);
251 fLeadingZeroes = false;
255 uint32_t nSize = (uint32_t) (p - (pch + 4));
256 pch[0] = (nSize >> 24) & 0xff;
257 pch[1] = (nSize >> 16) & 0xff;
258 pch[2] = (nSize >> 8) & 0xff;
259 pch[3] = (nSize >> 0) & 0xff;
260 BN_mpi2bn(pch, (int) (p - pch), bn);
263 uint160 getuint160() const
265 unsigned int nSize = BN_bn2mpi(bn, NULL);
268 std::vector<uint8_t> vch(nSize);
269 BN_bn2mpi(bn, &vch[0]);
273 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
274 ((uint8_t*)&n)[i] = vch[j];
278 void setuint256(uint256 n)
280 uint8_t pch[sizeof(n) + 6];
281 uint8_t* p = pch + 4;
282 bool fLeadingZeroes = true;
283 uint8_t* pbegin = (uint8_t*)&n;
284 uint8_t* psrc = pbegin + sizeof(n);
285 while (psrc != pbegin)
287 uint8_t c = *(--psrc);
294 fLeadingZeroes = false;
298 uint32_t nSize = (uint32_t) (p - (pch + 4));
299 pch[0] = (nSize >> 24) & 0xff;
300 pch[1] = (nSize >> 16) & 0xff;
301 pch[2] = (nSize >> 8) & 0xff;
302 pch[3] = (nSize >> 0) & 0xff;
303 BN_mpi2bn(pch, (int) (p - pch), bn);
306 uint256 getuint256() const
308 unsigned int nSize = BN_bn2mpi(bn, NULL);
311 std::vector<uint8_t> vch(nSize);
312 BN_bn2mpi(bn, &vch[0]);
316 for (size_t i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
317 ((uint8_t*)&n)[i] = vch[j];
321 void setBytes(const std::vector<uint8_t>& vchBytes)
323 BN_bin2bn(&vchBytes[0], (int) vchBytes.size(), bn);
326 std::vector<uint8_t> getBytes() const
328 int nBytes = BN_num_bytes(bn);
330 std::vector<uint8_t> vchBytes(nBytes);
332 int n = BN_bn2bin(bn, &vchBytes[0]);
334 throw bignum_error("CBigNum::getBytes : BN_bn2bin failed");
340 void setvch(const std::vector<uint8_t>& vch)
342 std::vector<uint8_t> vch2(vch.size() + 4);
343 uint32_t nSize = (uint32_t) vch.size();
344 // BIGNUM's byte stream format expects 4 bytes of
345 // big endian size data info at the front
346 vch2[0] = (nSize >> 24) & 0xff;
347 vch2[1] = (nSize >> 16) & 0xff;
348 vch2[2] = (nSize >> 8) & 0xff;
349 vch2[3] = (nSize >> 0) & 0xff;
350 // swap data to big endian
351 std::reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4);
352 BN_mpi2bn(&vch2[0], (int) vch2.size(), bn);
355 std::vector<uint8_t> getvch() const
357 unsigned int nSize = BN_bn2mpi(bn, NULL);
359 return std::vector<uint8_t>();
360 std::vector<uint8_t> vch(nSize);
361 BN_bn2mpi(bn, &vch[0]);
362 vch.erase(vch.begin(), vch.begin() + 4);
363 std::reverse(vch.begin(), vch.end());
367 CBigNum& SetCompact(uint32_t nCompact)
369 uint32_t nSize = nCompact >> 24;
370 std::vector<uint8_t> vch(4 + nSize);
372 if (nSize >= 1) vch[4] = (nCompact >> 16) & 0xff;
373 if (nSize >= 2) vch[5] = (nCompact >> 8) & 0xff;
374 if (nSize >= 3) vch[6] = (nCompact >> 0) & 0xff;
375 BN_mpi2bn(&vch[0], (int) vch.size(), bn);
379 uint32_t GetCompact() const
381 uint32_t nSize = BN_bn2mpi(bn, NULL);
382 std::vector<uint8_t> vch(nSize);
384 BN_bn2mpi(bn, &vch[0]);
385 uint32_t nCompact = nSize << 24;
386 if (nSize >= 1) nCompact |= (vch[4] << 16);
387 if (nSize >= 2) nCompact |= (vch[5] << 8);
388 if (nSize >= 3) nCompact |= (vch[6] << 0);
392 void SetHex(const std::string& str)
395 const char* psz = str.c_str();
396 while (isspace(*psz))
398 bool fNegative = false;
404 if (psz[0] == '0' && tolower(psz[1]) == 'x')
406 while (isspace(*psz))
409 // hex string to bignum
410 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 };
412 while (isxdigit(*psz))
415 int n = phexdigit[(uint8_t)*psz++];
422 std::string ToString(int nBase=10) const
425 CBigNum bnBase = nBase;
429 BN_set_negative(bn.bn, false);
432 if (BN_cmp(bn.bn, bn0.bn) == 0)
434 while (BN_cmp(bn.bn, bn0.bn) > 0)
436 if (!BN_div(dv.bn, rem.bn, bn.bn, bnBase.bn, pctx))
437 throw bignum_error("CBigNum::ToString() : BN_div failed");
439 uint32_t c = rem.getuint32();
440 str += "0123456789abcdef"[c];
442 if (BN_is_negative(bn.bn))
444 std::reverse(str.begin(), str.end());
448 std::string GetHex() const
453 BIGNUM* get() const {
457 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
459 return ::GetSerializeSize(getvch(), nType, nVersion);
462 template<typename Stream>
463 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
465 ::Serialize(s, getvch(), nType, nVersion);
468 template<typename Stream>
469 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
471 std::vector<uint8_t> vch;
472 ::Unserialize(s, vch, nType, nVersion);
476 bool operator!() const
478 return BN_is_zero(bn);
481 CBigNum& operator+=(const CBigNum& b)
483 if (!BN_add(bn, bn, b.bn))
484 throw bignum_error("CBigNum::operator+= : BN_add failed");
488 CBigNum& operator-=(const CBigNum& b)
494 CBigNum& operator*=(const CBigNum& b)
497 if (!BN_mul(bn, bn, b.bn, pctx))
498 throw bignum_error("CBigNum::operator*= : BN_mul failed");
502 CBigNum& operator/=(const CBigNum& b)
508 CBigNum& operator%=(const CBigNum& b)
514 CBigNum& operator<<=(unsigned int shift)
516 if (!BN_lshift(bn, bn, shift))
517 throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
521 CBigNum& operator>>=(unsigned int shift)
523 // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number
524 // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL
527 if (BN_cmp(a.bn, bn) > 0)
533 if (!BN_rshift(bn, bn, shift))
534 throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
538 CBigNum& operator++()
541 if (!BN_add(bn, bn, BN_value_one()))
542 throw bignum_error("CBigNum::operator++ : BN_add failed");
546 const CBigNum operator++(int)
549 const CBigNum ret = *this;
554 CBigNum& operator--()
558 if (!BN_sub(r.bn, bn, BN_value_one()))
559 throw bignum_error("CBigNum::operator-- : BN_sub failed");
564 const CBigNum operator--(int)
567 const CBigNum ret = *this;
572 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
573 friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b);
574 friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b);
575 friend inline const CBigNum operator*(const CBigNum& a, const CBigNum& b);
576 friend inline const CBigNum operator+(const CBigNum& a, const CBigNum& b);
577 friend inline const CBigNum operator*(const CBigNum& a);
579 friend inline const CBigNum operator-(const CBigNum& a);
580 friend inline const CBigNum operator<<(const CBigNum& a, unsigned int shift);
582 friend inline bool operator==(const CBigNum& a, const CBigNum& b);
583 friend inline bool operator!=(const CBigNum& a, const CBigNum& b);
584 friend inline bool operator<=(const CBigNum& a, const CBigNum& b);
585 friend inline bool operator>=(const CBigNum& a, const CBigNum& b);
586 friend inline bool operator<(const CBigNum& a, const CBigNum& b);
587 friend inline bool operator>(const CBigNum& a, const CBigNum& b);
588 friend inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b);
592 inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
595 if (!BN_add(r.bn, a.bn, b.bn))
596 throw bignum_error("CBigNum::operator+ : BN_add failed");
600 inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
603 if (!BN_sub(r.bn, a.bn, b.bn))
604 throw bignum_error("CBigNum::operator- : BN_sub failed");
608 inline const CBigNum operator-(const CBigNum& a)
611 BN_set_negative(r.bn, !BN_is_negative(r.bn));
615 inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
619 if (!BN_mul(r.bn, a.bn, b.bn, pctx))
620 throw bignum_error("CBigNum::operator* : BN_mul failed");
624 inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
628 if (!BN_div(r.bn, NULL, a.bn, b.bn, pctx))
629 throw bignum_error("CBigNum::operator/ : BN_div failed");
633 inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
637 if (!BN_nnmod(r.bn, a.bn, b.bn, pctx))
638 throw bignum_error("CBigNum::operator% : BN_div failed");
642 inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
645 if (!BN_lshift(r.bn, a.bn, shift))
646 throw bignum_error("CBigNum:operator<< : BN_lshift failed");
650 inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
657 inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) == 0); }
658 inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) != 0); }
659 inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) <= 0); }
660 inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) >= 0); }
661 inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) < 0); }
662 inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(a.bn, b.bn) > 0); }
664 inline std::ostream& operator<<(std::ostream &strm, const CBigNum &b) { return strm << b.ToString(10); }