• Stars
    star
    1,171
  • Rank 38,257 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

BigNum in pure javascript

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:

  • i - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs
  • u - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like mod(). In such cases if the result will be negative - modulo will be added to the result to make it positive

Postfixes

  • n - the argument of the function must be a plain JavaScript Number. Decimals are not supported. The number passed must be smaller than 0x4000000 (67_108_864). Otherwise, an error is thrown.
  • rn - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported.

Examples

  • a.iadd(b) - perform addition on a and b, storing the result in a
  • a.umod(b) - reduce a modulo b, returning positive value
  • a.iushln(13) - shift bits of a left by 13

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

  • a.clone() - clone number
  • a.toString(base, length) - convert to base-string and pad with zeroes
  • a.toNumber() - convert to Javascript Number (limited to 53 bits)
  • a.toJSON() - convert to JSON compatible hex string (alias of toString(16))
  • a.toArray(endian, length) - convert to byte Array, and optionally zero pad to length, throwing if already exceeding
  • a.toArrayLike(type, endian, length) - convert to an instance of type, which must behave like an Array
  • a.toBuffer(endian, length) - convert to Node.js Buffer (if available). length in bytes. For compatibility with browserify and similar tools, use this instead: a.toArrayLike(Buffer, endian, length)
  • a.bitLength() - get number of bits occupied
  • a.zeroBits() - return number of less-significant consequent zero bits (example: 1010000 has 4 zero bits)
  • a.byteLength() - return number of bytes occupied
  • a.isNeg() - true if the number is negative
  • a.isEven() - no comments
  • a.isOdd() - no comments
  • a.isZero() - no comments
  • a.cmp(b) - compare numbers and return -1 (a < b), 0 (a == b), or 1 (a > b) depending on the comparison result (ucmp, cmpn)
  • a.lt(b) - a less than b (n)
  • a.lte(b) - a less than or equals b (n)
  • a.gt(b) - a greater than b (n)
  • a.gte(b) - a greater than or equals b (n)
  • a.eq(b) - a equals b (n)
  • a.toTwos(width) - convert to two's complement representation, where width is bit width
  • a.fromTwos(width) - convert from two's complement representation, where width is the bit width
  • BN.isBN(object) - returns true if the supplied object is a BN.js instance
  • BN.max(a, b) - return a if a bigger than b
  • BN.min(a, b) - return a if a less than b

Arithmetics

  • a.neg() - negate sign (i)
  • a.abs() - absolute value (i)
  • a.add(b) - addition (i, n, in)
  • a.sub(b) - subtraction (i, n, in)
  • a.mul(b) - multiply (i, n, in)
  • a.sqr() - square (i)
  • a.pow(b) - raise a to the power of b
  • a.div(b) - divide (divn, idivn)
  • a.mod(b) - reduct (u, n) (but no umodn)
  • a.divmod(b) - quotient and modulus obtained by dividing
  • a.divRound(b) - rounded division

Bit operations

  • a.or(b) - or (i, u, iu)
  • a.and(b) - and (i, u, iu, andln) (NOTE: andln is going to be replaced with andn in future)
  • a.xor(b) - xor (i, u, iu)
  • a.setn(b, value) - set specified bit to value
  • a.shln(b) - shift left (i, u, iu)
  • a.shrn(b) - shift right (i, u, iu)
  • a.testn(b) - test if specified bit is set
  • a.maskn(b) - clear bits with indexes higher or equal to b (i)
  • a.bincn(b) - add 1 << b to the number
  • a.notn(w) - not (for the width specified by w) (i)

Reduction

  • a.gcd(b) - GCD
  • a.egcd(b) - Extended GCD results ({ a: ..., b: ..., gcd: ... })
  • a.invm(b) - inverse a modulo b

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:

  • 'k256'
  • 'p224'
  • 'p192'
  • 'p25519'

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:

  • Convert inputs to reducted ones
  • Operate on them in reduction context
  • Convert outputs back from the reduction context

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:

  • a.redAdd(b), a.redIAdd(b)
  • a.redSub(b), a.redISub(b)
  • a.redShl(num)
  • a.redMul(b), a.redIMul(b)
  • a.redSqr(), a.redISqr()
  • a.redSqrt() - square root modulo reduction context's prime
  • a.redInvm() - modular inverse of the number
  • a.redNeg()
  • a.redPow(b) - modular exponentiation

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.

