@ar.io/sdk 3.11.0-alpha.1 → 3.11.0-alpha.11

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 (64) hide show
  1. package/README.md +52 -0
  2. package/bundles/web.bundle.min.js +119 -116
  3. package/lib/cjs/cli/cli.js +137 -122
  4. package/lib/cjs/cli/commands/readCommands.js +6 -0
  5. package/lib/cjs/cli/utils.js +4 -1
  6. package/lib/cjs/common/ant.js +5 -5
  7. package/lib/cjs/common/io.js +49 -3
  8. package/lib/cjs/common/wayfinder/gateways/trusted-gateways.js +106 -0
  9. package/lib/cjs/common/wayfinder/gateways.js +19 -8
  10. package/lib/cjs/common/wayfinder/index.js +9 -1
  11. package/lib/cjs/common/wayfinder/routers/priority.js +11 -20
  12. package/lib/cjs/common/wayfinder/routers/priority.test.js +5 -5
  13. package/lib/cjs/common/wayfinder/routers/random.js +2 -2
  14. package/lib/cjs/common/wayfinder/routers/random.test.js +5 -84
  15. package/lib/cjs/common/wayfinder/routers/{fixed.js → static.js} +5 -5
  16. package/lib/cjs/common/wayfinder/routers/{fixed.test.js → static.test.js} +4 -4
  17. package/lib/cjs/common/wayfinder/verification/data-root-verifier.js +139 -0
  18. package/lib/cjs/common/wayfinder/verification/hash-verifier.js +50 -0
  19. package/lib/cjs/common/wayfinder/wayfinder.js +459 -30
  20. package/lib/cjs/common/wayfinder/wayfinder.test.js +296 -49
  21. package/lib/cjs/types/wayfinder.js +1 -0
  22. package/lib/cjs/utils/ao.js +37 -0
  23. package/lib/cjs/utils/arweave.js +1 -1
  24. package/lib/cjs/utils/hash.js +56 -0
  25. package/lib/cjs/version.js +1 -1
  26. package/lib/esm/cli/cli.js +138 -123
  27. package/lib/esm/cli/commands/readCommands.js +5 -0
  28. package/lib/esm/cli/utils.js +4 -1
  29. package/lib/esm/common/ant.js +5 -5
  30. package/lib/esm/common/io.js +49 -3
  31. package/lib/esm/common/wayfinder/gateways/trusted-gateways.js +102 -0
  32. package/lib/esm/common/wayfinder/gateways.js +17 -6
  33. package/lib/esm/common/wayfinder/index.js +9 -1
  34. package/lib/esm/common/wayfinder/routers/priority.js +11 -20
  35. package/lib/esm/common/wayfinder/routers/priority.test.js +5 -5
  36. package/lib/esm/common/wayfinder/routers/random.js +2 -2
  37. package/lib/esm/common/wayfinder/routers/random.test.js +5 -84
  38. package/lib/esm/common/wayfinder/routers/{fixed.js → static.js} +3 -3
  39. package/lib/esm/common/wayfinder/routers/{fixed.test.js → static.test.js} +4 -4
  40. package/lib/esm/common/wayfinder/verification/data-root-verifier.js +130 -0
  41. package/lib/esm/common/wayfinder/verification/hash-verifier.js +46 -0
  42. package/lib/esm/common/wayfinder/wayfinder.js +453 -30
  43. package/lib/esm/common/wayfinder/wayfinder.test.js +297 -50
  44. package/lib/esm/types/wayfinder.js +1 -0
  45. package/lib/esm/utils/ao.js +37 -0
  46. package/lib/esm/utils/arweave.js +1 -1
  47. package/lib/esm/utils/hash.js +50 -0
  48. package/lib/esm/version.js +1 -1
  49. package/lib/types/cli/commands/readCommands.d.ts +1 -0
  50. package/lib/types/common/io.d.ts +7 -8
  51. package/lib/types/common/wayfinder/gateways/trusted-gateways.d.ts +51 -0
  52. package/lib/types/common/wayfinder/gateways.d.ts +16 -7
  53. package/lib/types/common/wayfinder/index.d.ts +5 -1
  54. package/lib/types/common/wayfinder/routers/priority.d.ts +8 -12
  55. package/lib/types/common/wayfinder/routers/{fixed.d.ts → static.d.ts} +3 -3
  56. package/lib/types/common/wayfinder/verification/data-root-verifier.d.ts +31 -0
  57. package/lib/types/common/wayfinder/verification/hash-verifier.d.ts +27 -0
  58. package/lib/types/common/wayfinder/wayfinder.d.ts +169 -17
  59. package/lib/types/types/io.d.ts +16 -1
  60. package/lib/types/types/wayfinder.d.ts +43 -0
  61. package/lib/types/utils/hash.d.ts +4 -0
  62. package/lib/types/version.d.ts +1 -1
  63. package/package.json +1 -1
  64. /package/lib/types/common/wayfinder/routers/{fixed.test.d.ts → static.test.d.ts} +0 -0
