Skip to content

PKI & Merkle Ledger ​

LatticeDX maintains a per-organization hash-chained audit ledger (latticeCryptoLedger) backed by tenant-isolated Ed25519 signing keypairs (latticePkiKeys). Every signed record, frozen dataset snapshot (latticeFrozenSnapshots), ePOD delivery event, and key rotation appends a tamper-evident entry sealed with SHA-256 chaining, an Ed25519 signature, and an incremental binary Merkle root.

Collection Schemas and Immutability Guards ​

Both latticePkiKeys and latticeCryptoLedger enforce PostgreSQL FORCE ROW LEVEL SECURITY scoped by organizationId and block generic REST queries (PAAS_PRIVATE_COLLECTION_FORBIDDEN).

latticePkiKeys Fields
ParameterTypeDefaultDescription
organizationIdrequired
string—Tenant identifier owning the Ed25519 keypair.
keyIdrequired
string—Key identifier formatted as ed25519-<first 16 hex chars of fingerprintSha256>.
algorithm
stringEd25519Asymmetric signature algorithm.
publicKeyPemrequired
text—SPKI PEM public key exported for online and offline signature verification.
encryptedPrivateKeyrequired
text—PKCS#8 PEM private key encrypted with AES-256-GCM as <ivHex>:<tagHex>:<cipherHex>.
fingerprintSha256required
string—SHA-256 digest of the SPKI DER public key.
active / status
boolean / stringtrue / activeLifecycle state: active (signing), retired (historical verification allowed), or revoked (verification rejected).
latticeCryptoLedger Fields
ParameterTypeDefaultDescription
organizationIdrequired
string—Tenant identifier; paired with seq under unique index uidx_lattice_ledger_org_seq.
seqrequired
bigInt—Strictly monotonic per-organization sequence number starting at 1.
eventTyperequired
string—Audit event type (for example document.signed, pki.key_rotated, epod.captured).
targetCollection / targetRecordIdrequired
string—Collection name and record identifier bound to the ledger entry.
payloadHashrequired
string—Lowercase SHA-256 hex digest of canonicalJson(payload).
prevHashrequired
string—entryHash of seq - 1 within the same organization, or 64 zeros for seq = 1.
entryHashrequired
string—Chained SHA-256 digest binding metadata, payloadHash, prevHash, and recordedAt.
merkleRootrequired
string—Binary Merkle tree root computed across all entryHash values from seq = 1 through seq.
signatureBase64required
text—Base64-encoded Ed25519 signature issued by the active organization key.
keyId / recordedAtrequired
string / date—Signing key identifier and UTC ISO-8601 timestamp.

Concurrency and Immutability Controls ​

