@ar.io/sdk 3.11.0-alpha.7 → 3.11.0-alpha.8

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 (28) hide show
  1. package/bundles/web.bundle.min.js +119 -116
  2. package/lib/cjs/common/wayfinder/gateways/trusted-gateways.js +106 -0
  3. package/lib/cjs/common/wayfinder/index.js +6 -0
  4. package/lib/cjs/common/wayfinder/verification/data-root-verifier.js +139 -0
  5. package/lib/cjs/common/wayfinder/verification/hash-verifier.js +50 -0
  6. package/lib/cjs/common/wayfinder/wayfinder.js +407 -18
  7. package/lib/cjs/common/wayfinder/wayfinder.test.js +262 -3
  8. package/lib/cjs/types/wayfinder.js +1 -0
  9. package/lib/cjs/utils/hash.js +56 -0
  10. package/lib/cjs/version.js +1 -1
  11. package/lib/esm/common/wayfinder/gateways/trusted-gateways.js +102 -0
  12. package/lib/esm/common/wayfinder/index.js +6 -0
  13. package/lib/esm/common/wayfinder/verification/data-root-verifier.js +130 -0
  14. package/lib/esm/common/wayfinder/verification/hash-verifier.js +46 -0
  15. package/lib/esm/common/wayfinder/wayfinder.js +401 -18
  16. package/lib/esm/common/wayfinder/wayfinder.test.js +263 -4
  17. package/lib/esm/types/wayfinder.js +1 -0
  18. package/lib/esm/utils/hash.js +50 -0
  19. package/lib/esm/version.js +1 -1
  20. package/lib/types/common/wayfinder/gateways/trusted-gateways.d.ts +51 -0
  21. package/lib/types/common/wayfinder/index.d.ts +3 -0
  22. package/lib/types/common/wayfinder/verification/data-root-verifier.d.ts +31 -0
  23. package/lib/types/common/wayfinder/verification/hash-verifier.d.ts +27 -0
  24. package/lib/types/common/wayfinder/wayfinder.d.ts +148 -10
  25. package/lib/types/types/wayfinder.d.ts +43 -0
  26. package/lib/types/utils/hash.d.ts +4 -0
  27. package/lib/types/version.d.ts +1 -1
  28. package/package.json +1 -1
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TrustedGatewaysHashProvider = void 0;
4
+ const arioGatewayHeaders = {
5
+ digest: 'x-ar-io-digest',
6
+ verified: 'x-ar-io-verified',
7
+ txId: 'x-arns-resolved-tx-id',
8
+ processId: 'x-arns-resolved-process-id',
9
+ };
10
+ class TrustedGatewaysHashProvider {
11
+ gatewaysProvider;
12
+ constructor({ gatewaysProvider,
13
+ // TODO: add threshold for allowed hash difference (i.e. by count or ratio of total gateways checked)
14
+ }) {
15
+ this.gatewaysProvider = gatewaysProvider;
16
+ }
17
+ /**
18
+ * Gets the digest for a given txId from all trusted gateways and ensures they all match.
19
+ * @param txId - The txId to get the digest for.
20
+ * @returns The digest for the given txId.
21
+ */
22
+ async getHash({ txId, }) {
23
+ // get the hash from every gateway, and ensure they all match
24
+ const hashSet = new Set();
25
+ const hashResults = [];
26
+ const gateways = await this.gatewaysProvider.getGateways();
27
+ const hashes = await Promise.all(gateways.map(async (gateway) => {
28
+ const response = await fetch(`${gateway.toString()}${txId}`, {
29
+ method: 'HEAD',
30
+ redirect: 'follow',
31
+ });
32
+ if (!response.ok) {
33
+ // skip this gateway
34
+ return undefined;
35
+ }
36
+ const txIdHash = response.headers.get(arioGatewayHeaders.digest);
37
+ if (txIdHash === null || txIdHash === undefined) {
38
+ // skip this gateway
39
+ return undefined;
40
+ }
41
+ hashResults.push({
42
+ gateway: gateway.hostname,
43
+ txIdHash,
44
+ });
45
+ return txIdHash;
46
+ }));
47
+ for (const hash of hashes) {
48
+ if (hash !== undefined) {
49
+ hashSet.add(hash);
50
+ }
51
+ }
52
+ if (hashSet.size === 0) {
53
+ throw new Error(`No trusted gateways found for txId ${txId}`);
54
+ }
55
+ if (hashSet.size > 1) {
56
+ throw new Error(`Failed to get consistent hash from all trusted gateways. ${JSON.stringify(hashResults)}`);
57
+ }
58
+ return { hash: hashResults[0].txIdHash, algorithm: 'sha256' };
59
+ }
60
+ /**
61
+ * Get the data root for a given txId from all trusted gateways and ensure they all match.
62
+ * @param txId - The txId to get the data root for.
63
+ * @returns The data root for the given txId.
64
+ */
65
+ async getDataRoot({ txId }) {
66
+ const dataRootSet = new Set();
67
+ const dataRootResults = [];
68
+ const gateways = await this.gatewaysProvider.getGateways();
69
+ const dataRoots = await Promise.all(gateways.map(async (gateway) => {
70
+ const response = await fetch(`${gateway.toString()}tx/${txId}/data_root`);
71
+ if (!response.ok) {
72
+ // skip this gateway
73
+ return undefined;
74
+ }
75
+ const dataRoot = await response.text();
76
+ dataRootResults.push({
77
+ gateway: gateway.hostname,
78
+ dataRoot,
79
+ });
80
+ return dataRoot;
81
+ }));
82
+ for (const dataRoot of dataRoots) {
83
+ if (dataRoot !== undefined) {
84
+ dataRootSet.add(dataRoot);
85
+ }
86
+ }
87
+ if (dataRootSet.size > 1) {
88
+ throw new Error(`Failed to get consistent data root from all trusted gateways. ${JSON.stringify(dataRootResults)}`);
89
+ }
90
+ return dataRootSet.values().next().value;
91
+ }
92
+ }
93
+ exports.TrustedGatewaysHashProvider = TrustedGatewaysHashProvider;
94
+ // client could check hashes of data items, match expected hash
95
+ // if the gateway has the hash and they've verified it, you can trust the data item and offset
96
+ // you would be only trusting the gateway that it is a valid bundle
97
+ // you can request the offset from the gateway to verify the id
98
+ /**
99
+ * Note from @djwhitt
100
+ *
101
+ * Calculating data roots this way is fine, but it may not reproduce the original data root.
102
+ * We could also implement a data root verifier that pulls all the chunks, checks that they
103
+ * reproduce the expected data root, and then compares the concatenated chunk data to the
104
+ * original data retrieved. That would take a while, but it should be able to verify any L1
105
+ * data where we can find the chunks.
106
+ */
@@ -36,3 +36,9 @@ __exportStar(require("./routers/priority.js"), exports);
36
36
  __exportStar(require("./routers/static.js"), exports);
37
37
  // gateways providers
38
38
  __exportStar(require("./gateways.js"), exports);
39
+ // trusted gateways
40
+ __exportStar(require("./gateways/trusted-gateways.js"), exports);
41
+ // hash providers
42
+ __exportStar(require("./verification/data-root-verifier.js"), exports);
43
+ __exportStar(require("./verification/hash-verifier.js"), exports);
44
+ // TODO: signature verification
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DataRootVerifier = exports.convertReadableToDataRoot = void 0;
7
+ exports.convertBufferToDataRoot = convertBufferToDataRoot;
8
+ /**
9
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const arweave_1 = __importDefault(require("arweave"));
24
+ const merkle_js_1 = require("arweave/node/lib/merkle.js");
25
+ const node_stream_1 = require("node:stream");
26
+ const base64_js_1 = require("../../../utils/base64.js");
27
+ async function convertBufferToDataRoot({ buffer, }) {
28
+ const chunks = [];
29
+ let cursor = 0;
30
+ let offset = 0;
31
+ while (offset < buffer.byteLength) {
32
+ let chunkSize = Math.min(merkle_js_1.MAX_CHUNK_SIZE, buffer.byteLength - offset);
33
+ const remainder = buffer.byteLength - offset - chunkSize;
34
+ if (remainder > 0 && remainder < merkle_js_1.MIN_CHUNK_SIZE) {
35
+ chunkSize = Math.ceil((buffer.byteLength - offset) / 2);
36
+ }
37
+ // subarray does not exist on web Buffer type
38
+ const slice = buffer.subarray(offset, offset + chunkSize);
39
+ const hash = await crypto.subtle.digest('SHA-256', slice);
40
+ const hashArray = new Uint8Array(hash);
41
+ chunks.push({
42
+ dataHash: hashArray,
43
+ minByteRange: cursor,
44
+ maxByteRange: cursor + chunkSize,
45
+ });
46
+ cursor += chunkSize;
47
+ offset += chunkSize;
48
+ }
49
+ const leaves = await (0, merkle_js_1.generateLeaves)(chunks);
50
+ const result = await (0, merkle_js_1.buildLayers)(leaves);
51
+ return Buffer.from(result.id).toString('base64url');
52
+ }
53
+ const convertReadableToDataRoot = async ({ iterable, }) => {
54
+ const chunks = [];
55
+ let leftover = new Uint8Array(0);
56
+ let cursor = 0;
57
+ for await (const data of iterable) {
58
+ const inputChunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
59
+ const combined = new Uint8Array(leftover.length + inputChunk.length);
60
+ combined.set(leftover, 0);
61
+ combined.set(inputChunk, leftover.length);
62
+ let startIndex = 0;
63
+ while (combined.length - startIndex >= merkle_js_1.MAX_CHUNK_SIZE) {
64
+ let chunkSize = merkle_js_1.MAX_CHUNK_SIZE;
65
+ const remainderAfterThis = combined.length - startIndex - merkle_js_1.MAX_CHUNK_SIZE;
66
+ if (remainderAfterThis > 0 && remainderAfterThis < merkle_js_1.MIN_CHUNK_SIZE) {
67
+ chunkSize = Math.ceil((combined.length - startIndex) / 2);
68
+ }
69
+ const chunkData = combined.slice(startIndex, startIndex + chunkSize);
70
+ const dataHash = await arweave_1.default.crypto.hash(chunkData);
71
+ chunks.push({
72
+ dataHash,
73
+ minByteRange: cursor,
74
+ maxByteRange: cursor + chunkSize,
75
+ });
76
+ cursor += chunkSize;
77
+ startIndex += chunkSize;
78
+ }
79
+ leftover = combined.slice(startIndex);
80
+ }
81
+ if (leftover.length > 0) {
82
+ const dataHash = await arweave_1.default.crypto.hash(leftover);
83
+ chunks.push({
84
+ dataHash,
85
+ minByteRange: cursor,
86
+ maxByteRange: cursor + leftover.length,
87
+ });
88
+ }
89
+ const leaves = await (0, merkle_js_1.generateLeaves)(chunks);
90
+ const root = await (0, merkle_js_1.buildLayers)(leaves);
91
+ return (0, base64_js_1.toB64Url)(Buffer.from(root.id));
92
+ };
93
+ exports.convertReadableToDataRoot = convertReadableToDataRoot;
94
+ class DataRootVerifier {
95
+ trustedDataRootProvider;
96
+ constructor({ trustedDataRootProvider, }) {
97
+ this.trustedDataRootProvider = trustedDataRootProvider;
98
+ }
99
+ async verifyData({ data, txId, }) {
100
+ const trustedDataRootPromise = this.trustedDataRootProvider.getDataRoot({
101
+ txId,
102
+ });
103
+ let computedDataRoot;
104
+ if (Buffer.isBuffer(data)) {
105
+ computedDataRoot = await convertBufferToDataRoot({ buffer: data });
106
+ }
107
+ else if (data instanceof node_stream_1.Readable || data instanceof ReadableStream) {
108
+ computedDataRoot = await (0, exports.convertReadableToDataRoot)({ iterable: data });
109
+ }
110
+ if (computedDataRoot === undefined) {
111
+ throw new Error('Data root could not be computed');
112
+ }
113
+ const trustedDataRoot = await trustedDataRootPromise;
114
+ if (computedDataRoot !== trustedDataRoot) {
115
+ throw new Error('Data root does not match', {
116
+ cause: { computedDataRoot, trustedDataRoot },
117
+ });
118
+ }
119
+ }
120
+ }
121
+ exports.DataRootVerifier = DataRootVerifier;
122
+ // some data item options
123
+ // compute and verify data root, use offsets from server and verify the signature that the data item at the offset matches the signature
124
+ // does not give you assurance of valid bundle, but gives verification that the data item itself is valid
125
+ // reading from offsets is the only way for the client to compute and verify the signature
126
+ /**
127
+ * - when you get a signature of a data item, you can only verify the owner
128
+ * - you still need to verify it's going back to the bundle, unpack it, and verify the data item exists at the offset
129
+ * - 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
130
+ * - 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
131
+ *
132
+ * Composite verifier - you'll want to be very efficient with streams
133
+ * - hash verifier
134
+ * - parent chunks verifier --> for any range of data within a single transaction, tell me that it's correct
135
+ * - signature verifier
136
+ * - offset verifier
137
+ * - data item verifier
138
+ */
139
+ // introduce a composite verifier that determines where/how to lookup the hash
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HashVerifier = void 0;
4
+ /**
5
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ const node_stream_1 = require("node:stream");
20
+ const hash_js_1 = require("../../../utils/hash.js");
21
+ class HashVerifier {
22
+ trustedHashProvider;
23
+ constructor({ trustedHashProvider, }) {
24
+ this.trustedHashProvider = trustedHashProvider;
25
+ }
26
+ async verifyData({ data, txId, }) {
27
+ const hashPromise = this.trustedHashProvider.getHash({ txId });
28
+ let computedHash;
29
+ if (Buffer.isBuffer(data)) {
30
+ computedHash = (0, hash_js_1.hashBufferToB64Url)(data);
31
+ }
32
+ else if (data instanceof node_stream_1.Readable) {
33
+ computedHash = await (0, hash_js_1.hashReadableToB64Url)(data);
34
+ }
35
+ else if (data instanceof ReadableStream) {
36
+ computedHash = await (0, hash_js_1.hashReadableStreamToB64Url)(data);
37
+ }
38
+ // await on the hash promise and compare to get a little concurrency when computing hashes over larger data
39
+ const { hash } = await hashPromise;
40
+ if (computedHash === undefined) {
41
+ throw new Error('Hash could not be computed');
42
+ }
43
+ if (computedHash !== hash) {
44
+ throw new Error('Hash does not match', {
45
+ cause: { computedHash, trustedHash: hash },
46
+ });
47
+ }
48
+ }
49
+ }
50
+ exports.HashVerifier = HashVerifier;