indutny / bn.js

BigNum in pure javascript
MIT License
1.19k stars 150 forks source link

bn.js

BigNum in pure javascript

Build Status

Install

npm install --save bn.js

Usage

const BN = require('bn.js');

var a = new BN('dead', 16);
var b = new BN('101010', 2);

var res = a.add(b);
console.log(res.toString(10));  // 57047

Note: decimals are not supported in this library.

Sponsors

Scout APM My Open Source work is supported by Scout APM and other sponsors.

Notation

Prefixes

There are several prefixes to instructions that affect the way they work. Here is the list of them in the order of appearance in the function name:

Postfixes

Examples

Instructions

Prefixes/postfixes are put in parens at the end of the line. endian - could be either le (little-endian) or be (big-endian).

Utilities

Arithmetics

Bit operations

Reduction

Fast reduction

When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like Montgomery multiplication, or using special algorithm for Mersenne Prime.

Reduction context

To enable this trick one should create a reduction context:

var red = BN.red(num);

where num is just a BN instance.

Or:

var red = BN.red(primeName);

Where primeName is either of these Mersenne Primes:

Or:

var red = BN.mont(num);

To reduce numbers with Montgomery trick. .mont() is generally faster than .red(num), but slower than BN.red(primeName).

Converting numbers

Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should:

Here is how one may convert numbers to red:

var redA = a.toRed(red);

Where red is a reduction context created using instructions above

Here is how to convert them back:

var a = redA.fromRed();

Red instructions

Most of the instructions from the very start of this readme have their counterparts in red context:

Number Size

Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers.

LICENSE

This software is licensed under the MIT License.