forked from dfinity/agent-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
certificate.ts
275 lines (252 loc) · 7.51 KB
/
certificate.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
274
275
import * as cbor from './cbor';
import { AgentError } from './errors';
import { hash } from './request_id';
import { blsVerify } from './utils/bls';
import { concat, fromHex, toHex } from './utils/buffer';
import { Principal } from '@dfinity/principal';
/**
* A certificate needs to be verified (using {@link Certificate.prototype.verify})
* before it can be used.
*/
export class UnverifiedCertificateError extends AgentError {
constructor() {
super(`Cannot lookup unverified certificate. Call 'verify()' first.`);
}
}
interface Cert {
tree: HashTree;
signature: ArrayBuffer;
delegation?: Delegation;
}
const enum NodeId {
Empty = 0,
Fork = 1,
Labeled = 2,
Leaf = 3,
Pruned = 4,
}
export type HashTree =
| [NodeId.Empty]
| [NodeId.Fork, HashTree, HashTree]
| [NodeId.Labeled, ArrayBuffer, HashTree]
| [NodeId.Leaf, ArrayBuffer]
| [NodeId.Pruned, ArrayBuffer];
/**
* Make a human readable string out of a hash tree.
* @param tree
*/
export function hashTreeToString(tree: HashTree): string {
const indent = (s: string) =>
s
.split('\n')
.map(x => ' ' + x)
.join('\n');
function labelToString(label: ArrayBuffer): string {
const decoder = new TextDecoder(undefined, { fatal: true });
try {
return JSON.stringify(decoder.decode(label));
} catch (e) {
return `data(...${label.byteLength} bytes)`;
}
}
switch (tree[0]) {
case NodeId.Empty:
return '()';
case NodeId.Fork: {
const left = hashTreeToString(tree[1]);
const right = hashTreeToString(tree[2]);
return `sub(\n left:\n${indent(left)}\n---\n right:\n${indent(right)}\n)`;
}
case NodeId.Labeled: {
const label = labelToString(tree[1]);
const sub = hashTreeToString(tree[2]);
return `label(\n label:\n${indent(label)}\n sub:\n${indent(sub)}\n)`;
}
case NodeId.Leaf: {
return `leaf(...${tree[1].byteLength} bytes)`;
}
case NodeId.Pruned: {
return `pruned(${toHex(new Uint8Array(tree[1]))}`;
}
default: {
return `unknown(${JSON.stringify(tree[0])})`;
}
}
}
interface Delegation extends Record<string, any> {
subnet_id: ArrayBuffer;
certificate: ArrayBuffer;
}
function isBufferEqual(a: ArrayBuffer, b: ArrayBuffer): boolean {
if (a.byteLength !== b.byteLength) {
return false;
}
const a8 = new Uint8Array(a);
const b8 = new Uint8Array(b);
for (let i = 0; i < a8.length; i++) {
if (a8[i] !== b8[i]) {
return false;
}
}
return true;
}
export class Certificate {
private readonly cert: Cert;
private verified = false;
constructor(certificate: ArrayBuffer, private _rootKey: Promise<ArrayBuffer>) {
this.cert = cbor.decode(new Uint8Array(certificate));
}
public lookup(path: Array<ArrayBuffer | string>): ArrayBuffer | undefined {
this.checkState();
return lookup_path(path, this.cert.tree);
}
public async verify(canisterId: Principal): Promise<boolean> {
const rootHash = await reconstruct(this.cert.tree);
const derKey = await this._checkDelegationAndGetKey(canisterId, this.cert.delegation);
const sig = this.cert.signature;
const key = extractDER(derKey);
const msg = concat(domain_sep('ic-state-root'), rootHash);
const res = await blsVerify(new Uint8Array(key), new Uint8Array(sig), new Uint8Array(msg));
this.verified = res;
return res;
}
protected checkState(): void {
if (!this.verified) {
throw new UnverifiedCertificateError();
}
}
private async _checkDelegationAndGetKey(
canisterId: Principal,
d?: Delegation,
): Promise<ArrayBuffer> {
if (!d) {
return this._rootKey;
}
const cert: Certificate = new Certificate(d.certificate, this._rootKey);
if (!(await cert.verify(canisterId))) {
throw new Error('fail to verify delegation certificate');
}
if (canisterId.compareTo(Principal.managementCanister()) != 'eq') {
const rangeLookup = cert.lookup(['subnet', d.subnet_id, 'canister_ranges']);
if (!rangeLookup) {
throw new Error(`Could not find canister ranges for subnet 0x${toHex(d.subnet_id)}`);
}
const ranges_arr: Array<[Uint8Array, Uint8Array]> = cbor.decode(rangeLookup);
const ranges: Array<[Principal, Principal]> = ranges_arr.map(v => [
Principal.fromUint8Array(v[0]),
Principal.fromUint8Array(v[1]),
]);
const canisterInRange = ranges.some(r => r[0].ltEq(canisterId) && r[1].gtEq(canisterId));
if (!canisterInRange) {
throw new Error(
`Canister ${canisterId} not in range of delegations for subnet 0x${toHex(d.subnet_id)}`,
);
}
}
const publicKeyLookup = cert.lookup(['subnet', d.subnet_id, 'public_key']);
if (!publicKeyLookup) {
throw new Error(`Could not find subnet key for subnet 0x${toHex(d.subnet_id)}`);
}
return publicKeyLookup;
}
}
const DER_PREFIX = fromHex(
'308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100',
);
const KEY_LENGTH = 96;
function extractDER(buf: ArrayBuffer): ArrayBuffer {
const expectedLength = DER_PREFIX.byteLength + KEY_LENGTH;
if (buf.byteLength !== expectedLength) {
throw new TypeError(`BLS DER-encoded public key must be ${expectedLength} bytes long`);
}
const prefix = buf.slice(0, DER_PREFIX.byteLength);
if (!isBufferEqual(prefix, DER_PREFIX)) {
throw new TypeError(
`BLS DER-encoded public key is invalid. Expect the following prefix: ${DER_PREFIX}, but get ${prefix}`,
);
}
return buf.slice(DER_PREFIX.byteLength);
}
/**
* @param t
*/
export async function reconstruct(t: HashTree): Promise<ArrayBuffer> {
switch (t[0]) {
case NodeId.Empty:
return hash(domain_sep('ic-hashtree-empty'));
case NodeId.Pruned:
return t[1] as ArrayBuffer;
case NodeId.Leaf:
return hash(concat(domain_sep('ic-hashtree-leaf'), t[1] as ArrayBuffer));
case NodeId.Labeled:
return hash(
concat(
domain_sep('ic-hashtree-labeled'),
t[1] as ArrayBuffer,
await reconstruct(t[2] as HashTree),
),
);
case NodeId.Fork:
return hash(
concat(
domain_sep('ic-hashtree-fork'),
await reconstruct(t[1] as HashTree),
await reconstruct(t[2] as HashTree),
),
);
default:
throw new Error('unreachable');
}
}
function domain_sep(s: string): ArrayBuffer {
const len = new Uint8Array([s.length]);
const str = new TextEncoder().encode(s);
return concat(len, str);
}
/**
* @param path
* @param tree
*/
export function lookup_path(
path: Array<ArrayBuffer | string>,
tree: HashTree,
): ArrayBuffer | undefined {
if (path.length === 0) {
switch (tree[0]) {
case NodeId.Leaf: {
return new Uint8Array(tree[1]).buffer;
}
default: {
return undefined;
}
}
}
const label = typeof path[0] === 'string' ? new TextEncoder().encode(path[0]) : path[0];
const t = find_label(label, flatten_forks(tree));
if (t) {
return lookup_path(path.slice(1), t);
}
}
function flatten_forks(t: HashTree): HashTree[] {
switch (t[0]) {
case NodeId.Empty:
return [];
case NodeId.Fork:
return flatten_forks(t[1] as HashTree).concat(flatten_forks(t[2] as HashTree));
default:
return [t];
}
}
function find_label(l: ArrayBuffer, trees: HashTree[]): HashTree | undefined {
if (trees.length === 0) {
return undefined;
}
for (const t of trees) {
if (t[0] === NodeId.Labeled) {
const p = t[1] as ArrayBuffer;
if (isBufferEqual(l, p)) {
return t[2];
}
}
}
}