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.
- β 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
Install the package via Composer:
composer require ronald-ph/laravel-blockchainPublish the configuration file:
php artisan vendor:publish --tag=blockchain-configPublish and run the migrations:
php artisan vendor:publish --tag=blockchain-migrations
php artisan migrateGenerate cryptographic keys for signing blocks:
php artisan blockchain:generate-keys --password=yourpasswordSet the private key password in your .env file:
BLOCKCHAIN_PRIVATE_KEY_PASSWORD=yourpasswordThis release introduces user-specific certificates, health checks, and enhanced chain verification.
Update the package:
composer update ronald-ph/laravel-blockchainRepublish config and migrations if needed:
php artisan vendor:publish --tag=blockchain-config --force
php artisan vendor:publish --tag=blockchain-migrations --force
php artisan migrateRegenerate keys if necessary and set the password in .env.
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.pemuse 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
);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 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')
);$result = Blockchain::verifyBlock($blockHash);
if ($result['valid']) {
echo "Block is valid!";
} else {
echo "Block verification failed: " . $result['message'];
}$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']);
}$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!";
}$history = Blockchain::getHistory('users', $userId);
foreach ($history as $block) {
echo "Block #{$block->id} - {$block->created_at}\n";
echo "Hash: {$block->block_hash}\n";
}// 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);php artisan blockchain:generate-keys --password=yourpassword --bits=4096php artisan blockchain:verify users 1Output:
β Entire chain is valid
Total blocks verified: 5
Run comprehensive system health checks:
php artisan blockchain:healthOutput:
π 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 --jsonCreate 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();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')
);
});
}
}// Update default certificate for the application
$certificate = Blockchain::updateDefaultCertificate(
file_get_contents('/path/to/private.pem'),
file_get_contents('/path/to/public.pem')
);// 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);-
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
- π 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
composer testThis package is open-sourced software licensed under the MIT License
Developed by Ronald PH
π¦ GitHub Repository
For issues and questions, please use the GitHub issue tracker.
