diff --git a/mk-skin-plan.md b/mk-skin-plan.md new file mode 100644 index 0000000000..e451c30f41 --- /dev/null +++ b/mk-skin-plan.md @@ -0,0 +1,377 @@ +# UTxO-HD `js/utxo-hd-4` — the `mk`-skin review intermediate (plan) + +**Portable plan. Self-contained.** A fresh Claude on another machine should be +able to pick this up with only: this repo at branch `js/utxo-hd-4` (the finished, +green, `mk`-free tree), and this file. Read [`utxo-hd-4.md`](./utxo-hd-4.md) +(design record, esp. decisions 1–14), [`notes2.md`](./notes2.md) (design source +of truth), and [`next-steps.md`](./next-steps.md) (what the branch did) for the +redesign itself. **This file is only about the review scaffolding**, not the +redesign. + +--- + +## Why this exists + +`js/utxo-hd-4` removes the `mk :: MapKind` parameter from `LedgerState` and +carries on-disk tables as opaque `Keys`/`Values`/`Diff blk` payloads. The diff +vs the review base (`e6fad0630`, prepare-11.1) is ~196 source files / ~12k +changed lines and is hard to review as one unit. + +We are building an **intermediate tree `I`** (branch `js/utxo-hd-4-skin`) in which +the ledger state carries a `mk` parameter *again* — but `mk` is a **thin newtype +skin over the new opaque payloads**, not the old machinery. + +**The goal is ISOLATION of syntactic vs semantic changes — NOT line reduction.** +Re-dressing the finished design in `prepare-11.1`'s `mk` *vocabulary* splits the +review into two diffs: +- `git diff e6fad0630 ` — the **semantic** diff: the genuine redesign + expressed *in prepare-11.1's `mk` syntax*, with **zero mk-removal churn mixed + in** (mk is still present, like prepare-11.1). +- `git diff js/utxo-hd-4` — the **syntactic strip**: a *purely mechanical* + mk-removal pass, trust-by-inspection (or regenerable). + +⚠️ **Do not expect `e6 → I` to be smaller than `e6 → full`.** It is roughly the +same size — the redesign is simply large. What the skin buys is the clean +*factoring*: the mk-parameter syntax swap is pulled out into the strip, so the +semantic diff is no longer interleaved with mk-removal noise. See "Result" below +for the measured confirmation. + +**`I` is throwaway.** It is review scaffolding; the branch that merges is the +original `js/utxo-hd-4` (HEAD). The skin commits are dropped before merge. + +**Scope (decided): the five production libraries only** — +`lib:{ouroboros-consensus, diffusion, protocol, cardano, lsm}`. The testlibs +(`unstable-*`), tools, test-suites and benchmarks are **deliberately left red** in +`I`: they are themselves "recipe" code with little review value, and `I` is +throwaway so it need not build them. Only the five libs need to typecheck for +`prepare-11.1 → I` to be a trustworthy review artifact. + +### Early spike estimates (turned out partly misleading — see "Result") +The two spikes suggested ~51% of churn is vocabulary (cancellable) and Storage +~85% cancels. **Caveat:** those figures conflated *line cancellation* (which the +consensus lib barely shows — it IS the structural redesign) with *isolation* +(which works). The 51% was the testlibs/ports (out of scope); 85% was Storage +specifically. Read them as "isolation is feasible," not "the diff shrinks." + +### Cost / risk (eyes open) +Building `I` is **"the original `mk`-removal run in reverse"**: re-adding `mk` to +the `LedgerState`/`Ticked`/`ExtLedgerState` data families breaks **every +`data instance` lib-wide in one shot — no green checkpoint until nearly done**. +Type-level feasibility **confirmed in practice** (the whole consensus lib + 2 more +libs are green with **zero `unsafeCoerce`/`unsafePerformIO`**); the spike's +unverified risks (real `sop-core` `NS`/`Telescope`, `AllowAmbiguousTypes`) did not +bite. + +--- + +## Ground rules (do not forget these offline) + +- **Commits UNSIGNED:** `git -c commit.gpgsign=false commit -m "…"` (GPG/pinentry + hangs here). +- **Do NOT push** to GitHub. Syncing to your own private remote is your call. +- **Commit messages must not mention AI/Claude.** Prefix `[UTxO-HD][skin]`. +- **NEVER use `unsafeCoerce` or `unsafePerformIO`.** If the skin appears to need + them, STOP — that means the design is wrong; reconsider, don't reach for them. +- TODOs in source are tagged `TODO @js`. +- Work on branch **`js/utxo-hd-4-skin`** (off `js/utxo-hd-4`). Leave + `js/utxo-hd-4` untouched — it is the merge target. + +--- + +## The skin (the single design decision that drives everything) + +Add to `Ouroboros/Consensus/Ledger/Basics.hs`. **`l = blk` (a `Type`)** — this is +the only well-kinded reading and it is the clean one (a thin newtype layer over +the *existing* opaque associated types; no canonical machinery, no coercions): + +```haskell +type MapKind = Type -> Type +type LedgerStateKind = MapKind -> Type + +newtype LedgerTables l mk = LedgerTables (mk l) + +data EmptyMK l = EmptyMK +newtype KeysMK l = KeysMK (Keys l) -- Keys/Values/Diff are the CURRENT +newtype ValuesMK l = ValuesMK (Values l) -- associated types on +newtype DiffMK l = DiffMK (Diff l) -- BlockSupportsUTxOHD +-- so LedgerTables blk ValuesMK ≅ Values blk, etc. +``` + +**Resolved during Phase 1 (grounded in `git show e6fad0630`):** `prepare-11.1` is *already* +`blk`-indexed for tables — `newtype LedgerTables blk mk` (`Type -> MapKind -> +Type`), `type family TxIn blk`, and the handle is `LedgerTablesHandle m l blk` +with `read :: l blk EmptyMK -> LedgerTables blk KeysMK -> m (LedgerTables blk +ValuesMK)` (functor `l` applied to `blk`+`mk`, tables `blk`-indexed). So the clean +`l = blk` skin reproduces `prepare-11.1`'s signatures **verbatim** and is also the +feasible one — the two spikes were *not* in conflict (Spike A's `blk` model = +`prepare-11.1`'s shape). The only divergence is single-arg `mk` (`KeysMK blk = KeysMK +(Keys blk)`) vs `prepare-11.1`'s two-arg (`KeysMK k v = Set k`), invisible in applied +positions. `HasLedgerTables` is a per-`blk` class over `LedgerState blk mk` (the +spike's shape); `ExtLedgerState` gets its own handling in `Extended.hs`. + +**Crucial nuances:** + +1. **Single-arg `mk`, unlike `prepare-11.1`.** `prepare-11.1`'s `MapKind` is two-arg (`EmptyMK k + v`, `ValuesMK k v = ValuesMK (Map k v)`). Ours is one-arg (`KeysMK l`). In + *applied* form the signatures read identically — `LedgerState blk EmptyMK`, + `LedgerTables blk DiffMK` — so they **cancel textually** against `prepare-11.1`. We do + NOT resurrect `prepare-11.1`'s `CanMapMK`/`CanMapKeysMK`/`ZeroableMK`/`mapKeysMK` + combinator zoo; that machinery stays deleted in `I` and shows up in + `prepare-11.1 → I` as a deletion. **That is intended, bounded residue** — the + redesign genuinely deleted it. + +2. **Revert decision 1.** The HFC telescope functor goes back to `Flip + LedgerState mk` (`prepare-11.1`'s known-good shape). The telescope itself stays + **table-free** (`NS (Flip LedgerState EmptyMK) xs`); the running `mk` lives in + the **HFC-level tables field beside the telescope** (`NS WrapValues xs` etc.), + exactly as `prepare-11.1` arranges it. Spike A proved both body-level failures vanish + under this arrangement. So `Flip`/`unFlip`/`FlipTickedLedgerState` come back. + +3. **The Shelley `shelleyLedgerTables` field comes back** on `LedgerState + (ShelleyBlock …) mk`, holding `LedgerTables (ShelleyBlock …) mk`. + +4. Also restore the `HasLedgerTables` vocabulary the call sites use — + `projectLedgerTables` / `withLedgerTables` / `forgetLedgerTables` / + `emptyLedgerTables` — over the skin, so the call sites cancel against `prepare-11.1`. + Defer this to Phase 1 (its methods mention `l mk`). + +**Build target for each file:** drive `git diff e6fad0630: ` toward +zero *except* for the genuine structural changes. Keep `git show e6fad0630:` +open and match `prepare-11.1`'s signature text where the redesign didn't truly change the +shape. + +--- + +## Order of attack (the all-at-once edit is unavoidable) + +> There is **no green checkpoint** between Phase 0 and the end of Phase 1. Adding +> `mk` to the `LedgerState` data family breaks every `data instance` lib-wide +> simultaneously. Lean on HLS per-file + the breakage grep, not on a green +> ghciwatch, until Phase 1 lands. Same red-stretch profile as the original +> `mk`-removal, run in reverse. + +**Phase 0 — skin types (GREEN, self-contained).** Add the 6 skin definitions +above to `Basics.hs` + exports. They are unused so far ⇒ lib stays green. Commit. +*(Status: see bottom.)* + +**Phase 1 — re-add `mk` to the state functors (THE red stretch).** +- `Basics.hs`: `data family LedgerState blk` → `data family LedgerState blk (mk + :: MapKind)`; `TickedLedgerState`; `type LedgerState :: Type -> MapKind -> Type`. +- `Ledger/Extended.hs`: `ExtLedgerState blk` → `ExtLedgerState blk mk`. +- Add the `HasLedgerTables`/`CanStowLedgerTables`/`CanUpgradeLedgerTables`-style + classes back over the skin (only what the call sites actually use). +- Re-add `mk` to **every `data instance LedgerState`/`Ticked` lib-wide in one + shot** — Byron/mock trivial, Shelley with `shelleyLedgerTables`, HFC with the + `NS` tables field + `Flip` functor. Grep: `data instance LedgerState`, + `data instance Ticked`. +- Restore `Flip`/`FlipTickedLedgerState`/`unFlip` in `TypeFamilyWrappers` + HFC + `State`/`Basics`/`Ledger`. +- `GetTip`, `Eq`/`Show`/`NoThunks` quantified-over-`mk` instances. + +**Phase 2 — abstract apply path (`Ledger/Abstract`, `IsLedger`, `ApplyBlock`).** +Re-dress to `prepare-11.1`'s signatures over the skin: +- `applyChainTick :: … -> l EmptyMK -> Ticked l DiffMK` (re-bundle the current + `(ticked, diff)` return into the ticked state's `DiffMK` field). +- `applyBlock`/`tickThenApply`: `… -> Ticked l ValuesMK -> … l DiffMK` (or + `TrackingMK` to match `prepare-11.1` — check `prepare-11.1`'s exact result mk). +- `blockKeys` ↔ `prepare-11.1`'s `getBlockKeySets :: … -> LedgerTables l KeysMK` shape. + +**Phase 3 — Storage (`Storage/LedgerDB/**`).** Per Spike B: re-wrap the handle +record (`read :: … -> LedgerTables l KeysMK -> m (LedgerTables l ValuesMK)`), +`Forker`, `LedgerSeq`, the LedgerDB API, snapshots, V2 InMemory backend. **Leave** +the structural residue (it does not cancel and is the review target): the +`EraRangeReader`/`RangeReadTables` range-read rework, `duplicateWithDiffs` going +from `Diff` to `prepare-11.1`'s two-state shape (can't be faked — stays different), the +explicit `blockKeys` extraction. + +**Phase 4 — HFC combinator, Mempool, Node, MiniProtocol.** Re-dress signatures. +HFC is the hard part; the `Flip` functor + sibling tables field (decision above) +is the load-bearing arrangement. + +**Phase 5 — cardano lib (byron/shelley/cardano).** Re-dress. Lots of files, +mostly mechanical once the lib shape is settled. **Testlibs / tools / +test-suites are out of scope** (left red — see "Scope" above). + +**Phase 6 — verify `I` typechecks** (lib, then `diffusion`, `lsm`, `cardano`). +Full green not strictly required for review, but the closer to green, the more +trustworthy `prepare-11.1 → I` is. Tests need not pass (it is throwaway). + +**Phase 7 — produce + sanity-check the review artifacts.** +``` +git diff --stat e6fad0630 js/utxo-hd-4-skin # semantic — want this much smaller than the full diff +git diff --stat js/utxo-hd-4-skin js/utxo-hd-4 # mechanical strip — want this "obviously vocabulary" +``` +Confirm the semantic diff is dominated by the genuine redesign (HFC canonical→NS, +the new `forward`/`BlockSupportsUTxOHD` surface, Storage range-reads, mempool, +serialisation) and not by `mk`-vocabulary noise. + +--- + +## Verify loop + +ghciwatch (authoritative, whole-lib reload). **Watch only the lib source dir, not +`.`** Run in background, no trailing `&`: +``` +ghciwatch --command "cabal repl lib:ouroboros-consensus" \ + --watch ouroboros-consensus/src/ouroboros-consensus \ + --error-file /tmp/ghciwatch-skin.errors \ + --reload-glob '!dist-newstyle' --reload-glob '!../dist-newstyle' \ + > /tmp/ghciwatch-skin.log 2>&1 +``` +`cat /tmp/ghciwatch-skin.errors` after each save (`All good (N modules)` = clean). +HLS in-editor diagnostics are faster per-file during the red stretch. + +Breakage-surface grep (the reverse of the removal grep — find sites still missing +the skin): +``` +grep -rn 'data instance LedgerState\|data instance Ticked\|LedgerState blk ->\|ExtLedgerState blk ->' \ + ouroboros-consensus/src/ouroboros-consensus +``` + +--- + +## Spike findings (embedded so this file is self-contained) + +Two spikes (type-model + reasoning, **not** full builds) settled feasibility. +WIP patches: `mk-skin-spike-hfc.patch`, `mk-skin-spike-storage.patch` (copied into +the repo root alongside this file). + +**Spike A — HFC / "indexing by `l`": GO.** +- Well-kinded only under `l = blk`; then the skin is a thin newtype over the + existing opaque types. No `unsafeCoerce`, no `AllowAmbiguousTypes` needed for + the skin itself (the branch already lives with `AllowAmbiguousTypes` for the + non-injective families). +- Body failures (`withLedgerTables` on the telescope; rebuilding a telescope + element at the wrong mk) **both vanish** when the telescope stays table-free and + the running `mk` lives in the sibling HFC tables field — i.e. revert decision 1 + to `prepare-11.1`'s `Flip LedgerState mk` functor. +- Unverified: real `sop-core` `NS`/`Telescope` with `All`/`SListI`; re-quantified + `GetTip`/`NoThunks`/serialisation instances. + +**Spike B — Storage / "rearranging tuples": ~80–85% cancels.** +- Of ~650 changed Storage lines, ~85% become byte-identical to `prepare-11.1` once + re-dressed (the 148 `mk`-on-state lines dominate; the re-dressed handle `read` + field was confirmed byte-identical to `e6fad0630`). +- Irreducible residue (the genuine Storage redesign, ~15–20%): `readRange`/ + `readAll` → `RangeReadTables`/`EraRangeReader`/`EraRangeReaderProvider`/ + `withEraRangeReader` (decision 10); `duplicateWithDiffs` arity (2 states → 1 + `Diff` — the skin cannot fabricate states it doesn't have); explicit `blockKeys` + + `(state, diff)` apply flow; the `LedgerSeq` haddock rewrite. +- The cancellation is gated on the global `mk`-on-state kind change (Phase 1) — + i.e. it is mechanical per-site but only after the all-at-once edit. + +--- + +## RESULT (the isolation goal — achieved) + +The success criterion is **isolation of syntactic vs semantic**, not line reduction. +Verified on `lib:ouroboros-consensus`: the strip `js/utxo-hd-4-skin → js/utxo-hd-4` +(881 churn) is **purely syntactic** — word-diff shows every changed token is an +`mk`-vocabulary removal or its direct fragment (surviving `blk`, unwrapped +`unFlip`/`getFlipTickedLedgerState` inner expr, `StateKind`→`(Type -> Type)` +kind-sig reverts, removed skin pragma/comment/constraint). No reordered args, no +changed calls, no behavioural edits. So `e6fad0630 → skin` carries the genuine +redesign **in prepare-11.1's `mk` syntax with zero mk-removal churn mixed in**, +and the strip is a trust-by-inspection mechanical pass. (Line count of `e6 → skin` +≈ `e6 → full` — irrelevant; the redesign is simply large. What matters is it's +cleanly factored from the syntax swap.) + +**Measured per lib (line cancellation vs isolation):** +- `lib:ouroboros-consensus`: full `e6→utxo-hd-4` = 5,419 churn; semantic `e6→skin` + = 5,190 (~96% — barely smaller, because this lib *is* the structural redesign: + ~1,369 lines are the `Tables/` machinery deletion alone). Strip = 881, and it's + **purely syntactic** (the isolation win). +- `diffusion`: full diff is only 28 churn — never a review problem; skin moot. +- `lsm`: 1 module, 4 `EmptyMK` additions — trivial. +- `cardano`: expected to cancel *best* (Shelley regains `shelleyLedgerTables` + -in-state, matching prepare-11.1) — in progress. + +Takeaway: **isolation is the deliverable and it works; line-shrink does not happen +for the libs and was never the right metric.** + +## Status & decisions (current) + +**Branch `js/utxo-hd-4-skin`** (off untouched merge target `js/utxo-hd-4` @ `341ab6f55`). +Only `mk-skin-plan.md` is tracked as a non-code file. Safety backup of the +pre-history-scrub tip: branch `skin-backup-prefilter` (delete once happy). + +### Done +- [x] **`lib:ouroboros-consensus`** — fully skinned, `All good (239 modules)`, + **zero `unsafeCoerce`/`unsafePerformIO`**. +- [x] **`diffusion`** — green-skinned, integrated. +- [x] **`lsm`** — green-skinned, integrated. (Also fixed a latent consensus-lib bug: + the streaming `Yield`/`Sink` aliases must be `l blk EmptyMK`, not `l blk` — + only the LSM backend threads a handle through them, so it surfaced there.) +- [x] **History scrubbed.** An early *non-isolated* agent's `git add -A` folded the + repo-root working files (design notes, decks, logs, spike patches) into the + branch. Removed from ALL commits via `git filter-branch` (kept `mk-skin-plan.md`; + `.gitattributes` reset to base throughout, the user's `diff=cbor` change kept as + a pending working-tree modification). Code byte-identical pre/post scrub. + **Lesson: run sweep agents worktree-isolated, or scope every `git add` — never `-A`.** + +- [x] **`protocol`** (9 modules) — needed ZERO source changes (it never references + `LedgerState`/tables); green once the skinned lib built. +- [x] **`cardano`** (57 modules) — green-skinned, integrated (cherry-picked the 4 + cardano commits onto the scrubbed tip). Shelley `shelleyLedgerTables`-in-state + reintroduced; `CanHardFork` era-translation `Flip`/`Comp` wrapping restored at + `EmptyMK`. Artifacts: full `e6→utxo-hd-4` 3,648 churn; semantic `e6→skin` 3,554 + (~97%); strip 270 churn (mostly syntactic). **No `HasLedgerTables` instances + needed** for Shelley/Byron/Cardano/HFC — nothing in the 5 libs requires them. + +### ✅ ALL FIVE LIBS GREEN — the skin is complete +`cabal build` of `lib:ouroboros-consensus`, `diffusion`, `lsm`, `protocol`, +`cardano` all succeed on `js/utxo-hd-4-skin`. Zero `unsafeCoerce`/`unsafePerformIO`. + +### Remaining +- [ ] **Review artifacts (per lib):** `git diff e6fad0630 ` (semantic) + + `git diff js/utxo-hd-4` (syntactic strip). Measured: consensus lib + semantic ~5.2k churn / strip 881 (purely syntactic); cardano semantic ~3.6k / + strip 270; diffusion 28 total; lsm trivial. +- [ ] **Cleanup:** delete `skin-backup-prefilter` + `refs/original/*` (filter-branch + backup) once the history scrub is accepted. + +### Decisions (load-bearing) +1. **Skin shape:** single-arg `mk`, `l = blk`; thin newtype over the existing opaque + `Keys/Values/Diff`. prepare-11.1's `CanMapMK`/combinator zoo is NOT resurrected + (stays deleted — intended, shows in `e6→skin`). +2. **HFC = option 2 (phantom `mk`).** HFC `LedgerState (HardForkBlock xs) mk` has `mk` + phantom; telescope functor is `Flip LedgerState EmptyMK` (`FlipTickedLedgerState + EmptyMK` for ticked). `Flip` had to return regardless (a 2-arg `LedgerState x` + isn't a `Type`), but pinned at `EmptyMK` — no `mk`-threading through HFC bodies, + clean strip. The genuine canonical→`NS WrapValues` tables change correctly shows in + `e6→skin`. +3. **EqMK infeasible single-arg:** prepare-11.1's `forall mk. EqMK mk => Eq (l blk mk)` + needs two-arg `mk` (plain type vars); single-arg's payload is a type family + (`Keys blk`), and GHC forbids type families in quantified constraints (`GHC-22979`). + So `IsLedger` uses **concrete-`mk` constraints** (`Eq (l blk EmptyMK)`, …). That one + superclass block doesn't cancel — small localised residue. +4. **Apply-path altitude:** re-dress only the **state `mk`-vocabulary**; KEEP the + branch's genuine apply restructuring visible (explicit `Values blk` param, + `(state, Diff)` tuples, `forward`). So `applyChainTick` stays + `… l blk EmptyMK -> (Ticked l blk EmptyMK, Diff blk)` (a tuple — NOT prepare-11.1's + bundled `DiffMK`); only state positions get `EmptyMK`, bodies unchanged. That + restructuring is redesign and SHOULD appear in `e6→skin`. (This supersedes the + earlier "Phase 2" note above that suggested bundling into `DiffMK`.) +5. **Cardano:** Shelley `LedgerState (ShelleyBlock …) mk` regains `shelleyLedgerTables` + -in-state (matching prepare-11.1); Byron void/phantom. **One documented divergence + to review:** `transPraosLS` (CanHardFork) — prepare-11.1 keeps it poly-`mk` with + `shelleyLedgerTables = coerce tb`, but the single-arg skin's `coerce` fails (nominal + role crossing `TPraos`→`Praos`); it's only ever called at `EmptyMK` (telescope + state), so it was specialized to `EmptyMK` + `emptyLedgerTables`. Honest and + correct, but a small intentional deviation from the e6 text (shows in `e6→skin`). +6. **Scope:** the 5 production libs only; testlibs/tools/test-suites left red. + +### Mechanical rhythm (for the cardano sweep + any continuation) +Per module: save → **stable-read** the ghciwatch error file (wait until NOT "still +compiling" AND unchanged between two polls — a plain check races the reload) → for +each flagged `LedgerState`/`Ticked`/`ExtLedgerState` in **value/field/functor** +position add the right `mk`: **`EmptyMK`** (tableless states), **poly `mk`** +(read-only accessors), **`Flip EmptyMK`** (`NS`/`Current`/`HardForkState`/ +`Product` functor args, with `unFlip`/`getFlipTickedLedgerState`/`Flip` in bodies). +Add `EmptyMK` to explicit import lists where missing. **Leave alone** +functor-unapplied/constraint/instance-head sites (`LedgerErr l blk`, `IsLedger l blk`, +`LedgerCfg l blk`, `GetTip (l blk)`). Template per file: `git show e6fad0630:` +(it does this at `mk`; substitute `mk → EmptyMK`). Commit per module-group. + +> Note: the "Order of attack" / "Phase N" sections above are the *original plan*, +> kept for context; this section is the authoritative current state. diff --git a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/ByronHFC.hs b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/ByronHFC.hs index 40b3cb94ba..b08985676d 100644 --- a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/ByronHFC.hs +++ b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/ByronHFC.hs @@ -155,7 +155,7 @@ byronTransition :: PartialLedgerConfig ByronBlock -> -- | Shelley major protocol version Word16 -> - LedgerState ByronBlock -> + LedgerState ByronBlock mk -> Maybe EpochNo byronTransition partialConfig shelleyMajorVersion state = takeAny diff --git a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Forge.hs b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Forge.hs index 4ad5575c7e..c979e771a3 100644 --- a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Forge.hs +++ b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Forge.hs @@ -52,7 +52,7 @@ forgeByronBlock :: -- | Current slot number SlotNo -> -- | Current ledger - TickedLedgerState ByronBlock -> + TickedLedgerState ByronBlock mk -> -- | Txs to include [Validated (GenTx ByronBlock)] -> -- | Leader proof ('IsLeader') @@ -137,7 +137,7 @@ forgeRegularBlock :: -- | Current slot number SlotNo -> -- | Current ledger - TickedLedgerState ByronBlock -> + TickedLedgerState ByronBlock mk -> -- | Txs to include [Validated (GenTx ByronBlock)] -> -- | Leader proof ('IsLeader') diff --git a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Inspect.hs b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Inspect.hs index a0fe85dd3e..9d1ff6390a 100644 --- a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Inspect.hs +++ b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Inspect.hs @@ -97,7 +97,7 @@ data UpdateState -- | All proposal updates, from new to old protocolUpdates :: LedgerConfig ByronBlock -> - LedgerState ByronBlock -> + LedgerState ByronBlock mk -> [ProtocolUpdate] protocolUpdates genesis st = concat diff --git a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Ledger.hs b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Ledger.hs index a7d035a278..04978300f4 100644 --- a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Ledger.hs +++ b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Ledger.hs @@ -95,7 +95,7 @@ import Ouroboros.Consensus.Util (ShowProxy (..)) LedgerState -------------------------------------------------------------------------------} -data instance LedgerState ByronBlock = ByronLedgerState +data instance LedgerState ByronBlock mk = ByronLedgerState { byronLedgerTipBlockNo :: !(WithOrigin BlockNo) , byronLedgerState :: !CC.ChainValidationState , byronLedgerTransition :: !ByronTransition @@ -127,7 +127,7 @@ initByronLedgerState :: Gen.Config -> -- | Optionally override UTxO Maybe CC.UTxO -> - LedgerState ByronBlock + LedgerState ByronBlock mk initByronLedgerState genesis mUtxo = ByronLedgerState { byronLedgerState = override mUtxo initState @@ -174,7 +174,7 @@ getByronTip state = -------------------------------------------------------------------------------} -- | The ticked Byron ledger state -data instance Ticked LedgerState ByronBlock = TickedByronLedgerState +data instance Ticked LedgerState ByronBlock mk = TickedByronLedgerState { tickedByronLedgerState :: !CC.ChainValidationState , untickedByronLedgerTransition :: !ByronTransition } @@ -264,7 +264,7 @@ instance CommonProtocolParams ByronBlock where maxTxSize = fromIntegral . Update.ppMaxTxSize . getProtocolParameters -- | Return the protocol parameters adopted by the given ledger. -getProtocolParameters :: LedgerState ByronBlock -> Update.ProtocolParameters +getProtocolParameters :: LedgerState ByronBlock mk -> Update.ProtocolParameters getProtocolParameters = CC.adoptedProtocolParameters . CC.cvsUpdateState @@ -371,8 +371,8 @@ applyByronBlock :: ComputeLedgerEvents -> LedgerConfig ByronBlock -> ByronBlock -> - TickedLedgerState ByronBlock -> - Except (LedgerError ByronBlock) (LedgerState ByronBlock) + TickedLedgerState ByronBlock mk1 -> + Except (LedgerError ByronBlock) (LedgerState ByronBlock mk2) applyByronBlock doValidation _doEvents @@ -398,8 +398,8 @@ applyABlock :: CC.ABlock ByteString -> CC.HeaderHash -> BlockNo -> - TickedLedgerState ByronBlock -> - Except (LedgerError ByronBlock) (LedgerState ByronBlock) + TickedLedgerState ByronBlock mk1 -> + Except (LedgerError ByronBlock) (LedgerState ByronBlock mk2) applyABlock validationMode cfg blk blkHash blkNo TickedByronLedgerState{..} = do st' <- CC.validateBlock cfg validationMode blk blkHash tickedByronLedgerState @@ -441,8 +441,8 @@ applyABoundaryBlock :: Gen.Config -> CC.ABoundaryBlock ByteString -> BlockNo -> - TickedLedgerState ByronBlock -> - Except (LedgerError ByronBlock) (LedgerState ByronBlock) + TickedLedgerState ByronBlock mk1 -> + Except (LedgerError ByronBlock) (LedgerState ByronBlock mk2) applyABoundaryBlock cfg blk blkNo TickedByronLedgerState{..} = do st' <- CC.validateBoundary cfg blk tickedByronLedgerState return @@ -462,7 +462,7 @@ encodeByronAnnTip = encodeAnnTipIsEBB encodeByronHeaderHash decodeByronAnnTip :: Decoder s (AnnTip ByronBlock) decodeByronAnnTip = decodeAnnTipIsEBB decodeByronHeaderHash -encodeByronExtLedgerState :: ExtLedgerState ByronBlock -> Encoding +encodeByronExtLedgerState :: ExtLedgerState ByronBlock mk -> Encoding encodeByronExtLedgerState = encodeExtLedgerState encodeByronLedgerState @@ -529,7 +529,7 @@ decodeByronTransition = do bno <- decode return (Update.ProtocolVersion{pvMajor, pvMinor, pvAlt}, bno) -encodeByronLedgerState :: LedgerState ByronBlock -> Encoding +encodeByronLedgerState :: LedgerState ByronBlock mk -> Encoding encodeByronLedgerState ByronLedgerState{..} = mconcat [ encodeListLen 3 @@ -538,7 +538,7 @@ encodeByronLedgerState ByronLedgerState{..} = , encodeByronTransition byronLedgerTransition ] -decodeByronLedgerState :: Decoder s (LedgerState ByronBlock) +decodeByronLedgerState :: Decoder s (LedgerState ByronBlock mk) decodeByronLedgerState = do enforceSize "ByronLedgerState" 3 ByronLedgerState diff --git a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Mempool.hs b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Mempool.hs index 6e4378f8d0..7156599ee4 100644 --- a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Mempool.hs +++ b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Ledger/Mempool.hs @@ -305,8 +305,8 @@ applyByronGenTx :: LedgerConfig ByronBlock -> SlotNo -> GenTx ByronBlock -> - TickedLedgerState ByronBlock -> - Except (ApplyTxErr ByronBlock) (TickedLedgerState ByronBlock) + TickedLedgerState ByronBlock mk1 -> + Except (ApplyTxErr ByronBlock) (TickedLedgerState ByronBlock mk2) applyByronGenTx validationMode cfg slot genTx st = (\state -> st{tickedByronLedgerState = state}) <$> CC.applyMempoolPayload diff --git a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Node/Serialisation.hs b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Node/Serialisation.hs index e4574f6cee..f9a9d48380 100644 --- a/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Node/Serialisation.hs +++ b/ouroboros-consensus-cardano/src/byron/Ouroboros/Consensus/Byron/Node/Serialisation.hs @@ -53,9 +53,9 @@ instance EncodeDisk ByronBlock ByronBlock where instance DecodeDisk ByronBlock (Lazy.ByteString -> Either DecoderError ByronBlock) where decodeDisk ccfg = (Right .) <$> decodeByronBlock (getByronEpochSlots ccfg) -instance EncodeDisk ByronBlock (LedgerState ByronBlock) where +instance EncodeDisk ByronBlock (LedgerState ByronBlock mk) where encodeDisk _ = encodeByronLedgerState -instance DecodeDisk ByronBlock (LedgerState ByronBlock) where +instance DecodeDisk ByronBlock (LedgerState ByronBlock mk) where decodeDisk _ = decodeByronLedgerState -- | @'ChainDepState' ('BlockProtocol' 'ByronBlock')@ diff --git a/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Block.hs b/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Block.hs index a8a22f13f4..731251f42b 100644 --- a/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Block.hs +++ b/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Block.hs @@ -209,6 +209,7 @@ module Ouroboros.Consensus.Cardano.Block import Data.Kind import Data.SOP.BasicFunctors +import Data.SOP.Functors (Flip (..)) import Data.SOP.Strict import Ouroboros.Consensus.Block (BlockProtocol) import Ouroboros.Consensus.Byron.Ledger.Block (ByronBlock) @@ -219,7 +220,7 @@ import Ouroboros.Consensus.HeaderValidation ( OtherHeaderEnvelopeError , TipInfo ) -import Ouroboros.Consensus.Ledger.Abstract (LedgerError) +import Ouroboros.Consensus.Ledger.Abstract (EmptyMK, LedgerError) import Ouroboros.Consensus.Ledger.Query import Ouroboros.Consensus.Ledger.SupportsMempool ( ApplyTxErr @@ -1337,78 +1338,78 @@ pattern CardanoLedgerConfig cfgByron cfgShelley cfgAllegra cfgMary cfgAlonzo cfg -- 'LedgerState'. We don't give access to those internal details through the -- pattern synonyms. This is also the reason the pattern synonyms are not -- bidirectional. -type CardanoLedgerState c = LedgerState (CardanoBlock c) +type CardanoLedgerState c mk = LedgerState (CardanoBlock c) mk pattern LedgerStateByron :: - LedgerState ByronBlock -> - CardanoLedgerState c + LedgerState ByronBlock EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateByron st <- HardForkLedgerState ( State.HardForkState - (TeleByron (State.Current{currentState = st})) + (TeleByron (State.Current{currentState = Flip st})) ) pattern LedgerStateShelley :: - LedgerState (ShelleyBlock (TPraos c) ShelleyEra) -> - CardanoLedgerState c + LedgerState (ShelleyBlock (TPraos c) ShelleyEra) EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateShelley st <- HardForkLedgerState ( State.HardForkState - (TeleShelley _ (State.Current{currentState = st})) + (TeleShelley _ (State.Current{currentState = Flip st})) ) pattern LedgerStateAllegra :: - LedgerState (ShelleyBlock (TPraos c) AllegraEra) -> - CardanoLedgerState c + LedgerState (ShelleyBlock (TPraos c) AllegraEra) EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateAllegra st <- HardForkLedgerState ( State.HardForkState - (TeleAllegra _ _ (State.Current{currentState = st})) + (TeleAllegra _ _ (State.Current{currentState = Flip st})) ) pattern LedgerStateMary :: - LedgerState (ShelleyBlock (TPraos c) MaryEra) -> - CardanoLedgerState c + LedgerState (ShelleyBlock (TPraos c) MaryEra) EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateMary st <- HardForkLedgerState ( State.HardForkState - (TeleMary _ _ _ (State.Current{currentState = st})) + (TeleMary _ _ _ (State.Current{currentState = Flip st})) ) pattern LedgerStateAlonzo :: - LedgerState (ShelleyBlock (TPraos c) AlonzoEra) -> - CardanoLedgerState c + LedgerState (ShelleyBlock (TPraos c) AlonzoEra) EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateAlonzo st <- HardForkLedgerState ( State.HardForkState - (TeleAlonzo _ _ _ _ (State.Current{currentState = st})) + (TeleAlonzo _ _ _ _ (State.Current{currentState = Flip st})) ) pattern LedgerStateBabbage :: - LedgerState (ShelleyBlock (Praos c) BabbageEra) -> - CardanoLedgerState c + LedgerState (ShelleyBlock (Praos c) BabbageEra) EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateBabbage st <- HardForkLedgerState ( State.HardForkState - (TeleBabbage _ _ _ _ _ (State.Current{currentState = st})) + (TeleBabbage _ _ _ _ _ (State.Current{currentState = Flip st})) ) pattern LedgerStateConway :: - LedgerState (ShelleyBlock (Praos c) ConwayEra) -> - CardanoLedgerState c + LedgerState (ShelleyBlock (Praos c) ConwayEra) EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateConway st <- HardForkLedgerState ( State.HardForkState - (TeleConway _ _ _ _ _ _ (State.Current{currentState = st})) + (TeleConway _ _ _ _ _ _ (State.Current{currentState = Flip st})) ) pattern LedgerStateDijkstra :: - LedgerState (ShelleyBlock (Praos c) DijkstraEra) -> - CardanoLedgerState c + LedgerState (ShelleyBlock (Praos c) DijkstraEra) EmptyMK -> + CardanoLedgerState c EmptyMK pattern LedgerStateDijkstra st <- HardForkLedgerState ( State.HardForkState - (TeleDijkstra _ _ _ _ _ _ _ (State.Current{currentState = st})) + (TeleDijkstra _ _ _ _ _ _ _ (State.Current{currentState = Flip st})) ) {-# COMPLETE diff --git a/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/CanHardFork.hs b/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/CanHardFork.hs index 475eb41ab9..6a4de95ea5 100644 --- a/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/CanHardFork.hs +++ b/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/CanHardFork.hs @@ -56,6 +56,7 @@ import qualified Data.Map.Strict as Map import Data.Maybe.Strict (StrictMaybe (..)) import Data.Proxy import Data.SOP.BasicFunctors +import Data.SOP.Functors (Flip (..)) import Data.SOP.InPairs (RequiringBoth (..), ignoringBoth) import qualified Data.SOP.Strict as SOP import Data.SOP.Tails (Tails (..)) @@ -383,6 +384,7 @@ translateLedgerStateByronToShelleyWrapper = , shelleyLedgerStateNoUTxO = stateNoUTxO , shelleyLedgerTransition = ShelleyTransitionInfo{shelleyAfterVoting = 0} + , shelleyLedgerTables = emptyLedgerTables , shelleyLedgerLatestPerasCertRound = SNothing } , Diff.fromMapInserts utxo @@ -455,7 +457,7 @@ crossEraForecastByronToShelleyWrapper = ShelleyLedgerConfig ShelleyEra -> Bound -> SlotNo -> - LedgerState ByronBlock -> + LedgerState ByronBlock mk -> Except OutsideForecastRange (WrapLedgerView (ShelleyBlock (TPraos c) ShelleyEra)) @@ -535,9 +537,11 @@ translateLedgerStateShelleyToAllegraWrapper = -- The remaining (UTxO-free) ledger-state fields translate -- normally; we override the NES with the AVVM-consumed one above. lsAllegra = - unComp + unFlip + . unComp . SL.translateEra' SL.NoGenesis . Comp + . Flip $ ls in ( lsAllegra{shelleyLedgerStateNoUTxO = stateNoUTxO} , avvmsAsDeletions @@ -587,7 +591,7 @@ translateLedgerStateAllegraToMaryWrapper = -- A pure-upgrade boundary: the state translates with no new diffs. -- The per-era 'TxOut' upgrade of the on-disk values is handled by -- 'translateValues' when the first block's values are read. - (unComp . SL.translateEra' SL.NoGenesis . Comp $ ls, mempty) + (unFlip . unComp . SL.translateEra' SL.NoGenesis . Comp . Flip $ ls, mempty) } translateLedgerTablesAllegraToMaryWrapper :: @@ -630,7 +634,7 @@ translateLedgerStateMaryToAlonzoWrapper = RequireBoth $ \_cfgMary cfgAlonzo -> TranslateLedgerState { translateLedgerStateWith = \_epochNo ls -> - ( unComp . SL.translateEra' (getAlonzoTranslationContext cfgAlonzo) . Comp $ ls + ( unFlip . unComp . SL.translateEra' (getAlonzoTranslationContext cfgAlonzo) . Comp . Flip $ ls , mempty ) } @@ -684,19 +688,20 @@ translateLedgerStateAlonzoToBabbageWrapper = RequireBoth $ \_cfgAlonzo _cfgBabbage -> TranslateLedgerState { translateLedgerStateWith = \_epochNo ls -> - ( unComp . SL.translateEra' SL.NoGenesis . Comp . transPraosLS $ ls + ( unFlip . unComp . SL.translateEra' SL.NoGenesis . Comp . Flip . transPraosLS $ ls , mempty ) } where transPraosLS :: - LedgerState (ShelleyBlock (TPraos c) AlonzoEra) -> - LedgerState (ShelleyBlock (Praos c) AlonzoEra) - transPraosLS (ShelleyLedgerState wo nes st lcr) = + LedgerState (ShelleyBlock (TPraos c) AlonzoEra) EmptyMK -> + LedgerState (ShelleyBlock (Praos c) AlonzoEra) EmptyMK + transPraosLS (ShelleyLedgerState wo nes st _tb lcr) = ShelleyLedgerState { shelleyLedgerTip = fmap castShelleyTip wo , shelleyLedgerStateNoUTxO = nes , shelleyLedgerTransition = st + , shelleyLedgerTables = emptyLedgerTables , shelleyLedgerLatestPerasCertRound = lcr } @@ -761,7 +766,7 @@ translateLedgerStateBabbageToConwayWrapper = RequireBoth $ \_cfgBabbage cfgConway -> TranslateLedgerState { translateLedgerStateWith = \_epochNo ls -> - ( unComp . SL.translateEra' (getConwayTranslationContext cfgConway) . Comp $ ls + ( unFlip . unComp . SL.translateEra' (getConwayTranslationContext cfgConway) . Comp . Flip $ ls , mempty ) } @@ -815,7 +820,7 @@ translateLedgerStateConwayToDijkstraWrapper = RequireBoth $ \_cfgConway cfgDijkstra -> TranslateLedgerState { translateLedgerStateWith = \_epochNo ls -> - ( unComp . SL.translateEra' (getDijkstraTranslationContext cfgDijkstra) . Comp $ ls + ( unFlip . unComp . SL.translateEra' (getDijkstraTranslationContext cfgDijkstra) . Comp . Flip $ ls , mempty ) } diff --git a/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Node.hs b/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Node.hs index f0a3898587..31ec562563 100644 --- a/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Node.hs +++ b/ouroboros-consensus-cardano/src/ouroboros-consensus-cardano/Ouroboros/Consensus/Cardano/Node.hs @@ -63,6 +63,7 @@ import Data.Functor.These (These1 (..)) import qualified Data.Map.Strict as Map import Data.SOP.BasicFunctors import Data.SOP.Counting +import Data.SOP.Functors (Flip (..)) import Data.SOP.Index import Data.SOP.OptNP (NonEmptyOptNP, OptNP (OptSkip)) import qualified Data.SOP.OptNP as OptNP @@ -86,7 +87,7 @@ import Ouroboros.Consensus.HardFork.Combinator.Serialisation import qualified Ouroboros.Consensus.HardFork.Combinator.State as State import qualified Ouroboros.Consensus.HardFork.History as History import Ouroboros.Consensus.HeaderValidation -import Ouroboros.Consensus.Ledger.Basics (Values) +import Ouroboros.Consensus.Ledger.Basics (EmptyMK, Values) import Ouroboros.Consensus.Ledger.Extended import Ouroboros.Consensus.Node.NetworkProtocolVersion import Ouroboros.Consensus.Node.ProtocolInfo @@ -943,7 +944,7 @@ protocolInfoCardano (SomeHasFS hasFS) paramsCardano -- The initial 'ExtLedgerState' and the genesis 'Values' fed to the LedgerDB. -- Monadic because the per-era genesis-funds injection ('injectIntoTestState') -- takes the snapshot fs, as in prepare-11.1. - mkInitGenesis :: m (ExtLedgerState (CardanoBlock c), Values (CardanoBlock c)) + mkInitGenesis :: m (ExtLedgerState (CardanoBlock c) EmptyMK, Values (CardanoBlock c)) mkInitGenesis = do -- Inject the genesis config's initial funds/staking (testing/benchmarking) -- into whichever era we landed in, threading the new entries alongside the @@ -968,7 +969,7 @@ protocolInfoCardano (SomeHasFS hasFS) paramsCardano -- hard fork) together with the genesis values that extension produced (e.g. -- the Byron->Shelley UTxO dump). See 'injectInitialExtLedgerState'. initHeaderState :: HeaderState (CardanoBlock c) - initState :: HardForkState LedgerState (CardanoEras c) + initState :: HardForkState (Flip LedgerState EmptyMK) (CardanoEras c) genesisValues :: Values (CardanoBlock c) ( ExtLedgerState (HardForkLedgerState initState) initHeaderState , genesisValues @@ -977,7 +978,9 @@ protocolInfoCardano (SomeHasFS hasFS) paramsCardano registerAny :: NP - (Product WrapValues LedgerState -.-> (m :.: Product WrapValues LedgerState)) + ( Product WrapValues (Flip LedgerState EmptyMK) + -.-> (m :.: Product WrapValues (Flip LedgerState EmptyMK)) + ) (CardanoShelleyEras c) registerAny = hcmap (Proxy @IsShelleyBlock) injectIntoTestState $ @@ -993,10 +996,12 @@ protocolInfoCardano (SomeHasFS hasFS) paramsCardano injectIntoTestState :: ShelleyBasedEra era => WrapTransitionConfig (ShelleyBlock proto era) -> - (Product WrapValues LedgerState -.-> (m :.: Product WrapValues LedgerState)) + ( Product WrapValues (Flip LedgerState EmptyMK) + -.-> (m :.: Product WrapValues (Flip LedgerState EmptyMK)) + ) (ShelleyBlock proto era) injectIntoTestState (WrapTransitionConfig tcfg) = - fn $ \(Pair (WrapValues vals) st) -> Comp $ do + fn $ \(Pair (WrapValues vals) (Flip st)) -> Comp $ do -- Stow the genesis values into the (empty) UTxO field so the ledger's -- 'injectIntoTestState' adds the config's funds on top, then split the -- combined UTxO back out (the state is stored UTxO-free). @@ -1009,7 +1014,7 @@ protocolInfoCardano (SomeHasFS hasFS) paramsCardano pure $ Pair (WrapValues valsAll) - (st{Shelley.shelleyLedgerStateNoUTxO = stateNoUTxO}) + (Flip st{Shelley.shelleyLedgerStateNoUTxO = stateNoUTxO}) -- \| For each element in the list, a block forging thread will be started. -- diff --git a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Forge.hs b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Forge.hs index 00f2390d2e..a0d6ea402b 100644 --- a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Forge.hs +++ b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Forge.hs @@ -40,7 +40,7 @@ import Ouroboros.Consensus.Shelley.Protocol.Abstract -------------------------------------------------------------------------------} forgeShelleyBlock :: - forall m era proto. + forall m era proto mk. (ShelleyCompatible proto era, Monad m) => HotKey (ProtoCrypto proto) m -> CanBeLeader proto -> @@ -50,7 +50,7 @@ forgeShelleyBlock :: -- | Current slot number SlotNo -> -- | Current ledger - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> -- | Txs to include [Validated (GenTx (ShelleyBlock proto era))] -> IsLeader proto -> diff --git a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Inspect.hs b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Inspect.hs index 1d2a6fc70f..53fa56f011 100644 --- a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Inspect.hs +++ b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Inspect.hs @@ -55,9 +55,9 @@ instance ShelleyBasedEra era => InspectLedger (ShelleyBlock proto era) where updatesAfter = pparamsUpdate after pparamsUpdate :: - forall era proto. + forall era proto mk. ShelleyBasedEra era => - LedgerState (ShelleyBlock proto era) -> + LedgerState (ShelleyBlock proto era) mk -> ShelleyLedgerUpdate era pparamsUpdate st = let nes = shelleyLedgerState st diff --git a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Ledger.hs b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Ledger.hs index 83c6eda022..19e6e3e221 100644 --- a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Ledger.hs +++ b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Ledger.hs @@ -295,13 +295,14 @@ castShelleyTip (ShelleyTip sn bn hh) = -- 'SL.NewEpochState' has a UTxO field which we hold empty here (the entries live -- in the backend); 'applyBlockLedgerResultWithValidation' injects the read -- values, runs the ledger rules, and extracts the resulting diff. -data instance LedgerState (ShelleyBlock proto era) = ShelleyLedgerState +data instance LedgerState (ShelleyBlock proto era) mk = ShelleyLedgerState { shelleyLedgerTip :: !(WithOrigin (ShelleyTip proto era)) , shelleyLedgerStateNoUTxO :: !(NewEpochStateNoUTxOs era) -- ^ The new-epoch state with its UTxO field held empty; the UTxO lives in -- the backend (see 'Ouroboros.Consensus.Shelley.Ledger.LedgerCallShim'). Use -- the 'shelleyLedgerState' accessor for the (UTxO-free) 'SL.NewEpochState'. , shelleyLedgerTransition :: !ShelleyTransition + , shelleyLedgerTables :: !(LedgerTables (ShelleyBlock proto era) mk) , shelleyLedgerLatestPerasCertRound :: !(StrictMaybe PerasRoundNo) } deriving Generic @@ -314,7 +315,7 @@ data instance LedgerState (ShelleyBlock proto era) = ShelleyLedgerState -- read the UTxO, go through the LedgerDB forker \/ ledger tables. See -- 'newEpochStateWithEmptyUTxO'. shelleyLedgerState :: - LedgerState (ShelleyBlock proto era) -> SL.NewEpochState era + LedgerState (ShelleyBlock proto era) mk -> SL.NewEpochState era shelleyLedgerState = newEpochStateWithEmptyUTxO . shelleyLedgerStateNoUTxO #if __GLASGOW_HASKELL__ >= 910 @@ -324,14 +325,37 @@ shelleyLedgerState = newEpochStateWithEmptyUTxO . shelleyLedgerStateNoUTxO #endif deriving instance - ShelleyBasedEra era => - Eq (LedgerState (ShelleyBlock proto era)) + (ShelleyBasedEra era, Eq (LedgerTables (ShelleyBlock proto era) mk)) => + Eq (LedgerState (ShelleyBlock proto era) mk) deriving instance - ShelleyBasedEra era => - NoThunks (LedgerState (ShelleyBlock proto era)) + (ShelleyBasedEra era, NoThunks (LedgerTables (ShelleyBlock proto era) mk)) => + NoThunks (LedgerState (ShelleyBlock proto era) mk) deriving instance - ShelleyBasedEra era => - Show (LedgerState (ShelleyBlock proto era)) + (ShelleyBasedEra era, Show (LedgerTables (ShelleyBlock proto era) mk)) => + Show (LedgerState (ShelleyBlock proto era) mk) + +-- | The skin's 'LedgerTables' wrapper and its map-kind payloads carry no +-- derived instances (@main@ derives them via the @EqMK@\/@ShowMK@\/@NoThunksMK@ +-- machinery, which the single-arg skin cannot reproduce). The Shelley ledger +-- state holds a 'LedgerTables' field, so we provide the (transparent) instances +-- it needs at the map-kinds that actually appear in a Shelley state value +-- position — i.e. 'EmptyMK', the live UTxO being threaded externally as the +-- @'Values'@\/@'Diff'@ of 'BlockSupportsUTxOHD'. +deriving newtype instance + Eq (mk (ShelleyBlock proto era)) => + Eq (LedgerTables (ShelleyBlock proto era) mk) +deriving newtype instance + Show (mk (ShelleyBlock proto era)) => + Show (LedgerTables (ShelleyBlock proto era) mk) +deriving newtype instance + NoThunks (mk (ShelleyBlock proto era)) => + NoThunks (LedgerTables (ShelleyBlock proto era) mk) + +deriving stock instance Eq (EmptyMK (ShelleyBlock proto era)) +deriving stock instance Show (EmptyMK (ShelleyBlock proto era)) +instance NoThunks (EmptyMK (ShelleyBlock proto era)) where + showTypeOf _ = "EmptyMK" + wNoThunks _ EmptyMK = return Nothing -- | Information required to determine the hard fork point from Shelley to the -- next ledger @@ -359,7 +383,7 @@ newtype ShelleyTransition = ShelleyTransitionInfo deriving newtype NoThunks shelleyLedgerTipPoint :: - LedgerState (ShelleyBlock proto era) -> + LedgerState (ShelleyBlock proto era) mk -> Point (ShelleyBlock proto era) shelleyLedgerTipPoint = shelleyTipToPoint . shelleyLedgerTip @@ -486,7 +510,7 @@ instance GetTip (Ticked LedgerState (ShelleyBlock proto era)) where -------------------------------------------------------------------------------} -- | Ticking only affects the state itself -data instance Ticked LedgerState (ShelleyBlock proto era) = TickedShelleyLedgerState +data instance Ticked LedgerState (ShelleyBlock proto era) mk = TickedShelleyLedgerState { untickedShelleyLedgerTip :: !(WithOrigin (ShelleyTip proto era)) , tickedShelleyLedgerTransition :: !ShelleyTransition -- ^ We are counting blocks within an epoch, this means: @@ -497,6 +521,7 @@ data instance Ticked LedgerState (ShelleyBlock proto era) = TickedShelleyLedgerS , tickedShelleyLedgerStateNoUTxO :: !(NewEpochStateNoUTxOs era) -- ^ Like 'shelleyLedgerStateNoUTxO': the UTxO field is held empty. Use the -- 'tickedShelleyLedgerState' accessor for the (UTxO-free) 'SL.NewEpochState'. + , tickedShelleyLedgerTables :: !(LedgerTables (ShelleyBlock proto era) mk) , tickedShelleyLedgerLatestPerasCertRound :: !(StrictMaybe PerasRoundNo) } deriving Generic @@ -506,7 +531,7 @@ data instance Ticked LedgerState (ShelleyBlock proto era) = TickedShelleyLedgerS -- ⚠️ Its UTxO field is EMPTY by design (see 'shelleyLedgerState'): the live -- UTxO lives in the ledger tables, not the state. tickedShelleyLedgerState :: - Ticked LedgerState (ShelleyBlock proto era) -> SL.NewEpochState era + Ticked LedgerState (ShelleyBlock proto era) mk -> SL.NewEpochState era tickedShelleyLedgerState = newEpochStateWithEmptyUTxO . tickedShelleyLedgerStateNoUTxO #if __GLASGOW_HASKELL__ >= 910 @@ -516,7 +541,7 @@ tickedShelleyLedgerState = newEpochStateWithEmptyUTxO . tickedShelleyLedgerState #endif untickedShelleyLedgerTipPoint :: - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> Point (ShelleyBlock proto era) untickedShelleyLedgerTipPoint = shelleyTipToPoint . untickedShelleyLedgerTip @@ -547,6 +572,7 @@ instance ShelleyCompatible proto era => IsLedger LedgerState (ShelleyBlock proto then ShelleyTransitionInfo{shelleyAfterVoting = 0} else shelleyLedgerTransition , tickedShelleyLedgerStateNoUTxO = tickedNoUTxO + , tickedShelleyLedgerTables = emptyLedgerTables , tickedShelleyLedgerLatestPerasCertRound = shelleyLedgerLatestPerasCertRound } @@ -609,12 +635,12 @@ applyHelper :: LedgerConfig (ShelleyBlock proto era) -> ShelleyBlock proto era -> Values (ShelleyBlock proto era) -> - Ticked LedgerState (ShelleyBlock proto era) -> + Ticked LedgerState (ShelleyBlock proto era) EmptyMK -> Either (SL.BlockTransitionError era) ( LedgerResult (ShelleyBlock proto era) - (LedgerState (ShelleyBlock proto era), Diff (ShelleyBlock proto era)) + (LedgerState (ShelleyBlock proto era) EmptyMK, Diff (ShelleyBlock proto era)) ) applyHelper evs doValidate cfg blk values stBefore = do let TickedShelleyLedgerState @@ -649,6 +675,7 @@ applyHelper evs doValidate cfg blk values stBefore = do (if blockSlot blk >= votingDeadline then succ else id) $ shelleyAfterVoting tickedShelleyLedgerTransition } + , shelleyLedgerTables = emptyLedgerTables , shelleyLedgerLatestPerasCertRound = shelleyLedgerLatestPerasCertRound' } @@ -798,7 +825,7 @@ decodeShelleyTransition = do encodeShelleyLedgerState :: ShelleyCompatible proto era => - LedgerState (ShelleyBlock proto era) -> + LedgerState (ShelleyBlock proto era) EmptyMK -> Encoding encodeShelleyLedgerState ShelleyLedgerState @@ -819,13 +846,13 @@ encodeShelleyLedgerState decodeShelleyLedgerState :: forall era proto s. ShelleyCompatible proto era => - Decoder s (LedgerState (ShelleyBlock proto era)) + Decoder s (LedgerState (ShelleyBlock proto era) EmptyMK) decodeShelleyLedgerState = decodeVersion [ (serialisationFormatVersion2, Decode decodeShelleyLedgerState2) ] where - decodeShelleyLedgerState2 :: Decoder s' (LedgerState (ShelleyBlock proto era)) + decodeShelleyLedgerState2 :: Decoder s' (LedgerState (ShelleyBlock proto era) EmptyMK) decodeShelleyLedgerState2 = do enforceSize "ShelleyLedgerState" 4 shelleyLedgerTip <- decodeWithOrigin decodeShelleyTip @@ -839,6 +866,7 @@ decodeShelleyLedgerState = { shelleyLedgerTip , shelleyLedgerStateNoUTxO , shelleyLedgerTransition + , shelleyLedgerTables = emptyLedgerTables , shelleyLedgerLatestPerasCertRound } diff --git a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Mempool.hs b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Mempool.hs index 1a24051a50..ffcbfa1052 100644 --- a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Mempool.hs +++ b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Ledger/Mempool.hs @@ -296,10 +296,10 @@ applyShelleyTx :: SlotNo -> GenTx (ShelleyBlock proto era) -> Values (ShelleyBlock proto era) -> - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) EmptyMK -> Except (ApplyTxErr (ShelleyBlock proto era)) - ( TickedLedgerState (ShelleyBlock proto era) + ( TickedLedgerState (ShelleyBlock proto era) EmptyMK , Diff (ShelleyBlock proto era) , Validated (GenTx (ShelleyBlock proto era)) ) @@ -325,10 +325,10 @@ reapplyShelleyTx :: SlotNo -> Validated (GenTx (ShelleyBlock proto era)) -> Values (ShelleyBlock proto era) -> - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) EmptyMK -> Except (ApplyTxErr (ShelleyBlock proto era)) - ( TickedLedgerState (ShelleyBlock proto era) + ( TickedLedgerState (ShelleyBlock proto era) EmptyMK , Diff (ShelleyBlock proto era) ) reapplyShelleyTx cfg slot vgtx values st0 = do @@ -368,7 +368,7 @@ runValidation = liftEither . (unTxErrorSG +++ id) . view V.either txsMaxBytes :: ShelleyCompatible proto era => - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> IgnoringOverflow ByteSize32 txsMaxBytes st = -- `maxBlockBodySize` is expected to be bigger than `fixedBlockBodyOverhead` @@ -380,7 +380,7 @@ txsMaxBytes st = txInBlockSize :: (ShelleyCompatible proto era, MaxTxSizeUTxO era) => - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> GenTx (ShelleyBlock proto era) -> V.Validation (TxErrorSG era) (IgnoringOverflow ByteSize32) txInBlockSize st (ShelleyTx _txid tx') = @@ -554,9 +554,9 @@ fromExUnits :: ExUnits -> ExUnits' Natural fromExUnits = unWrapExUnits blockCapacityAlonzoMeasure :: - forall proto era. + forall proto era mk. (ShelleyCompatible proto era, L.AlonzoEraPParams era) => - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> AlonzoMeasure blockCapacityAlonzoMeasure ledgerState = AlonzoMeasure @@ -567,14 +567,14 @@ blockCapacityAlonzoMeasure ledgerState = pparams = getPParams $ tickedShelleyLedgerState ledgerState txMeasureAlonzo :: - forall proto era. + forall proto era mk. ( ShelleyCompatible proto era , L.AlonzoEraPParams era , L.AlonzoEraTxWits era , ExUnitsTooBigUTxO era , MaxTxSizeUTxO era ) => - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> GenTx (ShelleyBlock proto era) -> V.Validation (TxErrorSG era) AlonzoMeasure txMeasureAlonzo st tx@(ShelleyTx _txid tx') = @@ -665,11 +665,11 @@ instance TxMeasurePhase2Metrics RefScriptSize where txMeasureMetricRefScriptsSizeBytes = unIgnoringOverflow . refScriptsSize blockCapacityConwayMeasure :: - forall proto era. + forall proto era mk. ( ShelleyCompatible proto era , SL.ConwayEraPParams era ) => - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> (AlonzoMeasure, RefScriptSize) blockCapacityConwayMeasure st = ( blockCapacityAlonzoMeasure st @@ -681,14 +681,14 @@ blockCapacityConwayMeasure st = pparams = getPParams $ tickedShelleyLedgerState st txMeasureRefScripts :: - forall proto era. + forall proto era mk. ( ShelleyCompatible proto era , L.BabbageEraTxBody era , TxRefScriptsSizeTooBig era , SL.ConwayEraPParams era ) => Values (ShelleyBlock proto era) -> - TickedLedgerState (ShelleyBlock proto era) -> + TickedLedgerState (ShelleyBlock proto era) mk -> GenTx (ShelleyBlock proto era) -> V.Validation (TxErrorSG era) RefScriptSize txMeasureRefScripts values st (ShelleyTx _txid tx') = diff --git a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/Serialisation.hs b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/Serialisation.hs index 6d71822ab5..3b6a0ce572 100644 --- a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/Serialisation.hs +++ b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/Serialisation.hs @@ -34,6 +34,7 @@ import Ouroboros.Consensus.HardFork.Combinator.PartialConfig import Ouroboros.Consensus.HardFork.History.EpochInfo import Ouroboros.Consensus.HardFork.Simple import Ouroboros.Consensus.HeaderValidation +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Ouroboros.Consensus.Ledger.Query import Ouroboros.Consensus.Ledger.SupportsMempool (GenTxId) import Ouroboros.Consensus.Ledger.SupportsProtocol @@ -86,12 +87,12 @@ instance instance ShelleyCompatible proto era => - EncodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era)) + EncodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era) EmptyMK) where encodeDisk _ = encodeShelleyLedgerState instance ShelleyCompatible proto era => - DecodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era)) + DecodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era) EmptyMK) where decodeDisk _ = decodeShelleyLedgerState diff --git a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/TPraos.hs b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/TPraos.hs index 04df2c9858..ec4a93fc21 100644 --- a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/TPraos.hs +++ b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/Node/TPraos.hs @@ -216,6 +216,7 @@ protocolInfoTPraosShelleyBased { shelleyLedgerTip = Origin , shelleyLedgerStateNoUTxO = genesisStateNoUTxO , shelleyLedgerTransition = ShelleyTransitionInfo{shelleyAfterVoting = 0} + , shelleyLedgerTables = emptyLedgerTables , shelleyLedgerLatestPerasCertRound = SNothing } initExtLedgerState = diff --git a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/ShelleyHFC.hs b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/ShelleyHFC.hs index be0adf5d18..0244307f6d 100644 --- a/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/ShelleyHFC.hs +++ b/ouroboros-consensus-cardano/src/shelley/Ouroboros/Consensus/Shelley/ShelleyHFC.hs @@ -43,6 +43,7 @@ import Control.Monad.Except (runExcept, throwError) import Data.Coerce import qualified Data.Map.Strict as Map import Data.SOP.BasicFunctors +import Data.SOP.Functors (Flip (..)) import Data.SOP.InPairs (RequiringBoth (..), ignoringBoth) import Data.SOP.Index (Index (..)) import Data.SOP.Strict @@ -180,12 +181,12 @@ type ProtocolShelley = HardForkProtocol '[ShelleyBlock (TPraos StandardCrypto) S -------------------------------------------------------------------------------} shelleyTransition :: - forall era proto. + forall era proto mk. ShelleyCompatible proto era => PartialLedgerConfig (ShelleyBlock proto era) -> -- | Next era's initial major protocol version Word16 -> - LedgerState (ShelleyBlock proto era) -> + LedgerState (ShelleyBlock proto era) mk -> Maybe EpochNo shelleyTransition ShelleyPartialLedgerConfig{..} @@ -298,7 +299,7 @@ forecastAcrossShelley :: Bound -> -- | Forecast for this slot SlotNo -> - LedgerState (ShelleyBlock protoFrom eraFrom) -> + LedgerState (ShelleyBlock protoFrom eraFrom) EmptyMK -> Except OutsideForecastRange (WrapLedgerView (ShelleyBlock protoTo eraTo)) forecastAcrossShelley cfgFrom cfgTo transition forecastFor ledgerStateFrom | forecastFor < maxFor = @@ -352,10 +353,10 @@ instance , SL.TranslateEra era SL.NewEpochState , SL.TranslationError era SL.NewEpochState ~ Void ) => - SL.TranslateEra era (LedgerState :.: ShelleyBlock proto) + SL.TranslateEra era (Flip LedgerState EmptyMK :.: ShelleyBlock proto) where - translateEra ctxt (Comp st) = do - let ShelleyLedgerState tip stateNoUTxO _transition latestPerasCertRound = st + translateEra ctxt (Comp (Flip st)) = do + let ShelleyLedgerState tip stateNoUTxO _transition _tables latestPerasCertRound = st tip' <- mapM (SL.translateEra ctxt) tip -- The state's UTxO field is empty (the UTxO lives in the backend); the NES -- translation preserves that, and the value-level UTxO upgrade is handled @@ -363,12 +364,14 @@ instance state' <- SL.translateEra ctxt (newEpochStateWithEmptyUTxO stateNoUTxO) return $ Comp $ - ShelleyLedgerState - { shelleyLedgerTip = tip' - , shelleyLedgerStateNoUTxO = mkNewEpochStateNoUTxOs state' - , shelleyLedgerTransition = ShelleyTransitionInfo 0 - , shelleyLedgerLatestPerasCertRound = latestPerasCertRound - } + Flip $ + ShelleyLedgerState + { shelleyLedgerTip = tip' + , shelleyLedgerStateNoUTxO = mkNewEpochStateNoUTxOs state' + , shelleyLedgerTransition = ShelleyTransitionInfo 0 + , shelleyLedgerTables = emptyLedgerTables + , shelleyLedgerLatestPerasCertRound = latestPerasCertRound + } -- | Translate the on-disk 'Values' (the UTxO) across a Shelley-based era -- transition: the keys ('SL.TxIn') are era-stable, so only the @TxOut@s are diff --git a/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node.hs b/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node.hs index 5df68e11d0..fcf2af9dc1 100644 --- a/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node.hs +++ b/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node.hs @@ -108,7 +108,7 @@ import Ouroboros.Consensus.Block import Ouroboros.Consensus.BlockchainTime hiding (getSystemStart) import Ouroboros.Consensus.Config import Ouroboros.Consensus.Config.SupportsNode -import Ouroboros.Consensus.Ledger.Abstract (Values) +import Ouroboros.Consensus.Ledger.Abstract (EmptyMK, Values) import Ouroboros.Consensus.Ledger.Extended (ExtLedgerState (..)) import qualified Ouroboros.Consensus.Mempool as Mempool import Ouroboros.Consensus.MiniProtocol.ChainSync.Client.HistoricityCheck @@ -850,7 +850,7 @@ openChainDB :: ResourceRegistry m -> TopLevelConfig blk -> -- | Initial ledger (the pure state together with its genesis values) - (ExtLedgerState blk, Values blk) -> + (ExtLedgerState blk EmptyMK, Values blk) -> -- | Immutable FS, see 'NodeDatabasePaths' (ChainDB.RelativeMountPoint -> SomeHasFS m) -> -- | Volatile FS, see 'NodeDatabasePaths' diff --git a/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node/GSM.hs b/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node/GSM.hs index f54ccb56a3..d09ab18934 100644 --- a/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node/GSM.hs +++ b/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/Node/GSM.hs @@ -176,7 +176,7 @@ initializationGsmState :: ( L.GetTip (L.LedgerState blk) , Monad m ) => - m (L.LedgerState blk) -> + m (L.LedgerState blk L.EmptyMK) -> -- | 'Nothing' if @blk@ has no age limit Maybe (WrapDurationUntilTooOld m blk) -> MarkerFileView m -> @@ -463,7 +463,7 @@ realDurationUntilTooOld :: , MonadSTM m ) => L.LedgerConfig blk -> - STM m (L.LedgerState blk) -> + STM m (L.LedgerState blk L.EmptyMK) -> -- | If the volatile tip is older than this, then the node will exit the -- @CaughtUp@ state. -- diff --git a/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/NodeKernel.hs b/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/NodeKernel.hs index 591a3956a2..355201342f 100644 --- a/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/NodeKernel.hs +++ b/ouroboros-consensus-diffusion/src/ouroboros-consensus-diffusion/Ouroboros/Consensus/NodeKernel.hs @@ -975,7 +975,7 @@ getMempoolWriter mempool = getPeersFromCurrentLedger :: (IOLike m, LedgerSupportsPeerSelection blk) => NodeKernel m addrNTN addrNTC blk -> - (LedgerState blk -> Bool) -> + (LedgerState blk EmptyMK -> Bool) -> STM m (Maybe [(PoolStake, NonEmpty LedgerRelayAccessPoint)]) getPeersFromCurrentLedger kernel p = do immutableLedger <- @@ -1001,7 +1001,7 @@ getPeersFromCurrentLedgerAfterSlot :: getPeersFromCurrentLedgerAfterSlot kernel slotNo = getPeersFromCurrentLedger kernel afterSlotNo where - afterSlotNo :: LedgerState blk -> Bool + afterSlotNo :: LedgerState blk mk -> Bool afterSlotNo st = case ledgerTipSlot st of Origin -> False diff --git a/ouroboros-consensus/src/ouroboros-consensus-lsm/Ouroboros/Consensus/Storage/LedgerDB/V2/LSM.hs b/ouroboros-consensus/src/ouroboros-consensus-lsm/Ouroboros/Consensus/Storage/LedgerDB/V2/LSM.hs index d80e4ea6cc..67338abbe3 100644 --- a/ouroboros-consensus/src/ouroboros-consensus-lsm/Ouroboros/Consensus/Storage/LedgerDB/V2/LSM.hs +++ b/ouroboros-consensus/src/ouroboros-consensus-lsm/Ouroboros/Consensus/Storage/LedgerDB/V2/LSM.hs @@ -415,7 +415,7 @@ implRead :: ) => Tracer m LedgerDBV2Trace -> UTxOTable m -> - l blk -> + l blk EmptyMK -> Keys blk -> m (Values blk) implRead tracer t _st keys = @@ -472,7 +472,7 @@ implTakeHandleSnapshot :: Tracer m LedgerDBV2Trace -> (LSM.SnapshotName -> m ()) -> UTxOTable m -> - l blk -> + l blk EmptyMK -> String -> m (Maybe CRC) implTakeHandleSnapshot tracer exportSnapshot t _ snapshotName = do diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Block/Forging.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Block/Forging.hs index cc292c556c..99cb16e2d4 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Block/Forging.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Block/Forging.hs @@ -122,7 +122,7 @@ data BlockForging m blk = BlockForging TopLevelConfig blk -> BlockNo -> -- Current block number SlotNo -> -- Current slot number - TickedLedgerState blk -> -- Current ledger state + TickedLedgerState blk EmptyMK -> -- Current ledger state [Validated (GenTx blk)] -> -- Transactions to include IsLeader (BlockProtocol blk) -> -- Proof we are leader m blk diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/BlockchainTime/WallClock/HardFork.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/BlockchainTime/WallClock/HardFork.hs index bf3f5a4041..1d98cf38c1 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/BlockchainTime/WallClock/HardFork.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/BlockchainTime/WallClock/HardFork.hs @@ -46,7 +46,7 @@ newtype BackoffDelay = BackoffDelay NominalDiffTime data HardForkBlockchainTimeArgs m blk = HardForkBlockchainTimeArgs { hfbtBackoffDelay :: m BackoffDelay -- ^ See 'BackoffDelay' - , hfbtGetLedgerState :: STM m (LedgerState blk) + , hfbtGetLedgerState :: STM m (LedgerState blk EmptyMK) , hfbtLedgerConfig :: LedgerConfig blk , hfbtRegistry :: ResourceRegistry m , hfbtSystemTime :: SystemTime m @@ -98,7 +98,7 @@ hardForkBlockchainTime args = do , hfbtMaxClockRewind = maxClockRewind } = args - summarize :: LedgerState blk -> HF.Summary (HardForkIndices blk) + summarize :: LedgerState blk EmptyMK -> HF.Summary (HardForkIndices blk) summarize st = hardForkSummary cfg st loop :: diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Forecast.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Forecast.hs index fc08f2a4c1..b63be9fb7d 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Forecast.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Forecast.hs @@ -38,7 +38,7 @@ mapForecast f (Forecast at for) = -- 'GetTip'. -- -- Specialization of 'constantForecast'. -trivialForecast :: GetTip b => b -> Forecast () +trivialForecast :: GetTip b => b mk -> Forecast () trivialForecast x = constantForecastOf () (getTipSlot x) -- | Forecast where the values are never changing diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Genesis/Governor.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Genesis/Governor.hs index d60d276f35..0ff875a32d 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Genesis/Governor.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Genesis/Governor.hs @@ -63,6 +63,7 @@ import Ouroboros.Consensus.HardFork.History.Qry , slotToGenesisWindow ) import Ouroboros.Consensus.HeaderValidation (HeaderWithTime (..)) +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Ouroboros.Consensus.Ledger.Extended ( ExtLedgerState , ledgerState @@ -197,7 +198,7 @@ data GDDTrigger a data GDDStateView m blk peer = GDDStateView { gddCtxCurChain :: AnchoredFragment (HeaderWithTime blk) -- ^ The current chain selection - , gddCtxImmutableLedgerSt :: ExtLedgerState blk + , gddCtxImmutableLedgerSt :: ExtLedgerState blk EmptyMK -- ^ The current ledger state , gddCtxKillActions :: Map peer (m ()) -- ^ Callbacks to disconnect from peers diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Abstract.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Abstract.hs index 8d6f0206cc..b2a07369df 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Abstract.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Abstract.hs @@ -50,7 +50,7 @@ class HasHardForkHistory blk where -- (indeed, in this case the 'LedgerState' should be irrelevant). hardForkSummary :: LedgerConfig blk -> - LedgerState blk -> + LedgerState blk mk -> HardFork.Summary (HardForkIndices blk) -- | Helper function that can be used to define 'hardForkSummary' @@ -64,7 +64,7 @@ class HasHardForkHistory blk where neverForksHardForkSummary :: (LedgerConfig blk -> HardFork.EraParams) -> LedgerConfig blk -> - LedgerState blk -> + LedgerState blk mk -> HardFork.Summary '[blk] neverForksHardForkSummary getParams cfg _st = HardFork.neverForksSummary eraEpochSize eraSlotLength eraGenesisWin eraPerasRoundLength diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Abstract/SingleEraBlock.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Abstract/SingleEraBlock.hs index 539f74354f..acc2e7b5f5 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Abstract/SingleEraBlock.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Abstract/SingleEraBlock.hs @@ -88,9 +88,9 @@ class , Eq (Validated (GenTx blk)) , Eq (ApplyTxErr blk) , Show blk - , Show (LedgerState blk) - , Eq (LedgerState blk) - , NoThunks (LedgerState blk) + , Show (LedgerState blk EmptyMK) + , Eq (LedgerState blk EmptyMK) + , NoThunks (LedgerState blk EmptyMK) , Show (Header blk) , Show (CannotForge blk) , Show (ForgeStateInfo blk) @@ -113,7 +113,7 @@ class EraParams -> -- | Start of this era Bound -> - LedgerState blk -> + LedgerState blk EmptyMK -> Maybe EpochNo -- | Era information (for use in error messages) @@ -127,7 +127,7 @@ singleEraTransition' :: WrapPartialLedgerConfig blk -> EraParams -> Bound -> - LedgerState blk -> + LedgerState blk EmptyMK -> Maybe EpochNo singleEraTransition' = singleEraTransition . unwrapPartialLedgerConfig diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Basics.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Basics.hs index 38502c2fda..0d1c015a9f 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Basics.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Basics.hs @@ -37,6 +37,7 @@ module Ouroboros.Consensus.HardFork.Combinator.Basics , Except ) where +import Data.SOP.Functors (Flip (..)) import Cardano.Slotting.EpochInfo import Data.Kind (Type) import Data.SOP (K (..)) @@ -76,19 +77,19 @@ instance Typeable xs => ShowProxy (HardForkBlock xs) type instance BlockProtocol (HardForkBlock xs) = HardForkProtocol xs type instance HeaderHash (HardForkBlock xs) = OneEraHash xs -newtype instance LedgerState (HardForkBlock xs) = HardForkLedgerState - { hardForkLedgerStatePerEra :: HardForkState LedgerState xs +newtype instance LedgerState (HardForkBlock xs) mk = HardForkLedgerState + { hardForkLedgerStatePerEra :: HardForkState (Flip LedgerState EmptyMK) xs } deriving stock instance CanHardFork xs => - Show (LedgerState (HardForkBlock xs)) + Show (LedgerState (HardForkBlock xs) mk) deriving stock instance CanHardFork xs => - Eq (LedgerState (HardForkBlock xs)) + Eq (LedgerState (HardForkBlock xs) mk) deriving newtype instance CanHardFork xs => - NoThunks (LedgerState (HardForkBlock xs)) + NoThunks (LedgerState (HardForkBlock xs) mk) {------------------------------------------------------------------------------- Protocol config @@ -254,6 +255,6 @@ distribTopLevelConfig ei tlc = instance CanHardFork xs => LedgerSupportsPeras (HardForkBlock xs) where getLatestPerasCertRound = hcollapse - . hcmap proxySingle (K . getLatestPerasCertRound) + . hcmap proxySingle (K . getLatestPerasCertRound . unFlip) . State.tip . hardForkLedgerStatePerEra diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Degenerate.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Degenerate.hs index 2f49df1c99..c87071e2e1 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Degenerate.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Degenerate.hs @@ -27,6 +27,7 @@ module Ouroboros.Consensus.HardFork.Combinator.Degenerate , TxId (DegenGenTxId) ) where +import Data.SOP.Functors (Flip (..)) import Data.SOP.Strict import Ouroboros.Consensus.Block.Abstract import Ouroboros.Consensus.Config @@ -170,11 +171,11 @@ pattern DegenBlockConfig x <- (project -> x) pattern DegenLedgerState :: NoHardForks b => - LedgerState b -> - LedgerState (HardForkBlock '[b]) -pattern DegenLedgerState x <- (project -> x) - where - DegenLedgerState x = inject x + LedgerState b EmptyMK -> + LedgerState (HardForkBlock '[b]) EmptyMK +pattern DegenLedgerState x <- (unFlip . project . Flip -> x) + where + DegenLedgerState x = unFlip $ inject $ Flip x {------------------------------------------------------------------------------- Dealing with the config diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Binary.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Binary.hs index 2096bb2da5..ae996686de 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Binary.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Binary.hs @@ -11,6 +11,7 @@ import Control.Exception (assert) import qualified Control.Tracer as Tracer import Data.Align (alignWith) import Data.SOP.Counting (exactlyTwo) +import Data.SOP.Functors (Flip (..)) import Data.SOP.OptNP (NonEmptyOptNP, OptNP (..)) import Data.SOP.Strict (NP (..), NS (..)) import Data.Text (Text) @@ -101,7 +102,7 @@ protocolInfoBinary ExtLedgerState { ledgerState = HardForkLedgerState $ - initHardForkState initLedgerState1 + initHardForkState (Flip initLedgerState1) , headerState = genesisHeaderState $ initHardForkState $ diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Nary.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Nary.hs index dd72531b01..3fc886bee4 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Nary.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Nary.hs @@ -34,6 +34,7 @@ import Data.SOP.BasicFunctors import Data.SOP.Constraint import Data.SOP.Counting (Exactly (..)) import Data.SOP.Dict (Dict (..)) +import Data.SOP.Functors (Flip (..)) import qualified Data.SOP.InPairs as InPairs import Data.SOP.Index import Data.SOP.Strict @@ -48,7 +49,7 @@ import Ouroboros.Consensus.HeaderValidation , HeaderState (..) , genesisHeaderState ) -import Ouroboros.Consensus.Ledger.Basics (Values, emptyValues, forward) +import Ouroboros.Consensus.Ledger.Basics (EmptyMK, Values, emptyValues, forward) import Ouroboros.Consensus.Ledger.Extended (ExtLedgerState (..)) import Ouroboros.Consensus.Ledger.Query import Ouroboros.Consensus.Storage.Serialisation @@ -224,9 +225,9 @@ instance Inject AnnTip where inject = (undistribAnnTip .: injectNS' (Proxy @AnnTip)) . forgetInjectionIndex -instance Inject LedgerState where +instance Inject (Flip LedgerState EmptyMK) where inject iidx = - HardForkLedgerState . injectHardForkState iidx + Flip . HardForkLedgerState . injectHardForkState iidx instance Inject WrapChainDepState where inject = coerce .: injectHardForkState @@ -241,12 +242,13 @@ instance Inject HeaderState where WrapChainDepState headerStateChainDep } -instance Inject ExtLedgerState where - inject iidx ExtLedgerState{..} = - ExtLedgerState - { ledgerState = inject iidx ledgerState - , headerState = inject iidx headerState - } +instance Inject (Flip ExtLedgerState EmptyMK) where + inject iidx (Flip ExtLedgerState{..}) = + Flip $ + ExtLedgerState + { ledgerState = unFlip $ inject iidx (Flip ledgerState) + , headerState = inject iidx headerState + } {------------------------------------------------------------------------------- Initial ExtLedgerState @@ -269,8 +271,8 @@ injectInitialExtLedgerState :: forall x xs. CanHardFork (x ': xs) => TopLevelConfig (HardForkBlock (x ': xs)) -> - ExtLedgerState x -> - (ExtLedgerState (HardForkBlock (x ': xs)), Values (HardForkBlock (x ': xs))) + ExtLedgerState x EmptyMK -> + (ExtLedgerState (HardForkBlock (x ': xs)) EmptyMK, Values (HardForkBlock (x ': xs))) injectInitialExtLedgerState cfg extLedgerState0 = ( ExtLedgerState { ledgerState = targetEraLedgerState @@ -293,15 +295,15 @@ injectInitialExtLedgerState cfg extLedgerState0 = -- importantly the Byron->Shelley genesis-UTxO dump), so we keep it (rather -- than discarding it) and turn it into the genesis 'Values' the LedgerDB -- needs alongside the ledger state. - targetEraLedgerStateInner :: HardForkState LedgerState (x ': xs) + targetEraLedgerStateInner :: HardForkState (Flip LedgerState EmptyMK) (x ': xs) genesisDiff :: NS WrapDiff (x ': xs) (targetEraLedgerStateInner, genesisDiff) = State.extendToSlot (configLedger cfg) (SlotNo 0) - (initHardForkState (ledgerState extLedgerState0)) + (initHardForkState (Flip (ledgerState extLedgerState0))) - targetEraLedgerState :: LedgerState (HardForkBlock (x ': xs)) + targetEraLedgerState :: LedgerState (HardForkBlock (x ': xs)) EmptyMK targetEraLedgerState = HardForkLedgerState targetEraLedgerStateInner -- The genesis diff is all-inserts (deletes against an empty UTxO are no-ops), diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Unary.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Unary.hs index 0fa8b7c585..7917171d9e 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Unary.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Embed/Unary.hs @@ -41,6 +41,7 @@ import Data.Coerce import Data.Kind (Constraint, Type) import Data.Proxy import Data.SOP.BasicFunctors +import Data.SOP.Functors (Flip (..)) import qualified Data.SOP.OptNP as OptNP import Data.SOP.Strict import qualified Data.SOP.Telescope as Telescope @@ -179,9 +180,9 @@ deriving via IsomorphicUnary NS WrapTipInfo instance Isomorphic WrapTipInfo deriving via IsomorphicUnary NS WrapValidatedGenTx instance Isomorphic WrapValidatedGenTx deriving via - IsomorphicUnary HardForkState LedgerState + IsomorphicUnary HardForkState (Flip LedgerState EmptyMK) instance - Isomorphic LedgerState + Isomorphic (Flip LedgerState EmptyMK) deriving via IsomorphicUnary HardForkState WrapChainDepState instance @@ -339,31 +340,35 @@ instance Isomorphic HeaderState where , headerStateChainDep = inject' (Proxy @(WrapChainDepState blk)) headerStateChainDep } -instance Isomorphic (Ticked LedgerState) where +instance Isomorphic (FlipTickedLedgerState EmptyMK) where project = State.currentState . Telescope.fromTZ . getHardForkState . tickedHardForkLedgerStatePerEra + . getFlipTickedLedgerState inject = - TickedHardForkLedgerState TransitionImpossible + FlipTickedLedgerState + . TickedHardForkLedgerState TransitionImpossible . HardForkState . Telescope.TZ . State.Current History.initBound -instance Isomorphic ExtLedgerState where - project ExtLedgerState{..} = - ExtLedgerState - { ledgerState = project ledgerState - , headerState = project headerState - } +instance Isomorphic (Flip ExtLedgerState EmptyMK) where + project (Flip ExtLedgerState{..}) = + Flip $ + ExtLedgerState + { ledgerState = unFlip $ project $ Flip ledgerState + , headerState = project headerState + } - inject ExtLedgerState{..} = - ExtLedgerState - { ledgerState = inject ledgerState - , headerState = inject headerState - } + inject (Flip ExtLedgerState{..}) = + Flip $ + ExtLedgerState + { ledgerState = unFlip $ inject $ Flip ledgerState + , headerState = inject headerState + } instance Isomorphic AnnTip where project :: forall blk. NoHardForks blk => AnnTip (HardForkBlock '[blk]) -> AnnTip blk @@ -376,13 +381,13 @@ instance Functor m => Isomorphic (InitChainDB m) where forall blk. NoHardForks blk => InitChainDB m (HardForkBlock '[blk]) -> InitChainDB m blk - project = InitChainDB.map (inject' (Proxy @(I blk))) project + project = InitChainDB.map (inject' (Proxy @(I blk))) (unFlip . project . Flip) inject :: forall blk. NoHardForks blk => InitChainDB m blk -> InitChainDB m (HardForkBlock '[blk]) - inject = InitChainDB.map (project' (Proxy @(I blk))) inject + inject = InitChainDB.map (project' (Proxy @(I blk))) (unFlip . inject . Flip) instance Isomorphic ProtocolClientInfo where project ProtocolClientInfo{..} = @@ -460,7 +465,7 @@ instance Functor m => Isomorphic (BlockForging m) where (inject cfg) bno sno - (inject tickedLgrSt) + (getFlipTickedLedgerState (inject (FlipTickedLedgerState tickedLgrSt))) (inject' (Proxy @(WrapValidatedGenTx blk)) <$> txs) (inject' (Proxy @(WrapIsLeader blk)) isLeader) } @@ -506,7 +511,7 @@ instance Functor m => Isomorphic (BlockForging m) where (project cfg) bno sno - (project tickedLgrSt) + (getFlipTickedLedgerState (project (FlipTickedLedgerState tickedLgrSt))) (project' (Proxy @(WrapValidatedGenTx blk)) <$> txs) (project' (Proxy @(WrapIsLeader blk)) isLeader) } @@ -534,7 +539,7 @@ instance Isomorphic ProtocolInfo where project ProtocolInfo{..} = ProtocolInfo { pInfoConfig = project pInfoConfig - , pInfoInitLedger = project pInfoInitLedger + , pInfoInitLedger = unFlip $ project $ Flip pInfoInitLedger , -- @Values (HardForkBlock '[blk]) = NS WrapValues '[blk]@; project the -- single era arm. pInfoInitLedgerTables = unwrapValues (unZ pInfoInitLedgerTables) @@ -547,7 +552,7 @@ instance Isomorphic ProtocolInfo where inject ProtocolInfo{..} = ProtocolInfo { pInfoConfig = inject pInfoConfig - , pInfoInitLedger = inject pInfoInitLedger + , pInfoInitLedger = unFlip $ inject $ Flip pInfoInitLedger , pInfoInitLedgerTables = Z (WrapValues pInfoInitLedgerTables) } diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Forging.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Forging.hs index 6c4a746834..da23acec92 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Forging.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Forging.hs @@ -313,7 +313,7 @@ hardForkForgeBlock :: TopLevelConfig (HardForkBlock xs) -> BlockNo -> SlotNo -> - TickedLedgerState (HardForkBlock xs) -> + TickedLedgerState (HardForkBlock xs) EmptyMK -> [Validated (GenTx (HardForkBlock xs))] -> HardForkIsLeader xs -> m (HardForkBlock xs) @@ -382,7 +382,7 @@ hardForkForgeBlock Product ( Product WrapIsLeader - (Ticked LedgerState) + (FlipTickedLedgerState EmptyMK) ) ([] :.: WrapValidatedGenTx) blk -> @@ -392,7 +392,7 @@ hardForkForgeBlock cfg' (Comp mBlockForging') ( Pair - (Pair (WrapIsLeader isLeader') ledgerState') + (Pair (WrapIsLeader isLeader') (FlipTickedLedgerState ledgerState')) (Comp txs') ) = forgeBlock diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger.hs index c810e68077..e402c4264a 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger.hs @@ -22,6 +22,7 @@ module Ouroboros.Consensus.HardFork.Combinator.Ledger , HardForkLedgerWarning (..) -- * Type family instances + , FlipTickedLedgerState (..) , Ticked (..) -- * Low-level API (exported for the benefit of testing) @@ -29,6 +30,7 @@ module Ouroboros.Consensus.HardFork.Combinator.Ledger , mkHardForkForecast ) where +import Data.SOP.Functors (Flip (..)) import Codec.CBOR.Encoding (Encoding) import Control.Monad (guard) import Control.Monad.Except (throwError, withExcept) @@ -102,24 +104,30 @@ data HardForkLedgerError xs instance CanHardFork xs => GetTip (LedgerState (HardForkBlock xs)) where getTip = castPoint - . State.getTip (castPoint . getTip) + . State.getTip (castPoint . getTip . unFlip) . hardForkLedgerStatePerEra instance CanHardFork xs => GetTip (Ticked LedgerState (HardForkBlock xs)) where getTip = castPoint - . State.getTip (castPoint . getTip) + . State.getTip (castPoint . getTip . getFlipTickedLedgerState) . tickedHardForkLedgerStatePerEra {------------------------------------------------------------------------------- Ticking -------------------------------------------------------------------------------} -data instance Ticked LedgerState (HardForkBlock xs) +-- | The skin's ticked-state telescope functor: each era's ticked state at a +-- fixed 'EmptyMK' (the running tables live in the opaque @'Values'@, not here). +newtype FlipTickedLedgerState mk blk = FlipTickedLedgerState + { getFlipTickedLedgerState :: Ticked LedgerState blk mk + } + +data instance Ticked LedgerState (HardForkBlock xs) mk = TickedHardForkLedgerState { tickedHardForkLedgerStateTransition :: !TransitionInfo , tickedHardForkLedgerStatePerEra :: - !(HardForkState (Ticked LedgerState) xs) + !(HardForkState (FlipTickedLedgerState EmptyMK) xs) } type instance AuxLedgerEvent (HardForkBlock xs) = OneEraLedgerEvent xs @@ -154,7 +162,7 @@ instance CanHardFork xs => IsLedger LedgerState (HardForkBlock xs) where cfgs = getPerEraLedgerConfig hardForkLedgerConfigPerEra ei = State.epochInfoLedger cfg st0 - extended :: HardForkState LedgerState xs + extended :: HardForkState (Flip LedgerState EmptyMK) xs boundaryDiff :: NS WrapDiff xs (extended, boundaryDiff) = State.extendToSlot cfg slot st0 @@ -168,11 +176,11 @@ tickOne :: ComputeLedgerEvents -> Index xs blk -> WrapPartialLedgerConfig blk -> - LedgerState blk -> - (LedgerResult (HardForkBlock xs) :.: Product (Ticked LedgerState) WrapDiff) blk -tickOne ei slot evs sopIdx partialCfg st = + Flip LedgerState EmptyMK blk -> + (LedgerResult (HardForkBlock xs) :.: Product (FlipTickedLedgerState EmptyMK) WrapDiff) blk +tickOne ei slot evs sopIdx partialCfg (Flip st) = Comp - . fmap (\(ticked, diff) -> Pair ticked (WrapDiff diff)) + . fmap (\(ticked, diff) -> Pair (FlipTickedLedgerState ticked) (WrapDiff diff)) . embedLedgerResult (injectLedgerEvent sopIdx) $ applyChainTickLedgerResult evs (completeLedgerConfig' ei partialCfg) slot st @@ -219,8 +227,8 @@ instance st reassemble :: - HardForkState (Product LedgerState WrapDiff) xs -> - (LedgerState (HardForkBlock xs), NS WrapDiff xs) + HardForkState (Product (Flip LedgerState EmptyMK) WrapDiff) xs -> + (LedgerState (HardForkBlock xs) EmptyMK, NS WrapDiff xs) reassemble hs = ( HardForkLedgerState (hmap (\(Pair s _) -> s) hs) , State.tip (hmap (\(Pair _ d) -> d) hs) @@ -245,21 +253,21 @@ apply :: ComputeLedgerEvents -> Index xs blk -> WrapLedgerConfig blk -> - Product (Product I WrapValues) (Ticked LedgerState) blk -> + Product (Product I WrapValues) (FlipTickedLedgerState EmptyMK) blk -> ( Except (HardForkLedgerError xs) :.: LedgerResult (HardForkBlock xs) - :.: Product LedgerState WrapDiff + :.: Product (Flip LedgerState EmptyMK) WrapDiff ) blk -apply doValidate opts index (WrapLedgerConfig cfg) (Pair (Pair (I block) (WrapValues values)) tickedSt) = - Comp - $ withExcept (injectLedgerError index) - $ fmap - ( Comp - . fmap (\(st', diff) -> Pair st' (WrapDiff diff)) - . embedLedgerResult (injectLedgerEvent index) - ) - $ applyBlockLedgerResultWithValidation doValidate opts cfg block values tickedSt +apply doValidate opts index (WrapLedgerConfig cfg) (Pair (Pair (I block) (WrapValues values)) (FlipTickedLedgerState tickedSt)) = + Comp $ + withExcept (injectLedgerError index) $ + fmap + ( Comp + . fmap (\(st', diff) -> Pair (Flip st') (WrapDiff diff)) + . embedLedgerResult (injectLedgerEvent index) + ) + $ applyBlockLedgerResultWithValidation doValidate opts cfg block values tickedSt {------------------------------------------------------------------------------- UpdateLedger @@ -363,9 +371,9 @@ instance viewOne :: SingleEraBlock blk => WrapPartialLedgerConfig blk -> - TickedLedgerState blk -> + FlipTickedLedgerState EmptyMK blk -> WrapLedgerView blk - viewOne cfg st = + viewOne cfg (FlipTickedLedgerState st) = WrapLedgerView $ protocolLedgerView (completeLedgerConfig' ei cfg) st @@ -395,9 +403,9 @@ instance SingleEraBlock blk => WrapPartialLedgerConfig blk -> K EraParams blk -> - Current LedgerState blk -> + Current (Flip LedgerState EmptyMK) blk -> Current (AnnForecast LedgerState WrapLedgerView) blk - forecastOne cfg (K params) (Current start st) = + forecastOne cfg (K params) (Current start (Flip st)) = Current { currentStart = start , currentState = @@ -423,7 +431,7 @@ instance -- | Forecast annotated with details about the ledger it was derived from data AnnForecast state view blk = AnnForecast { annForecast :: Forecast (view blk) - , annForecastState :: state blk + , annForecastState :: state blk EmptyMK , annForecastTip :: WithOrigin SlotNo , annForecastEnd :: Maybe Bound } @@ -612,8 +620,8 @@ inspectHardForkLedger :: NP WrapPartialLedgerConfig xs -> NP (K EraParams) xs -> NP TopLevelConfig xs -> - NS (Current LedgerState) xs -> - NS (Current LedgerState) xs -> + NS (Current (Flip LedgerState EmptyMK)) xs -> + NS (Current (Flip LedgerState EmptyMK)) xs -> [LedgerEvent (HardForkBlock xs)] inspectHardForkLedger = go where @@ -622,8 +630,8 @@ inspectHardForkLedger = go NP WrapPartialLedgerConfig xs -> NP (K EraParams) xs -> NP TopLevelConfig xs -> - NS (Current LedgerState) xs -> - NS (Current LedgerState) xs -> + NS (Current (Flip LedgerState EmptyMK)) xs -> + NS (Current (Flip LedgerState EmptyMK)) xs -> [LedgerEvent (HardForkBlock xs)] go (pc :* _) (K ps :* pss) (c :* _) (Z before) (Z after) = @@ -631,8 +639,8 @@ inspectHardForkLedger = go [ map liftEvent $ inspectLedger c - (currentState before) - (currentState after) + (unFlip (currentState before)) + (unFlip (currentState after)) , case (pss, confirmedBefore, confirmedAfter) of (_, Nothing, Nothing) -> [] @@ -684,13 +692,13 @@ inspectHardForkLedger = go (unwrapPartialLedgerConfig pc) ps (currentStart before) - (currentState before) + (unFlip (currentState before)) confirmedAfter = singleEraTransition (unwrapPartialLedgerConfig pc) ps (currentStart after) - (currentState after) + (unFlip (currentState after)) go Nil _ _ before _ = case before of {} go (_ :* pcs) (_ :* pss) (_ :* cs) (S before) (S after) = @@ -797,7 +805,7 @@ shiftUpdate = go ledgerInfo :: forall blk. SingleEraBlock blk => - Current (Ticked LedgerState) blk -> LedgerEraInfo blk + Current (FlipTickedLedgerState EmptyMK) blk -> LedgerEraInfo blk ledgerInfo _ = LedgerEraInfo $ singleEraInfo (Proxy @blk) ledgerViewInfo :: @@ -962,7 +970,7 @@ instance CanHardFork xs => BlockSupportsUTxOHD (HardForkBlock xs) where hcollapse $ hcimap proxySingle - (\idx eraSt -> K (injectNS idx . WrapValues <$> decodeValues eraSt)) + (\idx eraSt -> K (injectNS idx . WrapValues <$> decodeValues (unFlip eraSt))) (State.tip st) -- | Upgrade an era-tagged 'Values' one era forward, using the adjacent diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/CommonProtocolParams.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/CommonProtocolParams.hs index b4dae1d1ea..66362f67b3 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/CommonProtocolParams.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/CommonProtocolParams.hs @@ -3,6 +3,8 @@ module Ouroboros.Consensus.HardFork.Combinator.Ledger.CommonProtocolParams () where +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) +import Data.SOP.Functors (Flip (..)) import Data.SOP.BasicFunctors import Data.SOP.Strict import Ouroboros.Consensus.HardFork.Combinator.Abstract @@ -20,11 +22,11 @@ instance askCurrentLedger :: CanHardFork xs => - (forall blk. CommonProtocolParams blk => LedgerState blk -> a) -> - LedgerState (HardForkBlock xs) -> + (forall blk. CommonProtocolParams blk => LedgerState blk EmptyMK -> a) -> + LedgerState (HardForkBlock xs) mk -> a askCurrentLedger f = hcollapse - . hcmap proxySingle (K . f) + . hcmap proxySingle (K . f . unFlip) . State.tip . hardForkLedgerStatePerEra diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/PeerSelection.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/PeerSelection.hs index ebb5a5cf00..312ea336d4 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/PeerSelection.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/PeerSelection.hs @@ -2,6 +2,7 @@ module Ouroboros.Consensus.HardFork.Combinator.Ledger.PeerSelection () where +import Data.SOP.Functors (Flip (..)) import Data.SOP.BasicFunctors import Data.SOP.Strict import Ouroboros.Consensus.HardFork.Combinator.Abstract @@ -13,6 +14,6 @@ import Ouroboros.Consensus.Ledger.SupportsPeerSelection instance CanHardFork xs => LedgerSupportsPeerSelection (HardForkBlock xs) where getPeers = hcollapse - . hcmap proxySingle (K . getPeers) + . hcmap proxySingle (K . getPeers . unFlip) . State.tip . hardForkLedgerStatePerEra diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/Query.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/Query.hs index f92a34db4d..d42826cd4a 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/Query.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Ledger/Query.hs @@ -34,6 +34,7 @@ module Ouroboros.Consensus.HardFork.Combinator.Ledger.Query , hardForkQueryInfo ) where +import Data.SOP.Functors (Flip (..)) import Cardano.Binary (enforceSize) import Codec.CBOR.Decoding (Decoder) import qualified Codec.CBOR.Decoding as Dec @@ -77,6 +78,7 @@ import Ouroboros.Consensus.HardFork.History ) import qualified Ouroboros.Consensus.HardFork.History as History import Ouroboros.Consensus.HeaderValidation +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Ouroboros.Consensus.Ledger.Extended import Ouroboros.Consensus.Ledger.Query import Ouroboros.Consensus.Node.Serialisation (Some (..)) @@ -284,9 +286,9 @@ answerBlockQueryHelper -- manually crafted. distribExtLedgerState :: All SingleEraBlock xs => - ExtLedgerState (HardForkBlock xs) -> NS ExtLedgerState xs + ExtLedgerState (HardForkBlock xs) EmptyMK -> NS (Flip ExtLedgerState EmptyMK) xs distribExtLedgerState (ExtLedgerState ledgerState headerState) = - hmap (\(Pair hst lst) -> ExtLedgerState lst hst) $ + hmap (\(Pair hst lst) -> Flip (ExtLedgerState (unFlip lst) hst)) $ mustMatchNS "HeaderState" (distribHeaderState headerState) @@ -358,7 +360,7 @@ interpretQueryIfCurrent :: All SingleEraBlock xs => NP ExtLedgerCfg xs -> QueryIfCurrent xs QFNoTables result -> - NS ExtLedgerState xs -> + NS (Flip ExtLedgerState EmptyMK) xs -> HardForkQueryResult xs result interpretQueryIfCurrent = go where @@ -366,15 +368,15 @@ interpretQueryIfCurrent = go All SingleEraBlock xs' => NP ExtLedgerCfg xs' -> QueryIfCurrent xs' QFNoTables result -> - NS ExtLedgerState xs' -> + NS (Flip ExtLedgerState EmptyMK) xs' -> HardForkQueryResult xs' result - go (c :* _) (QZ qry) (Z st) = + go (c :* _) (QZ qry) (Z (Flip st)) = Right $ answerPureBlockQuery c qry st go (_ :* cs) (QS qry) (S st) = first shiftMismatch $ go cs qry st go _ (QZ qry) (S st) = - Left $ MismatchEraInfo $ ML (queryInfo qry) (hcmap proxySingle (ledgerInfo) st) - go _ (QS qry) (Z st) = + Left $ MismatchEraInfo $ ML (queryInfo qry) (hcmap proxySingle (ledgerInfo . unFlip) st) + go _ (QS qry) (Z (Flip st)) = Left $ MismatchEraInfo $ MR (hardForkQueryInfo qry) (ledgerInfo st) interpretQueryIfCurrentLookup :: @@ -393,13 +395,13 @@ interpretQueryIfCurrentLookup cfg q forker = do NP (Index xs) xs' -> NP ExtLedgerCfg xs' -> QueryIfCurrent xs' QFLookupTables result -> - NS ExtLedgerState xs' -> + NS (Flip ExtLedgerState EmptyMK) xs' -> m (HardForkQueryResult xs' result) go (idx :* _) (c :* _) (QZ qry) _ = Right <$> answerBlockQueryHFLookup idx c qry forker go (_ :* idx) (_ :* cs) (QS qry) (S st) = first shiftMismatch <$> go idx cs qry st - go _ _ (QS qry) (Z st) = + go _ _ (QS qry) (Z (Flip st)) = pure $ Left $ MismatchEraInfo $ MR (hardForkQueryInfo qry) (ledgerInfo st) interpretQueryIfCurrentTraverse :: @@ -419,13 +421,13 @@ interpretQueryIfCurrentTraverse provider cfg q forker = do NP (Index xs) xs' -> NP ExtLedgerCfg xs' -> QueryIfCurrent xs' QFTraverseTables result -> - NS ExtLedgerState xs' -> + NS (Flip ExtLedgerState EmptyMK) xs' -> m (HardForkQueryResult xs' result) go (idx :* _) (c :* _) (QZ qry) _ = Right <$> answerBlockQueryHFTraverse idx c qry provider forker go (_ :* idx) (_ :* cs) (QS qry) (S st) = first shiftMismatch <$> go idx cs qry st - go _ _ (QS qry) (Z st) = + go _ _ (QS qry) (Z (Flip st)) = pure $ Left $ MismatchEraInfo $ MR (hardForkQueryInfo qry) (ledgerInfo st) {------------------------------------------------------------------------------- @@ -449,7 +451,7 @@ interpretQueryAnytime :: HardForkLedgerConfig xs -> QueryAnytime result -> EraIndex xs -> - State.HardForkState LedgerState xs -> + State.HardForkState (Flip LedgerState EmptyMK) xs -> result interpretQueryAnytime cfg query (EraIndex era) st = answerQueryAnytime cfg query (State.situate era st) @@ -458,7 +460,7 @@ answerQueryAnytime :: All SingleEraBlock xs => HardForkLedgerConfig xs -> QueryAnytime result -> - Situated h LedgerState xs -> + Situated h (Flip LedgerState EmptyMK) xs -> result answerQueryAnytime HardForkLedgerConfig{..} = go cfgs (getExactly (getShape hardForkLedgerConfigShape)) @@ -470,7 +472,7 @@ answerQueryAnytime HardForkLedgerConfig{..} = NP WrapPartialLedgerConfig xs' -> NP (K EraParams) xs' -> QueryAnytime result -> - Situated h LedgerState xs' -> + Situated h (Flip LedgerState EmptyMK) xs' -> result go Nil _ _ ctxt = case ctxt of {} go (c :* cs) (K ps :* pss) GetEraStart ctxt = case ctxt of @@ -484,7 +486,7 @@ answerQueryAnytime HardForkLedgerConfig{..} = (unwrapPartialLedgerConfig c) ps (currentStart cur) - (currentState cur) + (unFlip $ currentState cur) {------------------------------------------------------------------------------- Hard fork queries @@ -514,7 +516,7 @@ interpretQueryHardFork :: All SingleEraBlock xs => HardForkLedgerConfig xs -> QueryHardFork xs result -> - LedgerState (HardForkBlock xs) -> + LedgerState (HardForkBlock xs) EmptyMK -> result interpretQueryHardFork cfg query st = case query of @@ -568,7 +570,7 @@ decodeQueryHardForkResult = \case ledgerInfo :: forall blk. SingleEraBlock blk => - ExtLedgerState blk -> + ExtLedgerState blk EmptyMK -> LedgerEraInfo blk ledgerInfo _ = LedgerEraInfo $ singleEraInfo (Proxy @blk) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Mempool.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Mempool.hs index e75cbd4146..38b3fd75cf 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Mempool.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Mempool.hs @@ -148,9 +148,9 @@ instance f :: SingleEraBlock x => Index xs x -> - Ticked LedgerState x -> + FlipTickedLedgerState EmptyMK x -> K (Maybe (ApplyTxErr (HardForkBlock xs))) x - f idx tlst = + f idx (FlipTickedLedgerState tlst) = K $ injectApplyTxErr idx <$> mkMempoolApplyTxError tlst txt instance CanHardFork xs => TxLimits (HardForkBlock xs) where @@ -188,9 +188,9 @@ instance CanHardFork xs => TxLimits (HardForkBlock xs) where SingleEraBlock blk => Index xs blk -> WrapPartialLedgerConfig blk -> - Ticked LedgerState blk -> + FlipTickedLedgerState EmptyMK blk -> K (TxMeasure (HardForkBlock xs)) blk - aux idx pcfg st' = + aux idx pcfg (FlipTickedLedgerState st') = K $ let TxMeasure p1 p2 = blockCapacityTxMeasure @@ -228,9 +228,9 @@ instance CanHardFork xs => TxLimits (HardForkBlock xs) where SingleEraBlock blk => Index xs blk -> WrapLedgerConfig blk -> - (Product GenTx (Ticked LedgerState)) blk -> + (Product GenTx (FlipTickedLedgerState EmptyMK)) blk -> K (Except (HardForkApplyTxErr xs) (HardForkTxMeasurePhase1 xs)) blk - aux idx cfg (Pair tx' st') = + aux idx cfg (Pair tx' (FlipTickedLedgerState st')) = K $ mapExcept ( ( HardForkApplyTxErrFromEra @@ -278,9 +278,9 @@ instance CanHardFork xs => TxLimits (HardForkBlock xs) where SingleEraBlock blk => Index xs blk -> WrapLedgerConfig blk -> - Product WrapValues (Product GenTx (Ticked LedgerState)) blk -> + Product WrapValues (Product GenTx (FlipTickedLedgerState EmptyMK)) blk -> K (Except (HardForkApplyTxErr xs) (HardForkTxMeasurePhase2 xs)) blk - aux idx cfg (Pair (WrapValues vals) (Pair tx' st')) = + aux idx cfg (Pair (WrapValues vals) (Pair tx' (FlipTickedLedgerState st'))) = K $ mapExcept ( ( HardForkApplyTxErrFromEra @@ -303,7 +303,7 @@ data ApplyHelperMode :: (Type -> Type) -> Type where -- | A private type used only to clarify the definition of 'applyHelper' data ApplyResult xs blk = ApplyResult - { arState :: Ticked LedgerState blk + { arState :: FlipTickedLedgerState EmptyMK blk , arDiff :: WrapDiff blk , arValidatedTx :: Validated (GenTx (HardForkBlock xs)) } @@ -321,10 +321,10 @@ applyHelper :: SlotNo -> txIn (HardForkBlock xs) -> Values (HardForkBlock xs) -> - TickedLedgerState (HardForkBlock xs) -> + TickedLedgerState (HardForkBlock xs) EmptyMK -> Except (HardForkApplyTxErr xs) - ( TickedLedgerState (HardForkBlock xs) + ( TickedLedgerState (HardForkBlock xs) EmptyMK , Diff (HardForkBlock xs) , Validated (GenTx (HardForkBlock xs)) ) @@ -368,7 +368,7 @@ applyHelper result <- hsequence' $ hcizipWith proxySingle modeApplyCurrent cfgs matched' - let st' :: State.HardForkState (Ticked LedgerState) xs + let st' :: State.HardForkState (FlipTickedLedgerState EmptyMK) xs st' = arState `hmap` result diffs :: Diff (HardForkBlock xs) @@ -416,12 +416,12 @@ applyHelper SingleEraBlock blk => Index xs blk -> WrapLedgerConfig blk -> - Product WrapValues (Product txIn (Ticked LedgerState)) blk -> + Product WrapValues (Product txIn (FlipTickedLedgerState EmptyMK)) blk -> ( Except (HardForkApplyTxErr xs) :.: ApplyResult xs ) blk - modeApplyCurrent index cfg (Pair (WrapValues vals) (Pair tx' st)) = + modeApplyCurrent index cfg (Pair (WrapValues vals) (Pair tx' (FlipTickedLedgerState st))) = Comp $ withExcept (injectApplyTxErr index) $ do @@ -433,7 +433,7 @@ applyHelper ApplyResult { arValidatedTx = injectValidatedGenTx index vtx , arDiff = WrapDiff diff - , arState = st' + , arState = FlipTickedLedgerState st' } ModeReapply -> do let vtx' = unwrapValidatedGenTx tx' @@ -443,7 +443,7 @@ applyHelper ApplyResult { arValidatedTx = injectValidatedGenTx index vtx' , arDiff = WrapDiff diff - , arState = st' + , arState = FlipTickedLedgerState st' } newtype instance TxId (GenTx (HardForkBlock xs)) = HardForkGenTxId @@ -493,7 +493,7 @@ instance All HasTxs xs => HasTxs (HardForkBlock xs) where ledgerInfo :: forall blk. SingleEraBlock blk => - State.Current (Ticked LedgerState) blk -> LedgerEraInfo blk + State.Current (FlipTickedLedgerState EmptyMK) blk -> LedgerEraInfo blk ledgerInfo _ = LedgerEraInfo $ singleEraInfo (Proxy @blk) injectApplyTxErr :: SListI xs => Index xs blk -> ApplyTxErr blk -> HardForkApplyTxErr xs diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Node/InitStorage.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Node/InitStorage.hs index 84c9ac1ed1..79a14bb4ff 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Node/InitStorage.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Node/InitStorage.hs @@ -5,6 +5,8 @@ module Ouroboros.Consensus.HardFork.Combinator.Node.InitStorage () where +import Data.SOP.Functors (Flip (..)) +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Data.Proxy import Data.SOP.BasicFunctors import Data.SOP.Index @@ -49,7 +51,7 @@ instance CanHardFork xs => NodeInitStorage (HardForkBlock xs) where hcollapse $ hcizipWith proxySingle - aux + (\idx c -> aux idx c . unFlip) cfgs (State.tip (hardForkLedgerStatePerEra currentLedger)) where @@ -59,7 +61,7 @@ instance CanHardFork xs => NodeInitStorage (HardForkBlock xs) where SingleEraBlock blk => Index xs blk -> StorageConfig blk -> - LedgerState blk -> + LedgerState blk EmptyMK -> K (m ()) blk aux index cfg' currentLedger = K $ diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Serialisation/SerialiseDisk.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Serialisation/SerialiseDisk.hs index a3d067bcc4..349a80872a 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Serialisation/SerialiseDisk.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/Serialisation/SerialiseDisk.hs @@ -11,8 +11,10 @@ import qualified Data.ByteString.Lazy as Lazy import Data.SOP.BasicFunctors import Data.SOP.Constraint import Data.SOP.Dict (Dict (..), all_NP) +import Data.SOP.Functors (Flip (..)) import Data.SOP.Strict import Ouroboros.Consensus.Block +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Ouroboros.Consensus.HardFork.Combinator.AcrossEras import Ouroboros.Consensus.HardFork.Combinator.Basics import Ouroboros.Consensus.HardFork.Combinator.Protocol @@ -139,20 +141,20 @@ instance instance SerialiseHFC xs => - EncodeDisk (HardForkBlock xs) (LedgerState (HardForkBlock xs)) + EncodeDisk (HardForkBlock xs) (LedgerState (HardForkBlock xs) EmptyMK) where encodeDisk cfg = - encodeTelescope (hcmap pSHFC (\cfg' -> fn (K . encodeDisk cfg')) cfgs) + encodeTelescope (hcmap pSHFC (\cfg' -> fn (K . encodeDisk cfg' . unFlip)) cfgs) . hardForkLedgerStatePerEra where cfgs = getPerEraCodecConfig (hardForkCodecConfigPerEra cfg) instance SerialiseHFC xs => - DecodeDisk (HardForkBlock xs) (LedgerState (HardForkBlock xs)) + DecodeDisk (HardForkBlock xs) (LedgerState (HardForkBlock xs) EmptyMK) where decodeDisk cfg = fmap HardForkLedgerState $ - decodeTelescope (hcmap pSHFC (Comp . decodeDisk) cfgs) + decodeTelescope (hcmap pSHFC (Comp . fmap Flip . decodeDisk) cfgs) where cfgs = getPerEraCodecConfig (hardForkCodecConfigPerEra cfg) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State.hs index 34bbe710f9..10e645e749 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State.hs @@ -30,6 +30,7 @@ module Ouroboros.Consensus.HardFork.Combinator.State , extendToSlot ) where +import Data.SOP.Functors (Flip (..)) import Control.Monad (guard) import Data.Functor.Product import Data.Proxy @@ -120,7 +121,7 @@ recover = mostRecentTransitionInfo :: All SingleEraBlock xs => HardForkLedgerConfig xs -> - HardForkState LedgerState xs -> + HardForkState (Flip LedgerState EmptyMK) xs -> TransitionInfo mostRecentTransitionInfo HardForkLedgerConfig{..} st = hcollapse $ @@ -137,17 +138,17 @@ mostRecentTransitionInfo HardForkLedgerConfig{..} st = SingleEraBlock blk => WrapPartialLedgerConfig blk -> K History.EraParams blk -> - Current LedgerState blk -> + Current (Flip LedgerState EmptyMK) blk -> K TransitionInfo blk getTransition cfg (K eraParams) Current{..} = K $ - case singleEraTransition' cfg eraParams currentStart currentState of - Nothing -> TransitionUnknown (ledgerTipSlot currentState) + case singleEraTransition' cfg eraParams currentStart (unFlip currentState) of + Nothing -> TransitionUnknown (ledgerTipSlot (unFlip currentState)) Just e -> TransitionKnown e reconstructSummaryLedger :: All SingleEraBlock xs => HardForkLedgerConfig xs -> - HardForkState LedgerState xs -> + HardForkState (Flip LedgerState EmptyMK) xs -> History.Summary xs reconstructSummaryLedger cfg@HardForkLedgerConfig{..} st = reconstructSummary @@ -162,7 +163,7 @@ reconstructSummaryLedger cfg@HardForkLedgerConfig{..} st = epochInfoLedger :: All SingleEraBlock xs => HardForkLedgerConfig xs -> - HardForkState LedgerState xs -> + HardForkState (Flip LedgerState EmptyMK) xs -> EpochInfo (Except PastHorizonException) epochInfoLedger cfg st = History.summaryToEpochInfo $ @@ -223,63 +224,66 @@ extendToSlot :: (CanHardFork xs, Diff (HardForkBlock xs) ~ NS WrapDiff xs) => HardForkLedgerConfig xs -> SlotNo -> - HardForkState LedgerState xs -> - (HardForkState LedgerState xs, Diff (HardForkBlock xs)) + HardForkState (Flip LedgerState EmptyMK) xs -> + (HardForkState (Flip LedgerState EmptyMK) xs, Diff (HardForkBlock xs)) extendToSlot ledgerCfg@HardForkLedgerConfig{..} slot ledgerSt@(HardForkState st) = - let tele = - unI - . Telescope.extend - ( InPairs.hczipWith - proxySingle - ( \f f' -> Require $ \(K t) -> - Extend $ \cur -> - I $ howExtend f f' t cur - ) - translateLS - translateD - ) - ( hczipWith - proxySingle - (fn .: whenExtend) - pcfgs - (getExactly (History.getShape hardForkLedgerConfigShape)) - ) - -- In order to make this an automorphism, as required by 'Telescope.extend', - -- we have to promote each input state to a @Product LedgerState WrapDiff@, - -- pairing it with an (empty) diff alongside. - $ hcmap - proxySingle - initState - st - in ( hmap (\(Pair a _) -> a) $ HardForkState tele - , Telescope.tip $ hmap (\(Current _ (Pair _ b)) -> b) tele - ) + let tele = unI + . Telescope.extend + ( InPairs.hczipWith + proxySingle + ( \f f' -> Require $ \(K t) -> + Extend $ \cur -> + I $ howExtend f f' t cur + ) + translateLS + translateD + ) + ( hczipWith + proxySingle + (fn .: whenExtend) + pcfgs + (getExactly (History.getShape hardForkLedgerConfigShape)) + ) + -- In order to make this an automorphism, as required by 'Telescope.extend', + -- we have to promote each input state to a @Product (Flip LedgerState EmptyMK) WrapDiff@, + -- pairing it with an (empty) diff alongside. + $ hcmap + proxySingle + initState + st + in (hmap (\(Pair a _) -> a) $ HardForkState tele, + Telescope.tip $ hmap (\(Current _ (Pair _ b)) -> b) tele) where pcfgs = getPerEraLedgerConfig hardForkLedgerConfigPerEra cfgs = hcmap proxySingle (completeLedgerConfig'' ei) pcfgs ei = epochInfoLedger ledgerCfg ledgerSt initState :: - forall blk. - SingleEraBlock blk => - Current LedgerState blk -> - Current (Product LedgerState WrapDiff) blk - initState c = c{currentState = Pair (currentState c) (WrapDiff (emptyDiffs @blk))} + forall blk. + SingleEraBlock blk => + Current (Flip LedgerState EmptyMK) blk -> + Current (Product (Flip LedgerState EmptyMK) WrapDiff) blk + initState c = c { currentState = Pair (currentState c) (WrapDiff (emptyDiffs @blk)) } -- Return the end of this era if we should transition to the next whenExtend :: SingleEraBlock blk => WrapPartialLedgerConfig blk -> K History.EraParams blk -> - Current (Product LedgerState a) blk -> + Current (Product (Flip LedgerState EmptyMK) a) blk -> (Maybe :.: K History.Bound) blk whenExtend pcfg (K eraParams) cur = - let Pair curState _ = currentState cur - in Comp $ - K <$> do - transition <- - singleEraTransition' - pcfg + let Pair (Flip curState) _ = currentState cur in + Comp $ + K <$> do + transition <- + singleEraTransition' + pcfg + eraParams + (currentStart cur) + curState + let endBound = + History.mkUpperBound eraParams (currentStart cur) curState @@ -296,8 +300,8 @@ extendToSlot ledgerCfg@HardForkLedgerConfig{..} slot ledgerSt@(HardForkState st) TranslateLedgerState blk blk' -> TranslateDiff blk blk' -> History.Bound -> - Current (Product LedgerState WrapDiff) blk -> - (K Past blk, Current (Product LedgerState WrapDiff) blk') + Current (Product (Flip LedgerState EmptyMK) WrapDiff) blk -> + (K Past blk, Current (Product (Flip LedgerState EmptyMK) WrapDiff) blk') howExtend f f' currentEnd cur = ( K Past @@ -307,9 +311,9 @@ extendToSlot ledgerCfg@HardForkLedgerConfig{..} slot ledgerSt@(HardForkState st) , Current { currentStart = currentEnd , currentState = - let Pair curState (WrapDiff diff) = currentState cur + let Pair (Flip curState) (WrapDiff diff) = currentState cur (st', diff') = translateLedgerStateWith f (History.boundEpoch currentEnd) curState - in Pair st' (WrapDiff $ translateDiffWith f' diff <> diff') + in Pair (Flip st') (WrapDiff $ translateDiffWith f' diff <> diff') } ) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State/Types.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State/Types.hs index ccd48e5c56..37aaa757c6 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State/Types.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HardFork/Combinator/State/Types.hs @@ -138,7 +138,7 @@ newtype CrossEraForecaster state view x y = CrossEraForecaster { crossEraForecastWith :: Bound -> -- 'Bound' of the transition (start of the new era) SlotNo -> -- 'SlotNo' we're constructing a forecast for - state x -> + state x EmptyMK -> Except OutsideForecastRange (view y) } @@ -146,8 +146,8 @@ newtype CrossEraForecaster state view x y = CrossEraForecaster newtype TranslateLedgerState x y = TranslateLedgerState { translateLedgerStateWith :: EpochNo -> - LedgerState x -> - (LedgerState y, Diff y) + LedgerState x EmptyMK -> + (LedgerState y EmptyMK, Diff y) -- ^ How to translate a 'LedgerState' during the era transition. -- -- When translating between eras, it can be the case that values are modified, diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderStateHistory.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderStateHistory.hs index 71b87b1d70..10569054e5 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderStateHistory.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderStateHistory.hs @@ -205,7 +205,7 @@ mkHeaderStateWithTimeFromSummary summary hst = mkHeaderStateWithTime :: (HasCallStack, HasHardForkHistory blk, HasAnnTip blk) => LedgerConfig blk -> - ExtLedgerState blk -> + ExtLedgerState blk EmptyMK -> HeaderStateWithTime blk mkHeaderStateWithTime lcfg (ExtLedgerState lst hst) = mkHeaderStateWithTimeFromSummary summary hst @@ -262,7 +262,7 @@ fromChain :: ) => TopLevelConfig blk -> -- | Initial ledger state - ExtLedgerState blk -> + ExtLedgerState blk EmptyMK -> -- | Initial values (the full in-memory tables) Values blk -> Chain blk -> diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderValidation.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderValidation.hs index 68a1bb1c96..beab2be249 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderValidation.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/HeaderValidation.hs @@ -638,7 +638,7 @@ mkHeaderWithTime :: , HasHeader (Header blk) ) => LedgerConfig blk -> - LedgerState blk -> + LedgerState blk EmptyMK -> Header blk -> HeaderWithTime blk {-# INLINE mkHeaderWithTime #-} diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Abstract.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Abstract.hs index 15ea08d08b..133e4ba278 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Abstract.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Abstract.hs @@ -117,8 +117,8 @@ class LedgerCfg l blk -> blk -> Values blk -> - Ticked l blk -> - Except (LedgerErr l blk) (LedgerResult blk (l blk, Diff blk)) + Ticked l blk EmptyMK -> + Except (LedgerErr l blk) (LedgerResult blk (l blk EmptyMK, Diff blk)) -- | Apply a block to the ledger state. -- @@ -130,8 +130,8 @@ class LedgerCfg l blk -> blk -> Values blk -> - Ticked l blk -> - Except (LedgerErr l blk) (LedgerResult blk (l blk, Diff blk)) + Ticked l blk EmptyMK -> + Except (LedgerErr l blk) (LedgerResult blk (l blk EmptyMK, Diff blk)) -- | Re-apply a block to the very same ledger state it was applied in before. -- @@ -149,8 +149,8 @@ class LedgerCfg l blk -> blk -> Values blk -> - Ticked l blk -> - LedgerResult blk (l blk, Diff blk) + Ticked l blk EmptyMK -> + LedgerResult blk (l blk EmptyMK, Diff blk) defaultApplyBlockLedgerResult :: (HasCallStack, ApplyBlock l blk) => @@ -158,20 +158,20 @@ defaultApplyBlockLedgerResult :: LedgerCfg l blk -> blk -> Values blk -> - Ticked l blk -> - Except (LedgerErr l blk) (LedgerResult blk (l blk, Diff blk)) + Ticked l blk EmptyMK -> + Except (LedgerErr l blk) (LedgerResult blk (l blk EmptyMK, Diff blk)) defaultApplyBlockLedgerResult = applyBlockLedgerResultWithValidation STS.ValidateAll defaultReapplyBlockLedgerResult :: (HasCallStack, ApplyBlock l blk) => - (LedgerErr l blk -> LedgerResult blk (l blk, Diff blk)) -> + (LedgerErr l blk -> LedgerResult blk (l blk EmptyMK, Diff blk)) -> ComputeLedgerEvents -> LedgerCfg l blk -> blk -> Values blk -> - Ticked l blk -> - LedgerResult blk (l blk, Diff blk) + Ticked l blk EmptyMK -> + LedgerResult blk (l blk EmptyMK, Diff blk) defaultReapplyBlockLedgerResult throwReapplyError evs cfg blk vals ticked = either throwReapplyError id . runExcept $ applyBlockLedgerResultWithValidation STS.ValidateNone evs cfg blk vals ticked @@ -190,8 +190,8 @@ applyLedgerBlock :: LedgerCfg l blk -> blk -> Values blk -> - Ticked l blk -> - Except (LedgerErr l blk) (l blk, Diff blk) + Ticked l blk EmptyMK -> + Except (LedgerErr l blk) (l blk EmptyMK, Diff blk) applyLedgerBlock = fmap lrResult ....: applyBlockLedgerResult -- | 'lrResult' after 'reapplyBlockLedgerResult' @@ -201,8 +201,8 @@ reapplyLedgerBlock :: LedgerCfg l blk -> blk -> Values blk -> - Ticked l blk -> - (l blk, Diff blk) + Ticked l blk EmptyMK -> + (l blk EmptyMK, Diff blk) reapplyLedgerBlock = lrResult ....: reapplyBlockLedgerResult tickThenApplyLedgerResult :: @@ -213,8 +213,8 @@ tickThenApplyLedgerResult :: blk -> -- | The values the block consumes, read against the (pre-tick) state. Values blk -> - l blk -> - Except (LedgerErr l blk) (LedgerResult blk (l blk, Diff blk)) + l blk EmptyMK -> + Except (LedgerErr l blk) (LedgerResult blk (l blk EmptyMK, Diff blk)) tickThenApplyLedgerResult evs cfg blk vals l = do let lrTick = applyChainTickLedgerResult evs cfg (blockSlot blk) l (tickedSt, tickDiff) = lrResult lrTick @@ -237,8 +237,8 @@ tickThenReapplyLedgerResult :: LedgerCfg l blk -> blk -> Values blk -> - l blk -> - LedgerResult blk (l blk, Diff blk) + l blk EmptyMK -> + LedgerResult blk (l blk EmptyMK, Diff blk) tickThenReapplyLedgerResult evs cfg blk vals l = let lrTick = applyChainTickLedgerResult evs cfg (blockSlot blk) l (tickedSt, tickDiff) = lrResult lrTick @@ -256,8 +256,8 @@ tickThenApply :: LedgerCfg l blk -> blk -> Values blk -> - l blk -> - Except (LedgerErr l blk) (l blk, Diff blk) + l blk EmptyMK -> + Except (LedgerErr l blk) (l blk EmptyMK, Diff blk) tickThenApply = fmap lrResult ....: tickThenApplyLedgerResult tickThenReapply :: @@ -266,8 +266,8 @@ tickThenReapply :: LedgerCfg l blk -> blk -> Values blk -> - l blk -> - (l blk, Diff blk) + l blk EmptyMK -> + (l blk EmptyMK, Diff blk) tickThenReapply = lrResult ....: tickThenReapplyLedgerResult -- | Apply a sequence of blocks to a full, in-memory @(state, values)@ pair. @@ -282,8 +282,8 @@ foldLedger :: ComputeLedgerEvents -> LedgerCfg l blk -> [blk] -> - (l blk, Values blk) -> - Except (LedgerErr l blk) (l blk, Values blk) + (l blk EmptyMK, Values blk) -> + Except (LedgerErr l blk) (l blk EmptyMK, Values blk) foldLedger evs cfg = repeatedlyM $ \blk (st, vals) -> do (st', diff) <- tickThenApply evs cfg blk vals st @@ -295,8 +295,8 @@ refoldLedger :: ComputeLedgerEvents -> LedgerCfg l blk -> [blk] -> - (l blk, Values blk) -> - (l blk, Values blk) + (l blk EmptyMK, Values blk) -> + (l blk EmptyMK, Values blk) refoldLedger evs cfg = repeatedly $ \blk (st, vals) -> let (st', diff) = tickThenReapply evs cfg blk vals st @@ -308,15 +308,15 @@ refoldLedger evs cfg = ledgerTipPoint :: UpdateLedger blk => - LedgerState blk -> Point blk + LedgerState blk mk -> Point blk ledgerTipPoint = castPoint . getTip ledgerTipHash :: UpdateLedger blk => - LedgerState blk -> ChainHash blk + LedgerState blk mk -> ChainHash blk ledgerTipHash = pointHash . ledgerTipPoint ledgerTipSlot :: UpdateLedger blk => - LedgerState blk -> WithOrigin SlotNo + LedgerState blk mk -> WithOrigin SlotNo ledgerTipSlot = pointSlot . ledgerTipPoint diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Basics.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Basics.hs index de1300caec..7d4de09b1c 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Basics.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Basics.hs @@ -5,6 +5,7 @@ {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE QuantifiedConstraints #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneKindSignatures #-} {-# LANGUAGE TypeFamilies #-} @@ -21,6 +22,19 @@ module Ouroboros.Consensus.Ledger.Basics , LedgerState , TickedLedgerState + -- * The mk-skin (review intermediate — see mk-skin-plan.md) + , MapKind + , LedgerStateKind + , StateKind + , LedgerTables (..) + , EmptyMK (..) + , KeysMK (..) + , ValuesMK (..) + , DiffMK (..) + , HasLedgerTables (..) + , emptyLedgerTables + , forgetLedgerTables + -- * On-disk table vocabulary , TxIn , TxOut @@ -90,17 +104,17 @@ type family TxOut blk Tip -------------------------------------------------------------------------------} -type GetTip :: Type -> Constraint +type GetTip :: LedgerStateKind -> Constraint class GetTip l where -- | Point of the most recently applied block -- -- Should be 'GenesisPoint' when no blocks have been applied yet - getTip :: l -> Point l + getTip :: forall mk. l mk -> Point l -getTipHash :: GetTip l => l -> ChainHash l +getTipHash :: GetTip l => l mk -> ChainHash l getTipHash = pointHash . getTip -getTipSlot :: GetTip l => l -> WithOrigin SlotNo +getTipSlot :: GetTip l => l mk -> WithOrigin SlotNo getTipSlot = pointSlot . getTip type GetTipSTM :: (Type -> Type) -> Type -> Constraint @@ -157,7 +171,7 @@ pureLedgerResult a = -- | Static environment required for the ledger -- -- Types that inhabit this family will come from the Ledger code. -type LedgerCfg :: (Type -> Type) -> Type -> Type +type LedgerCfg :: StateKind -> Type -> Type type family LedgerCfg l blk :: Type -- | Event emitted by the ledger @@ -180,12 +194,14 @@ type family AuxLedgerEvent blk :: Type data ComputeLedgerEvents = ComputeLedgerEvents | OmitLedgerEvents deriving (Eq, Show, Generic, NoThunks) -type IsLedger :: (Type -> Type) -> Type -> Constraint +type IsLedger :: StateKind -> Type -> Constraint class - ( -- Requirements on the ledger state itself - Eq (l blk) - , NoThunks (l blk) - , Show (l blk) + ( -- Requirements on the ledger state itself (concrete map-kinds — the skin + -- cannot use @main@'s quantified @EqMK@\/@ShowMK@\/@NoThunksMK@ form; see + -- the note by the skin definitions). + Eq (l blk EmptyMK) + , NoThunks (l blk EmptyMK) + , Show (l blk EmptyMK) , -- Requirements on 'LedgerCfg' NoThunks (LedgerCfg l blk) , -- Requirements on 'LedgerErr' @@ -248,8 +264,8 @@ class ComputeLedgerEvents -> LedgerCfg l blk -> SlotNo -> - l blk -> - LedgerResult blk (Ticked l blk, Diff blk) + l blk EmptyMK -> + LedgerResult blk (Ticked l blk EmptyMK, Diff blk) -- | 'lrResult' after 'applyChainTickLedgerResult' applyChainTick :: @@ -257,8 +273,8 @@ applyChainTick :: ComputeLedgerEvents -> LedgerCfg l blk -> SlotNo -> - l blk -> - (Ticked l blk, Diff blk) + l blk EmptyMK -> + (Ticked l blk EmptyMK, Diff blk) applyChainTick = lrResult ...: applyChainTickLedgerResult {------------------------------------------------------------------------------- @@ -281,8 +297,8 @@ applyChainTick = lrResult ...: applyChainTickLedgerResult -- The main operations we can do with a 'LedgerState' are /ticking/ (defined in -- 'IsLedger'), and /applying a block/ (defined in -- 'Ouroboros.Consensus.Ledger.Abstract.ApplyBlock'). -type LedgerState :: Type -> Type -data family LedgerState blk +type LedgerState :: Type -> LedgerStateKind +data family LedgerState blk mk type TickedLedgerState blk = Ticked LedgerState blk @@ -293,6 +309,96 @@ instance StandardHash blk => StandardHash (LedgerState blk) type LedgerConfig blk = LedgerCfg LedgerState blk type LedgerError blk = LedgerErr LedgerState blk +{------------------------------------------------------------------------------- + The mk-skin (review intermediate — see mk-skin-plan.md) + + A thin newtype layer that re-expresses the opaque 'Keys'\/'Values'\/'Diff blk' + payloads in @main@'s map-kind vocabulary, so that the review diff against the + prepare-11.1 base cancels the vocabulary churn and leaves the genuine + structural redesign. + + This is deliberately /not/ @main@'s machinery: + + * @l@ is the block (@l = blk@), the only well-kinded reading; + + * the map-kind is single-argument (@'MapKind' = Type -> Type@), so each + wrapper is a thin newtype over the /existing/ opaque payload — there is no + @CanMapMK@\/@mapKeysMK@ combinator zoo and no canonical machinery; + + * @'LedgerTables' blk 'ValuesMK' ≅ 'Values' blk@, and likewise for + 'KeysMK'\/'DiffMK'. + + The whole layer (and the @mk@ argument of 'LedgerState') is to be stripped in + the final commit; see @mk-skin-plan.md@. +-------------------------------------------------------------------------------} + +-- | The kind of a map-kind: a wrapper that turns a block into the table payload +-- of one phase (keys\/values\/diff). Single-argument, unlike @main@'s @k -> v -> +-- Type@. +type MapKind = Type -> Type + +-- | The kind of a ledger-state-like type once it carries an 'mk' argument. +type LedgerStateKind = MapKind -> Type + +-- | The kind of an unapplied ledger-state functor (the generic @l@ in +-- @l blk mk@), e.g. 'LedgerState' itself. +type StateKind = Type -> LedgerStateKind + +-- | The on-disk tables of a block, in the chosen map-kind. A thin newtype over +-- @mk blk@ (e.g. @'LedgerTables' blk 'ValuesMK' ≅ 'Values' blk@). +type LedgerTables :: Type -> MapKind -> Type +newtype LedgerTables l mk = LedgerTables (mk l) + +-- | No tables. +type EmptyMK :: MapKind +data EmptyMK l = EmptyMK + +-- | The keys phase: a thin wrapper over the opaque 'Keys'. +type KeysMK :: MapKind +newtype KeysMK l = KeysMK (Keys l) + +-- | The values phase: a thin wrapper over the opaque 'Values'. +type ValuesMK :: MapKind +newtype ValuesMK l = ValuesMK (Values l) + +-- | The diff phase: a thin wrapper over the opaque 'Diff'. +type DiffMK :: MapKind +newtype DiffMK l = DiffMK (Diff l) + +-- NOTE: @main@ requires the ledger-state Eq\/Show\/NoThunks superclasses on +-- 'IsLedger' in a quantified form (@forall mk. EqMK mk => Eq (l blk mk)@), which +-- relies on @mk@ being a two-argument map-kind so the payload appears as the +-- plain type /variables/ @k@\/@v@. The single-arg skin (forced by the hard-fork +-- combinator, which has no @TxIn@\/@TxOut@) makes each payload a type-family +-- application (@'Keys' blk@ etc.), and GHC forbids type families in quantified +-- constraints. So the skin cannot reproduce that quantified form; 'IsLedger' +-- instead requires the concrete map-kinds the code uses. This one superclass +-- block therefore does not cancel against @main@ in the review diff (a small, +-- localised residue; see @mk-skin-plan.md@). + +-- | @main@'s vocabulary for getting\/setting a 'LedgerState'\'s tables, restored +-- over the skin so call sites (@projectLedgerTables@\/@withLedgerTables@\/ +-- @forgetLedgerTables@) read exactly as on @main@ and cancel in the review diff. +-- +-- This is /not/ @main@'s combinator class (no @LedgerTableConstraints@\/ +-- @ltliftA2@ zoo). It is a per-@blk@ class over @'LedgerState' blk mk@; +-- 'Ouroboros.Consensus.Ledger.Extended.ExtLedgerState' gets its own thin +-- wrapper. To be stripped with the rest of the skin. +type HasLedgerTables :: Type -> Constraint +class BlockSupportsUTxOHD blk => HasLedgerTables blk where + projectLedgerTables :: LedgerState blk mk -> LedgerTables blk mk + withLedgerTables :: + LedgerState blk any -> LedgerTables blk mk -> LedgerState blk mk + +-- | The empty tables. +emptyLedgerTables :: LedgerTables blk EmptyMK +emptyLedgerTables = LedgerTables EmptyMK + +-- | Drop a 'LedgerState'\'s tables. +forgetLedgerTables :: + HasLedgerTables blk => LedgerState blk mk -> LedgerState blk EmptyMK +forgetLedgerTables st = withLedgerTables st emptyLedgerTables + {------------------------------------------------------------------------------- UTxO-HD block axis -------------------------------------------------------------------------------} @@ -369,7 +475,7 @@ class (Semigroup (Diff blk), Semigroup (Keys blk)) => BlockSupportsUTxOHD blk wh -- current era to pick which @NS@ arm to decode into. Single-era instances -- ignore it. The snapshot loads the state before the tables, so it is always -- available at the call site. - decodeValues :: forall s. LedgerState blk -> Decoder s (Values blk) + decodeValues :: forall s. LedgerState blk EmptyMK -> Decoder s (Values blk) -- | The on-disk table operations that only /single-era/ blocks support, split -- out of 'BlockSupportsUTxOHD'. diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/CommonProtocolParams.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/CommonProtocolParams.hs index 4de46f1e05..d51ab4b601 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/CommonProtocolParams.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/CommonProtocolParams.hs @@ -7,8 +7,8 @@ import Ouroboros.Consensus.Ledger.Abstract class UpdateLedger blk => CommonProtocolParams blk where -- | The maximum header size in bytes according to the currently adopted -- protocol parameters of the ledger state. - maxHeaderSize :: LedgerState blk -> Word32 + maxHeaderSize :: LedgerState blk mk -> Word32 -- | The maximum transaction size in bytes according to the currently -- adopted protocol parameters of the ledger state. - maxTxSize :: LedgerState blk -> Word32 + maxTxSize :: LedgerState blk mk -> Word32 diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Dual.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Dual.hs index 3aab950a5d..0c4babdbf3 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Dual.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Dual.hs @@ -370,13 +370,13 @@ instance Bridge m a => GetTip (Ticked LedgerState (DualBlock m a)) where -- -- The auxiliary (spec) ledger keeps its whole UTxO in memory, so we carry its -- @'Values' a@ explicitly alongside the auxiliary state. -data instance Ticked LedgerState (DualBlock m a) = TickedDualLedgerState - { tickedDualLedgerStateMain :: Ticked LedgerState m - , tickedDualLedgerStateAux :: Ticked LedgerState a +data instance Ticked LedgerState (DualBlock m a) mk = TickedDualLedgerState + { tickedDualLedgerStateMain :: Ticked LedgerState m mk + , tickedDualLedgerStateAux :: Ticked LedgerState a EmptyMK , tickedDualLedgerStateAuxValues :: Values a -- ^ The ticked auxiliary ledger's full UTxO. , tickedDualLedgerStateBridge :: BridgeLedger m a - , tickedDualLedgerStateAuxOrig :: LedgerState a + , tickedDualLedgerStateAuxOrig :: LedgerState a EmptyMK -- ^ The original, unticked ledger for the auxiliary block -- -- The reason we keep this in addition to the ticked ledger state is that @@ -385,7 +385,7 @@ data instance Ticked LedgerState (DualBlock m a) = TickedDualLedgerState , tickedDualLedgerStateAuxOrigValues :: Values a -- ^ The original, unticked auxiliary ledger's full UTxO. } - deriving NoThunks via AllowThunk (Ticked LedgerState (DualBlock m a)) + deriving NoThunks via AllowThunk (Ticked LedgerState (DualBlock m a) mk) type instance AuxLedgerEvent (DualBlock m a) = AuxLedgerEvent m @@ -438,17 +438,17 @@ applyHelper :: LedgerCfg LedgerState m -> m -> Values m -> - Ticked LedgerState m -> - Except (LedgerErr LedgerState m) (LedgerResult m (LedgerState m, Diff m)) + Ticked LedgerState m EmptyMK -> + Except (LedgerErr LedgerState m) (LedgerResult m (LedgerState m EmptyMK, Diff m)) ) -> ComputeLedgerEvents -> DualLedgerConfig m a -> DualBlock m a -> Values (DualBlock m a) -> - Ticked LedgerState (DualBlock m a) -> + Ticked LedgerState (DualBlock m a) EmptyMK -> Except (DualLedgerError m a) - (LedgerResult (DualBlock m a) (LedgerState (DualBlock m a), Diff (DualBlock m a))) + (LedgerResult (DualBlock m a) (LedgerState (DualBlock m a) EmptyMK, Diff (DualBlock m a))) applyHelper f opts cfg block@DualBlock{..} vals TickedDualLedgerState{..} = do (ledgerResult, (aux', auxValues')) <- agreeOnError @@ -557,28 +557,30 @@ instance emptyValues = emptyValues @m emptyDiffs = emptyDiffs @m -data instance LedgerState (DualBlock m a) = DualLedgerState - { dualLedgerStateMain :: LedgerState m - , dualLedgerStateAux :: LedgerState a +data instance LedgerState (DualBlock m a) mk = DualLedgerState + { dualLedgerStateMain :: LedgerState m mk + , dualLedgerStateAux :: LedgerState a EmptyMK , dualLedgerStateAuxValues :: Values a , dualLedgerStateBridge :: BridgeLedger m a } - deriving NoThunks via AllowThunk (LedgerState (DualBlock m a)) + deriving NoThunks via AllowThunk (LedgerState (DualBlock m a) mk) instance Bridge m a => UpdateLedger (DualBlock m a) deriving instance ( Bridge m a - , Show (LedgerState a) + , Show (LedgerState m mk) + , Show (LedgerState a EmptyMK) , Show (Values a) ) => - Show (LedgerState (DualBlock m a)) + Show (LedgerState (DualBlock m a) mk) deriving instance ( Bridge m a - , Eq (LedgerState a) + , Eq (LedgerState m mk) + , Eq (LedgerState a EmptyMK) , Eq (Values a) ) => - Eq (LedgerState (DualBlock m a)) + Eq (LedgerState (DualBlock m a) mk) {------------------------------------------------------------------------------- Utilities for working with the extended ledger state @@ -991,12 +993,12 @@ applyMaybeBlock :: -- | Ticked values Values blk -> -- | Ticked state - Ticked LedgerState blk -> + Ticked LedgerState blk EmptyMK -> -- | Original, unticked state - LedgerState blk -> + LedgerState blk EmptyMK -> -- | Original, unticked values Values blk -> - Except (LedgerError blk) (LedgerState blk, Values blk) + Except (LedgerError blk) (LedgerState blk EmptyMK, Values blk) applyMaybeBlock _ _ Nothing _ _ origSt origVals = return (origSt, origVals) applyMaybeBlock evs cfg (Just block) tvals tst _ _ = do (st', diff) <- applyLedgerBlock evs cfg block tvals tst @@ -1012,10 +1014,10 @@ reapplyMaybeBlock :: LedgerConfig blk -> Maybe blk -> Values blk -> - Ticked LedgerState blk -> - LedgerState blk -> + Ticked LedgerState blk EmptyMK -> + LedgerState blk EmptyMK -> Values blk -> - (LedgerState blk, Values blk) + (LedgerState blk EmptyMK, Values blk) reapplyMaybeBlock _ _ Nothing _ _ origSt origVals = (origSt, origVals) reapplyMaybeBlock evs cfg (Just block) tvals tst _ _ = let (st', diff) = reapplyLedgerBlock evs cfg block tvals tst @@ -1175,9 +1177,9 @@ decodeDualGenTxErr decodeMain = do <*> decode encodeDualLedgerState :: - (Bridge m a, Serialise (LedgerState a), Serialise (Values a)) => - (LedgerState m -> Encoding) -> - LedgerState (DualBlock m a) -> + (Bridge m a, Serialise (LedgerState a EmptyMK), Serialise (Values a)) => + (LedgerState m mk -> Encoding) -> + LedgerState (DualBlock m a) mk -> Encoding encodeDualLedgerState encodeMain DualLedgerState{..} = mconcat @@ -1189,9 +1191,9 @@ encodeDualLedgerState encodeMain DualLedgerState{..} = ] decodeDualLedgerState :: - (Bridge m a, Serialise (LedgerState a), Serialise (Values a)) => - Decoder s (LedgerState m) -> - Decoder s (LedgerState (DualBlock m a)) + (Bridge m a, Serialise (LedgerState a EmptyMK), Serialise (Values a)) => + Decoder s (LedgerState m mk) -> + Decoder s (LedgerState (DualBlock m a) mk) decodeDualLedgerState decodeMain = do enforceSize "DualLedgerState" 4 DualLedgerState diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Extended.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Extended.hs index 713e7a9b9d..6958da5a61 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Extended.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Extended.hs @@ -65,26 +65,26 @@ deriving instance LedgerSupportsProtocol blk => Show (ExtValidationError blk) -- | Extended ledger state -- -- This is the combination of the header state and the ledger state proper. -data ExtLedgerState blk = ExtLedgerState - { ledgerState :: !(LedgerState blk) +data ExtLedgerState blk mk = ExtLedgerState + { ledgerState :: !(LedgerState blk mk) , headerState :: !(HeaderState blk) } deriving Generic deriving instance - LedgerSupportsProtocol blk => - Eq (ExtLedgerState blk) + (LedgerSupportsProtocol blk, Eq (LedgerState blk mk)) => + Eq (ExtLedgerState blk mk) deriving instance - LedgerSupportsProtocol blk => - Show (ExtLedgerState blk) + (LedgerSupportsProtocol blk, Show (LedgerState blk mk)) => + Show (ExtLedgerState blk mk) -- | We override 'showTypeOf' to show the type of the block -- -- This makes debugging a bit easier, as the block gets used to resolve all -- kinds of type families. instance - LedgerSupportsProtocol blk => - NoThunks (ExtLedgerState blk) + (LedgerSupportsProtocol blk, NoThunks (LedgerState blk mk)) => + NoThunks (ExtLedgerState blk mk) where showTypeOf _ = show $ typeRep (Proxy @(ExtLedgerState blk)) @@ -131,8 +131,8 @@ type instance LedgerCfg ExtLedgerState blk = ExtLedgerCfg blk The ticked extended ledger state -------------------------------------------------------------------------------} -data instance Ticked ExtLedgerState blk = TickedExtLedgerState - { tickedLedgerState :: Ticked LedgerState blk +data instance Ticked ExtLedgerState blk mk = TickedExtLedgerState + { tickedLedgerState :: Ticked LedgerState blk mk , ledgerView :: LedgerView (BlockProtocol blk) , tickedHeaderState :: Ticked (HeaderState blk) } @@ -173,19 +173,19 @@ applyHelper :: LedgerCfg LedgerState blk -> blk -> Values blk -> - Ticked LedgerState blk -> + Ticked LedgerState blk EmptyMK -> Except (LedgerErr LedgerState blk) - (LedgerResult blk (LedgerState blk, Diff blk)) + (LedgerResult blk (LedgerState blk EmptyMK, Diff blk)) ) -> ComputeLedgerEvents -> LedgerCfg ExtLedgerState blk -> blk -> Values blk -> - Ticked ExtLedgerState blk -> + Ticked ExtLedgerState blk EmptyMK -> Except (LedgerErr ExtLedgerState blk) - (LedgerResult blk (ExtLedgerState blk, Diff blk)) + (LedgerResult blk (ExtLedgerState blk EmptyMK, Diff blk)) applyHelper f opts cfg blk vals TickedExtLedgerState{..} = do ledgerResult <- withExcept ExtValidationErrorLedger $ @@ -233,10 +233,10 @@ instance (LedgerSupportsProtocol blk, BlockSupportsUTxOHD blk) => ApplyBlock Ext -------------------------------------------------------------------------------} encodeExtLedgerState :: - (LedgerState blk -> Encoding) -> + (LedgerState blk mk -> Encoding) -> (ChainDepState (BlockProtocol blk) -> Encoding) -> (AnnTip blk -> Encoding) -> - ExtLedgerState blk -> + ExtLedgerState blk mk -> Encoding encodeExtLedgerState encodeLedgerState @@ -255,12 +255,12 @@ encodeExtLedgerState encodeAnnTip encodeDiskExtLedgerState :: - forall blk. - ( EncodeDisk blk (LedgerState blk) + forall blk mk. + ( EncodeDisk blk (LedgerState blk mk) , EncodeDisk blk (ChainDepState (BlockProtocol blk)) , EncodeDisk blk (AnnTip blk) ) => - (CodecConfig blk -> ExtLedgerState blk -> Encoding) + (CodecConfig blk -> ExtLedgerState blk mk -> Encoding) encodeDiskExtLedgerState cfg = encodeExtLedgerState (encodeDisk cfg) @@ -268,10 +268,10 @@ encodeDiskExtLedgerState cfg = (encodeDisk cfg) decodeExtLedgerState :: - (forall s. Decoder s (LedgerState blk)) -> + (forall s. Decoder s (LedgerState blk mk)) -> (forall s. Decoder s (ChainDepState (BlockProtocol blk))) -> (forall s. Decoder s (AnnTip blk)) -> - (forall s. Decoder s (ExtLedgerState blk)) + (forall s. Decoder s (ExtLedgerState blk mk)) decodeExtLedgerState decodeLedgerState decodeChainDepState @@ -287,12 +287,12 @@ decodeExtLedgerState decodeAnnTip decodeDiskExtLedgerState :: - forall blk. - ( DecodeDisk blk (LedgerState blk) + forall blk mk. + ( DecodeDisk blk (LedgerState blk mk) , DecodeDisk blk (ChainDepState (BlockProtocol blk)) , DecodeDisk blk (AnnTip blk) ) => - (CodecConfig blk -> forall s. Decoder s (ExtLedgerState blk)) + (CodecConfig blk -> forall s. Decoder s (ExtLedgerState blk mk)) decodeDiskExtLedgerState cfg = decodeExtLedgerState (decodeDisk cfg) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Inspect.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Inspect.hs index 300d1cb757..97ef8244eb 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Inspect.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Inspect.hs @@ -70,9 +70,9 @@ class inspectLedger :: TopLevelConfig blk -> -- | Before - LedgerState blk -> + LedgerState blk mk1 -> -- | After - LedgerState blk -> + LedgerState blk mk2 -> [LedgerEvent blk] -- Defaults @@ -87,9 +87,9 @@ class ) => TopLevelConfig blk -> -- | Before - LedgerState blk -> + LedgerState blk mk1 -> -- | After - LedgerState blk -> + LedgerState blk mk2 -> [LedgerEvent blk] inspectLedger _ _ _ = [] where diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Query.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Query.hs index 20e8a3306c..47e0f51f0e 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Query.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/Query.hs @@ -153,7 +153,7 @@ class answerPureBlockQuery :: ExtLedgerCfg blk -> BlockQuery blk QFNoTables result -> - ExtLedgerState blk -> + ExtLedgerState blk EmptyMK -> result -- | Answer a query that requires to perform a lookup on the ledger tables. As diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsMempool.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsMempool.hs index b4aa3b7943..c273998dfa 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsMempool.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsMempool.hs @@ -138,8 +138,8 @@ class -- | The values the tx consumes (read against the virtual tip and forwarded -- through the diffs of the txs already in the mempool). Values blk -> - TickedLedgerState blk -> - Except (ApplyTxErr blk) (TickedLedgerState blk, Diff blk, Validated (GenTx blk)) + TickedLedgerState blk EmptyMK -> + Except (ApplyTxErr blk) (TickedLedgerState blk EmptyMK, Diff blk, Validated (GenTx blk)) -- | Apply a previously validated transaction to a potentially different -- ledger state @@ -159,8 +159,8 @@ class Validated (GenTx blk) -> -- | At least the values the tx consumes. Values blk -> - TickedLedgerState blk -> - Except (ApplyTxErr blk) (TickedLedgerState blk, Diff blk) + TickedLedgerState blk EmptyMK -> + Except (ApplyTxErr blk) (TickedLedgerState blk EmptyMK, Diff blk) -- | Apply a list of previously validated transactions to a new ledger state. -- @@ -184,7 +184,7 @@ class [(Validated (GenTx blk), InputTxDiffs blk wtd, extra)] -> -- | At least the values all the txs consume. Values blk -> - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> ReapplyTxsResult extra blk wtd reapplyTxs cfg slot txs vals0 st0 = let (accE, accV, st', _vals) = @@ -212,13 +212,13 @@ class -- node-to-client mini protocol sends when a tx is rejected. mkMempoolApplyTxError :: -- | for the HFC - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> Text -> Maybe (ApplyTxErr blk) -- | Value of 'mkMempoolApplyTxError' when the block type can never -- construct the ledger error -nothingMkMempoolApplyTxError :: TickedLedgerState blk -> Text -> Maybe (ApplyTxErr blk) +nothingMkMempoolApplyTxError :: TickedLedgerState blk EmptyMK -> Text -> Maybe (ApplyTxErr blk) nothingMkMempoolApplyTxError _ _ = Nothing data ReapplyTxsResult extra blk wtd @@ -228,7 +228,7 @@ data ReapplyTxsResult extra blk wtd , validatedTxs :: ![(Validated (GenTx blk), InputTxDiffs blk wtd, extra)] -- ^ txs that are valid again, order must be the same as the order in -- which txs were received - , resultingState :: !(TickedLedgerState blk) + , resultingState :: !(TickedLedgerState blk EmptyMK) } -- | A generalized transaction, 'GenTx', identifier. @@ -387,7 +387,7 @@ class txMeasurePhase1 :: -- | used at least by HFC's composition logic LedgerConfig blk -> - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> GenTx blk -> Except (ApplyTxErr blk) (TxMeasurePhase1 blk) @@ -398,7 +398,7 @@ class -- example in Cardano they look at the reference scripts), so the values are -- passed explicitly rather than resolved against an empty UTxO. Values blk -> - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> GenTx blk -> Except (ApplyTxErr blk) (TxMeasurePhase2 blk) @@ -406,7 +406,7 @@ class blockCapacityTxMeasure :: -- | at least for symmetry with 'txMeasure' LedgerConfig blk -> - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> TxMeasure blk -- | We intentionally do not declare a 'Num' instance! We prefer @ByteSize32@ diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeerSelection.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeerSelection.hs index d832ea9cc9..68483ded16 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeerSelection.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeerSelection.hs @@ -48,4 +48,4 @@ class LedgerSupportsPeerSelection blk where -- -- Note: if the ledger state is old, the registered relays can also be old and -- may no longer be online. - getPeers :: LedgerState blk -> [(PoolStake, NonEmpty StakePoolRelay)] + getPeers :: LedgerState blk mk -> [(PoolStake, NonEmpty StakePoolRelay)] diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeras.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeras.hs index 617ed81bf7..d2655a94a8 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeras.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsPeras.hs @@ -13,6 +13,6 @@ class LedgerSupportsPeras blk where -- | Extract the round number of the latest Peras certificate stored in the -- given ledger state (if any). This is needed to coordinate the end of a -- cooldown period. - getLatestPerasCertRound :: LedgerState blk -> Maybe PerasRoundNo - default getLatestPerasCertRound :: LedgerState blk -> Maybe PerasRoundNo + getLatestPerasCertRound :: LedgerState blk mk -> Maybe PerasRoundNo + default getLatestPerasCertRound :: LedgerState blk mk -> Maybe PerasRoundNo getLatestPerasCertRound _ = Nothing diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsProtocol.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsProtocol.hs index 7a933f7d66..feebf7a3d8 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsProtocol.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Ledger/SupportsProtocol.hs @@ -27,7 +27,7 @@ class -- relation between this and forecasting. protocolLedgerView :: LedgerConfig blk -> - Ticked LedgerState blk -> + Ticked LedgerState blk EmptyMK -> LedgerView (BlockProtocol blk) -- | Get a forecast at the given ledger state. @@ -68,7 +68,7 @@ class ledgerViewForecastAt :: HasCallStack => LedgerConfig blk -> - LedgerState blk -> + LedgerState blk EmptyMK -> Forecast (LedgerView (BlockProtocol blk)) -- | Relation between 'ledgerViewForecastAt' and 'applyChainTick' @@ -77,7 +77,7 @@ _lemma_ledgerViewForecastAt_applyChainTick :: , Eq (LedgerView (BlockProtocol blk)) ) => LedgerConfig blk -> - LedgerState blk -> + LedgerState blk EmptyMK -> Forecast (LedgerView (BlockProtocol blk)) -> SlotNo -> Either String () diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/API.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/API.hs index 78c1ab8291..28119e2fe1 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/API.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/API.hs @@ -183,7 +183,7 @@ data Mempool m blk = Mempool -- This doesn't look at the ledger state at all. , getSnapshotFor :: SlotNo -> - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> Diff blk -> (Keys blk -> m (Values blk)) -> m (MempoolSnapshot blk) @@ -402,14 +402,14 @@ data ForgeLedgerState blk -- This will only be the case when we realized that we are the slot leader -- and we are actually producing a block. It is the caller's responsibility -- to call 'applyChainTick' and produce the ticked ledger state. - ForgeInKnownSlot SlotNo (TickedLedgerState blk) (Diff blk) + ForgeInKnownSlot SlotNo (TickedLedgerState blk EmptyMK) (Diff blk) | -- | The slot number of the block is not yet known -- -- When we are validating transactions before we know in which block they -- will end up, we have to make an assumption about which slot number to use -- for 'applyChainTick' to prepare the ledger state; we will assume that -- they will end up in the slot after the slot at the tip of the ledger. - ForgeInUnknownSlot (LedgerState blk) + ForgeInUnknownSlot (LedgerState blk EmptyMK) {------------------------------------------------------------------------------- Snapshot of the mempool diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Capacity.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Capacity.hs index fde0fc47c1..e856f64139 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Capacity.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Capacity.hs @@ -56,7 +56,7 @@ mkCapacityBytesOverride = MempoolCapacityBytesOverride computeMempoolCapacity :: LedgerSupportsMempool blk => LedgerConfig blk -> - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> MempoolCapacityBytesOverride -> TxMeasure blk computeMempoolCapacity cfg st override = diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Impl/Common.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Impl/Common.hs index 677c0df27a..f4081ca49e 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Impl/Common.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Impl/Common.hs @@ -116,7 +116,7 @@ data InternalState blk = IS -- 'MempoolSnapshot' (see 'snapshotHasTx'). -- -- This should always be in-sync with the transactions in 'isTxs'. - , isLedgerState :: !(TickedLedgerState blk) + , isLedgerState :: !(TickedLedgerState blk EmptyMK) -- ^ The cached ledger state after applying the transactions in the -- Mempool against the chain's ledger state. New transactions will be -- validated against this ledger. @@ -163,7 +163,7 @@ data InternalState blk = IS deriving instance ( NoThunks (Validated (GenTx blk)) , NoThunks (GenTxId blk) - , NoThunks (TickedLedgerState blk) + , NoThunks (TickedLedgerState blk EmptyMK) , NoThunks (Diff blk) , NoThunks (TxMeasurePhase1 blk) , NoThunks (TxMeasurePhase2 blk) @@ -188,7 +188,7 @@ initInternalState :: TicketNo -> LedgerConfig blk -> SlotNo -> - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> -- | The tick diff (base → ticked state), the initial 'isLedgerDiff'. Diff blk -> InternalState blk @@ -214,7 +214,7 @@ newtype LedgerInterface m blk = LedgerInterface } data MempoolLedgerDBView m blk = MempoolLedgerDBView - { mldViewState :: LedgerState blk + { mldViewState :: LedgerState blk EmptyMK -- ^ The ledger state currently at the tip of the LedgerDB , mldViewGetForker :: m (Either GetForkerError (ReadOnlyForker m LedgerState blk)) -- ^ An action to get a forker at 'mldViewState' or an error in the unlikely @@ -311,7 +311,7 @@ tickLedgerState :: (UpdateLedger blk, ValidateEnvelope blk) => LedgerConfig blk -> ForgeLedgerState blk -> - (SlotNo, TickedLedgerState blk, Diff blk) + (SlotNo, TickedLedgerState blk EmptyMK, Diff blk) tickLedgerState _cfg (ForgeInKnownSlot slot st tickDiff) = (slot, st, tickDiff) tickLedgerState cfg (ForgeInUnknownSlot st) = (slot, tickedSt, tickDiff) @@ -392,7 +392,7 @@ revalidateTxsFor :: LedgerConfig blk -> SlotNo -> -- | The ticked ledger state against which txs will be revalidated - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> -- | The tick diff (base → ticked), to forward the read values to the tip Diff blk -> -- | All the inputs for the transactions, read against the base state @@ -445,7 +445,7 @@ computeSnapshot :: LedgerConfig blk -> SlotNo -> -- | The ticked ledger state against which txs will be revalidated - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> -- | The tick diff (base → ticked), to forward the read values to the tip Diff blk -> -- | All the inputs for the transactions, read against the base state diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Query.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Query.hs index 0802eed9bf..5d5fcf2c30 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Query.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Query.hs @@ -20,7 +20,7 @@ implGetSnapshotFor :: -- | Get snapshot for this slot number (usually the current slot) SlotNo -> -- | The ledger state at which we want the snapshot, ticked to @slot@. - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> -- | The tick diff (from the unticked state to @ticked@), used to forward the -- read values up to the ticked state. Diff blk -> diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Update.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Update.hs index dfb658f982..a5a3561f17 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Update.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Mempool/Update.hs @@ -539,7 +539,7 @@ pureRemoveTxs :: LedgerConfig blk -> SlotNo -> -- | The base ticked ledger state to revalidate against - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> -- | The tick diff (base → ticked), to forward the read values to the tip Diff blk -> -- | All the inputs for the kept txs, read against the base state @@ -696,7 +696,7 @@ pureSyncWithLedger :: LedgerConfig blk -> SlotNo -> -- | The base ticked ledger state to revalidate against - TickedLedgerState blk -> + TickedLedgerState blk EmptyMK -> -- | The tick diff (base → ticked), to forward the read values to the tip Diff blk -> -- | All the inputs for the txs, read against the base state diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client.hs index acca6f9ace..1e9615d0ba 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client.hs @@ -175,7 +175,7 @@ type Consensus data ChainDbView m blk = ChainDbView { getCurrentChain :: STM m (AnchoredFragment (Header blk)) , getHeaderStateHistory :: STM m (HeaderStateHistory blk) - , getPastLedger :: Point blk -> STM m (Maybe (ExtLedgerState blk)) + , getPastLedger :: Point blk -> STM m (Maybe (ExtLedgerState blk EmptyMK)) , getIsInvalidBlock :: STM m @@ -1759,7 +1759,7 @@ checkTime cfgEnv dynEnv intEnv = checkArrivalTime :: KnownIntersectionState blk -> arrival -> - WithEarlyExit m (Intersects blk (LedgerState blk, RelativeTime)) + WithEarlyExit m (Intersects blk (LedgerState blk EmptyMK, RelativeTime)) checkArrivalTime kis arrival = do Intersects kis' (lst, judgment) <- do readLedgerState kis $ \lst -> @@ -1782,14 +1782,14 @@ checkTime cfgEnv dynEnv intEnv = readLedgerState :: forall a. KnownIntersectionState blk -> - (LedgerState blk -> Maybe a) -> + (LedgerState blk EmptyMK -> Maybe a) -> WithEarlyExit m (Intersects blk a) readLedgerState kis prj = castM $ readLedgerStateHelper kis prj readLedgerStateHelper :: forall a. KnownIntersectionState blk -> - (LedgerState blk -> Maybe a) -> + (LedgerState blk EmptyMK -> Maybe a) -> m (WithEarlyExit m (Intersects blk a)) readLedgerStateHelper kis prj = atomically $ do -- We must first find the most recent intersection with the current @@ -1860,7 +1860,7 @@ checkTime cfgEnv dynEnv intEnv = -- that far into the future. projectLedgerView :: SlotNo -> - LedgerState blk -> + LedgerState blk EmptyMK -> Maybe (LedgerView (BlockProtocol blk)) projectLedgerView slot lst = let forecast = ledgerViewForecastAt (configLedger cfg) lst diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client/InFutureCheck.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client/InFutureCheck.hs index 33ecc8034f..76203dc7cd 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client/InFutureCheck.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/MiniProtocol/ChainSync/Client/InFutureCheck.hs @@ -54,6 +54,7 @@ import Ouroboros.Consensus.HardFork.History.Qry ) import Ouroboros.Consensus.Ledger.Abstract ( LedgerConfig + , EmptyMK , LedgerState ) import Ouroboros.Consensus.Util.Time @@ -81,7 +82,7 @@ data HeaderInFutureCheck m blk arrival judgment = HeaderInFutureCheck -- ^ This is ideally called _immediately_ upon the header arriving. , judgeHeaderArrival :: LedgerConfig blk -> - LedgerState blk -> + LedgerState blk EmptyMK -> arrival -> Except PastHorizonException judgment -- ^ Judge what to do about the header's arrival time. diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Node/ProtocolInfo.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Node/ProtocolInfo.hs index f0a0227c3c..52d4b2f7b9 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Node/ProtocolInfo.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Node/ProtocolInfo.hs @@ -11,7 +11,7 @@ import Data.Word import NoThunks.Class (NoThunks) import Ouroboros.Consensus.Block import Ouroboros.Consensus.Config -import Ouroboros.Consensus.Ledger.Basics (Values) +import Ouroboros.Consensus.Ledger.Basics (EmptyMK, Values) import Ouroboros.Consensus.Ledger.Extended import Ouroboros.Consensus.NodeId @@ -34,7 +34,7 @@ enumCoreNodes (NumCoreNodes numNodes) = -- | Data required to run the specified protocol. data ProtocolInfo b = ProtocolInfo { pInfoConfig :: !(TopLevelConfig b) - , pInfoInitLedger :: ExtLedgerState b + , pInfoInitLedger :: ExtLedgerState b EmptyMK -- ^ The ledger state at genesis. , pInfoInitLedgerTables :: Values b -- ^ The UTxO values at genesis, carried alongside 'pInfoInitLedger'. diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/API.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/API.hs index 9d628f254c..897572176e 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/API.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/API.hs @@ -92,6 +92,7 @@ import Ouroboros.Consensus.HeaderStateHistory ( HeaderStateHistory (..) ) import Ouroboros.Consensus.HeaderValidation (HeaderWithTime (..)) +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Ouroboros.Consensus.Ledger.Extended import Ouroboros.Consensus.Peras.Weight (PerasWeightSnapshot) import Ouroboros.Consensus.Storage.ChainDB.API.Types.InvalidBlockPunishment @@ -222,11 +223,11 @@ data ChainDB m blk = ChainDB -- to the chain it is on) -- -- INVARIANT @'hwtHeader' <$> 'getCurrentChainWithTime' = 'getCurrentChain'@ - , getCurrentLedger :: STM m (ExtLedgerState blk) + , getCurrentLedger :: STM m (ExtLedgerState blk EmptyMK) -- ^ Get current ledger - , getImmutableLedger :: STM m (ExtLedgerState blk) + , getImmutableLedger :: STM m (ExtLedgerState blk EmptyMK) -- ^ Get the immutable ledger, i.e., typically @k@ blocks back. - , getPastLedger :: Point blk -> STM m (Maybe (ExtLedgerState blk)) + , getPastLedger :: Point blk -> STM m (Maybe (ExtLedgerState blk EmptyMK)) -- ^ Get the ledger for the given point. -- -- When the given point is not among the last @k@ blocks of the current diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Args.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Args.hs index 6af16a3a69..5898bce3ed 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Args.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Args.hs @@ -170,7 +170,7 @@ completeChainDbArgs :: ResourceRegistry m -> TopLevelConfig blk -> -- | Initial ledger (the pure state together with its full table values) - (ExtLedgerState blk, Values blk) -> + (ExtLedgerState blk EmptyMK, Values blk) -> ImmutableDB.ChunkInfo -> -- | Check integrity (blk -> Bool) -> diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/ChainSel.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/ChainSel.hs index 2487a329e5..30499356d1 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/ChainSel.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/ChainSel.hs @@ -980,7 +980,7 @@ switchTo CDB{..} weights triggerPt chainDiff reason = MkSuccessForkerAction $ \f mkSelectionChangedInfo :: AnchoredFragment (Header blk) -> -- old selection ChainDiff (Header blk) -> -- diff we are adopting - ExtLedgerState blk -> -- new tip + ExtLedgerState blk EmptyMK -> -- new tip SelectionChangedInfo blk mkSelectionChangedInfo oldChain diff newTip = SelectionChangedInfo @@ -1001,7 +1001,7 @@ switchTo CDB{..} weights triggerPt chainDiff reason = MkSuccessForkerAction $ \f oldSuffix = AF.anchorNewest (getRollback diff) oldChain newSuffix = getSuffix diff - ledger :: LedgerState blk + ledger :: LedgerState blk EmptyMK ledger = ledgerState newTip summary :: History.Summary (HardForkIndices blk) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Query.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Query.hs index 9275a4a26f..7ad7422540 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Query.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Impl/Query.hs @@ -59,6 +59,7 @@ import Ouroboros.Consensus.HeaderStateHistory ( HeaderStateHistory (..) ) import Ouroboros.Consensus.HeaderValidation (HeaderWithTime) +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Ouroboros.Consensus.Ledger.Extended import Ouroboros.Consensus.Ledger.SupportsPeras (LedgerSupportsPeras (..)) import Ouroboros.Consensus.Peras.Weight @@ -283,11 +284,11 @@ getMaxSlotNo CDB{..} = do return $ curChainMaxSlotNo `max` volatileDbMaxSlotNo `max` queuedMaxSlotNo -- | Get current ledger -getCurrentLedger :: ChainDbEnv m blk -> STM m (ExtLedgerState blk) +getCurrentLedger :: ChainDbEnv m blk -> STM m (ExtLedgerState blk EmptyMK) getCurrentLedger CDB{..} = LedgerDB.getVolatileTip cdbLedgerDB -- | Get the immutable ledger, i.e., typically @k@ blocks back. -getImmutableLedger :: ChainDbEnv m blk -> STM m (ExtLedgerState blk) +getImmutableLedger :: ChainDbEnv m blk -> STM m (ExtLedgerState blk EmptyMK) getImmutableLedger CDB{..} = LedgerDB.getImmutableTip cdbLedgerDB -- | Get the ledger for the given point. @@ -298,7 +299,7 @@ getImmutableLedger CDB{..} = LedgerDB.getImmutableTip cdbLedgerDB getPastLedger :: ChainDbEnv m blk -> Point blk -> - STM m (Maybe (ExtLedgerState blk)) + STM m (Maybe (ExtLedgerState blk EmptyMK)) getPastLedger CDB{..} = LedgerDB.getPastLedgerState cdbLedgerDB allocInRegistryReadOnlyForkerAtPoint :: diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Init.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Init.hs index 8b84bb3d4d..6fe35b289c 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Init.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/ChainDB/Init.hs @@ -20,7 +20,7 @@ import Prelude hiding (map) data InitChainDB m blk = InitChainDB { addBlock :: blk -> m () -- ^ Add a block to the DB - , getCurrentLedger :: m (LedgerState blk) + , getCurrentLedger :: m (LedgerState blk EmptyMK) -- ^ Return the current ledger state } @@ -38,7 +38,7 @@ fromFull db = map :: Functor m => (blk' -> blk) -> - (LedgerState blk -> LedgerState blk') -> + (LedgerState blk EmptyMK -> LedgerState blk' EmptyMK) -> InitChainDB m blk -> InitChainDB m blk' map f g db = diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/API.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/API.hs index 47a4b94c04..9d9224aac6 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/API.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/API.hs @@ -263,8 +263,8 @@ import System.FS.CRC -- instantiated with a @blk@. type LedgerDbSerialiseConstraints blk = ( Serialise (HeaderHash blk) - , EncodeDisk blk (LedgerState blk) - , DecodeDisk blk (LedgerState blk) + , EncodeDisk blk (LedgerState blk EmptyMK) + , DecodeDisk blk (LedgerState blk EmptyMK) , EncodeDisk blk (AnnTip blk) , DecodeDisk blk (AnnTip blk) , EncodeDisk blk (ChainDepState (BlockProtocol blk)) @@ -273,13 +273,13 @@ type LedgerDbSerialiseConstraints blk = ) -- | The core API of the LedgerDB component -type LedgerDB :: (Type -> Type) -> (Type -> Type) -> Type -> Type +type LedgerDB :: (Type -> Type) -> StateKind -> Type -> Type data LedgerDB m l blk = LedgerDB - { getVolatileTip :: STM m (l blk) + { getVolatileTip :: STM m (l blk EmptyMK) -- ^ Get the empty ledger state at the (volatile) tip of the LedgerDB. - , getImmutableTip :: STM m (l blk) + , getImmutableTip :: STM m (l blk EmptyMK) -- ^ Get the empty ledger state at the immutable tip of the LedgerDB. - , getPastLedgerState :: Point blk -> STM m (Maybe (l blk)) + , getPastLedgerState :: Point blk -> STM m (Maybe (l blk EmptyMK)) -- ^ Get an empty ledger state at a requested point in the LedgerDB, if it -- exists. , getHeaderStateHistory :: @@ -367,7 +367,7 @@ data WhereToTakeSnapshot = TakeAtImmutableTip | TakeAtVolatileTip deriving Eq data TestInternals m l blk = TestInternals { wipeLedgerDB :: m () , takeSnapshotNOW :: WhereToTakeSnapshot -> Maybe String -> m () - , push :: l blk -> Diff blk -> m () + , push :: l blk EmptyMK -> Diff blk -> m () -- ^ Push a ledger state (together with the diff it produced), and prune the -- 'LedgerDB' to its immutable tip. -- @@ -499,7 +499,7 @@ data InitDB db m blk = InitDB , initReapplyBlock :: !(LedgerDbCfg ExtLedgerState blk -> blk -> db -> m db) -- ^ Reapply a block from the immutable DB when initializing the DB. Prune the -- LedgerDB such that there are no volatile states. - , currentTip :: !(db -> LedgerState blk) + , currentTip :: !(db -> LedgerState blk EmptyMK) -- ^ Getting the current tip for tracing the Ledger Events. , mkLedgerDb :: !(db -> m (LedgerDB' m blk, TestInternals' m blk)) @@ -800,7 +800,7 @@ class StreamingBackend m backend l blk where releaseSinkArgs :: SinkArgs m backend l blk -> m () type Yield m l blk = - l blk -> + l blk EmptyMK -> ( ( Stream (Of (TxIn blk, TxOut blk)) (ExceptT DeserialiseFailure m) @@ -811,7 +811,7 @@ type Yield m l blk = ExceptT DeserialiseFailure m (Maybe CRC, Maybe CRC) type Sink m l blk = - l blk -> + l blk EmptyMK -> Stream (Of (TxIn blk, TxOut blk)) (ExceptT DeserialiseFailure m) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Args.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Args.hs index 711a08ce28..49a5c7d7d3 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Args.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Args.hs @@ -52,7 +52,7 @@ type LedgerDbArgs :: Type data LedgerDbArgs f m blk = LedgerDbArgs { lgrSnapshotPolicyArgs :: SnapshotPolicyArgs - , lgrGenesis :: HKD f (m (ExtLedgerState blk, Values blk)) + , lgrGenesis :: HKD f (m (ExtLedgerState blk EmptyMK, Values blk)) , lgrHasFS :: HKD f (SomeHasFS m) , lgrConfig :: LedgerDbCfgF f ExtLedgerState blk , lgrTracer :: !(Tracer m (TraceEvent blk)) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Forker.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Forker.hs index e70955a2ae..53bd5bddd3 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Forker.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Forker.hs @@ -83,7 +83,7 @@ import Ouroboros.Consensus.Util.IOLike -- | An independent handle to a point in the LedgerDB, which can be advanced to -- evaluate forks in the chain. -- TODO @js split l in l blk -type Forker :: (Type -> Type) -> (Type -> Type) -> Type -> Type +type Forker :: (Type -> Type) -> StateKind -> Type -> Type data Forker m l blk = Forker { forkerClose :: !(m ()) -- ^ Close the current forker (idempotent). @@ -108,7 +108,7 @@ data Forker m l blk = Forker -- 'Ouroboros.Consensus.Storage.LedgerDB.V2.LedgerSeq.LedgerTablesHandle' and -- are surfaced to the LSQ server via a dedicated accessor. See -- 'EraRangeReader' and 'withEraRangeReader'. - , forkerGetLedgerState :: !(STM m (l blk)) + , forkerGetLedgerState :: !(STM m (l blk EmptyMK)) -- ^ Get the full ledger state without tables. -- -- If an empty ledger state is all you need, use 'getVolatileTip', @@ -119,7 +119,7 @@ data Forker m l blk = Forker -- Returns 'Nothing' if the implementation is backed by @lsm-tree@. , -- Updates - forkerPush :: !(l blk -> Diff blk -> m ()) + forkerPush :: !(l blk EmptyMK -> Diff blk -> m ()) -- ^ Advance the fork handle by pushing a new ledger state (and the diff it -- produced) to the tip of the current fork. , forkerCommit :: !(STM m (m ())) @@ -288,13 +288,13 @@ ledgerStateReadOnlyForker frk = -- - Forging loop. -- -- - Mempool. -type ReadOnlyForker :: (Type -> Type) -> (Type -> Type) -> Type -> Type +type ReadOnlyForker :: (Type -> Type) -> StateKind -> Type -> Type data ReadOnlyForker m l blk = ReadOnlyForker { roforkerClose :: !(m ()) -- ^ See 'forkerClose' , roforkerReadTables :: !(Keys blk -> m (Values blk)) -- ^ See 'forkerReadTables' - , roforkerGetLedgerState :: !(STM m (l blk)) + , roforkerGetLedgerState :: !(STM m (l blk EmptyMK)) -- ^ See 'forkerGetLedgerState' , roforkerReadStatistics :: !(m Statistics) -- ^ See 'forkerReadStatistics' @@ -457,7 +457,7 @@ switch withForkerAtFromTip evs cfg numRollbacks trace newBlocks doResolve onSucc -- 1. Are we passing the block by value or by reference? -- -- 2. Are we applying or reapplying the block? -type Ap :: (Type -> Type) -> (Type -> Type) -> Type -> Type +type Ap :: (Type -> Type) -> StateKind -> Type -> Type data Ap m l blk where ReapplyVal :: blk -> Ap m l blk ApplyVal :: blk -> Ap m l blk @@ -479,7 +479,7 @@ applyBlock :: Ap m l blk -> Forker m l blk -> ResolveBlock m blk -> - m (Either (AnnLedgerError l blk) (l blk, Diff blk)) + m (Either (AnnLedgerError l blk) (l blk EmptyMK, Diff blk)) applyBlock evs cfg ap fo doResolveBlock = case ap of ReapplyVal b -> withValues b (\vs l -> return $ Right $ tickThenReapply evs cfg b vs l) @@ -500,8 +500,8 @@ applyBlock evs cfg ap fo doResolveBlock = case ap of where withValues :: blk -> - (Values blk -> l blk -> m (Either (AnnLedgerError l blk) (l blk, Diff blk))) -> - m (Either (AnnLedgerError l blk) (l blk, Diff blk)) + (Values blk -> l blk EmptyMK -> m (Either (AnnLedgerError l blk) (l blk EmptyMK, Diff blk))) -> + m (Either (AnnLedgerError l blk) (l blk EmptyMK, Diff blk)) withValues blk f = do l <- atomically $ forkerGetLedgerState fo vs <- forkerReadTables fo (blockKeys blk) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Snapshots.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Snapshots.hs index e59dd5362a..35662ca603 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Snapshots.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/Snapshots.hs @@ -126,6 +126,7 @@ import GHC.Generics import NoThunks.Class import Ouroboros.Consensus.Block import Ouroboros.Consensus.Config +import Ouroboros.Consensus.Ledger.Basics (EmptyMK) import Ouroboros.Consensus.Ledger.Extended import Ouroboros.Consensus.Util (Flag (..), lastMaybe) import Ouroboros.Consensus.Util.Args (OverrideOrDefault (..), provideDefault) @@ -380,17 +381,17 @@ readExtLedgerState :: forall m blk. IOLike m => SomeHasFS m -> - (forall s. Decoder s (ExtLedgerState blk)) -> + (forall s. Decoder s (ExtLedgerState blk EmptyMK)) -> (forall s. Decoder s (HeaderHash blk)) -> FsPath -> - ExceptT ReadIncrementalErr m (ExtLedgerState blk, CRC) + ExceptT ReadIncrementalErr m (ExtLedgerState blk EmptyMK, CRC) readExtLedgerState hasFS decLedger decHash = do ExceptT . fmap (fmap (fmap runIdentity)) . readIncremental hasFS Identity decoder where - decoder :: Decoder s (ExtLedgerState blk) + decoder :: Decoder s (ExtLedgerState blk EmptyMK) decoder = decodeLBackwardsCompatible (Proxy @blk) decLedger decHash -- | Write an extended ledger state to disk @@ -398,15 +399,15 @@ writeExtLedgerState :: forall m blk. MonadThrow m => SomeHasFS m -> - (ExtLedgerState blk -> Encoding) -> + (ExtLedgerState blk EmptyMK -> Encoding) -> FsPath -> - ExtLedgerState blk -> + ExtLedgerState blk EmptyMK -> m CRC writeExtLedgerState (SomeHasFS hasFS) encLedger path cs = do withFile hasFS path (WriteMode MustBeNew) $ \h -> snd <$> hPutAllCRC hasFS h (CBOR.toLazyByteString $ encoder cs) where - encoder :: ExtLedgerState blk -> Encoding + encoder :: ExtLedgerState blk EmptyMK -> Encoding encoder = encodeL encLedger -- | Trim the number of on disk snapshots so that at most 'onDiskNumSnapshots' diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2.hs index e8f9bbf481..000b97c3a7 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2.hs @@ -240,13 +240,13 @@ implIntTruncateSnapshots snapManager (SomeHasFS fs) = do implGetVolatileTip :: (MonadSTM m, GetTip (l blk)) => LedgerDBEnv m l blk -> - STM m (l blk) + STM m (l blk EmptyMK) implGetVolatileTip = fmap current . getVolatileLedgerSeq implGetImmutableTip :: (MonadSTM m, GetTip (l blk)) => LedgerDBEnv m l blk -> - STM m (l blk) + STM m (l blk EmptyMK) implGetImmutableTip = fmap anchor . getVolatileLedgerSeq implGetPastLedgerState :: @@ -256,7 +256,7 @@ implGetPastLedgerState :: , StandardHash (l blk) , HeaderHash (l blk) ~ HeaderHash blk ) => - LedgerDBEnv m l blk -> Point blk -> STM m (Maybe (l blk)) + LedgerDBEnv m l blk -> Point blk -> STM m (Maybe (l blk EmptyMK)) implGetPastLedgerState env point = getPastLedgerAt point <$> getVolatileLedgerSeq env @@ -421,7 +421,7 @@ implCloseDB (LDBHandle varState) = do The LedgerDBEnv -------------------------------------------------------------------------------} -type LedgerDBEnv :: (Type -> Type) -> (Type -> Type) -> Type -> Type +type LedgerDBEnv :: (Type -> Type) -> StateKind -> Type -> Type data LedgerDBEnv m l blk = LedgerDBEnv { ldbSeq :: !(StrictTVar m (LedgerSeq m l blk)) -- ^ INVARIANT: the tip of the 'LedgerDB' is always in sync with the tip of @@ -473,7 +473,7 @@ data LedgerDBEnv m l blk = LedgerDBEnv deriving instance ( IOLike m , LedgerSupportsProtocol blk - , NoThunks (l blk) + , NoThunks (l blk EmptyMK) , NoThunks (LedgerCfg l blk) ) => NoThunks (LedgerDBEnv m l blk) @@ -482,7 +482,7 @@ deriving instance The LedgerDBHandle -------------------------------------------------------------------------------} -type LedgerDBHandle :: (Type -> Type) -> (Type -> Type) -> Type -> Type +type LedgerDBHandle :: (Type -> Type) -> StateKind -> Type -> Type newtype LedgerDBHandle m l blk = LDBHandle (StrictTVar m (LedgerDBState m l blk)) deriving Generic @@ -495,7 +495,7 @@ data LedgerDBState m l blk deriving instance ( IOLike m , LedgerSupportsProtocol blk - , NoThunks (l blk) + , NoThunks (l blk EmptyMK) , NoThunks (LedgerCfg l blk) ) => NoThunks (LedgerDBState m l blk) @@ -703,7 +703,8 @@ implForkerClose env = do newForker :: ( IOLike m - , NoThunks (l blk) + , BlockSupportsUTxOHD blk + , NoThunks (l blk EmptyMK) , GetTip (l blk) , StandardHash (l blk) ) => diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Backend.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Backend.hs index 41d10864d8..838699f98a 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Backend.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Backend.hs @@ -61,7 +61,7 @@ class NoThunks (Resources m backend) => Backend m backend blk where createAndPopulateStateRefFromGenesis :: Tracer m LedgerDBV2Trace -> Resources m backend -> - ExtLedgerState blk -> + ExtLedgerState blk EmptyMK -> Values blk -> m (StateRef m ExtLedgerState blk) diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Forker.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Forker.hs index cafe6c07a3..eee5ce5703 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Forker.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/Forker.hs @@ -53,7 +53,7 @@ data ForkerEnv m l blk = ForkerEnv deriving instance ( IOLike m - , NoThunks (l blk) + , NoThunks (l blk EmptyMK) ) => NoThunks (ForkerEnv m l blk) @@ -74,7 +74,7 @@ implForkerReadTables env ks = implForkerGetLedgerState :: (MonadSTM m, GetTip (l blk)) => ForkerEnv m l blk -> - STM m (l blk) + STM m (l blk EmptyMK) implForkerGetLedgerState = fmap current . readTVar . foeLedgerSeq implForkerReadStatistics :: @@ -88,7 +88,7 @@ implForkerReadStatistics env = do implForkerPush :: (IOLike m, GetTip (l blk), HasCallStack) => ForkerEnv m l blk -> - l blk -> + l blk EmptyMK -> Diff blk -> m () implForkerPush env newState diff = do diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/InMemory.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/InMemory.hs index 2786f57c4e..4cab85e588 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/InMemory.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/InMemory.hs @@ -127,7 +127,7 @@ implRead :: forall m l blk. (IOLike m, BlockSupportsUTxOHD blk) => Values blk -> - l blk -> + l blk EmptyMK -> Keys blk -> m (Values blk) implRead values _ keys = pure (restrictValues @blk keys values) @@ -152,7 +152,7 @@ implTakeHandleSnapshot :: (IOLike m, BlockSupportsUTxOHD blk) => Values blk -> HasFS m h -> - l blk -> + l blk EmptyMK -> String -> m (Maybe CRC) implTakeHandleSnapshot values hasFS _ snapshotName = do diff --git a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/LedgerSeq.hs b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/LedgerSeq.hs index 2cfedce093..4295dc02f7 100644 --- a/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/LedgerSeq.hs +++ b/ouroboros-consensus/src/ouroboros-consensus/Ouroboros/Consensus/Storage/LedgerDB/V2/LedgerSeq.hs @@ -109,7 +109,7 @@ data LedgerTablesHandle m l blk = LedgerTablesHandle -- ^ Create an duplicate of a handle. This will be used when opening read-only -- forkers and also to open the first handle for a forker used in chain -- selection. - , read :: !(l blk -> Keys blk -> m (Values blk)) + , read :: !(l blk EmptyMK -> Keys blk -> m (Values blk)) -- ^ Read values for the given keys from the tables, and deserialize them as -- if they were from the same era as the given ledger state. , readRange :: !(RangeReadTables m blk) @@ -117,7 +117,7 @@ data LedgerTablesHandle m l blk = LedgerTablesHandle -- @QFTraverseTables@ queries (see 'EraRangeReader' / 'withEraRangeReader'). -- The caller supplies the projection onto the current era @x@; see -- 'RangeReadTables' for the per-backend semantics and cursor contract. - , takeHandleSnapshot :: !(l blk -> String -> m (Maybe CRC)) + , takeHandleSnapshot :: !(l blk EmptyMK -> String -> m (Maybe CRC)) -- ^ Take a snapshot of a handle. The given ledger state is used to decide the -- encoding of the values based on the current era. -- @@ -170,17 +170,17 @@ mkEraRangeReaderProvider h batchSize = -- The table data lives entirely behind the 'LedgerTablesHandle', which the rest -- of the LedgerDB threads around backend-agnostically. data StateRef m l blk = StateRef - { state :: !(l blk) + { state :: !(l blk EmptyMK) , tables :: !(LedgerTablesHandle m l blk) } deriving Generic -deriving instance (IOLike m, NoThunks (l blk)) => NoThunks (StateRef m l blk) +deriving instance (IOLike m, NoThunks (l blk EmptyMK)) => NoThunks (StateRef m l blk) -instance Eq (l blk) => Eq (StateRef m l blk) where +instance Eq (l blk EmptyMK) => Eq (StateRef m l blk) where (==) = (==) `on` state -instance Show (l blk) => Show (StateRef m l blk) where +instance Show (l blk EmptyMK) => Show (StateRef m l blk) where show = show . state instance GetTip (l blk) => Anchorable (WithOrigin SlotNo) (StateRef m l blk) (StateRef m l blk) where @@ -196,10 +196,10 @@ newtype LedgerSeq m l blk = LedgerSeq } deriving Generic -deriving newtype instance (IOLike m, NoThunks (l blk)) => NoThunks (LedgerSeq m l blk) +deriving newtype instance (IOLike m, NoThunks (l blk EmptyMK)) => NoThunks (LedgerSeq m l blk) -deriving newtype instance Eq (l blk) => Eq (LedgerSeq m l blk) -deriving newtype instance Show (l blk) => Show (LedgerSeq m l blk) +deriving newtype instance Eq (l blk EmptyMK) => Eq (LedgerSeq m l blk) +deriving newtype instance Show (l blk EmptyMK) => Show (LedgerSeq m l blk) type LedgerSeq' m blk = LedgerSeq m ExtLedgerState blk @@ -212,7 +212,7 @@ empty :: ( GetTip (l blk) , IOLike m ) => - l blk -> + l blk EmptyMK -> init -> (init -> m (LedgerTablesHandle m l blk)) -> m (LedgerSeq m l blk) @@ -223,7 +223,7 @@ empty' :: ( GetTip (l blk) , IOLike m ) => - l blk -> + l blk EmptyMK -> Values blk -> (Values blk -> m (LedgerTablesHandle m l blk)) -> m (LedgerSeq m l blk) @@ -379,7 +379,7 @@ rollbackN n ldb -- >>> ldb = LedgerSeq $ AS.fromOldestFirst l0 [l1, l2, l3] -- >>> l3s == current ldb -- True -current :: GetTip (l blk) => LedgerSeq m l blk -> l blk +current :: GetTip (l blk) => LedgerSeq m l blk -> l blk EmptyMK current = state . currentHandle currentHandle :: GetTip (l blk) => LedgerSeq m l blk -> StateRef m l blk @@ -391,7 +391,7 @@ currentHandle = headAnchor . getLedgerSeq -- >>> ldb = LedgerSeq $ AS.fromOldestFirst l0 [l1, l2, l3] -- >>> l0s == anchor ldb -- True -anchor :: LedgerSeq m l blk -> l blk +anchor :: LedgerSeq m l blk -> l blk EmptyMK anchor = state . anchorHandle anchorHandle :: LedgerSeq m l blk -> StateRef m l blk @@ -405,7 +405,7 @@ anchorHandle = AS.anchor . getLedgerSeq -- >>> ldb = LedgerSeq $ AS.fromOldestFirst l0 [l1, l2, l3] -- >>> [(0, l3s), (1, l2s), (2, l1s)] == snapshots ldb -- True -snapshots :: LedgerSeq m l blk -> [(Word64, l blk)] +snapshots :: LedgerSeq m l blk -> [(Word64, l blk EmptyMK)] snapshots = zip [0 ..] . map state @@ -462,7 +462,7 @@ getPastLedgerAt :: ) => Point blk -> LedgerSeq m l blk -> - Maybe (l blk) + Maybe (l blk EmptyMK) getPastLedgerAt pt db = current <$> rollback pt db -- | Roll back the volatile states up to the specified point. @@ -533,8 +533,8 @@ immutableTipSlot = -- | Transform the underlying volatile 'AnchoredSeq' using the given functions. volatileStatesBimap :: AS.Anchorable (WithOrigin SlotNo) a b => - (l blk -> a) -> - (l blk -> b) -> + (l blk EmptyMK -> a) -> + (l blk EmptyMK -> b) -> LedgerSeq m l blk -> AS.AnchoredSeq (WithOrigin SlotNo) a b volatileStatesBimap f g =