@ar.io/sdk 3.11.0-alpha.12 → 3.11.0-alpha.14

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 (68) hide show
  1. package/bundles/web.bundle.min.js +120 -123
  2. package/lib/cjs/common/ant-versions.js +3 -2
  3. package/lib/cjs/common/index.js +0 -2
  4. package/lib/cjs/common/io.js +13 -9
  5. package/lib/cjs/common/turbo.js +1 -1
  6. package/lib/cjs/types/index.js +0 -1
  7. package/lib/cjs/utils/ao.js +2 -1
  8. package/lib/cjs/version.js +1 -1
  9. package/lib/esm/common/ant-versions.js +3 -2
  10. package/lib/esm/common/index.js +0 -2
  11. package/lib/esm/common/io.js +13 -9
  12. package/lib/esm/common/turbo.js +1 -1
  13. package/lib/esm/types/index.js +0 -1
  14. package/lib/esm/utils/ao.js +2 -1
  15. package/lib/esm/version.js +1 -1
  16. package/lib/types/common/ant-versions.d.ts +3 -5
  17. package/lib/types/common/index.d.ts +0 -1
  18. package/lib/types/types/index.d.ts +0 -1
  19. package/lib/types/version.d.ts +1 -1
  20. package/package.json +1 -1
  21. package/lib/cjs/common/wayfinder/gateways/trusted-gateways.js +0 -106
  22. package/lib/cjs/common/wayfinder/gateways.js +0 -86
  23. package/lib/cjs/common/wayfinder/index.js +0 -44
  24. package/lib/cjs/common/wayfinder/routers/priority.js +0 -29
  25. package/lib/cjs/common/wayfinder/routers/priority.test.js +0 -155
  26. package/lib/cjs/common/wayfinder/routers/random.js +0 -23
  27. package/lib/cjs/common/wayfinder/routers/random.test.js +0 -25
  28. package/lib/cjs/common/wayfinder/routers/simple-cache.js +0 -25
  29. package/lib/cjs/common/wayfinder/routers/simple-cache.test.js +0 -41
  30. package/lib/cjs/common/wayfinder/routers/static.js +0 -14
  31. package/lib/cjs/common/wayfinder/routers/static.test.js +0 -14
  32. package/lib/cjs/common/wayfinder/verification/data-root-verifier.js +0 -139
  33. package/lib/cjs/common/wayfinder/verification/hash-verifier.js +0 -50
  34. package/lib/cjs/common/wayfinder/wayfinder.js +0 -596
  35. package/lib/cjs/common/wayfinder/wayfinder.test.js +0 -500
  36. package/lib/cjs/types/wayfinder.js +0 -3
  37. package/lib/esm/common/wayfinder/gateways/trusted-gateways.js +0 -102
  38. package/lib/esm/common/wayfinder/gateways.js +0 -80
  39. package/lib/esm/common/wayfinder/index.js +0 -28
  40. package/lib/esm/common/wayfinder/routers/priority.js +0 -25
  41. package/lib/esm/common/wayfinder/routers/priority.test.js +0 -153
  42. package/lib/esm/common/wayfinder/routers/random.js +0 -19
  43. package/lib/esm/common/wayfinder/routers/random.test.js +0 -23
  44. package/lib/esm/common/wayfinder/routers/simple-cache.js +0 -21
  45. package/lib/esm/common/wayfinder/routers/simple-cache.test.js +0 -39
  46. package/lib/esm/common/wayfinder/routers/static.js +0 -10
  47. package/lib/esm/common/wayfinder/routers/static.test.js +0 -12
  48. package/lib/esm/common/wayfinder/verification/data-root-verifier.js +0 -130
  49. package/lib/esm/common/wayfinder/verification/hash-verifier.js +0 -46
  50. package/lib/esm/common/wayfinder/wayfinder.js +0 -584
  51. package/lib/esm/common/wayfinder/wayfinder.test.js +0 -495
  52. package/lib/esm/types/wayfinder.js +0 -2
  53. package/lib/types/common/wayfinder/gateways/trusted-gateways.d.ts +0 -51
  54. package/lib/types/common/wayfinder/gateways.d.ts +0 -53
  55. package/lib/types/common/wayfinder/index.d.ts +0 -23
  56. package/lib/types/common/wayfinder/routers/priority.d.ts +0 -29
  57. package/lib/types/common/wayfinder/routers/priority.test.d.ts +0 -1
  58. package/lib/types/common/wayfinder/routers/random.d.ts +0 -27
  59. package/lib/types/common/wayfinder/routers/random.test.d.ts +0 -1
  60. package/lib/types/common/wayfinder/routers/simple-cache.d.ts +0 -28
  61. package/lib/types/common/wayfinder/routers/simple-cache.test.d.ts +0 -1
  62. package/lib/types/common/wayfinder/routers/static.d.ts +0 -24
  63. package/lib/types/common/wayfinder/routers/static.test.d.ts +0 -1
  64. package/lib/types/common/wayfinder/verification/data-root-verifier.d.ts +0 -31
  65. package/lib/types/common/wayfinder/verification/hash-verifier.d.ts +0 -27
  66. package/lib/types/common/wayfinder/wayfinder.d.ts +0 -265
  67. package/lib/types/common/wayfinder/wayfinder.test.d.ts +0 -1
  68. package/lib/types/types/wayfinder.d.ts +0 -62
