]> Git Repo - VerusCoin.git/blame - src/bignum.h
Cleanup code using forward declarations.
[VerusCoin.git] / src / bignum.h
CommitLineData
8bd66202 1// Copyright (c) 2009-2010 Satoshi Nakamoto
db0e8ccd 2// Copyright (c) 2009-2013 The Bitcoin developers
8bd66202 3// Distributed under the MIT/X11 software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
51ed9ec9 5
223b6f1b
WL
6#ifndef BITCOIN_BIGNUM_H
7#define BITCOIN_BIGNUM_H
8bd66202 8
51ed9ec9
BD
9#include "serialize.h"
10#include "uint256.h"
11#include "version.h"
12
8bd66202 13#include <stdexcept>
51ed9ec9 14#include <stdint.h>
8bd66202 15#include <vector>
8bd66202 16
51ed9ec9 17#include <openssl/bn.h>
8bd66202 18
6b8de05d 19/** Errors thrown by the bignum class */
8bd66202
GA
20class bignum_error : public std::runtime_error
21{
22public:
23 explicit bignum_error(const std::string& str) : std::runtime_error(str) {}
24};
25
26
6b8de05d 27/** RAII encapsulated BN_CTX (OpenSSL bignum context) */
8bd66202
GA
28class CAutoBN_CTX
29{
30protected:
31 BN_CTX* pctx;
32 BN_CTX* operator=(BN_CTX* pnew) { return pctx = pnew; }
33
34public:
35 CAutoBN_CTX()
36 {
37 pctx = BN_CTX_new();
38 if (pctx == NULL)
39 throw bignum_error("CAutoBN_CTX : BN_CTX_new() returned NULL");
40 }
41
42 ~CAutoBN_CTX()
43 {
44 if (pctx != NULL)
45 BN_CTX_free(pctx);
46 }
47
48 operator BN_CTX*() { return pctx; }
49 BN_CTX& operator*() { return *pctx; }
50 BN_CTX** operator&() { return &pctx; }
51 bool operator!() { return (pctx == NULL); }
52};
53
54
7e05b972 55/** C++ wrapper for BIGNUM (OpenSSL bignum) */
8bd66202
GA
56class CBigNum : public BIGNUM
57{
58public:
59 CBigNum()
60 {
61 BN_init(this);
62 }
63
64 CBigNum(const CBigNum& b)
65 {
66 BN_init(this);
67 if (!BN_copy(this, &b))
68 {
69 BN_clear_free(this);
70 throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_copy failed");
71 }
72 }
73
74 CBigNum& operator=(const CBigNum& b)
75 {
76 if (!BN_copy(this, &b))
77 throw bignum_error("CBigNum::operator= : BN_copy failed");
78 return (*this);
79 }
80
81 ~CBigNum()
82 {
83 BN_clear_free(this);
84 }
85
8c8e8c2e 86 //CBigNum(char n) is not portable. Use 'signed char' or 'unsigned char'.
51ed9ec9
BD
87 CBigNum(signed char n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
88 CBigNum(short n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
89 CBigNum(int n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
90 CBigNum(long n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); }
91 CBigNum(long long n) { BN_init(this); setint64(n); }
92 CBigNum(unsigned char n) { BN_init(this); setulong(n); }
93 CBigNum(unsigned short n) { BN_init(this); setulong(n); }
94 CBigNum(unsigned int n) { BN_init(this); setulong(n); }
95 CBigNum(unsigned long n) { BN_init(this); setulong(n); }
96 CBigNum(unsigned long long n) { BN_init(this); setuint64(n); }
97 explicit CBigNum(uint256 n) { BN_init(this); setuint256(n); }
8bd66202
GA
98
99 explicit CBigNum(const std::vector<unsigned char>& vch)
100 {
101 BN_init(this);
102 setvch(vch);
103 }
104
105 void setulong(unsigned long n)
106 {
107 if (!BN_set_word(this, n))
108 throw bignum_error("CBigNum conversion from unsigned long : BN_set_word failed");
109 }
110
111 unsigned long getulong() const
112 {
113 return BN_get_word(this);
114 }
115
116 unsigned int getuint() const
117 {
118 return BN_get_word(this);
119 }
120
121 int getint() const
122 {
123 unsigned long n = BN_get_word(this);
124 if (!BN_is_negative(this))
1d8c7a95 125 return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : n);
8bd66202 126 else
1d8c7a95 127 return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::min() : -(int)n);
8bd66202
GA
128 }
129
51ed9ec9 130 void setint64(int64_t sn)
8bd66202 131 {
fe78c9ae 132 unsigned char pch[sizeof(sn) + 6];
8bd66202 133 unsigned char* p = pch + 4;
fe78c9ae 134 bool fNegative;
51ed9ec9 135 uint64_t n;
fe78c9ae 136
51ed9ec9 137 if (sn < (int64_t)0)
8bd66202 138 {
f0bf5fb2 139 // Since the minimum signed integer cannot be represented as positive so long as its type is signed,
140 // and it's not well-defined what happens if you make it unsigned before negating it,
141 // we instead increment the negative integer by 1, convert it, then increment the (now positive) unsigned integer by 1 to compensate
0f5a2a82
LD
142 n = -(sn + 1);
143 ++n;
8bd66202 144 fNegative = true;
fe78c9ae
RC
145 } else {
146 n = sn;
147 fNegative = false;
8bd66202 148 }
fe78c9ae 149
8bd66202
GA
150 bool fLeadingZeroes = true;
151 for (int i = 0; i < 8; i++)
152 {
153 unsigned char c = (n >> 56) & 0xff;
154 n <<= 8;
155 if (fLeadingZeroes)
156 {
157 if (c == 0)
158 continue;
159 if (c & 0x80)
160 *p++ = (fNegative ? 0x80 : 0);
161 else if (fNegative)
162 c |= 0x80;
163 fLeadingZeroes = false;
164 }
165 *p++ = c;
166 }
167 unsigned int nSize = p - (pch + 4);
168 pch[0] = (nSize >> 24) & 0xff;
169 pch[1] = (nSize >> 16) & 0xff;
170 pch[2] = (nSize >> 8) & 0xff;
171 pch[3] = (nSize) & 0xff;
172 BN_mpi2bn(pch, p - pch, this);
173 }
174
51ed9ec9 175 void setuint64(uint64_t n)
8bd66202
GA
176 {
177 unsigned char pch[sizeof(n) + 6];
178 unsigned char* p = pch + 4;
179 bool fLeadingZeroes = true;
180 for (int i = 0; i < 8; i++)
181 {
182 unsigned char c = (n >> 56) & 0xff;
183 n <<= 8;
184 if (fLeadingZeroes)
185 {
186 if (c == 0)
187 continue;
188 if (c & 0x80)
189 *p++ = 0;
190 fLeadingZeroes = false;
191 }
192 *p++ = c;
193 }
194 unsigned int nSize = p - (pch + 4);
195 pch[0] = (nSize >> 24) & 0xff;
196 pch[1] = (nSize >> 16) & 0xff;
197 pch[2] = (nSize >> 8) & 0xff;
198 pch[3] = (nSize) & 0xff;
199 BN_mpi2bn(pch, p - pch, this);
200 }
201
202 void setuint256(uint256 n)
203 {
204 unsigned char pch[sizeof(n) + 6];
205 unsigned char* p = pch + 4;
206 bool fLeadingZeroes = true;
207 unsigned char* pbegin = (unsigned char*)&n;
208 unsigned char* psrc = pbegin + sizeof(n);
209 while (psrc != pbegin)
210 {
211 unsigned char c = *(--psrc);
212 if (fLeadingZeroes)
213 {
214 if (c == 0)
215 continue;
216 if (c & 0x80)
217 *p++ = 0;
218 fLeadingZeroes = false;
219 }
220 *p++ = c;
221 }
222 unsigned int nSize = p - (pch + 4);
223 pch[0] = (nSize >> 24) & 0xff;
224 pch[1] = (nSize >> 16) & 0xff;
225 pch[2] = (nSize >> 8) & 0xff;
226 pch[3] = (nSize >> 0) & 0xff;
227 BN_mpi2bn(pch, p - pch, this);
228 }
229
1657c4bc 230 uint256 getuint256() const
8bd66202
GA
231 {
232 unsigned int nSize = BN_bn2mpi(this, NULL);
233 if (nSize < 4)
234 return 0;
235 std::vector<unsigned char> vch(nSize);
236 BN_bn2mpi(this, &vch[0]);
237 if (vch.size() > 4)
238 vch[4] &= 0x7f;
239 uint256 n = 0;
faf705a4 240 for (unsigned int i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--)
8bd66202
GA
241 ((unsigned char*)&n)[i] = vch[j];
242 return n;
243 }
244
245 void setvch(const std::vector<unsigned char>& vch)
246 {
247 std::vector<unsigned char> vch2(vch.size() + 4);
248 unsigned int nSize = vch.size();
a9d3af88
DH
249 // BIGNUM's byte stream format expects 4 bytes of
250 // big endian size data info at the front
8bd66202
GA
251 vch2[0] = (nSize >> 24) & 0xff;
252 vch2[1] = (nSize >> 16) & 0xff;
253 vch2[2] = (nSize >> 8) & 0xff;
254 vch2[3] = (nSize >> 0) & 0xff;
a9d3af88 255 // swap data to big endian
8bd66202
GA
256 reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4);
257 BN_mpi2bn(&vch2[0], vch2.size(), this);
258 }
259
260 std::vector<unsigned char> getvch() const
261 {
262 unsigned int nSize = BN_bn2mpi(this, NULL);
a06113b0 263 if (nSize <= 4)
8bd66202
GA
264 return std::vector<unsigned char>();
265 std::vector<unsigned char> vch(nSize);
266 BN_bn2mpi(this, &vch[0]);
267 vch.erase(vch.begin(), vch.begin() + 4);
268 reverse(vch.begin(), vch.end());
269 return vch;
270 }
271
48a10a37
CR
272 // The "compact" format is a representation of a whole
273 // number N using an unsigned 32bit number similar to a
274 // floating point format.
275 // The most significant 8 bits are the unsigned exponent of base 256.
276 // This exponent can be thought of as "number of bytes of N".
277 // The lower 23 bits are the mantissa.
278 // Bit number 24 (0x800000) represents the sign of N.
279 // N = (-1^sign) * mantissa * 256^(exponent-3)
280 //
281 // Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn().
282 // MPI uses the most significant bit of the first byte as sign.
283 // Thus 0x1234560000 is compact (0x05123456)
284 // and 0xc0de000000 is compact (0x0600c0de)
285 // (0x05c0de00) would be -0x40de000000
286 //
287 // Bitcoin only uses this "compact" format for encoding difficulty
288 // targets, which are unsigned 256bit quantities. Thus, all the
289 // complexities of the sign bit and using base 256 are probably an
290 // implementation accident.
291 //
292 // This implementation directly uses shifts instead of going
293 // through an intermediate MPI representation.
8bd66202
GA
294 CBigNum& SetCompact(unsigned int nCompact)
295 {
296 unsigned int nSize = nCompact >> 24;
48a10a37
CR
297 bool fNegative =(nCompact & 0x00800000) != 0;
298 unsigned int nWord = nCompact & 0x007fffff;
299 if (nSize <= 3)
300 {
301 nWord >>= 8*(3-nSize);
302 BN_set_word(this, nWord);
303 }
304 else
305 {
306 BN_set_word(this, nWord);
307 BN_lshift(this, this, 8*(nSize-3));
308 }
309 BN_set_negative(this, fNegative);
8bd66202
GA
310 return *this;
311 }
312
313 unsigned int GetCompact() const
314 {
48a10a37
CR
315 unsigned int nSize = BN_num_bytes(this);
316 unsigned int nCompact = 0;
317 if (nSize <= 3)
318 nCompact = BN_get_word(this) << 8*(3-nSize);
319 else
320 {
321 CBigNum bn;
322 BN_rshift(&bn, this, 8*(nSize-3));
323 nCompact = BN_get_word(&bn);
324 }
325 // The 0x00800000 bit denotes the sign.
326 // Thus, if it is already set, divide the mantissa by 256 and increase the exponent.
327 if (nCompact & 0x00800000)
328 {
329 nCompact >>= 8;
330 nSize++;
331 }
332 nCompact |= nSize << 24;
333 nCompact |= (BN_is_negative(this) ? 0x00800000 : 0);
8bd66202
GA
334 return nCompact;
335 }
336
337 void SetHex(const std::string& str)
338 {
339 // skip 0x
340 const char* psz = str.c_str();
341 while (isspace(*psz))
342 psz++;
343 bool fNegative = false;
344 if (*psz == '-')
345 {
346 fNegative = true;
347 psz++;
348 }
349 if (psz[0] == '0' && tolower(psz[1]) == 'x')
350 psz += 2;
351 while (isspace(*psz))
352 psz++;
353
354 // hex string to bignum
8bd66202 355 *this = 0;
f171ec0c
OL
356 int n;
357 while ((n = HexDigit(*psz)) != -1)
8bd66202
GA
358 {
359 *this <<= 4;
8bd66202 360 *this += n;
f171ec0c 361 ++psz;
8bd66202
GA
362 }
363 if (fNegative)
364 *this = 0 - *this;
365 }
366
367 std::string ToString(int nBase=10) const
368 {
369 CAutoBN_CTX pctx;
370 CBigNum bnBase = nBase;
371 CBigNum bn0 = 0;
223b6f1b 372 std::string str;
8bd66202
GA
373 CBigNum bn = *this;
374 BN_set_negative(&bn, false);
375 CBigNum dv;
376 CBigNum rem;
377 if (BN_cmp(&bn, &bn0) == 0)
378 return "0";
379 while (BN_cmp(&bn, &bn0) > 0)
380 {
381 if (!BN_div(&dv, &rem, &bn, &bnBase, pctx))
382 throw bignum_error("CBigNum::ToString() : BN_div failed");
383 bn = dv;
384 unsigned int c = rem.getulong();
385 str += "0123456789abcdef"[c];
386 }
387 if (BN_is_negative(this))
388 str += "-";
389 reverse(str.begin(), str.end());
390 return str;
391 }
392
393 std::string GetHex() const
394 {
395 return ToString(16);
396 }
397
f8ded588 398 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
8bd66202
GA
399 {
400 return ::GetSerializeSize(getvch(), nType, nVersion);
401 }
402
403 template<typename Stream>
f8ded588 404 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
8bd66202
GA
405 {
406 ::Serialize(s, getvch(), nType, nVersion);
407 }
408
409 template<typename Stream>
f8ded588 410 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
8bd66202 411 {
223b6f1b 412 std::vector<unsigned char> vch;
8bd66202
GA
413 ::Unserialize(s, vch, nType, nVersion);
414 setvch(vch);
415 }
416
417
418 bool operator!() const
419 {
420 return BN_is_zero(this);
421 }
422
423 CBigNum& operator+=(const CBigNum& b)
424 {
425 if (!BN_add(this, this, &b))
426 throw bignum_error("CBigNum::operator+= : BN_add failed");
427 return *this;
428 }
429
430 CBigNum& operator-=(const CBigNum& b)
431 {
432 *this = *this - b;
433 return *this;
434 }
435
436 CBigNum& operator*=(const CBigNum& b)
437 {
438 CAutoBN_CTX pctx;
439 if (!BN_mul(this, this, &b, pctx))
440 throw bignum_error("CBigNum::operator*= : BN_mul failed");
441 return *this;
442 }
443
444 CBigNum& operator/=(const CBigNum& b)
445 {
446 *this = *this / b;
447 return *this;
448 }
449
450 CBigNum& operator%=(const CBigNum& b)
451 {
452 *this = *this % b;
453 return *this;
454 }
455
456 CBigNum& operator<<=(unsigned int shift)
457 {
458 if (!BN_lshift(this, this, shift))
459 throw bignum_error("CBigNum:operator<<= : BN_lshift failed");
460 return *this;
461 }
462
463 CBigNum& operator>>=(unsigned int shift)
464 {
73aa2626 465 // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number
a7f82808 466 // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL
73aa2626
SN
467 CBigNum a = 1;
468 a <<= shift;
469 if (BN_cmp(&a, this) > 0)
470 {
471 *this = 0;
472 return *this;
473 }
474
8bd66202
GA
475 if (!BN_rshift(this, this, shift))
476 throw bignum_error("CBigNum:operator>>= : BN_rshift failed");
477 return *this;
478 }
479
480
481 CBigNum& operator++()
482 {
483 // prefix operator
484 if (!BN_add(this, this, BN_value_one()))
485 throw bignum_error("CBigNum::operator++ : BN_add failed");
486 return *this;
487 }
488
489 const CBigNum operator++(int)
490 {
491 // postfix operator
492 const CBigNum ret = *this;
493 ++(*this);
494 return ret;
495 }
496
497 CBigNum& operator--()
498 {
499 // prefix operator
500 CBigNum r;
501 if (!BN_sub(&r, this, BN_value_one()))
502 throw bignum_error("CBigNum::operator-- : BN_sub failed");
503 *this = r;
504 return *this;
505 }
506
507 const CBigNum operator--(int)
508 {
509 // postfix operator
510 const CBigNum ret = *this;
511 --(*this);
512 return ret;
513 }
514
515
516 friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b);
517 friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b);
518 friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b);
519};
520
521
522
523inline const CBigNum operator+(const CBigNum& a, const CBigNum& b)
524{
525 CBigNum r;
526 if (!BN_add(&r, &a, &b))
527 throw bignum_error("CBigNum::operator+ : BN_add failed");
528 return r;
529}
530
531inline const CBigNum operator-(const CBigNum& a, const CBigNum& b)
532{
533 CBigNum r;
534 if (!BN_sub(&r, &a, &b))
535 throw bignum_error("CBigNum::operator- : BN_sub failed");
536 return r;
537}
538
539inline const CBigNum operator-(const CBigNum& a)
540{
541 CBigNum r(a);
542 BN_set_negative(&r, !BN_is_negative(&r));
543 return r;
544}
545
546inline const CBigNum operator*(const CBigNum& a, const CBigNum& b)
547{
548 CAutoBN_CTX pctx;
549 CBigNum r;
550 if (!BN_mul(&r, &a, &b, pctx))
551 throw bignum_error("CBigNum::operator* : BN_mul failed");
552 return r;
553}
554
555inline const CBigNum operator/(const CBigNum& a, const CBigNum& b)
556{
557 CAutoBN_CTX pctx;
558 CBigNum r;
559 if (!BN_div(&r, NULL, &a, &b, pctx))
560 throw bignum_error("CBigNum::operator/ : BN_div failed");
561 return r;
562}
563
564inline const CBigNum operator%(const CBigNum& a, const CBigNum& b)
565{
566 CAutoBN_CTX pctx;
567 CBigNum r;
568 if (!BN_mod(&r, &a, &b, pctx))
569 throw bignum_error("CBigNum::operator% : BN_div failed");
570 return r;
571}
572
573inline const CBigNum operator<<(const CBigNum& a, unsigned int shift)
574{
575 CBigNum r;
576 if (!BN_lshift(&r, &a, shift))
577 throw bignum_error("CBigNum:operator<< : BN_lshift failed");
578 return r;
579}
580
581inline const CBigNum operator>>(const CBigNum& a, unsigned int shift)
582{
73aa2626
SN
583 CBigNum r = a;
584 r >>= shift;
8bd66202
GA
585 return r;
586}
587
588inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) == 0); }
589inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) != 0); }
590inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) <= 0); }
591inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) >= 0); }
592inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) < 0); }
593inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) > 0); }
223b6f1b
WL
594
595#endif
This page took 0.181903 seconds and 4 git commands to generate.