All files / src/common encoding-base58.ts

87.23% Statements 41/47
25% Branches 2/8
66.66% Functions 2/3
90% Lines 36/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71    68x       68x   68x   68x 48x 48x                   48x   48x   48x 1515x 1515x 1515x     48x 96x     48x     68x 40x 40x 40x 1340x 1340x 1340x         1340x 15120x   1340x 1340x 1340x 15120x 15120x 15120x   1340x 872x 872x     40x 88x   40x    
/*! micro-base58 - MIT License (c) 2021, Paul Miller (https://paulmillr.com) */
 
import { bytesToHex } from './encoding-hex';
 
/* See https://github.com/paulmillr/micro-base58 */
 
const B58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
 
const _58n = BigInt(58);
 
export function encodeB58(source: string | Uint8Array) {
  Iif (source.length === 0) return '';
  Iif (typeof source === 'string') {
    if (typeof TextEncoder !== 'undefined') {
      source = new TextEncoder().encode(source);
    } else {
      // note: only supports ASCII
      source = new Uint8Array(source.split('').map(c => c.charCodeAt(0)));
    }
  }
 
  // Convert Uint8Array to BigInt, Big Endian.
  let x = BigInt('0x' + bytesToHex(source));
 
  const output = [];
 
  while (x > 0) {
    const mod = Number(x % _58n);
    x = x / _58n;
    output.push(B58_ALPHABET[mod]);
  }
 
  for (let i = 0; source[i] === 0; i++) {
    output.push(B58_ALPHABET[0]);
  }
 
  return output.reverse().join('');
}
 
export function decodeB58(output: string) {
  Iif (output.length === 0) return new Uint8Array([]);
  const bytes = [0];
  for (let i = 0; i < output.length; i++) {
    const char = output[i];
    const value = B58_ALPHABET.indexOf(char);
    Iif (value === undefined) {
      throw new Error(
        `base58.decode received invalid input. Character '${char}' is not in the base58 alphabet.`
      );
    }
    for (let j = 0; j < bytes.length; j++) {
      bytes[j] *= 58;
    }
    bytes[0] += value;
    let carry = 0;
    for (let j = 0; j < bytes.length; j++) {
      bytes[j] += carry;
      carry = bytes[j] >> 8;
      bytes[j] &= 0xff;
    }
    while (carry > 0) {
      bytes.push(carry & 0xff);
      carry >>= 8;
    }
  }
  for (let i = 0; i < output.length && output[i] === '1'; i++) {
    bytes.push(0);
  }
  return new Uint8Array(bytes.reverse());
}