Skip to content

Storage

Peerborne uses Helia (the JavaScript IPFS implementation) for content-addressed storage. For each change, it serializes the CRDT update, encrypts it with the document key (AES-GCM by default), and stores the resulting key ID, mode-specific encryption parameters, and ciphertext bytes in the local Helia blockstore. The CID addresses those encrypted bytes. A separate signed-when-enabled, encrypted CRDTSyncMessage carries the CID and shadow graph metadata. A stored document change also carries its author’s change signature; the stored payload has no parent links. A stored ACL change carries its author’s signature the same way; keychain payloads have no writer signature.

Each stored change payload is an opaque blob:

A Helia stored byte frame contains the document-key ID, mode-specific encryption parameters, and encrypted serialized CRDT change bytes. The CID sits outside the frame and addresses all of those bytes.
Stored payload: the CID addresses the complete encrypted byte frame from outside it.
View diagram at full sizeFit diagram to page

Stored bytes are immutable under their CID. The document’s current state is materialized by the CRDT layer using the separately exchanged shadow sync tree. Its frontier is the current set of unreferenced change CIDs. New local changes and delivered remote messages update that in-memory graph, while the CRDT layer resolves concurrent edits.

The encrypted wire message may carry history inline or defer it to Helia:

  • Inline: A CRDTChangeNode inside the encrypted CRDTSyncMessage carries the serialized CRDT change, allowing immediate application after any configured outer-signature check. A first load has no prior writer set for that check.
  • Deferred: A shadow-tree node carries its kind but omits the change bytes. If the receiver does not already know that CID, it fetches the separately encrypted stored payload and decrypts it. An ordinary sync message fetches at most eight payloads within 10 seconds of its first fetch, and closing the document aborts the fetches. Loads and invitations need every payload and give up on one when none of its bytes arrive for 10 seconds; a load stops at the first payload it cannot fetch. A GossipSub frame fetches only after its writer signature verifies and before it takes the document’s state queue, so local changes continue meanwhile. One frame fetches at a time, a frame waits at most 10 seconds for its turn, and the frames waiting to apply hold at most 64 MiB of prefetched payloads per document. A payload that cannot be fetched is a missing change. The message’s inline changes still apply, but a node that references a missing change is not held: later messages and catch-up replies are walked down to it again, and catch-up keeps asking for it, until the change arrives or an applied snapshot covers it. A later message that cites the CID again skips it for 15 seconds, doubling up to 5 minutes, after a failure.

A replica stores the blocks of its own changes and of the changes it fetched, but not of changes it received inline, whose encrypted payload never reached it. It therefore cites a recent tip without its change only when it stores the block. A remote tip it received inline is carried inline instead, with the delivered history that its tree does not carry yet, while the change and that history fit in the half frame a change may use. A replica keeps that history in memory for its recent tips, up to one such frame. This keeps every change a replica names fetchable from that replica, or carried in the frame, after the change’s author leaves.

A tip that cannot be carried is not cross-linked. This happens when its history does not fit, after a checkpoint restore, which does not keep that history, or when a change is recorded only once a later message delivers its dependency. A writer then takes a snapshot after its change, and catch-up replies, loads and invitations convey the tip through that snapshot. A member can hold every head such a writer names and still lack the tip, for example when a Yjs writer restored a checkpoint and its later edits, under a new client, do not depend on it. When a catch-up reply cannot carry the snapshot, the writer’s load notice tells the member whether it lacks some of the writer’s state, and the member loads.

Before a replica answers a load or builds an invitation bootstrap, it checks that it stores every block its tree cites without the change above its latest snapshot, and that its tree carries or cites every change it holds or its latest snapshot covers it. A writer that adopted another writer’s pruned tree fails the second check when the snapshot that covers the pruned changes never reached it. A checkpoint records which held changes the latest snapshot covers, so a writer restored from it does not fail the second check for history its snapshot already conveys. When a check fails, a writer takes a snapshot first, which recipients apply instead. A replica that still cannot serve a block its tree cites declines the load, and an inviter that still cannot convey every change rejects the invitation with an error, instead of leaving the recipient waiting or joining it with partial history. A snapshot covers document changes only: a reader or writer change that the tree no longer carries, such as one from a branch received just before a restore, still does not reach the new member.

Peerborne’s stored change payloads contain no graph links. Parent and cross-link relationships live in the separately signed-when-enabled, encrypted shadow tree, whose child map is keyed by stored-payload CIDs. Later sync messages can therefore add references to known CIDs without rewriting the stored ciphertext.

In the browser, Helia stores blocks in IndexedDB:

import { IDBBlockstore } from 'blockstore-idb';
import { IDBDatastore } from 'datastore-idb';
const blockstore = new IDBBlockstore('/peerborne-blocks');
// In practice, pass these via PeerborneConfig.helia to initialize()

The configured blockstore, datastore, and libp2p peer store use IndexedDB under the browser origin. Those backends retain encrypted blocks across a tab refresh, but Peerborne does not reconstruct a document from them: they hold neither the document keys nor the membership and CRDT state an instance needs to open. A document reopens locally only from a checkpoint the application saved.

Current status: Local block storage works in single-session tests. The password-manager example and Peerborne Note save encrypted, self-signed document checkpoints, and their CI suites reopen documents after a full Chromium relaunch with the same profile. This application-managed path restores keys, CRDT state, and membership before opening locally. Retaining blocks alone does not restore those things; other applications must test their own checkpoint path, and peer-assisted recovery remains unverified.

A checkpoint is a bounded, self-signed capture of one document instance’s local state. It holds the CRDT state, the reader and writer ACLs, BeeKEM membership state, and the raw document keys. Without one, a new peerborne.doc(path).open() after close() must load from a connected peer that holds the document; when no peer can serve it, open() rejects with No document state is available. Export a checkpoint after each committed change and restore it on a fresh instance before open():

// A non-extractable 256-bit AES-GCM key that the application keeps, for
// example in IndexedDB, separately from the checkpoints.
const storageKey = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
await document.change((doc) => doc.getMap('data').set('title', 'Saved'));
await saveCheckpoint(path, await document.exportEncryptedCheckpoint(storageKey));
// On the next start, before open():
const restored = peerborne.doc(path);
const saved = await loadCheckpoint(path);
if (saved) await restored.restoreEncryptedCheckpoint(saved, storageKey);
await restored.open();

saveCheckpoint and loadCheckpoint are application storage. exportEncryptedCheckpoint() seals the checkpoint with AES-GCM under the application’s key, with associated data that binds it to the document path and checkpoint format, so it restores only under that key, into that path, for the identity that signed it. Restoration rejects bytes sealed under another key or for another path, signed by another identity, or altered in any byte. Protect the storage key as well as the checkpoint, and never send either to another party. A checkpoint is local recovery for the identity that exported it, not a backup or sharing format.

exportPlaintextCheckpoint() returns the same checkpoint unencrypted: its payload is a binary record that holds the document’s state and its document keys. Use it only when the application encrypts it at once with its own authenticated format. The Peerborne Note, password-manager and wiki examples do this in browser-checkpoint-store.ts, which also binds a per-document revision so a stale save fails. Never store a plaintext checkpoint unencrypted and never transmit it.

A signature does not prove that a checkpoint is the latest one. To reject an older checkpoint that storage replays, keep the documentCheckpointCommitment(bytes) of the latest saved bytes outside the checkpoint store and pass it as the third argument of restoreEncryptedCheckpoint().

A checkpoint is also what a retired document instance reopens from. A Yjs or Loro instance retires when a change cannot be stored or signed, including after a transient IndexedDB write error or a cancelled remote or WebAuthn signer. A change that was committed locally but not delivered to peers, as reported to subscribeDeliveryFailures() handlers, exists only on this device, so export a checkpoint after each such change. Otherwise reopening loses it.

A change that did reach a member is not in an earlier checkpoint either. An instance reopened from that checkpoint gets it back only through catch-up, from an online member that still holds it, and the same holds for its reader and writer changes, such as a writer removal. A writer that holds the change replies with it, also when it sits on a branch concurrent with the writer’s own latest change. A reader cannot sign a reply, so every replica keeps in memory the encrypted frames that delivered its current heads, at most eight frames and 4 MiB per document. When a current writer’s verified sync request names a head the reader holds but not the root of a frame that writer signed, the reader publishes that frame again, byte for byte. Receivers decrypt it and verify its writer signature, actor binding and ACL changes as they did the original. A reader re-serves only frames the requester signed and that are encrypted under the current document key, one per request and at most one reply every 2 s, and never answers a reader or a removed writer this way.

