P-LensOpen the app

P-Lens Engineering Notes

Encrypted ledger sync over Nostr

Based on the Japanese article “サーバーを捨てたかったのに、共有にはサーバーが必要だった話”, restructured for readers outside Japan.

A local-first app keeps a personal ledger on the device. The ledger never needs a server: it is written, read and totalled in the browser, and it works offline. Then two things happen, as they always do. The owner wants the same ledger on a phone and a laptop, and a few friends want to keep one ledger together. Both need somewhere for one device to leave changes and another to pick them up later. The requirement this article is about is that this somewhere learns nothing about what is in the ledger.

P-Lens solves this by sealing every change on the device and carrying it as ordinary Nostr events, so that any Nostr relay that passes a conformance suite can carry a ledger. The rules for doing so are written down as a protocol called PLN-1. This article walks through it with the real code: the event kinds and tags, the keys, the encryption, the merge, who decides which changes count, and what the relay can still see.

All code is quoted as it is from p-lens at v0.10.63 (GPL-3.0) and p-lens-relay at f9c4fa8 (MIT), which also holds the protocol, PROTOCOL.md.

The app, for readers who have never been to a pachinko parlor

Pachinko and pachislot are machine games played in pachinko parlors across Japan. A player rents balls (pachinko) or tokens (pachislot) with cash, plays them in a machine, and at the end takes whatever is left to the counter. In Japan, you cannot cash out at the pachinko parlor: the law does not let a parlor pay out cash or buy back the prizes it gives, so at the counter balls are exchanged only for prizes, and a separate prize exchange shop nearby buys the special prizes (特殊景品, to-ku-shu kay-hin) for cash. With a wholesaler that sells those prizes back to the parlor, the arrangement is known as the three-shop system (三店方式, sahn-ten hoh-shi-ki); a separate article goes through it from the start.

Diagram of the three-shop system. The player gives the pachinko parlor cash and rents balls, and at the end of play gives the leftover balls to the parlor’s counter for prizes; inside the parlor no step turns balls into cash. The player sells special prizes for cash at a prize exchange shop, a separate business nearby, which sells them to a wholesaler, who sells them back to the parlor.

Instead of exchanging, a player can leave the balls on deposit with the parlor and play them on another day. That deposit is a balance at one parlor only: balls saved at マレハン東京皇国第8支店 (a fictional parlor; read Ma-re-han Toh-kyoh Koh-ko-ku Dai-ha-chi Shi-ten, “Marehan, Tokyo Empire, Branch No. 8”) cannot be played at 723豚の帽子亭店 (a fictional parlor; read Shi-chi-nissan Buta-no-boh-shi-tei, “723, the Pig’s Hat Tavern”). Both names come from the app’s test fixtures.

P-Lens is a bookkeeping app for a player’s own results. Its ledger is hledger, the plain-text accounting tool, compiled to WebAssembly and run in a worker in the browser. Each parlor’s balls at each rental rate are a commodity of their own, because they cannot be exchanged for each other, and a parlor’s exchange rate is a price directive that is only ever added, never edited. The book of record is a set of journal files on the device; exported, they open in desktop hledger as they are.

The project’s ARCHITECTURE.md states the starting point as an invariant:

Everything works offline. The engine and the app shell are precached; no backend is needed to start, read or write.

That is the whole story as long as one person uses one device. The rest of this article is about what happens when they don’t: someone records on a phone in the parlor and reads the totals on a laptop at home, and some players keep a team book, pooling their money and results with friends (ノリ打ち, no-ri-u-chi, team play). In the examples below, 🐪マイ帳簿 (“my book”) is one person’s ledger on two devices, and 🚀チーム帳簿 (“team book”) is shared with a teammate who goes by すばやいおサル (“quick monkey”).

Why a server came back

A browser cannot talk to another browser on its own. WebRTC can connect two of them, but it needs a signaling server to find the other side, a relay server when NAT gets in the way, and both devices running at the same time. A phone in a parlor and a laptop switched off at home never meet. Something has to hold what one device leaves until the other comes for it. That is a server.

What the app did not give up was the original rule: the operator does not hold anyone’s results. The way to have both is to give the server only what it cannot read. Changes are sealed on the device, the keys never leave the devices, and the server becomes a courier for boxes it cannot open.

