ronald-ph/laravel-blockchain

A Laravel package for implementing blockchain ledger functionality with digital signatures.

Installs: 6

Dependents: 0

Suggesters: 0

Security: 0

Stars: 4

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/ronald-ph/laravel-blockchain

2.0.1 2025-11-09 08:27 UTC

This package is auto-updated.

Last update: 2025-11-09 14:51:53 UTC


README

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.