- Notifications
You must be signed in to change notification settings - Fork16
Secure, audited & 0-deps implementation of bech32, base64, base32, base16 & base58
License
paulmillr/scure-base
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Audited & minimal implementation of bech32, base64, base58, base32 & base16.
- 🔒Audited by an independent security firm
- 🔻 Tree-shakeable: unused code is excluded from your builds
- 📦 ESM and common.js
- ✍️ Written infunctional style, easily composable
- 💼 Matches specs
- BIP173,BIP350 for bech32 / bech32m
- RFC 4648 (aka RFC 3548) for Base16, Base32, Base32Hex, Base64, Base64Url
- Base58,Base58check,Base32 Crockford
- 🪶 4KB gzipped
Check outProjects using scure-base.
scure — audited micro-libraries.
- Zero or minimal dependencies
- Highly readable TypeScript / JS code
- PGP-signed releases and transparent NPM builds
- Check outhomepage & all libraries:base,bip32,bip39,btc-signer,starknet
npm install @scure/base
deno add jsr:@scure/base
deno doc jsr:@scure/base
# command-line documentation
We support all major platforms and runtimes. The library is hybrid ESM / Common.js package.
import{base16,base32,base64,base58}from'@scure/base';// Flavorsimport{base58xmr,base58xrp,base32nopad,base32hex,base32hexnopad,base32crockford,base64nopad,base64url,base64urlnopad,}from'@scure/base';constdata=Uint8Array.from([1,2,3]);base64.decode(base64.encode(data));// Convert utf8 string to Uint8Arrayconstdata2=newTextEncoder().encode('hello');base58.encode(data2);// Everything has the same API except for bech32 and base58checkbase32.encode(data);base16.encode(data);base32hex.encode(data);
base58check is a special case: you need to passsha256()
function:
import{createBase58check}from'@scure/base';createBase58check(sha256).encode(data);
We provide low-level bech32 operations.If you need high-level methods for BTC (addresses, and others), usescure-btc-signer instead.
Bitcoin addresses use both 5-bit words and bytes representations.They can't be parsed usingbech32.decodeToBytes
.
Same applies to Lightning Invoice ProtocolBOLT-11.We have many tests in./test/bip173.test.js
that serve as minimal examples ofBitcoin address and Lightning Invoice Protocol parsers.Keep in mind that you'll need to verify the examples before using them in your code.
Do something like this:
constdecoded=bech32.decode(address);// NOTE: words in bitcoin addresses contain version as first element,// with actual witness program words in rest// BIP-141: The value of the first push is called the "version byte".// The following byte vector pushed is called the "witness program".const[version, ...dataW]=decoded.words;constprogram=bech32.fromWords(dataW);// actual witness program
The code may feel unnecessarily complicated; but actually it's much easier to reason about.Any encoding library consists of two functions:
encode(A) -> Bdecode(B) -> A where X = decode(encode(X)) # encode(decode(X)) can be !== X! # because decoding can normalize inpute.g.base58checksum = { encode(): { // checksum // radix conversion // alphabet }, decode(): { // alphabet // radix conversion // checksum }}
But instead of creating two big functions for each specific case,we create them from tiny composable building blocks:
base58checksum = chain(checksum(), radix(), alphabet())
Which is the same as chain/pipe/sequence function in Functional Programming,but significantly more useful since it enforces same order of execution of encode/decode.Basically you only define encode (in declarative way) and get correct decode for free.So, instead of reasoning about two big functions you need only reason about primitives and encode chain.The design revealed obvious bug in older version of the lib,where xmr version of base58 had errors in decode's block processing.
Besides base-encodings, we can reuse the same approach with any encode/decode function(bytes2number
,bytes2u32
, etc).For example, you can easily encode entropy to mnemonic (BIP-39):
exportfunctiongetCoder(wordlist:string[]){if(!Array.isArray(wordlist)||wordlist.length!==2**11||typeofwordlist[0]!=='string'){thrownewError('Wordlist: expected array of 2048 strings');}returnmbc.chain(mbu.checksum(1,checksum),mbu.radix2(11,true),mbu.alphabet(wordlist));}
Uint8Array
is represented as big-endian number:
[1, 2, 3, 4, 5] -> 1*(256**4) + 2*(256**3) 3*(256**2) + 4*(256**1) + 5*(256**0)where 256 = 2**8 (8 bits per byte)
which is then converted to a number in another radix/base (16/32/58/64, etc).
However, generic conversion between bases hasquadratic O(n^2) time complexity.
Which means base58 has quadratic time complexity too. Use base58 only when you have smallconstant sized input, because variable length sized input from user can cause DoS.
On the other hand, if both bases are power of same number (like2**8 <-> 2**64
),there is linear algorithm. For now we have implementation for power-of-two bases only (radix2).
The library has been independently audited:
- at version 1.0.0, in Jan 2022, bycure53
- PDFs:online,offline
- Changes since audit.
- The audit has been funded byEthereum Foundation with help ofNomic Labs
The library was initially developed forjs-ethereum-cryptography.At commitae00e6d7,it was extracted to a separate package calledmicro-base
.After the audit we've decided to use@scure
NPM namespace for security.
- Commits are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures
- Releases are transparent and built on GitHub CI. Make sure to verifyprovenance logs
- Rare releasing is followed to ensure less re-audit need for end-users
- Dependencies are minimized and locked-down: any dependency could get hacked and users will be downloading malware with every install.
- We make sure to use as few dependencies as possible
- Automatic dep updates are prevented by locking-down version ranges; diffs are checked with
npm-diff
- Dev Dependencies are disabled for end-users; they are only used to develop / build the source code
For this package, there are 0 dependencies; and a few dev dependencies:
- micro-bmark, micro-should and jsbt are used for benchmarking / testing / build tooling and developed by the same author
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation. It's hard to audit their source code thoroughly and fully because of their size
npm install && npm run build && npm test
will build the code and run tests.npm run lint
/npm run format
will run linter / fix linter issues.npm run build:release
will build single file
- scure-btc-signer
- prefixed-api-key
- coinspace wallet and its modules:ada,btceos,sol,xmr
MIT (c) Paul Miller(https://paulmillr.com), see LICENSE file.
About
Secure, audited & 0-deps implementation of bech32, base64, base32, base16 & base58