Skip to content

Ronald-PH/laravel-blockchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Laravel Blockchain Banner

⚑ Laravel Blockchain

A comprehensive Laravel package for implementing blockchain ledger functionality with RSA-based digital signatures, Merkle root verification, and user-specific certificates to ensure data integrity, provide an immutable audit trail, and enable advanced security features like fork detection and health monitoring.

Packagist Version License PHP Laravel

πŸš€ Features

  • βœ… Immutable blockchain records for any Eloquent model
  • βœ… RSA-based digital signature verification for cryptographic security
  • βœ… Chain integrity checks and data tamper detection
  • βœ… Full audit trail of all data changes with timestamps
  • βœ… Artisan commands for key generation, chain verification, and health checks
  • βœ… Configurable hash algorithms (SHA-256, SHA-512, etc.)
  • βœ… Support for custom cryptographic keys and password-protected private keys
  • βœ… User-specific certificates for multi-user applications and enhanced security
  • βœ… Merkle root verification for additional integrity and hierarchical signing
  • βœ… Health check command for comprehensive system monitoring
  • βœ… Fork detection to prevent and identify chain manipulations
  • βœ… Comprehensive verification (individual blocks, entire chains, data integrity)
  • βœ… Automatic chain verification on block creation (configurable)
  • βœ… Multiple key management (default certificates and user-specific certificates)
  • βœ… Exception handling with custom BlockchainException for robust error management
  • βœ… Model relationships for certificates and ledgers

πŸ“¦ Installation

Install the package via Composer:

composer require ronald-ph/laravel-blockchain

Publish the configuration file:

php artisan vendor:publish --tag=blockchain-config

Publish and run the migrations:

php artisan vendor:publish --tag=blockchain-migrations
php artisan migrate

Generate cryptographic keys for signing blocks:

php artisan blockchain:generate-keys --password=yourpassword

Set the private key password in your .env file:

BLOCKCHAIN_PRIVATE_KEY_PASSWORD=yourpassword

⚑ Upgrade from v1.2.1 to v2.0.0

This release introduces user-specific certificates, health checks, and enhanced chain verification.

Update the package:

composer update ronald-ph/laravel-blockchain

Republish config and migrations if needed:

php artisan vendor:publish --tag=blockchain-config --force
php artisan vendor:publish --tag=blockchain-migrations --force
php artisan migrate

Regenerate keys if necessary and set the password in .env.

βš™οΈ Configuration

The configuration file is located at config/blockchain.php. Key settings include:

return [
    'table_name' => 'blockchain_ledgers', // Main ledger table name
    'hash_algorithm' => 'sha256', // Hash algorithm for block hashing
    'keys_path' => storage_path('blockchain/keys'), // Path to store keys
    'private_key' => 'private.pem', // Default private key file
    'public_key' => 'public.pem', // Default public key file
    'private_key_password' => env('BLOCKCHAIN_PRIVATE_KEY_PASSWORD'), // Password for private key
    'genesis_hash' => '00000', // Genesis block hash
    'auto_verify' => false, // Auto-verify chain on block creation
    'with_blockchain_root' => false, // Enable Merkle root verification
    'master_private_key' => 'master_private.pem', // Master private key for Merkle roots
    'master_public_key' => 'master_public.pem', // Master public key for Merkle roots
    'master_private_key_password' => env('BLOCKCHAIN_MASTER_PRIVATE_KEY_PASSWORD'), // Master key password
];

To enable Merkle root verification, set 'with_blockchain_root' => true and generate master keys:

openssl genrsa -out master_private.pem 4096
openssl rsa -in master_private.pem -pubout -out master_public.pem

Usage

🧩 Basic Usage

use RonaldPH\LaravelBlockchain\Facades\Blockchain;

// Create a user
$user = User::create([
    'name' => 'Juan Dela Cruz',
    'email' => 'juan@example.com',
]);

// Create blockchain record
$block = Blockchain::createBlock(
    'users',                                      // table name
    $user->id,                                    // record ID
    $user->only('id', 'name', 'email')           // data to hash
);

πŸ“€ Using with Request (File Upload)

use Illuminate\Http\Request;
use RonaldPH\LaravelBlockchain\Facades\Blockchain;

public function store(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'private_key' => 'file', // Optional for user-specific certificates
        'private_key_password' => 'string', // Optional for user-specific certificates
    ]);

    $user = User::create([
        'email' => $request->email,
    ]);

    // Create block with optional user-specific private key
    $block = Blockchain::createBlock(
        'users',
        $user->id,
        json_encode($user->only('id', 'email', 'created_at')),
        Auth::user()->id, // Optional: user ID
        $request->file('private_key'), // Optional: user-specific key
        $request->private_key_password // Optional: password
    );

    return response()->json(['user' => $user, 'block' => $block]);
}

πŸ”„ Update & Chain Blocks

// Update user
$user->update(['email' => 'juan@example.com']);

