-
Notifications
You must be signed in to change notification settings - Fork 403
/
util.ts
273 lines (252 loc) · 7.17 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { CID } from 'multiformats/cid'
import * as cbor from '@ipld/dag-cbor'
import { CarReader } from '@ipld/car/reader'
import { BlockWriter, CarWriter } from '@ipld/car/writer'
import { Block as CarBlock } from '@ipld/car/api'
import {
streamToBuffer,
verifyCidForBytes,
cborDecode,
check,
schema,
cidForCbor,
} from '@atproto/common'
import { ipldToLex, lexToIpld, LexValue, RepoRecord } from '@atproto/lexicon'
import * as crypto from '@atproto/crypto'
import Repo from './repo'
import { MST } from './mst'
import DataDiff from './data-diff'
import { RepoStorage } from './storage'
import {
Commit,
RecordCreateDescript,
RecordDeleteDescript,
RecordPath,
RecordUpdateDescript,
RecordWriteDescript,
UnsignedCommit,
WriteLog,
WriteOpAction,
} from './types'
import BlockMap from './block-map'
import { MissingBlocksError } from './error'
import * as parse from './parse'
import { Keypair } from '@atproto/crypto'
export async function* verifyIncomingCarBlocks(
car: AsyncIterable<CarBlock>,
): AsyncIterable<CarBlock> {
for await (const block of car) {
await verifyCidForBytes(block.cid, block.bytes)
yield block
}
}
export const writeCar = (
root: CID | null,
fn: (car: BlockWriter) => Promise<void>,
): AsyncIterable<Uint8Array> => {
const { writer, out } =
root !== null ? CarWriter.create(root) : CarWriter.create()
fn(writer).finally(() => writer.close())
return out
}
export const blocksToCarStream = (
root: CID | null,
blocks: BlockMap,
): AsyncIterable<Uint8Array> => {
return writeCar(root, async (writer) => {
for (const entry of blocks.entries()) {
await writer.put(entry)
}
})
}
export const blocksToCarFile = (
root: CID | null,
blocks: BlockMap,
): Promise<Uint8Array> => {
const carStream = blocksToCarStream(root, blocks)
return streamToBuffer(carStream)
}
export const readCar = async (
bytes: Uint8Array,
): Promise<{ roots: CID[]; blocks: BlockMap }> => {
const car = await CarReader.fromBytes(bytes)
const roots = await car.getRoots()
const blocks = new BlockMap()
for await (const block of verifyIncomingCarBlocks(car.blocks())) {
await blocks.set(block.cid, block.bytes)
}
return {
roots,
blocks,
}
}
export const readCarWithRoot = async (
bytes: Uint8Array,
): Promise<{ root: CID; blocks: BlockMap }> => {
const { roots, blocks } = await readCar(bytes)
if (roots.length !== 1) {
throw new Error(`Expected one root, got ${roots.length}`)
}
const root = roots[0]
return {
root,
blocks,
}
}
export const getWriteLog = async (
storage: RepoStorage,
latest: CID,
earliest: CID | null,
): Promise<WriteLog> => {
const commits = await storage.getCommitPath(latest, earliest)
if (!commits) throw new Error('Could not find shared history')
const heads = await Promise.all(commits.map((c) => Repo.load(storage, c)))
// Turn commit path into list of diffs
let prev = await MST.create(storage) // Empty
const msts = heads.map((h) => h.data)
const diffs: DataDiff[] = []
for (const mst of msts) {
diffs.push(await DataDiff.of(mst, prev))
prev = mst
}
const fullDiff = collapseDiffs(diffs)
const diffBlocks = await storage.getBlocks(fullDiff.newCidList())
if (diffBlocks.missing.length > 0) {
throw new MissingBlocksError('write op log', diffBlocks.missing)
}
// Map MST diffs to write ops
return Promise.all(
diffs.map((diff) => diffToWriteDescripts(diff, diffBlocks.blocks)),
)
}
export const diffToWriteDescripts = (
diff: DataDiff,
blocks: BlockMap,
): Promise<RecordWriteDescript[]> => {
return Promise.all([
...diff.addList().map(async (add) => {
const { collection, rkey } = parseDataKey(add.key)
const value = await parse.getAndParseRecord(blocks, add.cid)
return {
action: WriteOpAction.Create,
collection,
rkey,
cid: add.cid,
record: value.record,
} as RecordCreateDescript
}),
...diff.updateList().map(async (upd) => {
const { collection, rkey } = parseDataKey(upd.key)
const value = await parse.getAndParseRecord(blocks, upd.cid)
return {
action: WriteOpAction.Update,
collection,
rkey,
cid: upd.cid,
prev: upd.prev,
record: value.record,
} as RecordUpdateDescript
}),
...diff.deleteList().map((del) => {
const { collection, rkey } = parseDataKey(del.key)
return {
action: WriteOpAction.Delete,
collection,
rkey,
cid: del.cid,
} as RecordDeleteDescript
}),
])
}
export const collapseWriteLog = (log: WriteLog): RecordWriteDescript[] => {
const creates: Record<string, RecordCreateDescript> = {}
const updates: Record<string, RecordUpdateDescript> = {}
const deletes: Record<string, RecordDeleteDescript> = {}
for (const commit of log) {
for (const op of commit) {
const key = op.collection + '/' + op.rkey
if (op.action === WriteOpAction.Create) {
const del = deletes[key]
if (del) {
if (del.cid !== op.cid) {
updates[key] = {
...op,
action: WriteOpAction.Update,
prev: del.cid,
}
}
delete deletes[key]
} else {
creates[key] = op
}
} else if (op.action === WriteOpAction.Update) {
updates[key] = op
delete creates[key]
delete deletes[key]
} else if (op.action === WriteOpAction.Delete) {
if (creates[key]) {
delete creates[key]
} else {
delete updates[key]
deletes[key] = op
}
} else {
throw new Error(`unknown action: ${op}`)
}
}
}
return [
...Object.values(creates),
...Object.values(updates),
...Object.values(deletes),
]
}
export const collapseDiffs = (diffs: DataDiff[]): DataDiff => {
return diffs.reduce((acc, cur) => {
acc.addDiff(cur)
return acc
}, new DataDiff())
}
export const parseDataKey = (key: string): RecordPath => {
const parts = key.split('/')
if (parts.length !== 2) throw new Error(`Invalid record key: ${key}`)
return { collection: parts[0], rkey: parts[1] }
}
export const formatDataKey = (collection: string, rkey: string): string => {
return collection + '/' + rkey
}
export const metaEqual = (a: Commit, b: Commit): boolean => {
return a.did === b.did && a.version === b.version
}
export const signCommit = async (
unsigned: UnsignedCommit,
keypair: Keypair,
): Promise<Commit> => {
const encoded = cbor.encode(unsigned)
const sig = await keypair.sign(encoded)
return {
...unsigned,
sig,
}
}
export const verifyCommitSig = async (
commit: Commit,
didKey: string,
): Promise<boolean> => {
const { sig, ...rest } = commit
const encoded = cbor.encode(rest)
return crypto.verifySignature(didKey, encoded, sig)
}
export const cborToLex = (val: Uint8Array): LexValue => {
return ipldToLex(cborDecode(val))
}
export const cborToLexRecord = (val: Uint8Array): RepoRecord => {
const parsed = cborToLex(val)
if (!check.is(parsed, schema.map)) {
throw new Error('lexicon records be a json object')
}
return parsed
}
export const cidForRecord = async (val: LexValue) => {
return cidForCbor(lexToIpld(val))
}