@ar.io/sdk 3.13.0-alpha.1 → 3.13.0-beta.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.
Files changed (53) hide show
  1. package/bundles/web.bundle.min.js +139 -136
  2. package/lib/cjs/common/index.js +2 -0
  3. package/lib/cjs/common/wayfinder/gateways/network.js +48 -0
  4. package/lib/cjs/common/wayfinder/gateways/simple-cache.js +35 -0
  5. package/lib/cjs/common/wayfinder/gateways/static.js +13 -0
  6. package/lib/cjs/common/wayfinder/index.js +48 -0
  7. package/lib/cjs/common/wayfinder/routing/strategies/ping.js +72 -0
  8. package/lib/cjs/common/wayfinder/routing/strategies/preferred-with-fallback.js +50 -0
  9. package/lib/cjs/common/wayfinder/routing/strategies/random.js +13 -0
  10. package/lib/cjs/common/wayfinder/routing/strategies/round-robin.js +42 -0
  11. package/lib/cjs/common/wayfinder/routing/strategies/static.js +29 -0
  12. package/lib/cjs/common/wayfinder/verification/strategies/data-root-verifier.js +110 -0
  13. package/lib/cjs/common/wayfinder/verification/strategies/hash-verifier.js +27 -0
  14. package/lib/cjs/common/wayfinder/verification/trusted.js +125 -0
  15. package/lib/cjs/common/wayfinder/wayfinder.js +508 -0
  16. package/lib/cjs/types/wayfinder.js +3 -0
  17. package/lib/cjs/utils/hash.js +83 -31
  18. package/lib/cjs/version.js +1 -1
  19. package/lib/esm/common/index.js +2 -0
  20. package/lib/esm/common/wayfinder/gateways/network.js +44 -0
  21. package/lib/esm/common/wayfinder/gateways/simple-cache.js +31 -0
  22. package/lib/esm/common/wayfinder/gateways/static.js +9 -0
  23. package/lib/esm/common/wayfinder/index.js +32 -0
  24. package/lib/esm/common/wayfinder/routing/strategies/ping.js +68 -0
  25. package/lib/esm/common/wayfinder/routing/strategies/preferred-with-fallback.js +46 -0
  26. package/lib/esm/common/wayfinder/routing/strategies/random.js +9 -0
  27. package/lib/esm/common/wayfinder/routing/strategies/round-robin.js +38 -0
  28. package/lib/esm/common/wayfinder/routing/strategies/static.js +25 -0
  29. package/lib/esm/common/wayfinder/verification/strategies/data-root-verifier.js +102 -0
  30. package/lib/esm/common/wayfinder/verification/strategies/hash-verifier.js +23 -0
  31. package/lib/esm/common/wayfinder/verification/trusted.js +121 -0
  32. package/lib/esm/common/wayfinder/wayfinder.js +499 -0
  33. package/lib/esm/types/wayfinder.js +2 -0
  34. package/lib/esm/utils/hash.js +74 -27
  35. package/lib/esm/version.js +1 -1
  36. package/lib/types/common/index.d.ts +1 -0
  37. package/lib/types/common/wayfinder/gateways/network.d.ts +33 -0
  38. package/lib/types/common/wayfinder/gateways/simple-cache.d.ts +31 -0
  39. package/lib/types/common/wayfinder/gateways/static.d.ts +23 -0
  40. package/lib/types/common/wayfinder/index.d.ts +27 -0
  41. package/lib/types/common/wayfinder/routing/strategies/ping.d.ts +27 -0
  42. package/lib/types/common/wayfinder/routing/strategies/preferred-with-fallback.d.ts +31 -0
  43. package/lib/types/common/wayfinder/routing/strategies/random.d.ts +21 -0
  44. package/lib/types/common/wayfinder/routing/strategies/round-robin.d.ts +29 -0
  45. package/lib/types/common/wayfinder/routing/strategies/static.d.ts +29 -0
  46. package/lib/types/common/wayfinder/verification/strategies/data-root-verifier.d.ts +27 -0
  47. package/lib/types/common/wayfinder/verification/strategies/hash-verifier.d.ts +26 -0
  48. package/lib/types/common/wayfinder/verification/trusted.d.ts +51 -0
  49. package/lib/types/common/wayfinder/wayfinder.d.ts +257 -0
  50. package/lib/types/types/wayfinder.d.ts +66 -0
  51. package/lib/types/utils/hash.d.ts +8 -4
  52. package/lib/types/version.d.ts +1 -1
  53. package/package.json +2 -1
