#pragma once #include #include #include #include #include #include #include #include #include #include namespace Void::Containers { using LedgerQuantity = std::uint64_t; using LedgerAccountKey = std::string; using LedgerOperationId = std::string; struct LedgerDebit { LedgerAccountKey account; LedgerQuantity quantity{0}; [[nodiscard]] auto operator<=>(const LedgerDebit&) const noexcept = default; [[nodiscard]] bool operator==(const LedgerDebit&) const noexcept = default; }; enum class LedgerStatus : std::uint8_t { committed = 0, /// The operation already committed; the recorded outcome is returned. replayed, insufficient_balance, capacity_exhausted, overflow, unknown_operation, unknown_account, /// Operation id reused with a different request or a forbidden phase. invalid_state, /// A released reservation cannot be delivered. released, limit_exceeded, }; enum class ReservationPhase : std::uint8_t { held = 0, delivered, released, }; struct LedgerResult { LedgerStatus status{LedgerStatus::unknown_operation}; ReservationPhase phase{ReservationPhase::held}; LedgerOperationId operation; [[nodiscard]] bool committed() const noexcept { return status == LedgerStatus::committed || status == LedgerStatus::replayed; } [[nodiscard]] bool operator==(const LedgerResult&) const noexcept = default; }; struct LedgerLimits { std::size_t max_accounts{1024}; std::size_t max_operations{4096}; }; /// In-memory, restorable account ledger with atomic multi-account /// reservations and repeatable transfers. /// /// Accounts are caller-keyed and carry an owner, a balance and a capacity. /// `reserve` debits one or more accounts atomically into a held reservation; /// `transfer` gives the reserved quantity to a destination account (the next /// owner); `release` returns it to the sources without changing ownership. /// /// Every committed phase is recorded under its operation id, so repeating the /// same request returns the recorded outcome instead of applying it twice. /// The state is a plain value: `save()` can be persisted and `restore()`d, and /// a replay after restoring a partially completed transfer still applies once. /// Failed attempts (insufficient balance, capacity, overflow) change nothing /// and are not recorded, so they can be retried after conditions change. /// /// Single-threaded by contract; callers synchronize concurrent access. class AccountLedger { public: using Limits = LedgerLimits; struct AccountState { std::string owner; LedgerQuantity balance{0}; LedgerQuantity capacity{ std::numeric_limits::max()}; [[nodiscard]] auto operator<=>(const AccountState&) const noexcept = default; [[nodiscard]] bool operator==(const AccountState&) const noexcept = default; }; struct OperationState { /// Normalized (aggregated and sorted) debits of the reservation. std::vector sources; ReservationPhase phase{ReservationPhase::held}; LedgerAccountKey destination; [[nodiscard]] auto operator<=>(const OperationState&) const noexcept = default; [[nodiscard]] bool operator==(const OperationState&) const noexcept = default; }; struct State { std::map accounts; std::map operations; [[nodiscard]] auto operator<=>(const State&) const noexcept = default; [[nodiscard]] bool operator==(const State&) const noexcept = default; }; explicit AccountLedger(Limits limits = Limits{}) : limits_(limits) {} [[nodiscard]] const Limits& limits() const noexcept { return limits_; } [[nodiscard]] bool create_account(const LedgerAccountKey& key, std::string owner, LedgerQuantity balance = 0, LedgerQuantity capacity = std::numeric_limits< LedgerQuantity>::max()) { if (balance > capacity || accounts_.size() >= limits_.max_accounts || accounts_.contains(key)) { return false; } accounts_.emplace(key, AccountState{.owner = std::move(owner), .balance = balance, .capacity = capacity}); return true; } [[nodiscard]] bool set_capacity(const LedgerAccountKey& key, LedgerQuantity capacity) { const auto found = accounts_.find(key); if (found == accounts_.end() || found->second.balance > capacity) { return false; } found->second.capacity = capacity; return true; } [[nodiscard]] std::optional account(const LedgerAccountKey& key) const { const auto found = accounts_.find(key); if (found == accounts_.end()) { return std::nullopt; } return found->second; } /// Sum of all balances plus quantities held in reservations. [[nodiscard]] LedgerQuantity total() const { LedgerQuantity sum = 0; for (const auto& [key, account] : accounts_) { (void)key; sum += account.balance; } for (const auto& [id, operation] : operations_) { (void)id; if (operation.phase == ReservationPhase::held) { for (const auto& debit : operation.sources) { sum += debit.quantity; } } } return sum; } [[nodiscard]] std::size_t account_count() const noexcept { return accounts_.size(); } [[nodiscard]] std::size_t operation_count() const noexcept { return operations_.size(); } /// Atomically debit every source into a held reservation. [[nodiscard]] LedgerResult reserve(const LedgerOperationId& operation, std::vector debits) { for (const auto& debit : debits) { if (debit.account.empty() || debit.quantity == 0) { return LedgerResult{.status = LedgerStatus::invalid_state, .operation = operation}; } } auto normalized = normalize(std::move(debits)); if (!normalized.has_value()) { return LedgerResult{.status = LedgerStatus::overflow, .operation = operation}; } if (const auto existing = operations_.find(operation); existing != operations_.end()) { if (existing->second.sources != *normalized) { return LedgerResult{.status = LedgerStatus::invalid_state, .phase = existing->second.phase, .operation = operation}; } return LedgerResult{.status = LedgerStatus::replayed, .phase = existing->second.phase, .operation = operation}; } if (operations_.size() >= limits_.max_operations) { return LedgerResult{.status = LedgerStatus::limit_exceeded, .operation = operation}; } for (const auto& debit : *normalized) { const auto found = accounts_.find(debit.account); if (found == accounts_.end()) { return LedgerResult{ .status = LedgerStatus::unknown_account, .operation = operation}; } if (found->second.balance < debit.quantity) { return LedgerResult{ .status = LedgerStatus::insufficient_balance, .operation = operation}; } } // All preconditions hold: apply every debit. for (const auto& debit : *normalized) { accounts_.at(debit.account).balance -= debit.quantity; } operations_.emplace(operation, OperationState{.sources = std::move(*normalized), .phase = ReservationPhase::held, .destination = {}}); return LedgerResult{.status = LedgerStatus::committed, .phase = ReservationPhase::held, .operation = operation}; } /// Return a held reservation to its sources. Ownership is unchanged. [[nodiscard]] LedgerResult release(const LedgerOperationId& operation) { const auto found = operations_.find(operation); if (found == operations_.end()) { return LedgerResult{.status = LedgerStatus::unknown_operation, .operation = operation}; } if (found->second.phase == ReservationPhase::released) { return LedgerResult{.status = LedgerStatus::replayed, .phase = ReservationPhase::released, .operation = operation}; } if (found->second.phase == ReservationPhase::delivered) { return LedgerResult{ .status = LedgerStatus::invalid_state, .phase = ReservationPhase::delivered, .operation = operation}; } for (const auto& debit : found->second.sources) { accounts_.at(debit.account).balance += debit.quantity; } found->second.phase = ReservationPhase::released; return LedgerResult{.status = LedgerStatus::committed, .phase = ReservationPhase::released, .operation = operation}; } /// Deliver a held reservation to `destination` (the next owner). /// On capacity/overflow failure nothing changes and the reservation /// stays held, so the caller can retry or release it. [[nodiscard]] LedgerResult transfer(const LedgerOperationId& operation, const LedgerAccountKey& destination) { const auto found = operations_.find(operation); if (found == operations_.end()) { return LedgerResult{.status = LedgerStatus::unknown_operation, .operation = operation}; } if (found->second.phase == ReservationPhase::released) { return LedgerResult{.status = LedgerStatus::released, .phase = ReservationPhase::released, .operation = operation}; } if (found->second.phase == ReservationPhase::delivered) { return LedgerResult{ .status = found->second.destination == destination ? LedgerStatus::replayed : LedgerStatus::invalid_state, .phase = ReservationPhase::delivered, .operation = operation}; } const auto target = accounts_.find(destination); if (target == accounts_.end()) { return LedgerResult{.status = LedgerStatus::unknown_account, .phase = ReservationPhase::held, .operation = operation}; } LedgerQuantity quantity = 0; for (const auto& debit : found->second.sources) { if (debit.quantity > std::numeric_limits::max() - quantity) { return LedgerResult{.status = LedgerStatus::overflow, .phase = ReservationPhase::held, .operation = operation}; } quantity += debit.quantity; } if (quantity > target->second.capacity - target->second.balance) { return LedgerResult{.status = LedgerStatus::capacity_exhausted, .phase = ReservationPhase::held, .operation = operation}; } target->second.balance += quantity; found->second.phase = ReservationPhase::delivered; found->second.destination = destination; return LedgerResult{.status = LedgerStatus::committed, .phase = ReservationPhase::delivered, .operation = operation}; } [[nodiscard]] State save() const { return State{.accounts = accounts_, .operations = operations_}; } /// Rebuild a ledger from `save()` output. Rejects states that violate /// the limits or the balance/capacity and reservation invariants. [[nodiscard]] static std::optional restore(State state, Limits limits = Limits{}) { if (state.accounts.size() > limits.max_accounts || state.operations.size() > limits.max_operations) { return std::nullopt; } for (const auto& [key, account] : state.accounts) { (void)key; if (account.balance > account.capacity) { return std::nullopt; } } for (const auto& [id, operation] : state.operations) { (void)id; if (operation.sources.empty()) { return std::nullopt; } for (const auto& debit : operation.sources) { if (!state.accounts.contains(debit.account)) { return std::nullopt; } } if (operation.phase == ReservationPhase::delivered && !state.accounts.contains(operation.destination)) { return std::nullopt; } } AccountLedger ledger{limits}; ledger.accounts_ = std::move(state.accounts); ledger.operations_ = std::move(state.operations); return ledger; } private: [[nodiscard]] static std::optional> normalize(std::vector debits) { std::map aggregated; for (const auto& debit : debits) { LedgerQuantity& sum = aggregated[debit.account]; if (debit.quantity > std::numeric_limits::max() - sum) { return std::nullopt; } sum += debit.quantity; } std::vector normalized; normalized.reserve(aggregated.size()); for (auto& [account, quantity] : aggregated) { normalized.push_back( LedgerDebit{.account = std::move(account), .quantity = quantity}); } return normalized; } Limits limits_{}; std::map accounts_; std::map operations_; }; } // namespace Void::Containers