-
Notifications
You must be signed in to change notification settings - Fork 89
/
index.ts
1017 lines (913 loc) · 34.3 KB
/
index.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { JsonObject } from '@dfinity/candid';
import { Principal } from '@dfinity/principal';
import { AgentError } from '../../errors';
import { AnonymousIdentity, Identity } from '../../auth';
import * as cbor from '../../cbor';
import { RequestId, hashOfMap, requestIdOf } from '../../request_id';
import { bufFromBufLike, concat, fromHex } from '../../utils/buffer';
import {
Agent,
ApiQueryResponse,
QueryFields,
QueryResponse,
ReadStateOptions,
ReadStateResponse,
SubmitResponse,
} from '../api';
import { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';
import {
CallRequest,
Endpoint,
HttpAgentRequest,
HttpAgentRequestTransformFn,
HttpAgentSubmitRequest,
makeNonce,
Nonce,
QueryRequest,
ReadRequestType,
SubmitRequestType,
} from './types';
import { AgentHTTPResponseError } from './errors';
import { SubnetStatus, request } from '../../canisterStatus';
import { CertificateVerificationError, HashTree, lookup_path } from '../../certificate';
import { ed25519 } from '@noble/curves/ed25519';
import { ExpirableMap } from '../../utils/expirableMap';
import { Ed25519PublicKey } from '../../public_key';
import { decodeTime } from '../../utils/leb';
import { ObservableLog } from '../../observable';
import { BackoffStrategy, BackoffStrategyFactory, ExponentialBackoff } from '../../polling/backoff';
export * from './transforms';
export { Nonce, makeNonce } from './types';
export enum RequestStatusResponseStatus {
Received = 'received',
Processing = 'processing',
Replied = 'replied',
Rejected = 'rejected',
Unknown = 'unknown',
Done = 'done',
}
// Default delta for ingress expiry is 5 minutes.
const DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;
// Root public key for the IC, encoded as hex
export const IC_ROOT_KEY =
'308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +
'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +
'5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +
'b01291091c5f87b98883463f98091a0baaae';
export const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';
// IC0 domain info
const IC0_DOMAIN = 'ic0.app';
const IC0_SUB_DOMAIN = '.ic0.app';
const ICP0_DOMAIN = 'icp0.io';
const ICP0_SUB_DOMAIN = '.icp0.io';
const ICP_API_DOMAIN = 'icp-api.io';
const ICP_API_SUB_DOMAIN = '.icp-api.io';
class HttpDefaultFetchError extends AgentError {
constructor(public readonly message: string) {
super(message);
}
}
export class IdentityInvalidError extends AgentError {
constructor(public readonly message: string) {
super(message);
}
}
// HttpAgent options that can be used at construction.
export interface HttpAgentOptions {
// Another HttpAgent to inherit configuration (pipeline and fetch) of. This
// is only used at construction.
source?: HttpAgent;
// A surrogate to the global fetch function. Useful for testing.
fetch?: typeof fetch;
// Additional options to pass along to fetch. Will not override fields that
// the agent already needs to set
// Should follow the RequestInit interface, but we intentially support non-standard fields
fetchOptions?: Record<string, unknown>;
// Additional options to pass along to fetch for the call API.
callOptions?: Record<string, unknown>;
// The host to use for the client. By default, uses the same host as
// the current page.
host?: string;
// The principal used to send messages. This cannot be empty at the request
// time (will throw).
identity?: Identity | Promise<Identity>;
credentials?: {
name: string;
password?: string;
};
/**
* Adds a unique {@link Nonce} with each query.
* Enabling will prevent queries from being answered with a cached response.
* @example
* const agent = new HttpAgent({ useQueryNonces: true });
* agent.addTransform(makeNonceTransform(makeNonce);
* @default false
*/
useQueryNonces?: boolean;
/**
* Number of times to retry requests before throwing an error
* @default 3
*/
retryTimes?: number;
/**
* The strategy to use for backoff when retrying requests
*/
backoffStrategy?: BackoffStrategyFactory;
/**
* Whether the agent should verify signatures signed by node keys on query responses. Increases security, but adds overhead and must make a separate request to cache the node keys for the canister's subnet.
* @default true
*/
verifyQuerySignatures?: boolean;
/**
* Whether to log to the console. Defaults to false.
*/
logToConsole?: boolean;
}
function getDefaultFetch(): typeof fetch {
let defaultFetch;
if (typeof window !== 'undefined') {
// Browser context
if (window.fetch) {
defaultFetch = window.fetch.bind(window);
} else {
throw new HttpDefaultFetchError(
'Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.',
);
}
} else if (typeof global !== 'undefined') {
// Node context
if (global.fetch) {
defaultFetch = global.fetch.bind(global);
} else {
throw new HttpDefaultFetchError(
'Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.',
);
}
} else if (typeof self !== 'undefined') {
if (self.fetch) {
defaultFetch = self.fetch.bind(self);
}
}
if (defaultFetch) {
return defaultFetch;
}
throw new HttpDefaultFetchError(
'Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.',
);
}
// A HTTP agent allows users to interact with a client of the internet computer
// using the available methods. It exposes an API that closely follows the
// public view of the internet computer, and is not intended to be exposed
// directly to the majority of users due to its low-level interface.
//
// There is a pipeline to apply transformations to the request before sending
// it to the client. This is to decouple signature, nonce generation and
// other computations so that this class can stay as simple as possible while
// allowing extensions.
export class HttpAgent implements Agent {
public rootKey = fromHex(IC_ROOT_KEY);
private _identity: Promise<Identity> | null;
private readonly _fetch: typeof fetch;
private readonly _fetchOptions?: Record<string, unknown>;
private readonly _callOptions?: Record<string, unknown>;
private _timeDiffMsecs = 0;
private readonly _host: URL;
private readonly _credentials: string | undefined;
private _rootKeyFetched = false;
#retryTimes; // Retry requests N times before erroring by default
#backoffStrategy: BackoffStrategyFactory;
public readonly _isAgent = true;
// The UTC time in milliseconds when the latest request was made
#waterMark = 0;
get waterMark(): number {
return this.#waterMark;
}
public log: ObservableLog = new ObservableLog();
#queryPipeline: HttpAgentRequestTransformFn[] = [];
#updatePipeline: HttpAgentRequestTransformFn[] = [];
#subnetKeys: ExpirableMap<string, SubnetStatus> = new ExpirableMap({
expirationTime: 5 * 60 * 1000, // 5 minutes
});
#verifyQuerySignatures = true;
constructor(options: HttpAgentOptions = {}) {
if (options.source) {
if (!(options.source instanceof HttpAgent)) {
throw new Error("An Agent's source can only be another HttpAgent");
}
this._identity = options.source._identity;
this._fetch = options.source._fetch;
this._host = options.source._host;
this._credentials = options.source._credentials;
} else {
this._fetch = options.fetch || getDefaultFetch() || fetch.bind(global);
this._fetchOptions = options.fetchOptions;
this._callOptions = options.callOptions;
}
if (options.host !== undefined) {
if (!options.host.match(/^[a-z]+:/) && typeof window !== 'undefined') {
this._host = new URL(window.location.protocol + '//' + options.host);
} else {
this._host = new URL(options.host);
}
} else if (options.source !== undefined) {
// Safe to ignore here.
this._host = options.source._host;
} else {
const location = typeof window !== 'undefined' ? window.location : undefined;
if (!location) {
this._host = new URL('https://icp-api.io');
this.log.warn(
'Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning.',
);
}
// Mainnet, local, and remote environments will have the api route available
const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];
const remoteHosts = ['.github.dev', '.gitpod.io'];
const hostname = location?.hostname;
let knownHost;
if (hostname && typeof hostname === 'string') {
if (remoteHosts.some(host => hostname.endsWith(host))) {
knownHost = hostname;
} else {
knownHost = knownHosts.find(host => hostname.endsWith(host));
}
}
if (location && knownHost) {
// If the user is on a boundary-node provided host, we can use the same host for the agent
this._host = new URL(
`${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`,
);
} else {
this._host = new URL('https://icp-api.io');
this.log.warn(
'Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning.',
);
}
}
if (options.verifyQuerySignatures !== undefined) {
this.#verifyQuerySignatures = options.verifyQuerySignatures;
}
// Default is 3
this.#retryTimes = options.retryTimes ?? 3;
// Delay strategy for retries. Default is exponential backoff
const defaultBackoffFactory = () =>
new ExponentialBackoff({
maxIterations: this.#retryTimes,
});
this.#backoffStrategy = options.backoffStrategy || defaultBackoffFactory;
// Rewrite to avoid redirects
if (this._host.hostname.endsWith(IC0_SUB_DOMAIN)) {
this._host.hostname = IC0_DOMAIN;
} else if (this._host.hostname.endsWith(ICP0_SUB_DOMAIN)) {
this._host.hostname = ICP0_DOMAIN;
} else if (this._host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {
this._host.hostname = ICP_API_DOMAIN;
}
if (options.credentials) {
const { name, password } = options.credentials;
this._credentials = `${name}${password ? ':' + password : ''}`;
}
this._identity = Promise.resolve(options.identity || new AnonymousIdentity());
// Add a nonce transform to ensure calls are unique
this.addTransform('update', makeNonceTransform(makeNonce));
if (options.useQueryNonces) {
this.addTransform('query', makeNonceTransform(makeNonce));
}
if (options.logToConsole) {
this.log.subscribe(log => {
if (log.level === 'error') {
console.error(log.message);
} else if (log.level === 'warn') {
console.warn(log.message);
} else {
console.log(log.message);
}
});
}
}
public isLocal(): boolean {
const hostname = this._host.hostname;
return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');
}
public addTransform(
type: 'update' | 'query',
fn: HttpAgentRequestTransformFn,
priority = fn.priority || 0,
): void {
if (type === 'update') {
// Keep the pipeline sorted at all time, by priority.
const i = this.#updatePipeline.findIndex(x => (x.priority || 0) < priority);
this.#updatePipeline.splice(
i >= 0 ? i : this.#updatePipeline.length,
0,
Object.assign(fn, { priority }),
);
} else if (type === 'query') {
// Keep the pipeline sorted at all time, by priority.
const i = this.#queryPipeline.findIndex(x => (x.priority || 0) < priority);
this.#queryPipeline.splice(
i >= 0 ? i : this.#queryPipeline.length,
0,
Object.assign(fn, { priority }),
);
}
}
public async getPrincipal(): Promise<Principal> {
if (!this._identity) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
return (await this._identity).getPrincipal();
}
public async call(
canisterId: Principal | string,
options: {
methodName: string;
arg: ArrayBuffer;
effectiveCanisterId?: Principal | string;
},
identity?: Identity | Promise<Identity>,
): Promise<SubmitResponse> {
const id = await (identity !== undefined ? await identity : await this._identity);
if (!id) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
const canister = Principal.from(canisterId);
const ecid = options.effectiveCanisterId
? Principal.from(options.effectiveCanisterId)
: canister;
const sender: Principal = id.getPrincipal() || Principal.anonymous();
let ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS);
// If the value is off by more than 30 seconds, reconcile system time with the network
if (Math.abs(this._timeDiffMsecs) > 1_000 * 30) {
ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS + this._timeDiffMsecs);
}
const submit: CallRequest = {
request_type: SubmitRequestType.Call,
canister_id: canister,
method_name: options.methodName,
arg: options.arg,
sender,
ingress_expiry,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let transformedRequest: any = (await this._transform({
request: {
body: null,
method: 'POST',
headers: {
'Content-Type': 'application/cbor',
...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),
},
},
endpoint: Endpoint.Call,
body: submit,
})) as HttpAgentSubmitRequest;
// Apply transform for identity.
transformedRequest = await id.transformRequest(transformedRequest);
const body = cbor.encode(transformedRequest.body);
this.log(`fetching "/api/v2/canister/${ecid.toText()}/call" with request:`, transformedRequest);
// Run both in parallel. The fetch is quite expensive, so we have plenty of time to
// calculate the requestId locally.
const backoff = this.#backoffStrategy();
const request = this.#requestAndRetry({
request: () =>
this._fetch('' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this._host), {
...this._callOptions,
...transformedRequest.request,
body,
}),
backoff,
tries: 0,
});
const [response, requestId] = await Promise.all([request, requestIdOf(submit)]);
const responseBuffer = await response.arrayBuffer();
const responseBody = (
response.status === 200 && responseBuffer.byteLength > 0 ? cbor.decode(responseBuffer) : null
) as SubmitResponse['response']['body'];
return {
requestId,
response: {
ok: response.ok,
status: response.status,
statusText: response.statusText,
body: responseBody,
headers: httpHeadersTransform(response.headers),
},
};
}
async #requestAndRetryQuery(args: {
ecid: Principal;
transformedRequest: HttpAgentRequest;
body: ArrayBuffer;
requestId: RequestId;
backoff: BackoffStrategy;
tries: number;
}): Promise<ApiQueryResponse> {
const { ecid, transformedRequest, body, requestId, backoff, tries } = args;
const delay = tries === 0 ? 0 : backoff.next();
this.log(`fetching "/api/v2/canister/${ecid.toString()}/query" with tries:`, {
tries,
backoff,
delay,
});
// If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason
if (delay === null) {
throw new AgentError(
`Timestamp failed to pass the watermark after retrying the configured ${
this.#retryTimes
} times. We cannot guarantee the integrity of the response since it could be a replay attack.`,
);
}
if (delay > 0) {
await new Promise(resolve => setTimeout(resolve, delay));
}
let response: ApiQueryResponse;
// Make the request and retry if it throws an error
try {
this.log(
`fetching "/api/v2/canister/${ecid.toString()}/query" with request:`,
transformedRequest,
);
const fetchResponse = await this._fetch(
'' + new URL(`/api/v2/canister/${ecid.toString()}/query`, this._host),
{
...this._fetchOptions,
...transformedRequest.request,
body,
},
);
if (fetchResponse.status === 200) {
const queryResponse: QueryResponse = cbor.decode(await fetchResponse.arrayBuffer());
response = {
...queryResponse,
httpDetails: {
ok: fetchResponse.ok,
status: fetchResponse.status,
statusText: fetchResponse.statusText,
headers: httpHeadersTransform(fetchResponse.headers),
},
requestId,
};
} else {
throw new AgentHTTPResponseError(
`Server returned an error:\n` +
` Code: ${fetchResponse.status} (${fetchResponse.statusText})\n` +
` Body: ${await fetchResponse.text()}\n`,
{
ok: fetchResponse.ok,
status: fetchResponse.status,
statusText: fetchResponse.statusText,
headers: httpHeadersTransform(fetchResponse.headers),
},
);
}
} catch (error) {
if (tries < this.#retryTimes) {
this.log.warn(
`Caught exception while attempting to make query:\n` +
` ${error}\n` +
` Retrying query.`,
);
return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
}
throw error;
}
const timestamp = response.signatures?.[0]?.timestamp;
// Skip watermark verification if the user has set verifyQuerySignatures to false
if (!this.#verifyQuerySignatures) {
return response;
}
if (!timestamp) {
throw new Error(
'Timestamp not found in query response. This suggests a malformed or malicious response.',
);
}
// Convert the timestamp to milliseconds
const timeStampInMs = Number(BigInt(timestamp) / BigInt(1_000_000));
this.log('watermark and timestamp', {
waterMark: this.waterMark,
timestamp: timeStampInMs,
});
// If the timestamp is less than the watermark, retry the request up to the retry limit
if (Number(this.waterMark) > timeStampInMs) {
const error = new AgentError('Timestamp is below the watermark. Retrying query.');
this.log.error('Timestamp is below', error, {
timestamp,
waterMark: this.waterMark,
});
if (tries < this.#retryTimes) {
return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
}
{
throw new AgentError(
`Timestamp failed to pass the watermark after retrying the configured ${
this.#retryTimes
} times. We cannot guarantee the integrity of the response since it could be a replay attack.`,
);
}
}
return response;
}
async #requestAndRetry(args: {
request: () => Promise<Response>;
backoff: BackoffStrategy;
tries: number;
}): Promise<Response> {
const { request, backoff, tries } = args;
const delay = tries === 0 ? 0 : backoff.next();
// If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason
if (delay === null) {
throw new AgentError(
`Timestamp failed to pass the watermark after retrying the configured ${
this.#retryTimes
} times. We cannot guarantee the integrity of the response since it could be a replay attack.`,
);
}
if (delay > 0) {
await new Promise(resolve => setTimeout(resolve, delay));
}
let response: Response;
try {
response = await request();
} catch (error) {
if (this.#retryTimes > tries) {
this.log.warn(
`Caught exception while attempting to make request:\n` +
` ${error}\n` +
` Retrying request.`,
);
// Delay the request by the configured backoff strategy
return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });
}
throw error;
}
if (response.ok) {
return response;
}
const responseText = await response.clone().text();
const errorMessage =
`Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${responseText}\n`;
if (tries < this.#retryTimes) {
return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });
}
throw new AgentHTTPResponseError(errorMessage, {
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: httpHeadersTransform(response.headers),
});
}
public async query(
canisterId: Principal | string,
fields: QueryFields,
identity?: Identity | Promise<Identity>,
): Promise<ApiQueryResponse> {
const backoff = this.#backoffStrategy();
const ecid = fields.effectiveCanisterId
? Principal.from(fields.effectiveCanisterId)
: Principal.from(canisterId);
this.log(`ecid ${ecid.toString()}`);
this.log(`canisterId ${canisterId.toString()}`);
const makeQuery = async () => {
const id = await (identity !== undefined ? await identity : await this._identity);
if (!id) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
const canister = Principal.from(canisterId);
const sender = id?.getPrincipal() || Principal.anonymous();
const request: QueryRequest = {
request_type: ReadRequestType.Query,
canister_id: canister,
method_name: fields.methodName,
arg: fields.arg,
sender,
ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),
};
const requestId = await requestIdOf(request);
// TODO: remove this any. This can be a Signed or UnSigned request.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let transformedRequest: HttpAgentRequest = await this._transform({
request: {
method: 'POST',
headers: {
'Content-Type': 'application/cbor',
...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),
},
},
endpoint: Endpoint.Query,
body: request,
});
// Apply transform for identity.
transformedRequest = (await id?.transformRequest(transformedRequest)) as HttpAgentRequest;
const body = cbor.encode(transformedRequest.body);
const args = {
canister: canister.toText(),
ecid,
transformedRequest,
body,
requestId,
backoff,
tries: 0,
};
return await this.#requestAndRetryQuery(args);
};
const getSubnetStatus = async (): Promise<SubnetStatus | void> => {
if (!this.#verifyQuerySignatures) {
return undefined;
}
const subnetStatus = this.#subnetKeys.get(ecid.toString());
if (subnetStatus) {
return subnetStatus;
}
await this.fetchSubnetKeys(ecid.toString());
return this.#subnetKeys.get(ecid.toString());
};
// Attempt to make the query i=retryTimes times
// Make query and fetch subnet keys in parallel
const [query, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);
this.log('Query response:', query);
// Skip verification if the user has disabled it
if (!this.#verifyQuerySignatures) {
return query;
}
try {
return this.#verifyQueryResponse(query, subnetStatus);
} catch (_) {
// In case the node signatures have changed, refresh the subnet keys and try again
this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
this.#subnetKeys.delete(canisterId.toString());
await this.fetchSubnetKeys(ecid.toString());
const updatedSubnetStatus = this.#subnetKeys.get(canisterId.toString());
if (!updatedSubnetStatus) {
throw new CertificateVerificationError(
'Invalid signature from replica signed query: no matching node key found.',
);
}
return this.#verifyQueryResponse(query, updatedSubnetStatus);
}
}
/**
* See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation
* @param queryResponse - The response from the query
* @param subnetStatus - The subnet status, including all node keys
* @returns ApiQueryResponse
*/
#verifyQueryResponse = (
queryResponse: ApiQueryResponse,
subnetStatus: SubnetStatus | void,
): ApiQueryResponse => {
if (this.#verifyQuerySignatures === false) {
// This should not be called if the user has disabled verification
return queryResponse;
}
if (!subnetStatus) {
throw new CertificateVerificationError(
'Invalid signature from replica signed query: no matching node key found.',
);
}
const { status, signatures = [], requestId } = queryResponse;
const domainSeparator = new TextEncoder().encode('\x0Bic-response');
for (const sig of signatures) {
const { timestamp, identity } = sig;
const nodeId = Principal.fromUint8Array(identity).toText();
let hash: ArrayBuffer;
// Hash is constructed differently depending on the status
if (status === 'replied') {
const { reply } = queryResponse;
hash = hashOfMap({
status: status,
reply: reply,
timestamp: BigInt(timestamp),
request_id: requestId,
});
} else if (status === 'rejected') {
const { reject_code, reject_message, error_code } = queryResponse;
hash = hashOfMap({
status: status,
reject_code: reject_code,
reject_message: reject_message,
error_code: error_code,
timestamp: BigInt(timestamp),
request_id: requestId,
});
} else {
throw new Error(`Unknown status: ${status}`);
}
const separatorWithHash = concat(domainSeparator, new Uint8Array(hash));
// FIX: check for match without verifying N times
const pubKey = subnetStatus?.nodeKeys.get(nodeId);
if (!pubKey) {
throw new CertificateVerificationError(
'Invalid signature from replica signed query: no matching node key found.',
);
}
const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;
const valid = ed25519.verify(
sig.signature,
new Uint8Array(separatorWithHash),
new Uint8Array(rawKey),
);
if (valid) return queryResponse;
throw new CertificateVerificationError(
`Invalid signature from replica ${nodeId} signed query.`,
);
}
return queryResponse;
};
public async createReadStateRequest(
fields: ReadStateOptions,
identity?: Identity | Promise<Identity>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
const id = await (identity !== undefined ? await identity : await this._identity);
if (!id) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
const sender = id?.getPrincipal() || Principal.anonymous();
// TODO: remove this any. This can be a Signed or UnSigned request.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const transformedRequest: any = await this._transform({
request: {
method: 'POST',
headers: {
'Content-Type': 'application/cbor',
...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),
},
},
endpoint: Endpoint.ReadState,
body: {
request_type: ReadRequestType.ReadState,
paths: fields.paths,
sender,
ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),
},
});
// Apply transform for identity.
return id?.transformRequest(transformedRequest);
}
public async readState(
canisterId: Principal | string,
fields: ReadStateOptions,
identity?: Identity | Promise<Identity>,
// eslint-disable-next-line
request?: any,
): Promise<ReadStateResponse> {
const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;
const transformedRequest = request ?? (await this.createReadStateRequest(fields, identity));
const body = cbor.encode(transformedRequest.body);
this.log(
`fetching "/api/v2/canister/${canister}/read_state" with request:`,
transformedRequest,
);
// TODO - https://dfinity.atlassian.net/browse/SDK-1092
const backoff = this.#backoffStrategy();
const response = await this.#requestAndRetry({
request: () =>
this._fetch(
'' + new URL(`/api/v2/canister/${canister.toString()}/read_state`, this._host),
{
...this._fetchOptions,
...transformedRequest.request,
body,
},
),
backoff,
tries: 0,
});
if (!response.ok) {
throw new Error(
`Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${await response.text()}\n`,
);
}
const decodedResponse: ReadStateResponse = cbor.decode(await response.arrayBuffer());
this.log('Read state response:', decodedResponse);
const parsedTime = await this.parseTimeFromResponse(decodedResponse);
if (parsedTime > 0) {
this.log('Read state response time:', parsedTime);
this.#waterMark = parsedTime;
}
return decodedResponse;
}
public async parseTimeFromResponse(response: ReadStateResponse): Promise<number> {
let tree: HashTree;
if (response.certificate) {
const decoded: { tree: HashTree } | undefined = cbor.decode(response.certificate);
if (decoded && 'tree' in decoded) {
tree = decoded.tree;
} else {
throw new Error('Could not decode time from response');
}
const timeLookup = lookup_path(['time'], tree);
if (!timeLookup) {
throw new Error('Time was not found in the response or was not in its expected format.');
}
if (!(timeLookup instanceof ArrayBuffer) && !ArrayBuffer.isView(timeLookup)) {
throw new Error('Time was not found in the response or was not in its expected format.');
}
const date = decodeTime(bufFromBufLike(timeLookup));
this.log('Time from response:', date);
this.log('Time from response in milliseconds:', Number(date));
return Number(date);
} else {
this.log.warn('No certificate found in response');
}
return 0;
}
/**
* Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request
* @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
*/
public async syncTime(canisterId?: Principal): Promise<void> {
const CanisterStatus = await import('../../canisterStatus');
const callTime = Date.now();
try {
if (!canisterId) {
this.log(
'Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai',
);
}
const status = await CanisterStatus.request({
// Fall back with canisterId of the ICP Ledger
canisterId: canisterId ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),
agent: this,
paths: ['time'],
});
const replicaTime = status.get('time');
if (replicaTime) {
this._timeDiffMsecs = Number(replicaTime as bigint) - Number(callTime);
}
} catch (error) {
this.log.error('Caught exception while attempting to sync time', error as AgentError);
}
}
public async status(): Promise<JsonObject> {
const headers: Record<string, string> = this._credentials
? {
Authorization: 'Basic ' + btoa(this._credentials),
}
: {};
this.log(`fetching "/api/v2/status"`);
const backoff = this.#backoffStrategy();
const response = await this.#requestAndRetry({
backoff,
request: () =>
this._fetch('' + new URL(`/api/v2/status`, this._host), { headers, ...this._fetchOptions }),
tries: 0,
});
return cbor.decode(await response.arrayBuffer());
}
public async fetchRootKey(): Promise<ArrayBuffer> {
if (!this._rootKeyFetched) {
// Hex-encoded version of the replica root key
this.rootKey = ((await this.status()) as JsonObject & { root_key: ArrayBuffer }).root_key;
this._rootKeyFetched = true;
}
return this.rootKey;
}
public invalidateIdentity(): void {
this._identity = null;
}
public replaceIdentity(identity: Identity): void {
this._identity = Promise.resolve(identity);
}
public async fetchSubnetKeys(canisterId: Principal | string) {
const effectiveCanisterId: Principal = Principal.from(canisterId);
const response = await request({
canisterId: effectiveCanisterId,
paths: ['subnet'],
agent: this,
});
const subnetResponse = response.get('subnet');
if (subnetResponse && typeof subnetResponse === 'object' && 'nodeKeys' in subnetResponse) {
this.#subnetKeys.set(effectiveCanisterId.toText(), subnetResponse as SubnetStatus);
return subnetResponse as SubnetStatus;
}
// If the subnet status is not returned, return undefined
return undefined;