// Create new blockchain block for the update
$block = Blockchain::createBlock(
    'users',
    $user->id,
    $user->only('id', 'email', 'updated_at')
);

πŸ” Verification

Verify a Block

$result = Blockchain::verifyBlock($blockHash);

if ($result['valid']) {
    echo "Block is valid!";
} else {
    echo "Block verification failed: " . $result['message'];
}

Verify Entire Chain

$result = Blockchain::verifyChain('users', $userId);

if ($result['valid']) {
    echo "Chain is valid! Total blocks: " . $result['total_blocks'];
} else {
    echo "Chain verification failed!";
    print_r($result['invalid_blocks']);
}

Verify Data Integrity

$user = User::find($userId);

$result = Blockchain::verifyData(
    'users',
    $user->id,
    $user->only('id', 'email', 'updated_at')
);

if ($result['valid']) {
    echo "Data has not been tampered with!";
} else {
    echo "Data tampering detected!";
}

Get Blockchain History

$history = Blockchain::getHistory('users', $userId);

foreach ($history as $block) {
    echo "Block #{$block->id} - {$block->created_at}\n";
    echo "Hash: {$block->block_hash}\n";
}

πŸ” Using Custom Keys

// Set custom private and public keys for a specific operation
$block = Blockchain::setPrivateKey('/path/to/private.pem', 'password')
    ->setPublicKey('/path/to/public.pem')
    ->createBlock('users', $userId, $data);

// Verify with custom public key
$result = Blockchain::setPublicKey('/path/to/public.pem')
    ->verifyBlock($blockHash);

🧰 Artisan Commands

Generate Keys

php artisan blockchain:generate-keys --password=yourpassword --bits=4096

Verify Chain

php artisan blockchain:verify users 1

Output:

βœ“ Entire chain is valid
Total blocks verified: 5

Health Check

Run comprehensive system health checks:

php artisan blockchain:health

Output:

πŸ” Blockchain Health Check
═══════════════════════════════════════════════════

+----------------+-----------------------------+--------+--------------------------------+
| Category       | Check                       | Status | Details                        |
+----------------+-----------------------------+--------+--------------------------------+
| Environment    | PHP Version                 | βœ“      | 8.2.0                          |
| Environment    | OpenSSL Extension           | βœ“      | OK                             |
| Environment    | JSON Extension              | βœ“      | OK                             |
| Environment    | App Environment             | βœ“      | local                          |
| Keys           | Keys Directory Exists       | βœ“      | /path/to/storage/blockchain    |
| Keys           | Private Key Exists          | βœ“      | βœ“                              |
| Keys           | Private Key Readable        | βœ“      | βœ“                              |
| Keys           | Private Key Format          | βœ“      | Valid PEM                      |
| Keys           | Private Key Size            | βœ“      | 1.8 KB                         |
| Keys           | Public Key Exists           | βœ“      | βœ“                              |
| Keys           | Public Key Readable         | βœ“      | βœ“                              |
| Keys           | Public Key Format           | βœ“      | Valid PEM                      |
| Keys           | Private Key Password Set    | βœ“      | Configured                     |
| Database       | Connection                  | βœ“      | Connected                      |
| Database       | Database Name               | βœ“      | laravel                        |
| Database       | Table Exists                | βœ“      | blockchain_ledgers             |
| Database       | Table Schema                | βœ“      | Valid                          |
| Database       | Indexes                     | βœ“      | 4 indexes                      |
| Database       | Total Blocks                | βœ“      | 1,234                          |
| Database       | Table Size                  | βœ“      | 15.67 MB                       |
| Permissions    | Keys Directory              | βœ“      | Writable (Perms: 0755)         |
| Permissions    | Logs Directory              | βœ“      | Writable                       |
| Permissions    | Storage Directory           | βœ“      | Writable                       |
| Configuration  | Hash Algorithm              | βœ“      | sha256                         |
| Configuration  | Genesis Hash                | βœ“      | 00000                          |
| Configuration  | Auto Verify                 | βœ“      | Disabled                       |
| Configuration  | Keys Path                   | βœ“      | /path/to/storage/blockchain    |
| Configuration  | Production Security         | βœ“      | N/A (not production)           |
| Activity       | Last 24 Hours               | βœ“      | 45 blocks                      |
| Activity       | Last 7 Days                 | βœ“      | 312 blocks                     |
| Activity       | Last 30 Days                | βœ“      | 1,156 blocks                   |
| Activity       | Latest Block                | βœ“      | 2 hours ago                    |
| Activity       | Latest Block Hash           | βœ“      | a1b2c3d4...                    |
| Activity       | Tables Tracked              | βœ“      | 8                              |
| Chain Integrity| Sample Verification         | βœ“      | 5/5 valid chains               |
| Chain Integrity| Orphaned Blocks             | βœ“      | 0 blocks                       |
| Metrics        | Blocks Created              | βœ“      | 1,234                          |
| Metrics        | Block Creation Failures     | βœ“      | 0                              |
| Metrics        | Successful Verifications    | βœ“      | 987                            |
| Metrics        | Invalid Signatures          | βœ“      | 0                              |
| Metrics        | Hash Mismatch               | βœ“      | 0                              |
| Metrics        | Chain Breaks                | βœ“      | 0                              |
| Metrics        | Data Tampering Detected     | βœ“      | 0                              |
| Disk Space     | Free Space                  | βœ“      | 45.2 GB                        |
| Disk Space     | Total Space                 | βœ“      | 100 GB                         |
| Disk Space     | Used                        | βœ“      | 54.8%                          |
+----------------+-----------------------------+--------+--------------------------------+

