update to 0.4 preview
[novacoin.git] / src / bignum.h
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
7
8 #include <stdexcept>
9 #include <vector>
10 #include <openssl/bn.h>
11
12 #include "util.h" // for uint64
13
14 /** Errors thrown by the bignum class */
15 class bignum_error : public std::runtime_error
16 {
17 public:
18     explicit bignum_error(const std::string& str) : std::runtime_error(str) {}
19 };
20
21
22 /** RAII encapsulated BN_CTX (OpenSSL bignum context) */
23 class CAutoBN_CTX
24 {
25 protected:
26     BN_CTX* pctx;
27     BN_CTX* operator=(BN_CTX* pnew) { return pctx = pnew; }
28
29 public:
30     CAutoBN_CTX()
31     {
32         pctx = BN_CTX_new();
33         if (pctx == NULL)
34             throw bignum_error("CAutoBN_CTX : BN_CTX_new() returned NULL");
35     }
36
37     ~CAutoBN_CTX()
38     {
39         if (pctx != NULL)
40             BN_CTX_free(pctx);
41     }
42
43     operator BN_CTX*() { return pctx; }
44     BN_CTX& operator*() { return *pctx; }
45     BN_CTX** operator&() { return &pctx; }
46     bool operator!() { return (pctx == NULL); }
47 };
48
49
50 /** C++ wrapper for BIGNUM (OpenSSL bignum) */
51 class CBigNum : public BIGNUM
52 {
53 public:
54     CBigNum()
55     {
56         BN_init(this);
57     }
58
59     CBigNum(const CBigNum& b)
60     {
61         BN_init(this);
62         if (!BN_copy(this, &b))
63         {
64             BN_clear_free(this);
65             throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_copy failed");
66         }
67     }
68
69     CBigNum& operator=(const CBigNum& b)
70     {
71         if (!BN_copy(this, &b))
72             throw bignum_error("CBigNum::operator= : BN_copy failed");
73         return (*this);
74     }
75
76     ~CBigNum()
77     {
78         BN_clear_free(this);
79     }
80
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); }
93
94     explicit CBigNum(const std::vector<unsigned char>& vch)
95     {
96         BN_init(this);
97         setvch(vch);
98     }
99
100     void setulong(unsigned long n)
101     {
102         if (!BN_set_word(this, n))
103             throw bignum_error("CBigNum conversion from unsigned long : BN_set_word failed");
104     }
105
106     unsigned long getulong() const
107     {
108         return BN_get_word(this);
109     }
110
111     unsigned int getuint() const
112     {
113         return BN_get_word(this);
114     }
115
116     int getint() const
117     {
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);
121         else
122             return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::min() : -(int)n);
123     }
124
125     void setint64(int64 sn)
126     {
127         unsigned char pch[sizeof(sn) + 6];
128         unsigned char* p = pch + 4;
129         bool fNegative;
130         uint64 n;
131
132         if (sn < (int64)0)
133         {
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
135             n = -(sn + 1);
136             ++n;
137             fNegative = true;
138         } else {
139             n = sn;
140             fNegative = false;
141         }
142
143         bool fLeadingZeroes = true;
144         for (int i = 0; i < 8; i++)
145         {
146             unsigned char c = (n >> 56) & 0xff;
147             n <<= 8;
148             if (fLeadingZeroes)
149             {
150                 if (c == 0)
151                     continue;
152                 if (c & 0x80)
153                     *p++ = (fNegative ? 0x80 : 0);
154                 else if (fNegative)
155                     c |= 0x80;
156                 fLeadingZeroes = false;
157             }
158             *p++ = c;
159         }
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);
166     }
167
168     uint64 getuint64()
169     {
170         unsigned int nSize = BN_bn2mpi(this, NULL);
171         if (nSize < 4)
172             return 0;
173         std::vector<unsigned char> vch(nSize);
174         BN_bn2mpi(this, &vch[0]);
175         if (vch.size() > 4)
176             vch[4] &= 0x7f;
177         uint64 n = 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];
180         return n;
181     }
182
183     void setuint64(uint64 n)
184     {
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++)
189         {
190             unsigned char c = (n >> 56) & 0xff;
191             n <<= 8;
192             if (fLeadingZeroes)
193             {
194                 if (c == 0)
195                     continue;
196                 if (c & 0x80)
197                     *p++ = 0;
198                 fLeadingZeroes = false;
199             }
200             *p++ = c;
201         }
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);
208     }
209
210     void setuint256(uint256 n)
211     {
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)
218         {
219             unsigned char c = *(--psrc);
220             if (fLeadingZeroes)
221             {
222                 if (c == 0)
223                     continue;
224                 if (c & 0x80)
225                     *p++ = 0;
226                 fLeadingZeroes = false;
227             }
228             *p++ = c;
229         }
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);
236     }
237
238     uint256 getuint256()
239     {
240         unsigned int nSize = BN_bn2mpi(this, NULL);
241         if (nSize < 4)
242             return 0;
243         std::vector<unsigned char> vch(nSize);
244         BN_bn2mpi(this, &vch[0]);
245         if (vch.size() > 4)
246             vch[4] &= 0x7f;
247         uint256 n = 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];
250         return n;
251     }
252
253
254     void setvch(const std::vector<unsigned char>& vch)
255     {
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);
267     }
268
269     std::vector<unsigned char> getvch() const
270     {
271         unsigned int nSize = BN_bn2mpi(this, NULL);
272         if (nSize <= 4)
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());
278         return vch;
279     }
280
281     CBigNum& SetCompact(unsigned int nCompact)
282     {
283         unsigned int nSize = nCompact >> 24;
284         std::vector<unsigned char> vch(4 + nSize);
285         vch[3] = 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);
290         return *this;
291     }
292
293     unsigned int GetCompact() const
294     {
295         unsigned int nSize = BN_bn2mpi(this, NULL);
296         std::vector<unsigned char> vch(nSize);
297         nSize -= 4;
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);
303         return nCompact;
304     }
305
306     void SetHex(const std::string& str)
307     {
308         // skip 0x
309         const char* psz = str.c_str();
310         while (isspace(*psz))
311             psz++;
312         bool fNegative = false;
313         if (*psz == '-')
314         {
315             fNegative = true;
316             psz++;
317         }
318         if (psz[0] == '0' && tolower(psz[1]) == 'x')
319             psz += 2;
320         while (isspace(*psz))
321             psz++;
322
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 };
325         *this = 0;
326         while (isxdigit(*psz))
327         {
328             *this <<= 4;
329             int n = phexdigit[(unsigned char)*psz++];
330             *this += n;
331         }
332         if (fNegative)
333             *this = 0 - *this;
334     }
335
336     std::string ToString(int nBase=10) const
337     {
338         CAutoBN_CTX pctx;
339         CBigNum bnBase = nBase;
340         CBigNum bn0 = 0;
341         std::string str;
342         CBigNum bn = *this;
343         BN_set_negative(&bn, false);
344         CBigNum dv;
345         CBigNum rem;
346         if (BN_cmp(&bn, &bn0) == 0)
347             return "0";
348         while (BN_cmp(&bn, &bn0) > 0)
349         {
350             if (!BN_div(&dv, &rem, &bn, &bnBase, pctx))
351                 throw bignum_error("CBigNum::ToString() : BN_div failed");
352             bn = dv;
353             unsigned int c = rem.getulong();
354             str += "0123456789abcdef"[c];
355         }
356         if (BN_is_negative(this))
357             str += "-";
358         reverse(str.begin(), str.end());
359         return str;
360     }
361
362     std::string GetHex() const
363     {
364         return ToString(16);
365     }
366
367     unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
368     {
369         return ::GetSerializeSize(getvch(), nType, nVersion);
370     }
371
372     template<typename Stream>
373     void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
374     {
375         ::Serialize(s, getvch(), nType, nVersion);
376     }
377
378     template<typename Stream>
379     void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
380     {
381         std::vector<unsigned char> vch;
382         ::Unserialize(s, vch, nType, nVersion);
383         setvch(vch);
384     }
385
386
387     bool operator!() const
388     {
389         return BN_is_zero(this);
390     }
391
392     CBigNum& operator+=(const CBigNum& b)
393     {
394         if (!BN_add(this, this, &b))
395             throw bignum_error("CBigNum::operator+= : BN_add failed");
396         return *this;
397     }
398
399     CBigNum& operator-=(const CBigNum& b)
400     {
401         *this = *this - b;
402         return *this;
403     }
404
405     CBigNum& operator*=(const CBigNum& b)
406     {
407         CAutoBN_CTX pctx;
408         if (!BN_mul(this, this, &b, pctx))
409             throw bignum_error("CBigNum::operator*= : BN_mul failed");
410         return *this;
411     }
412
413     CBigNum& operator/=(const CBigNum& b)
414     {
415         *this = *this / b;
416         return *this;
417     }
418
419     CBigNum& operator%=(const CBigNum& b)
420     {
421         *this = *this % b;
422         return *this;
423     }
424
425     CBigNum& operator<<=(unsigned int shift)
426     {
427         if (!BN_lshift(this, this, shift))
428             throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
429         return *this;
430     }
431
432     CBigNum& operator>>=(unsigned int shift)
433     {
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
436         CBigNum a = 1;
437         a <<= shift;
438         if (BN_cmp(&a, this) > 0)
439         {
440             *this = 0;
441             return *this;
442         }
443
444         if (!BN_rshift(this, this, shift))
445             throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
446         return *this;
447     }
448
449
450     CBigNum& operator++()
451     {
452         // prefix operator
453         if (!BN_add(this, this, BN_value_one()))
454             throw bignum_error("CBigNum::operator++ : BN_add failed");
455         return *this;
456     }
457
458     const CBigNum operator++(int)
459     {
460         // postfix operator
461         const CBigNum ret = *this;
462         ++(*this);
463         return ret;
464     }
465
466     CBigNum& operator--()
467     {
468         // prefix operator
469         CBigNum r;
470         if (!BN_sub(&r, this, BN_value_one()))
471             throw bignum_error("CBigNum::operator-- : BN_sub failed");
472         *this = r;
473         return *this;
474     }
475
476     const CBigNum operator--(int)
477     {
478         // postfix operator
479         const CBigNum ret = *this;
480         --(*this);
481         return ret;
482     }
483
484
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);
488 };
489
490
491
492 inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
493 {
494     CBigNum r;
495     if (!BN_add(&r, &a, &b))
496         throw bignum_error("CBigNum::operator+ : BN_add failed");
497     return r;
498 }
499
500 inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
501 {
502     CBigNum r;
503     if (!BN_sub(&r, &a, &b))
504         throw bignum_error("CBigNum::operator- : BN_sub failed");
505     return r;
506 }
507
508 inline const CBigNum operator-(const CBigNum& a)
509 {
510     CBigNum r(a);
511     BN_set_negative(&r, !BN_is_negative(&r));
512     return r;
513 }
514
515 inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
516 {
517     CAutoBN_CTX pctx;
518     CBigNum r;
519     if (!BN_mul(&r, &a, &b, pctx))
520         throw bignum_error("CBigNum::operator* : BN_mul failed");
521     return r;
522 }
523
524 inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
525 {
526     CAutoBN_CTX pctx;
527     CBigNum r;
528     if (!BN_div(&r, NULL, &a, &b, pctx))
529         throw bignum_error("CBigNum::operator/ : BN_div failed");
530     return r;
531 }
532
533 inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
534 {
535     CAutoBN_CTX pctx;
536     CBigNum r;
537     if (!BN_mod(&r, &a, &b, pctx))
538         throw bignum_error("CBigNum::operator% : BN_div failed");
539     return r;
540 }
541
542 inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
543 {
544     CBigNum r;
545     if (!BN_lshift(&r, &a, shift))
546         throw bignum_error("CBigNum:operator<< : BN_lshift failed");
547     return r;
548 }
549
550 inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
551 {
552     CBigNum r = a;
553     r >>= shift;
554     return r;
555 }
556
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); }
563
564 #endif