@@ -1,7 +1,15 @@
1
- export class ARIOGatewaysProvider {
1
+ export class NetworkGatewaysProvider {
2
2
  ario;
3
- constructor({ ario }) {
3
+ sortBy;
4
+ sortOrder;
5
+ limit;
6
+ filter;
7
+ constructor({ ario, sortBy = 'operatorStake', sortOrder = 'desc', limit = 1000, filter = (g) => g.status === 'joined', }) {
4
8
  this.ario = ario;
9
+ this.sortBy = sortBy;
10
+ this.sortOrder = sortOrder;
11
+ this.limit = limit;
12
+ this.filter = filter;
5
13
  }
6
14
  async getGateways() {
7
15
  let cursor;
@@ -9,9 +17,11 @@ export class ARIOGatewaysProvider {
9
17
  const gateways = [];
10
18
  do {
11
19
  try {
12
- const { items: newGateways, nextCursor } = await this.ario.getGateways({
20
+ const { items: newGateways = [], nextCursor } = await this.ario.getGateways({
13
21
  limit: 1000,
14
22
  cursor,
23
+ sortBy: this.sortBy,
24
+ sortOrder: this.sortOrder,
15
25
  });
16
26
  gateways.push(...newGateways);
17
27
  cursor = nextCursor;
@@ -27,13 +37,14 @@ export class ARIOGatewaysProvider {
27
37
  }
28
38
  } while (cursor !== undefined && attempts < 3);
29
39
  // filter out any gateways that are not joined
30
- return gateways.filter((g) => g.status === 'joined');
40
+ const filteredGateways = gateways.filter(this.filter).slice(0, this.limit);
41
+ return filteredGateways.map((g) => new URL(`${g.settings.protocol}://${g.settings.fqdn}:${g.settings.port}`));
31
42
  }
32
43
  }
33
44
  export class StaticGatewaysProvider {
34
45
  gateways;
35
46
  constructor({ gateways }) {
36
- this.gateways = gateways;
47
+ this.gateways = gateways.map((g) => new URL(g));
37
48
  }
38
49
  async getGateways() {
39
50
  return this.gateways;
@@ -57,7 +68,7 @@ export class SimpleCacheGatewaysProvider {
57
68
  try {
58
69
  // preserve the cache if the fetch fails
59
70
  const allGateways = await this.gatewaysProvider.getGateways();
60
- this.gatewaysCache = allGateways.filter((g) => g.status === 'joined');
71
+ this.gatewaysCache = allGateways;
61
72
  this.lastUpdated = now;
62
73
  }
63
74
  catch (error) {
@@ -17,4 +17,12 @@ export * from './wayfinder.js';
17
17
  // routers
18
18
  export * from './routers/random.js';
19
19
  export * from './routers/priority.js';
20
- export * from './routers/fixed.js';
20
+ export * from './routers/static.js';
21
+ // gateways providers
22
+ export * from './gateways.js';
23
+ // trusted gateways
24
+ export * from './gateways/trusted-gateways.js';
25
+ // hash providers
26
+ export * from './verification/data-root-verifier.js';
27
+ export * from './verification/hash-verifier.js';
28
+ // TODO: signature verification
@@ -1,34 +1,25 @@
1
1
  import { randomInt } from '../../../utils/random.js';
2
+ import { NetworkGatewaysProvider } from '../gateways.js';
2
3
  // TODO: one of N where N are in the last time window have met certain performance thresholds
3
4
  // TODO: look at bitorrent routing protocols for inspiration
4
5
  // TODO: router that looks at local stats/metrics and adjusts based on those
5
6
  export class PriorityGatewayRouter {
6
7
  name = 'priority';
7
8
  gatewaysProvider;
8
- limit;
9
- sortBy;
10
- sortOrder;
11
- blocklist;
12
- constructor({ gatewaysProvider, limit = 1, sortBy = 'operatorStake', sortOrder = 'desc', blocklist = [], }) {
13
- this.gatewaysProvider = gatewaysProvider;
14
- this.limit = limit;
15
- this.sortBy = sortBy;
16
- this.sortOrder = sortOrder;
17
- this.blocklist = blocklist;
9
+ constructor({ ario, sortBy, sortOrder, limit, }) {
10
+ this.gatewaysProvider = new NetworkGatewaysProvider({
11
+ ario,
12
+ sortBy,
13
+ sortOrder,
14
+ limit,
15
+ });
18
16
  }
19
17
  async getTargetGateway() {
20
- const allGateways = await this.gatewaysProvider.getGateways();
21
- const gateways = allGateways.filter((gateway) => gateway.status === 'joined' &&
22
- !this.blocklist.includes(gateway.settings.fqdn));
23
- const sortedGateways = gateways
24
- .sort(this.sortOrder === 'asc'
25
- ? (a, b) => a[this.sortBy] - b[this.sortBy]
26
- : (a, b) => b[this.sortBy] - a[this.sortBy])
27
- .slice(0, this.limit);
28
- const targetGateway = sortedGateways[randomInt(0, sortedGateways.length)];
18
+ const gateways = await this.gatewaysProvider.getGateways();
19
+ const targetGateway = gateways[randomInt(0, gateways.length)];
29
20
  if (targetGateway === undefined) {
30
21
  throw new Error('No target gateway found');
31
22
  }
32
- return new URL(`${targetGateway.settings.protocol}://${targetGateway.settings.fqdn}:${targetGateway.settings.port}`);
23
+ return targetGateway;
33
24
  }
34
25
  }
@@ -127,13 +127,13 @@ describe('PriorityRouter', () => {
127
127
  },
128
128
  },
129
129
  ];
130
- const mockGatewaysProvider = {
131
- getGateways: async () => mockGateways,
130
+ const mockArIOClient = {
131
+ getGateways: async () => ({ items: mockGateways }),
132
132
  };
133
133
  it('should prioritize gateway with highest success rate when using successRate weight', async () => {
134
134
  const router = new PriorityGatewayRouter({
135
- gatewaysProvider: mockGatewaysProvider,
136
- sortBy: 'totalDelegatedStake',
135
+ ario: mockArIOClient,
136
+ sortBy: 'operatorStake',
137
137
  sortOrder: 'desc',
138
138
  limit: 1,
139
139
  });
@@ -142,7 +142,7 @@ describe('PriorityRouter', () => {
142
142
  });
143
143
  it('should prioritize gateway with lowest latency when using latency weight', async () => {
144
144
  const router = new PriorityGatewayRouter({
145
- gatewaysProvider: mockGatewaysProvider,
145
+ ario: mockArIOClient,
146
146
  sortBy: 'operatorStake',
147
147
  sortOrder: 'desc',
148
148
  limit: 1,
@@ -9,11 +9,11 @@ export class RandomGatewayRouter {
9
9
  }
10
10
  async getTargetGateway() {
11
11
  const allGateways = await this.gatewaysProvider.getGateways();
12
- const gateways = allGateways.filter((g) => g.status === 'joined' && !this.blocklist.includes(g.settings.fqdn));
12
+ const gateways = allGateways.filter((g) => !this.blocklist.includes(g.hostname));
13
13
  const targetGateway = gateways[randomInt(0, gateways.length)];
14
14
  if (targetGateway === undefined) {
15
15
  throw new Error('No target gateway found');
16
16
  }
17
- return new URL(`${targetGateway.settings.protocol}://${targetGateway.settings.fqdn}:${targetGateway.settings.port}`);
17
+ return targetGateway;
18
18
  }
19
19
  }
@@ -3,88 +3,9 @@ import { describe, it } from 'node:test';
3
3
  import { RandomGatewayRouter } from './random.js';
4
4
  describe('RandomRouter', () => {
5
5
  const mockGateways = [
6
- {
7
- settings: {
8
- fqdn: 'gateway1.net',
9
- port: 443,
10
- protocol: 'https',
11
- allowDelegatedStaking: false,
12
- delegateRewardShareRatio: 0.5,
13
- allowedDelegates: [],
14
- minDelegatedStake: 0,
15
- autoStake: false,
16
- properties: '',
17
- label: '',
18
- note: '',
19
- },
20
- gatewayAddress: 'addr1',
21
- observerAddress: 'addr1',
22
- totalDelegatedStake: 1000,
23
- startTimestamp: 0,
24
- endTimestamp: 0,
25
- operatorStake: 100,
26
- status: 'joined',
27
- weights: {
28
- normalizedCompositeWeight: 0.5,
29
- stakeWeight: 0.5,
30
- tenureWeight: 0.5,
31
- gatewayPerformanceRatio: 0.5,
32
- observerPerformanceRatio: 0.5,
33
- compositeWeight: 0.5,
34
- gatewayRewardRatioWeight: 0.5,
35
- observerRewardRatioWeight: 0.5,
36
- },
37
- stats: {
38
- passedConsecutiveEpochs: 10,
39
- failedConsecutiveEpochs: 5,
40
- totalEpochCount: 15,
41
- passedEpochCount: 10,
42
- failedEpochCount: 5,
43
- observedEpochCount: 15,
44
- prescribedEpochCount: 20,
45
- },
46
- },
47
- {
48
- settings: {
49
- fqdn: 'gateway2.net',
50
- port: 443,
51
- protocol: 'https',
52
- allowDelegatedStaking: false,
53
- delegateRewardShareRatio: 0.5,
54
- allowedDelegates: [],
55
- minDelegatedStake: 0,
56
- autoStake: false,
57
- properties: '',
58
- label: '',
59
- note: '',
60
- },
61
- gatewayAddress: 'addr2',
62
- observerAddress: 'addr2',
63
- totalDelegatedStake: 0,
64
- startTimestamp: 0,
65
- endTimestamp: 0,
66
- operatorStake: 0,
67
- status: 'leaving',
68
- weights: {
69
- normalizedCompositeWeight: 0.5,
70
- stakeWeight: 0.5,
71
- tenureWeight: 0.5,
72
- gatewayPerformanceRatio: 0.5,
73
- observerPerformanceRatio: 0.5,
74
- compositeWeight: 0.5,
75
- gatewayRewardRatioWeight: 0.5,
76
- observerRewardRatioWeight: 0.5,
77
- },
78
- stats: {
79
- passedConsecutiveEpochs: 10,
80
- failedConsecutiveEpochs: 5,
81
- totalEpochCount: 15,
82
- passedEpochCount: 10,
83
- failedEpochCount: 5,
84
- observedEpochCount: 15,
85
- prescribedEpochCount: 20,
86
- },
87
- },
6
+ new URL('https://gateway1.net'),
7
+ new URL('https://gateway2.net'),
8
+ new URL('https://gateway3.net'),
88
9
  ];
89
10
  const mockGatewaysProvider = {
90
11
  getGateways: async () => mockGateways,
@@ -93,10 +14,10 @@ describe('RandomRouter', () => {
93
14
  const router = new RandomGatewayRouter({
94
15
  gatewaysProvider: mockGatewaysProvider,
95
16
  });
96
- // Run multiple times to ensure we only get joined gateways
17
+ // random gateway should be one of the mock gateways
97
18
  for (let i = 0; i < 10; i++) {
98
19
  const result = await router.getTargetGateway();
99
- assert.deepStrictEqual(result, new URL('https://gateway1.net'));
20
+ assert.ok(mockGateways.includes(result));
100
21
  }
101
22
  });
102
23
  });
@@ -1,8 +1,8 @@
1
- export class FixedGatewayRouter {
2
- name = 'fixed';
1
+ export class StaticGatewayRouter {
2
+ name = 'static';
3
3
  gateway;
4
4
  constructor({ gateway }) {
5
- this.gateway = gateway;
5
+ this.gateway = new URL(gateway);
6
6
  }
7
7
  async getTargetGateway() {
8
8
  return this.gateway;
@@ -1,10 +1,10 @@
1
1
  import { strict as assert } from 'node:assert';
2
2
  import { describe, it } from 'node:test';
3
- import { FixedGatewayRouter } from './fixed.js';
4
- describe('FixedRouter', () => {
3
+ import { StaticGatewayRouter } from './static.js';
4
+ describe('StaticGatewayRouter', () => {
5
5
  it('should return the provided gateway', async () => {
6
- const router = new FixedGatewayRouter({
7
- gateway: new URL('http://test-gateway.net'),
6
+ const router = new StaticGatewayRouter({
7
+ gateway: 'http://test-gateway.net',
8
8
  });
9
9
  const result = await router.getTargetGateway();
10
10
  assert.deepStrictEqual(result, new URL('http://test-gateway.net'));
@@ -0,0 +1,130 @@
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 { Readable } from 'node:stream';
19
+ import { toB64Url } from '../../../utils/base64.js';
20
+ export async function convertBufferToDataRoot({ buffer, }) {
21
+ const chunks = [];
22
+ let cursor = 0;
23
+ let offset = 0;
24
+ while (offset < buffer.byteLength) {
25
+ let chunkSize = Math.min(MAX_CHUNK_SIZE, buffer.byteLength - offset);
26
+ const remainder = buffer.byteLength - offset - chunkSize;
27
+ if (remainder > 0 && remainder < MIN_CHUNK_SIZE) {
28
+ chunkSize = Math.ceil((buffer.byteLength - offset) / 2);
29
+ }
30
+ // subarray does not exist on web Buffer type
31
+ const slice = buffer.subarray(offset, offset + chunkSize);
32
+ const hash = await crypto.subtle.digest('SHA-256', slice);
33
+ const hashArray = new Uint8Array(hash);
34
+ chunks.push({
35
+ dataHash: hashArray,
36
+ minByteRange: cursor,
37
+ maxByteRange: cursor + chunkSize,
38
+ });
39
+ cursor += chunkSize;
40
+ offset += chunkSize;
41
+ }
42
+ const leaves = await generateLeaves(chunks);
43
+ const result = await buildLayers(leaves);
44
+ return Buffer.from(result.id).toString('base64url');
45
+ }
46
+ export const convertReadableToDataRoot = async ({ iterable, }) => {
47
+ const chunks = [];
48
+ let leftover = new Uint8Array(0);
49
+ let cursor = 0;
50
+ for await (const data of iterable) {
51
+ const inputChunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
52
+ const combined = new Uint8Array(leftover.length + inputChunk.length);
53
+ combined.set(leftover, 0);
54
+ combined.set(inputChunk, leftover.length);
55
+ let startIndex = 0;
56
+ while (combined.length - startIndex >= MAX_CHUNK_SIZE) {
57
+ let chunkSize = MAX_CHUNK_SIZE;
58
+ const remainderAfterThis = combined.length - startIndex - MAX_CHUNK_SIZE;
59
+ if (remainderAfterThis > 0 && remainderAfterThis < MIN_CHUNK_SIZE) {
60
+ chunkSize = Math.ceil((combined.length - startIndex) / 2);
61
+ }
62
+ const chunkData = combined.slice(startIndex, startIndex + chunkSize);
63
+ const dataHash = await Arweave.crypto.hash(chunkData);
64
+ chunks.push({
65
+ dataHash,
66
+ minByteRange: cursor,
67
+ maxByteRange: cursor + chunkSize,
68
+ });
69
+ cursor += chunkSize;
70
+ startIndex += chunkSize;
71
+ }
72
+ leftover = combined.slice(startIndex);
73
+ }
74
+ if (leftover.length > 0) {
75
+ const dataHash = await Arweave.crypto.hash(leftover);
76
+ chunks.push({
77
+ dataHash,
78
+ minByteRange: cursor,
79
+ maxByteRange: cursor + leftover.length,
80
+ });
81
+ }
82
+ const leaves = await generateLeaves(chunks);
83
+ const root = await buildLayers(leaves);
84
+ return toB64Url(Buffer.from(root.id));
85
+ };
86
+ export class DataRootVerifier {
87
+ trustedDataRootProvider;
88
+ constructor({ trustedDataRootProvider, }) {
89
+ this.trustedDataRootProvider = trustedDataRootProvider;
90
+ }
91
+ async verifyData({ data, txId, }) {
92
+ const trustedDataRootPromise = this.trustedDataRootProvider.getDataRoot({
93
+ txId,
94
+ });
95
+ let computedDataRoot;
96
+ if (Buffer.isBuffer(data)) {
97
+ computedDataRoot = await convertBufferToDataRoot({ buffer: data });
98
+ }
99
+ else if (data instanceof Readable || data instanceof ReadableStream) {
100
+ computedDataRoot = await convertReadableToDataRoot({ iterable: data });
101
+ }
102
+ if (computedDataRoot === undefined) {
103
+ throw new Error('Data root could not be computed');
104
+ }
105
+ const trustedDataRoot = await trustedDataRootPromise;
106
+ if (computedDataRoot !== trustedDataRoot) {
107
+ throw new Error('Data root does not match', {
108
+ cause: { computedDataRoot, trustedDataRoot },
109
+ });
110
+ }
111
+ }
112
+ }
113
+ // some data item options
114
+ // compute and verify data root, use offsets from server and verify the signature that the data item at the offset matches the signature
115
+ // does not give you assurance of valid bundle, but gives verification that the data item itself is valid
116
+ // reading from offsets is the only way for the client to compute and verify the signature
117
+ /**
118
+ * - when you get a signature of a data item, you can only verify the owner
119
+ * - you still need to verify it's going back to the bundle, unpack it, and verify the data item exists at the offset
120
+ * - 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
121
+ * - 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
122
+ *
123
+ * Composite verifier - you'll want to be very efficient with streams
124
+ * - hash verifier
125
+ * - parent chunks verifier --> for any range of data within a single transaction, tell me that it's correct
126
+ * - signature verifier
127
+ * - offset verifier
128
+ * - data item verifier
129
+ */
130
+ // introduce a composite verifier that determines where/how to lookup the hash
@@ -0,0 +1,46 @@
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 { Readable } from 'node:stream';
17
+ import { hashBufferToB64Url, hashReadableStreamToB64Url, hashReadableToB64Url, } from '../../../utils/hash.js';
18
+ export class HashVerifier {
19
+ trustedHashProvider;
20
+ constructor({ trustedHashProvider, }) {
21
+ this.trustedHashProvider = trustedHashProvider;
22
+ }
23
+ async verifyData({ data, txId, }) {
24
+ const hashPromise = this.trustedHashProvider.getHash({ txId });
25
+ let computedHash;
26
+ if (Buffer.isBuffer(data)) {
27
+ computedHash = hashBufferToB64Url(data);
28
+ }
29
+ else if (data instanceof Readable) {
30
+ computedHash = await hashReadableToB64Url(data);
31
+ }
32
+ else if (data instanceof ReadableStream) {
33
+ computedHash = await hashReadableStreamToB64Url(data);
34
+ }
35
+ // await on the hash promise and compare to get a little concurrency when computing hashes over larger data
36
+ const { hash } = await hashPromise;
37
+ if (computedHash === undefined) {
38
+ throw new Error('Hash could not be computed');
39
+ }
40
+ if (computedHash !== hash) {
41
+ throw new Error('Hash does not match', {
42
+ cause: { computedHash, trustedHash: hash },
43
+ });
44
+ }
45
+ }
46
+ }