All files / src/inspectors ensureValidReceipt.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 0/0
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 47                31x 31x     31x 31x     44x     15x 15x   27x 27x   2x               2x             7x            
import { sha256 } from '@noble/hashes/sha2.js';
import { Buffer } from 'buffer';
import VerifierError from '../models/verifierError';
import { toByteArray } from '../helpers/data';
import { getText } from '../domain/i18n/useCases';
import type { Receipt } from '../models/Receipt';
 
export default function ensureValidReceipt (receipt: Receipt): void {
  let proofHash = receipt.targetHash;
  const merkleRoot = receipt.merkleRoot;
 
  try {
    const proof = receipt.proof ?? receipt.path;
    const isProof = !!proof;
    if (isProof) {
      for (const index in proof) {
        const node = proof[index];
        let appendedBuffer;
        if (typeof node.left !== 'undefined') {
          appendedBuffer = toByteArray(`${node.left}${proofHash}`);
          proofHash = Buffer.from(sha256(Uint8Array.from(appendedBuffer))).toString('hex');
        } else if (typeof node.right !== 'undefined') {
          appendedBuffer = toByteArray(`${proofHash}${node.right}`);
          proofHash = Buffer.from(sha256(Uint8Array.from(appendedBuffer))).toString('hex');
        } else {
          throw new VerifierError(
            'checkReceipt',
            'Trigger catch error.'
          );
        }
      }
    }
  } catch (e) {
    throw new VerifierError(
      'checkReceipt',
      getText('errors', 'ensureValidReceipt')
    );
  }
 
  if (proofHash !== merkleRoot) {
    throw new VerifierError(
      'checkReceipt',
      getText('errors', 'invalidMerkleReceipt')
    );
  }
}