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
Requires
- php: ^8.1
- illuminate/database: ^9.0|10.0|^11.0|^12.0
- illuminate/support: ^9.0|10.0|^11.0|^12.0
Requires (Dev)
- orchestra/testbench: ^8.0|^9.0|^10.0
- phpunit/phpunit: ^10.0
README
โก 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.
๐ 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
-
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
-
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
-
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/keyswith 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.