The change stays missing while no member that holds it is online. A reader cannot return it after reopening itself, after dropping the frame for space, or when the change reached it in a load or a reply that carried a snapshot. An invitation delivers no change that way: the founder’s beforeAcceptance checkpoint is stored after the bootstrap is built, and before the founder answers the new member’s catch-up with changes made since that checkpoint, it runs beforeAcceptance again, so a founder reopened from its latest checkpoint already has them. A change the founder makes after that catch-up captured its state reaches the member as a frame, which the member keeps, even when it arrives before its invitation completes, and re-serves. A writer that keeps neither a concurrent branch’s delivered history nor its frame, as after its own restore, returns the branch only in its next change. Exporting a checkpoint after each change remains the only way to keep a change on the device that made it.

A checkpoint stores the document’s state once, in the CRDT’s own binary encoding, beside the latest snapshot it keeps to serve loads. When only a few changes follow that snapshot, it stores the snapshot and those changes. Otherwise it stores the full state as well: Automerge’s save(), or the Yjs or Loro update, which for Loro is about half the size of its snapshot. Applying many edits to a restored snapshot takes several times longer than restoring the full state, so Automerge uses the snapshot only when the changes after it are at most an eighth of its size, and Yjs at most a thirty-second. The checkpoint also holds the retained change tree, up to about 1.75 MiB, and the ACLs, document keys and membership state.

A checkpoint is limited to MAX_DOCUMENT_CHECKPOINT_BYTES, 64 MiB. With a recent snapshot, a checkpoint measured about 1.02 times the full-state snapshot for Automerge, Yjs and Loro documents of 50 to 60 MiB, so a document whose full-state snapshot is up to about 62 MiB checkpoints. When more than a few changes follow the latest snapshot, the checkpoint holds the snapshot and the full state, and the limit is about half that. An export over the limit rejects with DocumentCheckpointLimitError, whose byteLength and limit an application can show, and exports nothing. An application that saves only after a successful export, as Peerborne Note does, keeps its previous checkpoint and reports the failed save. Documents this large exceed the 10 MiB load response first.

Exporting holds the document’s state queue only while it captures the state, so a local change waits for that capture and not for the signature. Exports are signed and sealed one at a time and finish in the order they captured the state. Restoring an Automerge checkpoint loads a saved state instead of applying every change.

defaultConfig() opens the same IndexedDB blockstore (/peerborne-blocks) and datastore (/peerborne-data) in every tab of a browser origin. The datastore holds Helia pins, the libp2p peer store and one persisted libp2p key. Unless config.helia.libp2p.privateKey is set, the first running instance takes a Web Lock named after the datastore and uses that key, so a single tab keeps its PeerId across reloads. Any other instance running at the same time gets a new Ed25519 key for that session, so tabs are separate peers that can dial each other. Stopping the Helia node releases the lock. Where the Web Locks API is unavailable, every instance uses a new key. Other datastores, such as the in-memory default of defaultNodeConfig(), give the persisted key to one instance at a time within a JavaScript realm.

A PeerId only addresses a node. Document access is bound to signing keys, and online invitations already end when their creator restarts. Set a fixed key only when a specific PeerId is required, and never in two instances that run at the same time.

Sharing the stores leaves these caveats:

  • Each additional tab reserves its own relay slot, under a new PeerId on every load. A relay frees a reservation only when its TTL expires, so reloading additional tabs repeatedly can fill a relay with a small RELAY_MAX_RESERVATIONS.
  • Garbage collection (gcAfterPrune, off by default) protects only the retained history of the tab that runs it. It deletes only blocks that tab stored, but another tab may still need them for the same document.
  • Peerborne does not coordinate application storage between tabs. Two tabs that restore one signing identity are two peers of the same member, and the application must coordinate any checkpoints they both save. Peerborne Note and the password manager keep a same-profile Web Lock for this reason: their encrypted checkpoint store accepts a save only at the expected revision, so a second tab’s saves would be rejected as stale.