The first courier was written from scratch: about 400 lines on Cloudflare Workers and D1 (v0.9.0), one queue per book, devices polling it for anything new. The design was sound; the bill was the problem. Polling asks even when nothing has happened, and every ask is a billed request. The screen that shows a team’s live plays asked every 30 seconds (READ_EVERY in v0.9.118), so a teammate’s result arrived up to 30 seconds late, and making that a few seconds meant ten times the requests: everyone opening an empty mailbox every few seconds, and paying for each look.

In v0.10.0 the courier was replaced by a Nostr relay. Devices keep a WebSocket open and are told when something arrives. The official relay runs as Cloudflare Workers in front of Durable Objects, which hold the sockets by WebSocket hibernation and sleep between messages. In the measurements the Japanese article reports, on a day two people ran the team screen for nine hours, the Durable Objects were awake for about one minute in total. The Japanese article has the cost estimates, and the part where the new relay turned out to write about 13 times as many database rows per person-hour as the old one: subscriptions were rewritten every time a phone reconnected, and replacing an event touched every index, each of which counts as a written row. Keeping subscriptions on the sockets themselves, updating replaceable events in place in a table of their own, and dropping indexes no read used brought it down to about 15 rows per person-hour.

PLN-1: the relay carries, the devices decide

A Nostr event is a signed JSON object: kind, created_at, tags, content, the author’s public key pubkey, and a BIP-340 Schnorr signature over secp256k1 sig. A relay stores events and hands back the ones matching a filter. PLN-1 is a set of rules for what P-Lens writes into those events. It carries four things:

Product What it carries
Book sync a book between its owner’s devices, and the owner’s live plays between them
Book sharing the same book to editors and viewers the owner invites
Sending plays sent by invited senders to a book’s inbox
Huddles people playing together on one day, each shown the others’ plays

The protocol’s design fits in one paragraph near the top of PROTOCOL.md:

A relay carries; it never decides. Every device keeps the whole of what it has, and a relay that loses, reorders, repeats or withholds events makes a device late, never wrong.

So PLN-1 asks a relay for nothing beyond ordinary Nostr: NIP-01 (EVENT, REQ, CLOSE, EOSE, OK, CLOSED), NIP-09 deletion, events of at least 48,000 bytes, filters by ids, authors, kinds, #v, #d, since, until, and no NIP-42 AUTH required to read or write (§2.1). The official relay runs the p-lens-relay code, but any relay that passes testing/conformance can carry a book, including relays written with no thought of P-Lens, such as strfry and nostr-rs-relay.

Event shapes: nine kinds and three tags

Kind Class Author Tags Content
4738 regular owner, editor v a change, a base’s manifest, or a part
34738 addressable owner, editor v, d a device’s tip: the changes it is at
34742 addressable owner v, d the access list, in plain text
34743 addressable owner v, d a mailbox for one invited person
34739 addressable owner v, d, expiration a live play’s copy
34740 addressable sender v, d, expiration a sent play’s latest state
34741 addressable huddle participant v, d, expiration a play shown to a huddle, or leaving it
28934 ephemeral owner, participant claim, v a ticket redeemed for paid sync
5 regular (NIP-09) the author e deleting one’s own events

There are three tags. v says which line an event belongs to, d is its place on that line for an addressable event, and expiration (NIP-40) says when the relay may let it go. v and d are 32 hex digits derived from secrets, and nothing in them reads back as an id, a date or a name.

The p-lens-relay gate refuses anything not shaped like this, in every mode, the moment it arrives. From packages/gate/src/shape.ts:

/** The tags a kind carries, each exactly once, and nothing else; and what its content is. */
type Shape = { readonly tags: readonly string[]; readonly content: Content }

const SHAPES: Readonly<Record<Exclude<KindName, "deletion">, Shape>> = {
  bookChange: { tags: ["v"], content: "sealed" },
  tip: { tags: ["v", "d"], content: "sealed" },
  accessList: { tags: ["v", "d"], content: "access-list" },
  mailbox: { tags: ["v", "d"], content: "sealed" },
  playCopy: { tags: ["v", "d", "expiration"], content: "sealed" },
  sentPlay: { tags: ["v", "d", "expiration"], content: "sealed" },
  huddleState: { tags: ["v", "d", "expiration"], content: "sealed" },
  redemption: { tags: ["v", "claim"], content: "empty" },
}

