@icp-sdk/core 5.0.0-beta.0 → 5.0.0-beta.2
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/README.md +0 -2
- package/lib/cjs/agent/actor.js +2 -2
- package/lib/cjs/agent/actor.js.map +1 -1
- package/lib/cjs/agent/agent/api.d.ts +6 -6
- package/lib/cjs/agent/agent/api.js +4 -4
- package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts +30 -0
- package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -1
- package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js +33 -1
- package/lib/cjs/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -1
- package/lib/cjs/agent/agent/http/index.d.ts +23 -5
- package/lib/cjs/agent/agent/http/index.d.ts.map +1 -1
- package/lib/cjs/agent/agent/http/index.js +201 -86
- package/lib/cjs/agent/agent/http/index.js.map +1 -1
- package/lib/cjs/agent/agent/index.d.ts +2 -0
- package/lib/cjs/agent/agent/index.d.ts.map +1 -1
- package/lib/cjs/agent/agent/index.js +2 -0
- package/lib/cjs/agent/agent/index.js.map +1 -1
- package/lib/cjs/agent/canisterStatus/index.d.ts +18 -50
- package/lib/cjs/agent/canisterStatus/index.d.ts.map +1 -1
- package/lib/cjs/agent/canisterStatus/index.js +30 -97
- package/lib/cjs/agent/canisterStatus/index.js.map +1 -1
- package/lib/cjs/agent/certificate.d.ts +68 -10
- package/lib/cjs/agent/certificate.d.ts.map +1 -1
- package/lib/cjs/agent/certificate.js +198 -27
- package/lib/cjs/agent/certificate.js.map +1 -1
- package/lib/cjs/agent/constants.d.ts +4 -0
- package/lib/cjs/agent/constants.d.ts.map +1 -1
- package/lib/cjs/agent/constants.js +5 -1
- package/lib/cjs/agent/constants.js.map +1 -1
- package/lib/cjs/agent/errors.d.ts +9 -2
- package/lib/cjs/agent/errors.d.ts.map +1 -1
- package/lib/cjs/agent/errors.js +19 -7
- package/lib/cjs/agent/errors.js.map +1 -1
- package/lib/cjs/agent/index.d.ts +97 -5
- package/lib/cjs/agent/index.d.ts.map +1 -1
- package/lib/cjs/agent/index.js +92 -11
- package/lib/cjs/agent/index.js.map +1 -1
- package/lib/cjs/agent/polling/index.js +1 -1
- package/lib/cjs/agent/polling/index.js.map +1 -1
- package/lib/cjs/agent/subnetStatus/index.d.ts +70 -0
- package/lib/cjs/agent/subnetStatus/index.d.ts.map +1 -0
- package/lib/cjs/agent/subnetStatus/index.js +219 -0
- package/lib/cjs/agent/subnetStatus/index.js.map +1 -0
- package/lib/cjs/agent/utils/readState.d.ts +84 -0
- package/lib/cjs/agent/utils/readState.d.ts.map +1 -0
- package/lib/cjs/agent/utils/readState.js +149 -0
- package/lib/cjs/agent/utils/readState.js.map +1 -0
- package/lib/cjs/candid/index.d.ts +20 -1
- package/lib/cjs/candid/index.d.ts.map +1 -1
- package/lib/cjs/candid/index.js +20 -1
- package/lib/cjs/candid/index.js.map +1 -1
- package/lib/cjs/identity/index.d.ts +30 -7
- package/lib/cjs/identity/index.d.ts.map +1 -1
- package/lib/cjs/identity/index.js +31 -11
- package/lib/cjs/identity/index.js.map +1 -1
- package/lib/cjs/identity/secp256k1/index.d.ts +48 -1
- package/lib/cjs/identity/secp256k1/index.d.ts.map +1 -1
- package/lib/cjs/identity/secp256k1/index.js +48 -1
- package/lib/cjs/identity/secp256k1/index.js.map +1 -1
- package/lib/cjs/identity/secp256k1/pem.d.ts.map +1 -1
- package/lib/cjs/identity/secp256k1/pem.js +1 -2
- package/lib/cjs/identity/secp256k1/pem.js.map +1 -1
- package/lib/cjs/principal/index.d.ts +15 -0
- package/lib/cjs/principal/index.d.ts.map +1 -1
- package/lib/cjs/principal/index.js +15 -0
- package/lib/cjs/principal/index.js.map +1 -1
- package/lib/esm/agent/actor.js +3 -3
- package/lib/esm/agent/actor.js.map +1 -1
- package/lib/esm/agent/agent/api.d.ts +6 -6
- package/lib/esm/agent/agent/api.js +3 -3
- package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts +30 -0
- package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.d.ts.map +1 -1
- package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js +33 -1
- package/lib/esm/agent/agent/http/__certificates__/goldenCertificates.js.map +1 -1
- package/lib/esm/agent/agent/http/index.d.ts +23 -5
- package/lib/esm/agent/agent/http/index.d.ts.map +1 -1
- package/lib/esm/agent/agent/http/index.js +203 -84
- package/lib/esm/agent/agent/http/index.js.map +1 -1
- package/lib/esm/agent/agent/index.d.ts +2 -0
- package/lib/esm/agent/agent/index.d.ts.map +1 -1
- package/lib/esm/agent/agent/index.js +2 -0
- package/lib/esm/agent/agent/index.js.map +1 -1
- package/lib/esm/agent/canister-env/index.d.ts +2 -1
- package/lib/esm/agent/canister-env/index.d.ts.map +1 -1
- package/lib/esm/agent/canister-env/index.js +2 -1
- package/lib/esm/agent/canister-env/index.js.map +1 -1
- package/lib/esm/agent/canisterStatus/index.d.ts +18 -50
- package/lib/esm/agent/canisterStatus/index.d.ts.map +1 -1
- package/lib/esm/agent/canisterStatus/index.js +31 -98
- package/lib/esm/agent/canisterStatus/index.js.map +1 -1
- package/lib/esm/agent/certificate.d.ts +68 -10
- package/lib/esm/agent/certificate.d.ts.map +1 -1
- package/lib/esm/agent/certificate.js +196 -29
- package/lib/esm/agent/certificate.js.map +1 -1
- package/lib/esm/agent/constants.d.ts +4 -0
- package/lib/esm/agent/constants.d.ts.map +1 -1
- package/lib/esm/agent/constants.js +4 -0
- package/lib/esm/agent/constants.js.map +1 -1
- package/lib/esm/agent/errors.d.ts +9 -2
- package/lib/esm/agent/errors.d.ts.map +1 -1
- package/lib/esm/agent/errors.js +15 -4
- package/lib/esm/agent/errors.js.map +1 -1
- package/lib/esm/agent/index.d.ts +97 -5
- package/lib/esm/agent/index.d.ts.map +1 -1
- package/lib/esm/agent/index.js +97 -5
- package/lib/esm/agent/index.js.map +1 -1
- package/lib/esm/agent/polling/index.js +1 -1
- package/lib/esm/agent/polling/index.js.map +1 -1
- package/lib/esm/agent/subnetStatus/index.d.ts +70 -0
- package/lib/esm/agent/subnetStatus/index.d.ts.map +1 -0
- package/lib/esm/agent/subnetStatus/index.js +178 -0
- package/lib/esm/agent/subnetStatus/index.js.map +1 -0
- package/lib/esm/agent/utils/readState.d.ts +84 -0
- package/lib/esm/agent/utils/readState.d.ts.map +1 -0
- package/lib/esm/agent/utils/readState.js +107 -0
- package/lib/esm/agent/utils/readState.js.map +1 -0
- package/lib/esm/candid/index.d.ts +20 -1
- package/lib/esm/candid/index.d.ts.map +1 -1
- package/lib/esm/candid/index.js +20 -1
- package/lib/esm/candid/index.js.map +1 -1
- package/lib/esm/identity/index.d.ts +30 -7
- package/lib/esm/identity/index.d.ts.map +1 -1
- package/lib/esm/identity/index.js +30 -9
- package/lib/esm/identity/index.js.map +1 -1
- package/lib/esm/identity/secp256k1/index.d.ts +48 -1
- package/lib/esm/identity/secp256k1/index.d.ts.map +1 -1
- package/lib/esm/identity/secp256k1/index.js +48 -1
- package/lib/esm/identity/secp256k1/index.js.map +1 -1
- package/lib/esm/identity/secp256k1/pem.d.ts.map +1 -1
- package/lib/esm/identity/secp256k1/pem.js +1 -2
- package/lib/esm/identity/secp256k1/pem.js.map +1 -1
- package/lib/esm/principal/index.d.ts +15 -0
- package/lib/esm/principal/index.d.ts.map +1 -1
- package/lib/esm/principal/index.js +15 -0
- package/lib/esm/principal/index.js.map +1 -1
- package/package.json +3 -1
- package/src/agent/actor.ts +3 -3
- package/src/agent/agent/api.ts +8 -8
- package/src/agent/agent/http/index.ts +259 -97
- package/src/agent/agent/index.ts +2 -0
- package/src/agent/canister-env/index.ts +2 -1
- package/src/agent/canisterStatus/index.ts +46 -196
- package/src/agent/certificate.ts +271 -52
- package/src/agent/constants.ts +5 -0
- package/src/agent/errors.ts +19 -5
- package/src/agent/index.ts +97 -5
- package/src/agent/polling/index.ts +1 -1
- package/src/agent/subnetStatus/index.ts +265 -0
- package/src/agent/utils/readState.ts +180 -0
- package/src/candid/index.ts +20 -1
- package/src/identity/index.ts +30 -10
- package/src/identity/secp256k1/index.ts +48 -1
- package/src/identity/secp256k1/pem.ts +1 -2
- package/src/principal/index.ts +16 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Principal } from '../../../principal/index.js';
|
|
2
|
-
import { HashTreeDecodeErrorCode, CreateHttpAgentErrorCode, ExternalError, HttpDefaultFetchErrorCode, IdentityInvalidErrorCode, IngressExpiryInvalidErrorCode, InputError, LookupErrorCode, MalformedPublicKeyErrorCode, MalformedSignatureErrorCode, MissingRootKeyErrorCode, MissingSignatureErrorCode, ProtocolError, QuerySignatureVerificationFailedErrorCode, TimeoutWaitingForResponseErrorCode, TrustError, UnexpectedErrorCode, UnknownError, HttpErrorCode,
|
|
2
|
+
import { HashTreeDecodeErrorCode, CreateHttpAgentErrorCode, ExternalError, HttpDefaultFetchErrorCode, IdentityInvalidErrorCode, IngressExpiryInvalidErrorCode, InputError, LookupErrorCode, MalformedPublicKeyErrorCode, MalformedSignatureErrorCode, MissingRootKeyErrorCode, MissingSignatureErrorCode, ProtocolError, QuerySignatureVerificationFailedErrorCode, TimeoutWaitingForResponseErrorCode, TrustError, UnexpectedErrorCode, UnknownError, HttpErrorCode, HttpV4ApiNotSupportedErrorCode, TransportError, HttpFetchErrorCode, AgentError, MalformedLookupFoundValueErrorCode, CertificateOutdatedErrorCode, CertificateNotAuthorizedErrorCode, UNREACHABLE_ERROR, } from "../../errors.js";
|
|
3
3
|
import { AnonymousIdentity } from "../../auth.js";
|
|
4
4
|
import * as cbor from "../../cbor.js";
|
|
5
5
|
import { hashOfMap, requestIdOf } from "../../request_id.js";
|
|
@@ -7,18 +7,18 @@ import { QueryResponseStatus, } from "../api.js";
|
|
|
7
7
|
import { Expiry, httpHeadersTransform, makeNonceTransform } from "./transforms.js";
|
|
8
8
|
import { Endpoint, makeNonce, ReadRequestType, SubmitRequestType, } from "./types.js";
|
|
9
9
|
import { request as canisterStatusRequest } from "../../canisterStatus/index.js";
|
|
10
|
-
import {
|
|
10
|
+
import { request as subnetStatusRequest } from "../../subnetStatus/index.js";
|
|
11
|
+
import { lookupNodeKeysFromCertificate } from "../../utils/readState.js";
|
|
12
|
+
import { Certificate, check_canister_ranges, getSubnetIdFromCertificate, lookup_path, LookupPathStatus, } from "../../certificate.js";
|
|
11
13
|
import { ed25519 } from '@noble/curves/ed25519';
|
|
12
14
|
import { ExpirableMap } from "../../utils/expirableMap.js";
|
|
13
15
|
import { Ed25519PublicKey } from "../../public_key.js";
|
|
14
16
|
import { ObservableLog } from "../../observable.js";
|
|
15
17
|
import { ExponentialBackoff, } from "../../polling/backoff.js";
|
|
16
18
|
import { decodeTime } from "../../utils/leb.js";
|
|
17
|
-
import { concatBytes, hexToBytes } from '@noble/hashes/utils';
|
|
19
|
+
import { concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';
|
|
18
20
|
import { uint8Equals, uint8FromBufLike } from "../../utils/buffer.js";
|
|
19
21
|
import { IC_RESPONSE_DOMAIN_SEPARATOR } from "../../constants.js";
|
|
20
|
-
export * from "./transforms.js";
|
|
21
|
-
export { makeNonce } from "./types.js";
|
|
22
22
|
export var RequestStatusResponseStatus;
|
|
23
23
|
(function (RequestStatusResponseStatus) {
|
|
24
24
|
RequestStatusResponseStatus["Received"] = "received";
|
|
@@ -168,10 +168,10 @@ export class HttpAgent {
|
|
|
168
168
|
/**
|
|
169
169
|
* See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation
|
|
170
170
|
* @param queryResponse - The response from the query
|
|
171
|
-
* @param
|
|
171
|
+
* @param subnetNodeKeys - The subnet node keys
|
|
172
172
|
* @returns ApiQueryResponse
|
|
173
173
|
*/
|
|
174
|
-
this.#verifyQueryResponse = (queryResponse,
|
|
174
|
+
this.#verifyQueryResponse = (queryResponse, subnetNodeKeys) => {
|
|
175
175
|
if (this.#verifyQuerySignatures === false) {
|
|
176
176
|
// This should not be called if the user has disabled verification
|
|
177
177
|
return queryResponse;
|
|
@@ -206,16 +206,15 @@ export class HttpAgent {
|
|
|
206
206
|
throw UnknownError.fromCode(new UnexpectedErrorCode(`Unknown status: ${status}`));
|
|
207
207
|
}
|
|
208
208
|
const separatorWithHash = concatBytes(IC_RESPONSE_DOMAIN_SEPARATOR, hash);
|
|
209
|
-
|
|
210
|
-
const pubKey = subnetStatus.nodeKeys.get(nodeId);
|
|
209
|
+
const pubKey = subnetNodeKeys.get(nodeId);
|
|
211
210
|
if (!pubKey) {
|
|
212
211
|
throw ProtocolError.fromCode(new MalformedPublicKeyErrorCode());
|
|
213
212
|
}
|
|
214
213
|
const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;
|
|
215
214
|
const valid = ed25519.verify(sig.signature, separatorWithHash, rawKey);
|
|
216
|
-
if (valid)
|
|
217
|
-
|
|
218
|
-
|
|
215
|
+
if (!valid) {
|
|
216
|
+
throw TrustError.fromCode(new QuerySignatureVerificationFailedErrorCode(nodeId));
|
|
217
|
+
}
|
|
219
218
|
}
|
|
220
219
|
return queryResponse;
|
|
221
220
|
};
|
|
@@ -410,9 +409,9 @@ export class HttpAgent {
|
|
|
410
409
|
const backoff = this.#backoffStrategy();
|
|
411
410
|
const requestId = requestIdOf(submit);
|
|
412
411
|
try {
|
|
413
|
-
// Attempt
|
|
412
|
+
// Attempt v4 sync call
|
|
414
413
|
const requestSync = () => {
|
|
415
|
-
const url = new URL(`/api/
|
|
414
|
+
const url = new URL(`/api/v4/canister/${ecid.toText()}/call`, this.host);
|
|
416
415
|
this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
|
|
417
416
|
return this.#fetch(url, {
|
|
418
417
|
...this.#callOptions,
|
|
@@ -448,12 +447,12 @@ export class HttpAgent {
|
|
|
448
447
|
catch (error) {
|
|
449
448
|
let callError;
|
|
450
449
|
if (error instanceof AgentError) {
|
|
451
|
-
// If the error is due to the
|
|
452
|
-
if (error.hasCode(
|
|
453
|
-
this.log.warn('
|
|
450
|
+
// If the error is due to the v4 api not being supported, fall back to v2
|
|
451
|
+
if (error.hasCode(HttpV4ApiNotSupportedErrorCode)) {
|
|
452
|
+
this.log.warn('v4 api not supported. Fall back to v2');
|
|
454
453
|
return this.call(canisterId, {
|
|
455
454
|
...options,
|
|
456
|
-
// disable
|
|
455
|
+
// disable v4 api
|
|
457
456
|
callSync: false,
|
|
458
457
|
}, identity);
|
|
459
458
|
}
|
|
@@ -484,7 +483,7 @@ export class HttpAgent {
|
|
|
484
483
|
async #requestAndRetryQuery(args) {
|
|
485
484
|
const { ecid, transformedRequest, body, requestId, backoff, tries } = args;
|
|
486
485
|
const delay = tries === 0 ? 0 : backoff.next();
|
|
487
|
-
const url = new URL(`/api/
|
|
486
|
+
const url = new URL(`/api/v3/canister/${ecid.toString()}/query`, this.host);
|
|
488
487
|
this.log.print(`fetching "${url.pathname}" with tries:`, {
|
|
489
488
|
tries,
|
|
490
489
|
backoff,
|
|
@@ -497,31 +496,15 @@ export class HttpAgent {
|
|
|
497
496
|
if (delay > 0) {
|
|
498
497
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
499
498
|
}
|
|
500
|
-
let
|
|
499
|
+
let fetchResponse;
|
|
501
500
|
// Make the request and retry if it throws an error
|
|
502
501
|
try {
|
|
503
502
|
this.log.print(`fetching "${url.pathname}" with request:`, transformedRequest);
|
|
504
|
-
|
|
503
|
+
fetchResponse = await this.#fetch(url, {
|
|
505
504
|
...this.#fetchOptions,
|
|
506
505
|
...transformedRequest.request,
|
|
507
506
|
body,
|
|
508
507
|
});
|
|
509
|
-
if (fetchResponse.status === HTTP_STATUS_OK) {
|
|
510
|
-
const queryResponse = cbor.decode(uint8FromBufLike(await fetchResponse.arrayBuffer()));
|
|
511
|
-
response = {
|
|
512
|
-
...queryResponse,
|
|
513
|
-
httpDetails: {
|
|
514
|
-
ok: fetchResponse.ok,
|
|
515
|
-
status: fetchResponse.status,
|
|
516
|
-
statusText: fetchResponse.statusText,
|
|
517
|
-
headers: httpHeadersTransform(fetchResponse.headers),
|
|
518
|
-
},
|
|
519
|
-
requestId,
|
|
520
|
-
};
|
|
521
|
-
}
|
|
522
|
-
else {
|
|
523
|
-
throw ProtocolError.fromCode(new HttpErrorCode(fetchResponse.status, fetchResponse.statusText, httpHeadersTransform(fetchResponse.headers), await fetchResponse.text()));
|
|
524
|
-
}
|
|
525
508
|
}
|
|
526
509
|
catch (error) {
|
|
527
510
|
if (tries < this.#retryTimes) {
|
|
@@ -530,13 +513,30 @@ export class HttpAgent {
|
|
|
530
513
|
` Retrying query.`);
|
|
531
514
|
return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
|
|
532
515
|
}
|
|
533
|
-
if (error instanceof AgentError) {
|
|
534
|
-
// if it's an error that we have thrown, just throw it as is
|
|
535
|
-
throw error;
|
|
536
|
-
}
|
|
537
|
-
// if it's an error that we have not thrown, wrap it in a TransportError
|
|
538
516
|
throw TransportError.fromCode(new HttpFetchErrorCode(error));
|
|
539
517
|
}
|
|
518
|
+
const headers = httpHeadersTransform(fetchResponse.headers);
|
|
519
|
+
if (fetchResponse.status !== HTTP_STATUS_OK) {
|
|
520
|
+
const responseText = await fetchResponse.text();
|
|
521
|
+
if (isIngressExpiryInvalidResponse(responseText)) {
|
|
522
|
+
throw InputError.fromCode(new IngressExpiryInvalidErrorCode(responseText, this.#maxIngressExpiryInMinutes));
|
|
523
|
+
}
|
|
524
|
+
if (tries < this.#retryTimes) {
|
|
525
|
+
return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
|
|
526
|
+
}
|
|
527
|
+
throw ProtocolError.fromCode(new HttpErrorCode(fetchResponse.status, fetchResponse.statusText, headers, responseText));
|
|
528
|
+
}
|
|
529
|
+
const queryResponse = cbor.decode(uint8FromBufLike(await fetchResponse.arrayBuffer()));
|
|
530
|
+
const response = {
|
|
531
|
+
...queryResponse,
|
|
532
|
+
httpDetails: {
|
|
533
|
+
ok: fetchResponse.ok,
|
|
534
|
+
status: fetchResponse.status,
|
|
535
|
+
statusText: fetchResponse.statusText,
|
|
536
|
+
headers,
|
|
537
|
+
},
|
|
538
|
+
requestId,
|
|
539
|
+
};
|
|
540
540
|
// Skip timestamp verification if the user has set verifyQuerySignatures to false
|
|
541
541
|
if (!this.#verifyQuerySignatures) {
|
|
542
542
|
return response;
|
|
@@ -554,6 +554,7 @@ export class HttpAgent {
|
|
|
554
554
|
requestId,
|
|
555
555
|
signatureTimestampMs,
|
|
556
556
|
});
|
|
557
|
+
await this.syncTime(ecid);
|
|
557
558
|
return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });
|
|
558
559
|
}
|
|
559
560
|
throw TrustError.fromCode(new CertificateOutdatedErrorCode(this.#maxIngressExpiryInMinutes, requestId, tries));
|
|
@@ -612,11 +613,10 @@ export class HttpAgent {
|
|
|
612
613
|
};
|
|
613
614
|
}
|
|
614
615
|
const responseText = await response.text();
|
|
615
|
-
if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/
|
|
616
|
-
throw ProtocolError.fromCode(new
|
|
616
|
+
if (response.status === HTTP_STATUS_NOT_FOUND && response.url.includes('api/v4')) {
|
|
617
|
+
throw ProtocolError.fromCode(new HttpV4ApiNotSupportedErrorCode());
|
|
617
618
|
}
|
|
618
|
-
|
|
619
|
-
if (responseText.startsWith('Invalid request expiry: ')) {
|
|
619
|
+
if (isIngressExpiryInvalidResponse(responseText)) {
|
|
620
620
|
throw InputError.fromCode(new IngressExpiryInvalidErrorCode(responseText, this.#maxIngressExpiryInMinutes));
|
|
621
621
|
}
|
|
622
622
|
if (tries < this.#retryTimes) {
|
|
@@ -680,17 +680,17 @@ export class HttpAgent {
|
|
|
680
680
|
...query,
|
|
681
681
|
};
|
|
682
682
|
};
|
|
683
|
-
const
|
|
684
|
-
const
|
|
685
|
-
if (
|
|
686
|
-
return
|
|
683
|
+
const getSubnetNodeKeys = async () => {
|
|
684
|
+
const cachedSubnetNodeKeys = this.#subnetKeys.get(ecid.toString());
|
|
685
|
+
if (cachedSubnetNodeKeys) {
|
|
686
|
+
return cachedSubnetNodeKeys;
|
|
687
687
|
}
|
|
688
688
|
await this.fetchSubnetKeys(ecid.toString());
|
|
689
|
-
const
|
|
690
|
-
if (!
|
|
689
|
+
const subnetNodeKeys = this.#subnetKeys.get(ecid.toString());
|
|
690
|
+
if (!subnetNodeKeys) {
|
|
691
691
|
throw TrustError.fromCode(new MissingSignatureErrorCode());
|
|
692
692
|
}
|
|
693
|
-
return
|
|
693
|
+
return subnetNodeKeys;
|
|
694
694
|
};
|
|
695
695
|
try {
|
|
696
696
|
if (!this.#verifyQuerySignatures) {
|
|
@@ -698,21 +698,30 @@ export class HttpAgent {
|
|
|
698
698
|
return await makeQuery();
|
|
699
699
|
}
|
|
700
700
|
// Make query and fetch subnet keys in parallel
|
|
701
|
-
const [queryWithDetails,
|
|
701
|
+
const [queryWithDetails, subnetNodeKeys] = await Promise.all([
|
|
702
|
+
makeQuery(),
|
|
703
|
+
getSubnetNodeKeys(),
|
|
704
|
+
]);
|
|
702
705
|
try {
|
|
703
|
-
return this.#verifyQueryResponse(queryWithDetails,
|
|
706
|
+
return this.#verifyQueryResponse(queryWithDetails, subnetNodeKeys);
|
|
704
707
|
}
|
|
705
708
|
catch {
|
|
706
709
|
// In case the node signatures have changed, refresh the subnet keys and try again
|
|
707
710
|
this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');
|
|
708
711
|
this.#subnetKeys.delete(ecid.toString());
|
|
709
|
-
const
|
|
710
|
-
return this.#verifyQueryResponse(queryWithDetails,
|
|
712
|
+
const updatedSubnetNodeKeys = await getSubnetNodeKeys();
|
|
713
|
+
return this.#verifyQueryResponse(queryWithDetails, updatedSubnetNodeKeys);
|
|
711
714
|
}
|
|
712
715
|
}
|
|
713
716
|
catch (error) {
|
|
714
717
|
let queryError;
|
|
715
718
|
if (error instanceof AgentError) {
|
|
719
|
+
if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
|
|
720
|
+
// if there is an ingress expiry error and the time has not been synced yet,
|
|
721
|
+
// sync time with the network and try again
|
|
722
|
+
await this.syncTime(ecid);
|
|
723
|
+
return this.query(canisterId, fields, identity);
|
|
724
|
+
}
|
|
716
725
|
// override the error code to include the request details
|
|
717
726
|
error.code.requestContext = {
|
|
718
727
|
requestId,
|
|
@@ -732,7 +741,7 @@ export class HttpAgent {
|
|
|
732
741
|
/**
|
|
733
742
|
* See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation
|
|
734
743
|
* @param queryResponse - The response from the query
|
|
735
|
-
* @param
|
|
744
|
+
* @param subnetNodeKeys - The subnet node keys
|
|
736
745
|
* @returns ApiQueryResponse
|
|
737
746
|
*/
|
|
738
747
|
#verifyQueryResponse;
|
|
@@ -782,7 +791,6 @@ export class HttpAgent {
|
|
|
782
791
|
if (request) {
|
|
783
792
|
// This is a pre-signed request
|
|
784
793
|
transformedRequest = request;
|
|
785
|
-
requestId = requestIdOf(transformedRequest);
|
|
786
794
|
}
|
|
787
795
|
else {
|
|
788
796
|
// This is fields, we need to create a request
|
|
@@ -794,8 +802,23 @@ export class HttpAgent {
|
|
|
794
802
|
}
|
|
795
803
|
transformedRequest = await this.createReadStateRequest(fields, identity);
|
|
796
804
|
}
|
|
797
|
-
const url = new URL(`/api/
|
|
798
|
-
this
|
|
805
|
+
const url = new URL(`/api/v3/canister/${canister.toString()}/read_state`, this.host);
|
|
806
|
+
return await this.#readStateInner(url, { canisterId: canister }, transformedRequest, requestId);
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Reads the state of a subnet from the `/api/v3/subnet/{subnetId}/read_state` endpoint.
|
|
810
|
+
* @param subnetId The ID of the subnet to read the state of. If you have a canister ID, you can use {@link HttpAgent.getSubnetIdFromCanister | getSubnetIdFromCanister} to get the subnet ID.
|
|
811
|
+
* @param options The options for the read state request.
|
|
812
|
+
* @returns The response from the read state request.
|
|
813
|
+
*/
|
|
814
|
+
async readSubnetState(subnetId, options) {
|
|
815
|
+
await this.#rootKeyGuard();
|
|
816
|
+
const subnet = Principal.from(subnetId);
|
|
817
|
+
const url = new URL(`/api/v3/subnet/${subnet.toString()}/read_state`, this.host);
|
|
818
|
+
const transformedRequest = await this.createReadStateRequest(options, this.#identity ?? undefined);
|
|
819
|
+
return await this.#readStateInner(url, { subnetId: subnet }, transformedRequest);
|
|
820
|
+
}
|
|
821
|
+
async #readStateInner(url, principal, transformedRequest, requestId) {
|
|
799
822
|
const backoff = this.#backoffStrategy();
|
|
800
823
|
try {
|
|
801
824
|
const { responseBodyBytes } = await this.#requestAndRetry({
|
|
@@ -808,15 +831,28 @@ export class HttpAgent {
|
|
|
808
831
|
tries: 0,
|
|
809
832
|
});
|
|
810
833
|
const decodedResponse = cbor.decode(responseBodyBytes);
|
|
811
|
-
this.log.print('Read state response:', decodedResponse);
|
|
812
834
|
return decodedResponse;
|
|
813
835
|
}
|
|
814
836
|
catch (error) {
|
|
815
837
|
let readStateError;
|
|
816
838
|
if (error instanceof AgentError) {
|
|
839
|
+
if (error.hasCode(IngressExpiryInvalidErrorCode) && !this.#hasSyncedTime) {
|
|
840
|
+
// if there is an ingress expiry error and the time has not been synced yet,
|
|
841
|
+
// sync time with the network and try again
|
|
842
|
+
if ('canisterId' in principal) {
|
|
843
|
+
await this.syncTime(principal.canisterId);
|
|
844
|
+
}
|
|
845
|
+
else if ('subnetId' in principal) {
|
|
846
|
+
await this.syncTimeWithSubnet(principal.subnetId);
|
|
847
|
+
}
|
|
848
|
+
else {
|
|
849
|
+
throw UNREACHABLE_ERROR;
|
|
850
|
+
}
|
|
851
|
+
return await this.#readStateInner(url, principal, transformedRequest, requestId);
|
|
852
|
+
}
|
|
817
853
|
// override the error code to include the request details
|
|
818
854
|
error.code.requestContext = {
|
|
819
|
-
requestId,
|
|
855
|
+
requestId: requestId ?? requestIdOf(transformedRequest),
|
|
820
856
|
senderPubKey: transformedRequest.body.sender_pubkey,
|
|
821
857
|
senderSignature: transformedRequest.body.sender_sig,
|
|
822
858
|
ingressExpiry: transformedRequest.body.content.ingress_expiry,
|
|
@@ -858,7 +894,7 @@ export class HttpAgent {
|
|
|
858
894
|
return 0;
|
|
859
895
|
}
|
|
860
896
|
/**
|
|
861
|
-
* Allows agent to sync its time with the network. Can be called during
|
|
897
|
+
* Allows agent to sync its time with the network. Can be called during initialization 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
|
|
862
898
|
* @param {Principal} canisterIdOverride - Pass a canister ID if you need to sync the time with a particular subnet. Uses the ICP ledger canister by default.
|
|
863
899
|
*/
|
|
864
900
|
async syncTime(canisterIdOverride) {
|
|
@@ -895,17 +931,7 @@ export class HttpAgent {
|
|
|
895
931
|
return date.getTime();
|
|
896
932
|
}
|
|
897
933
|
}, []));
|
|
898
|
-
|
|
899
|
-
return typeof current === 'number' && current > max ? current : max;
|
|
900
|
-
}, 0);
|
|
901
|
-
if (maxReplicaTime > 0) {
|
|
902
|
-
this.#timeDiffMsecs = maxReplicaTime - callTime;
|
|
903
|
-
this.#hasSyncedTime = true;
|
|
904
|
-
this.log.notify({
|
|
905
|
-
message: `Syncing time: offset of ${this.#timeDiffMsecs}`,
|
|
906
|
-
level: 'info',
|
|
907
|
-
});
|
|
908
|
-
}
|
|
934
|
+
this.#setTimeDiffMsecs(callTime, replicaTimes);
|
|
909
935
|
}
|
|
910
936
|
catch (error) {
|
|
911
937
|
const syncTimeError = error instanceof AgentError
|
|
@@ -919,6 +945,57 @@ export class HttpAgent {
|
|
|
919
945
|
this.#syncTimePromise = null;
|
|
920
946
|
});
|
|
921
947
|
}
|
|
948
|
+
/**
|
|
949
|
+
* Allows agent to sync its time with the network.
|
|
950
|
+
* @param {Principal} subnetId - Pass the subnet ID you need to sync the time with.
|
|
951
|
+
*/
|
|
952
|
+
async syncTimeWithSubnet(subnetId) {
|
|
953
|
+
await this.#rootKeyGuard();
|
|
954
|
+
const callTime = Date.now();
|
|
955
|
+
try {
|
|
956
|
+
const anonymousAgent = HttpAgent.createSync({
|
|
957
|
+
identity: new AnonymousIdentity(),
|
|
958
|
+
host: this.host.toString(),
|
|
959
|
+
fetch: this.#fetch,
|
|
960
|
+
retryTimes: 0,
|
|
961
|
+
rootKey: this.rootKey ?? undefined,
|
|
962
|
+
shouldSyncTime: false,
|
|
963
|
+
});
|
|
964
|
+
const replicaTimes = await Promise.all(Array(3)
|
|
965
|
+
.fill(null)
|
|
966
|
+
.map(async () => {
|
|
967
|
+
const status = await subnetStatusRequest({
|
|
968
|
+
subnetId,
|
|
969
|
+
agent: anonymousAgent,
|
|
970
|
+
paths: ['time'],
|
|
971
|
+
disableCertificateTimeVerification: true, // avoid recursive calls to syncTime
|
|
972
|
+
});
|
|
973
|
+
const date = status.get('time');
|
|
974
|
+
if (date instanceof Date) {
|
|
975
|
+
return date.getTime();
|
|
976
|
+
}
|
|
977
|
+
}, []));
|
|
978
|
+
this.#setTimeDiffMsecs(callTime, replicaTimes);
|
|
979
|
+
}
|
|
980
|
+
catch (error) {
|
|
981
|
+
const syncTimeError = error instanceof AgentError ? error : UnknownError.fromCode(new UnexpectedErrorCode(error));
|
|
982
|
+
this.log.error('Caught exception while attempting to sync time with subnet', syncTimeError);
|
|
983
|
+
throw syncTimeError;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
#setTimeDiffMsecs(callTime, replicaTimes) {
|
|
987
|
+
const maxReplicaTime = replicaTimes.reduce((max, current) => {
|
|
988
|
+
return typeof current === 'number' && current > max ? current : max;
|
|
989
|
+
}, 0);
|
|
990
|
+
if (maxReplicaTime > 0) {
|
|
991
|
+
this.#timeDiffMsecs = maxReplicaTime - callTime;
|
|
992
|
+
this.#hasSyncedTime = true;
|
|
993
|
+
this.log.notify({
|
|
994
|
+
message: `Syncing time: offset of ${this.#timeDiffMsecs}`,
|
|
995
|
+
level: 'info',
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
}
|
|
922
999
|
async status() {
|
|
923
1000
|
const headers = this.#credentials
|
|
924
1001
|
? {
|
|
@@ -980,18 +1057,51 @@ export class HttpAgent {
|
|
|
980
1057
|
async fetchSubnetKeys(canisterId) {
|
|
981
1058
|
const effectiveCanisterId = Principal.from(canisterId);
|
|
982
1059
|
await this.#asyncGuard(effectiveCanisterId);
|
|
983
|
-
const
|
|
984
|
-
|
|
985
|
-
paths: ['subnet'],
|
|
1060
|
+
const rootKey = this.rootKey;
|
|
1061
|
+
const canisterReadState = await this.readState(effectiveCanisterId, {
|
|
1062
|
+
paths: [[utf8ToBytes('subnet')]],
|
|
1063
|
+
});
|
|
1064
|
+
const canisterCertificate = await Certificate.create({
|
|
1065
|
+
certificate: canisterReadState.certificate,
|
|
1066
|
+
rootKey,
|
|
1067
|
+
principal: { canisterId: effectiveCanisterId },
|
|
986
1068
|
agent: this,
|
|
987
1069
|
});
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
1070
|
+
if (!canisterCertificate.cert.delegation) {
|
|
1071
|
+
const subnetId = Principal.selfAuthenticating(rootKey);
|
|
1072
|
+
const canisterInRange = check_canister_ranges({
|
|
1073
|
+
canisterId: effectiveCanisterId,
|
|
1074
|
+
subnetId,
|
|
1075
|
+
tree: canisterCertificate.cert.tree,
|
|
1076
|
+
});
|
|
1077
|
+
if (!canisterInRange) {
|
|
1078
|
+
throw TrustError.fromCode(new CertificateNotAuthorizedErrorCode(effectiveCanisterId, subnetId));
|
|
1079
|
+
}
|
|
992
1080
|
}
|
|
993
|
-
|
|
994
|
-
|
|
1081
|
+
const subnetId = getSubnetIdFromCertificate(canisterCertificate.cert, rootKey);
|
|
1082
|
+
const nodeKeys = lookupNodeKeysFromCertificate(canisterCertificate.cert, subnetId);
|
|
1083
|
+
this.#subnetKeys.set(effectiveCanisterId.toText(), nodeKeys);
|
|
1084
|
+
return nodeKeys;
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Returns the subnet ID for a given canister ID, by looking at the certificate delegation
|
|
1088
|
+
* returned by the canister's state obtained by requesting the `/time` path with {@link HttpAgent.readState | readState}.
|
|
1089
|
+
* @param canisterId The canister ID to get the subnet ID for.
|
|
1090
|
+
* @returns The subnet ID for the given canister ID.
|
|
1091
|
+
*/
|
|
1092
|
+
async getSubnetIdFromCanister(canisterId) {
|
|
1093
|
+
const effectiveCanisterId = Principal.from(canisterId);
|
|
1094
|
+
await this.#asyncGuard(effectiveCanisterId);
|
|
1095
|
+
const canisterReadState = await this.readState(effectiveCanisterId, {
|
|
1096
|
+
paths: [[utf8ToBytes('time')]],
|
|
1097
|
+
});
|
|
1098
|
+
const canisterCertificate = await Certificate.create({
|
|
1099
|
+
certificate: canisterReadState.certificate,
|
|
1100
|
+
rootKey: this.rootKey,
|
|
1101
|
+
principal: { canisterId: effectiveCanisterId },
|
|
1102
|
+
agent: this,
|
|
1103
|
+
});
|
|
1104
|
+
return getSubnetIdFromCertificate(canisterCertificate.cert, this.rootKey);
|
|
995
1105
|
}
|
|
996
1106
|
_transform(request) {
|
|
997
1107
|
let p = Promise.resolve(request);
|
|
@@ -1034,4 +1144,13 @@ export function calculateIngressExpiry(maxIngressExpiryInMinutes, timeDiffMsecs)
|
|
|
1034
1144
|
const ingressExpiryMs = maxIngressExpiryInMinutes * MINUTE_TO_MSECS;
|
|
1035
1145
|
return Expiry.fromDeltaInMilliseconds(ingressExpiryMs, timeDiffMsecs);
|
|
1036
1146
|
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Checks if the response text is an ingress expiry invalid response.
|
|
1149
|
+
* @see https://github.com/dfinity/ic/blob/23d5990bfc5277c32e54f0087b5a38fa412171e1/rs/validator/src/ingress_validation.rs#L233
|
|
1150
|
+
* @param responseText The response body as string.
|
|
1151
|
+
* @returns `true` if the response text is an ingress expiry invalid response, `false` otherwise.
|
|
1152
|
+
*/
|
|
1153
|
+
function isIngressExpiryInvalidResponse(responseText) {
|
|
1154
|
+
return responseText.includes('Invalid request expiry: ');
|
|
1155
|
+
}
|
|
1037
1156
|
//# sourceMappingURL=index.js.map
|