ZATCA Invoice Hash Chain (PIH) & ICV Counter Implementation Guide (With Code)
Developer implementation guide for ZATCA Phase 2 Previous Invoice Hash (PIH) and Invoice Counter Value (ICV): genesis PIH, SHA-256 XML canonicalization, atomic DB locking, and Node.js code examples.
Summarize or verify this guide with AI:
Opens your preferred AI assistant with this article and ZATCA compliance context pre-loaded.
Quick Answer: How ZATCA PIH & ICV Work Together
In ZATCA Phase 2 (Integration Phase), every EGS unit (each CSID certificate) must link every generated document into an immutable cryptographic chain using two fields:
- ICV (
cbc:ID = ICVinsideAdditionalDocumentReference): A strictly monotonic integer starting at1(1, 2, 3...) with no gaps, no resets, and no reused numbers. - PIH (
cbc:ID = PIHinsideAdditionalDocumentReference): The Base64-encoded SHA-256 hash of the previous document’s canonicalized UBL 2.1 XML.
Test your onboarding sequence with our ZATCA 6-Check Compliance Checklist or inspect your signed XML in our ZATCA XML Validator & Viewer.
1. The Genesis PIH (First Invoice, ICV = 1)
Before any invoice exists in your EGS unit, ZATCA defines a fixed Genesis PIH equal to base64(sha256("0")):
NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==
In your UBL 2.1 XML, both ICV and PIH live inside cac:AdditionalDocumentReference:
<cac:AdditionalDocumentReference>
<cbc:ID>ICV</cbc:ID>
<cbc:UUID>1</cbc:UUID>
</cac:AdditionalDocumentReference>
<cac:AdditionalDocumentReference>
<cbc:ID>PIH</cbc:ID>
<cac:Attachment>
<cbc:EmbeddedDocumentBinaryObject mimeCode="text/plain">NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==</cbc:EmbeddedDocumentBinaryObject>
</cac:Attachment>
</cac:AdditionalDocumentReference>
2. Computing the Invoice Hash (C14N 1.1 + SHA-256 + Base64)
To produce the hash that becomes both the current invoice’s digest (in ds:DigestValue & QR Tag 6) and the next invoice’s PIH, your backend must follow ZATCA’s exact 4-step pipeline:
- Parse the generated UBL 2.1 XML document.
- Remove these three nodes (they contain or depend on the signature/hash itself):
//*[local-name()='UBLExtensions']//*[local-name()='Signature']//*[local-name()='AdditionalDocumentReference'][*[local-name()='ID']='QR']
- Canonicalize the remaining XML using W3C Canonical XML 1.1 (
C14N 1.1) (without comments). - Compute
SHA-256over the UTF-8 canonical bytes and encode the raw 32-byte digest in Base64 (not hex!).
Node.js Reference Snippet
import crypto from 'node:crypto';
import { DOMParser } from '@xmldom/xmldom';
import xpath from 'xpath';
import { ExclusiveCanonicalization } from 'xml-crypto';
export const GENESIS_PIH =
'NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==';
export function computeZatcaInvoiceHash(rawXml: string): string {
const doc = new DOMParser().parseFromString(rawXml, 'text/xml');
const nodesToStrip = [
"//*[local-name()='UBLExtensions']",
"//*[local-name()='Signature']",
"//*[local-name()='AdditionalDocumentReference'][*[local-name()='ID']='QR']",
];
for (const expr of nodesToStrip) {
const matches = xpath.select(expr, doc) as Node[];
for (const node of matches) {
node.parentNode?.removeChild(node);
}
}
const c14n = new ExclusiveCanonicalization();
const canonicalXml = c14n.process(doc.documentElement, {});
return crypto.createHash('sha256').update(canonicalXml, 'utf8').digest('base64');
}
(Note: verify your exact C14N 1.1 vs exclusive C14N behavior against ZATCA’s official SDK / Fatoora Simulation Portal for namespace ordering.)
3. Concurrency-Safe Database Locking (Preventing Broken Chains)
The #1 production bug in multi-user ERPs is two concurrent cashiers or API workers reading the same PIH and ICV at the same millisecond, creating a forked chain and failing ZATCA validation.
Always wrap ICV increment + PIH read/write inside an atomic database transaction (SELECT ... FOR UPDATE on the EGS unit row):
BEGIN;
SELECT last_icv, last_pih
FROM zatca_egs_units
WHERE id = $1 AND organization_id = $2
FOR UPDATE;
-- Compute next_icv = last_icv + 1, build & hash XML using last_pih,
-- then persist the new invoice hash BEFORE committing:
UPDATE zatca_egs_units
SET last_icv = $3, last_pih = $4, updated_at = NOW()
WHERE id = $1 AND organization_id = $2;
COMMIT;
4. What Happens When ZATCA Rejects an Invoice?
Never delete a rejected invoice or reset ICV! Read our full playbook on Why Rejected ZATCA Documents Must Never Be Deleted:
- Keep the rejected document archived with its assigned
ICVand computed hash. - Issue the corrected document with a new
UUID v4,ICV = N + 1, andPIHpointing to the previous hash.
Or Let Qeemah Handle the Entire Cryptographic Chain
Qeemah Cloud manages isolated EGS units per branch, atomic PostgreSQL ICV/PIH locking, ECDSA secp256k1 signing, and automatic B2B Clearance / B2C Reporting natively.
Frequently Asked Questions
What is the exact genesis PIH value for ZATCA ICV = 1?
For the first document generated by an EGS unit (ICV = 1), ZATCA mandates the Base64-encoded SHA-256 hash of the character '0': NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==.
Which XML tags must be removed before hashing a ZATCA UBL 2.1 invoice?
Before computing the SHA-256 invoice hash, you must strip three XPaths from the UBL 2.1 XML: (1) ext:UBLExtensions, (2) cac:Signature, and (3) the cac:AdditionalDocumentReference node where cbc:ID equals 'QR'. Then canonicalize using C14N 1.1 before hashing.
Does a rejected ZATCA invoice update the PIH and ICV chain?
Yes. Once an invoice is generated, hashed, and assigned an ICV, that ICV and its hash remain part of your local sequential chain even if ZATCA returns a 400 rejection. Never delete or reuse the rejected ICV; issue the corrected document with the next ICV (N + 1) and the previous document's hash as PIH.
Should ICV and PIH be shared across multiple POS terminals or branches?
No. Each EGS unit (device/branch with its own CSID certificate) maintains its own independent ICV counter (starting at 1) and PIH hash chain.