How CloddsBot Ensures Trade Ledger Integrity with SHA-256 Hashing
CloddsBot guarantees trade ledger integrity by computing deterministic SHA-256 hashes of immutable decision fields, storing them in the ledger database, and optionally anchoring them on-chain to create tamper-proof audit trails.
CloddsBot is an open-source trading automation framework that cryptographically secures every decision using SHA-256 hashing. The trade ledger integrity system ensures that once a trading decision is recorded, any alteration—whether accidental or malicious—can be detected instantly through hash verification. This article examines the implementation details found in the alsk1992/CloddsBot repository, breaking down how deterministic hashing, persistent storage, and optional blockchain anchoring work together to create an immutable audit trail.
Deterministic Hash Generation in src/ledger/hash.ts
The foundation of the integrity system lies in the hashDecision function located in src/ledger/hash.ts. This utility creates a deterministic fingerprint of every trading decision by processing a fixed set of immutable fields.
When a decision is captured, the function gathers fields such as userId, sessionId, timestamp, category, action, and reason. These fields are sorted alphabetically, serialized to JSON, and passed to Node.js's native crypto.createHash('sha256') to generate a 64-character hexadecimal digest. Because the input fields are immutable and the serialization order is fixed, any modification to the recorded data produces a completely different hash value, immediately signaling tampering.
Persisting Hashes with LedgerStorage.capture
The LedgerStorage class in src/ledger/storage.ts handles the persistence of decision records alongside their cryptographic proofs. The capture method accepts a hashIntegrity boolean flag that triggers hash computation and storage.
When hashIntegrity is set to true, the method invokes hashDecision and writes the resulting 64-character hex digest to the hash column of the trade_ledger table. This couples each database record with its SHA-256 fingerprint, enabling local verification at any point in the future without external dependencies.
Optional On-Chain Anchoring for Tamper-Proofing
For environments requiring the highest assurance levels, CloddsBot supports anchoring ledger hashes to public blockchains through src/ledger/anchor.ts. The anchor service supports Solana (via memo instructions), Polygon, and Base (via calldata).
The createAnchorService factory initializes a connection to the specified chain. When anchor is called, it formats the hash into a prefixed string clodds:ledger:<hash> and submits it as a transaction. This creates an immutable, timestamped proof on the blockchain that can be used to verify the ledger state existed at a specific block time.
Verifying Ledger Integrity
CloddsBot provides dual verification mechanisms to validate trade ledger integrity against stored or anchored hashes.
Local Hash Verification
The verifyHash function in src/ledger/hash.ts re-computes the SHA-256 digest from a retrieved DecisionRecord using the same deterministic algorithm as hashDecision. It compares the freshly computed hash against the stored value; if they match, the record is verified intact.
On-Chain Anchor Verification
For records anchored to a blockchain, the verifyAnchor function retrieves the transaction by hash and inspects the memo or calldata field. It validates that the payload contains the exact clodds:ledger:<hash> string associated with the decision record, confirming the hash was committed to the chain at the claimed timestamp.
Implementation Examples
The following examples demonstrate how to capture decisions with integrity hashing, verify them locally, and anchor them to Solana.
Capturing a Decision with Integrity Hashing
Use the LedgerStorage.capture method with the hashIntegrity option enabled:
import { LedgerStorage } from '@/ledger/storage';
import { DecisionRecord } from '@/ledger/types';
// Assume `db` is an SQLite-compatible DB object
const ledger = new LedgerStorage(db);
ledger.init();
const decision: Omit<DecisionRecord, 'id' | 'timestamp' | 'hash'> = {
userId: 'U123',
sessionId: 'S456',
category: 'trade',
action: 'buy',
platform: 'binance',
marketId: 'BTC-USD',
inputs: { amount: 0.1 },
analysis: { signal: 'bullish' },
constraints: [],
confidence: 92,
decision: 'approved',
reason: 'trend breakout',
};
const ledgerId = ledger.capture(decision, { hashIntegrity: true });
console.log('Stored decision ID:', ledgerId);
Verifying the Stored Hash
Retrieve the record and validate its integrity using verifyHash:
import { LedgerStorage } from '@/ledger/storage';
import { verifyHash } from '@/ledger/hash';
const stored = ledger.get(ledgerId);
if (stored && stored.hash) {
const isValid = verifyHash(stored, stored.hash);
console.log('Integrity check:', isValid ? 'OK' : 'FAIL');
}
Anchoring to Solana
Create an anchor service and commit the hash on-chain:
import { createAnchorService } from '@/ledger/anchor';
const anchor = createAnchorService({
chain: 'solana',
solanaRpcUrl: 'https://api.mainnet-beta.solana.com',
solanaPrivateKey: process.env.SOLANA_PRIVATE_KEY,
});
const result = await anchor.anchor(stored!.hash!);
if (result.success) {
console.log('Anchored on Solana, tx:', result.txHash);
}
Verifying the On-Chain Anchor
Confirm the hash exists on-chain using the transaction hash:
import { verifyAnchor } from '@/ledger/anchor';
const verification = await verifyAnchor(result.txHash!, stored!.hash!, 'solana');
console.log('On-chain verification:', verification.verified);
Key Source Files
The integrity architecture spans four primary files in the src/ledger/ directory:
- src/ledger/hash.ts: Implements deterministic SHA-256 hashing (
hashDecision), verification (verifyHash), and commitment utilities. - src/ledger/storage.ts: Persists decision records and manages the
hashcolumn viaLedgerStorage.capture. - src/ledger/anchor.ts: Provides on-chain anchoring for hashes (Solana memo, Polygon/Base calldata) and verification via
verifyAnchor. - src/ledger/types.ts: Defines the
DecisionRecordinterface and related type definitions used throughout the ledger.
Summary
- Deterministic hashing: The
hashDecisionfunction insrc/ledger/hash.tsgenerates SHA-256 digests from immutable decision fields to create unique fingerprints. - Persistent storage:
LedgerStorage.captureinsrc/ledger/storage.tsstores hashes alongside records when thehashIntegrityflag is enabled. - Blockchain anchoring: The anchor service in
src/ledger/anchor.tsoptionally commits hashes to Solana, Polygon, or Base for immutable timestamping. - Dual verification:
verifyHashenables local integrity checks, whileverifyAnchorvalidates on-chain proofs againstclodds:ledger:<hash>formatted payloads.
Frequently Asked Questions
What specific fields are included in the SHA-256 hash calculation?
The hashDecision function includes immutable fields such as userId, sessionId, timestamp, category, action, platform, marketId, inputs, analysis, constraints, confidence, decision, and reason. These fields are sorted alphabetically, serialized to JSON, and concatenated before being hashed by crypto.createHash('sha256').
Is blockchain anchoring required to verify trade ledger integrity?
No. Local verification using verifyHash requires only the stored decision record and its associated hash from the trade_ledger table. Blockchain anchoring via src/ledger/anchor.ts is optional and designed for use cases requiring external, cryptographically secure timestamp authority.
Which blockchain networks does CloddsBot support for hash anchoring?
According to the source code in src/ledger/anchor.ts, CloddsBot supports anchoring to Solana (using memo instructions), Polygon, and Base (using transaction calldata). The hash is consistently formatted as clodds:ledger:<hash> regardless of the target chain.
How does the system detect tampering in a ledger record?
During verification, verifyHash re-computes the SHA-256 digest from the stored fields using the same deterministic algorithm as the original hashDecision call. If any field was modified after storage, the computed 64-character hex digest will differ from the stored hash value, causing verifyHash to return false and flag the record as compromised.
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 →