Bounty
XE-0129 · Bounty

Exploitable Failures That Could Damage the Network at Scale

Closed · invalid — xe#218 filed 2026-10-30 08:33 UTC by willyoungzy001

Report

Good day XE team

I would approach this as an attacker trying to break the ledger, not simply checking whether each validation function exists. The real concern is whether I can bypass authorization, manipulate balances, compromise accounts, or prevent the network from reaching finality.

  1. Signature forgery through incomplete block hashing

Potentially critical

I create a legitimate transaction, sign it, and investigate whether every transaction field is included in the block hash.

If VerifyBlock() omits a critical field, I may be able to modify the destination, amount, or transaction type without invalidating the signature.

What breaks: Unauthorized transfers and transaction manipulation.

  1. Account takeover through opening-key validation

Potentially critical

I submit an opening block with a public key that derives the account address. Then I investigate whether subsequent transactions actually authenticate against the account's established signing authority.

If account identity and signing authorization are improperly linked, I may impersonate another account.

What breaks: Unauthorized spending and account takeover.

  1. Validation bypass through conflict staging

Potentially critical

I deliberately submit a conflicting block. The system stages it, fires a callback, and returns before opening-key and transaction-specific validation.

If downstream processing assumes staged blocks are valid, I may get an invalid transaction into the execution path.

What breaks: Invalid block promotion and potentially unauthorized state changes.

  1. Network slowdown through account-lock exhaustion

High severity

I flood heavily used accounts with competing transactions. If expensive cryptographic operations or database writes happen while account locks are held, transaction processing slows dramatically.

Shared resources could also cause unrelated accounts to suffer.

What breaks: Throughput, confirmation times, and network availability.

  1. Finality disruption through conflict amplification

Potentially critical

I generate competing blocks sharing the same previous hash. Each conflict creates additional staged work.

If conflict resolution is serialized or finality depends on resolving every conflict, I may prevent otherwise valid transactions from finalizing.

What breaks: Network-wide liveness and finality.

  1. Ledger corruption through non-atomic state updates

Potentially critical

I submit a valid transaction that updates in-memory balances, then trigger a database failure before persistent storage completes.

Now memory and disk may disagree. If recovery does not restore the last committed state correctly, balances and pending transfers can diverge.

What breaks: Ledger integrity, replay consistency, and potentially double execution.

  1. Double spending through concurrent receives

High severity

I submit two receive blocks referencing the same pending send simultaneously.

If both transactions observe the pending entry before either consumes it, both could potentially succeed.

What breaks: Duplicate asset crediting and balance inflation.

  1. Unauthorized issuance through mint validation

Potentially critical

I investigate inconsistencies between sys.minter, account authorization, and transaction signatures.

If these checks disagree, I may find a way to issue XUSD without legitimate permission.

What breaks: Monetary integrity and unauthorized asset creation.

  1. Escrow manipulation through lease settlement

High severity

I construct leases around expiry, renewal, settlement-grace, and escrow-expiry boundaries.

If those calculations disagree, I may obtain excess XE emissions or trigger unauthorized settlement.

What breaks: Escrow integrity and asset accounting.

  1. Multisig compromise through keyset rotation

Potentially critical

I target multisig_update, particularly the transition between old and new signers.

If updates are not authorized by the currently committed keyset or concurrent rotations can race, I may replace legitimate signers with keys I control.

What breaks: Permanent account takeover and unauthorized spending.

Final attack priority

Vulnerability Potential damage
1 Signature/hash manipulation Unauthorized transactions
2 Opening-key bypass Account takeover
3 Conflict staging bypass Invalid block execution
4 Lock exhaustion Network degradation
5 Conflict amplification Finality stalls
6 Non-atomic commits Ledger corruption
7 Concurrent receives Balance inflation
8 Mint authorization bypass Unauthorized issuance
9 Lease settlement manipulation Escrow theft
10 Multisig rotation compromise Account takeover

My three highest-priority investigation targets are conflict staging, signature verification, and atomic state commitment. Their failure could undermine the network's transaction integrity, account security, and ability to reach finality.

Payout address - 040d2665b6244d198f3c6c1f44ede6c9b9a546afc73dc33387a10ec09751e4a8

Thread

ujjwalmishramishra8977-cell2026-10-30 12:13 UTCgithub

