All files / src/domain/certificates/useCases getChain.ts

100% Statements 12/12
80% Branches 4/5
100% Functions 2/2
100% Lines 12/12

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                8x       36x 324x 76x   1x   35x                         44x   43x 43x   36x 36x           8x    
import { BLOCKCHAINS } from '@blockcerts/explorer-lookup';
import addresses from '../../addresses';
import { getText } from '../../i18n/useCases';
import type { IBlockchainObject } from '@blockcerts/explorer-lookup';
import type { Receipt } from '../../../models/Receipt';
import type { MerkleProof2017Anchor } from '../../../models/MerkleProof2017';
 
function defaultChainAssumption (address = ''): IBlockchainObject {
  return addresses.isMainnet(address) ? BLOCKCHAINS.bitcoin : BLOCKCHAINS.testnet;
}
 
function getChainObject (chainCodeSignatureValue): IBlockchainObject {
  const chainObject: IBlockchainObject = Object.keys(BLOCKCHAINS)
    .map(key => BLOCKCHAINS[key])
    .find((entry: IBlockchainObject) => entry.signatureValue === chainCodeSignatureValue);
  if (typeof chainObject === 'undefined') {
    throw new Error(getText('errors', 'getChain'));
  }
  return chainObject;
}
 
/**
 * getChain
 *
 * Returns a chain object by looking at the signature value or the bitcoin address (legacy)
 *
 * @param signature
 * @param address
 * @returns {*}
 */
export default function getChain (address: string, proof: Receipt): IBlockchainObject {
  const cleanedSignature = proof || null;
  if (cleanedSignature?.anchors) {
    const anchors = cleanedSignature.anchors;
    const anchor = anchors[0];
    if ((anchor as MerkleProof2017Anchor).chain) {
      const chainCodeSignatureValue = (anchor as MerkleProof2017Anchor).chain;
      return getChainObject(chainCodeSignatureValue);
    }
  }
 
  // Legacy path: we didn't support anything other than testnet and mainnet, so we check the address prefix
  // otherwise try to determine the chain from a bitcoin address
  return defaultChainAssumption(address);
}