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>
12 #include "util.h" // for uint64
14 /** Errors thrown by the bignum class */
15 class bignum_error : public std::runtime_error
18 explicit bignum_error(const std::string& str) : std::runtime_error(str) {}
22 /** RAII encapsulated BN_CTX (OpenSSL bignum context) */
27 BN_CTX* operator=(BN_CTX* pnew) { return pctx = pnew; }
34 throw bignum_error("CAutoBN_CTX : BN_CTX_new() returned NULL");
43 operator BN_CTX*() { return pctx; }
44 BN_CTX& operator*() { return *pctx; }
45 BN_CTX** operator&() { return &pctx; }
46 bool operator!() { return (pctx == NULL); }
50 /** C++ wrapper for BIGNUM (OpenSSL bignum) */
51 class CBigNum : public BIGNUM
59 CBigNum(const CBigNum& b)
62 if (!BN_copy(this, &b))
65 throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_copy failed");
69 CBigNum& operator=(const CBigNum& b)
71 if (!BN_copy(this, &b))
72 throw bignum_error("CBigNum::operator= : BN_copy failed");
81 //CBigNum(char n) is not portable. Use 'signed char' or 'unsigned char'.
82 CBigNum(signed char n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
83 CBigNum(short n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
84 CBigNum(int n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
85 CBigNum(long n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
86 CBigNum(int64 n) { BN_init(this); setint64(n); }
87 CBigNum(unsigned char n) { BN_init(this); setulong(n); }
88 CBigNum(unsigned short n) { BN_init(this); setulong(n); }
89 CBigNum(unsigned int n) { BN_init(this); setulong(n); }
90 CBigNum(unsigned long n) { BN_init(this); setulong(n); }
91 CBigNum(uint64 n) { BN_init(this); setuint64(n); }
92 explicit CBigNum(uint256 n) { BN_init(this); setuint256(n); }
94 explicit CBigNum(const std::vector<unsigned char>& vch)
100 void setulong(unsigned long n)
102 if (!BN_set_word(this, n))
103 throw bignum_error("CBigNum conversion from unsigned long : BN_set_word failed");
106 unsigned long getulong() const
108 return BN_get_word(this);
111 unsigned int getuint() const
113 return BN_get_word(this);
118 unsigned long n = BN_get_word(this);
119 if (!BN_is_negative(this))
120 return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : n);
122 return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::min() : -(int)n);
125 void setint64(int64 sn)
127 unsigned char pch[sizeof(sn) + 6];
128 unsigned char* p = pch + 4;
134 // 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
143 bool fLeadingZeroes = true;
144 for (int i = 0; i < 8; i++)
146 unsigned char c = (n >> 56) & 0xff;
153 *p++ = (fNegative ? 0x80 : 0);
156 fLeadingZeroes = false;
160 unsigned int nSize = p - (pch + 4);
161 pch[0] = (nSize >> 24) & 0xff;
162 pch[1] = (nSize >> 16) & 0xff;
163 pch[2] = (nSize >> 8) & 0xff;
164 pch[3] = (nSize) & 0xff;
165 BN_mpi2bn(pch, p - pch, this);
170 unsigned int nSize = BN_bn2mpi(this, NULL);
173 std::vector<unsigned char> vch(nSize);
174 BN_bn2mpi(this, &vch[0]);
178 for (unsigned int i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
179 ((unsigned char*)&n)[i] = vch[j];
183 void setuint64(uint64 n)
185 unsigned char pch[sizeof(n) + 6];
186 unsigned char* p = pch + 4;
187 bool fLeadingZeroes = true;
188 for (int i = 0; i < 8; i++)
190 unsigned char c = (n >> 56) & 0xff;
198 fLeadingZeroes = false;
202 unsigned int nSize = p - (pch + 4);
203 pch[0] = (nSize >> 24) & 0xff;
204 pch[1] = (nSize >> 16) & 0xff;
205 pch[2] = (nSize >> 8) & 0xff;
206 pch[3] = (nSize) & 0xff;
207 BN_mpi2bn(pch, p - pch, this);
210 void setuint256(uint256 n)
212 unsigned char pch[sizeof(n) + 6];
213 unsigned char* p = pch + 4;
214 bool fLeadingZeroes = true;
215 unsigned char* pbegin = (unsigned char*)&n;
216 unsigned char* psrc = pbegin + sizeof(n);
217 while (psrc != pbegin)
219 unsigned char c = *(--psrc);
226 fLeadingZeroes = false;
230 unsigned int nSize = p - (pch + 4);
231 pch[0] = (nSize >> 24) & 0xff;
232 pch[1] = (nSize >> 16) & 0xff;
233 pch[2] = (nSize >> 8) & 0xff;
234 pch[3] = (nSize >> 0) & 0xff;
235 BN_mpi2bn(pch, p - pch, this);
238 uint256 getuint256() const
240 unsigned int nSize = BN_bn2mpi(this, NULL);
243 std::vector<unsigned char> vch(nSize);
244 BN_bn2mpi(this, &vch[0]);
248 for (unsigned int i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
249 ((unsigned char*)&n)[i] = vch[j];
254 void setvch(const std::vector<unsigned char>& vch)
256 std::vector<unsigned char> vch2(vch.size() + 4);
257 unsigned int nSize = vch.size();
258 // BIGNUM's byte stream format expects 4 bytes of
259 // big endian size data info at the front
260 vch2[0] = (nSize >> 24) & 0xff;
261 vch2[1] = (nSize >> 16) & 0xff;
262 vch2[2] = (nSize >> 8) & 0xff;
263 vch2[3] = (nSize >> 0) & 0xff;
264 // swap data to big endian
265 reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4);
266 BN_mpi2bn(&vch2[0], vch2.size(), this);
269 std::vector<unsigned char> getvch() const
271 unsigned int nSize = BN_bn2mpi(this, NULL);
273 return std::vector<unsigned char>();
274 std::vector<unsigned char> vch(nSize);
275 BN_bn2mpi(this, &vch[0]);
276 vch.erase(vch.begin(), vch.begin() + 4);
277 reverse(vch.begin(), vch.end());
281 CBigNum& SetCompact(unsigned int nCompact)
283 unsigned int nSize = nCompact >> 24;
284 std::vector<unsigned char> vch(4 + nSize);
286 if (nSize >= 1) vch[4] = (nCompact >> 16) & 0xff;
287 if (nSize >= 2) vch[5] = (nCompact >> 8) & 0xff;
288 if (nSize >= 3) vch[6] = (nCompact >> 0) & 0xff;
289 BN_mpi2bn(&vch[0], vch.size(), this);
293 unsigned int GetCompact() const
295 unsigned int nSize = BN_bn2mpi(this, NULL);
296 std::vector<unsigned char> vch(nSize);
298 BN_bn2mpi(this, &vch[0]);
299 unsigned int nCompact = nSize << 24;
300 if (nSize >= 1) nCompact |= (vch[4] << 16);
301 if (nSize >= 2) nCompact |= (vch[5] << 8);
302 if (nSize >= 3) nCompact |= (vch[6] << 0);
306 void SetHex(const std::string& str)
309 const char* psz = str.c_str();
310 while (isspace(*psz))
312 bool fNegative = false;
318 if (psz[0] == '0' && tolower(psz[1]) == 'x')
320 while (isspace(*psz))
323 // hex string to bignum
324 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 };
326 while (isxdigit(*psz))
329 int n = phexdigit[(unsigned char)*psz++];
336 std::string ToString(int nBase=10) const
339 CBigNum bnBase = nBase;
343 BN_set_negative(&bn, false);
346 if (BN_cmp(&bn, &bn0) == 0)
348 while (BN_cmp(&bn, &bn0) > 0)
350 if (!BN_div(&dv, &rem, &bn, &bnBase, pctx))
351 throw bignum_error("CBigNum::ToString() : BN_div failed");
353 unsigned int c = rem.getulong();
354 str += "0123456789abcdef"[c];
356 if (BN_is_negative(this))
358 reverse(str.begin(), str.end());
362 std::string GetHex() const
367 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
369 return ::GetSerializeSize(getvch(), nType, nVersion);
372 template<typename Stream>
373 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
375 ::Serialize(s, getvch(), nType, nVersion);
378 template<typename Stream>
379 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
381 std::vector<unsigned char> vch;
382 ::Unserialize(s, vch, nType, nVersion);
387 bool operator!() const
389 return BN_is_zero(this);
392 CBigNum& operator+=(const CBigNum& b)
394 if (!BN_add(this, this, &b))
395 throw bignum_error("CBigNum::operator+= : BN_add failed");
399 CBigNum& operator-=(const CBigNum& b)
405 CBigNum& operator*=(const CBigNum& b)
408 if (!BN_mul(this, this, &b, pctx))
409 throw bignum_error("CBigNum::operator*= : BN_mul failed");
413 CBigNum& operator/=(const CBigNum& b)
419 CBigNum& operator%=(const CBigNum& b)
425 CBigNum& operator<<=(unsigned int shift)
427 if (!BN_lshift(this, this, shift))
428 throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
432 CBigNum& operator>>=(unsigned int shift)
434 // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number
435 // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL
438 if (BN_cmp(&a, this) > 0)
444 if (!BN_rshift(this, this, shift))
445 throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
450 CBigNum& operator++()
453 if (!BN_add(this, this, BN_value_one()))
454 throw bignum_error("CBigNum::operator++ : BN_add failed");
458 const CBigNum operator++(int)
461 const CBigNum ret = *this;
466 CBigNum& operator--()
470 if (!BN_sub(&r, this, BN_value_one()))
471 throw bignum_error("CBigNum::operator-- : BN_sub failed");
476 const CBigNum operator--(int)
479 const CBigNum ret = *this;
485 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
486 friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b);
487 friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b);
492 inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
495 if (!BN_add(&r, &a, &b))
496 throw bignum_error("CBigNum::operator+ : BN_add failed");
500 inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
503 if (!BN_sub(&r, &a, &b))
504 throw bignum_error("CBigNum::operator- : BN_sub failed");
508 inline const CBigNum operator-(const CBigNum& a)
511 BN_set_negative(&r, !BN_is_negative(&r));
515 inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
519 if (!BN_mul(&r, &a, &b, pctx))
520 throw bignum_error("CBigNum::operator* : BN_mul failed");
524 inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
528 if (!BN_div(&r, NULL, &a, &b, pctx))
529 throw bignum_error("CBigNum::operator/ : BN_div failed");
533 inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
537 if (!BN_mod(&r, &a, &b, pctx))
538 throw bignum_error("CBigNum::operator% : BN_div failed");
542 inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
545 if (!BN_lshift(&r, &a, shift))
546 throw bignum_error("CBigNum:operator<< : BN_lshift failed");
550 inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
557 inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) == 0); }
558 inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) != 0); }
559 inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) <= 0); }
560 inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) >= 0); }
561 inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) < 0); }
562 inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) > 0); }