All files Base58Check.ts

38.46% Statements 5/13
0% Branches 0/2
0% Functions 0/2
38.46% Lines 5/13

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 351x   1x 1x 1x   1x                                                        
import { hash256 } from '@node-dlc/crypto';
 
import { Base58 } from './Base58';
import { BitcoinError } from './BitcoinError';
import { BitcoinErrorCode } from './BitcoinErrorCode';
 
export class Base58Check {
  /**
   * Perform a base58 encoding by appends a 4-byte hash256 checksum
   * at the end of the value.
   * @param buf
   */
  public static encode(buf: Buffer): string {
    return Base58.encode(Buffer.concat([buf, hash256(buf).slice(0, 4)]));
  }
 
  /**
   * Decodes a base58 check value. Throws error if checksum is invalid
   * @param buf
   */
  public static decode(input: string): Buffer {
    const total = Base58.decode(input);
    const data = total.slice(0, total.length - 4);
    const checksum = total.slice(total.length - 4);
    const hash = hash256(data).slice(0, 4);
    if (!hash.equals(checksum)) {
      throw new BitcoinError(BitcoinErrorCode.Base58ChecksumFailed, {
        actual: hash,
        expected: checksum,
      });
    }
    return data;
  }
}