-
Notifications
You must be signed in to change notification settings - Fork 22
/
stake_verifier.go
302 lines (254 loc) · 8.24 KB
/
stake_verifier.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
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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package staking
import (
"context"
"errors"
"sync"
"time"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/core/validators"
"code.vegaprotocol.io/vega/logging"
)
const (
// 3 weeks, duration of the whole network at first?
timeTilCancel = 24 * 21 * time.Hour
)
var (
ErrNoStakeDepositedEventFound = errors.New("no stake deposited event found")
ErrNoStakeRemovedEventFound = errors.New("no stake removed event found")
ErrMissingConfirmations = errors.New("not enough confirmations")
ErrInvalidStakeRemovedEventID = errors.New("invalid stake removed event ID")
ErrInvalidStakeDepositedEventID = errors.New("invalid stake deposited event ID")
ErrDuplicatedStakeDepositedEvent = errors.New("duplicated stake deposited event")
ErrDuplicatedStakeRemovedEvent = errors.New("duplicated stake deposited event")
)
// Witness provide foreign chain resources validations
type TimeService interface {
GetTimeNow() time.Time
}
type EthConfirmations interface {
Check(uint64) error
}
type EthOnChainVerifier interface {
CheckStakeDeposited(*types.StakeDeposited) error
CheckStakeRemoved(*types.StakeRemoved) error
}
// Witness provide foreign chain resources validations.
type Witness interface {
StartCheck(validators.Resource, func(interface{}, bool), time.Time) error
RestoreResource(validators.Resource, func(interface{}, bool)) error
}
type StakeVerifier struct {
log *logging.Logger
cfg Config
accs *Accounting
witness Witness
timeService TimeService
broker Broker
ocv EthOnChainVerifier
ethEventSource EthereumEventSource
pendingSDs []*pendingSD
pendingSRs []*pendingSR
finalizedEvents []*types.StakeLinking
mu sync.Mutex
ids map[string]struct{}
hashes map[string]struct{}
// snapshot data
svss *stakeVerifierSnapshotState
}
type pendingSD struct {
*types.StakeDeposited
chainID string
check func() error
}
func (p pendingSD) GetID() string { return p.ID }
func (p pendingSD) GetChainID() string { return p.chainID }
func (p pendingSD) GetType() types.NodeVoteType { return types.NodeVoteTypeStakeDeposited }
func (p *pendingSD) Check(ctx context.Context) error { return p.check() }
type pendingSR struct {
*types.StakeRemoved
chainID string
check func() error
}
func (p pendingSR) GetID() string { return p.ID }
func (p pendingSR) GetChainID() string { return p.chainID }
func (p pendingSR) GetType() types.NodeVoteType { return types.NodeVoteTypeStakeRemoved }
func (p *pendingSR) Check(ctx context.Context) error { return p.check() }
func NewStakeVerifier(
log *logging.Logger,
cfg Config,
accs *Accounting,
witness Witness,
ts TimeService,
broker Broker,
onChainVerifier EthOnChainVerifier,
ethEventSource EthereumEventSource,
) (sv *StakeVerifier) {
log = log.Named("stake-verifier")
s := &StakeVerifier{
log: log,
cfg: cfg,
accs: accs,
witness: witness,
ocv: onChainVerifier,
timeService: ts,
broker: broker,
ethEventSource: ethEventSource,
ids: map[string]struct{}{},
hashes: map[string]struct{}{},
svss: &stakeVerifierSnapshotState{},
}
return s
}
func (s *StakeVerifier) ensureNotDuplicate(id, h string) bool {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.ids[id]; ok {
return false
}
if _, ok := s.hashes[h]; ok {
return false
}
s.ids[id] = struct{}{}
s.hashes[h] = struct{}{}
return true
}
// TODO: address this as the ID/hash map will grow forever now
// func (s *StakeVerifier) removeEvent(id string) {
// delete(s.ids, id)
// }
func (s *StakeVerifier) ProcessStakeRemoved(
ctx context.Context, event *types.StakeRemoved,
) error {
if ok := s.ensureNotDuplicate(event.ID, event.IntoStakeLinking().Hash()); !ok {
s.log.Error("stake removed event already exists",
logging.String("event", event.String()))
return ErrDuplicatedStakeRemovedEvent
}
pending := &pendingSR{
StakeRemoved: event,
chainID: s.accs.chainID,
check: func() error { return s.ocv.CheckStakeRemoved(event) },
}
s.pendingSRs = append(s.pendingSRs, pending)
evt := pending.IntoStakeLinking()
evt.Status = types.StakeLinkingStatusPending
s.broker.Send(events.NewStakeLinking(ctx, *evt))
s.log.Info("stake removed event received, starting validation",
logging.String("event", event.String()))
return s.witness.StartCheck(
pending, s.onEventVerified, s.timeService.GetTimeNow().Add(timeTilCancel))
}
func (s *StakeVerifier) ProcessStakeDeposited(
ctx context.Context, event *types.StakeDeposited,
) error {
if ok := s.ensureNotDuplicate(event.ID, event.IntoStakeLinking().Hash()); !ok {
s.log.Error("stake deposited event already exists",
logging.String("event", event.String()))
return ErrDuplicatedStakeDepositedEvent
}
pending := &pendingSD{
StakeDeposited: event,
chainID: s.accs.chainID,
check: func() error { return s.ocv.CheckStakeDeposited(event) },
}
s.pendingSDs = append(s.pendingSDs, pending)
evt := pending.IntoStakeLinking()
evt.Status = types.StakeLinkingStatusPending
s.broker.Send(events.NewStakeLinking(ctx, *evt))
s.log.Info("stake deposited event received, starting validation",
logging.String("event", event.String()))
return s.witness.StartCheck(
pending, s.onEventVerified, s.timeService.GetTimeNow().Add(timeTilCancel))
}
func (s *StakeVerifier) removePendingStakeDeposited(id string) error {
for i, v := range s.pendingSDs {
if v.ID == id {
s.pendingSDs = s.pendingSDs[:i+copy(s.pendingSDs[i:], s.pendingSDs[i+1:])]
return nil
}
}
return ErrInvalidStakeDepositedEventID
}
func (s *StakeVerifier) removePendingStakeRemoved(id string) error {
for i, v := range s.pendingSRs {
if v.ID == id {
s.pendingSRs = s.pendingSRs[:i+copy(s.pendingSRs[i:], s.pendingSRs[i+1:])]
return nil
}
}
return ErrInvalidStakeRemovedEventID
}
func (s *StakeVerifier) getLastBlockSeen() uint64 {
var block uint64
for _, p := range s.pendingSDs {
if block == 0 {
block = p.BlockNumber
continue
}
if p.BlockNumber < block {
block = p.BlockNumber
}
}
for _, p := range s.pendingSRs {
if block == 0 {
block = p.BlockNumber
continue
}
if p.BlockNumber < block {
block = p.BlockNumber
}
}
return block
}
func (s *StakeVerifier) onEventVerified(event interface{}, ok bool) {
var evt *types.StakeLinking
switch pending := event.(type) {
case *pendingSD:
evt = pending.IntoStakeLinking()
if err := s.removePendingStakeDeposited(evt.ID); err != nil {
s.log.Error("could not remove pending stake deposited event", logging.Error(err))
}
case *pendingSR:
evt = pending.IntoStakeLinking()
if err := s.removePendingStakeRemoved(evt.ID); err != nil {
s.log.Error("could not remove pending stake removed event", logging.Error(err))
}
default:
s.log.Error("stake verifier received invalid event")
return
}
evt.Status = types.StakeLinkingStatusRejected
if ok {
evt.Status = types.StakeLinkingStatusAccepted
}
evt.FinalizedAt = s.timeService.GetTimeNow().UnixNano()
s.finalizedEvents = append(s.finalizedEvents, evt)
}
func (s *StakeVerifier) OnTick(ctx context.Context, t time.Time) {
for _, evt := range s.finalizedEvents {
// s.removeEvent(evt.ID)
if evt.Status == types.StakeLinkingStatusAccepted {
s.accs.AddEvent(ctx, evt)
}
s.log.Info("stake linking finalized",
logging.String("status", evt.Status.String()),
logging.String("event", evt.String()))
s.broker.Send(events.NewStakeLinking(ctx, *evt))
}
s.finalizedEvents = nil
}