@btc-vision/as-bignum
v0.1.2
Published
High-performance 128-bit and 256-bit integer arithmetic for AssemblyScript. Fully audited by Verichains. Designed for blockchain and cryptographic applications.
Maintainers
Readme
@btc-vision/as-bignum
Overview
High-performance fixed-length big numbers for AssemblyScript and
WebAssembly. This library provides wide numeric types such as u128, u256, i128, and i256 with full arithmetic
operations support.
Designed for blockchain smart contracts, cryptographic operations, and any use case requiring deterministic behavior with large integers in WebAssembly environments.
Critical: Floating-Point Arithmetic is Prohibited in Blockchain
Floating-point arithmetic (
f32,f64) is strictly prohibited in blockchain and smart contract environments. Floating-point operations are non-deterministic across different CPU architectures, compilers, and platforms due to differences in rounding, precision, and IEEE 754 implementation details.This library provides some floating-arithmetic operations but should not be used in smart contracts. If you use floating by mistake, your contract will be invalidated on the blockchain.
Always use integer arithmetic (
u128,u256,i128,i256) for all blockchain computations. For decimal values, use fixed-point representation (e.g., store currency as smallest units like satoshis).
This library is a fork of the original as-bignum by MaxGraey. The original library contained critical vulnerabilities that have been addressed in this fork.
Security Audit
This library has been professionally audited by Verichains, a leading blockchain security firm specializing in smart contract audits, cryptographic implementation reviews, and WebAssembly security analysis.
For detailed audit information and security policy, see SECURITY.md.
Installation
npm install @btc-vision/as-bignumSupported Types
| Type | Description | Status |
|--------|--------------------------|----------------------------|
| u128 | 128-bit unsigned integer | Fully implemented & tested |
| i128 | 128-bit signed integer | Fully implemented & tested |
| u256 | 256-bit unsigned integer | Fully implemented & tested |
| i256 | 256-bit signed integer | Basic implementation |
Quick Start
import { u128, u256 } from "@btc-vision/as-bignum/assembly";
// Create values
let a = u256.from(1000);
let b = u256.from(500);
// Full arithmetic support
let sum = a + b;
let product = a * b;
let quotient = a / b;
// Safe multiply-divide without overflow
let result = u128.muldiv(u128.Max, u128.from(2), u128.from(3));Usage
Basic Import
import { u128, u256, i128 } from "@btc-vision/as-bignum/assembly";Creating Instances
// From literals
let a = u128.One;
let b = u128.Zero;
let c = u128.Max;
// From numbers
let d = u128.from(42);
let e = u128.fromU64(0x0123456789ABCDEF);
let f = u128.fromI64(-1);
// From strings
let g = u128.fromString("123456789012345678901234567890");
let h = u128.fromString("0x1234567890ABCDEF", 16);
// From bytes
let bytes: u8[] = [/* 16 bytes */];
let i = u128.fromBytesLE(bytes);
let j = u128.fromBytesBE(bytes);
// Constructor (lo, hi)
let k = new u128(0x0123456789ABCDEF, 0xFEDCBA9876543210);Arithmetic Operations
import { u128 } from "@btc-vision/as-bignum/assembly";
let a = u128.from(100);
let b = u128.from(25);
// Addition
let sum = a + b; // or u128.add(a, b)
// Subtraction
let diff = a - b; // or u128.sub(a, b)
// Multiplication
let product = a * b; // or u128.mul(a, b)
// Division
let quotient = a / b; // or u128.div(a, b)
// Modulo
let remainder = a % b; // or u128.rem(a, b)
// Power
let power = a ** 3; // or u128.pow(a, 3)
// Square root
let sqrt = u128.sqrt(a);Bitwise Operations
import { u128 } from "@btc-vision/as-bignum/assembly";
let a = u128.from(0xFF00);
let b = u128.from(0x0FF0);
// AND
let and = a & b;
// OR
let or = a | b;
// XOR
let xor = a ^ b;
// NOT
let not = ~a;
// Left shift
let lshift = a << 4;
// Right shift
let rshift = a >> 4;
// Rotate left
let rotl = u128.rotl(a, 4);
// Rotate right
let rotr = u128.rotr(a, 4);Comparison Operations
import { u128 } from "@btc-vision/as-bignum/assembly";
let a = u128.from(100);
let b = u128.from(50);
// Equality
let eq = a == b;
let ne = a != b;
// Comparison
let lt = a < b;
let le = a <= b;
let gt = a > b;
let ge = a >= b;
// Ordering (-1, 0, 1)
let ord = u128.ord(a, b);
// Zero check
let isZero = a.isZero();Bit Manipulation
import { u128 } from "@btc-vision/as-bignum/assembly";
let a = u128.from(0b10110100);
// Count leading zeros
let clz = u128.clz(a);
// Count trailing zeros
let ctz = u128.ctz(a);
// Population count (count of 1 bits)
let popcnt = u128.popcnt(a);Type Conversions
import { u128, u256 } from "@btc-vision/as-bignum/assembly";
let a = u128.from(12345);
// To primitive types
let asU64: u64 = a.toU64();
let asI64: i64 = a.toI64();
let asU32: u32 = a.toU32();
let asBool: bool = a.toBool();
let asF64: f64 = a.toF64();
// To string
let decStr = a.toString(); // decimal
let hexStr = a.toString(16); // hexadecimal
// To bytes
let bytesLE = a.toBytes(); // little-endian
let bytesBE = a.toBytes(true); // big-endian
let uint8Arr = a.toUint8Array();
let staticArr = a.toStaticBytes();
// To larger types
let asU256 = a.toU256();
let asI128 = a.toI128();
// Generic conversion
let asString = a.as<string>();u256 Operations
import { u256 } from "@btc-vision/as-bignum/assembly";
// Create u256 values
let a = u256.from(1000);
let b = u256.fromU128(someU128Value);
let c = u256.fromString("115792089237316195423570985008687907853269984665640564039457584007913129639935");
// Full arithmetic support
let sum = a + b;
let diff = a - b;
let product = a * b;
let quotient = a / b; // Division is supported!
// Bitwise operations
let shifted = a << 128;
let masked = a & b;
// Comparisons
if (a > b) {
// ...
}
// Conversion to u128 (truncates upper 128 bits)
let lower128 = c.toU128();Multiply-Divide Without Overflow
import { u128 } from "@btc-vision/as-bignum/assembly";
// Calculate (a * b) / c without overflow in the multiplication step
let a = u128.Max;
let b = u128.from(2);
let c = u128.from(3);
// This internally uses u256 to prevent overflow
let result = u128.muldiv(a, b, c);Immutable Constants
import { u128 } from "@btc-vision/as-bignum/assembly";
// Use immutable versions for read-only access (more efficient)
let zero = u128.immutableZero;
let one = u128.immutableOne;
let max = u128.immutableMax;
let min = u128.immutableMin;
// Use regular versions when you need to modify
let mutableZero = u128.Zero; // creates new instanceAPI Reference
u128
Static Properties
Zero/immutableZero- Zero value (0)One/immutableOne- One value (1)Min/immutableMin- Minimum value (0)Max/immutableMax- Maximum value (2^128 - 1)
Factory Methods
from<T>(value: T)- Create from generic typefromU64(value: u64)- Create from unsigned 64-bitfromI64(value: i64)- Create from signed 64-bitfromU32(value: u32)- Create from unsigned 32-bitfromI32(value: i32)- Create from signed 32-bitfromF64(value: f64)- Create from 64-bit floatfromString(value: string, radix?: i32)- Parse from stringfromBytes<T>(array: T, bigEndian?: bool)- Create from byte arrayfromBytesLE(array: u8[])- Create from little-endian bytesfromBytesBE(array: u8[])- Create from big-endian bytesfromBits(lo1: u32, lo2: u32, hi1: u32, hi2: u32)- Create from 32-bit parts
Arithmetic
add(a, b)/+- Additionsub(a, b)/-- Subtractionmul(a, b)/*- Multiplicationdiv(a, b)//- Divisionrem(a, b)/%- Remainderpow(base, exp)/**- Powersqrt(value)- Square rootsqr(value)- Squarediv10(value)- Fast division by 10rem10(value)- Fast remainder by 10muldiv(a, b, c)- (a * b) / c without overflow
Bitwise
or(a, b)/|- Bitwise ORxor(a, b)/^- Bitwise XORand(a, b)/&- Bitwise ANDshl(value, shift)/<<- Left shiftshr(value, shift)/>>- Right shiftrotl(value, shift)- Rotate leftrotr(value, shift)- Rotate right
Comparison
eq(a, b)/==- Equalityne(a, b)/!=- Inequalitylt(a, b)/<- Less thangt(a, b)/>- Greater thanle(a, b)/<=- Less or equalge(a, b)/>=- Greater or equalord(a, b)- Ordering (-1, 0, 1)
Bit Operations
clz(value)- Count leading zerosctz(value)- Count trailing zerospopcnt(value)- Population count
Instance Methods
isZero()- Check if zeroclone()- Create a copytoString(radix?: i32)- Convert to stringtoU64()/toI64()/toU32()/toI32()- Convert to primitivestoF64()/toF32()- Convert to floatstoBool()- Convert to booleantoBytes(bigEndian?: bool)- Convert to byte arraytoUint8Array(bigEndian?: bool)- Convert to Uint8ArraytoStaticBytes(bigEndian?: bool)- Convert to StaticArraytoU256()/toI128()- Convert to larger typesas<T>()- Generic conversion
u256
Similar API to u128 with 256-bit support. Constructor takes four u64 limbs: (lo1, lo2, hi1, hi2).
i128
Signed 128-bit integer with two's complement representation. Supports all standard signed integer operations.
Running Tests
npm testFor verbose output:
npm run test:ciBuilding
# Debug build
npm run build:debug
# Release build (default)
npm run buildContributing
Contributions are welcome! Please ensure all tests pass before submitting a pull request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Run tests (
npm test) - Commit your changes
- Push to the branch
- Open a Pull Request
Reporting Issues
- Bug Reports: Open an issue
- Security Vulnerabilities: See SECURITY.md - Do not open public issues for security vulnerabilities
License
Credits
- Original library by MaxGraey
- Fork maintained by OPNet
- Security audit by Verichains
