-
Notifications
You must be signed in to change notification settings - Fork 19
/
engine.go
1444 lines (1290 loc) · 52.2 KB
/
engine.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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 governance
import (
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"sort"
"strings"
"time"
"code.vegaprotocol.io/vega/core/assets"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/netparams"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/core/validators"
vgcrypto "code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
"github.com/pkg/errors"
)
var (
ErrProposalDoesNotExist = errors.New("proposal does not exist")
ErrMarketDoesNotExist = errors.New("market does not exist")
ErrMarketStateUpdateNotAllowed = errors.New("market state does not allow for state update")
ErrMarketProposalStillOpen = errors.New("original market proposal is still open")
ErrProposalNotOpenForVotes = errors.New("proposal is not open for votes")
ErrProposalIsDuplicate = errors.New("proposal with given ID already exists")
ErrVoterInsufficientTokensAndEquityLikeShare = errors.New("vote requires tokens or equity-like share")
ErrVoterInsufficientTokens = errors.New("vote requires more tokens than the party has")
ErrUnsupportedProposalType = errors.New("unsupported proposal type")
ErrUnsupportedAssetSourceType = errors.New("unsupported asset source type")
ErrExpectedERC20Asset = errors.New("expected an ERC20 asset but was not")
ErrErc20AddressAlreadyInUse = errors.New("erc20 address already in use")
ErrParentMarketDoesNotExist = errors.New("market to succeed does not exist")
ErrParentMarketAlreadySucceeded = errors.New("the parent market was already succeeded by a prior proposal")
ErrParentMarketSucceededByCompeting = errors.New("the parent market has been succeeded by a competing propsal")
ErrSettlementDataOutOfRange = errors.New("the settlement data is invalid")
)
//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/governance Markets,StakingAccounts,Assets,TimeService,Witness,NetParams,Banking
// Broker - event bus.
type Broker interface {
Send(e events.Event)
SendBatch(es []events.Event)
}
// Markets allows to get the market data for use in the market update proposal
// computation.
type Markets interface {
MarketExists(market string) bool
GetMarket(market string, settled bool) (types.Market, bool)
GetMarketState(market string) (types.MarketState, error)
GetEquityLikeShareForMarketAndParty(market, party string) (num.Decimal, bool)
RestoreMarket(ctx context.Context, marketConfig *types.Market) error
StartOpeningAuction(ctx context.Context, marketID string) error
UpdateMarket(ctx context.Context, marketConfig *types.Market) error
IsSucceeded(mktID string) bool
ValidateSettlementData(mktID string, data *num.Uint) bool
}
// StakingAccounts ...
type StakingAccounts interface {
GetAvailableBalance(party string) (*num.Uint, error)
GetStakingAssetTotalSupply() *num.Uint
}
type Assets interface {
NewAsset(ctx context.Context, ref string, assetDetails *types.AssetDetails) (string, error)
Get(assetID string) (*assets.Asset, error)
IsEnabled(string) bool
SetRejected(ctx context.Context, assetID string) error
SetPendingListing(ctx context.Context, assetID string) error
ValidateAsset(assetID string) error
ValidateEthereumAddress(address, chainID string) error
}
type Banking interface {
VerifyGovernanceTransfer(transfer *types.NewTransferConfiguration) error
VerifyCancelGovernanceTransfer(transferID string) error
}
// TimeService ...
type TimeService interface {
GetTimeNow() time.Time
}
// Witness ...
type Witness interface {
StartCheck(validators.Resource, func(interface{}, bool), time.Time) error
RestoreResource(validators.Resource, func(interface{}, bool)) error
}
type NetParams interface {
Validate(string, string) error
Update(context.Context, string, string) error
GetDecimal(string) (num.Decimal, error)
GetInt(string) (int64, error)
GetUint(string) (*num.Uint, error)
GetDuration(string) (time.Duration, error)
GetJSONStruct(string, netparams.Reset) error
Get(string) (string, error)
}
// Engine is the governance engine that handles proposal and vote lifecycle.
type Engine struct {
Config
log *logging.Logger
nodeProposalValidation *NodeValidation
accs StakingAccounts
markets Markets
timeService TimeService
broker Broker
assets Assets
netp NetParams
banking Banking
// we store proposals in slice
// not as easy to access them directly, but by doing this we can keep
// them in order of arrival, which makes their processing deterministic
activeBatchProposals map[string]*batchProposal
activeProposals []*proposal
enactedProposals []*proposal
// snapshot state
gss *governanceSnapshotState
// main chain ID
chainID uint64
}
func NewEngine(
log *logging.Logger,
cfg Config,
accs StakingAccounts,
tm TimeService,
broker Broker,
assets Assets,
witness Witness,
markets Markets,
netp NetParams,
banking Banking,
) *Engine {
log = log.Named(namedLogger)
log.SetLevel(cfg.Level.Level)
e := &Engine{
Config: cfg,
accs: accs,
log: log,
activeProposals: []*proposal{},
enactedProposals: []*proposal{},
activeBatchProposals: map[string]*batchProposal{},
nodeProposalValidation: NewNodeValidation(log, assets, tm.GetTimeNow(), witness),
timeService: tm,
broker: broker,
assets: assets,
markets: markets,
netp: netp,
gss: &governanceSnapshotState{},
banking: banking,
}
return e
}
func (e *Engine) Hash() []byte {
// get the node proposal hash first
npHash := e.nodeProposalValidation.Hash()
// Create the slice for this state
// 32 -> len(proposal.ID) = 32 bytes pubkey
// vote counts = 3*uint64
// 32 -> len of enactedProposal.ID
// len of the np hash
output := make(
[]byte,
len(e.activeProposals)*(32+8*3)+len(e.enactedProposals)*32+len(npHash),
)
var i int
for _, k := range e.activeProposals {
idbytes := []byte(k.ID)
copy(output[i:], idbytes[:])
i += 32
binary.BigEndian.PutUint64(output[i:], uint64(len(k.yes)))
i += 8
binary.BigEndian.PutUint64(output[i:], uint64(len(k.no)))
i += 8
binary.BigEndian.PutUint64(output[i:], uint64(len(k.invalidVotes)))
i += 8
}
for _, k := range e.enactedProposals {
idbytes := []byte(k.ID)
copy(output[i:], idbytes[:])
i += 32
}
// now add the hash of the nodeProposals
copy(output[i:], npHash[:])
h := vgcrypto.Hash(output)
e.log.Debug("governance state hash", logging.String("hash", hex.EncodeToString(h)))
return h
}
// ReloadConf updates the internal configuration of the governance engine.
func (e *Engine) ReloadConf(cfg Config) {
e.log.Info("reloading configuration")
if e.log.GetLevel() != cfg.Level.Get() {
e.log.Info("updating log level",
logging.String("old", e.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
e.log.SetLevel(cfg.Level.Get())
}
e.Config = cfg
}
func (e *Engine) preEnactProposal(ctx context.Context, p *proposal) (te *ToEnact, perr types.ProposalError, err error) {
te = &ToEnact{
p: p,
}
defer func() {
if err != nil {
p.FailWithErr(perr, err)
}
}()
switch p.Terms.Change.GetTermType() {
case types.ProposalTermsTypeNewMarket:
te.m = &ToEnactNewMarket{}
case types.ProposalTermsTypeNewSpotMarket:
te.s = &ToEnactNewSpotMarket{}
case types.ProposalTermsTypeUpdateMarket:
mkt, perr, err := e.updatedMarketFromProposal(p)
if err != nil {
return nil, perr, err
}
te.updatedMarket = mkt
case types.ProposalTermsTypeUpdateSpotMarket:
mkt, perr, err := e.updatedSpotMarketFromProposal(p)
if err != nil {
return nil, perr, err
}
te.updatedSpotMarket = mkt
case types.ProposalTermsTypeUpdateNetworkParameter:
unp := p.Terms.GetUpdateNetworkParameter()
if unp != nil {
te.n = unp.Changes
}
if err := e.netp.Validate(unp.Changes.Key, unp.Changes.Value); err != nil {
return nil, types.ProposalErrorNetworkParameterInvalidValue, err
}
case types.ProposalTermsTypeNewAsset:
asset, err := e.assets.Get(p.ID)
if err != nil {
return nil, types.ProposalErrorUnspecified, err
}
te.newAsset = asset.Type()
// notify the asset engine that the proposal was passed
// and the asset is not pending for listing on the bridge
e.assets.SetPendingListing(ctx, p.ID)
case types.ProposalTermsTypeUpdateAsset:
asset, perr, err := e.updatedAssetFromProposal(p)
if err != nil {
return nil, perr, err
}
te.updatedAsset = asset
case types.ProposalTermsTypeNewFreeform:
te.f = &ToEnactFreeform{}
case types.ProposalTermsTypeNewTransfer:
te.t = &ToEnactTransfer{}
case types.ProposalTermsTypeCancelTransfer:
te.c = &ToEnactCancelTransfer{}
case types.ProposalTermsTypeUpdateMarketState:
te.msu = &ToEnactMarketStateUpdate{}
case types.ProposalTermsTypeUpdateReferralProgram:
te.referralProgramChanges = updatedReferralProgramFromProposal(p)
case types.ProposalTermsTypeUpdateVolumeDiscountProgram:
te.volumeDiscountProgram = updatedVolumeDiscountProgramFromProposal(p)
}
return //nolint:nakedret
}
func (e *Engine) preVoteClosedProposal(p *proposal) *VoteClosed {
vc := &VoteClosed{
p: p.Proposal,
}
switch p.Terms.Change.GetTermType() {
case types.ProposalTermsTypeNewMarket, types.ProposalTermsTypeNewSpotMarket:
startAuction := true
if p.State != types.ProposalStatePassed {
startAuction = false
}
vc.m = &NewMarketVoteClosed{
startAuction: startAuction,
}
}
return vc
}
func (e *Engine) removeActiveProposalByID(ctx context.Context, id string) {
for i, p := range e.activeProposals {
if p.ID == id {
copy(e.activeProposals[i:], e.activeProposals[i+1:])
e.activeProposals[len(e.activeProposals)-1] = nil
e.activeProposals = e.activeProposals[:len(e.activeProposals)-1]
if p.State == types.ProposalStateDeclined || p.State == types.ProposalStateFailed || p.State == types.ProposalStateRejected {
// if it's an asset proposal we need to update it's
// state in the asset engine
switch p.Terms.Change.GetTermType() {
case types.ProposalTermsTypeNewAsset:
e.assets.SetRejected(ctx, p.ID)
}
}
return
}
}
}
func (e *Engine) OnTick(ctx context.Context, t time.Time) ([]*ToEnact, []*VoteClosed) {
now := t.Unix()
voteClosed, addToActiveProposals := e.evaluateBatchProposals(ctx, now)
var (
preparedToEnact []*ToEnact
toBeRemoved []string // ids
)
for _, proposal := range e.activeProposals {
// check if the market for successor proposals still exists, if not, reject the proposal
if nm := proposal.Terms.GetNewMarket(); nm != nil && nm.Successor() != nil {
if _, err := e.markets.GetMarketState(proposal.ID); err != nil {
proposal.RejectWithErr(types.ProposalErrorInvalidSuccessorMarket, ErrParentMarketSucceededByCompeting)
e.broker.Send(events.NewProposalEvent(ctx, *proposal.Proposal))
toBeRemoved = append(toBeRemoved, proposal.ID)
continue
}
}
// do not check parent market, the market was either rejected when the parent was succeeded
// or, if the parent market state is gone (ie succession window has expired), the proposal simply
// loses its parent market reference
if proposal.ShouldClose(now) {
e.closeProposal(ctx, proposal)
voteClosed = append(voteClosed, e.preVoteClosedProposal(proposal))
}
if !proposal.IsOpen() && !proposal.IsPassed() {
toBeRemoved = append(toBeRemoved, proposal.ID)
} else if proposal.IsPassed() && (e.isAutoEnactableProposal(proposal.Proposal) || proposal.IsTimeToEnact(now)) {
enact, perr, err := e.preEnactProposal(ctx, proposal)
if err != nil {
e.broker.Send(events.NewProposalEvent(ctx, *proposal.Proposal))
toBeRemoved = append(toBeRemoved, proposal.ID)
e.log.Error("proposal enactment has failed",
logging.String("proposal-id", proposal.ID),
logging.String("proposal-error", perr.String()),
logging.Error(err))
} else {
toBeRemoved = append(toBeRemoved, proposal.ID)
preparedToEnact = append(preparedToEnact, enact)
}
}
}
// then get all proposal accepted through node validation, and start their vote time.
accepted, rejected := e.nodeProposalValidation.OnTick(t)
for _, p := range accepted {
e.log.Info("proposal has been validated by nodes, starting now",
logging.String("proposal-id", p.ID))
p.State = types.ProposalStateOpen
e.broker.Send(events.NewProposalEvent(ctx, *p.Proposal))
e.startValidatedProposal(p) // can't fail, and proposal has been validated at an ulterior time
}
for _, p := range rejected {
e.log.Info("proposal has not been validated by nodes",
logging.String("proposal-id", p.ID))
p.Reject(types.ProposalErrorNodeValidationFailed)
e.broker.Send(events.NewProposalEvent(ctx, *p.Proposal))
// if it's an asset proposal we need to update it's
// state in the asset engine
switch p.Terms.Change.GetTermType() {
case types.ProposalTermsTypeNewAsset:
e.assets.SetRejected(ctx, p.ID)
}
}
// then do the same thing for batches
acceptedBatches, rejectedBatches := e.nodeProposalValidation.OnTickBatch(t)
for _, p := range acceptedBatches {
e.log.Info("proposal has been validated by nodes, starting now",
logging.String("proposal-id", p.ID))
p.Open()
e.broker.Send(events.NewProposalEventFromProto(ctx, p.ToProto()))
proposalsEvents := []events.Event{}
for _, v := range p.Proposals {
proposalsEvents = append(proposalsEvents, events.NewProposalEvent(ctx, *v))
}
e.broker.SendBatch(proposalsEvents)
e.startValidatedBatchProposal(p) // can't fail, and proposal has been validated at an ulterior time
}
for _, p := range rejectedBatches {
e.log.Info("proposal has not been validated by nodes",
logging.String("proposal-id", p.ID))
p.Reject(types.ProposalErrorNodeValidationFailed)
e.broker.Send(events.NewProposalEventFromProto(ctx, p.ToProto()))
proposalsEvents := []events.Event{}
for _, v := range p.Proposals {
proposalsEvents = append(proposalsEvents, events.NewProposalEvent(ctx, *v))
}
e.broker.SendBatch(proposalsEvents)
for _, v := range p.Proposals {
// if it's an asset proposal we need to update it's
// state in the asset engine
switch v.Terms.Change.GetTermType() {
case types.ProposalTermsTypeNewAsset:
e.assets.SetRejected(ctx, v.ID)
}
}
}
toBeEnacted := []*ToEnact{}
for i, ep := range preparedToEnact {
// this is the new market proposal, and should already be in the slice
prop := *ep.ProposalData()
propType := prop.Terms.Change.GetTermType()
id := prop.ID
if propType == types.ProposalTermsTypeNewMarket || propType == types.ProposalTermsTypeUpdateMarket {
if propType == types.ProposalTermsTypeUpdateMarket {
id = prop.Terms.GetUpdateMarket().MarketID
}
// before trying to enact a successor market proposal, check if the market wasn't rejected due
// to another successor leaving opening auction
if _, err := e.markets.GetMarketState(id); err != nil {
if nm := prop.Terms.GetNewMarket(); nm != nil && nm.Successor() != nil {
prop.RejectWithErr(types.ProposalErrorInvalidSuccessorMarket, ErrParentMarketSucceededByCompeting)
e.broker.Send(events.NewProposalEvent(ctx, *prop.Proposal))
continue
}
e.log.Error("could not get state of market %s", logging.String("market-id", id))
continue
}
}
e.enactedProposals = append(e.enactedProposals, &prop)
toBeEnacted = append(toBeEnacted, preparedToEnact[i])
}
// now we iterate over all proposal ids to remove them from the list
for _, id := range toBeRemoved {
e.removeActiveProposalByID(ctx, id)
}
// add these passed proposals from batch to prepare them for enactment
e.activeProposals = append(e.activeProposals, addToActiveProposals...)
// flush here for now
return toBeEnacted, voteClosed
}
func (e *Engine) getProposal(id string) (*proposal, bool) {
for _, v := range e.activeProposals {
if v.ID == id {
return v, true
}
}
p, ok := e.nodeProposalValidation.getProposal(id)
if !ok {
return nil, false
}
return p.proposal, true
}
// SubmitProposal submits new proposal to the governance engine so it can be voted on, passed and enacted.
// Only open can be submitted and validated at this point. No further validation happens.
func (e *Engine) SubmitProposal(
ctx context.Context,
psub types.ProposalSubmission,
id, party string,
) (ts *ToSubmit, err error) {
if _, ok := e.getProposal(id); ok {
return nil, ErrProposalIsDuplicate // state is not allowed to change externally
}
p := &types.Proposal{
ID: id,
Timestamp: e.timeService.GetTimeNow().UnixNano(),
Party: party,
State: types.ProposalStateOpen,
Terms: psub.Terms,
Reference: psub.Reference,
Rationale: psub.Rationale,
RequiredMajority: num.DecimalZero(),
RequiredParticipation: num.DecimalZero(),
RequiredLPMajority: num.DecimalZero(),
RequiredLPParticipation: num.DecimalZero(),
}
defer func() {
e.broker.Send(events.NewProposalEvent(ctx, *p))
}()
params, err := e.getProposalParams(p.Terms.Change)
if err != nil {
p.RejectWithErr(types.ProposalErrorUnknownType, err)
return nil, err
}
if perr, err := e.validateOpenProposal(p, params); err != nil {
p.RejectWithErr(perr, err)
if e.log.IsDebug() {
e.log.Debug("Proposal rejected",
logging.String("proposal-id", p.ID),
logging.String("proposal details", p.String()),
)
}
return nil, err
}
// now if it's a 2 steps proposal, start the node votes
if e.isTwoStepsProposal(p) {
p.WaitForNodeVote()
if err := e.startTwoStepsProposal(ctx, p); err != nil {
p.RejectWithErr(types.ProposalErrorNodeValidationFailed, err)
if e.log.IsDebug() {
e.log.Debug("Proposal rejected",
logging.String("proposal-id", p.ID),
logging.String("proposal details", p.String()),
)
}
return nil, err
}
} else {
e.startProposal(p)
}
return e.intoToSubmit(ctx, p, &enactmentTime{current: p.Terms.EnactmentTimestamp}, false)
}
func (e *Engine) RejectProposal(
ctx context.Context, p *types.Proposal, r types.ProposalError, errorDetails error,
) error {
if _, ok := e.getProposal(p.ID); !ok {
return ErrProposalDoesNotExist
}
e.rejectProposal(ctx, p, r, errorDetails)
e.broker.Send(events.NewProposalEvent(ctx, *p))
return nil
}
// FinaliseEnactment receives the enact proposal and updates the state in our enactedProposal
// list to have the current state of the proposals. This is entirely so that when we restore
// from a snapshot we can propagate the proposal with the latest state back into the API service.
func (e *Engine) FinaliseEnactment(ctx context.Context, prop *types.Proposal) {
// find the proposal so we can update the state after enactment
for _, enacted := range e.enactedProposals {
if enacted.ID == prop.ID {
enacted.State = prop.State
break
}
}
e.broker.Send(events.NewProposalEvent(ctx, *prop))
}
func (e *Engine) rejectProposal(ctx context.Context, p *types.Proposal, r types.ProposalError, errorDetails error) {
e.removeActiveProposalByID(ctx, p.ID)
p.RejectWithErr(r, errorDetails)
}
// toSubmit build the return response for the SubmitProposal
// method.
func (e *Engine) intoToSubmit(ctx context.Context, p *types.Proposal, enct *enactmentTime, restore bool) (*ToSubmit, error) {
tsb := &ToSubmit{p: p}
switch p.Terms.Change.GetTermType() {
case types.ProposalTermsTypeNewMarket:
// use to calculate the auction duration
// which is basically enacttime - closetime
// FIXME(): normally we should use the closetime
// but this would not play well with the MarketAuctionState stuff
// for now we start the auction as of now.
newMarket := p.Terms.GetNewMarket()
var parent *types.Market
if suc := newMarket.Successor(); suc != nil {
pm, ok := e.markets.GetMarket(suc.ParentID, true)
if !ok {
if !restore {
e.rejectProposal(ctx, p, types.ProposalErrorInvalidSuccessorMarket, ErrParentMarketDoesNotExist)
return nil, fmt.Errorf("%w, %v", ErrParentMarketDoesNotExist, types.ProposalErrorInvalidSuccessorMarket)
}
} else {
parent = &pm
}
// proposal to succeed a market that was already succeeded
// on restore, the parent market may be succeeded and the restored market may have own state (ie was the successor)
// So skip this check when restoring markets from checkpoints
if !restore && e.markets.IsSucceeded(suc.ParentID) {
e.rejectProposal(ctx, p, types.ProposalErrorInvalidSuccessorMarket, ErrParentMarketAlreadySucceeded)
return nil, fmt.Errorf("%w, %v", ErrParentMarketAlreadySucceeded, types.ProposalErrorInvalidSuccessorMarket)
}
// restore can be true while parent == nil. This is fine, though
}
now := e.timeService.GetTimeNow()
closeTime := time.Unix(p.Terms.ClosingTimestamp, 0)
enactTime := time.Unix(p.Terms.EnactmentTimestamp, 0)
auctionDuration := enactTime.Sub(closeTime)
if perr, err := validateNewMarketChange(newMarket, e.assets, true, e.netp, auctionDuration, enct, parent, now, restore); err != nil {
e.rejectProposal(ctx, p, perr, err)
return nil, fmt.Errorf("%w, %v", err, perr)
}
// closeTime = e.timeService.GetTimeNow().Round(time.Second)
// auctionDuration = enactTime.Sub(closeTime)
mkt, perr, err := buildMarketFromProposal(p.ID, newMarket, e.netp, auctionDuration)
if err != nil {
e.rejectProposal(ctx, p, perr, err)
return nil, fmt.Errorf("%w, %v", err, perr)
}
tsb.m = &ToSubmitNewMarket{
m: mkt,
}
case types.ProposalTermsTypeNewSpotMarket:
closeTime := time.Unix(p.Terms.ClosingTimestamp, 0)
enactTime := time.Unix(p.Terms.EnactmentTimestamp, 0)
newMarket := p.Terms.GetNewSpotMarket()
auctionDuration := enactTime.Sub(closeTime)
if perr, err := validateNewSpotMarketChange(newMarket, e.assets, true, e.netp, auctionDuration, enct); err != nil {
e.rejectProposal(ctx, p, perr, err)
return nil, fmt.Errorf("%w, %v", err, perr)
}
mkt, perr, err := buildSpotMarketFromProposal(p.ID, newMarket, e.netp, auctionDuration)
if err != nil {
e.rejectProposal(ctx, p, perr, err)
return nil, fmt.Errorf("%w, %v", err, perr)
}
tsb.s = &ToSubmitNewSpotMarket{
m: mkt,
}
}
return tsb, nil
}
func (e *Engine) startProposal(p *types.Proposal) {
e.activeProposals = append(e.activeProposals, &proposal{
Proposal: p,
yes: map[string]*types.Vote{},
no: map[string]*types.Vote{},
invalidVotes: map[string]*types.Vote{},
})
}
func (e *Engine) startValidatedProposal(p *proposal) {
e.activeProposals = append(e.activeProposals, p)
}
func (e *Engine) startValidatedBatchProposal(p *batchProposal) {
e.activeBatchProposals[p.ID] = p
}
func (e *Engine) startTwoStepsProposal(ctx context.Context, p *types.Proposal) error {
return e.nodeProposalValidation.Start(ctx, p)
}
func (e *Engine) startTwoStepsBatchProposal(ctx context.Context, p *types.BatchProposal) error {
return e.nodeProposalValidation.StartBatch(ctx, p)
}
func (e *Engine) isTwoStepsProposal(p *types.Proposal) bool {
return e.nodeProposalValidation.IsNodeValidationRequired(p)
}
// isAutoEnactableProposal returns true if the proposal is of a type that has no on-chain enactment
// and so can be automatically enacted without needing to care for the enactment timestamps.
func (e *Engine) isAutoEnactableProposal(p *types.Proposal) bool {
switch p.Terms.Change.GetTermType() {
case types.ProposalTermsTypeNewFreeform:
return true
}
return false
}
func (e *Engine) getProposalParams(proposalTerm types.ProposalTerm) (*types.ProposalParameters, error) {
switch proposalTerm.GetTermType() {
case types.ProposalTermsTypeNewMarket:
return e.getNewMarketProposalParameters(), nil
case types.ProposalTermsTypeUpdateMarket:
return e.getUpdateMarketProposalParameters(), nil
case types.ProposalTermsTypeNewAsset:
return e.getNewAssetProposalParameters(), nil
case types.ProposalTermsTypeUpdateAsset:
return e.getUpdateAssetProposalParameters(), nil
case types.ProposalTermsTypeUpdateNetworkParameter:
return e.getUpdateNetworkParameterProposalParameters(), nil
case types.ProposalTermsTypeNewFreeform:
return e.getNewFreeformProposalParameters(), nil
case types.ProposalTermsTypeNewTransfer:
return e.getNewTransferProposalParameters(), nil
case types.ProposalTermsTypeCancelTransfer:
// for governance transfer cancellation reuse the governance transfer proposal params
return e.getNewTransferProposalParameters(), nil
case types.ProposalTermsTypeNewSpotMarket:
return e.getNewSpotMarketProposalParameters(), nil
case types.ProposalTermsTypeUpdateSpotMarket:
return e.getUpdateSpotMarketProposalParameters(), nil
case types.ProposalTermsTypeUpdateMarketState:
// reusing market update net params
return e.getUpdateMarketStateProposalParameters(), nil
case types.ProposalTermsTypeUpdateReferralProgram:
return e.getReferralProgramNetworkParameters(), nil
case types.ProposalTermsTypeUpdateVolumeDiscountProgram:
return e.getVolumeDiscountProgramNetworkParameters(), nil
default:
return nil, ErrUnsupportedProposalType
}
}
func (e *Engine) validateOpenProposal(proposal *types.Proposal, params *types.ProposalParameters) (types.ProposalError, error) {
// assign all requirement to the proposal itself.
proposal.RequiredMajority = params.RequiredMajority
proposal.RequiredParticipation = params.RequiredParticipation
proposal.RequiredLPMajority = params.RequiredMajorityLP
proposal.RequiredLPParticipation = params.RequiredParticipationLP
now := e.timeService.GetTimeNow()
closeTime := time.Unix(proposal.Terms.ClosingTimestamp, 0)
minCloseTime := now.Add(params.MinClose)
if closeTime.Before(minCloseTime) {
e.log.Debug("proposal close time is too soon",
logging.Time("expected-min", minCloseTime),
logging.Time("provided", closeTime),
logging.String("id", proposal.ID))
return types.ProposalErrorCloseTimeTooSoon,
fmt.Errorf("proposal closing time too soon, expected > %v, got %v", minCloseTime.UTC(), closeTime.UTC())
}
maxCloseTime := now.Add(params.MaxClose)
if closeTime.After(maxCloseTime) {
e.log.Debug("proposal close time is too late",
logging.Time("expected-max", maxCloseTime),
logging.Time("provided", closeTime),
logging.String("id", proposal.ID))
return types.ProposalErrorCloseTimeTooLate,
fmt.Errorf("proposal closing time too late, expected < %v, got %v", maxCloseTime.UTC(), closeTime.UTC())
}
enactTime := time.Unix(proposal.Terms.EnactmentTimestamp, 0)
minEnactTime := now.Add(params.MinEnact)
if !e.isAutoEnactableProposal(proposal) && enactTime.Before(minEnactTime) {
e.log.Debug("proposal enact time is too soon",
logging.Time("expected-min", minEnactTime),
logging.Time("provided", enactTime),
logging.String("id", proposal.ID))
return types.ProposalErrorEnactTimeTooSoon,
fmt.Errorf("proposal enactment time too soon, expected > %v, got %v", minEnactTime.UTC(), enactTime.UTC())
}
maxEnactTime := now.Add(params.MaxEnact)
if !e.isAutoEnactableProposal(proposal) && enactTime.After(maxEnactTime) {
e.log.Debug("proposal enact time is too late",
logging.Time("expected-max", maxEnactTime),
logging.Time("provided", enactTime),
logging.String("id", proposal.ID))
return types.ProposalErrorEnactTimeTooLate,
fmt.Errorf("proposal enactment time too late, expected < %v, got %v", maxEnactTime.UTC(), enactTime.UTC())
}
if e.isTwoStepsProposal(proposal) {
validationTime := time.Unix(proposal.Terms.ValidationTimestamp, 0)
if closeTime.Before(validationTime) {
e.log.Debug("proposal closing time can't be smaller or equal than validation time",
logging.Time("closing-time", closeTime),
logging.Time("validation-time", validationTime),
logging.String("id", proposal.ID))
return types.ProposalErrorIncompatibleTimestamps,
fmt.Errorf("proposal closing time cannot be before validation time, expected > %v got %v", validationTime.UTC(), closeTime.UTC())
}
if closeTime.Before(now) {
e.log.Debug("proposal validation time can't be in the past",
logging.Time("now", now),
logging.Time("validation-time", validationTime),
logging.String("id", proposal.ID))
return types.ProposalErrorIncompatibleTimestamps,
fmt.Errorf("proposal validation time cannot be in the past, expected > %v got %v", now.UTC(), validationTime.UTC())
}
}
if !e.isAutoEnactableProposal(proposal) && enactTime.Before(closeTime) {
e.log.Debug("proposal enactment time can't be smaller than closing time",
logging.Time("enactment-time", enactTime),
logging.Time("closing-time", closeTime),
logging.String("id", proposal.ID))
return types.ProposalErrorIncompatibleTimestamps,
fmt.Errorf("proposal enactment time cannot be before closing time, expected > %v got %v", closeTime.UTC(), enactTime.UTC())
}
checkProposerToken := true
if proposal.IsMarketUpdate() || proposal.IsMarketStateUpdate() {
marketID := ""
if proposal.Terms.GetMarketStateUpdate() != nil {
marketID = proposal.Terms.GetMarketStateUpdate().Changes.MarketID
} else {
marketID = proposal.MarketUpdate().MarketID
}
proposalError, err := e.validateMarketUpdate(proposal.ID, marketID, proposal.Party, params)
if err != nil && proposalError != types.ProposalErrorInsufficientEquityLikeShare {
return proposalError, err
}
checkProposerToken = proposalError == types.ProposalErrorInsufficientEquityLikeShare
}
if proposal.IsSpotMarketUpdate() {
proposalError, err := e.validateSpotMarketUpdate(proposal, params)
if err != nil && proposalError != types.ProposalErrorInsufficientEquityLikeShare {
return proposalError, err
}
checkProposerToken = proposalError == types.ProposalErrorInsufficientEquityLikeShare
}
if checkProposerToken {
proposerTokens, err := getGovernanceTokens(e.accs, proposal.Party)
if err != nil {
e.log.Debug("proposer have no governance token",
logging.PartyID(proposal.Party),
logging.ProposalID(proposal.ID))
return types.ProposalErrorInsufficientTokens, err
}
if proposerTokens.LT(params.MinProposerBalance) {
e.log.Debug("proposer have insufficient governance token",
logging.BigUint("expect-balance", params.MinProposerBalance),
logging.String("proposer-balance", proposerTokens.String()),
logging.PartyID(proposal.Party),
logging.ProposalID(proposal.ID))
return types.ProposalErrorInsufficientTokens,
fmt.Errorf("proposer have insufficient governance token, expected >= %v got %v", params.MinProposerBalance, proposerTokens)
}
}
return e.validateChange(proposal.Terms)
}
func (e *Engine) ValidatorKeyChanged(ctx context.Context, oldKey, newKey string) {
for _, p := range e.activeProposals {
e.updateValidatorKey(ctx, p.yes, oldKey, newKey)
e.updateValidatorKey(ctx, p.no, oldKey, newKey)
e.updateValidatorKey(ctx, p.invalidVotes, oldKey, newKey)
}
}
// AddVote adds a vote onto an existing active proposal.
func (e *Engine) AddVote(ctx context.Context, cmd types.VoteSubmission, party string) error {
proposal, found := e.getProposal(cmd.ProposalID)
batchProposal, batchFound := e.getBatchProposal(cmd.ProposalID)
if found {
if !proposal.IsOpenForVotes() {
return ErrProposalNotOpenForVotes
}
return e.addVote(ctx, cmd, proposal, party)
}
if batchFound {
if !batchProposal.IsOpenForVotes() {
return ErrProposalNotOpenForVotes
}
return e.addBatchVote(ctx, batchProposal, cmd, party)
}
return ErrProposalDoesNotExist
}
func (e *Engine) addVote(ctx context.Context, cmd types.VoteSubmission, proposal *proposal, party string) error {
params, err := e.getProposalParams(proposal.Terms.Change)
if err != nil {
return err
}
if err := e.canVote(proposal.Proposal, params, party); err != nil {
e.log.Debug("invalid vote submission",
logging.PartyID(party),
logging.String("vote", cmd.String()),
logging.Error(err),
)
return err
}
vote := types.Vote{
PartyID: party,
ProposalID: cmd.ProposalID,
Value: cmd.Value,
Timestamp: e.timeService.GetTimeNow().UnixNano(),
TotalGovernanceTokenBalance: getTokensBalance(e.accs, party),
TotalGovernanceTokenWeight: num.DecimalZero(),
TotalEquityLikeShareWeight: num.DecimalZero(),
}
if proposal.IsMarketUpdate() {
mID := proposal.MarketUpdate().MarketID
vote.TotalEquityLikeShareWeight, _ = e.markets.GetEquityLikeShareForMarketAndParty(mID, party)
}
if err := proposal.AddVote(vote); err != nil {
return fmt.Errorf("couldn't cast the vote: %w", err)
}
if e.log.IsDebug() {
e.log.Debug("vote submission accepted",
logging.PartyID(party),
logging.String("vote", cmd.String()),
)
}
e.broker.Send(events.NewVoteEvent(ctx, vote))
return nil
}
func (e *Engine) canVote(
proposal *types.Proposal,
params *types.ProposalParameters,
party string,
) error {
voterTokens, err := getGovernanceTokens(e.accs, party)
if err != nil {
return err
}
if proposal.IsMarketUpdate() || proposal.IsSpotMarketUpdate() {
var mktID string
if proposal.IsMarketUpdate() {
mktID = proposal.MarketUpdate().MarketID
} else {
mktID = proposal.SpotMarketUpdate().MarketID
}
partyELS, _ := e.markets.GetEquityLikeShareForMarketAndParty(mktID, party)
if partyELS.IsZero() && voterTokens.IsZero() {
return ErrVoterInsufficientTokensAndEquityLikeShare
}
// If he is not voting using his equity-like share, he should at least
// have enough tokens.
if partyELS.IsZero() && voterTokens.LT(params.MinVoterBalance) {
return ErrVoterInsufficientTokens
}
} else {
if voterTokens.LT(params.MinVoterBalance) {
return ErrVoterInsufficientTokens
}
}
return nil
}
func (e *Engine) validateMarketUpdate(ID, marketID, party string, params *types.ProposalParameters) (types.ProposalError, error) {
if !e.markets.MarketExists(marketID) {
e.log.Debug("market does not exist",
logging.MarketID(marketID),
logging.PartyID(party),
logging.ProposalID(ID))
return types.ProposalErrorInvalidMarket, ErrMarketDoesNotExist
}
for _, p := range e.activeProposals {
if p.ID == marketID && p.IsOpen() {
return types.ProposalErrorInvalidMarket, ErrMarketProposalStillOpen
}
}
partyELS, _ := e.markets.GetEquityLikeShareForMarketAndParty(marketID, party)
if partyELS.LessThan(params.MinEquityLikeShare) {
e.log.Debug("proposer have insufficient equity-like share",
logging.String("expect-balance", params.MinEquityLikeShare.String()),