chadtmiller.com/monolith
An atproto PDS
0
0
// Each account's whole repository: each side's getRepo, verified and held to
// the reference's, getLatestCommit, and getRepo with `since` (spec/SYNC.md).
// With --firehose, each check checks the firehose too.
import { isDeepStrictEqual } from 'node:util'
import { readCarWithRoot, verifyRepoCar } from '@atproto/repo'
import { cborDecode } from '@atproto/common'
import { FIREHOSE } from '../lib/args.mjs'
import { chance, rand } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { normalize, strip, xrpc } from '../lib/xrpc.mjs'
import { checkFirehose, checkReplay } from './firehose.mjs'
/// The CIDs of the MST nodes a write of `key` can change, in a tree whose
/// blocks are `blocks` (by CID string), from `root`, and the record CID at
/// `key` if the tree holds it. They are the nodes a search for it passes
/// through and, where it is found, the edges of the subtrees beside it,
/// which deleting it merges and putting it back splits again.
function search(blocks, root, key) {
const path = []
let cid = root
while (cid && blocks.has(cid)) {
path.push(cid)
const node = cborDecode(blocks.get(cid))
let prev = ''
let next = node.l ? node.l.toString() : null
for (const e of node.e) {
const k = prev.slice(0, e.p) + Buffer.from(e.k).toString('latin1')
prev = k
if (key === k) {
const edge = (c, last) => {
for (; c && blocks.has(c); ) {
path.push(c)
const n = cborDecode(blocks.get(c))
const t = last ? (n.e.length ? n.e.at(-1).t : n.l) : n.l
c = t ? t.toString() : null
}
}
edge(next, true)
edge(e.t ? e.t.toString() : null, false)
return { path, value: e.v.toString() }
}
if (key < k) break
next = e.t ? e.t.toString() : null
}
cid = next
}
return { path, value: null }
}
/// Every account's repository checked, then, with --firehose, the firehose.
export async function checkRepos() {
for (const acct of accounts) await checkRepo(acct)
if (FIREHOSE) {
await checkFirehose()
if (chance(0.3)) await checkReplay()
}
}
/// The CAR each side last gave for each account that verified, and the DID
/// and key it verified against.
const verifiedCars = { reference: new Map(), server: new Map() }
/// `verifyRepoCar` of the account's CAR from `side`, against `key`. The same
/// bytes verify the same against the same DID and key, so a CAR that is,
/// byte for byte, the one this side gave at the last check, which verified,
/// is not verified again: most accounts are not written between two checks.
async function verifyOnce(acct, side, bytes, key) {
const did = didOf(side, acct)
const last = verifiedCars[side.name].get(acct)
if (last && last.did === did && last.key === key && Buffer.compare(last.bytes, bytes) === 0) return last.verified
const verified = await verifyRepoCar(bytes, did, key)
verifiedCars[side.name].set(acct, { bytes, did, key, verified })
return verified
}
/// The account's repository from each side's getRepo, each verified against
/// the signing key the account's DID document names on that side, the
/// server's held to the reference's; its getLatestCommit; and sometimes
/// getRepo with `since`.
export async function checkRepo(acct) {
const did = (side) => didOf(side, acct)
const request = { did: `<did:${acct.n}>` }
const [a, b] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.sync.getRepo', { params: { did: did(side) }, raw: true })))
if (a.status !== 200) throw new Error(`reference getRepo: ${JSON.stringify(a.body)}`)
if (b.status !== 200) await differ('com.atproto.sync.getRepo', request, 'a CAR', normalize(cand, b))
// The reference is verified too, which checks the check.
try {
await verifyOnce(acct, ref, a.bytes, acct.sides.reference.key)
} catch (err) {
throw new Error(`the reference's repository of ${did(ref)} does not verify against its key: ${err.message ?? err}`)
}
const theirs = await readCarWithRoot(a.bytes)
const theirCommit = cborDecode(theirs.blocks.get(theirs.root))
let verified
try {
verified = await verifyOnce(acct, cand, b.bytes, acct.sides.server.key)
} catch (err) {
await differ('com.atproto.sync.getRepo', request, 'a repo the reference library verifies against the signing key the DID document names', String(err.message ?? err))
}
const ours = await readCarWithRoot(b.bytes)
const ourCommit = cborDecode(ours.blocks.get(ours.root))
if (theirCommit.data.toString() !== ourCommit.data.toString()) {
await differ('the repository', { ...request, records: [...acct.records.keys()].sort() }, { data: theirCommit.data.toString() }, { data: ourCommit.data.toString() }, 'the MST roots differ, so the records or their encoding do')
}
if (ourCommit.version !== 3 || ourCommit.did !== did(cand)) await differ('the commit', request, { version: 3, did: request.did }, { version: ourCommit.version, did: strip(cand, String(ourCommit.did)) })
if (ourCommit.rev < acct.lastRev) await differ('the commit', request, `a rev not before ${acct.lastRev}`, ourCommit.rev, 'revs must not go back')
acct.lastRev = ourCommit.rev
const latest = await xrpc(cand, 'com.atproto.sync.getLatestCommit', { params: { did: did(cand) } })
if (latest.status !== 200 || latest.body.cid !== ours.root.toString() || latest.body.rev !== ourCommit.rev) {
await differ('com.atproto.sync.getLatestCommit', request, { cid: ours.root.toString(), rev: ourCommit.rev }, latest.body)
}
// The current tree's blocks, the same on both sides: their roots are equal.
const tree = new Set()
theirs.blocks.forEach((_, cid) => { if (!cid.equals(theirs.root)) tree.add(cid.toString()) })
const current = { data: theirCommit.data.toString(), blocks: new Map() }
theirs.blocks.forEach((bytes, cid) => current.blocks.set(cid.toString(), bytes))
const { revs, written } = acct
if (revs.server && chance(0.3)) await checkSince(acct, theirCommit.rev, ourCommit.rev, theirs.root.toString(), ours.root.toString(), tree, current)
revs.reference = theirCommit.rev
revs.server = ourCommit.rev
revs.tree = tree
revs.blocks = new Map()
theirs.blocks.forEach((bytes, cid) => revs.blocks.set(cid.toString(), bytes))
revs.data = theirCommit.data.toString()
written.keys.clear()
written.records.clear()
count('repository check', Boolean(verified))
}
/// `getRepo` with `since`: a CAR whose root is the latest commit, holding the
/// blocks of the current tree written after that rev, none if it is the
/// latest. Which blocks were written since depends on the order a side made
/// its commits in, which writes sent at once may change, so each side is held
/// to what does not: every block of the current tree that the tree at the
/// last check lacked must be there; nothing outside the current tree; and
/// nothing that stayed in it untouched by every write since (spec/SYNC.md,
/// "What the reference does that the specs leave open").
async function checkSince(acct, theirHead, ourHead, theirRoot, ourRoot, tree, current) {
const { revs, written } = acct
const r = rand()
const which = r < 0.25 ? 'latest' : r < 0.35 ? 'bad' : 'last'
const since = which === 'latest' ? { reference: theirHead, server: ourHead } : which === 'bad' ? { reference: 'notarev', server: 'notarev' } : { ...revs }
const [a, b] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.sync.getRepo', { params: { did: didOf(side, acct), since: since[side.name] }, raw: true })))
const request = { did: `<did:${acct.n}>`, since: { latest: 'the latest rev', bad: 'notarev', last: 'the rev at the last check' }[which] }
if (a.status !== 200 || b.status !== 200) {
const [na, nb] = [normalize(ref, a), normalize(cand, b)]
if (!isDeepStrictEqual(na, nb)) await differ('com.atproto.sync.getRepo', request, na, nb)
return count('getRepo since', false)
}
const read = async (bytes) => {
const car = await readCarWithRoot(bytes)
const held = new Set()
car.blocks.forEach((_, cid) => { if (!cid.equals(car.root)) held.add(cid.toString()) })
return { root: car.root.toString(), blocks: car.blocks.size, held }
}
let theirsSince, oursSince
try {
oursSince = await read(b.bytes)
} catch (err) {
return differ('com.atproto.sync.getRepo', request, 'a CAR', String(err.message ?? err))
}
theirsSince = await read(a.bytes)
if (oursSince.root !== ourRoot) await differ('com.atproto.sync.getRepo', request, `the latest commit, ${ourRoot}, as root`, oursSince.root)
if (theirsSince.root !== theirRoot) throw new Error(`the reference's getRepo since has root ${theirsSince.root}, not ${theirRoot}`)
if (which === 'latest' && oursSince.blocks !== 0) await differ('com.atproto.sync.getRepo', request, 'no blocks', `${oursSince.blocks} blocks`)
if (which === 'last') {
const need = [...tree].filter((c) => !revs.tree.has(c))
// A block in both trees may be there only if a write since touched it: a
// node on the path of a key written since, that key's record, or a record
// a write since answered, which another key may hold too. Only such a
// block can have been taken out and put back, or written again.
const blocks = new Map(current.blocks)
revs.blocks.forEach((bytes, cid) => blocks.has(cid) || blocks.set(cid, bytes))
const touched = new Set(written.records)
for (const key of written.keys) {
for (const root of [current.data, revs.data]) {
const { path, value } = search(blocks, root, key)
path.forEach((c) => touched.add(c))
if (value) touched.add(value)
}
}
const judge = (s) => ({
missing: need.filter((c) => !s.held.has(c)),
outside: [...s.held].filter((c) => !tree.has(c)),
unchanged: [...s.held].filter((c) => revs.tree.has(c) && tree.has(c) && !touched.has(c)),
})
const [t, o] = [judge(theirsSince), judge(oursSince)]
// The reference holds to the rule too, which checks the rule.
if (t.missing.length || t.outside.length || t.unchanged.length) {
const show = (c) => ({ cid: c, block: cborDecode(blocks.get(c)), holders: [...acct.records].filter(([, v]) => v === c).map(([k]) => k) })
throw new Error(`the reference's getRepo since breaks the rule it is held to: ${JSON.stringify({ ...t, unchanged: t.unchanged.map(show), keys: [...written.keys], records: [...written.records] }, (_, v) => (v instanceof Uint8Array ? Buffer.from(v).toString('latin1') : v?.['/'] ?? (v?.toString && v.asCID ? v.toString() : v)))}`)
}
if (o.missing.length || o.outside.length || o.unchanged.length) await differ('com.atproto.sync.getRepo', request, 'every block the current tree gained since that rev; none outside it; none that stayed, untouched by any write since', o)
}
count('getRepo since', true)
}