// verify-anchor-proof.mjs
//
// A sample script: check a document's blockchain anchor yourself, without
// asking Twala.
//
// It answers one question: was the fingerprint of this exact file written to
// the blockchain, and when? You need two things:
//
//   - the sealed PDF
//   - its anchor proof, the .json file you download from Twala
//
// Run it with Node.js 18 or newer:
//
//   npm install ethers
//   node verify-anchor-proof.mjs "Contract.pdf" "Contract — anchor proof.json"
//
// This is an example to read and adapt, not a product. It follows the happy
// path only, and it does not check the PDF's digital signatures: open the
// file in a PDF reader such as Adobe Acrobat for those.

import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { Contract, JsonRpcProvider, concat, keccak256 } from 'ethers';

// Public nodes for the chains Twala anchors on. Any node of the same chain
// gives the same answer, so pass your own as a third argument if you prefer.
const PUBLIC_NODES = {
  137: 'https://polygon.drpc.org', // Polygon
  80002: 'https://polygon-amoy.drpc.org', // Polygon Amoy (test network)
};

// The contracts Twala anchors on, as its Verify page publishes them. The
// script asks these and no other: a proof file names a contract of its own,
// and a forged one could name a contract that answers yes to anything.
const TWALA_CONTRACTS = {
  137: '0xc4dC769404E919bD6F03EF2E9F5e8a7071090F58', // Polygon
  80002: '0xe9E7722585434b97975C077cB9D55fe1e2291B13', // Polygon Amoy (test network)
};

const [pdfPath, proofPath, nodeUrl] = process.argv.slice(2);
const proof = JSON.parse(readFileSync(proofPath, 'utf8'));

// ── Step 1: fingerprint the file ───────────────────────────────────────────
// SHA-256 turns the file into 32 bytes. Change one byte of the PDF and this
// value changes completely, so it stands for this exact file and no other.
const documentHash = createHash('sha256').update(readFileSync(pdfPath)).digest('hex');
console.log('1. Document hash (SHA-256):', documentHash);

// ── Step 2: find the document's leaf ───────────────────────────────────────
// Twala anchors many documents at once by arranging their hashes in a Merkle
// tree and writing only the tree's root to the blockchain. A document's place
// at the bottom of that tree is its leaf: the keccak256 hash of its SHA-256.
// The 0x tells keccak256 to hash the 32 bytes the hex stands for. Hashing the
// hex as text would give a different, wrong leaf.
//
// Always compute the leaf like this, from the file. Never take a leaf or a
// root from a proof, a certificate or anyone else: the contract cannot tell a
// real document's leaf from other values in the tree, so only one you derived
// yourself proves anything.
const leaf = keccak256(`0x${documentHash}`);
console.log('2. Leaf (keccak256):       ', leaf);

// ── Step 3: climb the tree to its root ─────────────────────────────────────
// The proof lists the one neighbor needed at each level of the tree. Hashing
// our value together with that neighbor (the two joined as 64 bytes) gives
// the value one level up, and repeating it to the top gives the root. At each
// step the smaller of the two goes first, which is the order the smart
// contract uses as well. A document anchored on its own has no neighbors, and
// its leaf is already the root.
let root = leaf;
for (const neighbor of proof.merkle.proof) {
  const pair = BigInt(root) <= BigInt(neighbor) ? [root, neighbor] : [neighbor, root];
  root = keccak256(concat(pair));
}
console.log('3. Merkle root:            ', root);

// ── Step 4: ask the blockchain ─────────────────────────────────────────────
// We computed that root from the file alone. Now we ask Twala's contract on
// the proof's chain whether that same root was anchored, and when. This is a
// free read: no wallet, no account and no fee.
const provider = new JsonRpcProvider(nodeUrl ?? PUBLIC_NODES[proof.anchor.chainId]);
const contractAddress = TWALA_CONTRACTS[proof.anchor.chainId];

const contract = new Contract(
  contractAddress,
  ['function isAnchored(bytes32 merkleRoot) view returns (bool exists, uint256 timestamp)'],
  provider,
);
const [anchored, timestamp] = await contract.isAnchored(root);
console.log(`4. Contract ${contractAddress} on ${proof.anchor.chainName}`);

// ── The answer ─────────────────────────────────────────────────────────────
if (anchored) {
  const anchoredAt = new Date(Number(timestamp) * 1000).toISOString();
  console.log(`\nAnchored. This exact file was recorded on the blockchain on ${anchoredAt}.`);
} else {
  console.log('\nNot anchored. The contract holds no such root: the file was changed, or the proof is not this file\'s.');
}
