Sổ cái PKI và Merkle
LatticeDX duy trì sổ cái kiểm toán mật mã nối chuỗi băm theo từng tổ chức (latticeCryptoLedger) kết hợp cặp khóa ký Ed25519 riêng biệt trên mỗi tenant (latticePkiKeys). Cơ chế này bảo đảm tính toàn vẹn không thể chối bỏ cho chứng từ nghiệp vụ, bản chụp dữ liệu đông lạnh (latticeFrozenSnapshots), ePOD giao nhận và sự kiện xoay khóa.
Lược đồ bảng và Bất biến dữ liệu
Cả latticePkiKeys và latticeCryptoLedger đều kích hoạt PostgreSQL FORCE ROW LEVEL SECURITY theo organizationId và bị chặn truy cập REST trực tiếp (PAAS_PRIVATE_COLLECTION_FORBIDDEN).
| Tham số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
organizationIdbắt buộc | string | — | Định danh tenant sở hữu cặp khóa Ed25519. |
keyIdbắt buộc | string | — | Định danh khóa theo mẫu ed25519-<16hex đầu của fingerprintSha256>. |
algorithm | string | Ed25519 | Thuật toán chữ ký bất đối xứng. |
publicKeyPembắt buộc | text | — | Khóa công khai định dạng SPKI PEM dùng để kiểm chứng công khai. |
encryptedPrivateKeybắt buộc | text | — | Khóa riêng PKCS#8 PEM mã hóa AES-256-GCM theo dạng <ivHex>:<tagHex>:<cipherHex>. |
fingerprintSha256bắt buộc | string | — | Hàm băm SHA-256 của khóa công khai dạng SPKI DER. |
active / status | boolean / string | true / active | Trạng thái khóa: active (đang ký), retired (ngừng ký nhưng vẫn hợp lệ khi kiểm chứng lịch sử) hoặc revoked. |
| Tham số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
organizationIdbắt buộc | string | — | Định danh tổ chức; ghép với seq tạo chỉ mục duy nhất uidx_lattice_ledger_org_seq. |
seqbắt buộc | bigInt | — | Số thứ tự tăng đơn điệu bắt đầu từ 1 trong phạm vi từng tổ chức. |
eventTypebắt buộc | string | — | Loại sự kiện (ví dụ document.signed, pki.key_rotated, epod.captured). |
targetCollection / targetRecordIdbắt buộc | string | — | Tên collection và ID bản ghi được ký hoặc kiểm toán. |
payloadHashbắt buộc | string | — | SHA-256 hex của JSON chuẩn hóa (canonicalJson(payload)). |
prevHashbắt buộc | string | — | entryHash của bản ghi seq - 1, hoặc chuỗi 64 ký tự 0 với seq = 1. |
entryHashbắt buộc | string | — | Hàm băm nối chuỗi SHA-256 toàn phần của mục sổ cái. |
merkleRootbắt buộc | string | — | Gốc cây Merkle nhị phân tính trên toàn bộ entryHash từ seq = 1 tới seq hiện tại. |
signatureBase64bắt buộc | text | — | Chữ ký Ed25519 (base64) ký bằng khóa đang hoạt động của tổ chức. |
keyId / recordedAtbắt buộc | string / date | — | Mã khóa đã ký và mốc thời gian ISO-8601 ghi nhận mục sổ cái. |
Cơ chế chống sửa đổi và Khóa đồng thời
| Cơ chế | Thực thi trong pki-ledger.js |
|---|---|
| Khóa ghi theo tổ chức | Mọi thao tác ghi (appendLedgerEntry và rotateOrgSigningKey) tuần tự hóa qua hàng đợi mutex trong tiến trình (runWithOrgMutex) và khóa giao dịch PostgreSQL `pg_advisory_xact_lock(hashtext('latticedx📒' |
Hook chỉ thêm (LEDGER_IMMUTABLE) | registerLedgerHooks gắn sự kiện beforeUpdate, beforeDestroy, beforeBulkUpdate và beforeBulkDestroy trên latticeCryptoLedger để ném lỗi 403 LEDGER_IMMUTABLE. |
| Bảo vệ khóa riêng tại nghỉ | Khóa chủ mã hóa AES-256-GCM là `SHA-256(ENCRYPTION_FIELD_KEY |
Toán học Chuỗi băm, Chữ ký Ed25519 và Cây Merkle
1. Chuẩn hóa JSON (canonicalJson)
Trước khi băm payload, hàm canonicalJson chuyển đổi đệ quy giá trị theo quy tắc xác định:
- Khóa của mọi object được sắp xếp tăng dần theo thứ tự từ điển (
a < b ? -1 : 1), loại bỏ thuộc tính có giá trịundefined,functionhoặcsymbol. - Đối tượng
Datechuyển thành chuỗi ISO (toISOString()),bigintchuyển thành chuỗi thập phân,-0chuẩn hóa về0. payloadHash = sha256Hex(canonicalJson(payload)).
2. Công thức entryHash và signatureBase64
Với seq === 1, giá trị khởi thủy prevHash là '0'.repeat(64). Với seq > 1, prevHash bằng entryHash của bản ghi seq - 1 cùng tổ chức:
entryHash = SHA256("${organizationId}|${seq}|${eventType}|${targetCollection}|${targetRecordId}|${payloadHash}|${prevHash}|${recordedAtIso}")
signatureBase64 = Base64(Ed25519.Sign("${organizationId}|${seq}|${entryHash}", privateKey))Riêng API ký trực tiếp bản ghi (dxosLedger:signDocument) tạo thêm chữ ký trên JSON chuẩn hóa của ảnh chụp bản ghi: Ed25519.Sign(canonicalJson(docSnapshot), privateKey).
3. Gốc cây Merkle nhị phân (computeMerkleRoot)
Trên danh sách entryHash sắp theo seq tăng dần:
- Danh sách rỗng trả về
'0'.repeat(64); danh sách1phần tử trả về chínhentryHash[0]. - Ở mỗi tầng, ghép từng cặp
(left, right)và tínhsha256Hex("${left}${right}"). Nếu số nút ở tầng là lẻ, nút cuối được nhân đôi (right = left) trước khi băm lên tầng trên cho đến khi còn duy nhất một gốcmerkleRoot.
Tham chiếu Endpoint dxosLedger
/api/dxosLedger:publicKey/api/dxosLedger:entries?page=1&pageSize=20&sort=-seq/api/dxosLedger:status/api/dxosLedger:verify/api/dxosLedger:signDocument/api/dxosLedger:verifySignature/api/dxosLedger:rotateKey/api/dxosLedger:exportProof?limit=100Kiểm chứng độc lập ngoại tuyến
Kiểm toán viên có thể tải gói JSON từ /api/dxosLedger:exportProof và chạy mã kiểm chứng bằng thư viện chuẩn Node.js hoặc Python mà không cần kết nối lại máy chủ LatticeDX.
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));