# blnkfinance/blnk — Kavach Visual Invariant Atlas

> Open-source double-entry financial ledger. Zero-memstore capture over real PostgreSQL datasource and Gin HTTP handlers.

- **Repository:** https://github.com/blnkfinance/blnk
- **Commit:** `064daa3` (branch `main`)
- **Proof Tier:** `gold_showcase`
- **Stateful Backend Supported:** `true`
- **Scan:** 331 ms · 151 files · $0.00 LLM tokens

## Detected Stateful Drivers & Gateways

| Driver | Language | Category | Kavach Adapter |
| :--- | :--- | :--- | :--- |
| `database/sql + pgx` | go | database | `kavachpgx` |
| `github.com/gin-gonic/gin` | go | http | `kavachhttp` |
| `github.com/redis/go-redis/v9` | go | cache | `kavachredis` |

## Extracted System Invariants (5)

| Invariant | Proof State | Category | Rule Kind | Evidence |
| :--- | :--- | :--- | :--- | :--- |
| `conservation_of_money` | `verified` | conservation | `conservation` | `.kavach/invariants.yaml` |
| `non_negative_transaction_amount` | `verified` | schema | `non_negative` | `.kavach/invariants.yaml` |
| `at_most_once_transaction_reference` | `verified` | transport | `at_most_once_emit` | `.kavach/invariants.yaml` |
| `no_silent_ledger_drop` | `verified` | transport | `anti_lobotomy` | `.kavach/invariants.yaml` |
| `double_entry_balances` | `verified` | schema | `non_negative` | `harness/internal/sqldb/sqlite.go:154-209` |

### `conservation_of_money`
- **Summary:** Declarative YAML conservation rule: sum($.deltas[*]) == 0 on every ledger:tx commit.
- **Proof State:** `verified`
- **Code:** `.kavach/invariants.yaml`

### `non_negative_transaction_amount`
- **Summary:** Declarative YAML non_negative rule: $.precise_amount >= 0 on every ledger:tx commit.
- **Proof State:** `verified`
- **Code:** `.kavach/invariants.yaml`

### `at_most_once_transaction_reference`
- **Summary:** Declarative YAML at_most_once_emit rule: unique $.reference across ledger:tx commits and duplicate redeliveries.
- **Proof State:** `verified`
- **Code:** `.kavach/invariants.yaml`

### `no_silent_ledger_drop`
- **Summary:** Declarative YAML anti_lobotomy rule: http:response, pg:exec, and ledger:tx output counts >= 100% of baseline.
- **Proof State:** `verified`
- **Code:** `.kavach/invariants.yaml`

### `double_entry_balances`
- **Summary:** Live SQL check on blnk.balances: sum(credit)==sum(debit), balance==credit-debit, inflight balance & non-negativity.
- **Proof State:** `verified`
- **Code:** `harness/internal/sqldb/sqlite.go:154-209`

## Guided Causal Flows

### B1: Repeated fixed payee overwrite & sweep failure
Two fixed payouts to @PartnerContractor overwrite $30 with $20 and shift $30 onto @PlatformEscrow.

1. **`in_bulk`**: POST /transactions/bulk (seq 66) submits an atomic bulk batch splitting $100: $30+$20 to @PartnerContractor, $50 to @PlatformEscrow, plus a $35 sweep from @PartnerContractor.
2. **`fn_create_bulk`**: CreateBulkTransactions assigns batchID and invokes QueueTransaction synchronously (SkipQueue: true).
3. **`fn_calc_dist`**: processFixedDistributions (model/transaction.go:165) overwrites fixedAmounts[@PartnerContractor]=3000 with 2000 while deducting both from amountLeftDec.
4. **`bug_b1`**: balanceDistributions sees sum=7000 < 10000 and credits the missing 3000 onto the largest leg (@PlatformEscrow: 5000 -> 8000).
5. **`sink_ledger_tx`**: Real SQL commits corrupted legs (2000 to @PartnerContractor, 8000 to @PlatformEscrow); the $35 sweep then fails HTTP 400 TXN_INSUFFICIENT_FUNDS.

