-
Notifications
You must be signed in to change notification settings - Fork 12
/
accounts.go
273 lines (228 loc) · 11.2 KB
/
accounts.go
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
package requesthandler
import (
"fmt"
"sort"
"github.com/labstack/echo/v4"
"github.com/iotaledger/hive.go/ierrors"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/lo"
"github.com/iotaledger/iota-core/pkg/core/account"
iotago "github.com/iotaledger/iota.go/v4"
"github.com/iotaledger/iota.go/v4/api"
)
func (r *RequestHandler) CongestionByAccountAddress(accountAddress *iotago.AccountAddress, workScore iotago.WorkScore, commitmentID iotago.CommitmentID) (*api.CongestionResponse, error) {
// if work score is 0, we don't pass it to the scheduler
workScores := []iotago.WorkScore{}
if workScore != 0 {
workScores = append(workScores, workScore)
}
commitment, err := r.GetCommitmentByID(commitmentID)
if err != nil {
return nil, err
}
accountID := accountAddress.AccountID()
targetSlot := commitment.Slot()
maxCommittableAge := r.protocol.APIForSlot(targetSlot).ProtocolParameters().MaxCommittableAge()
latestCommittedSlot := r.protocol.Engines.Main.Get().SyncManager.LatestCommitment().Slot()
if latestCommittedSlot >= maxCommittableAge && targetSlot+maxCommittableAge < latestCommittedSlot {
return nil, ierrors.Errorf("can't calculate account, target slot index older than allowed (%d<%d)", targetSlot, latestCommittedSlot-maxCommittableAge)
}
acc, exists, err := r.protocol.Engines.Main.Get().Ledger.Account(accountID, targetSlot)
if err != nil {
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get account %s from the Ledger: %w", accountID.ToHex(), err)
} else if !exists {
return nil, ierrors.WithMessagef(echo.ErrNotFound, "account %s not found", accountID.ToHex())
}
blockIssuanceCredits := acc.Credits().Value()
// Apply decay to BIC if the value is positive
if blockIssuanceCredits > 0 {
manaDecayProvider := r.APIProvider().APIForSlot(targetSlot).ManaDecayProvider()
decayedBIC, err := manaDecayProvider.DecayManaBySlots(iotago.Mana(acc.Credits().Value()), acc.Credits().UpdateSlot(), targetSlot)
if err != nil {
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to decay BIC for account %s: %w", accountID.ToHex(), err)
}
blockIssuanceCredits = iotago.BlockIssuanceCredits(decayedBIC)
}
return &api.CongestionResponse{
Slot: targetSlot,
Ready: r.protocol.Engines.Main.Get().Scheduler.IsBlockIssuerReady(accountID, workScores...),
ReferenceManaCost: commitment.ReferenceManaCost(),
BlockIssuanceCredits: blockIssuanceCredits,
}, nil
}
func (r *RequestHandler) Validators(epochIndex iotago.EpochIndex, cursorIndex, pageSize uint32) (*api.ValidatorsResponse, error) {
apiForEpoch := r.APIProvider().APIForEpoch(epochIndex)
currentSlot := r.protocol.Engines.Main.Get().SyncManager.LatestCommitment().Slot()
currentEpoch := apiForEpoch.TimeProvider().EpochFromSlot(currentSlot)
var registeredValidators []*api.ValidatorResponse
var err error
key := epochIndex.MustBytes()
// The key of validators cache for current epoch is the combination of current epoch and current slot. So the results is updated when new commitment is created.
if epochIndex == currentEpoch {
key = append(key, currentSlot.MustBytes()...)
}
// get registered validators from cache, if not found, get from engine and store in cache.
registeredValidators, err = r.cache.GetOrCreateRegisteredValidators(apiForEpoch, key, func() ([]*api.ValidatorResponse, error) {
return r.protocol.Engines.Main.Get().SybilProtection.OrderedRegisteredCandidateValidatorsList(epochIndex)
})
if err != nil {
return nil, ierrors.Wrapf(err, "failed to get registered validators for epoch %d", epochIndex)
}
if cursorIndex >= uint32(len(registeredValidators)) {
return nil, ierrors.Wrapf(echo.ErrBadRequest, "invalid pagination cursorIndex, cursorIndex %d is larger than the number of registered validators %d", cursorIndex, len(registeredValidators))
}
pageEndIndex := lo.Min(cursorIndex+pageSize, uint32(len(registeredValidators)))
page := registeredValidators[cursorIndex:pageEndIndex]
resp := &api.ValidatorsResponse{
Validators: page,
PageSize: pageSize,
}
// this is the last page
if int(cursorIndex+pageSize) <= len(registeredValidators) {
resp.Cursor = fmt.Sprintf("%d,%d", epochIndex, cursorIndex+pageSize)
}
return resp, nil
}
func (r *RequestHandler) ValidatorByAccountAddress(accountAddress *iotago.AccountAddress) (*api.ValidatorResponse, error) {
latestCommittedSlot := r.protocol.Engines.Main.Get().SyncManager.LatestCommitment().Slot()
accountID := accountAddress.AccountID()
accountData, exists, err := r.protocol.Engines.Main.Get().Ledger.Account(accountID, latestCommittedSlot)
if err != nil {
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get account %s from the Ledger: %s", accountID.ToHex(), err)
}
if !exists {
return nil, ierrors.WithMessagef(echo.ErrNotFound, "account %s not found for latest committedSlot %d", accountID.ToHex(), latestCommittedSlot)
}
epoch := r.protocol.APIForSlot(latestCommittedSlot).TimeProvider().EpochFromSlot(latestCommittedSlot)
active, err := r.protocol.Engines.Main.Get().SybilProtection.IsCandidateActive(accountID, epoch)
if err != nil {
return nil, ierrors.Wrapf(err, "failed to check if account %s is an active candidate", accountID.ToHex())
}
return &api.ValidatorResponse{
AddressBech32: accountID.ToAddress().Bech32(r.protocol.CommittedAPI().ProtocolParameters().Bech32HRP()),
PoolStake: accountData.ValidatorStake() + accountData.DelegationStake(),
ValidatorStake: accountData.ValidatorStake(),
StakingEndEpoch: accountData.StakeEndEpoch(),
FixedCost: accountData.FixedCost(),
Active: active,
LatestSupportedProtocolVersion: accountData.LatestSupportedProtocolVersionAndHash().Version,
LatestSupportedProtocolHash: accountData.LatestSupportedProtocolVersionAndHash().Hash,
}, nil
}
func (r *RequestHandler) RewardsByOutputID(outputID iotago.OutputID, optSlot ...iotago.SlotIndex) (*api.ManaRewardsResponse, error) {
var slot iotago.SlotIndex
if len(optSlot) > 0 {
genesisSlot := r.LatestAPI().ProtocolParameters().GenesisSlot()
if optSlot[0] < genesisSlot {
return nil, ierrors.WithMessagef(echo.ErrBadRequest, "slot index (%d) before genesis slot (%d)", slot, genesisSlot)
}
slot = optSlot[0]
} else {
slot = r.GetLatestCommitment().Slot()
}
utxoOutput, err := r.protocol.Engines.Main.Get().Ledger.Output(outputID)
if err != nil {
if ierrors.Is(err, kvstore.ErrKeyNotFound) {
return nil, ierrors.WithMessagef(echo.ErrNotFound, "output %s not found", outputID.ToHex())
}
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get output %s from ledger: %w", outputID.ToHex(), err)
}
var stakingPoolValidatorAccountID iotago.AccountID
var reward iotago.Mana
var firstRewardEpoch, lastRewardEpoch iotago.EpochIndex
apiForSlot := r.protocol.APIForSlot(slot)
switch utxoOutput.OutputType() {
case iotago.OutputAccount:
//nolint:forcetypeassert
accountOutput := utxoOutput.Output().(*iotago.AccountOutput)
feature, exists := accountOutput.FeatureSet()[iotago.FeatureStaking]
if !exists {
return nil, ierrors.WithMessagef(echo.ErrBadRequest, "account %s is not a validator", outputID.ToHex())
}
//nolint:forcetypeassert
stakingFeature := feature.(*iotago.StakingFeature)
futureBoundedSlot := slot + apiForSlot.ProtocolParameters().MinCommittableAge()
claimingEpoch := apiForSlot.TimeProvider().EpochFromSlot(futureBoundedSlot)
stakingPoolValidatorAccountID = accountOutput.AccountID
// check if the account is a validator
reward, firstRewardEpoch, lastRewardEpoch, err = r.protocol.Engines.Main.Get().SybilProtection.ValidatorReward(
stakingPoolValidatorAccountID,
stakingFeature,
claimingEpoch,
)
case iotago.OutputDelegation:
//nolint:forcetypeassert
delegationOutput := utxoOutput.Output().(*iotago.DelegationOutput)
delegationEnd := delegationOutput.EndEpoch
futureBoundedSlot := slot + apiForSlot.ProtocolParameters().MinCommittableAge()
claimingEpoch := apiForSlot.TimeProvider().EpochFromSlot(futureBoundedSlot)
// If Delegation ID is zeroed, the output is in delegating state, which means its End Epoch is not set and we must use the
// "last epoch" for the rewards calculation.
// In this case the calculation must be consistent with the rewards calculation at execution time, so a client can specify
// a slot index explicitly, which should be equal to the slot it uses as the commitment input for the claiming transaction.
if delegationOutput.DelegationID.Empty() {
delegationEnd = claimingEpoch - iotago.EpochIndex(1)
}
stakingPoolValidatorAccountID = delegationOutput.ValidatorAddress.AccountID()
reward, firstRewardEpoch, lastRewardEpoch, err = r.protocol.Engines.Main.Get().SybilProtection.DelegatorReward(
stakingPoolValidatorAccountID,
delegationOutput.DelegatedAmount,
delegationOutput.StartEpoch,
delegationEnd,
claimingEpoch,
)
default:
return nil, ierrors.Wrapf(echo.ErrBadRequest, "output %s is neither a delegation output nor account", outputID.ToHex())
}
if err != nil {
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to calculate reward for output %s: %w", outputID.ToHex(), err)
}
latestCommittedEpochPoolRewards, poolRewardExists, err := r.protocol.Engines.Main.Get().SybilProtection.PoolRewardsForAccount(stakingPoolValidatorAccountID)
if err != nil {
return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to retrieve pool rewards for account %s: %w", stakingPoolValidatorAccountID.ToHex(), err)
}
if !poolRewardExists {
latestCommittedEpochPoolRewards = 0
}
return &api.ManaRewardsResponse{
StartEpoch: firstRewardEpoch,
EndEpoch: lastRewardEpoch,
Rewards: reward,
LatestCommittedEpochPoolRewards: latestCommittedEpochPoolRewards,
}, nil
}
func (r *RequestHandler) SelectedCommittee(epoch iotago.EpochIndex) (*api.CommitteeResponse, error) {
seatedAccounts, exists := r.protocol.Engines.Main.Get().SybilProtection.SeatManager().CommitteeInEpoch(epoch)
if !exists {
return &api.CommitteeResponse{
Epoch: epoch,
}, nil
}
accounts, err := seatedAccounts.Accounts()
if err != nil {
return nil, ierrors.Wrapf(err, "failed to get accounts from committee for epoch %d", epoch)
}
committee := make([]*api.CommitteeMemberResponse, 0, accounts.Size())
accounts.ForEach(func(accountID iotago.AccountID, seat *account.Pool) bool {
committee = append(committee, &api.CommitteeMemberResponse{
AddressBech32: accountID.ToAddress().Bech32(r.protocol.CommittedAPI().ProtocolParameters().Bech32HRP()),
PoolStake: seat.PoolStake,
ValidatorStake: seat.ValidatorStake,
FixedCost: seat.FixedCost,
})
return true
})
// sort committee by pool stake, then by address
sort.Slice(committee, func(i, j int) bool {
if committee[i].PoolStake == committee[j].PoolStake {
return committee[i].AddressBech32 < committee[j].AddressBech32
}
return committee[i].PoolStake > committee[j].PoolStake
})
return &api.CommitteeResponse{
Epoch: epoch,
Committee: committee,
TotalStake: accounts.TotalStake(),
TotalValidatorStake: accounts.TotalValidatorStake(),
}, nil
}