More Repositories

1

elliptic

Fast Elliptic Curve Cryptography in plain javascript
JavaScript
1,583
star
2

node-ip

IP address tools for node.js
JavaScript
1,455
star
3

sticky-session

Sticky session balancer based on a `cluster` module
JavaScript
965
star
4

webpack-common-shake

CommonJS Tree Shaker plugin for WebPack
JavaScript
914
star
5

bud

**NOT MAINTAINED** Bud - The TLS Terminator
C
454
star
6

heartbleed

Extracting server private key using Heartbleed OpenSSL vulnerability.
C++
391
star
7

hash.js

Hash functions in pure javascript
JavaScript
312
star
8

fft.js

The fastest JS Radix-4/Radix-2 FFT implementation
JavaScript
228
star
9

dht.js

True bittorrent DHT in javascript
JavaScript
215
star
10

vock

VoIP on node.js
C++
182
star
11

candor

Experimental VM for a `Candor` language
C++
176
star
12

asn1.js

ASN.1 Decoder/Encoder/DSL
JavaScript
174
star
13

gyp.js

Feature-reduced port of GYP to JavaScript
JavaScript
160
star
14

common-shake

CommonJS Tree Shaker API
JavaScript
149
star
15

node-nat-upnp

NAT port mapping via UPnP
JavaScript
147
star
16

caine

Friendly butler
JavaScript
139
star
17

proof-of-work

Proof of Work with SHA256 and Bloom filter
JavaScript
112
star
18

node-index

Append-only B+ Tree index for node.js
CoffeeScript
85
star
19

wasm-jit

WebAssembly JIT
JavaScript
84
star
20

ocsp

OCSP Stapling/Checking for node.js
JavaScript
83
star
21

gradtype

WIP
Python
67
star
22

keychair

Chair and the Key
JavaScript
65
star
23

uv_link_t

Chainable libuv streams
C
63
star
24

vock-server

Server for Vock VoIP
JavaScript
58
star
25

tlsnappy

TLS, but faster!
C++
57
star
26

uv_ssl_t

Chainable SSL implementation for libuv
C
57
star
27

mmap.js

Working mmap bindings for node.js
C++
56
star
28

bitcode

Generate binary LLVM-compatible bitcode from JS
TypeScript
56
star
29

vote.wdgt

Free Proof-of-Work API for fancy Vote Counting widgets
JavaScript
54
star
30

deadbolt

Autoreleasing locks for node.js
JavaScript
54
star
31

node-netroute

Route table bindings for node.js
C++
48
star
32

wasm-ast

WebAssembly AST Parser
JavaScript
47
star
33

git-secure-tag

Secure git tag signing
JavaScript
46
star
34

heatline

Source-annotating profiler for node.js
JavaScript
46
star
35

home

My homepage
JavaScript
46
star
36

disasm

JS Disassembler
JavaScript
45
star
37

json-depth-stream

Streaming JSON parser with depth-limited auxiliary data
JavaScript
43
star
38

self-signed

Generate Self-Signed certificates in browser
JavaScript
41
star
39

hpack.js

HPACK implementation in pure JavaScript
JavaScript
39
star
40

tls.js

TLS Protocol implementation for node.js
JavaScript
39
star
41

spoon

CPS Style for JavaScript, JS->CFG->JS Transpiler
JavaScript
37
star
42

entropoetry

Entropic Poetry
JavaScript
36
star
43

dns.js

Plain javascript dns
JavaScript
36
star
44

bthread

BThread - Thread messaging and blog posting on bitcoin blockchain
JavaScript
33
star
45

bplus

Append-only B+ tree implemented in C
C
31
star
46

promise-waitlist

Promise-based Wait List for your apps
JavaScript
31
star
47

json-pipeline

JSON pipeline for a hypothetical compiler
JavaScript
30
star
48

