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.ts
291 lines (272 loc) · 10.2 KB
/
observers.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
import {
EPOCH_BLOCK_LENGTH,
EPOCH_DISTRIBUTION_DELAY,
MAXIMUM_OBSERVERS_PER_EPOCH,
MAX_TENURE_WEIGHT,
OBSERVERS_SAMPLED_BLOCKS_COUNT,
OBSERVERS_SAMPLED_BLOCKS_OFFSET,
TENURE_WEIGHT_PERIOD,
} from './constants';
import {
BlockHeight,
DeepReadonly,
EpochDistributionData,
Gateway,
Gateways,
WalletAddress,
WeightedObserver,
mIOToken,
} from './types';
export function getEpochDataForHeight({
currentBlockHeight,
epochBlockLength = new BlockHeight(EPOCH_BLOCK_LENGTH),
epochZeroStartHeight,
}: {
currentBlockHeight: BlockHeight;
epochBlockLength?: BlockHeight;
epochZeroStartHeight: BlockHeight;
}): {
epochStartHeight: BlockHeight;
epochEndHeight: BlockHeight;
epochDistributionHeight: BlockHeight;
epochPeriod: BlockHeight;
} {
const epochIndexForCurrentBlockHeight = Math.floor(
Math.max(
0,
(currentBlockHeight.valueOf() - epochZeroStartHeight.valueOf()) /
epochBlockLength.valueOf(),
),
);
const epochStartHeight =
epochZeroStartHeight.valueOf() +
epochBlockLength.valueOf() * epochIndexForCurrentBlockHeight;
const epochEndHeight = epochStartHeight + epochBlockLength.valueOf() - 1;
const epochDistributionHeight = epochEndHeight + EPOCH_DISTRIBUTION_DELAY;
return {
epochStartHeight: new BlockHeight(epochStartHeight),
epochEndHeight: new BlockHeight(epochEndHeight),
epochDistributionHeight: new BlockHeight(epochDistributionHeight),
epochPeriod: new BlockHeight(epochIndexForCurrentBlockHeight),
};
}
// TODO: can we confidently us buffers here in non-node environments?
export async function getEntropyHashForEpoch({
epochStartHeight,
}: {
epochStartHeight: BlockHeight;
}): Promise<Buffer> {
// used as we don't have access to Hash object in smartweave executions, so we concat our buffer and hash it at the end
let bufferHash: Buffer = Buffer.from('');
// We hash multiple previous block hashes to reduce the chance that someone will
// influence the value produced by grinding with excessive hash power.
for (let i = 0; i < OBSERVERS_SAMPLED_BLOCKS_COUNT; i++) {
const blockHeight = Math.max(
0,
epochStartHeight.valueOf() - OBSERVERS_SAMPLED_BLOCKS_OFFSET - i,
);
const path = `/block/height/${blockHeight}`;
const data = await SmartWeave.safeArweaveGet(path);
const indep_hash = data.indep_hash;
// TODO: add regex check on the indep_hash
if (!indep_hash) {
throw new ContractError(
`Block ${blockHeight.valueOf()} has no indep_hash`,
);
}
bufferHash = Buffer.concat([
bufferHash,
Buffer.from(indep_hash, 'base64url'),
]);
}
return SmartWeave.arweave.crypto.hash(bufferHash, 'SHA-256');
}
export function isGatewayLeaving({
gateway,
currentBlockHeight,
}: {
gateway: DeepReadonly<Gateway>;
currentBlockHeight: BlockHeight;
}): boolean {
return (
gateway.status === 'leaving' && gateway.end <= currentBlockHeight.valueOf()
);
}
export function isGatewayEligibleForDistribution({
epochStartHeight,
epochEndHeight,
gateway,
}: {
epochStartHeight: BlockHeight;
epochEndHeight: BlockHeight;
gateway: DeepReadonly<Gateway> | undefined;
}): boolean {
if (!gateway) return false;
// gateway must have joined before the epoch started, as it affects weighting for distributions
const didStartBeforeEpoch = gateway.start <= epochStartHeight.valueOf();
// gateway must not be leaving before the end of the epoch - TODO: confirm this
const didNotLeaveDuringEpoch = !isGatewayLeaving({
gateway,
currentBlockHeight: epochEndHeight,
});
return didStartBeforeEpoch && didNotLeaveDuringEpoch;
}
export function getEligibleGatewaysForEpoch({
epochStartHeight,
epochEndHeight,
gateways,
}: {
epochStartHeight: BlockHeight;
epochEndHeight: BlockHeight;
gateways: DeepReadonly<Gateways>;
}): Gateways {
const eligibleGateways: Gateways = {};
for (const [address, gateway] of Object.entries(gateways)) {
if (
isGatewayEligibleForDistribution({
epochStartHeight,
epochEndHeight,
gateway,
})
) {
eligibleGateways[address] = gateway;
}
}
return eligibleGateways;
}
export function getObserverWeightsForEpoch({
gateways,
epochStartHeight,
minOperatorStake,
}: {
gateways: DeepReadonly<Gateways>;
epochStartHeight: BlockHeight;
minOperatorStake: mIOToken;
}): WeightedObserver[] {
const weightedObservers: WeightedObserver[] = [];
let totalCompositeWeight = 0;
// Get all eligible observers and assign weights
for (const [address, gateway] of Object.entries(gateways)) {
const stake = new mIOToken(
gateway.operatorStake + gateway.totalDelegatedStake,
); // e.g. 100 - no cap to this
const stakeWeightRatio = stake.valueOf() / minOperatorStake.valueOf(); // this is always greater than 1 as the minOperatorStake is always less than the stake
// the percentage of the epoch the gateway was joined for before this epoch, if the gateway starts in the future this will be 0
const gatewayStart = new BlockHeight(gateway.start);
const totalBlocksForGateway = epochStartHeight.isGreaterThanOrEqualTo(
gatewayStart,
)
? epochStartHeight.minus(gatewayStart).valueOf()
: -1;
// TODO: should we increment by one here or are observers that join at the epoch start not eligible to be selected as an observer
const calculatedTenureWeightForGateway =
totalBlocksForGateway < 0
? 0
: totalBlocksForGateway
? totalBlocksForGateway / TENURE_WEIGHT_PERIOD
: 1 / TENURE_WEIGHT_PERIOD;
// max of 4, which implies after 2 years, you are considered a mature gateway and this number stops increasing
const gatewayTenureWeight = Math.min(
calculatedTenureWeightForGateway,
MAX_TENURE_WEIGHT,
);
// the percentage of epochs participated in that the gateway passed
const totalEpochsGatewayPassed = gateway.stats.passedEpochCount || 0;
const totalEpochsParticipatedIn =
gateway.stats.totalEpochParticipationCount || 0;
// default to 1 for gateways that have not participated in a full epoch
const gatewayRewardRatioWeight =
(1 + totalEpochsGatewayPassed) / (1 + totalEpochsParticipatedIn);
// the percentage of epochs the observer was prescribed and submitted reports for
const totalEpochsPrescribed = gateway.stats.totalEpochsPrescribedCount || 0;
const totalEpochsSubmitted = gateway.stats.submittedEpochCount || 0;
// defaults to one again if either are 0, encouraging new gateways to join and observe
const observerRewardRatioWeight =
(1 + totalEpochsSubmitted) / (1 + totalEpochsPrescribed);
// calculate composite weight based on sub weights
const compositeWeight =
stakeWeightRatio *
gatewayTenureWeight *
gatewayRewardRatioWeight *
observerRewardRatioWeight;
weightedObservers.push({
gatewayAddress: address,
observerAddress: gateway.observerWallet,
stake: stake.valueOf(),
start: gateway.start,
stakeWeight: stakeWeightRatio,
tenureWeight: gatewayTenureWeight,
gatewayRewardRatioWeight,
observerRewardRatioWeight,
compositeWeight,
normalizedCompositeWeight: undefined, // set later once we have the total composite weight
});
// total weight for all eligible gateways
totalCompositeWeight += compositeWeight;
}
// calculate the normalized composite weight for each observer - do not default to one as these are dependent on the total weights of all observers
for (const weightedObserver of weightedObservers) {
weightedObserver.normalizedCompositeWeight = totalCompositeWeight
? weightedObserver.compositeWeight / totalCompositeWeight
: 0;
}
return weightedObservers;
}
export async function getPrescribedObserversForEpoch({
gateways,
epochStartHeight,
epochEndHeight,
minOperatorStake,
}: {
gateways: DeepReadonly<Gateways>;
distributions: DeepReadonly<EpochDistributionData>;
epochStartHeight: BlockHeight;
epochEndHeight: BlockHeight;
minOperatorStake: mIOToken;
}): Promise<WeightedObserver[]> {
const eligibleGateways = getEligibleGatewaysForEpoch({
epochStartHeight,
epochEndHeight,
gateways,
});
const weightedObservers = getObserverWeightsForEpoch({
gateways: eligibleGateways,
epochStartHeight,
minOperatorStake,
// filter out any that could have a normalized composite weight of 0 to avoid infinite loops when randomly selecting prescribed observers below
}).filter((observer) => observer.normalizedCompositeWeight > 0); // TODO: this could be some required minimum weight
// return all the observers if there are fewer than the number of observers per epoch
if (MAXIMUM_OBSERVERS_PER_EPOCH >= weightedObservers.length) {
return weightedObservers;
}
// deterministic way to get observers per epoch based on the epochs end height
const blockHeightEntropyHash = await getEntropyHashForEpoch({
epochStartHeight,
});
// note: this should always result to MAXIMUM_OBSERVERS_PER_EPOCH
const prescribedObserversAddresses: Set<WalletAddress> = new Set();
let hash = blockHeightEntropyHash; // our starting hash
while (prescribedObserversAddresses.size < MAXIMUM_OBSERVERS_PER_EPOCH) {
const random = hash.readUInt32BE(0) / 0xffffffff; // Convert hash to a value between 0 and 1
let cumulativeNormalizedCompositeWeight = 0;
for (const observer of weightedObservers) {
// skip observers that have already been prescribed
if (prescribedObserversAddresses.has(observer.gatewayAddress)) continue;
// add the observers normalized composite weight to the cumulative weight
cumulativeNormalizedCompositeWeight += observer.normalizedCompositeWeight;
// if the random value is less than the cumulative weight, we have found our observer
if (random <= cumulativeNormalizedCompositeWeight) {
prescribedObserversAddresses.add(observer.gatewayAddress);
break;
}
// Compute the next hash for the next iteration
hash = await SmartWeave.arweave.crypto.hash(hash, 'SHA-256');
}
}
const prescribedObservers: WeightedObserver[] = weightedObservers.filter(
(observer) => prescribedObserversAddresses.has(observer.gatewayAddress),
);
return prescribedObservers.sort(
(a, b) => a.normalizedCompositeWeight - b.normalizedCompositeWeight,
);
}