@@ -0,0 +1,44 @@
1
+ import { ARIO } from '../../io.js';
2
+ export class NetworkGatewaysProvider {
3
+ ario;
4
+ sortBy;
5
+ sortOrder;
6
+ limit;
7
+ filter;
8
+ constructor({ ario = ARIO.mainnet(), sortBy = 'operatorStake', sortOrder = 'desc', limit = 1000, filter = (g) => g.status === 'joined', }) {
9
+ this.ario = ario;
10
+ this.sortBy = sortBy;
11
+ this.sortOrder = sortOrder;
12
+ this.limit = limit;
13
+ this.filter = filter;
14
+ }
15
+ async getGateways() {
16
+ let cursor;
17
+ let attempts = 0;
18
+ const gateways = [];
19
+ do {
20
+ try {
21
+ const { items: newGateways = [], nextCursor } = await this.ario.getGateways({
22
+ limit: 1000,
23
+ cursor,
24
+ sortBy: this.sortBy,
25
+ sortOrder: this.sortOrder,
26
+ });
27
+ gateways.push(...newGateways);
28
+ cursor = nextCursor;
29
+ attempts = 0; // reset attempts if we get a new cursor
30
+ }
31
+ catch (error) {
32
+ console.error('Error fetching gateways', {
33
+ cursor,
34
+ attempts,
35
+ error,
36
+ });
37
+ attempts++;
38
+ }
39
+ } while (cursor !== undefined && attempts < 3);
40
+ // filter out any gateways that are not joined
41
+ const filteredGateways = gateways.filter(this.filter).slice(0, this.limit);
42
+ return filteredGateways.map((g) => new URL(`${g.settings.protocol}://${g.settings.fqdn}:${g.settings.port}`));
43
+ }
44
+ }
@@ -0,0 +1,31 @@
1
+ import { Logger } from '../../../web/index.js';
2
+ export class SimpleCacheGatewaysProvider {
3
+ gatewaysProvider;
4
+ ttlSeconds;
5
+ lastUpdated;
6
+ gatewaysCache;
7
+ logger;
8
+ constructor({ gatewaysProvider, ttlSeconds = 60 * 60, // 1 hour
9
+ logger = Logger.default, }) {
10
+ this.gatewaysCache = [];
11
+ this.gatewaysProvider = gatewaysProvider;
12
+ this.ttlSeconds = ttlSeconds;
13
+ this.logger = logger;
14
+ }
15
+ async getGateways() {
16
+ const now = Date.now();
17
+ if (this.gatewaysCache.length === 0 ||
18
+ now - this.lastUpdated > this.ttlSeconds * 1000) {
19
+ try {
20
+ // preserve the cache if the fetch fails
21
+ const allGateways = await this.gatewaysProvider.getGateways();
22
+ this.gatewaysCache = allGateways;
23
+ this.lastUpdated = now;
24
+ }
25
+ catch (error) {
26
+ this.logger.error('Error fetching gateways', error);
27
+ }
28
+ }
29
+ return this.gatewaysCache;
30
+ }
31
+ }
@@ -0,0 +1,9 @@
1
+ export class StaticGatewaysProvider {
2
+ gateways;
3
+ constructor({ gateways }) {
4
+ this.gateways = gateways.map((g) => new URL(g));
5
+ }
6
+ async getGateways() {
7
+ return this.gateways;
8
+ }
9
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export * from './wayfinder.js';
17
+ // routing strategies
18
+ export * from './routing/strategies/random.js';
19
+ export * from './routing/strategies/static.js';
20
+ export * from './routing/strategies/ping.js';
21
+ export * from './routing/strategies/round-robin.js';
22
+ export * from './routing/strategies/preferred-with-fallback.js';
23
+ // gateways providers
24
+ export * from './gateways/network.js';
25
+ export * from './gateways/simple-cache.js';
26
+ export * from './gateways/static.js';
27
+ // trusted gateways
28
+ export * from './verification/trusted.js';
29
+ // hash providers
30
+ export * from './verification/strategies/data-root-verifier.js';
31
+ export * from './verification/strategies/hash-verifier.js';
32
+ // TODO: signature verification
@@ -0,0 +1,68 @@
1
+ export class FastestPingRoutingStrategy {
2
+ timeoutMs;
3
+ probePath;
4
+ constructor({ timeoutMs = 500, probePath = '/ar-io/info', // TODO: limit to allowed /ar-io and arweave node endpoints
5
+ } = {}) {
6
+ this.timeoutMs = timeoutMs;
7
+ this.probePath = probePath;
8
+ }
9
+ async selectGateway({ gateways }) {
10
+ if (gateways.length === 0) {
11
+ throw new Error('No gateways provided');
12
+ }
13
+ try {
14
+ const results = await Promise.allSettled(gateways.map(async (gateway) => {
15
+ try {
16
+ const startTime = Date.now();
17
+ const response = await fetch(`${gateway.toString().replace(/\/$/, '')}${this.probePath}`, {
18
+ method: 'HEAD',
19
+ signal: AbortSignal.timeout(this.timeoutMs),
20
+ });
21
+ const endTime = Date.now();
22
+ const durationMs = endTime - startTime;
23
+ return {
24
+ gateway,
25
+ status: response.status,
26
+ durationMs,
27
+ error: null,
28
+ };
29
+ }
30
+ catch (error) {
31
+ // Handle network errors
32
+ return {
33
+ gateway,
34
+ status: 'rejected',
35
+ durationMs: Infinity,
36
+ error,
37
+ };
38
+ }
39
+ }));
40
+ // Process results
41
+ const processedResults = results.map((result, index) => {
42
+ if (result.status === 'fulfilled') {
43
+ return result.value;
44
+ }
45
+ else {
46
+ return {
47
+ gateway: gateways[index],
48
+ status: 'rejected',
49
+ durationMs: Infinity,
50
+ error: result.reason,
51
+ };
52
+ }
53
+ });
54
+ // Filter healthy gateways and sort by latency
55
+ const healthyGateways = processedResults
56
+ .filter((result) => result.status === 200)
57
+ .sort((a, b) => a.durationMs - b.durationMs);
58
+ if (healthyGateways.length > 0) {
59
+ return healthyGateways[0].gateway;
60
+ }
61
+ throw new Error('No healthy gateways found');
62
+ }
63
+ catch (error) {
64
+ throw new Error('Failed to ping gateways: ' +
65
+ (error instanceof Error ? error.message : String(error)));
66
+ }
67
+ }
68
+ }
@@ -0,0 +1,46 @@
1
+ import { Logger } from '../../../logger.js';
2
+ import { FastestPingRoutingStrategy } from './ping.js';
3
+ export class PreferredWithFallbackRoutingStrategy {
4
+ name = 'preferred-with-fallback';
5
+ preferredGateway;
6
+ fallbackStrategy;
7
+ logger;
8
+ constructor({ preferredGateway, fallbackStrategy = new FastestPingRoutingStrategy(), logger = Logger.default, }) {
9
+ try {
10
+ this.preferredGateway = new URL(preferredGateway);
11
+ }
12
+ catch (error) {
13
+ throw new Error(`Invalid URL provided for preferred gateway: ${preferredGateway}`);
14
+ }
15
+ this.fallbackStrategy = fallbackStrategy;
16
+ this.logger = logger;
17
+ }
18
+ async selectGateway({ gateways = [] }) {
19
+ this.logger.debug('Attempting to connect to preferred gateway', {
20
+ preferredGateway: this.preferredGateway.toString(),
21
+ });
22
+ try {
23
+ // Check if the preferred gateway is responsive
24
+ const response = await fetch(this.preferredGateway.toString(), {
25
+ method: 'HEAD',
26
+ signal: AbortSignal.timeout(1000),
27
+ });
28
+ if (response.ok) {
29
+ this.logger.debug('Successfully connected to preferred gateway', {
30
+ preferredGateway: this.preferredGateway.toString(),
31
+ });
32
+ return this.preferredGateway;
33
+ }
34
+ throw new Error(`Preferred gateway responded with status: ${response.status}`);
35
+ }
36
+ catch (error) {
37
+ this.logger.warn('Failed to connect to preferred gateway, falling back to alternative strategy', {
38
+ preferredGateway: this.preferredGateway.toString(),
39
+ error: error instanceof Error ? error.message : String(error),
40
+ fallbackStrategy: this.fallbackStrategy.constructor.name,
41
+ });
42
+ // Fall back to the provided routing strategy
43
+ return this.fallbackStrategy.selectGateway({ gateways });
44
+ }
45
+ }
46
+ }
@@ -0,0 +1,9 @@
1
+ import { randomInt } from '../../../../utils/random.js';
2
+ export class RandomRoutingStrategy {
3
+ async selectGateway({ gateways }) {
4
+ if (gateways.length === 0) {
5
+ throw new Error('No gateways available');
6
+ }
7
+ return gateways[randomInt(0, gateways.length)];
8
+ }
9
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { Logger } from '../../../../common/logger.js';
17
+ export class RoundRobinRoutingStrategy {
18
+ gateways;
19
+ currentIndex;
20
+ logger;
21
+ constructor({ gateways, logger = Logger.default, }) {
22
+ this.gateways = gateways;
23
+ this.currentIndex = 0;
24
+ this.logger = logger;
25
+ }
26
+ // provided gateways are ignored
27
+ async selectGateway({ gateways = [], } = {}) {
28
+ if (gateways.length > 0) {
29
+ this.logger.warn('RoundRobinRoutingStrategy does not accept provided gateways. Ignoring provided gateways...', {
30
+ providedGateways: gateways.length,
31
+ internalGateways: this.gateways,
32
+ });
33
+ }
34
+ const gateway = this.gateways[this.currentIndex];
35
+ this.currentIndex = (this.currentIndex + 1) % this.gateways.length;
36
+ return gateway;
37
+ }
38
+ }
@@ -0,0 +1,25 @@
1
+ import { Logger } from '../../../logger.js';
2
+ export class StaticRoutingStrategy {
3
+ name = 'static';
4
+ gateway;
5
+ logger;
6
+ constructor({ gateway, logger = Logger.default, }) {
7
+ try {
8
+ this.gateway = new URL(gateway);
9
+ }
10
+ catch (error) {
11
+ throw new Error(`Invalid URL provided for static gateway: ${gateway}`);
12
+ }
13
+ this.logger = logger;
14
+ }
15
+ // provided gateways are ignored
16
+ async selectGateway({ gateways = [], } = {}) {
17
+ if (gateways.length > 0) {
18
+ this.logger.warn('StaticRoutingStrategy does not accept provided gateways. Ignoring provided gateways...', {
19
+ providedGateways: gateways.length,
20
+ internalGateway: this.gateway,
21
+ });
22
+ }
23
+ return this.gateway;
24
+ }
25
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import Arweave from 'arweave';
17
+ import { MAX_CHUNK_SIZE, MIN_CHUNK_SIZE, buildLayers, generateLeaves, } from 'arweave/node/lib/merkle.js';
18
+ import { toB64Url } from '../../../../utils/base64.js';
19
+ import { isAsyncIterable, readableStreamToAsyncIterable, } from '../../../../utils/hash.js';
20
+ export const convertDataStreamToDataRoot = async ({ dataStream, }) => {
21
+ const chunks = [];
22
+ let leftover = new Uint8Array(0);
23
+ let cursor = 0;
24
+ const asyncIterable = isAsyncIterable(dataStream)
25
+ ? dataStream
26
+ : readableStreamToAsyncIterable(dataStream);
27
+ for await (const data of asyncIterable) {
28
+ const inputChunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
29
+ const combined = new Uint8Array(leftover.length + inputChunk.length);
30
+ combined.set(leftover, 0);
31
+ combined.set(inputChunk, leftover.length);
32
+ let startIndex = 0;
33
+ while (combined.length - startIndex >= MAX_CHUNK_SIZE) {
34
+ let chunkSize = MAX_CHUNK_SIZE;
35
+ const remainderAfterThis = combined.length - startIndex - MAX_CHUNK_SIZE;
36
+ if (remainderAfterThis > 0 && remainderAfterThis < MIN_CHUNK_SIZE) {
37
+ chunkSize = Math.ceil((combined.length - startIndex) / 2);
38
+ }
39
+ const chunkData = combined.slice(startIndex, startIndex + chunkSize);
40
+ const dataHash = await Arweave.crypto.hash(chunkData);
41
+ chunks.push({
42
+ dataHash,
43
+ minByteRange: cursor,
44
+ maxByteRange: cursor + chunkSize,
45
+ });
46
+ cursor += chunkSize;
47
+ startIndex += chunkSize;
48
+ }
49
+ leftover = combined.slice(startIndex);
50
+ }
51
+ if (leftover.length > 0) {
52
+ // TODO: ensure a web friendly crypto hash function is used in web
53
+ const dataHash = await Arweave.crypto.hash(leftover);
54
+ chunks.push({
55
+ dataHash,
56
+ minByteRange: cursor,
57
+ maxByteRange: cursor + leftover.length,
58
+ });
59
+ }
60
+ const leaves = await generateLeaves(chunks);
61
+ const root = await buildLayers(leaves);
62
+ return toB64Url(Buffer.from(root.id));
63
+ };
64
+ export class DataRootVerificationStrategy {
65
+ trustedDataRootProvider;
66
+ constructor({ trustedDataRootProvider, }) {
67
+ this.trustedDataRootProvider = trustedDataRootProvider;
68
+ }
69
+ async verifyData({ data, txId, }) {
70
+ const [computedDataRoot, trustedDataRoot] = await Promise.all([
71
+ convertDataStreamToDataRoot({
72
+ dataStream: data,
73
+ }),
74
+ this.trustedDataRootProvider.getDataRoot({
75
+ txId,
76
+ }),
77
+ ]);
78
+ if (computedDataRoot !== trustedDataRoot) {
79
+ throw new Error('Data root does not match', {
80
+ cause: { computedDataRoot, trustedDataRoot },
81
+ });
82
+ }
83
+ }
84
+ }
85
+ // some data item options
86
+ // compute and verify data root, use offsets from server and verify the signature that the data item at the offset matches the signature
87
+ // does not give you assurance of valid bundle, but gives verification that the data item itself is valid
88
+ // reading from offsets is the only way for the client to compute and verify the signature
89
+ /**
90
+ * - when you get a signature of a data item, you can only verify the owner
91
+ * - you still need to verify it's going back to the bundle, unpack it, and verify the data item exists at the offset
92
+ * - you need to the location of the chunks for the data item, and prove it's in the chunk and then prove the data root of the bundle, then you have fully verified the data verifier
93
+ * - how to prove the data item is on arweave - verify the merkle hash that the chunks for the data item, fit within the expected tree of the parent bundle
94
+ *
95
+ * Composite verifier - you'll want to be very efficient with streams
96
+ * - hash verifier
97
+ * - parent chunks verifier --> for any range of data within a single transaction, tell me that it's correct
98
+ * - signature verifier
99
+ * - offset verifier
100
+ * - data item verifier
101
+ */
102
+ // introduce a composite verifier that determines where/how to lookup the hash
@@ -0,0 +1,23 @@
1
+ import { hashDataStreamToB64Url } from '../../../../utils/hash.js';
2
+ export class HashVerificationStrategy {
3
+ trustedHashProvider;
4
+ constructor({ trustedHashProvider, }) {
5
+ this.trustedHashProvider = trustedHashProvider;
6
+ }
7
+ async verifyData({ data, txId, }) {
8
+ // kick off the hash computation, but don't wait for it until we compute our own hash
9
+ const [computedHash, fetchedHash] = await Promise.all([
10
+ hashDataStreamToB64Url(data),
11
+ this.trustedHashProvider.getHash({ txId }),
12
+ ]);
13
+ // await on the hash promise and compare to get a little concurrency when computing hashes over larger data
14
+ if (computedHash === undefined) {
15
+ throw new Error('Hash could not be computed');
16
+ }
17
+ if (computedHash !== fetchedHash.hash) {
18
+ throw new Error('Hash does not match', {
19
+ cause: { computedHash, trustedHash: fetchedHash },
20
+ });
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,121 @@
1
+ import { sandboxFromId } from '../wayfinder.js';
2
+ const arioGatewayHeaders = {
3
+ digest: 'x-ar-io-digest',
4
+ verified: 'x-ar-io-verified',
5
+ txId: 'x-arns-resolved-tx-id',
6
+ processId: 'x-arns-resolved-process-id',
7
+ };
8
+ export class TrustedGatewaysHashProvider {
9
+ gatewaysProvider;
10
+ constructor({ gatewaysProvider,
11
+ // TODO: add threshold for allowed hash difference (i.e. by count or ratio of total gateways checked)
12
+ }) {
13
+ this.gatewaysProvider = gatewaysProvider;
14
+ }
15
+ /**
16
+ * Gets the digest for a given txId from all trusted gateways and ensures they all match.
17
+ * @param txId - The txId to get the digest for.
18
+ * @returns The digest for the given txId.
19
+ */
20
+ async getHash({ txId, }) {
21
+ // get the hash from every gateway, and ensure they all match
22
+ const hashSet = new Set();
23
+ const hashResults = [];
24
+ const gateways = await this.gatewaysProvider.getGateways();
25
+ const hashes = await Promise.all(gateways.map(async (gateway) => {
26
+ const sandbox = sandboxFromId(txId);
27
+ const urlWithSandbox = `${gateway.protocol}//${sandbox}.${gateway.hostname}/${txId}`;
28
+ let txIdHash;
29
+ /**
30
+ * This is a problem because we're not able to verify the hash of the data item if the gateway doesn't have the data in its cache.
31
+ * We should add the ability to send a HEAD request to trigger a GET request to hydrate the cache on the trusted gateway via a header.
32
+ * For now, we'll just do a GET request to hydrate the cache if the HEAD request doesn't contain the digest.
33
+ */
34
+ for (const method of ['GET', 'GET']) {
35
+ const response = await fetch(urlWithSandbox, {
36
+ method,
37
+ redirect: 'follow',
38
+ mode: 'cors',
39
+ headers: {
40
+ 'Cache-Control': 'no-cache',
41
+ },
42
+ });
43
+ if (!response.ok) {
44
+ // skip if the request failed or the digest is not present
45
+ return;
46
+ }
47
+ const fetchedTxIdHash = response.headers.get(arioGatewayHeaders.digest);
48
+ if (fetchedTxIdHash !== null && fetchedTxIdHash !== undefined) {
49
+ txIdHash = fetchedTxIdHash;
50
+ break;
51
+ }
52
+ }
53
+ if (txIdHash === undefined) {
54
+ // skip this gateway if we didn't get a hash
55
+ return undefined;
56
+ }
57
+ hashResults.push({
58
+ gateway: gateway.hostname,
59
+ txIdHash,
60
+ });
61
+ return txIdHash;
62
+ }));
63
+ for (const hash of hashes) {
64
+ if (hash !== undefined) {
65
+ hashSet.add(hash);
66
+ }
67
+ }
68
+ if (hashSet.size === 0) {
69
+ throw new Error(`No trusted gateways returned a hash for txId ${txId}`);
70
+ }
71
+ if (hashSet.size > 1) {
72
+ throw new Error(`Failed to get consistent hash from all trusted gateways. ${JSON.stringify(hashResults)}`);
73
+ }
74
+ return { hash: hashResults[0].txIdHash, algorithm: 'sha256' };
75
+ }
76
+ /**
77
+ * Get the data root for a given txId from all trusted gateways and ensure they all match.
78
+ * @param txId - The txId to get the data root for.
79
+ * @returns The data root for the given txId.
80
+ */
81
+ async getDataRoot({ txId }) {
82
+ const dataRootSet = new Set();
83
+ const dataRootResults = [];
84
+ const gateways = await this.gatewaysProvider.getGateways();
85
+ const dataRoots = await Promise.all(gateways.map(async (gateway) => {
86
+ const response = await fetch(`${gateway.toString()}tx/${txId}/data_root`);
87
+ if (!response.ok) {
88
+ // skip this gateway
89
+ return undefined;
90
+ }
91
+ const dataRoot = await response.text();
92
+ dataRootResults.push({
93
+ gateway: gateway.hostname,
94
+ dataRoot,
95
+ });
96
+ return dataRoot;
97
+ }));
98
+ for (const dataRoot of dataRoots) {
99
+ if (dataRoot !== undefined) {
100
+ dataRootSet.add(dataRoot);
101
+ }
102
+ }
103
+ if (dataRootSet.size > 1) {
104
+ throw new Error(`Failed to get consistent data root from all trusted gateways. ${JSON.stringify(dataRootResults)}`);
105
+ }
106
+ return dataRootSet.values().next().value;
107
+ }
108
+ }
109
+ // client could check hashes of data items, match expected hash
110
+ // if the gateway has the hash and they've verified it, you can trust the data item and offset
111
+ // you would be only trusting the gateway that it is a valid bundle
112
+ // you can request the offset from the gateway to verify the id
113
+ /**
114
+ * Note from @djwhitt
115
+ *
116
+ * Calculating data roots this way is fine, but it may not reproduce the original data root.
117
+ * We could also implement a data root verifier that pulls all the chunks, checks that they
118
+ * reproduce the expected data root, and then compares the concatenated chunk data to the
119
+ * original data retrieved. That would take a while, but it should be able to verify any L1
120
+ * data where we can find the chunks.
121
+ */