sealed checks only the outside of the box: base64, the version byte 0x01 first, and a length NIP-44’s padding can produce. The relay cannot read the content, so it checks its shape. The point is that a bug on a device does not end up as plain text in the relay’s storage.

One 32-byte secret instead of an account

PLN-1 has no usernames and no passwords. It has secrets, each 32 random bytes:

Secret Held by Derives
S, a book’s sync secret the owner’s devices the owner’s signing key O, a vault only the owner reads, the lines for live plays
E_n, a book’s epoch secret owner, editors, viewers the key the book is sealed with, and the book line’s v
m, one per invitation the person invited an editor’s signing key M, a sender’s X, a mailbox
h, one per huddle everyone who scanned its QR code that day’s seal key and line

Every key comes out of HKDF-SHA256 (§3.1):

derive(secret, label) = HKDF-SHA256(ikm = secret, salt = "p-lens/pln-1", info = label, L = 32)

The labels and the salt live in one place in the app, keyring.ts:

/** The labels HKDF is given for each use of a secret (PROTOCOL.md §3.1). */
export const LABEL = {
  sign: (name: string, counter: number): string => `sign:${name}:${counter}`,
  seal: (name: string): string => `seal:${name}`,
  locator: (name: string): string => `locator:${name}`,
  address: "address",
  device: "device:",
} as const

/** The salt every PLN-1 key is derived under. */
export const SALT = "p-lens/pln-1"

The derivation uses the browser’s Web Crypto HKDF. A signing key must be a scalar in [1, n) for secp256k1, so the counter at the end of the label goes 0, 1, 2, … until the 32 bytes land in range. From web-crypto-keys.ts:

const derive = async (secret: Uint8Array, info: string | Uint8Array): Promise<Uint8Array<ArrayBuffer>> => {
  const key = await crypto.subtle.importKey("raw", copied(secret), "HKDF", false, ["deriveBits"])
  const label = typeof info === "string" ? encoder.encode(info) : copied(info)
  return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: encoder.encode(SALT), info: label }, key, 256))
}

const ORDER = secp256k1.Point.CURVE().n

const signingKeyFrom = async (secret: Uint8Array, name: string, counter: number): Promise<SigningKey> => {
  const candidate = await derive(secret, LABEL.sign(name, counter))
  const scalar = BigInt(`0x${bytesToHex(candidate)}`)
  return scalar >= 1n && scalar < ORDER ? { secret: candidate, pubkey: bytesToHex(schnorr.getPublicKey(candidate)) } : signingKeyFrom(secret, name, counter + 1)
}

The odds of needing counter 1 are about one in 2^128, so the recursion is there for correctness rather than exercise. Web Crypto has no secp256k1 Schnorr, so signing uses @noble/curves. Everything else (HKDF, HMAC, AES-GCM, SHA-256, deflate) is a browser API.

A line’s v is the first 16 bytes of an HKDF output; a place’s d is the first 16 bytes of an HMAC-SHA256 under a derived key (web-crypto-keys.ts):

  locator: async (secret, name) => bytesToHex((await derive(secret, LABEL.locator(name))).subarray(0, 16)),
  address: async (secret, name) => {
    const key = await crypto.subtle.importKey("raw", await derive(secret, LABEL.address), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
    return bytesToHex(new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(name))).subarray(0, 16))
  },

Each use has its own label, so the outputs are unrelated to each other. The relay receives signing public keys, v and d, and none of them leads back to a secret or a seal key.

Moving a book to another device means moving its secrets. The “sync code” is shown as a QR code or text:

p-lens-sync:1:<S>:<E_n>:<relay address>

The code is the book’s key: whoever holds it is the owner. Inviting someone never hands over S. The owner’s device makes a fresh m for each person and gives them an invitation code of their own:

p-lens-invite:1:<m>:<O>:<relay address>

The invited device reads the mailbox (kind 34743) derived from m. In it, sealed under a key from m, the owner has left the book’s epoch secret E_n and the person’s role. So when 🚀チーム帳簿 is shared with すばやいおサル, what travels is one invitation code, and the book’s own sync secret stays on the owner’s devices.

