Lumoin.Verisync.Cbor
0.0.2
See the version list below for details.
dotnet add package Lumoin.Verisync.Cbor --version 0.0.2
NuGet\Install-Package Lumoin.Verisync.Cbor -Version 0.0.2
<PackageReference Include="Lumoin.Verisync.Cbor" Version="0.0.2" />
<PackageVersion Include="Lumoin.Verisync.Cbor" Version="0.0.2" />
<PackageReference Include="Lumoin.Verisync.Cbor" />
paket add Lumoin.Verisync.Cbor --version 0.0.2
#r "nuget: Lumoin.Verisync.Cbor, 0.0.2"
#:package Lumoin.Verisync.Cbor@0.0.2
#addin nuget:?package=Lumoin.Verisync.Cbor&version=0.0.2
#tool nuget:?package=Lumoin.Verisync.Cbor&version=0.0.2
<img style="display: block; margin-inline-start: auto; margin-inline-end: auto;" src="resources/lumoin-verisync-github-logo.svg" width="800" height="400" alt="Verisync project logo: A circular emblem in blue hues, two interlocking arrows forming a circular motion around the center evoking eventual convergence of replicas, followed by the wordmark 'verisync'.">
Lumoin.Verisync
A .NET stack for distributed state: conflict-free replicated data types, causal contexts, and leaderless consensus.
What is Verisync?
Verisync is a .NET library for distributed state synchronization without a central coordinator: conflict-free replicated data types, causal context tracking, and leaderless consensus. The library is designed so that wallets, edge devices, and services can share, merge, and reconcile state with strong eventual consistency, while exposing causality and conflicts as first-class concepts rather than implementation details.
The core value proposition is local-first state that converges across replicas. Each replica can read and write without waiting on a quorum; merges are deterministic and side-effect-free; causal history is preserved so that downstream consumers can reason about happens-before relationships and concurrent updates. Where a subset of operations genuinely needs linearizability, a leaderless consensus register provides it without electing a leader.
Verisync is designed to be a peer of credential, identity, and graph stacks rather than a dependency of any one of them. Replica identifiers, version vectors, and causal contexts are semantic types; nothing in the public API is a raw integer counter or a stringly-typed identifier.
Libraries
Key capabilities
State-based CRDTs with property-tested merges. Grow-only and positive-negative counters (GCounter, PNCounter), last-writer-wins and multi-value registers (LwwRegister, MvRegister), an observed-remove set (OrSet), and a replicated growable array for collaborative sequences (Rga). Every merge is a join-semilattice operation — commutative, associative, idempotent — verified with property-based tests.
Causal contexts as first-class types. Version vectors, dots, dotted version vectors, and dotted-version-vector sets are semantic types rather than dictionaries of opaque keys. Happens-before, concurrency, and observed-remove semantics are properties of these types, not ad-hoc comparisons in user code.
Serializable state. Every CRDT exposes ToState/FromState over pure, serialization-trivial records, so a host can persist state in any store — a database row, a message table, a blob — and reload and merge it later. AOT-safe JSON codecs for all state records ship in Lumoin.Verisync.Json.
Leaderless consensus. Classic CASPaxos and Fast CASPaxos registers: linearizable read-modify-write without leader election. The fast path commits in a single round trip when uncontended; contention falls back to a classic recovery round that tallies the fast-round winner. The protocol layer is message-driven, so the same proposer and acceptor run over in-process calls, in-memory channels, or sockets.
Authenticated register and log replay. A layer above consensus for cryptographically accumulated history: entry classification, chain-integrity verification, proof validation, and state folding are injected by the application, so the layer carries any proof scheme without baking one in.
Pluggable transport. The channel seam is System.IO.Pipelines with serialization injected as delegates: length-prefixed frames over any duplex byte stream. JSON and CBOR implementations are provided; the library does not own sockets, schedulers, or clocks.
Disciplined memory. Byte payloads rent from an exact-size slab pool (VerisyncMemoryPool) wired to OpenTelemetry metrics and traces, and pooled memory is always deterministically returned. Small fixed-size identifiers such as ReplicaId are inline value types — no allocation, a mechanical mapping to [u8; 32] if a Rust port is ever written.
Architecture principles
Verisync follows the same data-oriented principles as the rest of the family: code is separate from immutable data, CRDTs are values rather than entities with hidden identity, and merges are pure functions. Domain types are agnostic to serialization format; encoding lives at serialization boundaries in the dedicated Lumoin.Verisync.Json and Lumoin.Verisync.Cbor packages.
Transport, persistence, and clock sources are wired through delegates rather than interfaces. The same CRDT or consensus register is tested against a synthetic in-memory transport — including a deterministic interleaving bench that explores message reorderings from a seed — and deployed against a real transport without changes at the call site.
Getting started
Install the packages relevant to your use case:
# Core primitives: CRDTs, causal contexts, consensus.
dotnet add package Lumoin.Verisync.Core
# JSON serialization for state records and protocol messages.
dotnet add package Lumoin.Verisync.Json
# CBOR serialization for channel messages.
dotnet add package Lumoin.Verisync.Cbor
Development
The codebase runs on Windows, Linux, and macOS.
Press . on the repository page to open the codebase in VS Code web editor for quick exploration.
Vulnerability disclosure
Please report suspected security vulnerabilities privately through GitHub security advisories, not through public issues.
Contributing
Open issues for bugs, suggestions, or improvements, or create pull requests. Especially welcome:
- Convergence and commutativity tests using property-based testing.
- New CRDT shapes or transport adapters.
- Improvements to causal-history reasoning and delivery-interleaving test scenarios.
Acknowledgements
Work of Reuben Bond on Fast CASPaxos and the CASPaxos write-up has influenced the design of this library. Verisync's leaderless consensus follows the shape laid out there: a value-agnostic, rewritable register; the fast-round optimization that lets any proposer commit in one round trip when uncontended, recovering through a classic ballot under contention; and a message-driven acceptor/proposer split with the transport injected. The reference implementation, paper, and TLA+ model in that repository were the load-bearing guide for the ballot ordering and recovery logic.
License
See the LICENSE file for details.
Note: This library is under active development ahead of its first release. APIs may change between versions.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Lumoin.Verisync.Core (>= 0.0.2)
- System.Formats.Cbor (>= 10.0.9)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.0.16 | 185 | 11/11/2026 |
| 0.0.15 | 131 | 10/18/2026 |
| 0.0.14 | 144 | 9/15/2026 |
| 0.0.13 | 134 | 9/2/2026 |
| 0.0.12 | 130 | 9/2/2026 |
| 0.0.11 | 124 | 9/1/2026 |
| 0.0.10 | 162 | 8/23/2026 |
| 0.0.9 | 141 | 8/15/2026 |
| 0.0.8 | 134 | 8/14/2026 |
| 0.0.7 | 146 | 7/29/2026 |
| 0.0.6 | 143 | 7/13/2026 |
| 0.0.5 | 153 | 7/2/2026 |
| 0.0.4 | 133 | 6/28/2026 |
| 0.0.3 | 153 | 6/15/2026 |
| 0.0.2 | 150 | 6/11/2026 |
| 0.0.1 | 139 | 6/9/2026 |
Changes since version 0.1.0
Changed:
- `CheckpointedSequence.Promote` proposes a `CheckpointCommitment` — the digest of the snapshot's
canonical bytes — through the CASPaxos register instead of the snapshot itself. Consensus payloads
stay metadata-sized regardless of sequence length; the content stays local and travels the CRDT
plane, verifiable against the agreed commitment. `Create` takes the canonicalize and digest
delegates; the register type is `CasPaxosRegister<CheckpointCommitment>`.
- `ConsensusNode.RunAsync` takes the reply sink as the named `SendReplyDelegate<TValue>` instead of
a naked `Func`, matching the named-seam convention. Source-compatible: lambdas and method groups
at existing call sites convert unchanged.
Fixed:
- Fast CASPaxos acceptor safety: accepting now raises the promise to the accepted ballot, so a stale
lower-ballot accept can no longer regress acceptor state past a possibly-chosen value; fast ballots
are accepted only while they equal the acceptor's promise and prepares are classic-only, so only the
pre-promised initial fast round is blind-writable. Retry a contended fast write with the same fast
ballot and value, or complete it through classic recovery.
- `Rga` insert identities are assigned Lamport-style (`VectorClock.IncrementPastAll`), restoring
intention preservation: an insert-after now lands immediately after its predecessor instead of
potentially behind older sibling subtrees observed from other replicas. Sibling orders involving
pre-existing concurrent inserts may differ from earlier versions.
Security:
- Counter and clock arithmetic is checked: `GCounter.Increment`, `VectorClock.Increment`, and
`VectorClock.IncrementPastAll` throw `OverflowException` instead of wrapping (a wrapped counter is
silently rejected by max-merge forever); classic `Ballot` validates its round at construction.
`FromState` rejects what no honest history produces: negative counts (counters, clocks), zero-count
entries are filtered (restoring `Equals`/`GetHashCode` consistency), dotted-version-vector-set dots
must sit within their causal context, and RGA states with missing predecessors or predecessor
cycles are rejected rather than silently dropping vertices from traversal. Tombstones for absent
dots remain accepted and documented.
- The JSON channel deserializer is strict: a payload that is the JSON literal `null` and any payload
with trailing data after the message are rejected with `JsonException` — many-bytes-to-one-message
laxity breaks canonical-bytes assumptions near digest-relevant content.
- `TaggedMemory` equality members fail closed after dispose; the memory pool validates slab sizing
before allocation (no more wrapped products), disposes its rental activity on a throwing rent,
makes owner double-dispose idempotent, and keeps the active-rentals gauge paired across pool
shutdown races.
- `MessageChannelReader` rejects frames whose declared payload exceeds a configurable maximum
(16 MiB default) instead of buffering toward a hostile four-byte length prefix;
`MessageChannelWriter` fails fast on oversized payloads. The reader completes its pipe even when
deserialization throws.
- The JSON CRDT-state deserializers validate untrusted input: replica ids must decode to exactly
`ReplicaId.Size` bytes, replica counters cannot be negative, and dot counters start at one.
Added:
- `OffsetAnchoredSequence<TValue>` and `OffsetAnchor`, registered as `verisync.sequence.offset.v1`:
the checkpoint-offset sequence strategy — collaborative edits over an immutable, consensus-agreed
base snapshot, with anchors as stable base offsets or live dot identities and the same Lamport
intention-preservation rule as the RGA strategy. Merging is generation-aligned and fails closed
across differing bases. Passes the full shared law harness.
- Waterline compaction for the checkpoint-offset strategy: `OffsetAnchoredSequence<TValue>.Compact`
collapses stable visible vertices into the next base generation against an agreed
(frontier, checkpoint) pair and fails closed on a misaligned pair. Stable tombstones with surviving
descendants persist as position ghosts and removed base entries are always carried, so visible
order survives compaction; every survivor outside a surviving subtree re-anchors at its gap anchor
(the nearest preceding new-base entry), which the Lamport counter invariant keeps order-preserving
and replica-independent. `TranslateAnchor` serves previous-generation anchors from dot- and
offset-translation maps that compose across generations, so dot anchors stay translatable
indefinitely while base anchors serve exactly the one-generation window the stability rule permits.
The shared law harness gains the two remaining compaction laws — compact/merge commutation at or
above the frontier and anchor servability across compaction — and the
`TranslateAnchorDelegate` now receives the sequence, since translation maps are strategy state.
- `verisync.sequence.rga-rle.v1` (`WellKnownSequenceStrategies.CreateRgaRle`): the compactable RGA
strategy — identical RGA semantics and identifiers, plus ghost-based waterline compaction with no
re-anchoring of any kind. A stable tombstone persists as a ghost while any descendant survives;
only recursively childless stable tombstones drop (head-anchored ones never do, since no element
exists to translate to), so the visible order provably never changes. `Rga<TValue>.Compact`
verifies the agreed checkpoint against the stable visible content fail-closed, and
`TranslateAnchor` serves dropped dots from a translation map that composes across generations.
`ToRunState`/`FromRunState` add the run-length serialized state — maximal same-replica
predecessor-chained vertex runs, per-replica tombstone spans, and translation entries, validated
fail-closed on reconstruction — while `ToState` now refuses to serialize an instance carrying
translations rather than silently dropping them. Both compaction strategies pass the same four
shared compaction laws.
- Serialization for both compaction strategies: `OffsetAnchoredSequence<TValue>.ToState`/`FromState`
with the `OffsetAnchoredSequenceState` record family (vertices with anchors, removed offsets, and
both translation maps; deterministic replica-major output; reconstruction validates anchors,
ranges, duplicates, and anchor-graph acyclicity fail-closed), and `CrdtStateJson` codecs for
`OffsetAnchoredSequenceState` and `RgaRunState` — hand-written and AOT-safe like the existing
state codecs, with codec-level shape validation (`JsonException`) layered under the state-level
relational validation (`ArgumentException`).
- Fast CASPaxos next-ballot piggybacking: a successful accept may carry the next fast ballot, raising
the acceptor's promise to it and establishing the next fast round coordinator-free — recurring
one-round-trip fast commits, as in the original design. All reject rules ignore the piggyback, the
promise only ever rises, and an acceptor that never saw the piggyback keeps rejecting that fast
round via the equality rule, so blind writes at un-established rounds remain impossible. The wire
encoding's `next` field is optional and back-compatible.
- The Raft production story around the safety core: `RaftNode.ToState`/`FromState` with
`RaftNodeState` (the Figure 2 durable triple, validated fail-closed on restore; a restored node is
a follower at commit zero rediscovering the volatile commit index), `RaftRunner` — a
single-consumer message-driven loop preserving the node's single-threaded contract with the
universal handle → persist → apply → send sequencing, named seams
(`SendRaftEnvelopeDelegate`, `PersistRaftStateDelegate`, `ApplyCommittedDelegate`), host-triggered
elections and heartbeats (still no timers or entropy in the library), propose with a faulting task
on non-leaders, and self-quiescing follower catch-up off append replies — plus `RaftJson` wire
codecs for the envelope and the durable state, mirroring the consensus message codecs' strictness.
Apply is exactly-once per process lifetime and at-least-once across restarts, documented on the
seam. Proven over real localhost sockets: election, replication, identical applied sequences on
every node, and a follower restarted from its persisted state converging after reconnect.
- A naive, safety-correct, in-memory Raft node (`RaftNode<TCommand>` and its message records): the
complete Figure 2 safety core — election restriction, log matching with conflict truncation and
idempotent re-delivery, and the current-term commit rule — with liveness explicitly external
(host-triggered elections, no timers). The within-trust-domain log-replication primitive
complementing the register (metadata-grade anchors) and the CRDT plane (no ordering). The test
suite was authored blind against the same specification and includes the Figure 8 scenario.
- `StabilityFrontier`, `CompactSequenceDelegate`, `TranslateAnchorDelegate`, and a `Compact` step on
`CheckpointedSequence`: the waterline seams — the frontier (element-wise group minimum, in-library
because a silent member must pin the floor) is the WHEN of compaction, the agreed checkpoint the
WHAT; the first two compaction laws wait in the shared harness for the first compacting strategy.
- A shared sequence-strategy law harness in the test suite: every registered strategy inherits the
join-semilattice laws, merge-order convergence, and local intention preservation as property tests
exercised through the strategy context — the contract future strategies (including the compaction
strategies) are built against. The RGA strategy is the first registration.
- `PersistAcceptorDelegate<TValue>` and an optional durability hook on `ConsensusNode.RunAsync`:
when supplied, the acceptor state is made durable after every state-changing request and before the
matching reply is sent, so an unpersisted promise is never observable — the documented crash-safety
contract is now a seam instead of a caller obligation. A throwing hook fail-closes the reply.
- `SequenceCrdtContext<TSequence, TValue, TAnchor>` with named operation delegates and
`WellKnownSequenceStrategies`: the sequence CRDT behind `CheckpointedSequence` is now pluggable.
A strategy (addressing model, merge, ordering) is injected as a delegate bundle and named by a
stable identifier that is part of the document's replication contract — merging containers carrying
different strategy identifiers fails closed, since mismatched strategies silently diverge.
`CheckpointedSequence<TValue>` became `CheckpointedSequence<TSequence, TValue, TAnchor>` created
via `Create(context)`; the RGA-backed strategy (`verisync.sequence.rga.v1`) is the first
registration and preserves the previous behavior exactly.
- `FramePadding`: opt-in padded framing for the message channel. Frames are padded up to size
buckets (powers-of-two or fixed ladders) with an inner real-length prefix, so a network observer
cannot distinguish message types or content sizes within a bucket — a metadata-privacy measure
from the sealed-segments design. The unpadded wire format is unchanged byte for byte; both
endpoints must share the policy, and the attacker-influenced inner length is never trusted past
the frame bounds.
- `LogCommitmentJson`: hand-written AOT-safe JSON codecs for `LogHead`, `MerkleInclusionProof`,
`MerkleConsistencyProof`, and `SegmentSeal<TProof>`, so heads, proofs, and seals can cross a
message channel. The seal deserializer re-derives the canonical bytes and digest through
`SegmentSeal.Create` and fails closed on a digest mismatch, so a tampered seal is rejected at the
codec.
- `MerkleFrontier`: the bounded-state companion to `MerkleLogTree` — an append-only root tracker
holding only the O(log n) frontier peaks, producing roots byte-identical to the full tree (verified
by an exhaustive size sweep against it). Proofs still come from `MerkleLogTree` over archived
leaves; the frontier is how a live replica tracks its root without holding history.
- `LogHead` and `LogHeadConsistency`: the log-plane anti-equivocation exchange. A head claims a tree
size and root; `LogHeadConsistency.Verify` binds a `MerkleConsistencyProof` to exactly the two
heads before trusting it and reduces a failure between authentic heads to portable fork evidence.
In the single-tree composition a `SegmentSeal` whose commitment is the tree root at its boundary is
an attested head, so consecutive seals prove their own consistency.
- `SegmentSeal<TProof>` with `AttestSealDelegate` and `VerifySealAttestationDelegate`: sealed log
segments — a versioned, byte-for-byte pinned commitment to a contiguous entry range, chained by seal
digest with in-library link verification (digest linkage, index continuity, genesis rules).
Attestation evidence covers the seal digest and rides outside the digested bytes. Combined with an
`AuthenticatedRegister` whose accumulator is a `MerkleLogTree` folding entry digests, sealing a
segment is reading the accumulator root, and per-entry membership in a sealed segment is provable
with a `MerkleInclusionProof` alone.
- `MerkleLogTree`, `MerkleInclusionProof`, and `MerkleConsistencyProof`: an RFC 9162 (Certificate
Transparency v2) append-only Merkle log tree with inclusion and consistency proofs, hash-agnostic
through `ComputeDigestDelegate` with structural `0x00`/`0x01` domain separation. The documented
byte layout is a cross-stack contract; the test suite pins the canonical RFC 6962 SHA-256 vectors.
This is the foundation for sealed log segments and bounded logs.
- `VectorClock.IncrementPastAll`: a Lamport-style advance whose new counter exceeds every observed
counter.
- Documented contracts: `ConsensusNode` durability obligations across restarts, the CASPaxos
"a failed change may still be chosen" retry caveat on `ChangeOutcome`, the full verification
obligations of `VerifyChainIntegrityDelegate`, and the non-associativity of the
`DottedVersionVector` dot component.
See full changelog at https://github.com/lumoin/Verisync/blob/main/CHANGELOG.md.