This repository has been archived by the owner on Oct 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
observers.test.ts
379 lines (363 loc) · 12.2 KB
/
observers.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { createHash } from 'node:crypto';
import {
EPOCH_BLOCK_LENGTH,
GATEWAY_LEAVE_BLOCK_LENGTH,
INITIAL_EPOCH_DISTRIBUTION_DATA,
MAXIMUM_OBSERVERS_PER_EPOCH,
MIN_OPERATOR_STAKE,
TENURE_WEIGHT_PERIOD,
} from './constants';
import {
getEntropyHashForEpoch,
getEpochDataForHeight,
getPrescribedObserversForEpoch,
isGatewayEligibleForDistribution,
} from './observers';
import { stubbedGatewayData, stubbedGateways } from './tests/stubs';
import { BlockHeight, DeepReadonly, Gateway, Gateways } from './types';
describe('getPrescribedObserversForEpoch', () => {
beforeAll(() => {
// stub arweave crypto hash function
SmartWeave.arweave.crypto.hash = (
buffer: Buffer,
algorithm: string,
): Promise<Buffer> => {
const hash = createHash(algorithm);
hash.update(buffer);
return Promise.resolve(hash.digest());
};
// TODO: hard these values in the test based on the response from arweave.net for our test block heights
SmartWeave.safeArweaveGet = (): Promise<any> => {
return Promise.resolve({
indep_hash: 'test-indep-hash',
});
};
});
afterAll(() => {
// reset stubs
jest.resetAllMocks();
});
it(`should return the all eligible observers with proper weights if the total number is less than ${MAXIMUM_OBSERVERS_PER_EPOCH}`, async () => {
const epochStartHeight = 10;
const totalStake = 100;
const observers = await getPrescribedObserversForEpoch({
gateways: {
'test-observer-wallet-1': {
...stubbedGatewayData,
operatorStake: totalStake,
start: 0,
observerWallet: 'test-observer-wallet-1',
},
},
distributions: INITIAL_EPOCH_DISTRIBUTION_DATA,
epochStartHeight: new BlockHeight(epochStartHeight),
epochEndHeight: new BlockHeight(epochStartHeight + 10),
minOperatorStake: MIN_OPERATOR_STAKE,
});
expect(observers).toBeDefined();
const expectedStakeWeight = totalStake / MIN_OPERATOR_STAKE.valueOf();
const expectedTenureWeight = epochStartHeight / TENURE_WEIGHT_PERIOD;
const expectedCompositeWeight = expectedTenureWeight * expectedStakeWeight;
expect(observers).toEqual([
{
gatewayAddress: 'test-observer-wallet-1',
observerAddress: 'test-observer-wallet-1',
stake: totalStake,
start: 0,
stakeWeight: expectedStakeWeight,
tenureWeight: expectedTenureWeight,
gatewayRewardRatioWeight: 1,
observerRewardRatioWeight: 1,
compositeWeight: expectedCompositeWeight,
normalizedCompositeWeight: 1, // no other gateways
},
]);
});
it(`should return the correct number observers with proper weights if there are more than ${MAXIMUM_OBSERVERS_PER_EPOCH} gateways with composite scores greater than 0`, async () => {
const epochStartHeight = 10;
const extendedStubbedGateways = {
// initially spread so we clone
...stubbedGateways,
};
for (let i = 4; i < MAXIMUM_OBSERVERS_PER_EPOCH + 5; i++) {
extendedStubbedGateways[`test-observer-wallet-${i}`] = {
...stubbedGatewayData,
operatorStake: 100,
start: 0,
observerWallet: `test-observer-wallet-${i}`,
};
}
const eligibleGateways: DeepReadonly<Gateways> = extendedStubbedGateways;
const observers = await getPrescribedObserversForEpoch({
gateways: eligibleGateways,
distributions: INITIAL_EPOCH_DISTRIBUTION_DATA,
epochStartHeight: new BlockHeight(epochStartHeight),
epochEndHeight: new BlockHeight(epochStartHeight + 10),
minOperatorStake: MIN_OPERATOR_STAKE,
});
expect(observers).toBeDefined();
expect(observers.length).toBe(MAXIMUM_OBSERVERS_PER_EPOCH);
const expectedObserverWeights = [];
for (const gateway of Object.keys(eligibleGateways)) {
const expectedGatewayRewardRatioWeight = 1;
const expectedObserverRewardRatioWeight = 1;
const expectedStakeWeight =
eligibleGateways[gateway].operatorStake / MIN_OPERATOR_STAKE.valueOf();
const expectedTenureWeight =
(epochStartHeight - eligibleGateways[gateway].start) /
TENURE_WEIGHT_PERIOD;
const expectedCompositeWeight =
expectedTenureWeight * expectedStakeWeight;
expectedObserverWeights.push({
gatewayAddress: gateway,
observerAddress: eligibleGateways[gateway].observerWallet,
stake: eligibleGateways[gateway].operatorStake,
start: eligibleGateways[gateway].start,
stakeWeight: expectedStakeWeight,
tenureWeight: expectedTenureWeight,
gatewayRewardRatioWeight: expectedGatewayRewardRatioWeight,
observerRewardRatioWeight: expectedObserverRewardRatioWeight,
compositeWeight: expectedCompositeWeight,
normalizedCompositeWeight: 0, // set this after gateways have been selected
});
}
const totalCompositeWeight = expectedObserverWeights.reduce(
(acc, current) => (acc += current.compositeWeight),
0,
);
for (const observer of expectedObserverWeights) {
observer.normalizedCompositeWeight =
observer.compositeWeight / totalCompositeWeight;
}
// the observers returned should be a subset of the full observer weights
expect(expectedObserverWeights).toEqual(expect.arrayContaining(observers));
});
it('should not include any gateways that have a composite weight of 0', async () => {
const epochStartHeight = SmartWeave.block.height;
const extendedStubbedGateways: DeepReadonly<Gateways> = {
...stubbedGateways,
'test-observer-wallet-4': {
...stubbedGatewayData,
operatorStake: 400,
start: 4,
observerWallet: 'test-observer-wallet-4',
},
'test-observer-wallet-5': {
...stubbedGatewayData,
operatorStake: 500,
start: 5,
observerWallet: 'test-observer-wallet-5',
},
'test-observer-wallet-6': {
...stubbedGatewayData,
operatorStake: 600,
start: 6,
observerWallet: 'test-observer-wallet-6',
},
};
const observers = await getPrescribedObserversForEpoch({
gateways: extendedStubbedGateways,
distributions: INITIAL_EPOCH_DISTRIBUTION_DATA,
minOperatorStake: MIN_OPERATOR_STAKE,
epochStartHeight: new BlockHeight(epochStartHeight),
epochEndHeight: new BlockHeight(epochStartHeight + EPOCH_BLOCK_LENGTH),
});
// only include the gateways that do not have a zero composite weight based on their composite weight
expect(observers.map((o) => o.gatewayAddress)).toEqual(
expect.arrayContaining(['a-gateway', 'a-gateway-2', 'a-gateway-3']),
);
});
});
describe('isGatewayEligibleForDistribution', () => {
it.each([
[
'should be true if the gateway is joined, and started before the epoch start',
{
...stubbedGatewayData,
status: 'joined',
start: 0,
},
10,
Number.MAX_SAFE_INTEGER,
true,
],
[
'should be true if the gateway is joined, and started at the same block as the epoch start',
{
...stubbedGatewayData,
status: 'joined',
start: 10,
},
10,
Number.MAX_SAFE_INTEGER,
true,
],
[
'should be true if the gateway is leaving, but started before the epoch start and leaving after the end of the epoch',
{
...stubbedGatewayData,
status: 'leaving',
end: GATEWAY_LEAVE_BLOCK_LENGTH.plus(new BlockHeight(1)),
start: 0,
},
10,
GATEWAY_LEAVE_BLOCK_LENGTH.valueOf(),
true,
],
[
'should be true if the gateway is joined, and started before the epoch with large numbers',
{
...stubbedGatewayData,
start: Number.MAX_SAFE_INTEGER - 1,
},
Number.MAX_SAFE_INTEGER,
Number.MAX_SAFE_INTEGER,
true,
],
[
'should be false if gateway is undefined',
undefined,
10,
Number.MAX_SAFE_INTEGER,
false,
],
[
'should be false if gateway is joined but started after the epoch start',
{
...stubbedGatewayData,
status: 'joined',
start: 11,
},
10,
Number.MAX_SAFE_INTEGER,
false,
],
[
'should be false if gateway is leaving before the end of the epoch',
{
...stubbedGatewayData,
status: 'leaving',
start: 10,
end: GATEWAY_LEAVE_BLOCK_LENGTH.minus(new BlockHeight(1)),
},
10,
GATEWAY_LEAVE_BLOCK_LENGTH.valueOf(),
false,
],
[
'should be false if gateway is joined and started after the epoch start',
{
...stubbedGatewayData,
start: Number.MAX_SAFE_INTEGER,
},
Number.MAX_SAFE_INTEGER - 10,
Number.MAX_SAFE_INTEGER,
false,
],
])(
'%s',
(
_: string,
gateway: Gateway,
epochStartHeight: number,
epochEndHeight: number,
result: boolean,
) => {
expect(
isGatewayEligibleForDistribution({
gateway,
epochStartHeight: new BlockHeight(epochStartHeight),
epochEndHeight: new BlockHeight(epochEndHeight),
}),
).toBe(result);
},
);
});
describe('getEpochDataForHeight', () => {
it.each([
[1, 1, 1, 1, 1],
[19, 2, 100, 2, 101],
[34, 0, Number.MAX_SAFE_INTEGER, 0, Number.MAX_SAFE_INTEGER - 1],
[1340134, 1339961, 50, 1340111, 1340160],
])(
'should for current height of %d, zero block height of %d and epoch length of %d return the epoch start of %d and epoch end %d',
(
currentHeight,
zeroHeight,
epochLength: number,
expectedStart,
expectedEnd,
) => {
const {
epochStartHeight: returnedStartHeight,
epochEndHeight: returnedEndHeight,
} = getEpochDataForHeight({
currentBlockHeight: new BlockHeight(currentHeight),
epochZeroStartHeight: new BlockHeight(zeroHeight),
epochBlockLength: new BlockHeight(epochLength),
});
expect(returnedStartHeight.valueOf()).toBe(expectedStart);
expect(returnedEndHeight.valueOf()).toBe(expectedEnd);
},
);
it('should default the epoch block length if not provided', () => {
const { epochStartHeight, epochEndHeight } = getEpochDataForHeight({
currentBlockHeight: new BlockHeight(5),
epochZeroStartHeight: new BlockHeight(0),
});
expect(epochStartHeight.valueOf()).toBe(0);
expect(epochEndHeight.valueOf()).toBe(EPOCH_BLOCK_LENGTH - 1);
});
});
describe('getEntropyForEpoch', () => {
beforeAll(() => {
// stub arweave crypto hash function
SmartWeave.arweave.crypto.hash = (
buffer: Buffer,
algorithm: string,
): Promise<Buffer> => {
const hash = createHash(algorithm);
hash.update(buffer);
return Promise.resolve(hash.digest());
};
// TODO: hard these values in the test based on the response from arweave.net for our test block heights
SmartWeave.safeArweaveGet = (): Promise<any> => {
return Promise.resolve({
indep_hash: 'test-indep-hash',
});
};
});
afterAll(() => {
// reset stubs
jest.resetAllMocks();
});
it('should return the correct entropy for a given epoch', async () => {
// we create a hash of three blocks hash data as the entropy
const epochStartHeight = 0;
const expectedBuffer = Buffer.concat([
Buffer.from('test-indep-hash', 'base64url'), // hash from block 1
Buffer.from('test-indep-hash', 'base64url'), // hash from block 2
Buffer.from('test-indep-hash', 'base64url'), // hash from block 3
]);
// we call the smartweave hashing function
const expectedHash = await SmartWeave.arweave.crypto.hash(
expectedBuffer,
'SHA-256',
);
const entropy = await getEntropyHashForEpoch({
epochStartHeight: new BlockHeight(epochStartHeight),
});
expect(entropy.toString()).toBe(expectedHash.toString());
});
it('should throw an error if a block does not have indep_hash', async () => {
SmartWeave.safeArweaveGet = (): Promise<any> => {
return Promise.resolve({}); // no indep_hash
};
// we create a hash of three blocks hash data as the entropy
const error = await getEntropyHashForEpoch({
epochStartHeight: new BlockHeight(0),
}).catch((e) => e);
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe('Block 0 has no indep_hash');
});
});