The seal: AES-256-GCM, and what the box is stuck to

Nearly every event’s content is a seal, defined in §3.3:

plaintext = pad(deflateRaw(utf8(json)))          sealJson
plaintext = pad(bytes)                           sealBytes
content   = base64(0x01 ‖ nonce(12 random bytes) ‖ AES-256-GCM(key, nonce, plaintext, aad))
aad       = utf8("pln-1") ‖ 0x00 ‖ utf8(decimal kind) ‖ 0x00 ‖ utf8(v) ‖ 0x00 ‖ utf8(d or "") ‖ 0x00 ‖ utf8(pubkey hex)

The additional authenticated data carries the event’s kind, its line v, its place d and its author’s public key. From seal.ts:

/** What a box is stuck to: moved to another kind, line, address or author, it does not open. */
export type Place = { readonly kind: number; readonly v: string; readonly d: string | undefined; readonly pubkey: string }

and the bytes it becomes (seal.ts):

/** pln-1 ‖ 0 ‖ kind ‖ 0 ‖ v ‖ 0 ‖ d ‖ 0 ‖ pubkey: what a seal's AES-GCM tag binds it to. */
export const aadOf = (place: Place): Uint8Array<ArrayBuffer> => {
  const parts = ["pln-1", String(place.kind), place.v, place.d ?? "", place.pubkey].map((part) => encoder.encode(part))
  const whole = new Uint8Array(parts.reduce((length, part) => length + part.length + 1, -1))
  parts.reduce((offset, part, index) => {
    whole.set(part, offset)
    return offset + part.length + (index < parts.length - 1 ? 1 : 0)
  }, 0)
  return whole
}

A sealed box copied into an event of another kind, on another line, at another place or under another author fails authentication. A relay that tries to move boxes around produces events that a device cannot open, and a device drops those cheaply and silently.

Before sealing, the content is deflated and then padded the NIP-44 v2 way (a 2-byte length, then zeros up to NIP-44’s padded length), so that the size of a box says little about what is in it. The encryption is Web Crypto’s AES-GCM (web-crypto-keys.ts):

/** Seals bytes as they are, with the nonce given; `sealJson` draws one. Kept apart for the test vectors. */
export const sealBytesWith = async (key: Uint8Array, nonce: Uint8Array, place: Place, bytes: Uint8Array): Promise<Result<string, PadFailure>> => {
  const padded = pad(bytes)
  if (!padded.ok) return padded
  const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv: copied(nonce), additionalData: aadOf(place) }, await aesKey(key, "encrypt"), padded.value)
  return Ok(toBase64(joined(Uint8Array.of(SEAL_VERSION), nonce, new Uint8Array(sealed))))
}

The deflate is the browser’s CompressionStream("deflate-raw"). What is padded may be at most 32,000 bytes, so the largest content is 43,732 characters, inside the 48,000-byte event PLN-1 asks a relay to accept. Anything larger is cut into parts, below.

A book as a graph of changes

Sync does not send snapshots. It sends changes, and each change names the changes it was made on, so the devices assemble a graph much like Git’s. §5.1 gives the three sorts:

Base  = { sort: "base",  parents: ChangeId[], writer: pubkey, at: seconds,
          book: string, files: { <path>: <text> }, result: StateDigest }
Edit  = { sort: "edit",  parents: [ChangeId], writer: pubkey, at: seconds,
          patches: FilePatch[], result: StateDigest }
Merge = { sort: "merge", parents: [ChangeId, ChangeId], writer: pubkey | "",
          at: seconds, patches: FilePatch[], result: StateDigest }

FilePatch = { path, created: boolean, hunks: [ { at, removed: [line], added: [line] } ] }

Every change carries result, the SHA-256 of the book it leaves. A device checks that applying a change reaches that digest, and if it does not, it stops on that line and says so rather than carry on as a different book.

A change’s id is the SHA-256 of its canonical JSON (RFC 8785), from canonical.ts:

/**
 * A value as canonical JSON (RFC 8785) for what PLN-1 hashes: keys in order
 * of their UTF-16 code units, no white space. Every number in what is hashed
 * is a safe integer, which JSON writes the one way.
 */
