You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

221 lines
7.1 KiB

4 years ago
  1. # <img src="./logo.png" alt="bn.js" width="160" height="160" />
  2. > BigNum in pure javascript
  3. [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js)
  4. ## Install
  5. `npm install --save bn.js`
  6. ## Usage
  7. ```js
  8. const BN = require('bn.js');
  9. var a = new BN('dead', 16);
  10. var b = new BN('101010', 2);
  11. var res = a.add(b);
  12. console.log(res.toString(10)); // 57047
  13. ```
  14. **Note**: decimals are not supported in this library.
  15. ## Notation
  16. ### Prefixes
  17. There are several prefixes to instructions that affect the way the work. Here
  18. is the list of them in the order of appearance in the function name:
  19. * `i` - perform operation in-place, storing the result in the host object (on
  20. which the method was invoked). Might be used to avoid number allocation costs
  21. * `u` - unsigned, ignore the sign of operands when performing operation, or
  22. always return positive value. Second case applies to reduction operations
  23. like `mod()`. In such cases if the result will be negative - modulo will be
  24. added to the result to make it positive
  25. ### Postfixes
  26. The only available postfix at the moment is:
  27. * `n` - which means that the argument of the function must be a plain JavaScript
  28. Number. Decimals are not supported.
  29. ### Examples
  30. * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a`
  31. * `a.umod(b)` - reduce `a` modulo `b`, returning positive value
  32. * `a.iushln(13)` - shift bits of `a` left by 13
  33. ## Instructions
  34. Prefixes/postfixes are put in parens at the of the line. `endian` - could be
  35. either `le` (little-endian) or `be` (big-endian).
  36. ### Utilities
  37. * `a.clone()` - clone number
  38. * `a.toString(base, length)` - convert to base-string and pad with zeroes
  39. * `a.toNumber()` - convert to Javascript Number (limited to 53 bits)
  40. * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`)
  41. * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero
  42. pad to length, throwing if already exceeding
  43. * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`,
  44. which must behave like an `Array`
  45. * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For
  46. compatibility with browserify and similar tools, use this instead:
  47. `a.toArrayLike(Buffer, endian, length)`
  48. * `a.bitLength()` - get number of bits occupied
  49. * `a.zeroBits()` - return number of less-significant consequent zero bits
  50. (example: `1010000` has 4 zero bits)
  51. * `a.byteLength()` - return number of bytes occupied
  52. * `a.isNeg()` - true if the number is negative
  53. * `a.isEven()` - no comments
  54. * `a.isOdd()` - no comments
  55. * `a.isZero()` - no comments
  56. * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b)
  57. depending on the comparison result (`ucmp`, `cmpn`)
  58. * `a.lt(b)` - `a` less than `b` (`n`)
  59. * `a.lte(b)` - `a` less than or equals `b` (`n`)
  60. * `a.gt(b)` - `a` greater than `b` (`n`)
  61. * `a.gte(b)` - `a` greater than or equals `b` (`n`)
  62. * `a.eq(b)` - `a` equals `b` (`n`)
  63. * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width
  64. * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width
  65. * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance
  66. ### Arithmetics
  67. * `a.neg()` - negate sign (`i`)
  68. * `a.abs()` - absolute value (`i`)
  69. * `a.add(b)` - addition (`i`, `n`, `in`)
  70. * `a.sub(b)` - subtraction (`i`, `n`, `in`)
  71. * `a.mul(b)` - multiply (`i`, `n`, `in`)
  72. * `a.sqr()` - square (`i`)
  73. * `a.pow(b)` - raise `a` to the power of `b`
  74. * `a.div(b)` - divide (`divn`, `idivn`)
  75. * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`)
  76. * `a.divRound(b)` - rounded division
  77. ### Bit operations
  78. * `a.or(b)` - or (`i`, `u`, `iu`)
  79. * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced
  80. with `andn` in future)
  81. * `a.xor(b)` - xor (`i`, `u`, `iu`)
  82. * `a.setn(b)` - set specified bit to `1`
  83. * `a.shln(b)` - shift left (`i`, `u`, `iu`)
  84. * `a.shrn(b)` - shift right (`i`, `u`, `iu`)
  85. * `a.testn(b)` - test if specified bit is set
  86. * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`)
  87. * `a.bincn(b)` - add `1 << b` to the number
  88. * `a.notn(w)` - not (for the width specified by `w`) (`i`)
  89. ### Reduction
  90. * `a.gcd(b)` - GCD
  91. * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`)
  92. * `a.invm(b)` - inverse `a` modulo `b`
  93. ## Fast reduction
  94. When doing lots of reductions using the same modulo, it might be beneficial to
  95. use some tricks: like [Montgomery multiplication][0], or using special algorithm
  96. for [Mersenne Prime][1].
  97. ### Reduction context
  98. To enable this tricks one should create a reduction context:
  99. ```js
  100. var red = BN.red(num);
  101. ```
  102. where `num` is just a BN instance.
  103. Or:
  104. ```js
  105. var red = BN.red(primeName);
  106. ```
  107. Where `primeName` is either of these [Mersenne Primes][1]:
  108. * `'k256'`
  109. * `'p224'`
  110. * `'p192'`
  111. * `'p25519'`
  112. Or:
  113. ```js
  114. var red = BN.mont(num);
  115. ```
  116. To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than
  117. `.red(num)`, but slower than `BN.red(primeName)`.
  118. ### Converting numbers
  119. Before performing anything in reduction context - numbers should be converted
  120. to it. Usually, this means that one should:
  121. * Convert inputs to reducted ones
  122. * Operate on them in reduction context
  123. * Convert outputs back from the reduction context
  124. Here is how one may convert numbers to `red`:
  125. ```js
  126. var redA = a.toRed(red);
  127. ```
  128. Where `red` is a reduction context created using instructions above
  129. Here is how to convert them back:
  130. ```js
  131. var a = redA.fromRed();
  132. ```
  133. ### Red instructions
  134. Most of the instructions from the very start of this readme have their
  135. counterparts in red context:
  136. * `a.redAdd(b)`, `a.redIAdd(b)`
  137. * `a.redSub(b)`, `a.redISub(b)`
  138. * `a.redShl(num)`
  139. * `a.redMul(b)`, `a.redIMul(b)`
  140. * `a.redSqr()`, `a.redISqr()`
  141. * `a.redSqrt()` - square root modulo reduction context's prime
  142. * `a.redInvm()` - modular inverse of the number
  143. * `a.redNeg()`
  144. * `a.redPow(b)` - modular exponentiation
  145. ## LICENSE
  146. This software is licensed under the MIT License.
  147. Copyright Fedor Indutny, 2015.
  148. Permission is hereby granted, free of charge, to any person obtaining a
  149. copy of this software and associated documentation files (the
  150. "Software"), to deal in the Software without restriction, including
  151. without limitation the rights to use, copy, modify, merge, publish,
  152. distribute, sublicense, and/or sell copies of the Software, and to permit
  153. persons to whom the Software is furnished to do so, subject to the
  154. following conditions:
  155. The above copyright notice and this permission notice shall be included
  156. in all copies or substantial portions of the Software.
  157. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  158. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  159. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  160. NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  161. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  162. OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  163. USE OR OTHER DEALINGS IN THE SOFTWARE.
  164. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication
  165. [1]: https://en.wikipedia.org/wiki/Mersenne_prime