-
Notifications
You must be signed in to change notification settings - Fork 324
/
handlers.go
890 lines (783 loc) · 31 KB
/
handlers.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
// Copyright (c) 2022 IoTeX Foundation
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package staking
import (
"context"
"math/big"
"time"
"github.com/iotexproject/go-pkgs/hash"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-proto/golang/iotextypes"
"github.com/pkg/errors"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/action/protocol"
accountutil "github.com/iotexproject/iotex-core/action/protocol/account/util"
"github.com/iotexproject/iotex-core/pkg/util/byteutil"
"github.com/iotexproject/iotex-core/state"
)
// constants
const (
HandleCreateStake = "createStake"
HandleUnstake = "unstake"
HandleWithdrawStake = "withdrawStake"
HandleChangeCandidate = "changeCandidate"
HandleTransferStake = "transferStake"
HandleDepositToStake = "depositToStake"
HandleRestake = "restake"
HandleCandidateRegister = "candidateRegister"
HandleCandidateUpdate = "candidateUpdate"
)
const _withdrawWaitingTime = 14 * 24 * time.Hour // to maintain backward compatibility with r0.11 code
// Errors and vars
var (
ErrNilParameters = errors.New("parameter is nil")
errCandNotExist = &handleError{
err: ErrInvalidOwner,
failureStatus: iotextypes.ReceiptStatus_ErrCandidateNotExist,
}
)
type handleError struct {
err error
failureStatus iotextypes.ReceiptStatus
}
func (h *handleError) Error() string {
return h.err.Error()
}
func (h *handleError) ReceiptStatus() uint64 {
return uint64(h.failureStatus)
}
func (p *Protocol) handleCreateStake(ctx context.Context, act *action.CreateStake, csm CandidateStateManager,
) (*receiptLog, []*action.TransactionLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
blkCtx := protocol.MustGetBlockCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleCreateStake, featureCtx.NewStakingReceiptFormat)
staker, fetchErr := fetchCaller(ctx, csm, act.Amount())
if fetchErr != nil {
return log, nil, fetchErr
}
// Create new bucket and bucket index
candidate := csm.GetByName(act.Candidate())
if candidate == nil {
return log, nil, errCandNotExist
}
bucket := NewVoteBucket(candidate.Owner, actionCtx.Caller, act.Amount(), act.Duration(), blkCtx.BlockTimeStamp, act.AutoStake())
bucketIdx, err := csm.putBucketAndIndex(bucket)
if err != nil {
return log, nil, err
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucketIdx), candidate.Owner.Bytes())
// update candidate
weightedVote := p.calculateVoteWeight(bucket, false)
if err := candidate.AddVote(weightedVote); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to add vote for candidate %s", candidate.Owner.String()),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketAmount,
}
}
if err := csm.Upsert(candidate); err != nil {
return log, nil, csmErrorToHandleError(candidate.Owner.String(), err)
}
// update bucket pool
if err := csm.DebitBucketPool(act.Amount(), true); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to update staking bucket pool %s", err.Error()),
failureStatus: iotextypes.ReceiptStatus_ErrWriteAccount,
}
}
// update staker balance
if err := staker.SubBalance(act.Amount()); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to update the balance of staker %s", actionCtx.Caller.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
// put updated staker's account state to trie
if err := accountutil.StoreAccount(csm.SM(), actionCtx.Caller, staker); err != nil {
return log, nil, errors.Wrapf(err, "failed to store account %s", actionCtx.Caller.String())
}
log.AddAddress(candidate.Owner)
log.AddAddress(actionCtx.Caller)
log.SetData(byteutil.Uint64ToBytesBigEndian(bucketIdx))
return log, []*action.TransactionLog{
{
Type: iotextypes.TransactionLogType_CREATE_BUCKET,
Sender: actionCtx.Caller.String(),
Recipient: address.StakingBucketPoolAddr,
Amount: act.Amount(),
},
}, nil
}
func (p *Protocol) handleUnstake(ctx context.Context, act *action.Unstake, csm CandidateStateManager,
) (*receiptLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
blkCtx := protocol.MustGetBlockCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleUnstake, featureCtx.NewStakingReceiptFormat)
_, fetchErr := fetchCaller(ctx, csm, big.NewInt(0))
if fetchErr != nil {
return log, fetchErr
}
bucket, fetchErr := p.fetchBucket(csm, actionCtx.Caller, act.BucketIndex(), true, true)
if fetchErr != nil {
return log, fetchErr
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucket.Index), bucket.Candidate.Bytes())
candidate := csm.GetByOwner(bucket.Candidate)
if candidate == nil {
return log, errCandNotExist
}
if featureCtx.CannotUnstakeAgain && bucket.isUnstaked() {
return log, &handleError{
err: errors.New("unstake an already unstaked bucket again not allowed"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
if bucket.AutoStake {
return log, &handleError{
err: errors.New("AutoStake should be disabled first in order to unstake"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
if blkCtx.BlockTimeStamp.Before(bucket.StakeStartTime.Add(bucket.StakedDuration)) {
return log, &handleError{
err: errors.New("bucket is not ready to be unstaked"),
failureStatus: iotextypes.ReceiptStatus_ErrUnstakeBeforeMaturity,
}
}
// update bucket
bucket.UnstakeStartTime = blkCtx.BlockTimeStamp.UTC()
if err := csm.updateBucket(act.BucketIndex(), bucket); err != nil {
return log, errors.Wrapf(err, "failed to update bucket for voter %s", bucket.Owner.String())
}
weightedVote := p.calculateVoteWeight(bucket, csm.ContainsSelfStakingBucket(act.BucketIndex()))
if err := candidate.SubVote(weightedVote); err != nil {
return log, &handleError{
err: errors.Wrapf(err, "failed to subtract vote for candidate %s", bucket.Candidate.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
// clear candidate's self stake if the bucket is self staking
if csm.ContainsSelfStakingBucket(act.BucketIndex()) {
candidate.SelfStake = big.NewInt(0)
}
if err := csm.Upsert(candidate); err != nil {
return log, csmErrorToHandleError(candidate.Owner.String(), err)
}
log.AddAddress(actionCtx.Caller)
return log, nil
}
func (p *Protocol) handleWithdrawStake(ctx context.Context, act *action.WithdrawStake, csm CandidateStateManager,
) (*receiptLog, []*action.TransactionLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
blkCtx := protocol.MustGetBlockCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleWithdrawStake, featureCtx.NewStakingReceiptFormat)
withdrawer, fetchErr := fetchCaller(ctx, csm, big.NewInt(0))
if fetchErr != nil {
return log, nil, fetchErr
}
bucket, fetchErr := p.fetchBucket(csm, actionCtx.Caller, act.BucketIndex(), true, true)
if fetchErr != nil {
return log, nil, fetchErr
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucket.Index), bucket.Candidate.Bytes())
// check unstake time
cannotWithdraw := bucket.UnstakeStartTime.Unix() == 0
if featureCtx.CannotUnstakeAgain {
cannotWithdraw = !bucket.isUnstaked()
}
if cannotWithdraw {
return log, nil, &handleError{
err: errors.New("bucket has not been unstaked"),
failureStatus: iotextypes.ReceiptStatus_ErrWithdrawBeforeUnstake,
}
}
withdrawWaitTime := p.config.WithdrawWaitingPeriod
if !featureCtx.NewStakingReceiptFormat {
withdrawWaitTime = _withdrawWaitingTime
}
if blkCtx.BlockTimeStamp.Before(bucket.UnstakeStartTime.Add(withdrawWaitTime)) {
return log, nil, &handleError{
err: errors.New("stake is not ready to withdraw"),
failureStatus: iotextypes.ReceiptStatus_ErrWithdrawBeforeMaturity,
}
}
// delete bucket and bucket index
if err := csm.delBucketAndIndex(bucket.Owner, bucket.Candidate, act.BucketIndex()); err != nil {
return log, nil, errors.Wrapf(err, "failed to delete bucket for candidate %s", bucket.Candidate.String())
}
// update bucket pool
if err := csm.CreditBucketPool(bucket.StakedAmount); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to update staking bucket pool %s", err.Error()),
failureStatus: iotextypes.ReceiptStatus_ErrWriteAccount,
}
}
// update withdrawer balance
if err := withdrawer.AddBalance(bucket.StakedAmount); err != nil {
return log, nil, errors.Wrapf(err, "failed to add balance %s", bucket.StakedAmount)
}
// put updated withdrawer's account state to trie
if err := accountutil.StoreAccount(csm.SM(), actionCtx.Caller, withdrawer); err != nil {
return log, nil, errors.Wrapf(err, "failed to store account %s", actionCtx.Caller.String())
}
log.AddAddress(actionCtx.Caller)
if featureCtx.CannotUnstakeAgain {
log.SetData(bucket.StakedAmount.Bytes())
}
return log, []*action.TransactionLog{
{
Type: iotextypes.TransactionLogType_WITHDRAW_BUCKET,
Sender: address.StakingBucketPoolAddr,
Recipient: actionCtx.Caller.String(),
Amount: bucket.StakedAmount,
},
}, nil
}
func (p *Protocol) handleChangeCandidate(ctx context.Context, act *action.ChangeCandidate, csm CandidateStateManager,
) (*receiptLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleChangeCandidate, featureCtx.NewStakingReceiptFormat)
_, fetchErr := fetchCaller(ctx, csm, big.NewInt(0))
if fetchErr != nil {
return log, fetchErr
}
candidate := csm.GetByName(act.Candidate())
if candidate == nil {
return log, errCandNotExist
}
bucket, fetchErr := p.fetchBucket(csm, actionCtx.Caller, act.BucketIndex(), true, false)
if fetchErr != nil {
return log, fetchErr
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucket.Index), bucket.Candidate.Bytes(), candidate.Owner.Bytes())
prevCandidate := csm.GetByOwner(bucket.Candidate)
if prevCandidate == nil {
return log, errCandNotExist
}
if featureCtx.CannotUnstakeAgain && bucket.isUnstaked() {
return log, &handleError{
err: errors.New("change candidate for an unstaked bucket not allowed"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
if featureCtx.CannotTranferToSelf && address.Equal(prevCandidate.Owner, candidate.Owner) {
// change to same candidate, do nothing
return log, &handleError{
err: errors.New("change to same candidate"),
failureStatus: iotextypes.ReceiptStatus_ErrCandidateAlreadyExist,
}
}
// update bucket index
if err := csm.delCandBucketIndex(bucket.Candidate, act.BucketIndex()); err != nil {
return log, errors.Wrapf(err, "failed to delete candidate bucket index for candidate %s", bucket.Candidate.String())
}
if err := csm.putCandBucketIndex(candidate.Owner, act.BucketIndex()); err != nil {
return log, errors.Wrapf(err, "failed to put candidate bucket index for candidate %s", candidate.Owner.String())
}
// update bucket
bucket.Candidate = candidate.Owner
if err := csm.updateBucket(act.BucketIndex(), bucket); err != nil {
return log, errors.Wrapf(err, "failed to update bucket for voter %s", bucket.Owner.String())
}
// update previous candidate
weightedVotes := p.calculateVoteWeight(bucket, false)
if err := prevCandidate.SubVote(weightedVotes); err != nil {
return log, &handleError{
err: errors.Wrapf(err, "failed to subtract vote for previous candidate %s", prevCandidate.Owner.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
if err := csm.Upsert(prevCandidate); err != nil {
return log, csmErrorToHandleError(prevCandidate.Owner.String(), err)
}
// update current candidate
if err := candidate.AddVote(weightedVotes); err != nil {
return log, &handleError{
err: errors.Wrapf(err, "failed to add vote for candidate %s", candidate.Owner.String()),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketAmount,
}
}
if err := csm.Upsert(candidate); err != nil {
return log, csmErrorToHandleError(candidate.Owner.String(), err)
}
log.AddAddress(candidate.Owner)
log.AddAddress(actionCtx.Caller)
return log, nil
}
func (p *Protocol) handleTransferStake(ctx context.Context, act *action.TransferStake, csm CandidateStateManager,
) (*receiptLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleTransferStake, featureCtx.NewStakingReceiptFormat)
_, fetchErr := fetchCaller(ctx, csm, big.NewInt(0))
if fetchErr != nil {
return log, fetchErr
}
newOwner := act.VoterAddress()
bucket, fetchErr := p.fetchBucket(csm, actionCtx.Caller, act.BucketIndex(), true, false)
if fetchErr != nil {
if featureCtx.ReturnFetchError ||
fetchErr.ReceiptStatus() != uint64(iotextypes.ReceiptStatus_ErrUnauthorizedOperator) {
return log, fetchErr
}
// check whether the payload contains a valid consignment transfer
if consignment, ok := p.handleConsignmentTransfer(csm, actionCtx, act, bucket); ok {
newOwner = consignment.Transferee()
} else {
return log, fetchErr
}
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucket.Index), act.VoterAddress().Bytes(), bucket.Candidate.Bytes())
if featureCtx.CannotTranferToSelf && address.Equal(newOwner, bucket.Owner) {
// change to same owner, do nothing
return log, &handleError{
err: errors.New("transfer to same owner"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
// update bucket index
if err := csm.delVoterBucketIndex(bucket.Owner, act.BucketIndex()); err != nil {
return log, errors.Wrapf(err, "failed to delete voter bucket index for voter %s", bucket.Owner.String())
}
if err := csm.putVoterBucketIndex(newOwner, act.BucketIndex()); err != nil {
return log, errors.Wrapf(err, "failed to put candidate bucket index for voter %s", act.VoterAddress().String())
}
// update bucket
bucket.Owner = newOwner
if err := csm.updateBucket(act.BucketIndex(), bucket); err != nil {
return log, errors.Wrapf(err, "failed to update bucket for voter %s", bucket.Owner.String())
}
log.AddAddress(actionCtx.Caller)
return log, nil
}
func (p *Protocol) handleConsignmentTransfer(
csm CandidateStateManager,
actCtx protocol.ActionCtx,
act *action.TransferStake,
bucket *VoteBucket) (action.Consignment, bool) {
if len(act.Payload()) == 0 {
return nil, false
}
// self-stake cannot be transferred
if csm.ContainsSelfStakingBucket(bucket.Index) {
return nil, false
}
con, err := action.NewConsignment(act.Payload())
if err != nil {
return nil, false
}
// a consignment transfer is valid if:
// (1) signer owns the bucket
// (2) designated transferee matches the action caller
// (3) designated asset ID matches bucket index
// (4) nonce matches the action caller's nonce
return con, address.Equal(con.Transferor(), bucket.Owner) &&
address.Equal(con.Transferee(), actCtx.Caller) &&
con.AssetID() == bucket.Index &&
con.TransfereeNonce() == actCtx.Nonce
}
func (p *Protocol) handleDepositToStake(ctx context.Context, act *action.DepositToStake, csm CandidateStateManager,
) (*receiptLog, []*action.TransactionLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleDepositToStake, featureCtx.NewStakingReceiptFormat)
depositor, fetchErr := fetchCaller(ctx, csm, act.Amount())
if fetchErr != nil {
return log, nil, fetchErr
}
bucket, fetchErr := p.fetchBucket(csm, actionCtx.Caller, act.BucketIndex(), false, true)
if fetchErr != nil {
return log, nil, fetchErr
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucket.Index), bucket.Owner.Bytes(), bucket.Candidate.Bytes())
if !bucket.AutoStake {
return log, nil, &handleError{
err: errors.New("deposit is only allowed on auto-stake bucket"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
candidate := csm.GetByOwner(bucket.Candidate)
if candidate == nil {
return log, nil, errCandNotExist
}
if featureCtx.CannotUnstakeAgain && bucket.isUnstaked() {
return log, nil, &handleError{
err: errors.New("deposit to an unstaked bucket not allowed"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
prevWeightedVotes := p.calculateVoteWeight(bucket, csm.ContainsSelfStakingBucket(act.BucketIndex()))
// update bucket
bucket.StakedAmount.Add(bucket.StakedAmount, act.Amount())
if err := csm.updateBucket(act.BucketIndex(), bucket); err != nil {
return log, nil, errors.Wrapf(err, "failed to update bucket for voter %s", bucket.Owner.String())
}
// update candidate
if err := candidate.SubVote(prevWeightedVotes); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to subtract vote for candidate %s", bucket.Candidate.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
weightedVotes := p.calculateVoteWeight(bucket, csm.ContainsSelfStakingBucket(act.BucketIndex()))
if err := candidate.AddVote(weightedVotes); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to add vote for candidate %s", candidate.Owner.String()),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketAmount,
}
}
if csm.ContainsSelfStakingBucket(act.BucketIndex()) {
if err := candidate.AddSelfStake(act.Amount()); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to add self stake for candidate %s", candidate.Owner.String()),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketAmount,
}
}
}
if err := csm.Upsert(candidate); err != nil {
return log, nil, csmErrorToHandleError(candidate.Owner.String(), err)
}
// update bucket pool
if err := csm.DebitBucketPool(act.Amount(), false); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to update staking bucket pool %s", err.Error()),
failureStatus: iotextypes.ReceiptStatus_ErrWriteAccount,
}
}
// update depositor balance
if err := depositor.SubBalance(act.Amount()); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to update the balance of depositor %s", actionCtx.Caller.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
// put updated depositor's account state to trie
if err := accountutil.StoreAccount(csm.SM(), actionCtx.Caller, depositor); err != nil {
return log, nil, errors.Wrapf(err, "failed to store account %s", actionCtx.Caller.String())
}
log.AddAddress(actionCtx.Caller)
return log, []*action.TransactionLog{
{
Type: iotextypes.TransactionLogType_DEPOSIT_TO_BUCKET,
Sender: actionCtx.Caller.String(),
Recipient: address.StakingBucketPoolAddr,
Amount: act.Amount(),
},
}, nil
}
func (p *Protocol) handleRestake(ctx context.Context, act *action.Restake, csm CandidateStateManager,
) (*receiptLog, error) {
actionCtx := protocol.MustGetActionCtx(ctx)
blkCtx := protocol.MustGetBlockCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleRestake, featureCtx.NewStakingReceiptFormat)
_, fetchErr := fetchCaller(ctx, csm, big.NewInt(0))
if fetchErr != nil {
return log, fetchErr
}
bucket, fetchErr := p.fetchBucket(csm, actionCtx.Caller, act.BucketIndex(), true, true)
if fetchErr != nil {
return log, fetchErr
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucket.Index), bucket.Candidate.Bytes())
candidate := csm.GetByOwner(bucket.Candidate)
if candidate == nil {
return log, errCandNotExist
}
if featureCtx.CannotUnstakeAgain && bucket.isUnstaked() {
return log, &handleError{
err: errors.New("restake an unstaked bucket not allowed"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
prevWeightedVotes := p.calculateVoteWeight(bucket, csm.ContainsSelfStakingBucket(act.BucketIndex()))
// update bucket
actDuration := time.Duration(act.Duration()) * 24 * time.Hour
if bucket.StakedDuration.Hours() > actDuration.Hours() {
// in case of reducing the duration
if bucket.AutoStake {
// if auto-stake on, user can't reduce duration
return log, &handleError{
err: errors.New("AutoStake should be disabled first in order to reduce duration"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
} else if blkCtx.BlockTimeStamp.Before(bucket.StakeStartTime.Add(bucket.StakedDuration)) {
// if auto-stake off and maturity is not enough
return log, &handleError{
err: errors.New("bucket is not ready to be able to reduce duration"),
failureStatus: iotextypes.ReceiptStatus_ErrReduceDurationBeforeMaturity,
}
}
}
bucket.StakedDuration = actDuration
bucket.StakeStartTime = blkCtx.BlockTimeStamp.UTC()
bucket.AutoStake = act.AutoStake()
if err := csm.updateBucket(act.BucketIndex(), bucket); err != nil {
return log, errors.Wrapf(err, "failed to update bucket for voter %s", bucket.Owner.String())
}
// update candidate
if err := candidate.SubVote(prevWeightedVotes); err != nil {
return log, &handleError{
err: errors.Wrapf(err, "failed to subtract vote for candidate %s", bucket.Candidate.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
weightedVotes := p.calculateVoteWeight(bucket, csm.ContainsSelfStakingBucket(act.BucketIndex()))
if err := candidate.AddVote(weightedVotes); err != nil {
return log, &handleError{
err: errors.Wrapf(err, "failed to add vote for candidate %s", candidate.Owner.String()),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketAmount,
}
}
if err := csm.Upsert(candidate); err != nil {
return log, csmErrorToHandleError(candidate.Owner.String(), err)
}
log.AddAddress(actionCtx.Caller)
return log, nil
}
func (p *Protocol) handleCandidateRegister(ctx context.Context, act *action.CandidateRegister, csm CandidateStateManager,
) (*receiptLog, []*action.TransactionLog, error) {
actCtx := protocol.MustGetActionCtx(ctx)
blkCtx := protocol.MustGetBlockCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleCandidateRegister, featureCtx.NewStakingReceiptFormat)
registrationFee := new(big.Int).Set(p.config.RegistrationConsts.Fee)
caller, fetchErr := fetchCaller(ctx, csm, new(big.Int).Add(act.Amount(), registrationFee))
if fetchErr != nil {
return log, nil, fetchErr
}
owner := actCtx.Caller
if act.OwnerAddress() != nil {
owner = act.OwnerAddress()
}
c := csm.GetByOwner(owner)
ownerExist := c != nil
// cannot collide with existing owner (with selfstake != 0)
if ownerExist && c.SelfStake.Cmp(big.NewInt(0)) != 0 {
return log, nil, &handleError{
err: ErrInvalidOwner,
failureStatus: iotextypes.ReceiptStatus_ErrCandidateAlreadyExist,
}
}
// cannot collide with existing name
if csm.ContainsName(act.Name()) && (!ownerExist || act.Name() != c.Name) {
return log, nil, &handleError{
err: ErrInvalidCanName,
failureStatus: iotextypes.ReceiptStatus_ErrCandidateConflict,
}
}
// cannot collide with existing operator address
if csm.ContainsOperator(act.OperatorAddress()) &&
(!ownerExist || !address.Equal(act.OperatorAddress(), c.Operator)) {
return log, nil, &handleError{
err: ErrInvalidOperator,
failureStatus: iotextypes.ReceiptStatus_ErrCandidateConflict,
}
}
bucket := NewVoteBucket(owner, owner, act.Amount(), act.Duration(), blkCtx.BlockTimeStamp, act.AutoStake())
bucketIdx, err := csm.putBucketAndIndex(bucket)
if err != nil {
return log, nil, err
}
log.AddTopics(byteutil.Uint64ToBytesBigEndian(bucketIdx), owner.Bytes())
c = &Candidate{
Owner: owner,
Operator: act.OperatorAddress(),
Reward: act.RewardAddress(),
Name: act.Name(),
Votes: p.calculateVoteWeight(bucket, true),
SelfStakeBucketIdx: bucketIdx,
SelfStake: act.Amount(),
}
if err := csm.Upsert(c); err != nil {
return log, nil, csmErrorToHandleError(owner.String(), err)
}
height, _ := csm.SM().Height()
if p.needToWriteCandsMap(height) {
csm.DirtyView().candCenter.base.recordOwner(c)
}
// update bucket pool
if err := csm.DebitBucketPool(act.Amount(), true); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to update staking bucket pool %s", err.Error()),
failureStatus: iotextypes.ReceiptStatus_ErrWriteAccount,
}
}
// update caller balance
if err := caller.SubBalance(act.Amount()); err != nil {
return log, nil, &handleError{
err: errors.Wrapf(err, "failed to update the balance of register %s", actCtx.Caller.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
// put updated caller's account state to trie
if err := accountutil.StoreAccount(csm.SM(), actCtx.Caller, caller); err != nil {
return log, nil, errors.Wrapf(err, "failed to store account %s", actCtx.Caller.String())
}
// put registrationFee to reward pool
if _, err = p.depositGas(ctx, csm.SM(), registrationFee); err != nil {
return log, nil, errors.Wrap(err, "failed to deposit gas")
}
log.AddAddress(owner)
log.AddAddress(actCtx.Caller)
log.SetData(byteutil.Uint64ToBytesBigEndian(bucketIdx))
return log, []*action.TransactionLog{
{
Type: iotextypes.TransactionLogType_CANDIDATE_SELF_STAKE,
Sender: actCtx.Caller.String(),
Recipient: address.StakingBucketPoolAddr,
Amount: act.Amount(),
},
{
Type: iotextypes.TransactionLogType_CANDIDATE_REGISTRATION_FEE,
Sender: actCtx.Caller.String(),
Recipient: address.RewardingPoolAddr,
Amount: registrationFee,
},
}, nil
}
func (p *Protocol) handleCandidateUpdate(ctx context.Context, act *action.CandidateUpdate, csm CandidateStateManager,
) (*receiptLog, error) {
actCtx := protocol.MustGetActionCtx(ctx)
featureCtx := protocol.MustGetFeatureCtx(ctx)
log := newReceiptLog(p.addr.String(), HandleCandidateUpdate, featureCtx.NewStakingReceiptFormat)
_, fetchErr := fetchCaller(ctx, csm, big.NewInt(0))
if fetchErr != nil {
return log, fetchErr
}
// only owner can update candidate
c := csm.GetByOwner(actCtx.Caller)
if c == nil {
return log, errCandNotExist
}
if len(act.Name()) != 0 {
c.Name = act.Name()
}
if act.OperatorAddress() != nil {
c.Operator = act.OperatorAddress()
}
if act.RewardAddress() != nil {
c.Reward = act.RewardAddress()
}
log.AddTopics(c.Owner.Bytes())
if err := csm.Upsert(c); err != nil {
return log, csmErrorToHandleError(c.Owner.String(), err)
}
height, _ := csm.SM().Height()
if p.needToWriteCandsMap(height) {
csm.DirtyView().candCenter.base.recordOwner(c)
}
log.AddAddress(actCtx.Caller)
return log, nil
}
func (p *Protocol) fetchBucket(
csm CandidateStateManager,
caller address.Address,
index uint64,
checkOwner bool,
allowSelfStaking bool,
) (*VoteBucket, ReceiptError) {
bucket, err := csm.getBucket(index)
if err != nil {
fetchErr := &handleError{
err: errors.Wrapf(err, "failed to fetch bucket by index %d", index),
failureStatus: iotextypes.ReceiptStatus_Failure,
}
if errors.Cause(err) == state.ErrStateNotExist {
fetchErr.failureStatus = iotextypes.ReceiptStatus_ErrInvalidBucketIndex
}
return nil, fetchErr
}
// ReceiptStatus_ErrUnauthorizedOperator indicates action caller is not bucket owner
// upon return, the action will be subject to check whether it contains a valid consignment transfer
// do NOT return this value in case changes are added in the future
if checkOwner && !address.Equal(bucket.Owner, caller) {
return bucket, &handleError{
err: errors.New("bucket owner does not match action caller"),
failureStatus: iotextypes.ReceiptStatus_ErrUnauthorizedOperator,
}
}
if !allowSelfStaking && csm.ContainsSelfStakingBucket(index) {
return bucket, &handleError{
err: errors.New("self staking bucket cannot be processed"),
failureStatus: iotextypes.ReceiptStatus_ErrInvalidBucketType,
}
}
return bucket, nil
}
func fetchCaller(ctx context.Context, csm CandidateStateManager, amount *big.Int) (*state.Account, ReceiptError) {
actionCtx := protocol.MustGetActionCtx(ctx)
accountCreationOpts := []state.AccountCreationOption{}
if protocol.MustGetFeatureCtx(ctx).CreateLegacyNonceAccount {
accountCreationOpts = append(accountCreationOpts, state.LegacyNonceAccountTypeOption())
}
caller, err := accountutil.LoadAccount(csm.SM(), actionCtx.Caller, accountCreationOpts...)
if err != nil {
return nil, &handleError{
err: errors.Wrapf(err, "failed to load the account of caller %s", actionCtx.Caller.String()),
failureStatus: iotextypes.ReceiptStatus_Failure,
}
}
gasFee := big.NewInt(0).Mul(actionCtx.GasPrice, big.NewInt(0).SetUint64(actionCtx.IntrinsicGas))
// check caller's balance
if !caller.HasSufficientBalance(new(big.Int).Add(amount, gasFee)) {
return nil, &handleError{
err: errors.Wrapf(state.ErrNotEnoughBalance, "caller %s balance not enough", actionCtx.Caller.String()),
failureStatus: iotextypes.ReceiptStatus_ErrNotEnoughBalance,
}
}
return caller, nil
}
func csmErrorToHandleError(caller string, err error) error {
hErr := &handleError{
err: errors.Wrapf(err, "failed to put candidate %s", caller),
}
switch errors.Cause(err) {
case ErrInvalidCanName:
hErr.failureStatus = iotextypes.ReceiptStatus_ErrCandidateConflict
return hErr
case ErrInvalidOperator:
hErr.failureStatus = iotextypes.ReceiptStatus_ErrCandidateConflict
return hErr
case ErrInvalidSelfStkIndex:
hErr.failureStatus = iotextypes.ReceiptStatus_ErrCandidateConflict
return hErr
case ErrInvalidAmount:
hErr.failureStatus = iotextypes.ReceiptStatus_ErrCandidateNotExist
return hErr
case ErrInvalidOwner:
hErr.failureStatus = iotextypes.ReceiptStatus_ErrCandidateNotExist
return hErr
case ErrInvalidReward:
hErr.failureStatus = iotextypes.ReceiptStatus_ErrCandidateNotExist
return hErr
default:
return err
}
}
// BucketIndexFromReceiptLog extracts bucket index from log
func BucketIndexFromReceiptLog(log *iotextypes.Log) (uint64, bool) {
if log == nil || len(log.Topics) < 2 {
return 0, false
}
h := hash.Hash160b([]byte(_protocolID))
addr, _ := address.FromBytes(h[:])
if log.ContractAddress != addr.String() {
return 0, false
}
switch hash.BytesToHash256(log.Topics[0]) {
case hash.BytesToHash256([]byte(HandleCreateStake)), hash.BytesToHash256([]byte(HandleUnstake)),
hash.BytesToHash256([]byte(HandleWithdrawStake)), hash.BytesToHash256([]byte(HandleChangeCandidate)),
hash.BytesToHash256([]byte(HandleTransferStake)), hash.BytesToHash256([]byte(HandleDepositToStake)),
hash.BytesToHash256([]byte(HandleRestake)), hash.BytesToHash256([]byte(HandleCandidateRegister)):
return byteutil.BytesToUint64BigEndian(log.Topics[1][24:]), true
default:
return 0, false
}
}