Evidence boundary: a Node test with an IndexedDB shim and Node’s Web Locks checks that one default-config instance keeps the persisted PeerId across restarts while concurrent instances get their own. Two tabs of one profile synchronizing in a real browser is not covered by CI.

Peerborne does not replicate blocks automatically. If you have 3 peers and one stores a block, the other 2 may fetch it on demand (bitswap) or may not. There is no “store on at least N peers” guarantee.

Pinning is not implemented. What is missing:

  • No authenticated document announcement protocol; PeerborneNode does not publish or subscribe to document announcements
  • No generic IPFS pinning client (e.g., to pin to a remote IPFS node, S3, or Filecoin)

Without pinning:

  • No peer can serve its copy while every holder is offline
  • If every local copy is cleared or otherwise unrecoverable, the document is lost
  • A dedicated “pinning node” (always-on peer) can serve as a poor substitute, but is not integrated

See the pinning cookbook for the integration checklist.

Two browser origins have separate local IndexedDB stores containing only payloads written or fetched there, while a relay forwards but does not retain document blocks; a recovery stack adds keys, graph and authentication context, writer authorization, and reader-membership state.
Durability depends on local copies plus keys, graph context, and authorization state.
View diagram at full sizeFit diagram to page

Evidence boundary: a stored encrypted block is only one recovery input. Full restart recovery, remote pinning, cross-peer block fetch, and recovery after compaction are not verified end to end. Clearing the last local copy or running garbage collection can make data unrecoverable.

The components a peer needs depend on what it needs to do:

A reader that needs to reconstruct document history may require:

  1. The block data — encrypted stored change payloads (from any peer or pinning service)
  2. The graph structure — which CIDs form the frontier and its ancestor chain (from the shadow sync graph)
  3. The document key history — per-epoch document encryption keys (AES-GCM by default)
  4. Authentication context — the relevant writer ACL/public keys together with a signed sync envelope or snapshot when that verification is available

These inputs do not by themselves authenticate responder-supplied shadow-tree node kinds or interior topology, nor do they prove that served history is complete. A quorum-bound first load has no prior writer set for authenticating the selected outer response and relies on its narrower frontier/CID checks.

To issue new changes, a peer additionally needs:

  1. Writer capability — current writer authorization, plus the ECDSA P-384 private key when ordinary document signing is enabled

To participate in dynamic group membership (add/remove readers), a peer additionally needs:

  1. The KEM state — BeeKEM key material and tree state, held in memory and carried across a restart only by a checkpoint (determining the set of active members requires this)
  1. Network reachability — connection to at least one peer that can serve missing blocks
  2. Q-of-K quorum — agreement from distinct currently connected peers on the served-frontier hash (enabled by default but configurable)

Losing any of these components may make the corresponding recovery path impossible. Key management and backup are application responsibilities.

Compaction summarizes the current CRDT state in a full-state snapshot and can prune older nodes from the in-memory shadow tree. Automatic compaction is off by default; writers can still request one directly with await document.snapshot();.

Each change embeds the retained tree as its parent, so the tree grows one level per change and serialization rejects trees deeper than 512 levels. Whatever the compaction settings, a writer whose retained tree reaches 256 levels takes a snapshot and prunes the tree to its 128 most recent inline changes, whatever keepRecentNodes says. Membership changes count toward that limit, and older ones stay attached as leaves. A peer that misses more changes than the retained tree holds cannot fill the gap from later messages; automatic catch-up fetches the writer’s snapshot with a sync request, or loads when the reply does not fit a frame. This runs after local changes, remote syncs and loads; readers do not snapshot. A CRDT provider without getSnapshot cannot compact, so its documents still stop accepting changes at 512 levels.

When compaction runs:

  1. The current CRDT state is serialized as a full snapshot
  2. Its state and boundary metadata are signed when signing is enabled
  3. It is included in a signed-when-enabled, encrypted load response rather than stored as a CID-addressed change payload
  4. Older nodes are pruned from the in-memory sync tree when pruneAfterSnapshot is enabled, and always for a depth-bound snapshot
  5. Eligible pruned blocks are scheduled for deletion only when both pruneAfterSnapshot and gcAfterPrune are enabled

