laravel-ledger-guard maintained by amreljako
Laravel LedgerGuard
Laravel LedgerGuard is a highly secure, production-grade, and tamper-evident financial ledger system for Laravel. Unlike traditional wallet packages that simply increment/decrement a balance column, LedgerGuard utilizes a strict Double-Entry Bookkeeping architecture combined with Blockchain-like cryptographic chaining and Pessimistic Locking to completely eliminate financial fraud, race conditions, and unauthorized database manipulation.
The Threat Model & Architecture
Traditional database structures for wallets are inherently insecure against multi-threaded application exploits or insider threats. LedgerGuard introduces an immutable infrastructure layer to protect financial records:
| Threat | Standard Wallet Design | LedgerGuard |
|---|---|---|
| Race Conditions / Double Spending | Vulnerable during high-concurrency requests (e.g., fast sequential API calls). | Employs strict database Pessimistic Locking (lockForUpdate) to queue concurrent transactions safely. |
| Direct Database Tampering | If an attacker or malicious insider alters a balance directly in the DB, the system accepts it blindly. | Tamper-Evident Hashing Chain: Every transaction is cryptographically chained to the previous one via SHA-256. Any manual alteration breaks the chain and triggers an instant lockdown. |
| Negative Balance Exploit | Relies solely on application-level checks, which can be bypassed via asynchronous requests. | Enforces strict unsignedDecimal constraints at the database engine level, making negative data insertion physically impossible. |
| Data Leakage / Privacy | Transaction metadata (e.g., bank notes, user references) is stored in plaintext. | Metadata payloads are automatically encrypted at rest using AES-256-GCM. |
Key Features
- Polymorphic Flexibility: Attach financial wallets to any Eloquent model (
User,Vendor,Company, etc.) seamlessly using Morph relations. - Immutable Ledger Records: Financial logs are legally immutable; the Eloquent model explicitly blocks
updateanddeleteactions at the kernel level. - Automatic Account Freezing: Instantly locks and freezes a ledger with custom alerts if malicious data integrity degradation is spotted during runtime audits.
- Full Audit Trail: Every single transaction automatically tracks the originator's IP Address and User-Agent out-of-the-box.
Installation
Install the package via Composer:
composer require amreljako/laravel-ledger-guard
Publish and run the secure migrations:
php artisan vendor:publish \
--provider="Amreljako\LedgerGuard\LedgerGuardServiceProvider" \
--tag="ledger-guard-migrations"
php artisan migrate
Optionally publish the config file:
php artisan vendor:publish \
--provider="Amreljako\LedgerGuard\LedgerGuardServiceProvider" \
--tag="ledger-guard-config"
Configuration
The published configuration file will be located at config/ledger-guard.php:
return [
/*
|--------------------------------------------------------------------------
| Default Currency
|--------------------------------------------------------------------------
| The default ISO currency code used when creating a new ledger wallet.
*/
'default_currency' => 'EGP',
/*
|--------------------------------------------------------------------------
| Auto-Freeze on Tamper
|--------------------------------------------------------------------------
| When enabled, the package will instantly freeze the ledger if any
| cryptographic chain misalignment or direct database manipulation
| is detected.
*/
'auto_freeze_on_tamper' => true,
];
Usage & Quick Start
1. Prepare Your Model
Add the HasLedger trait to any Eloquent model you wish to grant a secure financial wallet:
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Amreljako\LedgerGuard\Traits\HasLedger;
class User extends Authenticatable
{
use HasLedger;
}
2. Credit Money (Deposits / Inbound)
To safely deposit funds into a model's ledger:
use Amreljako\LedgerGuard\Facades\LedgerGuard;
// Fetch or create user ledger for a specific currency
$ledger = $user->ledger()->firstOrCreate(['currency' => 'EGP']);
// Safely credit funds with encrypted tracking metadata
LedgerGuard::credit($ledger, 1500.50, [
'reference_id' => 'TXN_99821',
'gateway' => 'Paymob',
'description' => 'Wallet Top up via Credit Card',
]);
3. Debit Money (Secure Purchases / Payouts)
To safely deduct funds from a wallet, wrapped automatically inside a database transaction with Pessimistic Locking:
use Amreljako\LedgerGuard\Facades\LedgerGuard;
use Illuminate\Support\Facades\Log;
try {
$ledger = $user->ledger()->where('currency', 'EGP')->first();
LedgerGuard::debit($ledger, 250.00, [
'order_id' => 'ORD_5541',
'item' => 'Cyberpunk Minimalist Hooded Jacket',
]);
echo "Payment successful! Balance securely updated.";
} catch (\Exception $e) {
// Automatically catches Insufficient Funds, Frozen Accounts,
// or Tampered Chains
Log::alert("Transaction blocked: " . $e->getMessage());
}
4. Fetch the Audited Balance
Calculates the real-time balance via double-entry arithmetic while simultaneously auditing the entire cryptographic signature chain:
// Returns a float representing the absolute safe balance
$secureBalance = $user->walletBalance('EGP');
Mathematical Cryptographic Chain
Each record inside the ledger_transactions table computes a rolling cryptographic signature:
$$\text{Current Hash} = \text{SHA256}(\text{ledger_id} \parallel \text{type} \parallel \text{amount} \parallel \text{previous_hash} \parallel \text{APP_KEY})$$
If an attacker gains direct access to your SQL database and attempts to alter a transaction amount, the ledger's mathematical equilibrium breaks. Upon the next balance calculation or transaction request, LedgerGuard:
- Flags the anomaly
- Halts execution
- Freezes the account
- Throws a Security Violation Exception