### B1 (mixed): Fixed + percentage share overwrite
combineDistributions overwrites @AffiliatePartner's $25 fixed fee with its 25% share, crediting $25 onto @SellerMerchant.

1. **`in_bulk`**: POST /transactions/bulk (seq 66) splits $100 with fixed $25 + 25% to @AffiliatePartner and 50% to @SellerMerchant, followed by a $40 sweep from @AffiliatePartner.
2. **`fn_calc_dist`**: combineDistributions (model/transaction.go:282) writes result[@AffiliatePartner]=2500 (fixed) then overwrites it with 2500 (percent).
3. **`bug_b1`**: balanceDistributions adds the lost 2500 onto @SellerMerchant (5000 -> 7500), starving @AffiliatePartner so the $40 sweep fails TXN_INSUFFICIENT_FUNDS.
4. **`sink_ledger_tx`**: Real SQL commits 2500 to @AffiliatePartner and 7500 to @SellerMerchant before aborting.

### B3: Atomic SkipQueue bulk split rollback leak
When seq 66's sweep aborts the atomic batch, real SQL rollbackBatchTransactions finds 0 rows and leaks the corrupted split legs.

1. **`in_bulk`**: Batch runs with atomic: true and skip_queue: true over Gin HTTP.
2. **`fn_queue_tx`**: QueueTransaction (transaction_queue.go:108) takes the SkipQueue branch and omits MetaData['QUEUED_PARENT_TRANSACTION']=batchID.
3. **`fn_split_precise`**: SplitTransactionPrecise (model/transaction.go:475) overwrites each leg's ParentTransaction with the unpersisted split txn ID.
4. **`fn_rollback_batch`**: On sweep failure, real SQL GetRefundableTransactionsByParentID queries t.meta_data->>'QUEUED_PARENT_TRANSACTION' = $1, finds 0 rows, and leaves corrupted writes persisted.

## Replay-Verified Proofs (104/104 variants, 72/72 regressions)

- **B1: Repeated-Identifier Split Overwrite & Misdirection** (`model/transaction.go:165`) — Repeating a payee ID in a split overwrites the earlier share and credits it to an unrelated party. [52/52 variants · verdict `fixed`]
- **B2: Mixed Fixed + Percentage Split Over-Allocation** (`model/transaction.go:229-235`) — Validates % <= 100 and fixed <= total separately, allowing >100% over-debits before abort. [52/52 variants · verdict `fixed`]
- **B3: Sync Atomic Bulk Split Rollback Drop** (`transaction_queue.go:97-128`) — Atomic bulk abort fails to link split legs via QUEUED_PARENT_TRANSACTION, leaving debits committed. [104/104 variants · verdict `fixed`]

## Starter `.kavach/invariants.yaml`

```yaml
# Declarative Kavach invariants — checked on every replay and mutated variant.
# Kinds: conservation, non_negative, at_most_once_emit, anti_lobotomy
service: blnk
invariants:
  - name: conservation_of_money
    kind: conservation
    sink: ledger:tx
    field: $.deltas[*]

  - name: non_negative_transaction_amount
    kind: non_negative
    sink: ledger:tx
    field: $.precise_amount

  - name: at_most_once_transaction_reference
    kind: at_most_once_emit
    sink: ledger:tx
    key: $.reference

  - name: no_silent_ledger_drop
    kind: anti_lobotomy
    sinks: [http:response, pg:exec, ledger:tx]
    min_ratio_vs_baseline: 1.0
```

## Driver Wrap Snippet

```text
import (
  "github.com/kavachlabs/kavach-go/kavachpgx"
  "github.com/kavachlabs/kavach-go/kavachhttp"
)

ds := kavachpgx.WrapStatefulConnector(sqlDB)
router := kavachhttp.WrapHandler(ginEngine)
```

## Run Locally (Zero Upload)

```bash
brew install kavachlabs/tap/kavach && kavach map --auto --open
```
