Merkle-Tree
A TypeScript implementation of a checkpoint management system using Merkle trees for file integrity verification.
🚀 What it does
Creates and manages project checkpoints with cryptographic integrity:
- Scans project directories and builds Merkle trees
- Stores complete file contents with SHA-256 hashing
- Restores exact project states from any checkpoint
- Verifies file integrity using Merkle tree root hashes
- Manages checkpoint lifecycle (create, list, restore, delete)
📦 Installation
git clone https://github.com/NeaByteLab/Merkle-Tree.git
cd Merkle-Tree
npm install
npm run build
🎯 Usage
Basic Operations
import merkleCheckpoint from './dist/index.js'
// Create checkpoint
const checkpoint = merkleCheckpoint.create('/path/to/project', 'Before refactor')
console.log(checkpoint.id) // UUID
// List checkpoints
const checkpoints = merkleCheckpoint.get('/path/to/project')
console.log(checkpoints.length) // Number of checkpoints
// Restore checkpoint
const success = merkleCheckpoint.restore('/path/to/project', checkpoint.id)
console.log(success) // true if successful
// Delete checkpoint
const deleted = merkleCheckpoint.delete('/path/to/project', checkpoint.id)
console.log(deleted) // true if deleted
API
merkleCheckpoint.create(projectPath, description)
Creates a new checkpoint for the project.
Parameters:
projectPath (string): Root path of the project to checkpoint
description (string): Human-readable description for the checkpoint
Returns: CheckpointList - Checkpoint metadata object
{
id: string, // UUID identifier
description: string, // Checkpoint description
fileCount: number, // Number of files tracked
rootHash: string, // Merkle tree root hash
timestamp: number, // Creation timestamp
totalSize: number // Total size in bytes
}
merkleCheckpoint.get(projectPath)
Retrieves all checkpoints for a project.
Parameters:
projectPath (string): Root path of the project
Returns: CheckpointList[] - Array of checkpoint metadata objects
merkleCheckpoint.restore(projectPath, checkpointId)
Restores the project to a specific checkpoint state.
Parameters:
projectPath (string): Root path where files should be restored
checkpointId (string): UUID of the checkpoint to restore
Returns: boolean - true if restore was successful, false otherwise
Note: Automatically removes files not present in the target checkpoint while preserving system directories (.git, node_modules, dist, build).
merkleCheckpoint.delete(projectPath, checkpointId)
Deletes a specific checkpoint and its associated data.
Parameters:
projectPath (string): Root path of the project
checkpointId (string): UUID of the checkpoint to delete
Returns: boolean - true if deletion was successful, false otherwise
🔧 Implementation Details
flowchart TB
A[Project Directory] --> B[Scan Files]
B --> C[Filter System Files]
C --> D[Generate File Hashes]
D --> E[Build Merkle Tree]
E --> F[Create Checkpoint]
F --> G[Store Metadata]
F --> H[Store File Contents]
I[Restore Request] --> J[Load Checkpoint Data]
J --> K[Remove Extra Files]
K --> L[Recreate Directories]
L --> M[Write Files]
M --> N[Verify Integrity]
O[Delete Request] --> P[Remove Metadata]
P --> Q[Delete File Storage]
style A fill:#e1f5fe,color:#000
style F fill:#c8e6c9,color:#000
style I fill:#fff3e0,color:#000
style O fill:#ffebee,color:#000
Loading
Merkle Tree Construction
- Leaf Generation: Each file becomes a leaf node with its SHA-256 hash
- Tree Building: Parent nodes created by hashing concatenated child hashes
- Root Hash: Single hash representing entire file system state
- Integrity: Any file change produces different root hash
// Tree building algorithm
while (currentLevel.length > 1) {
const nextLevel: MerkleNode[] = []
for (let i = 0; i < currentLevel.length; i += 2) {
const left = currentLevel[i]
const right = currentLevel[i + 1] ?? left // Duplicate last node if odd count
const combinedHash = this.hash(left.hash + right.hash)
nextLevel.push({ hash: combinedHash, left, right })
}
currentLevel = nextLevel
}
File System Operations
Checkpoint Creation
- Scan project directory recursively
- Filter out system directories (
.git, node_modules, dist, build)
- Filter out temporary files (
.DS_Store, *.log, *.tmp)
- Build Merkle tree from remaining files
- Generate checkpoint metadata
- Store complete file contents in
.checkpoints/{id}.json
Checkpoint Restoration
- Load checkpoint data from storage
- Remove extra files not present in checkpoint
- Recreate directory structure
- Write all files with exact content
- Rebuild Merkle tree for verification
🗃️ Storage Format
Metadata Storage (.checkpoints/entries.json)
[
{
"id": "uuid",
"description": "Checkpoint description",
"fileCount": 14,
"rootHash": "sha256-hash",
"timestamp": 1759799312188,
"totalSize": 146601
}
]
Checkpoint Storage (.checkpoints/{id}.json)
{
"id": "uuid",
"timestamp": 1759799312188,
"description": "Checkpoint description",
"rootHash": "sha256-hash",
"fileCount": 14,
"totalSize": 146601,
"files": [
{
"path": "src/index.ts",
"content": "file content...",
"hash": "sha256-hash",
"size": 1024,
"mtime": 1759799294268
}
],
"merkleTree": { /* complete tree structure */ }
}
🔧 Build Process
npm run format # Prettier formatting
npm run lint:fix # ESLint with auto-fix
npm run clean # Remove dist and build artifacts
npm run build # TypeScript compilation + minification
⚠️ Error Handling
- Non-existent directory: Throws
Error with descriptive message
- Non-existent checkpoint: Returns
false for restore/delete operations
- File system errors: Propagated with original error messages
- Corrupted checkpoint data: Restore operation fails gracefully
📄 License
This project is licensed under the MIT license. See the LICENSE file for more info.