export const canonicalJson = (value: Json): string => {
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`
  if (typeof value === "object" && value !== null)
    return `{${Object.keys(value)
      .toSorted()
      .map((key) => `${JSON.stringify(key)}:${canonicalJson((value as { readonly [key: string]: Json })[key] ?? null)}`)
      .join(",")}}`
  return JSON.stringify(value)
}

/** The SHA-256 of a value's canonical JSON, in lowercase hex. */
export const digestOf = (value: Json): string => bytesToHex(sha256(utf8ToBytes(canonicalJson(value))))

The hardest part of RFC 8785, serialising floating-point numbers identically everywhere, is sidestepped by allowing only safe integers in anything hashed. Because the id comes from the content, the same change sent twice, by anyone, is one change. The ChangeId lives inside the seal, so the relay only ever sees Nostr event ids.

A change travels sealed in a kind 4738 event. When its deflated canonical JSON is over 32,000 bytes, it is cut into 32,000-byte parts, each sealed as an event of its own, followed by a manifest listing the parts’ event ids and the SHA-256 of the whole (eventsOfChange in book-sync.ts).

On the receiving side, the change’s writer must be the key that signed the event. A merge with an empty writer is the one exception, for a reason that comes up in the next section. From book-sync.ts:

/**
 * What a 4738 event brought, sealed for whoever signed it: a change its
 * writer signed, or a merge with no writer, whoever carried it
 * (PROTOCOL.md §5.1); a manifest; or something that did not open as JSON,
 * which may be a part.
 */
export const openChangeEvent = async (keys: Keys, line: BookLineKeys, event: NostrEvent): Promise<Opened> => {
  if (event.kind !== KIND.bookChange) return { type: "none" }
  const opened = await keys.openJson(line.sealKey, changePlace(line, event.pubkey), event.content)
  if (!opened.ok) return opened.error.type === "not-inflatable" || opened.error.type === "not-json" ? { type: "loose" } : { type: "none" }
  const message = readLineMessage(opened.value)
  if (message === undefined) return { type: "none" }
  return message.type === "manifest" || message.change.writer === event.pubkey || (message.change.sort === "merge" && message.change.writer === "") ? { type: "message", message } : { type: "none" }
}

Event signatures are checked as events arrive from the relay (readRelayMessage calls isSignedEvent). Nothing a relay passes on is taken on trust.

Each device keeps its current heads in an addressable kind 34738 event, its tip. A device joining a line reads every tip and then the line from the earliest base they name. A head it does not hold sends it back to read the line again, and any device holding a signed event may send it again, so whatever a relay lost comes back from whoever still has it.

Three-way merge, and what happens on conflict

When two devices make changes from the same point, say the phone in the parlor and the laptop at home both write to 🐪マイ帳簿 while offline, the line has two heads. A device merges them three ways from their common ancestor, file by file. From merge.ts:

/** The files merged key by key at their top level: a book's settings, and the line's roster (PROTOCOL.md §5.3). */
const KEYED_FILES: ReadonlySet<string> = new Set([BOOK_SETTINGS_FILE, ROSTER_FILE])

/** One file merged: the text it comes to, none where it is not there, or a conflict. */
const mergedFile = (path: string, base: string | undefined, first: string | undefined, second: string | undefined): Result<string | undefined, FileConflict["why"]> => {
  if (first === second || base === second) return Ok(first)
  if (base === first) return Ok(second)
  if (KEYED_FILES.has(path)) return ((text) => (text === undefined ? Err("keys" as const) : Ok(text)))(mergedByKey(base, first, second))
  if (first === undefined || second === undefined || (base === undefined && !keepsBothAdded(path))) return Err("lines")
  const parts = outlineOf(path, base ?? "", first, second)
  return contestedIn(parts) === 0 ? Ok(settledText(parts, [])) : Err("lines")
}
/** Whether lines both sides added at one place are both kept: in a journal, and in a log, which each side only adds to; anywhere else it is a conflict. */
const keepsBothAdded = (path: string): boolean => path.endsWith(".journal") || path.startsWith("logs/")

This is where plain-text accounting pays off. A ledger mostly grows by appending transactions, so two devices each adding a transaction at the end of the same day is not a conflict. Both are kept, the side with the lower ChangeId first.

The merge itself is written as { sort: "merge" } with the two parents in ChangeId order, an empty writer, and at set to the later of the two parents. Nothing in it depends on which device made it, so every device that merges the same two heads makes the same change with the same id. Two devices merging at the same moment produce one merge, not two that then need merging. This is also why a merge with no writer may arrive in anyone’s event: a device checking it simply makes the merge again and compares ids.

A conflict is one place changed two ways, a key set to two values, the same play (play-id) recorded on both sides, or a merged book that hledger refuses to read. Only something that can read the contents can settle that, which means a device, and in a ledger it means a person. P-Lens stops the merge, shows the two sides, and lets the person keep one side stretch by stretch. Their choice is written as a merge with their own key as writer. Nothing is guessed. The book stays writable at its own head meanwhile, and the merge is offered again as either side moves.

Who may write is decided by the receiving device

A shared book has roles:

Role Holds Writes
owner S everything of the book
editor m, E_n changes and its own tip, signed by M
viewer m, E_n nothing: it holds no signing key
sender m its own plays into the book’s inbox; it cannot read the book

The relay does not decide who may write. Inside the book is a roster file, pln:roster, that only the owner changes, listing the editors’ public keys. For every change, the receiving device checks whether its writer was on the roster as it stood when the change was made. From taking.ts:

  const judged = (id: ChangeId, change: Change): boolean => {
    if (change.writer === owner) return true
    switch (change.sort) {
      case "base":
        return false
      case "edit":
        return editorsEdit(id, change)
      case "merge":
        return change.writer === "" ? isTheMerge(id, change) : editorsMerge(id, change)
    }
  }

An editor’s edit must also leave the roster alone, and must not change what only the owner changes (taking.ts):

  const editorsEdit = (id: ChangeId, edit: Edit): boolean => {
    const [parent] = edit.parents as [ChangeId]
    const [before, after] = [stateAt(parent), stateAt(id)]
    return (
      before !== undefined &&
      after !== undefined &&
      editorOn(parent, edit.writer) &&
      edit.patches.every((patch) => patch.path !== ROSTER_FILE) &&
      leaves(id, edit) &&
      ownersPartOf(before) === ownersPartOf(after)
    )
  }

ownersPartOf is the book’s title and its place and business-day boundary among the owner’s books. So すばやいおサル can add transactions to 🚀チーム帳簿 but cannot rename it.

A change that is not taken is kept on the device but never becomes a head, and neither does anything built on it. The judgement depends only on the change and its ancestors, so every device holding the same changes arrives at the same book. A relay running with ENTITLEMENT=open, refusing nothing, cannot get an unauthorised change into anyone’s book. The official relay does read the plain-text access list (kind 34742) and refuses writes from people not on it, but that is to keep its storage tidy; the book’s correctness does not depend on it.

Removing someone rotates the key

When an editor or viewer is removed, the owner’s device makes a new epoch secret E_{n+1} and writes, in this order (§5.8): an edit on the old line taking the person off the roster and setting the epoch to n+1; a base and a tip on the new line; “removed” to that person’s mailbox; the new access list; and the new epoch secret to every remaining mailbox. The removed person holds only E_n, so what is written afterwards does not open for them, even with the boxes in hand.

The gaps that remain are stated in the protocol. Until a device learns of the new epoch, it may take a change the removed person wrote in the meantime. What is written on the old line in the meantime can be read by the removed person. And the removed person’s device still has the book as it was before. No cryptography fixes that last one.

What the relay can see

PROTOCOL.md §1.2 lists what the operator of a relay, the official one or anyone’s own, can and cannot read, “so that no one is told more is hidden than is.”

Never readable: anything in a book (journals, settings, title, files, the names the owner gives invited people, every change), and anything about a play (parlor, machine, money, balls and tokens, readings, results, when it was played, whether it was recorded, the name a huddle member goes by).

Readable by design:

What From
that P-Lens is in use, and which product each event belongs to kind
when an event was made, its rounded expiry day, its padded size created_at, expiration, the content’s length
which events belong together v, d, and the author’s pubkey
who may write to a book, and in what role (no names) the access list (kind 34742)
how many people a book is shared with, how many are in a huddle the access list; a huddle’s distinct authors
the network address and timing of every connection the transport

(The table in §1.2 also has a row for which paid plan a book uses. Paid sync is a topic of its own and is left out here.)

Two pieces of the timing are blunted on purpose. expiration is rounded up to a whole UTC day, so that the hour a person’s business day turns over is not a fingerprint. From plays.ts:

/** When a copy may be let go of by the relay: the start of the UTC day three days after its play's business day, so that no hour is told. */
export const playsExpiration = (day: IsoDate): number => {
  const [year, month, date] = day.split("-").map(Number) as [number, number, number]
  return Date.UTC(year, month - 1, date + 3) / 1000
}

And a live play’s copy is stamped with the time rounded down to 10 seconds, so that the moment a machine hits its bonus (大当り, oh-ah-ta-ri) cannot be read from when the event was made (plays.ts):

/** When a copy is said to be made: now rounded down to ten seconds, and later than the last at its address (PROTOCOL.md §1.2, §3.4). */
export const copyTime = (nowSeconds: number, last: number | undefined): number => Math.max(Math.floor(nowSeconds / 10) * 10, (last ?? 0) + 1)

The second argument of Math.max is there because an addressable event needs a created_at later than the last one at its address. When a device writes twice within the same 10 seconds, the second copy is stamped one second after the first rather than on a multiple of 10. What that tells the relay is that two copies were written close together, not when.

That the relay keeps nothing readable is also a test. It puts a marker string into the book, as a comment in the main journal and as a transaction’s description, syncs, serialises every event the relay received, and checks that neither the marker, nor a fragment of it, nor the book’s id appears, and that no tag but v and d was used. From book-sync.test.ts:

const MARKER = "MARKER-ネルフ本部-0451"

and (book-sync.test.ts):

  test("the relay holds nothing of the book that can be read", async () => {
    const { one, lineOne } = await twoDevices((files) => ({ ...files, [BOOK_FILES.main]: `${files[BOOK_FILES.main] ?? ""}\n; ${MARKER}\n` }))
    await one.write(entryOf("2026-11-06", 700, MARKER))
    lineOne.book.wrote()
    await until(() => (relayOf()?.events().length ?? 0) >= 4)
    const everything = JSON.stringify(relayOf()?.events())
    expect(everything).not.toContain(MARKER)
    expect(everything).not.toContain("ネルフ")
    expect(everything).not.toContain(BOOK)
    expect(relayOf()?.events().every((event) => event.tags.every((tag) => ["v", "d"].includes(tag[0] ?? "")))).toBe(true)
  }, 20_000)

Is this end-to-end encryption?

Sealed on the device, keys never on the server, opened only by the other devices: that is what end-to-end encryption usually means, and the relay’s README does call it end to end encrypted. We believe the description fits. Nobody outside the project has reviewed the design, though, so take that as our belief, not as a claim. People who hear “E2EE” also tend to picture a messaging app, and two things they would expect are not here.

And, as the table above shows, a relay still sees that someone is syncing, when, and with how many people. For these reasons P-Lens’s own pages do not lean on the term, and say instead that changes are encrypted on the device before they are sent and the relay cannot read them.

Running a relay yourself

The relay’s code runs on a server of one’s own with Bun and SQLite, per the p-lens-relay README:

bun --cwd=hosts/bun run relay                       # on ws://127.0.0.1:7780, its files in hosts/bun/data
RELAY_URL=ws://127.0.0.1:7780 bun --cwd=testing/conformance test

The same conformance suite runs against strfry and nostr-rs-relay. For anyone writing PLN-1 in another language, packages/reference holds a reference implementation of the key derivation, padding and seal, with test vectors in packages/reference/vectors/pln-1.json. Deflate output differs between implementations, so the vectors give the deflated bytes and check that they seal to the given content.

In P-Lens, sync is the only part that may become paid at some point. Using one device stays free, and so does sync through a relay you run yourself.

Limits, and what is not done

Choosing a relay that knows nothing means that everything clever happens on the devices. For a ledger app that turned out to cost little, because the ledger’s source of truth was on the devices from the start.

All articles