-
Notifications
You must be signed in to change notification settings - Fork 19
/
checkpoint.go
497 lines (456 loc) · 13.1 KB
/
checkpoint.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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// 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 types
import (
"bytes"
"errors"
"time"
"code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/libs/proto"
"code.vegaprotocol.io/vega/protos/vega"
checkpoint "code.vegaprotocol.io/vega/protos/vega/checkpoint/v1"
)
var (
ErrCheckpointStateInvalid = errors.New("state contained in the snapshot is invalid")
ErrCheckpointHashIncorrect = errors.New("the hash and snapshot data do not match")
ErrCheckpointHasNoState = errors.New("there is no state set on the checkpoint")
)
type CheckpointName string
const (
GovernanceCheckpoint CheckpointName = "governance"
AssetsCheckpoint CheckpointName = "assets"
CollateralCheckpoint CheckpointName = "collateral"
NetParamsCheckpoint CheckpointName = "netparams"
DelegationCheckpoint CheckpointName = "delegation"
EpochCheckpoint CheckpointName = "epoch"
BlockCheckpoint CheckpointName = "block" // pseudo-checkpoint, really...
MarketActivityTrackerCheckpoint CheckpointName = "marketActivity"
PendingRewardsCheckpoint CheckpointName = "rewards"
BankingCheckpoint CheckpointName = "banking"
ValidatorsCheckpoint CheckpointName = "validators"
StakingCheckpoint CheckpointName = "staking"
MultisigControlCheckpoint CheckpointName = "multisigControl"
ExecutionCheckpoint CheckpointName = "execution"
)
type Block struct {
Height int64
}
type CheckpointState struct {
State []byte
Hash []byte
}
type Checkpoint struct {
Governance []byte
Assets []byte
Collateral []byte
NetworkParameters []byte
Delegation []byte
Epoch []byte
Block []byte
Rewards []byte
Validators []byte
Banking []byte
Staking []byte
MultisigControl []byte
MarketActivityTracker []byte
Execution []byte
}
type DelegationEntry struct {
Party string
Node string
Amount *num.Uint
Undelegate bool
EpochSeq uint64
}
type DelegateCP struct {
Active []*DelegationEntry
Pending []*DelegationEntry
Auto []string
}
func NewCheckpointStateFromProto(ps *checkpoint.CheckpointState) *CheckpointState {
return &CheckpointState{
State: ps.State,
Hash: ps.Hash,
}
}
func (s CheckpointState) IntoProto() *checkpoint.CheckpointState {
return &checkpoint.CheckpointState{
Hash: s.Hash,
State: s.State,
}
}
func (s CheckpointState) GetCheckpoint() (*Checkpoint, error) {
pc := &checkpoint.Checkpoint{}
if err := proto.Unmarshal(s.State, pc); err != nil {
return nil, err
}
cp := NewCheckpointFromProto(pc)
return cp, nil
}
func (s *CheckpointState) SetState(state []byte) error {
cp := &checkpoint.Checkpoint{}
if err := proto.Unmarshal(state, cp); err != nil {
return err
}
c := NewCheckpointFromProto(cp)
s.State = state
s.Hash = crypto.HashBytesBuffer(c.HashBytes())
return nil
}
func (s CheckpointState) GetBlockHeight() (int64, error) {
if len(s.State) == 0 {
return 0, ErrCheckpointHasNoState
}
cp := &checkpoint.Checkpoint{}
if err := proto.Unmarshal(s.State, cp); err != nil {
return 0, err
}
c := NewCheckpointFromProto(cp)
return c.GetBlockHeight()
}
func (s *CheckpointState) SetCheckpoint(cp *Checkpoint) error {
b, err := proto.Marshal(cp.IntoProto())
if err != nil {
return err
}
s.Hash = crypto.HashBytesBuffer(cp.HashBytes())
s.State = b
return nil
}
// Validate checks the hash, returns nil if valid.
func (s CheckpointState) Validate() error {
cp, err := s.GetCheckpoint()
if err != nil {
return ErrCheckpointStateInvalid
}
if !bytes.Equal(crypto.HashBytesBuffer(cp.HashBytes()), s.Hash) {
return ErrCheckpointHashIncorrect
}
return nil
}
func NewCheckpointFromProto(pc *checkpoint.Checkpoint) *Checkpoint {
return &Checkpoint{
Governance: pc.Governance,
Assets: pc.Assets,
Collateral: pc.Collateral,
NetworkParameters: pc.NetworkParameters,
Delegation: pc.Delegation,
Epoch: pc.Epoch,
Block: pc.Block,
Rewards: pc.Rewards,
Validators: pc.Validators,
Banking: pc.Banking,
Staking: pc.Staking,
MultisigControl: pc.MultisigControl,
MarketActivityTracker: pc.MarketTracker,
Execution: pc.Execution,
}
}
func (c Checkpoint) IntoProto() *checkpoint.Checkpoint {
return &checkpoint.Checkpoint{
Governance: c.Governance,
Assets: c.Assets,
Collateral: c.Collateral,
NetworkParameters: c.NetworkParameters,
Delegation: c.Delegation,
Epoch: c.Epoch,
Block: c.Block,
Rewards: c.Rewards,
Validators: c.Validators,
Banking: c.Banking,
Staking: c.Staking,
MultisigControl: c.MultisigControl,
MarketTracker: c.MarketActivityTracker,
Execution: c.Execution,
}
}
func (c *Checkpoint) SetBlockHeight(height int64) error {
b := Block{
Height: height,
}
bb, err := proto.Marshal(b.IntoProto())
if err != nil {
return err
}
c.Block = bb
return nil
}
// HashBytes returns the data contained in the checkpoint as a []byte for hashing
// the order in which the data is added to the slice matters.
func (c Checkpoint) HashBytes() bytes.Buffer {
var b bytes.Buffer
// the order in which we append is quite important
b.Write(c.NetworkParameters)
b.Write(c.Assets)
b.Write(c.Collateral)
b.Write(c.Delegation)
b.Write(c.Epoch)
b.Write(c.Block)
b.Write(c.Governance)
b.Write(c.Rewards)
b.Write(c.Banking)
b.Write(c.Validators)
b.Write(c.Staking)
b.Write(c.MarketActivityTracker)
b.Write(c.MultisigControl)
b.Write(c.Execution)
return b
}
// Set set a specific checkpoint value using the name the engine returns.
func (c *Checkpoint) Set(name CheckpointName, val []byte) {
switch name {
case GovernanceCheckpoint:
c.Governance = val
case AssetsCheckpoint:
c.Assets = val
case CollateralCheckpoint:
c.Collateral = val
case NetParamsCheckpoint:
c.NetworkParameters = val
case DelegationCheckpoint:
c.Delegation = val
case EpochCheckpoint:
c.Epoch = val
case BlockCheckpoint:
c.Block = val
case PendingRewardsCheckpoint:
c.Rewards = val
case ValidatorsCheckpoint:
c.Validators = val
case BankingCheckpoint:
c.Banking = val
case StakingCheckpoint:
c.Staking = val
case MultisigControlCheckpoint:
c.MultisigControl = val
case MarketActivityTrackerCheckpoint:
c.MarketActivityTracker = val
case ExecutionCheckpoint:
c.Execution = val
}
}
// Get as the name suggests gets the data by checkpoint name.
func (c Checkpoint) Get(name CheckpointName) []byte {
switch name {
case GovernanceCheckpoint:
return c.Governance
case AssetsCheckpoint:
return c.Assets
case CollateralCheckpoint:
return c.Collateral
case NetParamsCheckpoint:
return c.NetworkParameters
case DelegationCheckpoint:
return c.Delegation
case EpochCheckpoint:
return c.Epoch
case BlockCheckpoint:
return c.Block
case PendingRewardsCheckpoint:
return c.Rewards
case ValidatorsCheckpoint:
return c.Validators
case BankingCheckpoint:
return c.Banking
case StakingCheckpoint:
return c.Staking
case MultisigControlCheckpoint:
return c.MultisigControl
case MarketActivityTrackerCheckpoint:
return c.MarketActivityTracker
case ExecutionCheckpoint:
return c.Execution
}
return nil
}
func (c Checkpoint) GetBlockHeight() (int64, error) {
pb := &checkpoint.Block{}
if err := proto.Unmarshal(c.Block, pb); err != nil {
return 0, err
}
return pb.Height, nil
}
func NewDelegationEntryFromProto(de *checkpoint.DelegateEntry) *DelegationEntry {
amt, _ := num.UintFromString(de.Amount, 10)
return &DelegationEntry{
Party: de.Party,
Node: de.Node,
Amount: amt,
Undelegate: de.Undelegate,
EpochSeq: de.EpochSeq,
}
}
func (d DelegationEntry) IntoProto() *checkpoint.DelegateEntry {
return &checkpoint.DelegateEntry{
Party: d.Party,
Node: d.Node,
Amount: d.Amount.String(),
Undelegate: d.Undelegate,
EpochSeq: d.EpochSeq,
}
}
func NewDelegationCPFromProto(sd *checkpoint.Delegate) *DelegateCP {
r := &DelegateCP{
Active: make([]*DelegationEntry, 0, len(sd.Active)),
Pending: make([]*DelegationEntry, 0, len(sd.Pending)),
Auto: sd.AutoDelegation[:],
}
for _, a := range sd.Active {
r.Active = append(r.Active, NewDelegationEntryFromProto(a))
}
for _, p := range sd.Pending {
r.Pending = append(r.Pending, NewDelegationEntryFromProto(p))
}
return r
}
func (d DelegateCP) IntoProto() *checkpoint.Delegate {
s := &checkpoint.Delegate{
Active: make([]*checkpoint.DelegateEntry, 0, len(d.Active)),
Pending: make([]*checkpoint.DelegateEntry, 0, len(d.Pending)),
AutoDelegation: d.Auto[:],
}
for _, a := range d.Active {
s.Active = append(s.Active, a.IntoProto())
}
for _, p := range d.Pending {
s.Pending = append(s.Pending, p.IntoProto())
}
return s
}
func NewBlockFromProto(bp *checkpoint.Block) *Block {
return &Block{
Height: bp.Height,
}
}
func (b Block) IntoProto() *checkpoint.Block {
return &checkpoint.Block{
Height: b.Height,
}
}
type ELSShare struct {
PartyID string
Share num.Decimal
SuppliedStake num.Decimal
VStake num.Decimal
Avg num.Decimal
}
func NewELSShareFromProto(ELSs *checkpoint.ELSShare) *ELSShare {
return &ELSShare{
PartyID: ELSs.PartyId,
Share: num.MustDecimalFromString(ELSs.Share),
SuppliedStake: num.MustDecimalFromString(ELSs.SuppliedStake),
VStake: num.MustDecimalFromString(ELSs.VirtualStake),
Avg: num.MustDecimalFromString(ELSs.Avg),
}
}
func (e *ELSShare) IntoProto() *checkpoint.ELSShare {
return &checkpoint.ELSShare{
PartyId: e.PartyID,
Share: e.Share.String(),
SuppliedStake: e.SuppliedStake.String(),
VirtualStake: e.VStake.String(),
Avg: e.Avg.String(),
}
}
type CPMarketState struct {
ID string
Shares []*ELSShare
InsuranceBalance *num.Uint
LastTradeValue *num.Uint
LastTradeVolume *num.Uint
TTL time.Time
Market *Market // the full market object - needed in case the market has settled but a successor market is enacted during the successor window.
State MarketState // only used during OnTick, indicating the parent is still in opening auction
}
func NewMarketStateFromProto(ms *checkpoint.MarketState) *CPMarketState {
els := make([]*ELSShare, 0, len(ms.Shares))
for _, s := range ms.Shares {
els = append(els, NewELSShareFromProto(s))
}
var insBal, tVal, tVol *num.Uint
if len(ms.InsuranceBalance) > 0 {
insBal, _ = num.UintFromString(ms.InsuranceBalance, 10)
}
if len(ms.LastTradeValue) > 0 {
tVal, _ = num.UintFromString(ms.LastTradeValue, 10)
}
if len(ms.LastTradeVolume) > 0 {
tVol, _ = num.UintFromString(ms.LastTradeVolume, 10)
}
var mkt *Market
if ms.Market != nil {
mkt, _ = MarketFromProto(ms.Market)
}
return &CPMarketState{
ID: ms.Id,
Shares: els,
InsuranceBalance: insBal,
LastTradeValue: tVal,
LastTradeVolume: tVol,
TTL: time.Unix(0, ms.SuccessionWindow),
Market: mkt,
}
}
func (m *CPMarketState) IntoProto() *checkpoint.MarketState {
els := make([]*checkpoint.ELSShare, 0, len(m.Shares))
for _, s := range m.Shares {
els = append(els, s.IntoProto())
}
var mkt *vega.Market
if m.Market != nil {
mkt = m.Market.IntoProto()
}
var insBal, ltVal, ltVol string
if m.InsuranceBalance != nil {
insBal = m.InsuranceBalance.String()
}
if m.LastTradeValue != nil {
ltVal = m.LastTradeValue.String()
}
if m.LastTradeVolume != nil {
ltVol = m.LastTradeVolume.String()
}
return &checkpoint.MarketState{
Id: m.ID,
Shares: els,
InsuranceBalance: insBal,
LastTradeValue: ltVal,
LastTradeVolume: ltVol,
SuccessionWindow: m.TTL.UnixNano(),
Market: mkt,
}
}
type ExecutionState struct {
Data []*CPMarketState
}
func NewExecutionStateFromProto(es *checkpoint.ExecutionState) *ExecutionState {
d := make([]*CPMarketState, 0, len(es.Data))
for _, m := range es.Data {
d = append(d, NewMarketStateFromProto(m))
}
return &ExecutionState{
Data: d,
}
}
func (e *ExecutionState) IntoProto() *checkpoint.ExecutionState {
d := make([]*checkpoint.MarketState, 0, len(e.Data))
for _, m := range e.Data {
d = append(d, m.IntoProto())
}
return &checkpoint.ExecutionState{
Data: d,
}
}