How the CloddsBot Trade Ledger Captures AI Decision Audit Trails with SHA-256 Integrity Hashing
The CloddsBot trade ledger creates tamper-evident AI decision audit trails by generating deterministic SHA-256 hashes of decision data in src/ledger/hash.ts and persisting them through LedgerStorage.capture() in src/ledger/storage.ts, enabling cryptographic verification of record integrity at any point in the data lifecycle.
The CloddsBot repository implements a cryptographically secure logging system designed to preserve the integrity of automated trading decisions. By combining deterministic JSON serialization with Node.js native hashing primitives, the ledger ensures that every AI-driven action remains auditable and immutable, providing irrefutable proof of decision state at the time of execution.
Deterministic Hash Generation for Decision Integrity
The foundation of the audit system rests on deterministic SHA-256 hashing that produces identical digests for identical decision inputs, regardless of serialization order or platform differences.
The hashDecision Implementation
In src/ledger/hash.ts, the hashDecision function constructs a cryptographic fingerprint of decision records by processing only the fields defined in the HASH_FIELDS array. This whitelist approach includes critical context such as user ID, session ID, timestamp, category, action, platform, market ID, inputs, analysis, constraints, confidence, decision, and reason.
The function filters undefined values to ensure consistency, then sorts all object keys alphabetically before stringification. This guarantees deterministic output: JSON.stringify(data, Object.keys(data).sort()). The resulting string feeds into Node’s native crypto.createHash('sha256') method, producing a standard 64-character hexadecimal digest that uniquely represents the decision state.
Persisting Hashed Records to the Trade Ledger
Once generated, these cryptographic hashes anchor the decision data within persistent storage, creating an immutable bond between the record and its integrity proof.
LedgerStorage.capture Method
The LedgerStorage.capture method in src/ledger/storage.ts (lines 95-102) accepts a decision record and an optional configuration object containing the hashIntegrity boolean flag. When this flag evaluates to true—typically driven by the global LedgerConfig.hashIntegrity setting—the method invokes hashDecision and persists the resulting hash in the dedicated hash column of the trade_ledger relational table.
This storage layer simultaneously persists the complete decision payload, operational constraints, and a generated UUID for the ledger entry, creating a comprehensive audit record that links the decision content directly to its integrity hash.
Cryptographic Commitments and Verification Workflows
Beyond simple hashing, the system supports advanced cryptographic patterns for external verification and blockchain anchoring scenarios.
Time-Anchored Commitments with createCommitment
The createCommitment function (also in src/ledger/hash.ts) constructs a composite integrity object containing both the decision data hash (dataHash) and a millisecond-resolution timestamp. This object undergoes a second round of SHA-256 hashing to produce a commitment hash suitable for off-chain proofs or on-chain anchoring, establishing cryptographic proof that the decision existed at a specific point in time.
Runtime Integrity Verification
For audit scenarios, the verifyHash function recomputes the SHA-256 digest from stored decision fields and compares it against the persisted hash value. Any deviation—whether from data corruption, unauthorized modification, or serialization errors—results in an immediate mismatch, enabling instant detection of tampering. The companion shortHash utility provides the first eight characters of any full hash, offering human-readable identifiers for UI listings without compromising cryptographic security.
Practical Implementation Example
The following implementation demonstrates configuring the ledger for hash integrity and capturing a verified decision:
import { LedgerStorage } from './ledger/storage';
import { LedgerConfig } from './ledger/types';
import { createCommitment, verifyHash } from './ledger/hash';
// Initialize the ledger storage layer
const ledger = new LedgerStorage(dbInstance);
ledger.init();
// Configure cryptographic audit trails
const config: LedgerConfig = {
enabled: true,
captureAll: true,
hashIntegrity: true, // Enable SHA-256 hashing
retentionDays: 90,
onchainAnchor: false
};
// Define an AI trading decision
const decision = {
userId: 'trader_001',
category: 'trade',
action: 'buy',
inputs: { market: 'BTC-USD', side: 'buy', size: 0.5 },
constraints: [{ type: 'max_slippage', value: 0.01 }],
decision: 'approved',
reason: 'Signal confidence exceeds 80% threshold'
};
// Capture with integrity hashing
const ledgerId = ledger.capture(decision, {
hashIntegrity: config.hashIntegrity
});
// Generate optional commitment for external anchoring
const commitment = createCommitment(decision);
console.log('Commitment hash:', commitment.hash);
// Later verification workflow
const stored = ledger.get(ledgerId);
if (stored?.hash) {
const isValid = verifyHash(stored, stored.hash);
console.log(isValid ? 'Integrity verified' : 'Tampering detected');
}
Summary
- Deterministic serialization in
src/ledger/hash.tssorts JSON keys alphabetically and filters undefined values to guarantee identical SHA-256 hashes across all platforms. - White-listed fields via
HASH_FIELDSensure only relevant decision context contributes to the cryptographic digest, excluding volatile metadata. LedgerStorage.captureconditionally persists hashes to thetrade_ledgertable whenhashIntegrityis enabled inLedgerConfig.createCommitmentbinds decision hashes to millisecond timestamps, enabling off-chain verification and blockchain anchoring workflows.- Runtime verification via
verifyHashdetects any data tampering by recomputing and comparing digests at retrieval time.
Frequently Asked Questions
How does the system prevent hash collisions between different decision records?
The hashDecision function incorporates high-entropy fields including user ID, session ID, millisecond timestamps, and unique market identifiers within the HASH_FIELDS schema. Combined with SHA-256’s 256-bit output space, this ensures that distinct decision records produce statistically unique digests, while identical decisions produce reproducible hashes for verification purposes.
Can the hash integrity verification detect partial data corruption?
Yes. The verifyHash function recomputes the SHA-256 digest from the stored decision fields using the exact same deterministic serialization logic (alphabetically sorted keys, filtered undefined values). Any modification to whitelisted fields—whether bit-level corruption, truncation, or malicious alteration—results in a digest mismatch, triggering immediate integrity warnings during the verification workflow.
What happens if the hashIntegrity flag is disabled in the configuration?
When LedgerConfig.hashIntegrity is set to false, the LedgerStorage.capture method skips the hashDecision invocation and stores records with a null hash column. The decision data persists normally, but the system provides no cryptographic proof of integrity, making the audit trail vulnerable to undetected tampering or data corruption.
Is the commitment hash compatible with blockchain anchoring?
Yes. The createCommitment function generates a standardized JSON object containing the dataHash and timestamp, which is then hashed using SHA-256. This produces a compact 64-character digest suitable for inclusion in blockchain transactions, timestamping services, or distributed ledger anchors, providing immutable proof of decision existence without revealing sensitive underlying data.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →