From 8fd3591b0e37aaecf00a6410a5926745a031cb6f Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 19 Sep 2026 19:42:29 -0400 Subject: [PATCH] Add atomic conserved energy and elemental inventory ledger --- CMakeLists.txt | 11 ++ README.md | 4 +- docs/ROADMAP.md | 6 +- docs/STATUS.md | 15 +- docs/adr/0024-conserved-inventory-ledger.md | 77 ++++++++ docs/adr/README.md | 1 + docs/architecture/SYSTEM_OVERVIEW.md | 6 +- docs/biology/ENERGY_MODEL.md | 31 ++++ docs/engineering/VALIDATION.md | 21 +++ include/evo/accounting/ledger.hpp | 71 +++++++ src/accounting/ledger.cpp | 87 +++++++++ tests/ledger_tests.cpp | 194 ++++++++++++++++++++ 12 files changed, 517 insertions(+), 7 deletions(-) create mode 100644 docs/adr/0024-conserved-inventory-ledger.md create mode 100644 include/evo/accounting/ledger.hpp create mode 100644 src/accounting/ledger.cpp create mode 100644 tests/ledger_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d1d589b..5f3de3f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,12 +34,23 @@ target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in target_compile_features(evo_simulation PUBLIC cxx_std_23) evo_owned_target(evo_simulation) +add_library(evo_accounting STATIC src/accounting/ledger.cpp) +add_library(evo::accounting ALIAS evo_accounting) +target_include_directories(evo_accounting PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_compile_features(evo_accounting PUBLIC cxx_std_23) +evo_owned_target(evo_accounting) + add_executable(evo-sim apps/evo-sim/main.cpp) target_link_libraries(evo-sim PRIVATE evo::simulation) evo_owned_target(evo-sim) include(CTest) if(BUILD_TESTING) + add_executable(evo-ledger-tests tests/ledger_tests.cpp) + target_link_libraries(evo-ledger-tests PRIVATE evo::accounting) + evo_owned_target(evo-ledger-tests) + add_test(NAME ledger-contracts COMMAND evo-ledger-tests) + set_tests_properties(ledger-contracts PROPERTIES TIMEOUT 60) add_executable(evo-tests tests/simulation_tests.cpp) target_link_libraries(evo-tests PRIVATE evo::simulation) evo_owned_target(evo-tests) diff --git a/README.md b/README.md index cfc3434..b5e1d96 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ network service. Dev verification manifests are separate from the simulation. - [Opt-in ECS evaluation and measurements](docs/engineering/ECS_EVALUATION.md) - [Sequential command scheduling and recovery](docs/architecture/SCHEDULER_CONTRACT.md) - [Local periodic spatial queries](docs/architecture/SPATIAL_CONTRACT.md) +- [Energy/matter model and implemented ledger boundary](docs/biology/ENERGY_MODEL.md) Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are authoritative over implementation. No external runtime library is needed for @@ -78,7 +79,8 @@ restore. See [testing strategy](docs/engineering/TEST_STRATEGY.md) and `include/evo` exposes core values and the headless simulation API. `src/simulation` implements component state, tick ordering and local snapshot -codec. `apps/evo-sim` owns CLI/file I/O and reporting. `tests` holds contract, +codec. `src/accounting` provides the independent finite-inventory ledger; +it is not yet part of particle snapshots. `apps/evo-sim` owns CLI/file I/O and reporting. `tests` holds contract, fuzz and measurement programs. Future biology, world, networking and persistence modules are documented boundaries; they are added when they have real behavior. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0eea9e5..3f9b875 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -43,7 +43,7 @@ this proof. Production indexing awaits actual interaction workloads. | ID / objective | Files/modules | Dependencies | Completion criteria | Tests / evidence | Risk | |---|---|---|---|---|---| -| 2.1 Ratify accounting units and ledger | biology/energy, world/resources, ENERGY_MODEL | M1, units ADR | Energy/matter/nutrient units, transfer APIs, overflow/error budget explicit | Dimensional compile checks and conservation properties | Rounding creates resources | +| 2.1 Ratify accounting units and ledger | accounting/ledger.*, ENERGY_MODEL, ADR-0024 | M1, units ADR | Exact local units/ranges, finite inventories and atomic ordered transfers | Unit-type separation, rollback/overflow/replay, million-transaction independent balance checks | Mistaking conservation for valid biology | | 2.2 Add abiotic source and producer | biology/metabolism, world/resources | 2.1 | Energy enters only through named source; uptake bounded by resources | Closed-box balance plus external source accounting | Arbitrary growth subsidies | | 2.3 Add consumer intentions and ingestion | biology/digestion, simulation/spatial | 2.2, 1.7 | Shared validated action path transfers matter/energy | Predator/prey transfer and dead-action rejection | Consuming twice in same tick | | 2.4 Death and decomposition | biology/lifecycle, ecology | 2.3 | Active capability ends; corpse pool transfers conserved nutrients | Death terminality, decomposition limits, ledger audit | Nutrients double counted | @@ -52,6 +52,10 @@ this proof. Production indexing awaits actual interaction workloads. M2 founder fixtures explicitly identify synthetic test-player origins; they do not introduce unrelated wildlife into persistent worlds. Morphology is absent. +M2.1's transfer-only ledger is implemented separately from the particle world. +M2.2 must define finite source flux, process-specific restrictions, rate residuals +and the atomic boundary between biological state and its inventories. Snapshot +integration requires its own versioned format; it is not provided by M1's codec. ## M3 — Genome v0.1 diff --git a/docs/STATUS.md b/docs/STATUS.md index a763a77..15f2e50 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged. ## Completed implementation - Vision, architectural pillars, risks, open-question register, architecture - diagrams, biological contracts, engineering constitution and 23 ADRs. + diagrams, biological contracts, engineering constitution and 24 ADRs. Proposed/deferred choices remain distinct from accepted proof decisions. - M0–M4 task breakdowns with dependencies, acceptance evidence and risks, plus M5–M14 gates in [ROADMAP.md](ROADMAP.md). @@ -61,8 +61,8 @@ for the bounded proof; the general production ECS remains a later measured choic | Priority | Work | Completion evidence | |---|---|---| -| 1 | M2.1 energy/matter ledger | Agreed units/ranges, atomic transfers, nonnegative balances and conservation tests before organisms | -| 2 | M2.2–2.6 first headless energy cycle | Explicit source → producer → consumer → death → decomposition → nutrients; seeded million-tick ledger evidence | +| 1 | M2.2 finite source and producer process contract | Finite flux, typed rates/residuals, restricted energy conversion and atomic inventory/process state | +| 2 | M2.3–2.6 first headless energy cycle | Producer → consumer → death → decomposition → nutrients; seeded million-tick ecosystem evidence | | Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes | M1.6 now implements [the sequential scheduler contract](architecture/SCHEDULER_CONTRACT.md): @@ -85,6 +85,15 @@ spatial index. See the spatial contract and validation report for scope/evidence Native Release/ASan/analysis/format checks passed, as did all jobs in Gitea run 1409. All 72 Linux benchmark result checksums and match counts equal Windows. +M2.1 adds an independent finite-inventory accounting library (ADR-0024). Typed +picojoules and C/N/P/other femtograms transfer atomically across bounded local +reservoirs. Opening totals are checked, repeated action IDs rejected, and failures +leave both balances and action watermark unchanged. One million seeded transfers +are checked against independently maintained balances and recomputed totals. +No organisms, biochemical rates, external replenishment, world snapshot format +or deployment changes are included. Conservation does not establish valid +chemistry or reusable heat; process restrictions are M2.2 work. + Before biology, resolve the relevant heredity and energetic contracts rather than treating proof particles as organisms. Exact game tick rate, NPC mutation, logout treatment, species/extinction rules and multicellular transition remain diff --git a/docs/adr/0024-conserved-inventory-ledger.md b/docs/adr/0024-conserved-inventory-ledger.md new file mode 100644 index 0000000..79edb6d --- /dev/null +++ b/docs/adr/0024-conserved-inventory-ledger.md @@ -0,0 +1,77 @@ +# ADR-0024: Conserved finite inventory ledger + +## Status + +Adopted for M2.1 synthetic accounting, not production biochemical scales. + +## Context + +Energy-model transfers must not create resources, overdraw a reserve or partially +fund reproduction. Before any organism implementation we need an exact bounded +accounting primitive. Its state is separate from the M1 particle snapshot. + +## Decision + +Add a dependency-free `evo::accounting` library. Energy uses u64 picojoules +(1e-12 J); elemental mass uses u64 femtograms (1e-18 kg). These are distinct +wrapper types, not a units algebra. A reservoir contains energy and four disjoint +mass inventories: carbon, nitrogen, phosphorus and other. All matter, including +unmodeled elements, belongs to exactly one category. Total biomass is derived, +never an additional balance. No chemical reaction or conversion is implemented. + +One ledger contains 1–4,096 reservoirs created from explicit opening balances. +The sum of each channel across the ledger must fit u64. Energy therefore ranges +up to about 18.45 MJ and each mass category up to about 18.45 kg. This deliberately +bounds a local synthetic experiment, not a planet or large organism. There are +no floating conversions, rounding, rates or residuals in this transfer-only API. + +A transaction has a strictly increasing nonzero u64 action ID and 1–256 ordered +transfer legs. Each leg debits and credits the same quantity bundle between two +different valid reservoirs. Earlier credits may fund later legs; intermediate +overdraft is rejected, even when a netted transaction would balance. Validate and +apply on a private copy, then commit by noexcept swap and advance the watermark. +On any failure balances and watermark remain unchanged. Accepted IDs cannot be +replayed; rejected IDs can be corrected and retried. IDs may have gaps. + +Reservoir IDs are local 1-based stable indices; no deletion/reuse or implicit +creation. Copies are isolated experiment branches, never a second world owner. +Source inputs must come from a finite opening reservoir; dissipated energy moves +to a heat reservoir. There is no mint/burn API or perpetual light fixture. + +## Alternatives Considered + +Floating-point balances need error budgets and residual treatment. A general +units library (the mp-units candidate in ADR-0009) is appropriate to evaluate for +future dimensional equations, but these two opaque quantities need no algebra, +conversion or new dependency. Smaller quanta sacrifice local range; larger ones +lose small-cell resolution. Production precision must be measured separately. +Netting or undo logs reduce copying but complicate intermediate solvency rules. + +## Benefits + +Exact per-channel conservation, atomic bundled transfers, bounded allocation, +typed units and constant-size replay watermark without a growing ID history. + +## Costs + +O(reservoir count + legs) work per transaction and a copied balance vector. +Serialization, cross-ledger escrow, opening-balance provenance and replenishment +are not implemented. The host must impose deterministic transaction ordering. + +## Risks + +Increasing IDs do not authenticate a caller or establish durable exactly-once +execution. Cross-ledger identity is a host responsibility. Ledger conservation +does not validate chemistry, energy quality or fair resource allocation. Arbitrary +reservoir reassignment would misrepresent biology despite balanced quantities. + +## Consequences + +Keep immutable public balance inspection and no direct write access. No entity, +genome, metabolism, external service or kernel snapshot integration yet. Before +integrating persistent ecology, version and serialize inventories and watermark +together, implement named finite flux budgets, carried division residuals and +atomic lifecycle/accounting commits. Unit-library diagnostics/compiler trials +remain a gate before dimensional biological equations, not this transfer proof. +Test exact limits, rollback, competing consumers, stale IDs, seeded conservation +and million-transaction replay under NDEBUG and sanitizers. diff --git a/docs/adr/README.md b/docs/adr/README.md index 74d5ec9..aa07777 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -16,6 +16,7 @@ Each record has the eight required sections. 0021 authorizes the opt-in ECS comparison only, not a production dependency. 0022 adopts the bounded sequential lifecycle-command scheduler for the proof. 0023 defines local periodic neighborhood queries and a measured linear baseline. +0024 adopts finite, typed energy/matter inventory transfers for M2.1. Every dependency adoption records exact version/commit and integrity hash, transitive license obligations, maintenance/security review, owner and removal diff --git a/docs/architecture/SYSTEM_OVERVIEW.md b/docs/architecture/SYSTEM_OVERVIEW.md index b5a4291..f71dd17 100644 --- a/docs/architecture/SYSTEM_OVERVIEW.md +++ b/docs/architecture/SYSTEM_OVERVIEW.md @@ -47,6 +47,7 @@ the simulation state. Durable account references live in orchestration mapping. |---|---|---| | core | Value types, deterministic algorithms, explicit version constants | Global state, threads, I/O | | simulation (`evo_simulation`, alias `evo::simulation`) | State, stable tick ordering, component lifecycle, pure restore validation | Wall clock, transport, database or rendering | +| accounting (`evo_accounting`, alias `evo::accounting`) | Typed finite inventories, atomic conserved transfers, in-memory action watermark | Chemistry, minting resources, entity lifecycle or durable storage | | biology | Genotype → development → phenotype; energetic transfers | Account rewards, player/NPC subclasses | | world | Procedural base identity, spatial/environmental fields | Dense planet allocation, gameplay authority | | persistence | Durable metadata, snapshots, replay batches, migration | Per-tick simulation decisions | @@ -54,8 +55,9 @@ the simulation state. Durable account references live in orchestration mapping. | backend | Identity adapters, account/world metadata, history queries, directory/lease coordination | Every noun deployed as a service | | app / server | Tick pacing, I/O ownership, durable outcome barrier, metrics export | Alternative biological implementation | -Only core, simulation, local snapshot codec and `evo-sim` are source modules in -the proof. Future rows are boundaries, not empty directories or dummy services. +Core, simulation, local snapshot codec, accounting and `evo-sim` are source modules +in the proof. Accounting has an independent tested contract; it is not yet wired +into particle state. Future rows are boundaries, not empty directories or dummy services. Split a library when a real independently tested contract exists. ## Runtime topology and data flow (target) diff --git a/docs/biology/ENERGY_MODEL.md b/docs/biology/ENERGY_MODEL.md index 7e4abd9..9deb304 100644 --- a/docs/biology/ENERGY_MODEL.md +++ b/docs/biology/ENERGY_MODEL.md @@ -86,3 +86,34 @@ competing consumers, long-run rounding, overflow/NaN rejection, cross-tier escro and independently recomputed seeded totals. Baseline metabolism, efficiencies, light attenuation, stoichiometry, heat fidelity and starvation rules remain open. Conservation alone does not guarantee a stable or enjoyable ecosystem. + +## Implemented M2.1 boundary + +[ADR-0024](../adr/0024-conserved-inventory-ledger.md) scopes the initial +`evo::accounting` library. Its ledger is independent of particle world state. +Opening inventories are explicit; later operations only transfer quantities. +Energy is in integer picojoules, disjoint C/N/P/other masses in femtograms. +Other contains all unmodeled matter; this is not a complete biochemical basis. +All quantities and global per-channel sums must fit u64. No float conversion, +division or fractional-rate handling is exposed yet, so there is no rounding loss. + +```cpp +// include/evo/accounting/ledger.hpp (contract sketch) +auto ledger = Ledger::create(opening_inventories); +auto result = ledger->transfer(action_id, ordered_legs); +``` + +Each leg transfers the same bundle between distinct reservoir IDs. Atomic commit +covers the entire ordered transaction and its monotonic action watermark. A +rejected transaction consumes nothing, including its ID. A duplicate/older +accepted ID is rejected. This is in-memory replay protection, not durable +exactly-once delivery. The owner assigns deterministic order; competing consumers +are first-funded, with no implicit fair-share or random priority rule. + +Reservoir meaning is caller-owned: source, reserve, substrate, structure, corpse, +heat or escrow. The primitive does not enforce chemical reactions or prevent a +caller from misclassifying heat as usable energy. M2.2 must provide restricted +process operations and finite flux budgets. Never treat conservation as biological +validity. There is no import/mint API, organism lifecycle, persisted ledger codec +or cross-ledger transaction in M2.1. Persistent integration must checkpoint both +inventories and action watermark atomically; M1 snapshots do not include them. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 45ecc3c..7bbf656 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -181,3 +181,24 @@ All 72 spatial benchmark checksums and match counts agree with Windows. Raw Linux measurements are in results/spatial-gcc142.jsonl; 24 native scenarios also have identical checksums across their three repetitions. No deployment manifest, rules version, snapshot format or golden was changed. + +## M2.1 finite inventory ledger (2026-09-19) + +Native Release, analysis and MSVC ASan each passed 6/6 CTests; formatting passed. +Commands: `tools/windows-check.ps1 -Preset -Action check` +and Release `-Action format`. Initial clang-tidy rejected the Element enum's +oversized base type; changed to u8 and reran all configurations successfully. + +The new independent ledger test checks typed energy/mass separation, finite-source +exhaustion, explicit heat transfer, intermediate overdraft, whole-transaction +rollback, retry/duplicate action semantics, invalid reservoir IDs, maximum batch +and reservoir counts, opening-total overflow and exact u64-limit transfers. +32 seeded runs × 31,250 transactions = one million transactions, each checked +against independent reference balances, a replay branch and recomputed per-channel +totals. This is transfer replay, not serialized recovery or an ecosystem run. +Final ledger tests took 0.63s Release and 7.62s ASan locally; not controlled +performance measurements. Existing particle goldens remain unchanged. + +Allocation-failure injection, durable ledger recovery and cross-ledger ownership +are not tested or implemented. Rates and conversions are absent, so rounding +residuals cannot occur in this transfer-only scope. Linux CI is pending source push. diff --git a/include/evo/accounting/ledger.hpp b/include/evo/accounting/ledger.hpp new file mode 100644 index 0000000..2f0e778 --- /dev/null +++ b/include/evo/accounting/ledger.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace evo::accounting { +struct Picojoules { + std::uint64_t value{}; + auto operator<=>(const Picojoules&) const = default; +}; +struct Femtograms { + std::uint64_t value{}; + auto operator<=>(const Femtograms&) const = default; +}; +enum class Element : std::uint8_t { carbon, nitrogen, phosphorus, other }; +struct Inventory { + Picojoules energy{}; + // Disjoint elemental categories; total mass is not an additional inventory. + std::array matter{}; + auto operator<=>(const Inventory&) const = default; +}; +struct ReservoirId { + std::uint32_t value{}; +}; +struct Transfer { + ReservoirId from; + ReservoirId to; + Inventory amount; +}; +enum class LedgerError : std::uint8_t { + reservoir_limit, + overflow, + stale_action, + transfer_limit, + invalid_reservoir, + same_reservoir, + insufficient_inventory +}; +inline constexpr std::size_t max_reservoirs = 4'096; +inline constexpr std::size_t max_transfers = 256; + +class Ledger { + public: + [[nodiscard]] static std::expected + create(std::span opening); + // Ordered legs form one atomic transaction. Single-owner access only. + [[nodiscard]] std::expected transfer(std::uint64_t action, + std::span legs); + // Inspection spans are invalidated by successful mutation or assignment. + [[nodiscard]] std::span balances() const noexcept { + return balances_; + } + [[nodiscard]] Inventory conserved_totals() const noexcept { + return totals_; + } + [[nodiscard]] std::uint64_t last_action() const noexcept { + return last_action_; + } + + private: + Ledger() = default; + std::vector balances_; + Inventory totals_{}; + std::uint64_t last_action_{}; +}; +} // namespace evo::accounting diff --git a/src/accounting/ledger.cpp b/src/accounting/ledger.cpp new file mode 100644 index 0000000..0b576eb --- /dev/null +++ b/src/accounting/ledger.cpp @@ -0,0 +1,87 @@ +#include "evo/accounting/ledger.hpp" + +#include + +namespace evo::accounting { +namespace { +bool add(std::uint64_t& value, std::uint64_t amount) noexcept { + if (amount > std::numeric_limits::max() - value) { + return false; + } + value += amount; + return true; +} +bool accumulate(Inventory& total, const Inventory& amount) noexcept { + if (!add(total.energy.value, amount.energy.value)) { + return false; + } + for (std::size_t index = 0; index < total.matter.size(); ++index) { + if (!add(total.matter[index].value, amount.matter[index].value)) { + return false; + } + } + return true; +} +bool contains(const Inventory& balance, const Inventory& amount) noexcept { + if (balance.energy < amount.energy) { + return false; + } + for (std::size_t index = 0; index < balance.matter.size(); ++index) { + if (balance.matter[index] < amount.matter[index]) { + return false; + } + } + return true; +} +} // namespace + +std::expected Ledger::create(std::span opening) { + if (opening.empty() || opening.size() > max_reservoirs) { + return std::unexpected{LedgerError::reservoir_limit}; + } + Ledger ledger; + for (const auto& balance : opening) { + if (!accumulate(ledger.totals_, balance)) { + return std::unexpected{LedgerError::overflow}; + } + } + ledger.balances_.assign(opening.begin(), opening.end()); + return ledger; +} + +std::expected Ledger::transfer(std::uint64_t action, + std::span legs) { + if (action <= last_action_) { + return std::unexpected{LedgerError::stale_action}; + } + if (legs.empty() || legs.size() > max_transfers) { + return std::unexpected{LedgerError::transfer_limit}; + } + auto candidate = balances_; + for (const auto& leg : legs) { + if (leg.from.value == 0 || leg.to.value == 0 || leg.from.value > candidate.size() || + leg.to.value > candidate.size()) { + return std::unexpected{LedgerError::invalid_reservoir}; + } + if (leg.from.value == leg.to.value) { + return std::unexpected{LedgerError::same_reservoir}; + } + auto& source = candidate[leg.from.value - 1]; + auto& destination = candidate[leg.to.value - 1]; + if (!contains(source, leg.amount)) { + return std::unexpected{LedgerError::insufficient_inventory}; + } + // Global totals bound every destination; keep the local check explicit. + if (!accumulate(destination, leg.amount)) { + return std::unexpected{LedgerError::overflow}; + } + source.energy.value -= leg.amount.energy.value; + for (std::size_t index = 0; index < source.matter.size(); ++index) { + source.matter[index].value -= leg.amount.matter[index].value; + } + } + balances_.swap(candidate); + last_action_ = action; + return {}; +} +} // namespace evo::accounting diff --git a/tests/ledger_tests.cpp b/tests/ledger_tests.cpp new file mode 100644 index 0000000..dde0b6f --- /dev/null +++ b/tests/ledger_tests.cpp @@ -0,0 +1,194 @@ +#include "evo/accounting/ledger.hpp" +#include "evo/core/random.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::accounting; +static_assert(!std::is_convertible_v); +static_assert(!std::is_convertible_v); + +void check(bool condition) { + if (!condition) { + throw std::runtime_error("ledger contract failed"); + } +} +#define CHECK(expression) check(static_cast(expression)) + +Inventory amount(std::uint64_t energy, std::uint64_t carbon = 0, std::uint64_t nitrogen = 0, + std::uint64_t phosphorus = 0, std::uint64_t other = 0) { + return {Picojoules{energy}, + {Femtograms{carbon}, Femtograms{nitrogen}, Femtograms{phosphorus}, Femtograms{other}}}; +} +std::vector copy(const Ledger& ledger) { + return {ledger.balances().begin(), ledger.balances().end()}; +} +void conserved(const Ledger& ledger) { + // Recompute independently from actual balances, not the cached total. + Inventory sum{}; + for (const auto& balance : ledger.balances()) { + CHECK(balance.energy.value <= std::numeric_limits::max() - sum.energy.value); + sum.energy.value += balance.energy.value; + for (std::size_t index = 0; index < 4; ++index) { + CHECK(balance.matter[index].value <= + std::numeric_limits::max() - sum.matter[index].value); + sum.matter[index].value += balance.matter[index].value; + } + } + CHECK(sum == ledger.conserved_totals()); +} + +void finite_source_and_heat() { + const std::array opening{amount(100, 10, 20, 30, 40), Inventory{}, Inventory{}}; + auto ledger = Ledger::create(opening); + CHECK(ledger); + // A finite source funds reserve plus explicitly accounted heat. + const std::array capture{Transfer{{1}, {2}, amount(100, 10, 20, 30, 40)}, + Transfer{{2}, {3}, amount(25)}}; + CHECK(ledger->transfer(1, capture)); + CHECK(ledger->balances()[0] == Inventory{}); + CHECK(ledger->balances()[1] == amount(75, 10, 20, 30, 40)); + CHECK(ledger->balances()[2] == amount(25)); + const auto before = copy(*ledger); + const auto duplicate = ledger->transfer(1, capture); + CHECK(!duplicate && duplicate.error() == LedgerError::stale_action); + const auto empty_source = ledger->transfer(2, capture); + CHECK(!empty_source && empty_source.error() == LedgerError::insufficient_inventory); + CHECK(copy(*ledger) == before && ledger->last_action() == 1); + conserved(*ledger); +} + +void atomic_rejection_and_limits() { + const std::array opening{amount(10, 10, 10, 10, 10), Inventory{}, Inventory{}}; + auto ledger = Ledger::create(opening); + CHECK(ledger); + const auto before = copy(*ledger); + const auto reject = [&](std::uint64_t action, std::span legs, + LedgerError expected) { + const auto result = ledger->transfer(action, legs); + CHECK(!result && result.error() == expected); + CHECK(copy(*ledger) == before && ledger->last_action() == 0); + }; + std::array legs{Transfer{{1}, {2}, amount(5, 5, 5, 5, 5)}, Transfer{{1}, {3}, amount(6)}}; + reject(0, legs, LedgerError::stale_action); + reject(1, {}, LedgerError::transfer_limit); + reject(1, legs, LedgerError::insufficient_inventory); + for (std::size_t channel = 0; channel < 4; ++channel) { + legs[1].amount = {}; + legs[1].amount.matter[channel] = Femtograms{6}; + reject(1, legs, LedgerError::insufficient_inventory); + } + legs[1] = Transfer{{0}, {3}, {}}; + reject(1, legs, LedgerError::invalid_reservoir); + legs[1] = Transfer{{1}, {4}, {}}; + reject(1, legs, LedgerError::invalid_reservoir); + legs[1] = Transfer{{1}, {1}, {}}; + reject(1, legs, LedgerError::same_reservoir); + std::vector large(max_transfers + 1, Transfer{{1}, {2}, {}}); + reject(1, large, LedgerError::transfer_limit); + large.pop_back(); + CHECK(ledger->transfer(1, large)); // Valid zero transfer consumes its action ID. + CHECK(ledger->last_action() == 1 && copy(*ledger) == before); + const std::array drain{Transfer{{1}, {2}, amount(10, 10, 10, 10, 10)}}; + CHECK(ledger->transfer(std::numeric_limits::max(), drain)); + CHECK(!ledger->transfer(std::numeric_limits::max(), drain)); + conserved(*ledger); + + CHECK(!Ledger::create({})); + std::vector many(max_reservoirs + 1); + CHECK(!Ledger::create(many)); + many.pop_back(); + CHECK(Ledger::create(many)); + constexpr auto maximum = std::numeric_limits::max(); + std::array excessive{amount(maximum), amount(1)}; + auto invalid = Ledger::create(excessive); + CHECK(!invalid && invalid.error() == LedgerError::overflow); + for (std::size_t channel = 0; channel < 4; ++channel) { + excessive = {}; + excessive[0].matter[channel] = Femtograms{maximum}; + excessive[1].matter[channel] = Femtograms{1}; + invalid = Ledger::create(excessive); + CHECK(!invalid && invalid.error() == LedgerError::overflow); + } + const std::array exact{amount(maximum, maximum, maximum, maximum, maximum), Inventory{}}; + auto full = Ledger::create(exact); + CHECK(full); + const std::array move_all{Transfer{{1}, {2}, exact[0]}}; + CHECK(full->transfer(1, move_all)); + CHECK(full->balances()[0] == Inventory{} && full->balances()[1] == exact[0]); + conserved(*full); +} + +void ordered_competition() { + const std::array opening{amount(10), Inventory{}, Inventory{}}; + auto ledger = Ledger::create(opening); + CHECK(ledger); + const std::array first{Transfer{{1}, {2}, amount(7)}}; + const std::array second{Transfer{{1}, {3}, amount(7)}}; + CHECK(ledger->transfer(1, first)); + CHECK(!ledger->transfer(2, second)); + const std::array corrected{Transfer{{1}, {3}, amount(3)}}; + CHECK(ledger->transfer(2, corrected)); + conserved(*ledger); + auto chain = Ledger::create(opening); + CHECK(chain); + const std::array unfunded{Transfer{{2}, {3}, amount(10)}, Transfer{{1}, {2}, amount(10)}}; + CHECK(!chain->transfer(1, unfunded)); + auto funded = unfunded; + std::ranges::reverse(funded); + CHECK(chain->transfer(1, funded)); + CHECK(chain->balances()[2] == amount(10)); +} + +void million_transaction_replay() { + // 32 deterministic streams, each with 31,250 transactions: one million total. + for (std::uint64_t seed = 0; seed < 32; ++seed) { + const std::array opening{amount(1000, 1000, 1000, 1000, 1000), + amount(1000, 1000, 1000, 1000, 1000), + amount(1000, 1000, 1000, 1000, 1000)}; + auto ledger = Ledger::create(opening); + CHECK(ledger); + auto replay = *ledger; + auto reference = opening; + evo::Random random{seed}; + for (std::uint64_t action = 1; action <= 31'250; ++action) { + const auto from = static_cast(random.next() % 3); + const auto to = (from + 1 + static_cast(random.next() % 2)) % 3; + const auto available = reference[from]; + Inventory moved{}; + moved.energy.value = random.next() % (available.energy.value + 1); + for (std::size_t channel = 0; channel < 4; ++channel) { + moved.matter[channel].value = random.next() % (available.matter[channel].value + 1); + reference[from].matter[channel].value -= moved.matter[channel].value; + reference[to].matter[channel].value += moved.matter[channel].value; + } + reference[from].energy.value -= moved.energy.value; + reference[to].energy.value += moved.energy.value; + const std::array legs{Transfer{ReservoirId{static_cast(from + 1)}, + ReservoirId{static_cast(to + 1)}, moved}}; + CHECK(ledger->transfer(action, legs)); + CHECK(replay.transfer(action, legs)); + CHECK(std::ranges::equal(ledger->balances(), reference)); + CHECK(std::ranges::equal(ledger->balances(), replay.balances())); + CHECK(ledger->last_action() == replay.last_action()); + conserved(*ledger); + } + } +} +} // namespace + +int main() try { + finite_source_and_heat(); + atomic_rejection_and_limits(); + ordered_competition(); + million_transaction_replay(); + std::cout << "PASS ledger contracts and 1000000 seeded transactions\n"; + return 0; +} catch (...) { + return 1; +}