═══════════════════════════════════════════════════
Summary: 45/45 checks passed
πŸŽ‰ All checks passed! System is healthy.

Options:

# Detailed output
php artisan blockchain:health --detailed

# JSON output for monitoring systems
php artisan blockchain:health --json

🧠 Advanced Usage

πŸ”Έ Model Trait (Optional)

Create a trait to easily add blockchain to your models:

namespace App\Traits;

use RonaldPH\LaravelBlockchain\Facades\Blockchain;

trait HasBlockchain
{
    public function createBlockchainRecord($data = null)
    {
        $data = $data ?? $this->toArray();

        return Blockchain::createBlock(
            $this->getTable(),
            $this->id,
            $data
        );
    }

    public function getBlockchainHistory()
    {
        return Blockchain::getHistory($this->getTable(), $this->id);
    }

    public function verifyBlockchain()
    {
        return Blockchain::verifyChain($this->getTable(), $this->id);
    }
}

Use in your model:

class User extends Model
{
    use HasBlockchain;
}

// Usage
$user->createBlockchainRecord();
$history = $user->getBlockchainHistory();
$result = $user->verifyBlockchain();

πŸ”Έ Model Events (Auto-create blocks)

class User extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::created(function ($user) {
            Blockchain::createBlock(
                'users',
                $user->id,
                $user->only('id', 'email', 'created_at')
            );
        });

        static::updated(function ($user) {
            Blockchain::createBlock(
                'users',
                $user->id,
                $user->only('id', 'email', 'updated_at')
            );
        });
    }
}

πŸ”Έ Certificate Management

Default Certificate Management

// Update default certificate for the application
$certificate = Blockchain::updateDefaultCertificate(
    file_get_contents('/path/to/private.pem'),
    file_get_contents('/path/to/public.pem')
);

User-Specific Certificates

// Update user-specific certificate for multi-user security
$certificate = Blockchain::updateModelCertificate(
    $userId,
    file_get_contents('/path/to/private.pem'),
    file_get_contents('/path/to/public.pem')
);

// Retrieve a user's certificate
$userCertificate = Blockchain::getModelCertificate($userId);

βš™οΈ How It Works

  1. Block Creation: When you create a block, the package:

    • Hashes your data using the configured algorithm (e.g., SHA-256)
    • Chains it to the previous block's hash (or genesis hash for the first block)
    • Creates a unique block hash combining data, previous hash, and timestamp
    • Signs the block with RSA private key (default or user-specific)
    • Optionally signs with master key for Merkle root verification
    • Stores the block, signature, and metadata in the blockchain_ledgers table
  2. Verification: When verifying:

    • Recalculates the block hash to ensure data integrity
    • Verifies the RSA digital signature using the corresponding public key
    • Checks chain continuity by validating previous hash links
    • Detects forks, tampering, or broken chains
    • For Merkle root enabled: Verifies hierarchical signatures
  3. Data Integrity: The blockchain ensures:

    • Immutable records with cryptographic tamper detection
    • Complete chronological audit trail of all changes
    • Cryptographic proof of authenticity and non-repudiation
    • Tamper-evident history with fork detection capabilities
    • Support for both default and user-specific certificate management

πŸ›‘οΈ Security Recommendations

  • πŸ” Never commit private keys to version control - Use .gitignore for key files
  • 🧱 Store keys securely in storage/blockchain/keys with restricted permissions (e.g., 0700)
  • πŸ’ͺ Use strong passwords for private keys and rotate them periodically
  • πŸ’Ύ Regularly back up both cryptographic keys and blockchain ledger data
  • πŸ” Run health checks (php artisan blockchain:health) regularly to monitor system integrity
  • πŸ›οΈ Enable Merkle root verification for hierarchical signing and enhanced security
  • πŸ‘€ Use user-specific certificates in multi-user applications for isolated security
  • πŸ”’ Enable auto-verification in config for real-time chain integrity checks
  • 🚨 Monitor for forks using the verification commands to detect tampering attempts
  • πŸ“Š Log and audit all blockchain operations for compliance and security monitoring

πŸ§ͺ Testing

composer test

πŸ“œ License

This package is open-sourced software licensed under the MIT License

πŸ’‘ Credits

Developed by Ronald PH
πŸ“¦ GitHub Repository

Support

For issues and questions, please use the GitHub issue tracker.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages