Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions pkgs/id/src/currency_poc/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ pub enum TransferError {
ExistsWithDifferentFields,
/// Another leg of the same linked chain failed; this leg did not post.
LinkedEventFailed,
/// The batch ended while this leg's linked chain was still open:
/// this leg is the final leg of the batch and still has
/// `linked == true`, so the chain it promised never terminated
/// (mirrors TigerBeetle's `linked_event_chain_open`).
LinkedEventChainOpen,
DebitAccountNotFound,
CreditAccountNotFound,
AccountsMustBeDifferent,
Expand All @@ -115,6 +120,17 @@ pub trait LedgerBackend {
fn create_accounts(&mut self, accounts: &[Account]) -> Vec<Result<(), AccountError>>;
/// Submit a batch. Contiguous runs ending at a transfer with
/// `linked == false` form linked chains and post atomically.
///
/// A batch whose final chain is unterminated — its last transfer
/// still has `linked == true` — is rejected atomically for that
/// chain: no leg of the open chain posts and no balance moves.
/// Every leg of the open chain reports an error: the final leg
/// reports [`TransferError::LinkedEventChainOpen`] and every
/// earlier leg reports [`TransferError::LinkedEventFailed`].
/// Terminated chains earlier in the same batch are unaffected,
/// and the transfers of a rejected open chain may be resubmitted
/// (properly terminated) in a later batch. A production binding
/// must implement the same rule.
fn create_transfers(&mut self, batch: &[Transfer]) -> Vec<Result<(), TransferError>>;
fn lookup_transfer(&self, id: TransferId) -> Option<Transfer>;
fn lookup_account(&self, id: AccountId) -> Option<Account>;
Expand Down Expand Up @@ -256,6 +272,23 @@ impl LedgerBackend for InMemoryLedger {
chain_end += 1;
}
let chain = &batch[chain_start..=chain_end];
// A chain that reaches the end of the batch with its last
// leg still `linked` is unterminated: the linked flag
// promises a following leg that never arrived. Reject the
// whole chain atomically — nothing is validated, staged,
// or stored — instead of committing it as if the end of
// the batch terminated it.
if chain[chain.len() - 1].linked {
for (offset, _) in chain.iter().enumerate() {
results.push(Err(if offset == chain.len() - 1 {
TransferError::LinkedEventChainOpen
} else {
TransferError::LinkedEventFailed
}));
}
chain_start = chain_end + 1;
continue;
}
let mut staged = self.balances.clone();
let mut staged_transfers: HashMap<TransferId, Transfer> = HashMap::new();
// Per-leg validation outcome. An idempotent `Exists` leg
Expand Down
80 changes: 80 additions & 0 deletions pkgs/id/src/currency_poc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,86 @@ fn linked_chain_failure_marks_other_legs_linked_event_failed() {
assert!(ledger.transfers_with_user_data_128(42).is_empty());
}

#[test]
fn single_unterminated_linked_transfer_rejected() {
// #4121: a lone transfer with `linked: true` promises a following
// leg; the batch ending there leaves the chain open, so nothing
// posts and no balance moves.
let mut ledger = funded_ledger();
let before = ledger.account_balance(USER_SRC).unwrap();
let open = Transfer {
linked: true,
..funding_transfer(700, USER_SRC, LP_SRC, 100, SRC)
};
let results = ledger.create_transfers(&[open]);
assert_eq!(results, vec![Err(TransferError::LinkedEventChainOpen)]);
assert!(ledger.lookup_transfer(700).is_none());
assert_eq!(ledger.account_balance(USER_SRC).unwrap(), before);
}

#[test]
fn multi_leg_unterminated_chain_rejected_atomically() {
// #4121: every leg of an open chain reports an error — the final
// leg `LinkedEventChainOpen`, the earlier legs
// `LinkedEventFailed` — and no leg is stored.
let mut ledger = funded_ledger();
let before_user = ledger.account_balance(USER_SRC).unwrap();
let before_lp = ledger.account_balance(LP_SRC).unwrap();
let chain = vec![
Transfer {
linked: true,
..funding_transfer(710, USER_SRC, LP_SRC, 100, SRC)
},
Transfer {
linked: true,
..funding_transfer(711, USER_SRC, LP_SRC, 200, SRC)
},
];
let results = ledger.create_transfers(&chain);
assert_eq!(
results,
vec![
Err(TransferError::LinkedEventFailed),
Err(TransferError::LinkedEventChainOpen),
]
);
assert!(ledger.lookup_transfer(710).is_none());
assert!(ledger.lookup_transfer(711).is_none());
assert_eq!(ledger.account_balance(USER_SRC).unwrap(), before_user);
assert_eq!(ledger.account_balance(LP_SRC).unwrap(), before_lp);
}

#[test]
fn unterminated_chain_does_not_block_terminated_chains() {
// #4121: the rejection is per-chain. A terminated chain earlier in
// the same batch still posts, and a properly terminated chain
// submitted in a later batch posts normally — including one that
// reuses the rejected open chain's transfers, terminated.
let mut ledger = funded_ledger();
let batch = vec![
Transfer {
linked: true,
..funding_transfer(720, USER_SRC, LP_SRC, 100, SRC)
},
funding_transfer(721, USER_SRC, LP_SRC, 50, SRC),
Transfer {
linked: true,
..funding_transfer(722, USER_SRC, LP_SRC, 200, SRC)
},
];
let results = ledger.create_transfers(&batch);
assert_eq!(results[0], Ok(()));
assert_eq!(results[1], Ok(()));
assert_eq!(results[2], Err(TransferError::LinkedEventChainOpen));
assert!(ledger.lookup_transfer(720).is_some());
assert!(ledger.lookup_transfer(721).is_some());
assert!(ledger.lookup_transfer(722).is_none());

let retry = ledger.create_transfers(&[funding_transfer(722, USER_SRC, LP_SRC, 200, SRC)]);
assert_eq!(retry, vec![Ok(())]);
assert!(ledger.lookup_transfer(722).is_some());
}

#[test]
fn crash_after_submission_recovers_without_double_posting() {
// #2063 §4: crash between submission and the Posted state write.
Expand Down
Loading