@@ -1,80 +0,0 @@
1
- export class NetworkGatewaysProvider {
2
- ario;
3
- sortBy;
4
- sortOrder;
5
- limit;
6
- filter;
7
- constructor({ ario, sortBy = 'operatorStake', sortOrder = 'desc', limit = 1000, filter = (g) => g.status === 'joined', }) {
8
- this.ario = ario;
9
- this.sortBy = sortBy;
10
- this.sortOrder = sortOrder;
11
- this.limit = limit;
12
- this.filter = filter;
13
- }
14
- async getGateways() {
15
- let cursor;
16
- let attempts = 0;
17
- const gateways = [];
18
- do {
19
- try {
20
- const { items: newGateways = [], nextCursor } = await this.ario.getGateways({
21
- limit: 1000,
22
- cursor,
23
- sortBy: this.sortBy,
24
- sortOrder: this.sortOrder,
25
- });
26
- gateways.push(...newGateways);
27
- cursor = nextCursor;
28
- attempts = 0; // reset attempts if we get a new cursor
29
- }
30
- catch (error) {
31
- console.error('Error fetching gateways', {
32
- cursor,
33
- attempts,
34
- error,
35
- });
36
- attempts++;
37
- }
38
- } while (cursor !== undefined && attempts < 3);
39
- // filter out any gateways that are not 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}`));
42
- }
43
- }
44
- export class StaticGatewaysProvider {
45
- gateways;
46
- constructor({ gateways }) {
47
- this.gateways = gateways.map((g) => new URL(g));
48
- }
49
- async getGateways() {
50
- return this.gateways;
51
- }
52
- }
53
- export class SimpleCacheGatewaysProvider {
54
- gatewaysProvider;
55
- ttlSeconds;
56
- lastUpdated;
57
- gatewaysCache;
58
- constructor({ gatewaysProvider, ttlSeconds = 5 * 60, // 5 minutes
59
- }) {
60
- this.gatewaysCache = [];
61
- this.gatewaysProvider = gatewaysProvider;
62
- this.ttlSeconds = ttlSeconds;
63
- }
64
- async getGateways() {
65
- const now = Date.now();
66
- if (this.gatewaysCache.length === 0 ||
67
- now - this.lastUpdated > this.ttlSeconds * 1000) {
68
- try {
69
- // preserve the cache if the fetch fails
70
- const allGateways = await this.gatewaysProvider.getGateways();
71
- this.gatewaysCache = allGateways;
72
- this.lastUpdated = now;
73
- }
74
- catch (error) {
75
- console.error('Error fetching gateways', error);
76
- }
77
- }
78
- return this.gatewaysCache;
79
- }
80
- }
@@ -1,28 +0,0 @@
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
- // routers
18
- export * from './routers/random.js';
19
- export * from './routers/priority.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,25 +0,0 @@
1
- import { randomInt } from '../../../utils/random.js';
2
- import { NetworkGatewaysProvider } from '../gateways.js';
3
- // TODO: one of N where N are in the last time window have met certain performance thresholds
4
- // TODO: look at bitorrent routing protocols for inspiration
5
- // TODO: router that looks at local stats/metrics and adjusts based on those
6
- export class PriorityGatewayRouter {
7
- name = 'priority';
8
- gatewaysProvider;
9
- constructor({ ario, sortBy, sortOrder, limit, }) {
10
- this.gatewaysProvider = new NetworkGatewaysProvider({
11
- ario,
12
- sortBy,
13
- sortOrder,
14
- limit,
15
- });
16
- }
17
- async getTargetGateway() {
18
- const gateways = await this.gatewaysProvider.getGateways();
19
- const targetGateway = gateways[randomInt(0, gateways.length)];
20
- if (targetGateway === undefined) {
21
- throw new Error('No target gateway found');
22
- }
23
- return targetGateway;
24
- }
25
- }
@@ -1,153 +0,0 @@
1
- import { strict as assert } from 'node:assert';
2
- import { describe, it } from 'node:test';
3
- import { PriorityGatewayRouter } from './priority.js';
4
- describe('PriorityRouter', () => {
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: 'gateway1.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: 'addr1',
62
- observerAddress: 'addr1',
63
- totalDelegatedStake: 2000,
64
- startTimestamp: 0,
65
- endTimestamp: 0,
66
- operatorStake: 2000,
67
- status: 'joined',
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
- },
88
- {
89
- settings: {
90
- fqdn: 'gateway2.net',
91
- port: 443,
92
- protocol: 'https',
93
- allowDelegatedStaking: false,
94
- delegateRewardShareRatio: 0.5,
95
- allowedDelegates: [],
96
- minDelegatedStake: 0,
97
- autoStake: false,
98
- properties: '',
99
- label: '',
100
- note: '',
101
- },
102
- gatewayAddress: 'addr2',
103
- observerAddress: 'addr2',
104
- totalDelegatedStake: 0,
105
- startTimestamp: 0,
106
- endTimestamp: 0,
107
- operatorStake: 0,
108
- status: 'leaving',
109
- weights: {
110
- normalizedCompositeWeight: 0.5,
111
- stakeWeight: 0.5,
112
- tenureWeight: 0.5,
113
- gatewayPerformanceRatio: 0.5,
114
- observerPerformanceRatio: 0.5,
115
- compositeWeight: 0.5,
116
- gatewayRewardRatioWeight: 0.5,
117
- observerRewardRatioWeight: 0.5,
118
- },
119
- stats: {
120
- passedConsecutiveEpochs: 10,
121
- failedConsecutiveEpochs: 5,
122
- totalEpochCount: 15,
123
- passedEpochCount: 10,
124
- failedEpochCount: 5,
125
- observedEpochCount: 15,
126
- prescribedEpochCount: 20,
127
- },
128
- },
129
- ];
130
- const mockArIOClient = {
131
- getGateways: async () => ({ items: mockGateways }),
132
- };
133
- it('should prioritize gateway with highest success rate when using successRate weight', async () => {
134
- const router = new PriorityGatewayRouter({
135
- ario: mockArIOClient,
136
- sortBy: 'operatorStake',
137
- sortOrder: 'desc',
138
- limit: 1,
139
- });
140
- const result = await router.getTargetGateway();
141
- assert.deepStrictEqual(result, new URL('http://gateway1.net'));
142
- });
143
- it('should prioritize gateway with lowest latency when using latency weight', async () => {
144
- const router = new PriorityGatewayRouter({
145
- ario: mockArIOClient,
146
- sortBy: 'operatorStake',
147
- sortOrder: 'desc',
148
- limit: 1,
149
- });
150
- const result = await router.getTargetGateway();
151
- assert.deepStrictEqual(result, new URL('http://gateway2.net'));
152
- });
153
- });
@@ -1,19 +0,0 @@
1
- import { randomInt } from '../../../utils/random.js';
2
- export class RandomGatewayRouter {
3
- name = 'random';
4
- gatewaysProvider;
5
- blocklist;
6
- constructor({ gatewaysProvider, blocklist = [], }) {
7
- this.gatewaysProvider = gatewaysProvider;
8
- this.blocklist = blocklist;
9
- }
10
- async getTargetGateway() {
11
- const allGateways = await this.gatewaysProvider.getGateways();
12
- const gateways = allGateways.filter((g) => !this.blocklist.includes(g.hostname));
13
- const targetGateway = gateways[randomInt(0, gateways.length)];
14
- if (targetGateway === undefined) {
15
- throw new Error('No target gateway found');
16
- }
17
- return targetGateway;
18
- }
19
- }
@@ -1,23 +0,0 @@
1
- import { strict as assert } from 'node:assert';
2
- import { describe, it } from 'node:test';
3
- import { RandomGatewayRouter } from './random.js';
4
- describe('RandomRouter', () => {
5
- const mockGateways = [
6
- new URL('https://gateway1.net'),
7
- new URL('https://gateway2.net'),
8
- new URL('https://gateway3.net'),
9
- ];
10
- const mockGatewaysProvider = {
11
- getGateways: async () => mockGateways,
12
- };
13
- it('should only return joined gateways', async () => {
14
- const router = new RandomGatewayRouter({
15
- gatewaysProvider: mockGatewaysProvider,
16
- });
17
- // random gateway should be one of the mock gateways
18
- for (let i = 0; i < 10; i++) {
19
- const result = await router.getTargetGateway();
20
- assert.ok(mockGateways.includes(result));
21
- }
22
- });
23
- });
@@ -1,21 +0,0 @@
1
- export class SimpleCacheRouter {
2
- name;
3
- lastUpdatedTimestamp;
4
- ttlSeconds;
5
- targetGateway;
6
- router;
7
- constructor({ router, ttlSeconds = 5 * 60, // 5 minutes
8
- }) {
9
- this.router = router;
10
- this.ttlSeconds = ttlSeconds;
11
- }
12
- async getTargetGateway() {
13
- if (this.targetGateway === undefined ||
14
- this.lastUpdatedTimestamp + this.ttlSeconds * 1000 < Date.now()) {
15
- this.targetGateway = await this.router.getTargetGateway();
16
- this.lastUpdatedTimestamp = Date.now();
17
- }
18
- return this.targetGateway;
19
- }
20
- }
21
- // TODO: a router that accepts ario and a router, and adds read through promise cache to ario.getGateways to avoid calling the ARIO contract on every request
@@ -1,39 +0,0 @@
1
- import { strict as assert } from 'node:assert';
2
- import { describe, it } from 'node:test';
3
- import { SimpleCacheRouter } from './simple-cache.js';
4
- describe('SimpleCacheRouter', () => {
5
- it('should cache gateway for TTL period even if underlying gateway changes', async () => {
6
- const gateway1 = new URL('https://gateway1.net');
7
- const gateway2 = new URL('https://gateway2.net');
8
- let currentGateway = gateway1;
9
- const mockRouter = {
10
- name: 'mock',
11
- getTargetGateway: async () => currentGateway,
12
- };
13
- const router = new SimpleCacheRouter({
14
- router: mockRouter,
15
- ttlSeconds: 300, // 5 minutes
16
- });
17
- // Get initial gateway which should be cached
18
- const initial = await router.getTargetGateway();
19
- assert.deepStrictEqual(initial, gateway1);
20
- // Change the underlying gateway
21
- currentGateway = gateway2;
22
- // Should still return cached gateway1 for multiple calls
23
- for (let i = 0; i < 5; i++) {
24
- const result = await router.getTargetGateway();
25
- assert.deepStrictEqual(result, gateway1);
26
- }
27
- // Advance time past TTL
28
- const originalNow = Date.now;
29
- try {
30
- Date.now = () => originalNow() + 300 * 1000 + 1;
31
- // Should now return the new gateway2
32
- const result = await router.getTargetGateway();
33
- assert.deepStrictEqual(result, gateway2);
34
- }
35
- finally {
36
- Date.now = originalNow;
37
- }
38
- });
39
- });
@@ -1,10 +0,0 @@
1
- export class StaticGatewayRouter {
2
- name = 'static';
3
- gateway;
4
- constructor({ gateway }) {
5
- this.gateway = new URL(gateway);
6
- }
7
- async getTargetGateway() {
8
- return this.gateway;
9
- }
10
- }
@@ -1,12 +0,0 @@
1
- import { strict as assert } from 'node:assert';
2
- import { describe, it } from 'node:test';
3
- import { StaticGatewayRouter } from './static.js';
4
- describe('StaticGatewayRouter', () => {
5
- it('should return the provided gateway', async () => {
6
- const router = new StaticGatewayRouter({
7
- gateway: 'http://test-gateway.net',
8
- });
9
- const result = await router.getTargetGateway();
10
- assert.deepStrictEqual(result, new URL('http://test-gateway.net'));
11
- });
12
- });
@@ -1,130 +0,0 @@
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
@@ -1,46 +0,0 @@
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
- }