Skip to content

A TypeScript checkpoint management system using Merkle trees for file integrity verification and project state restoration capabilities.

License

Notifications You must be signed in to change notification settings

NeaByteLab/Merkle-Tree

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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

  1. Leaf Generation: Each file becomes a leaf node with its SHA-256 hash
  2. Tree Building: Parent nodes created by hashing concatenated child hashes
  3. Root Hash: Single hash representing entire file system state
  4. 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

  1. Scan project directory recursively
  2. Filter out system directories (.git, node_modules, dist, build)
  3. Filter out temporary files (.DS_Store, *.log, *.tmp)
  4. Build Merkle tree from remaining files
  5. Generate checkpoint metadata
  6. Store complete file contents in .checkpoints/{id}.json

Checkpoint Restoration

  1. Load checkpoint data from storage
  2. Remove extra files not present in checkpoint
  3. Recreate directory structure
  4. Write all files with exact content
  5. 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.