Ledger Corruption Mitigation — Vulnerability #6

ACID-Compliant Serializable Ledger State Engine

To mitigate the risk of ledger corruption caused by non-atomic state updates (Vulnerability #6), I developed a transaction-isolated ledger state processor using Node.js, TypeScript, and PostgreSQL (pg).

The implementation combines Serializable Transaction Isolation, deterministic account-lock ordering, transaction idempotency, bounded local caching, atomic audit logging, and uncertain-commit verification.

Advanced Architectural Protections Implemented

  1. Serializable Transaction Isolation & Deterministic Lock Ordering: Uses PostgreSQL SERIALIZABLE isolation and locks account rows in alphabetical order to reduce deadlock risk during concurrent transfers.

  2. Uncertain-Commit Verification: Handles failures during COMMIT by releasing the original database connection and checking the transaction ID against the database before reporting the outcome. This prevents blindly replaying a potentially successful transfer.

  3. Idempotency & Duplicate Transaction Protection: Uses a unique transaction ID constraint and verifies the original sender, receiver, and amount before accepting a repeated request as a duplicate.

  4. Atomic Balance Updates & Audit Logging: Updates both account balances and inserts the corresponding audit record inside the same database transaction.

  5. Cache Invalidation & Bounded LRU Management: Uses a logical cache epoch and configurable cache-size limit to manage local cached balances and invalidate them after transfer outcomes.

  6. Exponential Backoff Retry Subsystem: Retries PostgreSQL serialization failures (40001) and deadlock errors (40P01) using increasing delays with jitter.

Production-Oriented Ledger Implementation

The following TypeScript implementation includes database schema initialization, balance retrieval, input validation, duplicate transaction verification, atomic transfer execution, audit logging, rollback handling, connection management, and retry logic.

Technology: TypeScript · Node.js · PostgreSQL · pg

import { Pool } from "pg";
import type { PoolClient } from "pg";

type Transfer = {
  txId: string;
  sender: string;
  receiver: string;
  amount: bigint;
};

type Result =
  | { success: true; txId: string; duplicate?: boolean }
  | { success: false; error: string };

type TransferRow = {
  sender: string;
  receiver: string;
  amount: string;
};

const MAX = (1n << 256n) - 1n;
const RETRIES = 3;
const CACHE_LIMIT = 10_000;
const RETRYABLE = new Set(["40001", "40P01"]);
const CONNECTION_ERRORS = new Set(["57P01", "57P02", "57P03"]);

const SCHEMA = `
CREATE TABLE IF NOT EXISTS accounts (
  address TEXT PRIMARY KEY,
  balance NUMERIC(78,0) NOT NULL CHECK (
    balance >= 0 AND balance <= ${MAX}
  )
);

CREATE TABLE IF NOT EXISTS transfers (
  tx_id TEXT PRIMARY KEY CHECK (length(tx_id) BETWEEN 1 AND 128),
  sender TEXT NOT NULL REFERENCES accounts(address),
  receiver TEXT NOT NULL REFERENCES accounts(address),
  amount NUMERIC(78,0) NOT NULL CHECK (
    amount > 0 AND amount <= ${MAX}
  ),
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CHECK (sender <> receiver)
);

CREATE TABLE IF NOT EXISTS transaction_audit (
  tx_id TEXT PRIMARY KEY REFERENCES transfers(tx_id),
  sender TEXT NOT NULL REFERENCES accounts(address),
  receiver TEXT NOT NULL REFERENCES accounts(address),
  amount NUMERIC(78,0) NOT NULL CHECK (
    amount > 0 AND amount <= ${MAX}
  ),
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CHECK (sender <> receiver)
);
`;

export class SecureLedgerManager {
  private readonly cache = new Map<string, bigint>();
  private epoch = 0;

  constructor(private readonly pool: Pool) {}

  async initializeSchema(): Promise<void> {
    await this.pool.query(SCHEMA);
  }

  private invalidate(): void {
    this.epoch++;
    this.cache.clear();
  }

  private remember(address: string, balance: bigint): void {
    this.cache.delete(address);
    this.cache.set(address, balance);

    if (this.cache.size > CACHE_LIMIT) {
      const oldest = this.cache.keys().next().value;
      if (oldest !== undefined) this.cache.delete(oldest);
    }
  }

  async getBalance(address: string): Promise<bigint> {
    if (typeof address !== "string" || !address.trim()) {
      throw new Error("Invalid account address");
    }

    const cached = this.cache.get(address);

    if (cached !== undefined) {
      this.cache.delete(address);
      this.cache.set(address, cached);
      return cached;
    }

    for (let i = 0; i < 3; i++) {
      const epoch = this.epoch;

      const { rows } = await this.pool.query<{ balance: string }>(
        "SELECT balance FROM accounts WHERE address = $1",
        [address]
      );

      if (!rows.length) throw new Error("Account not found");

      const balance = BigInt(rows[0].balance);

      if (epoch === this.epoch) {
        this.remember(address, balance);
        return balance;
      }
    }

    const { rows } = await this.pool.query<{ balance: string }>(
      "SELECT balance FROM accounts WHERE address = $1",
      [address]
    );

    if (!rows.length) throw new Error("Account not found");

    return BigInt(rows[0].balance);
  }

  private validate(t: Transfer): string | null {
    if (!t || typeof t !== "object") {
      return "Invalid transaction details";
    }

    const { txId, sender, receiver, amount } = t;

    if (
      typeof txId !== "string" ||
      !txId.trim() ||
      txId !== txId.trim() ||
      txId.length > 128 ||
      typeof sender !== "string" ||
      !sender.trim() ||
      sender !== sender.trim() ||
      typeof receiver !== "string" ||
      !receiver.trim() ||
      receiver !== receiver.trim()
    ) {
      return "Invalid transaction details";
    }

    if (sender === receiver) {
      return "Sender and receiver must differ";
    }

    if (
      typeof amount !== "bigint" ||
      amount <= 0n ||
      amount > MAX
    ) {
      return "Invalid transfer amount";
    }

    return null;
  }

  private code(error: unknown): string {
    return typeof error === "object" &&
      error !== null &&
      "code" in error
      ? String((error as { code: unknown }).code)
      : "";
  }

  private async find(
    txId: string
  ): Promise<TransferRow | undefined> {
    const { rows } = await this.pool.query<TransferRow>(
      `SELECT sender, receiver, amount
       FROM transfers
       WHERE tx_id = $1`,
      [txId]
    );

    return rows[0];
  }

  private matches(row: TransferRow, t: Transfer): boolean {
    return (
      row.sender === t.sender &&
      row.receiver === t.receiver &&
      BigInt(row.amount) === t.amount
    );
  }

  private async duplicate(t: Transfer): Promise<Result> {
    const row = await this.find(t.txId);

    if (!row) {
      return {
        success: false,
        error: "Transaction could not be verified"
      };
    }

    if (!this.matches(row, t)) {
      return {
        success: false,
        error: "Transaction ID already used"
      };
    }

    return {
      success: true,
      txId: t.txId,
      duplicate: true
    };
  }

  private async execute(
    client: PoolClient,
    t: Transfer
  ): Promise<void> {
    const { txId, sender, receiver, amount } = t;

    // Lock both accounts in deterministic order.
    const { rows } = await client.query<{
      address: string;
      balance: string;
    }>(
      `SELECT address, balance
       FROM accounts
       WHERE address = ANY($1::text[])
       ORDER BY address
       FOR UPDATE`,
      [[sender, receiver].sort()]
    );

    if (rows.length !== 2) {
      throw new Error("Account not found");
    }

    // Reserve the transaction ID before balance validation.
    // The reservation is rolled back if any later operation fails.
    const reservation = await client.query(
      `INSERT INTO transfers
       (tx_id, sender, receiver, amount)
       VALUES ($1, $2, $3, $4)
       ON CONFLICT (tx_id) DO NOTHING
       RETURNING tx_id`,
      [txId, sender, receiver, amount.toString()]
    );

    if (reservation.rowCount !== 1) {
      throw new Error("DUPLICATE_TRANSACTION");
    }

    const balances = new Map(
      rows.map(r => [r.address, BigInt(r.balance)])
    );

    const from = balances.get(sender);
    const to = balances.get(receiver);

    if (from === undefined || to === undefined) {
      throw new Error("Account resolution failed");
    }

    if (from < amount) {
      throw new Error("Insufficient balance");
    }

    if (to + amount > MAX) {
      throw new Error("Receiver balance overflow");
    }

    // Both account updates occur in the same transaction.
    for (const [address, balance] of [
      [sender, from - amount],
      [receiver, to + amount]
    ] as const) {
      const result = await client.query(
        `UPDATE accounts
         SET balance = $1
         WHERE address = $2
         RETURNING address`,
        [balance.toString(), address]
      );

      if (result.rowCount !== 1) {
        throw new Error("Balance update failed");
      }
    }

    // Audit record is committed atomically with the transfer.
    await client.query(
      `INSERT INTO transaction_audit
       (tx_id, sender, receiver, amount)
       VALUES ($1, $2, $3, $4)`,
      [txId, sender, receiver, amount.toString()]
    );
  }

  async transferTokens(t: Transfer): Promise<Result> {
    const invalid = this.validate(t);

    if (invalid) {
      return { success: false, error: invalid };
    }

    for (let attempt = 0; attempt < RETRIES; attempt++) {
      let client: PoolClient;

      try {
        client = await this.pool.connect();
      } catch {
        this.invalidate();

        return {
          success: false,
          error: "Database connection failed. Retry using the same transaction ID."
        };
      }

      let started = false;
      let committing = false;
      let destroy = false;
      let retry = false;
      let duplicateDetected = false;
      let uncertainCommit = false;
      let failure = "Transfer failed";

      try {
        await client.query("BEGIN ISOLATION LEVEL SERIALIZABLE");
        started = true;

        await this.execute(client, t);

        committing = true;
        await client.query("COMMIT");

        started = false;
        this.invalidate();

        return {
          success: true,
          txId: t.txId
        };

      } catch (error) {
        const errorCode = this.code(error);

        failure = error instanceof Error
          ? error.message
          : "Unknown transfer error";

        const isDuplicate =
          error instanceof Error &&
          error.message === "DUPLICATE_TRANSACTION";

        let rolledBack = !started;

        // A serialization/deadlock error returned by COMMIT
        // is a confirmed transaction failure and can be retried.
        if (committing && RETRYABLE.has(errorCode)) {
          try {
            await client.query("ROLLBACK");
            started = false;
            rolledBack = true;
          } catch {
            destroy = true;
          }
        } else if (committing) {
          // The commit outcome cannot safely be assumed.
          destroy = true;
          uncertainCommit = true;
        } else if (started) {
          try {
            await client.query("ROLLBACK");
            started = false;
            rolledBack = true;
          } catch {
            destroy = true;
          }
        }

        if (
          errorCode.startsWith("08") ||
          CONNECTION_ERRORS.has(errorCode)
        ) {
          destroy = true;
        }

        if (isDuplicate && rolledBack) {
          duplicateDetected = true;
        } else if (
          !uncertainCommit &&
          rolledBack &&
          !destroy &&
          RETRYABLE.has(errorCode) &&
          attempt < RETRIES - 1
        ) {
          retry = true;
        }

        this.invalidate();

      } finally {
        // Release the checked-out connection exactly once.
        client.release(destroy);
      }

      // Resolve uncertain COMMIT only after releasing the client.
      if (uncertainCommit) {
        try {
          const row = await this.find(t.txId);

          if (row && this.matches(row, t)) {
            return {
              success: true,
              txId: t.txId,
              duplicate: true
            };
          }

          if (row) {
            return {
              success: false,
              error: "Transaction ID already used"
            };
          }
        } catch {
          // Database verification is currently unavailable.
        }

        return {
          success: false,
          error: "Commit outcome uncertain. Retry using the same transaction ID."
        };
      }

      if (duplicateDetected) {
        try {
          return await this.duplicate(t);
        } catch {
          return {
            success: false,
            error: "Duplicate transaction verification failed"
          };
        }
      }

      if (retry) {
        const delay = Math.min(
          1000,
          50 * (2 ** attempt) + Math.floor(Math.random() * 50)
        );

        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }

      return {
        success: false,
        error: failure
      };
    }

    return {
      success: false,
      error: "Transfer failed after maximum retries"
    };
  }
}
ujjwalmishramishra8977-cell2026-10-30 12:14 UTCgithub

Contributor details Your Expensify account email: ujjwalmishramishra8977@gmail.com Upwork Profile Link: https://www.upwork.com/freelancers/~016f555cf43aa73e80

ujjwalmishramishra8977-cell2026-10-30 12:48 UTCgithub

Ledger Corruption Mitigation — Vulnerability #6

ACID-Compliant Serializable Ledger State Engine

To mitigate the risk of ledger corruption caused by non-atomic state updates (Vulnerability #6), I developed a transaction-isolated ledger state processor using Node.js, TypeScript, and PostgreSQL (pg).

The implementation combines Serializable Transaction Isolation, deterministic account-lock ordering, transaction idempotency, bounded local caching, atomic audit logging, and uncertain-commit verification.

Advanced Architectural Protections Implemented

  1. Serializable Transaction Isolation & Deterministic Lock Ordering: Uses PostgreSQL SERIALIZABLE isolation and locks account rows in alphabetical order to reduce deadlock risk during concurrent transfers.

  2. Uncertain-Commit Verification: Handles failures during COMMIT by releasing the original database connection and checking the transaction ID against the database before reporting the outcome. This prevents blindly replaying a potentially successful transfer.

  3. Idempotency & Duplicate Transaction Protection: Uses a unique transaction ID constraint and verifies the original sender, receiver, and amount before accepting a repeated request as a duplicate.

  4. Atomic Balance Updates & Audit Logging: Updates both account balances and inserts the corresponding audit record inside the same database transaction.

  5. Cache Invalidation & Bounded LRU Management: Uses a logical cache epoch and configurable cache-size limit to manage local cached balances and invalidate them after transfer outcomes.

  6. Exponential Backoff Retry Subsystem: Retries PostgreSQL serialization failures (40001) and deadlock errors (40P01) using increasing delays with jitter.

Production-Oriented Ledger Implementation

The following TypeScript implementation includes database schema initialization, balance retrieval, input validation, duplicate transaction verification, atomic transfer execution, audit logging, rollback handling, connection management, and retry logic.

Technology: TypeScript · Node.js · PostgreSQL · pg

import { Pool } from "pg";
import type { PoolClient } from "pg";

type Transfer = {
  txId: string;
  sender: string;
  receiver: string;
  amount: bigint;
};

type Result =
  | { success: true; txId: string; duplicate?: boolean }
  | { success: false; error: string };

type TransferRow = {
  sender: string;
  receiver: string;
  amount: string;
};

const MAX = (1n << 256n) - 1n;
const RETRIES = 3;
const CACHE_LIMIT = 10_000;
const RETRYABLE = new Set(["40001", "40P01"]);
const CONNECTION_ERRORS = new Set(["57P01", "57P02", "57P03"]);

const SCHEMA = `
CREATE TABLE IF NOT EXISTS accounts (
  address TEXT PRIMARY KEY,
  balance NUMERIC(78,0) NOT NULL CHECK (
    balance >= 0 AND balance <= ${MAX}
  )
);

CREATE TABLE IF NOT EXISTS transfers (
  tx_id TEXT PRIMARY KEY CHECK (length(tx_id) BETWEEN 1 AND 128),
  sender TEXT NOT NULL REFERENCES accounts(address),
  receiver TEXT NOT NULL REFERENCES accounts(address),
  amount NUMERIC(78,0) NOT NULL CHECK (
    amount > 0 AND amount <= ${MAX}
  ),
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CHECK (sender <> receiver)
);

CREATE TABLE IF NOT EXISTS transaction_audit (
  tx_id TEXT PRIMARY KEY REFERENCES transfers(tx_id),
  sender TEXT NOT NULL REFERENCES accounts(address),
  receiver TEXT NOT NULL REFERENCES accounts(address),
  amount NUMERIC(78,0) NOT NULL CHECK (
    amount > 0 AND amount <= ${MAX}
  ),
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CHECK (sender <> receiver)
);
`;

export class SecureLedgerManager {
  private readonly cache = new Map<string, bigint>();
  private epoch = 0;

  constructor(private readonly pool: Pool) {}

  async initializeSchema(): Promise<void> {
    await this.pool.query(SCHEMA);
  }

  private invalidate(): void {
    this.epoch++;
    this.cache.clear();
  }

  private remember(address: string, balance: bigint): void {
    this.cache.delete(address);
    this.cache.set(address, balance);

    if (this.cache.size > CACHE_LIMIT) {
      const oldest = this.cache.keys().next().value;
      if (oldest !== undefined) this.cache.delete(oldest);
    }
  }

  async getBalance(address: string): Promise<bigint> {
    if (typeof address !== "string" || !address.trim()) {
      throw new Error("Invalid account address");
    }

    const cached = this.cache.get(address);

    if (cached !== undefined) {
      this.cache.delete(address);
      this.cache.set(address, cached);
      return cached;
    }

    for (let i = 0; i < 3; i++) {
      const epoch = this.epoch;

      const { rows } = await this.pool.query<{ balance: string }>(
        "SELECT balance FROM accounts WHERE address = $1",
        [address]
      );

      if (!rows.length) throw new Error("Account not found");

      const balance = BigInt(rows[0].balance);

      if (epoch === this.epoch) {
        this.remember(address, balance);
        return balance;
      }
    }

    const { rows } = await this.pool.query<{ balance: string }>(
      "SELECT balance FROM accounts WHERE address = $1",
      [address]
    );

    if (!rows.length) throw new Error("Account not found");

    return BigInt(rows[0].balance);
  }

  private validate(t: Transfer): string | null {
    if (!t || typeof t !== "object") {
      return "Invalid transaction details";
    }

    const { txId, sender, receiver, amount } = t;

    if (
      typeof txId !== "string" ||
      !txId.trim() ||
      txId !== txId.trim() ||
      txId.length > 128 ||
      typeof sender !== "string" ||
      !sender.trim() ||
      sender !== sender.trim() ||
      typeof receiver !== "string" ||
      !receiver.trim() ||
      receiver !== receiver.trim()
    ) {
      return "Invalid transaction details";
    }

    if (sender === receiver) {
      return "Sender and receiver must differ";
    }

    if (
      typeof amount !== "bigint" ||
      amount <= 0n ||
      amount > MAX
    ) {
      return "Invalid transfer amount";
    }

    return null;
  }

  private code(error: unknown): string {
    return typeof error === "object" &&
      error !== null &&
      "code" in error
      ? String((error as { code: unknown }).code)
      : "";
  }

  private async find(
    txId: string
  ): Promise<TransferRow | undefined> {
    const { rows } = await this.pool.query<TransferRow>(
      `SELECT sender, receiver, amount
       FROM transfers
       WHERE tx_id = $1`,
      [txId]
    );

    return rows[0];
  }

  private matches(row: TransferRow, t: Transfer): boolean {
    return (
      row.sender === t.sender &&
      row.receiver === t.receiver &&
      BigInt(row.amount) === t.amount
    );
  }

  private async duplicate(t: Transfer): Promise<Result> {
    const row = await this.find(t.txId);

    if (!row) {
      return {
        success: false,
        error: "Transaction could not be verified"
      };
    }

    if (!this.matches(row, t)) {
      return {
        success: false,
        error: "Transaction ID already used"
      };
    }

    return {
      success: true,
      txId: t.txId,
      duplicate: true
    };
  }

  private async execute(
    client: PoolClient,
    t: Transfer
  ): Promise<void> {
    const { txId, sender, receiver, amount } = t;

    // Lock both accounts in deterministic order.
    const { rows } = await client.query<{
      address: string;
      balance: string;
    }>(
      `SELECT address, balance
       FROM accounts
       WHERE address = ANY($1::text[])
       ORDER BY address
       FOR UPDATE`,
      [[sender, receiver].sort()]
    );

    if (rows.length !== 2) {
      throw new Error("Account not found");
    }

    // Reserve the transaction ID before balance validation.
    // The reservation is rolled back if any later operation fails.
    const reservation = await client.query(
      `INSERT INTO transfers
       (tx_id, sender, receiver, amount)
       VALUES ($1, $2, $3, $4)
       ON CONFLICT (tx_id) DO NOTHING
       RETURNING tx_id`,
      [txId, sender, receiver, amount.toString()]
    );

    if (reservation.rowCount !== 1) {
      throw new Error("DUPLICATE_TRANSACTION");
    }

    const balances = new Map(
      rows.map(r => [r.address, BigInt(r.balance)])
    );

    const from = balances.get(sender);
    const to = balances.get(receiver);

    if (from === undefined || to === undefined) {
      throw new Error("Account resolution failed");
    }

    if (from < amount) {
      throw new Error("Insufficient balance");
    }

    if (to + amount > MAX) {
      throw new Error("Receiver balance overflow");
    }

    // Both account updates occur in the same transaction.
    for (const [address, balance] of [
      [sender, from - amount],
      [receiver, to + amount]
    ] as const) {
      const result = await client.query(
        `UPDATE accounts
         SET balance = $1
         WHERE address = $2
         RETURNING address`,
        [balance.toString(), address]
      );

      if (result.rowCount !== 1) {
        throw new Error("Balance update failed");
      }
    }

    // Audit record is committed atomically with the transfer.
    await client.query(
      `INSERT INTO transaction_audit
       (tx_id, sender, receiver, amount)
       VALUES ($1, $2, $3, $4)`,
      [txId, sender, receiver, amount.toString()]
    );
  }

  async transferTokens(t: Transfer): Promise<Result> {
    const invalid = this.validate(t);

    if (invalid) {
      return { success: false, error: invalid };
    }

    for (let attempt = 0; attempt < RETRIES; attempt++) {
      let client: PoolClient;

      try {
        client = await this.pool.connect();
      } catch {
        this.invalidate();

        return {
          success: false,
          error: "Database connection failed. Retry using the same transaction ID."
        };
      }

      let started = false;
      let committing = false;
      let destroy = false;
      let retry = false;
      let duplicateDetected = false;
      let uncertainCommit = false;
      let failure = "Transfer failed";

      try {
        await client.query("BEGIN ISOLATION LEVEL SERIALIZABLE");
        started = true;

        await this.execute(client, t);

        committing = true;
        await client.query("COMMIT");

        started = false;
        this.invalidate();

        return {
          success: true,
          txId: t.txId
        };

      } catch (error) {
        const errorCode = this.code(error);

        failure = error instanceof Error
          ? error.message
          : "Unknown transfer error";

        const isDuplicate =
          error instanceof Error &&
          error.message === "DUPLICATE_TRANSACTION";

        let rolledBack = !started;

        // A serialization/deadlock error returned by COMMIT
        // is a confirmed transaction failure and can be retried.
        if (committing && RETRYABLE.has(errorCode)) {
          try {
            await client.query("ROLLBACK");
            started = false;
            rolledBack = true;
          } catch {
            destroy = true;
          }
        } else if (committing) {
          // The commit outcome cannot safely be assumed.
          destroy = true;
          uncertainCommit = true;
        } else if (started) {
          try {
            await client.query("ROLLBACK");
            started = false;
            rolledBack = true;
          } catch {
            destroy = true;
          }
        }

        if (
          errorCode.startsWith("08") ||
          CONNECTION_ERRORS.has(errorCode)
        ) {
          destroy = true;
        }

        if (isDuplicate && rolledBack) {
          duplicateDetected = true;
        } else if (
          !uncertainCommit &&
          rolledBack &&
          !destroy &&
          RETRYABLE.has(errorCode) &&
          attempt < RETRIES - 1
        ) {
          retry = true;
        }

        this.invalidate();

      } finally {
        // Release the checked-out connection exactly once.
        client.release(destroy);
      }

      // Resolve uncertain COMMIT only after releasing the client.
      if (uncertainCommit) {
        try {
          const row = await this.find(t.txId);

          if (row && this.matches(row, t)) {
            return {
              success: true,
              txId: t.txId,
              duplicate: true
            };
          }

          if (row) {
            return {
              success: false,
              error: "Transaction ID already used"
            };
          }
        } catch {
          // Database verification is currently unavailable.
        }

        return {
          success: false,
          error: "Commit outcome uncertain. Retry using the same transaction ID."
        };
      }

      if (duplicateDetected) {
        try {
          return await this.duplicate(t);
        } catch {
          return {
            success: false,
            error: "Duplicate transaction verification failed"
          };
        }
      }

      if (retry) {
        const delay = Math.min(
          1000,
          50 * (2 ** attempt) + Math.floor(Math.random() * 50)
        );

        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }

      return {
        success: false,
        error: failure
      };
    }

    return {
      success: false,
      error: "Transfer failed after maximum retries"
    };
  }
}
XE deskteam2026-11-14 22:49 UTCgithub

Thanks for the report. We read it against the code and could not confirm a bug in what it describes.

This report is closed as invalid. If we have missed something, file a new report that links https://bounty.xe.network/XE-0129 and says what; it is read like any other.