Pular para o conteúdo

Transação Bancária com Auditoria

Cada movimentação deixa registro imutável na cadeia de hashes da conta (quem, IP, valor, saldo antes e depois); a verificação reconcilia os movimentos com o saldo.

passos
4
arquivos
7
testes
0
tecnologias
6

Cenário

PIX de R$ 500,00 de Alice para Bruno: débito e crédito em cada trilha com o mesmo transfer_id; saldo alterado por fora deixa de fechar.

Planta

Sequência
5/5
BEGIN, FOR UPDATE nas duas contas em ordem de id1debita e credita, COMMIT2pix.debited na cadeia da 0001-13pix.credited na cadeia da 0002-94reconcilia abertura + movimentos = saldo5pixTransferaccountsaudit_movements
5

5 passos — reproduza para seguir o fluxo

Como funciona

4passos

Cada movimentação deixa registro imutável na cadeia de hashes da conta (quem, IP, valor, saldo antes e depois)

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    A transferência trava as contas em ordem de id e commita

  2. 2

    Após o commit, débito e crédito na cadeia de cada conta

  3. 3

    Trava por conta (audit_heads): contas em paralelo

  4. 4

    Abertura + movimentos = saldo; RULE impede UPDATE e DELETE

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Pega saldo alterado por fora

  • Cadeia por conta não serializa tudo

Custos

  • Falha entre commit e append: a reconciliação acusa

  • Verificar a instituição percorre todas as cadeias

Código

pattern/security/bank-transaction-audit

7 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec bank-transaction-audit-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f bank-transaction-audit-db

Saída: após o PIX, auditedCents 950000 = balanceCents 950000 e reconciled: true; com o saldo alterado por fora, balanceCents 1050000 e reconciled: false.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: a PIX audited in each account's own hash chain; the verification reconciles audited movements with the balance.
import { createHash } from "node:crypto";
import pg from "pg";

type Movement = { accountId: string; eventType: "pix.debited" | "pix.credited"; transferId: string; amountCents: number; balanceBeforeCents: number; balanceAfterCents: number; actorId: string; ipAddress: string };
const pool = new pg.Pool({ connectionString: Bun.env.BANK_TRANSACTION_AUDIT_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/bank_audit_db" });
const FIELDS = ["accountId", "eventType", "transferId", "amountCents", "balanceBeforeCents", "balanceAfterCents", "actorId", "ipAddress"] as const;
const movementHash = (previousHash: string, movement: Movement, createdAtIso: string) => createHash("sha256").update([previousHash, ...FIELDS.map((field) => String(movement[field])), createdAtIso].join("|")).digest("hex");

// One chain per account: locking only that account's head lets different accounts be audited in parallel.
async function movementAudit(movement: Movement): Promise<void> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const { rows: [head] } = await client.query<{ last_hash: string }>("SELECT last_hash FROM audit_heads WHERE account_id = $1 FOR UPDATE", [movement.accountId]);
    if (!head) throw new Error(`audit head of ${movement.accountId} missing`);
    const createdAt = new Date().toISOString();
    const hash = movementHash(head.last_hash, movement, createdAt);
    await client.query("INSERT INTO audit_movements (account_id, event_type, transfer_id, amount_cents, balance_before_cents, balance_after_cents, actor_id, ip_address, previous_hash, hash, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", [...FIELDS.map((field) => movement[field]), head.last_hash, hash, createdAt]);
    await client.query("UPDATE audit_heads SET last_hash = $2 WHERE account_id = $1", [movement.accountId, hash]);
    await client.query("COMMIT");
  } catch (error) {
    await client.query("ROLLBACK");
    throw error;
  } finally {
    client.release();
  }
}

// The transfer commits first (accounts locked in id order); then the debit and the credit go to each account's chain.
async function pixTransfer(fromId: string, toId: string, amountCents: number, actorId: string): Promise<void> {
  const client = await pool.connect();
  let beforeCents: Record<string, number>;
  try {
    await client.query("BEGIN");
    const { rows } = await client.query<{ id: string; balance_cents: string }>("SELECT id, balance_cents FROM accounts WHERE id = ANY($1) ORDER BY id FOR UPDATE", [[fromId, toId]]);
    beforeCents = Object.fromEntries(rows.map((row) => [row.id, Number(row.balance_cents)]));
    await client.query("UPDATE accounts SET balance_cents = balance_cents + CASE WHEN id = $1 THEN -$3::bigint ELSE $3::bigint END WHERE id IN ($1, $2)", [fromId, toId, amountCents]);
    await client.query("COMMIT");
  } catch (error) {
    await client.query("ROLLBACK");
    throw error;
  } finally {
    client.release();
  }
  const base = { transferId: crypto.randomUUID(), amountCents, actorId, ipAddress: "187.65.44.12" };
  await movementAudit({ ...base, accountId: fromId, eventType: "pix.debited", balanceBeforeCents: beforeCents[fromId] ?? 0, balanceAfterCents: (beforeCents[fromId] ?? 0) - amountCents });
  await movementAudit({ ...base, accountId: toId, eventType: "pix.credited", balanceBeforeCents: beforeCents[toId] ?? 0, balanceAfterCents: (beforeCents[toId] ?? 0) + amountCents });
}

// Opening balance plus the audited movements must equal the balance: a change made outside the flow does not reconcile.
async function accountReconcile(accountId: string) {
  const { rows: [row] } = await pool.query<{ audited_cents: string; balance_cents: string }>(`SELECT h.opening_cents + COALESCE(sum(CASE m.event_type WHEN 'pix.credited' THEN m.amount_cents ELSE -m.amount_cents END), 0) AS audited_cents, a.balance_cents
    FROM accounts a JOIN audit_heads h ON h.account_id = a.id LEFT JOIN audit_movements m ON m.account_id = a.id WHERE a.id = $1 GROUP BY h.opening_cents, a.balance_cents`, [accountId]);
  if (!row) throw new Error(`account ${accountId} not found`);
  const auditedCents = Number(row.audited_cents);
  const balanceCents = Number(row.balance_cents);
  return { accountId, auditedCents, balanceCents, reconciled: auditedCents === balanceCents };
}

await pixTransfer("0001-1", "0002-9", 50_000, "customer:alice");
console.log(`  [RECONCILE] ${JSON.stringify(await accountReconcile("0001-1"))}`);
await pool.query("UPDATE accounts SET balance_cents = balance_cents + 100000 WHERE id = '0001-1'");
console.log(`  [RECONCILE] after a balance change outside the flow: ${JSON.stringify(await accountReconcile("0001-1"))}`);
await pool.end();

Nível

intermediário

6/13

Linhas de TypeScript
60
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX
  • Crédito/Empréstimo
  • Conta corrente
  • Saldo
  • Conciliação

Padrões do catálogo que implementa

  • Transação Bancária com Auditoria

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • audit_heads
  • audit_movements

Variáveis de ambiente

BANK_TRANSACTION_AUDIT_DATABASE_URL
postgres://postgres:postgres@localhost:5432/bank_audit_db

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Transação Bancária com Auditoria?

Próximo projeto, Segurança & AuditoriaCriptografia Ponta a Ponta (E2EE)
Esc

↑ ↓ navegarEnter abrir239 resultados