A replica’s snapshot may be the only cover of history it pruned, so a replica replaces its snapshot only with one that includes it. Each snapshot lists, in its signed metadata, up to 32 earlier snapshots whose state it includes: the one its writer held and those it merged, with theirs. A snapshot that does not include the replica’s own is applied as well, and a writer then snapshots the merged state, which lists both. Two writers that each compacted while disconnected therefore exchange their snapshots through catch-up replies or loads, and each ends up holding a snapshot that covers both pruned histories. A reader cannot snapshot, so it keeps the snapshot with the higher compacted count and still applies the other’s state. A replica refuses a snapshot whose boundary is neither empty nor a canonical change CID, so a writer cannot send a snapshot that the replica’s checkpoints could not store.

Each document also remembers the CIDs of the changes it has seen, so it does not apply one twice. Writers and readers bound that memory with or without compaction. They keep the CIDs of the retained tree, the snapshot boundary, the recent tips and the newest 1,024 heads, plus every CID learned in the current generation of 1,024. Older CIDs are forgotten when the next generation fills, so the checkpoint of a long-edited document stays small and restorable. hasChange() and loadChangeBlock() report only remembered CIDs. A checkpoint export rejects any state that restoration would refuse, such as more than 100,000 remembered CIDs. An application that saves only after a successful export, as Peerborne Note does, keeps its previous checkpoint.

Snapshots can reduce replay work, but:

  • With pruning enabled, in-memory pruning does not delete Helia blocks unless gcAfterPrune is also enabled
  • A locally deleted block may still be fetchable from another provider, but there is no replication guarantee
  • A quorum-bound first load rejects a snapshot-only response because it has no prior writer set with which to authenticate the snapshot
  • When a first-load response carries a snapshot with its change tree, the snapshot is verified after the CID-addressed ACL blocks establish the writer set. If the agreed snapshot is not applied, the load fails instead of applying only the retained change tail

When pruneAfterSnapshot and the opt-in gcAfterPrune setting are both enabled, Peerborne asynchronously deletes eligible pruned blocks from the local Helia blockstore. It protects blocks still reachable from the retained tree and the snapshot boundary, but deletion is destructive for that local copy:

  • Deleted blocks disappear from that origin’s IndexedDB-backed blockstore
  • Recovery then depends on another reachable provider still holding the bytes
  • GC is disabled by default

A document deletes only blocks that it stored for its own changes while gcAfterPrune was on. Any writer can name an arbitrary CID in its change tree, and the blockstore is shared by every document on the node and by the application, so a pruned CID alone never makes its block deletable. Blocks fetched from peers, other documents’ blocks and application data stay in the blockstore. The document remembers at most 32,768 stored blocks; when that record is full, it forgets the oldest one, which then stays in the blockstore.

When the retained tree changes during a collection, the remaining blocks are checked again against the new tree and the collection continues, so a writer that keeps editing does not fall behind. A block that is still referenced or pinned, or that failed to delete, waits for the next prune or document.collectGarbage(); the first failure of each collection is logged with its cause. A node without a content router, such as a DHT, deletes blocks too: Helia refuses to cancel reproviding them, but such a node never provided them. The next checkpoint export records the stored blocks and the blocks still waiting, and an instance restored from that checkpoint deletes them at its next collection. Restoration refuses a checkpoint that lists a waiting block the document did not store. Blocks stored after the last export are recorded nowhere else and stay in the blockstore. Peerborne does not sweep the blockstore for them, because it is shared by every document on the node.

Verified in CI:

  • Block creation, storage, and retrieval in a single browser session
  • Encrypted existing history loaded through Circuit Relay
  • IndexedDB blockstore initialization and basic read/write
  • Password-manager and Peerborne Note identity and encrypted checkpoint restoration after browser relaunch

Not verified:

  • Browser restart and document recovery outside the Note and password-manager checkpoint paths
  • Multi-device and peer-assisted recovery
  • Compaction and GC with subsequent recovery
  • Pinning publisher integration
  • Remote block fetch (bitswap/HTTP) of blocks stored by a different peer