-
Notifications
You must be signed in to change notification settings - Fork 458
/
method.ts
186 lines (164 loc) · 6.18 KB
/
method.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
/*
* Copyright © 2021 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { math } from '@liskhq/lisk-utils';
import { ImmutableMethodContext, MethodContext } from '../../state_machine';
import { BaseMethod } from '../base_method';
import { EMPTY_KEY } from './constants';
import { GenesisDataStore } from './stores/genesis';
import { StakerStore } from './stores/staker';
import { ModuleConfig, StakerData, TokenMethod } from './types';
import { ValidatorAccount, ValidatorStore } from './stores/validator';
import { NameStore } from './stores/name';
import { isUsername } from './utils';
import { InternalMethod } from './internal_method';
import { EligibleValidatorsStore } from './stores/eligible_validators';
export class PoSMethod extends BaseMethod {
private _config!: ModuleConfig;
private _moduleName!: string;
private _tokenMethod!: TokenMethod;
private _internalMethod!: InternalMethod;
public init(
moduleName: string,
config: ModuleConfig,
internalMethod: InternalMethod,
tokenMethod: TokenMethod,
) {
this._moduleName = moduleName;
this._config = config;
this._tokenMethod = tokenMethod;
this._internalMethod = internalMethod;
}
public async isNameAvailable(
methodContext: ImmutableMethodContext,
name: string,
): Promise<boolean> {
const nameSubStore = this.stores.get(NameStore);
if (name.length > this._config.maxLengthName || name.length < 1 || !isUsername(name)) {
return false;
}
const isRegistered = await nameSubStore.has(methodContext, Buffer.from(name));
if (isRegistered) {
return false;
}
return true;
}
public async getStaker(
methodContext: ImmutableMethodContext,
address: Buffer,
): Promise<StakerData> {
const stakerSubStore = this.stores.get(StakerStore);
const stakerData = await stakerSubStore.get(methodContext, address);
return stakerData;
}
public async getValidator(
methodContext: ImmutableMethodContext,
address: Buffer,
): Promise<ValidatorAccount> {
const validatorSubStore = this.stores.get(ValidatorStore);
const validator = await validatorSubStore.get(methodContext, address);
return validator;
}
public getRoundLength(_methodContext: ImmutableMethodContext): number {
return this._config.roundLength;
}
public getNumberOfActiveValidators(_methodContext: ImmutableMethodContext): number {
return this._config.numberActiveValidators;
}
public async updateSharedRewards(
context: MethodContext,
generatorAddress: Buffer,
tokenID: Buffer,
reward: bigint,
): Promise<void> {
const validatorStore = this.stores.get(ValidatorStore);
const validator = await validatorStore.get(context, generatorAddress);
if (validator.totalStake === BigInt(0)) {
return;
}
const { q96 } = math;
const rewardQ = q96(reward);
const commissionQ = q96(BigInt(validator.commission));
const rewardFractionQ = q96(BigInt(1)).sub(commissionQ.div(q96(BigInt(10000))));
const selfStakeQ = q96(validator.selfStake);
const totalStakesQ = q96(validator.totalStake);
const matchingCoefficientIndex = validator.sharingCoefficients.findIndex(coefficient =>
coefficient.tokenID.equals(tokenID),
);
const index =
matchingCoefficientIndex > -1
? matchingCoefficientIndex
: validator.sharingCoefficients.length;
if (matchingCoefficientIndex < 0) {
validator.sharingCoefficients[index] = { tokenID, coefficient: q96(BigInt(0)).toBuffer() };
}
const oldSharingCoefficient = q96(validator.sharingCoefficients[index].coefficient);
const sharingCoefficientIncrease = rewardQ.muldiv(rewardFractionQ, totalStakesQ);
const sharedRewards = sharingCoefficientIncrease.mul(totalStakesQ.sub(selfStakeQ)).ceil();
// it should not lock more than the original reward. This might happen because of ceil above
const cappedSharedRewards = sharedRewards > reward ? reward : sharedRewards;
await this._tokenMethod.lock(
context,
generatorAddress,
this._moduleName,
tokenID,
cappedSharedRewards,
);
const newSharingCoefficient = oldSharingCoefficient.add(sharingCoefficientIncrease);
validator.sharingCoefficients[index].coefficient = newSharingCoefficient.toBuffer();
validator.sharingCoefficients.sort((a, b) => a.tokenID.compare(b.tokenID));
await validatorStore.set(context, generatorAddress, validator);
}
public async getRoundNumberFromHeight(
methodContext: ImmutableMethodContext,
height: number,
): Promise<number> {
const { height: genesisHeight } = await this.stores
.get(GenesisDataStore)
.get(methodContext, EMPTY_KEY);
return Math.ceil((height - genesisHeight) / this._config.roundLength);
}
public async isEndOfRound(
methodContext: ImmutableMethodContext,
height: number,
): Promise<boolean> {
const { height: genesisHeight } = await this.stores
.get(GenesisDataStore)
.get(methodContext, EMPTY_KEY);
return (height - genesisHeight) % this._config.roundLength === 0;
}
public async unbanValidator(methodContext: MethodContext, address: Buffer): Promise<void> {
const validatorSubStore = this.stores.get(ValidatorStore);
const validator = await validatorSubStore.get(methodContext, address);
if (!validator.isBanned) {
throw new Error('The specified validator is not banned.');
}
if (validator.reportMisbehaviorHeights.length >= this._config.reportMisbehaviorLimitBanned) {
throw new Error(
'Validator exceeded the maximum allowed number of misbehaviors and is permanently banned.',
);
}
validator.isBanned = false;
await validatorSubStore.set(methodContext, address, validator);
// previous weight is always 0 because the validator was banned previously
await this.stores
.get(EligibleValidatorsStore)
.update(methodContext, address, BigInt(0), validator);
}
public async getLockedStakedAmount(
ctx: ImmutableMethodContext,
address: Buffer,
): Promise<bigint> {
return this._internalMethod.getLockedStakedAmount(ctx, address);
}
}