ControlEnforcement in pki-ledger.js
Serialized appendsBoth appendLedgerEntry and rotateOrgSigningKey serialize per organization through an in-process queue (runWithOrgMutex) and a PostgreSQL transaction advisory lock: `pg_advisory_xact_lock(hashtext('latticedx📒'
Append-only hooks (LEDGER_IMMUTABLE)registerLedgerHooks intercepts beforeUpdate, beforeDestroy, beforeBulkUpdate, and beforeBulkDestroy on latticeCryptoLedger and throws 403 LEDGER_IMMUTABLE.
Private key protection at restPrivate keys are wrapped using AES-256-GCM with `SHA-256(ENCRYPTION_FIELD_KEY

Hash Chaining, Ed25519 Signing, and Merkle Tree Math ​

1. Canonical JSON (canonicalJson) ​

Before hashing, canonicalJson recursively normalizes payloads deterministically:

  • Object keys are sorted lexicographically (a < b ? -1 : 1), omitting undefined, function, and symbol properties.
  • Date instances serialize as ISO-8601 strings (toISOString()), bigint values serialize as strings, and -0 normalizes to 0.
  • payloadHash = sha256Hex(canonicalJson(payload)).

2. Entry Hash and Ed25519 Signature ​

For seq === 1, prevHash equals '0'.repeat(64). For seq > 1, prevHash equals the entryHash of seq - 1 in the same organizationId:

text
entryHash       = SHA256("${organizationId}|${seq}|${eventType}|${targetCollection}|${targetRecordId}|${payloadHash}|${prevHash}|${recordedAtIso}")
signatureBase64 = Base64(Ed25519.Sign("${organizationId}|${seq}|${entryHash}", privateKey))

When invoking dxosLedger:signDocument, the service also computes a direct document signature over the canonical snapshot: Ed25519.Sign(canonicalJson(docSnapshot), privateKey).

3. Binary Merkle Root (computeMerkleRoot) ​

Given the ordered list of entryHash leaves (seq = 1..N):

  • An empty array yields '0'.repeat(64); a single leaf returns entryHash[0].
  • Each tree level pairs adjacent digests (left, right) and computes sha256Hex("${left}${right}"). Levels with an odd node count duplicate the trailing node (right = left) before advancing upward.

dxosLedger Endpoint Reference ​

GET/api/dxosLedger:publicKey
Bearer JWT | X-Lattice-API-Keyread
Returns the organization active Ed25519 public key (publicKeyPem, keyId, fingerprintSha256).
GET/api/dxosLedger:entries?page=1&pageSize=20&sort=-seq
Bearer JWT | X-Lattice-API-Keyread
Lists paginated ledger entries with optional targetCollection, targetRecordId, and eventType filters.
GET/api/dxosLedger:status
Bearer JWT | X-Lattice-API-Keyread
Returns the latest seq, headHash, merkleRoot, entryCount, and active keyId.
POST/api/dxosLedger:verify
Bearer JWT | X-Lattice-API-Keyread
Recomputes and verifies sequence continuity, prevHash, entryHash, Ed25519 signatures, and merkleRoot across all org entries (supports GET and POST).
POST/api/dxosLedger:signDocument
Bearer JWT | X-Lattice-API-Keywrite | ledger
Snapshots a record and appends a document.signed entry. Allowed collections: latticeRequests, latticeOrders, latticeServiceTickets, latticeAssets, latticeParaDocuments, latticeIncidentCases.
POST/api/dxosLedger:verifySignature
Bearer JWT | X-Lattice-API-Key | Public (APISIX)read
Verifies signatureBase64 for a canonical JSON payload against the active or retired key matching keyId.
POST/api/dxosLedger:rotateKey
Bearer JWT | X-Lattice-API-Keywrite | ledger
Admin-only: marks prior active keys retired, generates a new Ed25519 keypair, and appends a pki.key_rotated ledger entry.
GET/api/dxosLedger:exportProof?limit=100
Bearer JWT | X-Lattice-API-Keyread
Exports a self-contained verification bundle (publicKeys, entries, chainValid, merkleRoot, and target entry proof).

Standalone Offline Verification ​

Auditors can download an exportProof JSON bundle and verify chain integrity, Ed25519 signatures, and the Merkle root offline using standard Node.js or Python libraries with zero LatticeDX server access.

js
import { createHash, createPublicKey, verify } from 'node:crypto';
import { readFileSync } from 'node:fs';

const sha256Hex = (s) => createHash('sha256').update(s, 'utf8').digest('hex');

function computeMerkleRoot(hashes) {
  if (!hashes.length) return '0'.repeat(64);
  if (hashes.length === 1) return hashes[0];
  let level = [...hashes];
  while (level.length > 1) {
    const next = [];
    for (let i = 0; i < level.length; i += 2) {
      const left = level[i];
      const right = i + 1 < level.length ? level[i + 1] : left;
      next.push(sha256Hex(`${left}${right}`));
    }
    level = next;
  }
  return level[0];
}

const bundle = JSON.parse(readFileSync('./ledger-proof.json', 'utf8'));
const keys = new Map(
  bundle.publicKeys.map((k) => [k.keyId, createPublicKey(k.publicKeyPem)]),
);

let prevHash = '0'.repeat(64);
const hashes = [];
for (const e of bundle.entries.sort((a, b) => a.seq - b.seq)) {
  if (e.prevHash !== prevHash) throw new Error(`Broken prevHash at seq ${e.seq}`);
  const recIso = new Date(e.recordedAt).toISOString();
  const expectedEntry = sha256Hex(
    `${e.organizationId}|${e.seq}|${e.eventType}|${e.targetCollection}|${e.targetRecordId}|${e.payloadHash}|${e.prevHash}|${recIso}`,
  );
  if (expectedEntry !== e.entryHash) throw new Error(`Entry hash mismatch at seq ${e.seq}`);
  const pubKey = keys.get(e.keyId);
  const ok = verify(
    null,
    Buffer.from(`${e.organizationId}|${e.seq}|${expectedEntry}`, 'utf8'),
    pubKey,
    Buffer.from(e.signatureBase64, 'base64'),
  );
  if (!ok) throw new Error(`Invalid Ed25519 signature at seq ${e.seq}`);
  hashes.push(expectedEntry);
  if (computeMerkleRoot(hashes) !== e.merkleRoot) {
    throw new Error(`Merkle root mismatch at seq ${e.seq}`);
  }
  prevHash = expectedEntry;
}
console.log('Verified entries:', hashes.length, 'Root:', computeMerkleRoot(hashes));

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)