@watchtowerobservability/activity-react-native 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +84 -2
- package/package.json +38 -4
- package/src/ActivityLog.tsx +230 -0
- package/src/EventDetail.tsx +99 -0
- package/src/Sheets.tsx +113 -0
- package/src/builtInStrings.ts +230 -0
- package/src/client.ts +179 -0
- package/src/index.ts +14 -0
- package/src/link.ts +17 -0
- package/src/live.ts +74 -0
- package/src/query.ts +36 -0
- package/src/sealed.ts +38 -0
- package/src/strings.ts +67 -0
- package/src/theme.ts +37 -0
- package/src/types.ts +65 -0
- package/src/useActivityLog.ts +181 -0
- package/src/verify.ts +164 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
2
|
+
import { AppState } from 'react-native';
|
|
3
|
+
import { nextStep, openStream } from './live';
|
|
4
|
+
import { revealTokens } from './sealed';
|
|
5
|
+
import { ActivityError, type ActivityClient } from './client';
|
|
6
|
+
import { fmt, pickStrings } from './strings';
|
|
7
|
+
import type { Appearance } from './theme';
|
|
8
|
+
import type { ActivityEvent, Bucket, Facet, Filters, SavedView, Strings, Theme } from './types';
|
|
9
|
+
import type { Verdict } from './verify';
|
|
10
|
+
|
|
11
|
+
export type VerifyState = { state: 'idle' } | { state: 'running' } | { state: 'done'; verdict: Verdict };
|
|
12
|
+
|
|
13
|
+
const sleep = (s: number, stop: () => boolean) => new Promise<void>((r) => {
|
|
14
|
+
const t0 = Date.now();
|
|
15
|
+
const tick = () => (stop() || Date.now() - t0 >= s * 1000 ? r() : setTimeout(tick, 250));
|
|
16
|
+
tick();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
/** State and actions of one viewer; `ActivityLog` renders it, or build your own UI on it. `live` opens the feed stream. */
|
|
20
|
+
export function useActivityLog(client: ActivityClient, appearance: Appearance = {}, initial: Filters = {}, pageSize = 25, live = false) {
|
|
21
|
+
const [events, setEvents] = useState<ActivityEvent[]>([]);
|
|
22
|
+
const [cursor, setCursor] = useState<string | null>(null);
|
|
23
|
+
const [filters, setFiltersState] = useState<Filters>(initial);
|
|
24
|
+
const [theme, setTheme] = useState<Theme>();
|
|
25
|
+
const [caps, setCaps] = useState<string[]>(['read']);
|
|
26
|
+
const [sessionLocale, setLocale] = useState<string>();
|
|
27
|
+
const [timeZone, setTz] = useState<string>();
|
|
28
|
+
const [loading, setLoading] = useState(false);
|
|
29
|
+
const [offline, setOffline] = useState(false);
|
|
30
|
+
const [error, setError] = useState<string | null>(null);
|
|
31
|
+
const [note, setNote] = useState<string | null>(null);
|
|
32
|
+
const [facets, setFacets] = useState<Record<string, Facet[]>>({});
|
|
33
|
+
const [histogram, setHistogram] = useState<Bucket[]>([]);
|
|
34
|
+
const [views, setViews] = useState<SavedView[]>([]);
|
|
35
|
+
const [verify, setVerify] = useState<VerifyState>({ state: 'idle' });
|
|
36
|
+
const [fresh, setFresh] = useState(0);
|
|
37
|
+
const [time, setTime] = useState<'relative' | 'absolute'>('relative');
|
|
38
|
+
const gen = useRef(0);
|
|
39
|
+
const remote = useRef<boolean | null>(null);
|
|
40
|
+
|
|
41
|
+
const locale = appearance.locale ?? sessionLocale;
|
|
42
|
+
const strings: Strings = useMemo(() => pickStrings(theme?.strings, locale, appearance.strings), [theme, locale, appearance.strings]);
|
|
43
|
+
const message = useCallback((e: unknown) => {
|
|
44
|
+
const x = e instanceof ActivityError ? e.status : -1;
|
|
45
|
+
return x === 404 ? strings.sessionExpired! : x === 429 ? fmt(strings.rateLimited!, { n: (e as ActivityError).retryAfter ?? 60 }) : x === 0 ? strings.offline! : strings.error!;
|
|
46
|
+
}, [strings]);
|
|
47
|
+
|
|
48
|
+
const page = useCallback(async (f: Filters, from: string | null) => {
|
|
49
|
+
const g = from ? gen.current : ++gen.current;
|
|
50
|
+
setLoading(true);
|
|
51
|
+
if (!from) setError(null);
|
|
52
|
+
try {
|
|
53
|
+
const p = await client.feed(f, { cursor: from, limit: pageSize });
|
|
54
|
+
if (g !== gen.current) return;
|
|
55
|
+
const rows = p.theme?.hideAccessEvents ? p.data.filter((e) => !e.action.startsWith('wt.activity.')) : p.data;
|
|
56
|
+
setEvents((old) => (from ? [...old, ...rows] : rows));
|
|
57
|
+
setCursor(p.next_cursor ?? null);
|
|
58
|
+
setOffline(!!p.offline);
|
|
59
|
+
if (p.theme) setTheme(p.theme);
|
|
60
|
+
if (p.capabilities) setCaps(p.capabilities);
|
|
61
|
+
if (p.locale) setLocale(p.locale);
|
|
62
|
+
if (p.time_zone) setTz(p.time_zone);
|
|
63
|
+
} catch (e) {
|
|
64
|
+
if (g !== gen.current) return;
|
|
65
|
+
if (!from) setEvents([]);
|
|
66
|
+
setError(message(e));
|
|
67
|
+
} finally {
|
|
68
|
+
if (g === gen.current) setLoading(false);
|
|
69
|
+
}
|
|
70
|
+
}, [client, pageSize, message]);
|
|
71
|
+
|
|
72
|
+
const loadFacets = useCallback(async (f: Filters) => {
|
|
73
|
+
const own: Record<string, keyof Filters> = { action: 'action', actor: 'actor_id', target_type: 'target_type' };
|
|
74
|
+
const out: Record<string, Facet[]> = {};
|
|
75
|
+
await Promise.all(Object.entries(own).map(([field, k]) => client.facets(field, { ...f, [k]: undefined }).then((d) => { out[field] = d; }, () => {})));
|
|
76
|
+
setFacets(out);
|
|
77
|
+
}, [client]);
|
|
78
|
+
|
|
79
|
+
const setFilters = useCallback((f: Filters) => {
|
|
80
|
+
setFiltersState(f);
|
|
81
|
+
void page(f, null);
|
|
82
|
+
void loadFacets(f);
|
|
83
|
+
client.histogram(f).then(setHistogram, () => {});
|
|
84
|
+
}, [client, page, loadFacets]);
|
|
85
|
+
|
|
86
|
+
const reload = useCallback(() => setFilters(filters), [setFilters, filters]);
|
|
87
|
+
const loadMore = useCallback(() => { if (cursor && !loading && !error) void page(filters, cursor); }, [cursor, loading, error, page, filters]);
|
|
88
|
+
useEffect(() => { setFilters(initial); }, [client]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
89
|
+
|
|
90
|
+
// Account tokens keep their views on the server; viewer sessions in `storage`.
|
|
91
|
+
const isRemote = useCallback(async () => (remote.current ??= await client.session().then((s) => s.credential === 'account_token', () => false)), [client]);
|
|
92
|
+
const run = useCallback(async (fn: (r: boolean) => Promise<unknown>) => {
|
|
93
|
+
try { const r = await isRemote(); await fn(r); setViews(await client.views(r)); } catch (e) { setNote(message(e)); }
|
|
94
|
+
}, [client, isRemote, message]);
|
|
95
|
+
const loadViews = useCallback(() => run(async () => {}), [run]);
|
|
96
|
+
const saveView = useCallback((name: string) => {
|
|
97
|
+
const { q = '', ...rest } = filters;
|
|
98
|
+
const params = Object.fromEntries(Object.entries(rest).filter(([, v]) => v)) as Record<string, string>;
|
|
99
|
+
return run((r) => client.saveView({ name, q, params }, r));
|
|
100
|
+
}, [client, filters, run]);
|
|
101
|
+
const deleteView = useCallback((v: SavedView) => run((r) => client.deleteView(v, r)), [client, run]);
|
|
102
|
+
const applyView = useCallback((v: SavedView) => setFilters({ ...v.params, q: v.q }), [setFilters]);
|
|
103
|
+
|
|
104
|
+
const verifyChain = useCallback(async () => {
|
|
105
|
+
setVerify({ state: 'running' });
|
|
106
|
+
try { setVerify({ state: 'done', verdict: await client.verifyChain() }); } catch (e) { setVerify({ state: 'idle' }); setNote(message(e)); }
|
|
107
|
+
}, [client, message]);
|
|
108
|
+
|
|
109
|
+
const prove = useCallback(async (id: string) => {
|
|
110
|
+
try {
|
|
111
|
+
const v = await client.proveEvent(id);
|
|
112
|
+
return v.ok ? (v.signature ? strings.proved! : strings.provedUnsigned!) : strings.proofFailed!;
|
|
113
|
+
} catch (e) {
|
|
114
|
+
return e instanceof ActivityError && e.status === 409 ? strings.notSealed! : message(e);
|
|
115
|
+
}
|
|
116
|
+
}, [client, strings, message]);
|
|
117
|
+
|
|
118
|
+
// Live: one stream while the app is in the foreground; reconnects with backoff, refreshes the token on expiry.
|
|
119
|
+
const [active, setActive] = useState(AppState.currentState !== 'background');
|
|
120
|
+
useEffect(() => { const sub = AppState.addEventListener('change', (st) => setActive(st === 'active')); return () => sub.remove(); }, []);
|
|
121
|
+
useEffect(() => {
|
|
122
|
+
if (!live || !active) return;
|
|
123
|
+
let stopped = false, abort = () => {};
|
|
124
|
+
void (async () => {
|
|
125
|
+
let backoff = 1;
|
|
126
|
+
while (!stopped) {
|
|
127
|
+
const s = openStream(`${client.baseUrl}/v1/activity/feed/stream`, client.token, (n) => setFresh((f) => f + n));
|
|
128
|
+
abort = s.abort;
|
|
129
|
+
const outcome = await s.done.then((end) => ({ end }), (error: ActivityError) => ({ error }));
|
|
130
|
+
if (stopped) return;
|
|
131
|
+
const step = nextStep(outcome, backoff);
|
|
132
|
+
backoff = step.backoff;
|
|
133
|
+
if (step.refresh) {
|
|
134
|
+
const t = await client.refreshToken?.().catch(() => null);
|
|
135
|
+
if (!t || t === client.token) return;
|
|
136
|
+
client.setToken(t);
|
|
137
|
+
}
|
|
138
|
+
await sleep(step.delay, () => stopped);
|
|
139
|
+
}
|
|
140
|
+
})();
|
|
141
|
+
return () => { stopped = true; abort(); };
|
|
142
|
+
}, [client, live, active]);
|
|
143
|
+
|
|
144
|
+
const timeKey = `wta.time:${client.baseUrl}`;
|
|
145
|
+
useEffect(() => { void client.storage.getItem(timeKey).then((v) => v === 'absolute' && setTime('absolute'), () => {}); }, [client, timeKey]);
|
|
146
|
+
const toggleTime = useCallback(() => setTime((t) => {
|
|
147
|
+
const n = t === 'relative' ? 'absolute' : 'relative';
|
|
148
|
+
void client.storage.setItem(timeKey, n).catch(() => {});
|
|
149
|
+
return n;
|
|
150
|
+
}), [client, timeKey]);
|
|
151
|
+
|
|
152
|
+
/** Reveal the tokenised IP / email of an event (capability `reveal`, audited); the sentence to show. */
|
|
153
|
+
const reveal = useCallback(async (e: ActivityEvent) => {
|
|
154
|
+
try {
|
|
155
|
+
const v = await Promise.all(revealTokens(e.context?.ip ?? e.ip, e.actor.email).map((t) => client.reveal(t)));
|
|
156
|
+
return `${strings.revealed}: ${v.join(', ')}`;
|
|
157
|
+
} catch (x) {
|
|
158
|
+
return `${strings.revealFailed} (${x instanceof ActivityError ? x.status : '?'})`;
|
|
159
|
+
}
|
|
160
|
+
}, [client, strings]);
|
|
161
|
+
|
|
162
|
+
/** Open a permalink (`#wta-event=&wta-at=`): the event, or null with the "not available" note. */
|
|
163
|
+
const openEvent = useCallback(async (id: string, at: string) => {
|
|
164
|
+
try {
|
|
165
|
+
const e = await client.event(id, at);
|
|
166
|
+
if (!e) setNote(strings.linkMissing!);
|
|
167
|
+
return e;
|
|
168
|
+
} catch (x) { setNote(message(x)); return null; }
|
|
169
|
+
}, [client, strings, message]);
|
|
170
|
+
|
|
171
|
+
const exportText = useCallback(async (format = 'csv') => {
|
|
172
|
+
try { return await client.export(filters, format); } catch (e) { setNote(`${strings.exportFailed} ${message(e)}`); return null; }
|
|
173
|
+
}, [client, filters, strings, message]);
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
client, events, filters, theme, caps, locale, timeZone, strings, loading, offline, error, note, facets, histogram, views, verify,
|
|
177
|
+
hasMore: !!cursor && !error, setFilters, reload, loadMore, loadViews, saveView, deleteView, applyView, verifyChain, prove, exportText,
|
|
178
|
+
setNote, can: (c: string) => caps.includes(c), fresh, clearFresh: () => { setFresh(0); reload(); }, time, toggleTime, reveal, openEvent,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
export type ActivityLogState = ReturnType<typeof useActivityLog>;
|
package/src/verify.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { ed25519 } from '@noble/curves/ed25519.js';
|
|
2
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
3
|
+
|
|
4
|
+
// Client-side chain check of what the viewer API serves, the same algorithm as the web element and `wtctl`
|
|
5
|
+
// (React Native has no WebCrypto, so SHA-256 and Ed25519 come from the audited @noble packages):
|
|
6
|
+
// GET /v1/activity/feed/verify rows {seq, prev_hash, hash, body (the canonical JSON string the server hashed)},
|
|
7
|
+
// head_seq, anchor_seq, project, checkpoint {seq, hash, kid, message, signature}
|
|
8
|
+
// GET /v1/activity/feed/proof?event_id= RFC 9162 inclusion proof against a signed tree head
|
|
9
|
+
// GET /v1/activity/feed/consistency two signed tree heads and the proof between them
|
|
10
|
+
// GET /v1/activity/keys?project= Ed25519 public keys {kid, x (base64url raw)}
|
|
11
|
+
|
|
12
|
+
export interface ChainRow { id?: string; seq: number; prev_hash: string; hash: string; body: string }
|
|
13
|
+
export interface Checkpoint { seq: number; hash: string; at?: string; kid: string; kind?: string; message: string; signature: string }
|
|
14
|
+
export interface VerifyPage { data: ChainRow[]; next_cursor: string | null; head_seq: number; anchor_seq: number | null; checkpoint: Checkpoint | null; project: string }
|
|
15
|
+
export interface Proof {
|
|
16
|
+
row: ChainRow; leaf: string; index: number; size: number; path: string[]; root: string; from_seq: number; to_seq: number;
|
|
17
|
+
kid: string; message: string; signature: string; project: string;
|
|
18
|
+
}
|
|
19
|
+
export interface Sth { size: number; from_seq: number; to_seq: number; root: string; kid: string; message: string; signature: string }
|
|
20
|
+
export interface Consistency { from_size: number; to_size: number; proof: string[]; from_root: string; to_root: string; sth: Sth; from_sth: Sth; project: string }
|
|
21
|
+
/** `signature`: true valid, false invalid, null not checkable (no checkpoint or unknown key). */
|
|
22
|
+
export interface Verdict { ok: boolean; checked: number; firstBadSeq: number | null; signature: boolean | null }
|
|
23
|
+
export type Keys = { kid: string; x: string }[];
|
|
24
|
+
|
|
25
|
+
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
26
|
+
|
|
27
|
+
/** Hex (even length) or base64url. */
|
|
28
|
+
export function bytes(s: string): Uint8Array {
|
|
29
|
+
if (/^([0-9a-f]{2})*$/i.test(s)) return new Uint8Array((s.match(/../g) ?? []).map((h) => parseInt(h, 16)));
|
|
30
|
+
const t = s.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '');
|
|
31
|
+
const out: number[] = [];
|
|
32
|
+
let buf = 0, n = 0;
|
|
33
|
+
for (const c of t) {
|
|
34
|
+
const v = B64.indexOf(c);
|
|
35
|
+
if (v < 0) return new Uint8Array();
|
|
36
|
+
buf = (buf << 6) | v; n += 6;
|
|
37
|
+
if (n >= 8) { n -= 8; out.push((buf >> n) & 0xff); }
|
|
38
|
+
}
|
|
39
|
+
return new Uint8Array(out);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
|
|
43
|
+
const eq = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
44
|
+
const cat = (...p: Uint8Array[]) => {
|
|
45
|
+
const out = new Uint8Array(p.reduce((n, x) => n + x.length, 0));
|
|
46
|
+
p.reduce((o, x) => (out.set(x, o), o + x.length), 0);
|
|
47
|
+
return out;
|
|
48
|
+
};
|
|
49
|
+
const utf8 = (s: string) => new TextEncoder().encode(s);
|
|
50
|
+
const parsed = (body: string): { seq?: number; id?: string } => { try { return JSON.parse(body); } catch { return {}; } };
|
|
51
|
+
const msg = (m: string): unknown[] => { try { const x = JSON.parse(m); return Array.isArray(x) ? x : []; } catch { return []; } };
|
|
52
|
+
|
|
53
|
+
/** SHA-256(prev_hash bytes || body). */
|
|
54
|
+
export const rowHash = (prev: Uint8Array, body: string) => sha256(cat(prev, utf8(body)));
|
|
55
|
+
|
|
56
|
+
/** Recompute rows; ascending and contiguous from `anchor` (or seq 1 with an empty link). */
|
|
57
|
+
export function verifyRows(rows: ChainRow[], anchor?: { seq: number; hash: string } | null): Verdict {
|
|
58
|
+
let seq = anchor?.seq ?? 0;
|
|
59
|
+
let prev = anchor ? bytes(anchor.hash) : new Uint8Array();
|
|
60
|
+
for (const [i, r] of rows.entries()) {
|
|
61
|
+
const link = bytes(r.prev_hash), h = bytes(r.hash);
|
|
62
|
+
if (!(r.seq === seq + 1 && eq(link, prev) && parsed(r.body).seq === r.seq && eq(rowHash(link, r.body), h))) {
|
|
63
|
+
return { ok: false, checked: i, firstBadSeq: r.seq, signature: null };
|
|
64
|
+
}
|
|
65
|
+
seq = r.seq;
|
|
66
|
+
prev = h;
|
|
67
|
+
}
|
|
68
|
+
return { ok: true, checked: rows.length, firstBadSeq: null, signature: null };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Ed25519 over the UTF-8 `message`; null when the key is unknown. */
|
|
72
|
+
export function verifySignature(s: { kid: string; message: string; signature: string }, keys: Keys): boolean | null {
|
|
73
|
+
const k = keys.find((x) => x.kid === s.kid);
|
|
74
|
+
if (!k) return null;
|
|
75
|
+
try { return ed25519.verify(bytes(s.signature), utf8(s.message), bytes(k.x)); } catch { return false; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The merged pages of one account: every row from the anchor to the head, then the signed checkpoint. */
|
|
79
|
+
export function verifyResponse(r: Omit<VerifyPage, 'next_cursor'>, keys: Keys): Verdict {
|
|
80
|
+
const anchor = r.anchor_seq ? { seq: r.anchor_seq, hash: r.data[0]?.prev_hash ?? '' } : null;
|
|
81
|
+
const v = verifyRows(r.data, anchor);
|
|
82
|
+
if (!v.ok) return v;
|
|
83
|
+
const last = r.data[r.data.length - 1]?.seq ?? r.anchor_seq ?? 0;
|
|
84
|
+
if (last !== r.head_seq) return { ok: false, checked: v.checked, firstBadSeq: last + 1, signature: null };
|
|
85
|
+
const cp = r.checkpoint;
|
|
86
|
+
if (!cp) return v;
|
|
87
|
+
const m = msg(cp.message);
|
|
88
|
+
const at = r.data.find((x) => x.seq === cp.seq);
|
|
89
|
+
if (m[0] !== 'wt.activity.checkpoint.v1' || m[3] !== cp.seq || m[4] !== cp.hash || (at && at.hash !== cp.hash)) {
|
|
90
|
+
return { ok: false, checked: v.checked, firstBadSeq: cp.seq, signature: false };
|
|
91
|
+
}
|
|
92
|
+
return { ...v, signature: verifySignature(cp, keys) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const node = (l: Uint8Array, x: Uint8Array) => sha256(cat(new Uint8Array([1]), l, x));
|
|
96
|
+
const half = (x: number) => Math.floor(x / 2);
|
|
97
|
+
|
|
98
|
+
/** RFC 9162 2.1.3.2 inclusion check of an already leaf-hashed `leaf`. */
|
|
99
|
+
export function merkleVerify(leaf: Uint8Array, index: number, size: number, path: string[], root: string): boolean {
|
|
100
|
+
if (index >= size) return false;
|
|
101
|
+
let f = index, s = size - 1, r = leaf;
|
|
102
|
+
for (const p of path.map(bytes)) {
|
|
103
|
+
if (s === 0) return false;
|
|
104
|
+
if (f % 2 === 1 || f === s) {
|
|
105
|
+
r = node(p, r);
|
|
106
|
+
while (f % 2 === 0 && f !== 0) { f = half(f); s = half(s); }
|
|
107
|
+
} else r = node(r, p);
|
|
108
|
+
f = half(f); s = half(s);
|
|
109
|
+
}
|
|
110
|
+
return s === 0 && eq(r, bytes(root));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** RFC 9162 2.1.4.2: `proof` shows the tree (m, oldRoot) is a prefix of (n, newRoot). */
|
|
114
|
+
export function consistencyVerify(m: number, n: number, oldRoot: string, newRoot: string, proof: string[]): boolean {
|
|
115
|
+
if (!(m >= 1 && m <= n)) return false;
|
|
116
|
+
if (m === n) return proof.length === 0 && oldRoot === newRoot;
|
|
117
|
+
const p = proof.map(bytes);
|
|
118
|
+
let x = m;
|
|
119
|
+
while (x % 2 === 0) x /= 2;
|
|
120
|
+
if (x === 1) p.unshift(bytes(oldRoot));
|
|
121
|
+
let fn = m - 1, sn = n - 1;
|
|
122
|
+
while (fn % 2 === 1) { fn = half(fn); sn = half(sn); }
|
|
123
|
+
let fr = p[0], sr = p[0];
|
|
124
|
+
if (!fr || !sr) return false;
|
|
125
|
+
for (const c of p.slice(1)) {
|
|
126
|
+
if (sn === 0) return false;
|
|
127
|
+
if (fn % 2 === 1 || fn === sn) {
|
|
128
|
+
fr = node(c, fr); sr = node(c, sr);
|
|
129
|
+
while (fn % 2 === 0 && fn !== 0) { fn = half(fn); sn = half(sn); }
|
|
130
|
+
} else sr = node(sr, c);
|
|
131
|
+
fn = half(fn); sn = half(sn);
|
|
132
|
+
}
|
|
133
|
+
return sn === 0 && eq(fr, bytes(oldRoot)) && eq(sr, bytes(newRoot));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const sthShape = (s: Sth) => {
|
|
137
|
+
const m = msg(s.message);
|
|
138
|
+
return m[0] === 'wt.activity.merkle.v1' && m[3] === s.from_seq && m[4] === s.to_seq && m[5] === s.root && s.size === s.to_seq - s.from_seq + 1;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** Two signed tree heads and the proof between them, plus (when given) the head you pinned earlier. */
|
|
142
|
+
export function verifyConsistency(c: Consistency, keys: Keys, pinned?: { size: number; root: string }): Verdict {
|
|
143
|
+
const bad: Verdict = { ok: false, checked: 0, firstBadSeq: c.sth.from_seq + c.from_size, signature: null };
|
|
144
|
+
const heads = sthShape(c.sth) && sthShape(c.from_sth) && c.sth.from_seq === c.from_sth.from_seq
|
|
145
|
+
&& c.sth.size === c.to_size && c.from_sth.size === c.from_size && c.sth.root === c.to_root && c.from_sth.root === c.from_root;
|
|
146
|
+
if (!heads || (pinned && (pinned.size !== c.from_size || pinned.root !== c.from_root))) return bad;
|
|
147
|
+
if (!consistencyVerify(c.from_size, c.to_size, c.from_root, c.to_root, c.proof)) return { ...bad, signature: false };
|
|
148
|
+
const sigs = [verifySignature(c.sth, keys), verifySignature(c.from_sth, keys)];
|
|
149
|
+
const signature = sigs.includes(false) ? false : sigs.every((x) => x === true) ? true : null;
|
|
150
|
+
return { ok: true, checked: c.to_size - c.from_size, firstBadSeq: null, signature };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** One event: its row hash, its leaf in the account's Merkle log, and the signed tree head. */
|
|
154
|
+
export function verifyProof(p: Proof, keys: Keys, eventId?: string): Verdict {
|
|
155
|
+
const bad: Verdict = { ok: false, checked: 0, firstBadSeq: p.row.seq, signature: null };
|
|
156
|
+
const b = parsed(p.row.body);
|
|
157
|
+
if (b.seq !== p.row.seq || (eventId && b.id !== eventId) || !eq(rowHash(bytes(p.row.prev_hash), p.row.body), bytes(p.row.hash))) return bad;
|
|
158
|
+
const leaf = sha256(cat(new Uint8Array([0]), bytes(p.row.hash)));
|
|
159
|
+
const m = msg(p.message);
|
|
160
|
+
const shape = m[0] === 'wt.activity.merkle.v1' && m[3] === p.from_seq && m[4] === p.to_seq && m[5] === p.root
|
|
161
|
+
&& p.index === p.row.seq - p.from_seq && p.size === p.to_seq - p.from_seq + 1 && hex(leaf) === p.leaf;
|
|
162
|
+
if (!shape || !merkleVerify(leaf, p.index, p.size, p.path, p.root)) return { ...bad, signature: false };
|
|
163
|
+
return { ok: true, checked: 1, firstBadSeq: null, signature: verifySignature(p, keys) };
|
|
164
|
+
}
|