satoshi

Satoshi Conspiracy
JavaScript
30
star
49

bar

Node.js framework for building large modular web applications.
JavaScript
29
star
50

breakdown

Trace outgoing http requests for an http server and track the time spent doing CPU intensive workload during each request.
JavaScript
29
star
51

isodrive

Isometric game engine
JavaScript
28
star
52

miller-rabin

JavaScript
28
star
53

des.js

DES algorithm
JavaScript
27
star
54

pripub

RSA encryption for node.js
C++
25
star
55

minimalistic-crypto-utils

Minimalistic utils for JS-only crypto
JavaScript
24
star
56

macho

Mach-O parser for node.js
JavaScript
23
star
57

wasm-cli

CLI for wasm-jit
JavaScript
23
star
58

node-balancer

Node load balancer
JavaScript
22
star
59

nTPL

node.js Templating system
JavaScript
22
star
60

node.gzip

!!!!!! Not-supported !!!!!!!
JavaScript
22
star
61

uv_http_t

Chainable HTTP Server implementation
C
21
star
62

hmac-drbg

JS-only Hmac DRBG implementation
JavaScript
20
star
63

hash-cracker

V8 Hash Seed timing attack
C
20
star
64

json-gpg

JSON GPG sign and verify
JavaScript
20
star
65

dukhttp

C
19
star
66

bulk-gcd

Bulk GCD in Rust
Rust
19
star
67

brorand

JavaScript
19
star
68

ninja.js

Naive `ninja` implementation
JavaScript
18
star
69

escape.js

Using escape analysis to enforce heap value lifetime in JS
18
star
70

bitcode-builder

API for building typed CFG for bitcode module
TypeScript
17
star
71

github-scan

Collecting public SSH keys using GitHub APIs
TypeScript
16
star
72

elfy

Dumb simple ELF parser
JavaScript
16
star
73

llvm-ir

LLVM IR Builder
JavaScript
16
star
74

redns

Fast and configurable DNS lookup cache
JavaScript
15
star
75

awesome64

WIP Awesome 64-bit integer implementation in JS
JavaScript
15
star
76

pyg

Not GYP
C
14
star
77

linearscan.rs

Linear scan register allocator written in Rust
Rust
14
star
78

crypto-deck

Cryptographically secure Mental Card Deck implementation
JavaScript
14
star
79

hypercorn

WIP
JavaScript
14
star
80

node-bplus

Node.js bindings for a bplus library
C++
13
star
81

mini-test.c

Minimalistic portable test runner for C projects
C
13
star
82

node-cf

Run CFRunLoop within libuv's eventloop
C++
13
star
83

assert-text

Assertion for multi-line texts when you need it
JavaScript
13
star
84

tokio-lock

Access an object from a single Tokio task
Rust
13
star
85

sneequals

Sneaky equality check between objects using proxies
TypeScript
13
star
86

huffin

Vanity ed25519 public keys, through Huffman Codes
JavaScript
12
star
87

core2dump

Core to dump
C
12
star
88

latetyper

Typing latency (OS X only)
C
11
star
89

file-shooter

File Shooter (uv_link_t, uv_ssl_t, uv_http_t)
C
11
star
90

spectrum-analyzer

FFT-based windowed spectrum analyzer
JavaScript
11
star
91

mean.engineer

An incomplete ActivityPub implementation in TypeScript
TypeScript
11
star
92

endian-reader

Small node.js helper for reading from Buffer with specified (ahead of time) endian
JavaScript
11
star
93

audio

Some realtime audio playback/recording for node.js
C++
11
star
94

stream-pair

Coupled Streams
JavaScript
11
star
95

json-pipeline-reducer

Reducer for json-pipeline
JavaScript
11
star
96

mitm.js

JavaScript
10
star
97

json-pipeline-scheduler

Scheduler for JSON-Pipeline project
JavaScript
10
star
98

wbuf

JavaScript
10
star
99

offset-buffer

JavaScript
10
star
100

reopen-tty

A small library to open /dev/tty in a cross-platform way
JavaScript
9
star