0.1.1 • Published 1 year ago

mnemonic-bytes v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Mnemonic Bytes

Mnemonic Bytes encode and decode binary data to and from mnemonic words using a base-256 encoding scheme. This is great for turning things like UUIDs, encryption keys, and wallet addresses into something that humans can actually remember and type.

To install, do the npm thing:

$ npm install mnemonic-bytes

To use it, call .encode and .decode:

import { encode, decode } from 'mnemonic-bytes'

const someBytes = new Uint8Array([ 0x01, 0x02, 0x03, 0x04 ])
const mnemonics = encode(someBytes)
console.log(mnemonics) // Result: [ 'affix', 'agony', 'ajar', 'alike' ]

const bytes = decode([ 'affix', 'agony', 'ajar', 'alike' ])
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

Encoding

The .encode function takes either an ArrayBuffer or a JavaScript object that has a .buffer property that contains an ArrayBuffer—like a DataView or a TypedArray. It returns a string[].

const bytes = new Uint8Array([ 0x01, 0x02, 0x03, 0x04 ])
const buffer = bytes.buffer

let mnemonics

mnemonics = encode(bytes)
console.log(mnemonics) // Result: [ 'affix', 'agony', 'ajar', 'alike' ]

mnemonics = encode(buffer)
console.log(mnemonics) // Result: [ 'affix', 'agony', 'ajar', 'alike' ]

Decoding

The .decode function takes either a string containing whitespace-delimited mnemonics or a string[] containing mnemonics. It returns a Uint8Array.

let bytes

bytes = decode('affix agony ajar alike')
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

bytes = decode('affix\tagony\tajar\talike')
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

bytes = decode([ 'affix', 'agony', 'ajar', 'alike' ])
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

It ignores empty strings:

bytes = decode('')
console.log(bytes) // Result: Uint8Array(0) []

bytes = decode('\t')
console.log(bytes) // Result: Uint8Array(0) []

bytes = decode([ '', 'affix', 'agony', 'ajar', 'alike' ])
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

bytes = decode([ '\t', 'affix', 'agony', 'ajar', 'alike' ])
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

It ignores casing in the mnemonics:

bytes = decode('affix Agony AJAR AlIkE')
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

bytes = decode([ 'affix', 'Agony', 'AJAR', 'AlIkE' ])
console.log(bytes) // Result: Uint8Array(4) [ 1, 2, 3, 4 ]

It throws an error if an invalid word is encountered:

try {
  bytes = decode('foo bar baz')
} catch (err) {
  console.log(err) // Result: Error: Invalid value 'foo' found at index 0
}

Contributing

If you find a bug, typo, or some third thing, feel free to send me a pull request.

0.1.1

1 year ago

0.1.0

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago