@ar.io/sdk 3.11.0-alpha.6 → 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.
- package/bundles/web.bundle.min.js +119 -116
- package/lib/cjs/common/io.js +8 -3
- package/lib/cjs/common/wayfinder/gateways/trusted-gateways.js +106 -0
- package/lib/cjs/common/wayfinder/gateways.js +19 -8
- package/lib/cjs/common/wayfinder/index.js +7 -1
- package/lib/cjs/common/wayfinder/routers/priority.js +11 -20
- package/lib/cjs/common/wayfinder/routers/priority.test.js +5 -5
- package/lib/cjs/common/wayfinder/routers/random.js +2 -2
- package/lib/cjs/common/wayfinder/routers/random.test.js +5 -84
- package/lib/cjs/common/wayfinder/routers/{fixed.js → static.js} +5 -5
- package/lib/cjs/common/wayfinder/routers/{fixed.test.js → static.test.js} +4 -4
- package/lib/cjs/common/wayfinder/verification/data-root-verifier.js +139 -0
- package/lib/cjs/common/wayfinder/verification/hash-verifier.js +50 -0
- package/lib/cjs/common/wayfinder/wayfinder.js +408 -19
- package/lib/cjs/common/wayfinder/wayfinder.test.js +296 -49
- package/lib/cjs/types/wayfinder.js +1 -0
- package/lib/cjs/utils/arweave.js +1 -1
- package/lib/cjs/utils/hash.js +56 -0
- package/lib/cjs/version.js +1 -1
- package/lib/esm/common/io.js +8 -3
- package/lib/esm/common/wayfinder/gateways/trusted-gateways.js +102 -0
- package/lib/esm/common/wayfinder/gateways.js +17 -6
- package/lib/esm/common/wayfinder/index.js +7 -1
- package/lib/esm/common/wayfinder/routers/priority.js +11 -20
- package/lib/esm/common/wayfinder/routers/priority.test.js +5 -5
- package/lib/esm/common/wayfinder/routers/random.js +2 -2
- package/lib/esm/common/wayfinder/routers/random.test.js +5 -84
- package/lib/esm/common/wayfinder/routers/{fixed.js → static.js} +3 -3
- package/lib/esm/common/wayfinder/routers/{fixed.test.js → static.test.js} +4 -4
- package/lib/esm/common/wayfinder/verification/data-root-verifier.js +130 -0
- package/lib/esm/common/wayfinder/verification/hash-verifier.js +46 -0
- package/lib/esm/common/wayfinder/wayfinder.js +402 -19
- package/lib/esm/common/wayfinder/wayfinder.test.js +297 -50
- package/lib/esm/types/wayfinder.js +1 -0
- package/lib/esm/utils/arweave.js +1 -1
- package/lib/esm/utils/hash.js +50 -0
- package/lib/esm/version.js +1 -1
- package/lib/types/common/wayfinder/gateways/trusted-gateways.d.ts +51 -0
- package/lib/types/common/wayfinder/gateways.d.ts +16 -7
- package/lib/types/common/wayfinder/index.d.ts +4 -1
- package/lib/types/common/wayfinder/routers/priority.d.ts +8 -12
- package/lib/types/common/wayfinder/routers/{fixed.d.ts → static.d.ts} +3 -3
- package/lib/types/common/wayfinder/verification/data-root-verifier.d.ts +31 -0
- package/lib/types/common/wayfinder/verification/hash-verifier.d.ts +27 -0
- package/lib/types/common/wayfinder/wayfinder.d.ts +148 -10
- package/lib/types/types/wayfinder.d.ts +43 -0
- package/lib/types/utils/hash.d.ts +4 -0
- package/lib/types/version.d.ts +1 -1
- package/package.json +1 -1
- /package/lib/types/common/wayfinder/routers/{fixed.test.d.ts → static.test.d.ts} +0 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const arioGatewayHeaders = {
|
|
2
|
+
digest: 'x-ar-io-digest',
|
|
3
|
+
verified: 'x-ar-io-verified',
|
|
4
|
+
txId: 'x-arns-resolved-tx-id',
|
|
5
|
+
processId: 'x-arns-resolved-process-id',
|
|
6
|
+
};
|
|
7
|
+
export class TrustedGatewaysHashProvider {
|
|
8
|
+
gatewaysProvider;
|
|
9
|
+
constructor({ gatewaysProvider,
|
|
10
|
+
// TODO: add threshold for allowed hash difference (i.e. by count or ratio of total gateways checked)
|
|
11
|
+
}) {
|
|
12
|
+
this.gatewaysProvider = gatewaysProvider;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Gets the digest for a given txId from all trusted gateways and ensures they all match.
|
|
16
|
+
* @param txId - The txId to get the digest for.
|
|
17
|
+
* @returns The digest for the given txId.
|
|
18
|
+
*/
|
|
19
|
+
async getHash({ txId, }) {
|
|
20
|
+
// get the hash from every gateway, and ensure they all match
|
|
21
|
+
const hashSet = new Set();
|
|
22
|
+
const hashResults = [];
|
|
23
|
+
const gateways = await this.gatewaysProvider.getGateways();
|
|
24
|
+
const hashes = await Promise.all(gateways.map(async (gateway) => {
|
|
25
|
+
const response = await fetch(`${gateway.toString()}${txId}`, {
|
|
26
|
+
method: 'HEAD',
|
|
27
|
+
redirect: 'follow',
|
|
28
|
+
});
|
|
29
|
+
if (!response.ok) {
|
|
30
|
+
// skip this gateway
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
const txIdHash = response.headers.get(arioGatewayHeaders.digest);
|
|
34
|
+
if (txIdHash === null || txIdHash === undefined) {
|
|
35
|
+
// skip this gateway
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
hashResults.push({
|
|
39
|
+
gateway: gateway.hostname,
|
|
40
|
+
txIdHash,
|
|
41
|
+
});
|
|
42
|
+
return txIdHash;
|
|
43
|
+
}));
|
|
44
|
+
for (const hash of hashes) {
|
|
45
|
+
if (hash !== undefined) {
|
|
46
|
+
hashSet.add(hash);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (hashSet.size === 0) {
|
|
50
|
+
throw new Error(`No trusted gateways found for txId ${txId}`);
|
|
51
|
+
}
|
|
52
|
+
if (hashSet.size > 1) {
|
|
53
|
+
throw new Error(`Failed to get consistent hash from all trusted gateways. ${JSON.stringify(hashResults)}`);
|
|
54
|
+
}
|
|
55
|
+
return { hash: hashResults[0].txIdHash, algorithm: 'sha256' };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Get the data root for a given txId from all trusted gateways and ensure they all match.
|
|
59
|
+
* @param txId - The txId to get the data root for.
|
|
60
|
+
* @returns The data root for the given txId.
|
|
61
|
+
*/
|
|
62
|
+
async getDataRoot({ txId }) {
|
|
63
|
+
const dataRootSet = new Set();
|
|
64
|
+
const dataRootResults = [];
|
|
65
|
+
const gateways = await this.gatewaysProvider.getGateways();
|
|
66
|
+
const dataRoots = await Promise.all(gateways.map(async (gateway) => {
|
|
67
|
+
const response = await fetch(`${gateway.toString()}tx/${txId}/data_root`);
|
|
68
|
+
if (!response.ok) {
|
|
69
|
+
// skip this gateway
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
const dataRoot = await response.text();
|
|
73
|
+
dataRootResults.push({
|
|
74
|
+
gateway: gateway.hostname,
|
|
75
|
+
dataRoot,
|
|
76
|
+
});
|
|
77
|
+
return dataRoot;
|
|
78
|
+
}));
|
|
79
|
+
for (const dataRoot of dataRoots) {
|
|
80
|
+
if (dataRoot !== undefined) {
|
|
81
|
+
dataRootSet.add(dataRoot);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (dataRootSet.size > 1) {
|
|
85
|
+
throw new Error(`Failed to get consistent data root from all trusted gateways. ${JSON.stringify(dataRootResults)}`);
|
|
86
|
+
}
|
|
87
|
+
return dataRootSet.values().next().value;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// client could check hashes of data items, match expected hash
|
|
91
|
+
// if the gateway has the hash and they've verified it, you can trust the data item and offset
|
|
92
|
+
// you would be only trusting the gateway that it is a valid bundle
|
|
93
|
+
// you can request the offset from the gateway to verify the id
|
|
94
|
+
/**
|
|
95
|
+
* Note from @djwhitt
|
|
96
|
+
*
|
|
97
|
+
* Calculating data roots this way is fine, but it may not reproduce the original data root.
|
|
98
|
+
* We could also implement a data root verifier that pulls all the chunks, checks that they
|
|
99
|
+
* reproduce the expected data root, and then compares the concatenated chunk data to the
|
|
100
|
+
* original data retrieved. That would take a while, but it should be able to verify any L1
|
|
101
|
+
* data where we can find the chunks.
|
|
102
|
+
*/
|
|
@@ -1,7 +1,15 @@
|
|
|
1
|
-
export class
|
|
1
|
+
export class NetworkGatewaysProvider {
|
|
2
2
|
ario;
|
|
3
|
-
|
|
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
|
-
|
|
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
|
|
71
|
+
this.gatewaysCache = allGateways;
|
|
61
72
|
this.lastUpdated = now;
|
|
62
73
|
}
|
|
63
74
|
catch (error) {
|
|
@@ -17,6 +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/
|
|
20
|
+
export * from './routers/static.js';
|
|
21
21
|
// gateways providers
|
|
22
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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
|
21
|
-
const
|
|
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
|
|
23
|
+
return targetGateway;
|
|
33
24
|
}
|
|
34
25
|
}
|
|
@@ -127,13 +127,13 @@ describe('PriorityRouter', () => {
|
|
|
127
127
|
},
|
|
128
128
|
},
|
|
129
129
|
];
|
|
130
|
-
const
|
|
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
|
-
|
|
136
|
-
sortBy: '
|
|
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
|
-
|
|
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) =>
|
|
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
|
|
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
|
-
|
|
8
|
-
|
|
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
|
-
//
|
|
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.
|
|
20
|
+
assert.ok(mockGateways.includes(result));
|
|
100
21
|
}
|
|
101
22
|
});
|
|
102
23
|
});
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export class
|
|
2
|
-
name = '
|
|
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 {
|
|
4
|
-
describe('
|
|
3
|
+
import { StaticGatewayRouter } from './static.js';
|
|
4
|
+
describe('StaticGatewayRouter', () => {
|
|
5
5
|
it('should return the provided gateway', async () => {
|
|
6
|
-
const router = new
|
|
7
|
-
gateway:
|
|
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
|
+
}
|