-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathmsg_server.go
771 lines (643 loc) · 28.1 KB
/
msg_server.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
package keeper
import (
"context"
"fmt"
"strings"
"time"
btcckpttypes "github.com/babylonlabs-io/babylon/x/btccheckpoint/types"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/babylonlabs-io/babylon/btcstaking"
bbn "github.com/babylonlabs-io/babylon/types"
"github.com/babylonlabs-io/babylon/x/btcstaking/types"
)
type msgServer struct {
Keeper
}
// NewMsgServerImpl returns an implementation of the MsgServer interface
// for the provided Keeper.
func NewMsgServerImpl(keeper Keeper) types.MsgServer {
return &msgServer{Keeper: keeper}
}
var _ types.MsgServer = msgServer{}
// UpdateParams updates the params
func (ms msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
if ms.authority != req.Authority {
return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", ms.authority, req.Authority)
}
if err := req.Params.Validate(); err != nil {
return nil, govtypes.ErrInvalidProposalMsg.Wrapf("invalid parameter: %v", err)
}
// ensure the min unbonding time is always larger than the checkpoint finalization timeout
ctx := sdk.UnwrapSDKContext(goCtx)
ckptFinalizationTime := ms.btccKeeper.GetParams(ctx).CheckpointFinalizationTimeout
unbondingTime := req.Params.UnbondingTimeBlocks
if unbondingTime <= ckptFinalizationTime {
return nil, govtypes.ErrInvalidProposalMsg.
Wrapf("the unbonding time %d must be larger than the checkpoint finalization timeout %d",
unbondingTime, ckptFinalizationTime)
}
if err := ms.SetParams(ctx, req.Params); err != nil {
return nil, err
}
return &types.MsgUpdateParamsResponse{}, nil
}
// CreateFinalityProvider creates a finality provider
func (ms msgServer) CreateFinalityProvider(goCtx context.Context, req *types.MsgCreateFinalityProvider) (*types.MsgCreateFinalityProviderResponse, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), types.MetricsKeyCreateFinalityProvider)
// ensure the finality provider address does not already exist
ctx := sdk.UnwrapSDKContext(goCtx)
// basic stateless checks
if err := req.ValidateBasic(); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
fpAddr, err := sdk.AccAddressFromBech32(req.Addr)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s: %v", req.Addr, err)
}
// verify proof of possession
if err := req.Pop.Verify(fpAddr, req.BtcPk, ms.btcNet); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid proof of possession: %v", err)
}
if err := ms.AddFinalityProvider(ctx, req); err != nil {
return nil, err
}
return &types.MsgCreateFinalityProviderResponse{}, nil
}
// EditFinalityProvider edits an existing finality provider
func (ms msgServer) EditFinalityProvider(goCtx context.Context, req *types.MsgEditFinalityProvider) (*types.MsgEditFinalityProviderResponse, error) {
// basic stateless checks
// NOTE: after this, description is guaranteed to be valid
if err := req.ValidateBasic(); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
// ensure commission rate is
// - at least the minimum commission rate in parameters, and
// - at most 1
if req.Commission.LT(ms.MinCommissionRate(goCtx)) {
return nil, types.ErrCommissionLTMinRate.Wrapf(
"cannot set finality provider commission to less than minimum rate of %s",
ms.MinCommissionRate(goCtx))
}
if req.Commission.GT(sdkmath.LegacyOneDec()) {
return nil, types.ErrCommissionGTMaxRate
}
fp, err := ms.GetFinalityProvider(goCtx, req.BtcPk)
if err != nil {
return nil, err
}
fpAddr, err := sdk.AccAddressFromBech32(req.Addr)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid address %s: %v", req.Addr, err)
}
// ensure the signer corresponds to the finality provider's Babylon address
if !strings.EqualFold(fpAddr.String(), fp.Addr) {
return nil, status.Errorf(codes.PermissionDenied, "the signer does not correspond to the finality provider's Babylon address")
}
// all good, update the finality provider and set back
fp.Description = req.Description
fp.Commission = req.Commission
ms.setFinalityProvider(goCtx, fp)
// notify subscriber
ctx := sdk.UnwrapSDKContext(goCtx)
if err := ctx.EventManager().EmitTypedEvent(types.NewEventFinalityProviderEdited(fp)); err != nil {
panic(fmt.Errorf("failed to emit EventFinalityProviderEdited event: %w", err))
}
return &types.MsgEditFinalityProviderResponse{}, nil
}
// isAllowListEnabled checks if the allow list is enabled at the given height
// allow list is enabled if AllowListExpirationHeight is larger than 0,
// and current block height is less than AllowListExpirationHeight
func (ms msgServer) isAllowListEnabled(ctx sdk.Context, p *types.Params) bool {
return p.AllowListExpirationHeight > 0 && uint64(ctx.BlockHeight()) < p.AllowListExpirationHeight
}
func (ms msgServer) getTimeInfoAndParams(
ctx sdk.Context,
parsedMsg *types.ParsedCreateDelegationMessage,
) (*DelegationTimeRangeInfo, *types.Params, uint32, error) {
if parsedMsg.IsIncludedOnBTC() {
// staking tx is already included on BTC
// 1. Validate inclusion proof and retrieve inclusion height
// 2. Get params for the validated inclusion height
btccParams := ms.btccKeeper.GetParams(ctx)
timeInfo, err := ms.VerifyInclusionProofAndGetHeight(
ctx,
btcutil.NewTx(parsedMsg.StakingTx.Transaction),
btccParams.BtcConfirmationDepth,
uint32(parsedMsg.StakingTime),
uint32(parsedMsg.UnbondingTime),
parsedMsg.StakingTxProofOfInclusion,
)
if err != nil {
return nil, nil, 0, fmt.Errorf("invalid inclusion proof: %w", err)
}
paramsByHeight, version, err := ms.GetParamsForBtcHeight(ctx, uint64(timeInfo.StartHeight))
if err != nil {
// this error can happen if we receive delegations which is included before
// first activation height we support
return nil, nil, 0, err
}
return timeInfo, paramsByHeight, version, nil
}
// staking tx is not included on BTC, retrieve params for the current tip height
// and return info about the tip
btcTip := ms.btclcKeeper.GetTipInfo(ctx)
paramsByHeight, version, err := ms.GetParamsForBtcHeight(ctx, uint64(btcTip.Height))
if err != nil {
return nil, nil, 0, err
}
return &DelegationTimeRangeInfo{
StartHeight: 0,
EndHeight: 0,
TipHeight: btcTip.Height,
}, paramsByHeight, version, nil
}
// CreateBTCDelegation creates a BTC delegation
func (ms msgServer) CreateBTCDelegation(goCtx context.Context, req *types.MsgCreateBTCDelegation) (*types.MsgCreateBTCDelegationResponse, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), types.MetricsKeyCreateBTCDelegation)
ctx := sdk.UnwrapSDKContext(goCtx)
// 1. Parse the message into better domain format
parsedMsg, err := types.ParseCreateDelegationMessage(req)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
// 2. Basic stateless checks
// - verify proof of possession
if err := parsedMsg.ParsedPop.Verify(parsedMsg.StakerAddress, parsedMsg.StakerPK.BIP340PubKey, ms.btcNet); err != nil {
return nil, types.ErrInvalidProofOfPossession.Wrap(err.Error())
}
// 3. Check if it is not duplicated staking tx
stakingTxHash := parsedMsg.StakingTx.Transaction.TxHash()
delegation := ms.getBTCDelegation(ctx, stakingTxHash)
if delegation != nil {
return nil, types.ErrReusedStakingTx.Wrapf("duplicated tx hash: %s", stakingTxHash.String())
}
// Ensure all finality providers
// - are known to Babylon,
// - at least 1 one of them is a Babylon finality provider,
// - are not slashed, and
// - their registered epochs are finalised
// and then check whether the BTC stake is restaked to FPs of consumers
// TODO: ensure the BTC delegation does not restake to too many finality providers
// (pending concrete design)
restakedToConsumers, err := ms.validateRestakedFPs(ctx, parsedMsg.FinalityProviderKeys.PublicKeysBbnFormat)
if err != nil {
return nil, err
}
// 5. Get params for the validated inclusion height either tip or inclusion height
timeInfo, params, paramsVersion, err := ms.getTimeInfoAndParams(ctx, parsedMsg)
if err != nil {
return nil, err
}
// 6. Validate the staking tx against the params
paramsValidationResult, err := types.ValidateParsedMessageAgainstTheParams(parsedMsg, params, ms.btcNet)
if err != nil {
return nil, err
}
// 7. if allow list is enabled we need to check whether staking transactions hash
// is in the allow list
if ms.isAllowListEnabled(ctx, params) {
if !ms.IsStakingTransactionAllowed(ctx, &stakingTxHash) {
return nil, types.ErrInvalidStakingTx.Wrapf("staking tx hash: %s, is not in the allow list", stakingTxHash.String())
}
}
// everything is good, if the staking tx is not included on BTC consume additinal
// gas
if !parsedMsg.IsIncludedOnBTC() {
ctx.GasMeter().ConsumeGas(params.DelegationCreationBaseGasFee, "delegation creation fee")
}
// 7.all good, construct BTCDelegation and insert BTC delegation
// NOTE: the BTC delegation does not have voting power yet. It will
// have voting power only when it receives a covenant signatures
newBTCDel := &types.BTCDelegation{
StakerAddr: parsedMsg.StakerAddress.String(),
BtcPk: parsedMsg.StakerPK.BIP340PubKey,
Pop: parsedMsg.ParsedPop,
FpBtcPkList: parsedMsg.FinalityProviderKeys.PublicKeysBbnFormat,
StakingTime: uint32(parsedMsg.StakingTime),
StartHeight: timeInfo.StartHeight,
EndHeight: timeInfo.EndHeight,
TotalSat: uint64(parsedMsg.StakingValue),
StakingTx: parsedMsg.StakingTx.TransactionBytes,
StakingOutputIdx: paramsValidationResult.StakingOutputIdx,
SlashingTx: types.NewBtcSlashingTxFromBytes(parsedMsg.StakingSlashingTx.TransactionBytes),
DelegatorSig: parsedMsg.StakerStakingSlashingTxSig.BIP340Signature,
UnbondingTime: uint32(parsedMsg.UnbondingTime),
CovenantSigs: nil, // NOTE: covenant signature will be submitted in a separate msg by covenant
BtcUndelegation: &types.BTCUndelegation{
UnbondingTx: parsedMsg.UnbondingTx.TransactionBytes,
SlashingTx: types.NewBtcSlashingTxFromBytes(parsedMsg.UnbondingSlashingTx.TransactionBytes),
DelegatorSlashingSig: parsedMsg.StakerUnbondingSlashingSig.BIP340Signature,
CovenantSlashingSigs: nil, // NOTE: covenant signature will be submitted in a separate msg by covenant
CovenantUnbondingSigList: nil, // NOTE: covenant signature will be submitted in a separate msg by covenant
DelegatorUnbondingInfo: nil,
},
ParamsVersion: paramsVersion, // version of the params against which delegation was validated
BtcTipHeight: timeInfo.TipHeight, // height of the BTC light client tip at the time of the delegation creation
}
// add this BTC delegation, and emit corresponding events
if err := ms.AddBTCDelegation(ctx, newBTCDel); err != nil {
panic(fmt.Errorf("failed to add BTC delegation that has passed verification: %w", err))
}
// if this BTC delegation is restaked to consumers' FPs, add it to btcstkconsumer indexes
// TODO: revisit the relationship between BTC staking module and BTC staking consumer module
if restakedToConsumers {
if err := ms.indexBTCConsumerDelegation(ctx, newBTCDel); err != nil {
panic(fmt.Errorf("failed to add BTC delegation restaked to consumers' finality providers despite it has passed verification: %w", err))
}
}
return &types.MsgCreateBTCDelegationResponse{}, nil
}
// AddBTCDelegationInclusionProof adds inclusion proof of the given delegation on BTC chain
func (ms msgServer) AddBTCDelegationInclusionProof(
goCtx context.Context,
req *types.MsgAddBTCDelegationInclusionProof,
) (*types.MsgAddBTCDelegationInclusionProofResponse, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), types.MetricsKeyAddBTCDelegationInclusionProof)
ctx := sdk.UnwrapSDKContext(goCtx)
// 1. make sure the delegation exists
btcDel, params, err := ms.getBTCDelWithParams(ctx, req.StakingTxHash)
if err != nil {
return nil, err
}
// 2. check if the delegation already has inclusion proof
if btcDel.HasInclusionProof() {
return nil, fmt.Errorf("the delegation %s already has inclusion proof", req.StakingTxHash)
}
// 3. check if the delegation has received a quorum of covenant sigs
if !btcDel.HasCovenantQuorums(params.CovenantQuorum) {
return nil, fmt.Errorf("the delegation %s has not received a quorum of covenant signatures", req.StakingTxHash)
}
// 4. check if the delegation is already unbonded
if btcDel.BtcUndelegation.DelegatorUnbondingInfo != nil {
return nil, fmt.Errorf("the delegation %s is already unbonded", req.StakingTxHash)
}
// 5. verify inclusion proof
parsedInclusionProof, err := types.NewParsedProofOfInclusion(req.StakingTxInclusionProof)
if err != nil {
return nil, err
}
stakingTx, err := bbn.NewBTCTxFromBytes(btcDel.StakingTx)
if err != nil {
return nil, err
}
btccParams := ms.btccKeeper.GetParams(ctx)
timeInfo, err := ms.VerifyInclusionProofAndGetHeight(
ctx,
btcutil.NewTx(stakingTx),
btccParams.BtcConfirmationDepth,
btcDel.StakingTime,
params.UnbondingTimeBlocks,
parsedInclusionProof,
)
if err != nil {
return nil, fmt.Errorf("invalid inclusion proof: %w", err)
}
// 6. check if the staking tx is included after the BTC tip height at the time of the delegation creation
if timeInfo.StartHeight < btcDel.BtcTipHeight {
return nil, types.ErrStakingTxIncludedTooEarly.Wrapf(
"btc tip height at the time of the delegation creation: %d, staking tx inclusion height: %d",
btcDel.BtcTipHeight,
timeInfo.StartHeight,
)
}
// 7. set start height and end height and save it to db
btcDel.StartHeight = timeInfo.StartHeight
btcDel.EndHeight = timeInfo.EndHeight
ms.setBTCDelegation(ctx, btcDel)
// 8. emit events
stakingTxHash := btcDel.MustGetStakingTxHash()
newInclusionProofEvent := types.NewInclusionProofEvent(
stakingTxHash.String(),
btcDel.StartHeight,
btcDel.EndHeight,
types.BTCDelegationStatus_ACTIVE,
)
if err := ctx.EventManager().EmitTypedEvents(newInclusionProofEvent); err != nil {
panic(fmt.Errorf("failed to emit events for the new active BTC delegation: %w", err))
}
activeEvent := types.NewEventPowerDistUpdateWithBTCDel(
&types.EventBTCDelegationStateUpdate{
StakingTxHash: stakingTxHash.String(),
NewState: types.BTCDelegationStatus_ACTIVE,
},
)
// notify consumer chains about the active BTC delegation
ms.notifyConsumersOnActiveBTCDel(ctx, btcDel)
ms.addPowerDistUpdateEvent(ctx, timeInfo.TipHeight, activeEvent)
// record event that the BTC delegation will become unbonded at EndHeight-w
expiredEvent := types.NewEventPowerDistUpdateWithBTCDel(&types.EventBTCDelegationStateUpdate{
StakingTxHash: req.StakingTxHash,
NewState: types.BTCDelegationStatus_EXPIRED,
})
// NOTE: we should have verified that EndHeight > btcTip.Height + min_unbonding_time
ms.addPowerDistUpdateEvent(ctx, btcDel.EndHeight-params.UnbondingTimeBlocks, expiredEvent)
// at this point, the BTC delegation inclusion proof is verified and is not duplicated
// thus, we can safely consider this message as refundable
ms.iKeeper.IndexRefundableMsg(ctx, req)
return &types.MsgAddBTCDelegationInclusionProofResponse{}, nil
}
func (ms msgServer) getBTCDelWithParams(
ctx context.Context,
stakingTxHash string) (*types.BTCDelegation, *types.Params, error) {
btcDel, err := ms.GetBTCDelegation(ctx, stakingTxHash)
if err != nil {
return nil, nil, err
}
bsParams := ms.GetParamsByVersion(ctx, btcDel.ParamsVersion)
if bsParams == nil {
panic("params version in BTC delegation is not found")
}
return btcDel, bsParams, nil
}
// AddCovenantSig adds signatures from covenants to a BTC delegation
// TODO: refactor this handler. Now it's too convoluted
func (ms msgServer) AddCovenantSigs(goCtx context.Context, req *types.MsgAddCovenantSigs) (*types.MsgAddCovenantSigsResponse, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), types.MetricsKeyAddCovenantSigs)
ctx := sdk.UnwrapSDKContext(goCtx)
// basic stateless checks
if err := req.ValidateBasic(); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
btcDel, params, err := ms.getBTCDelWithParams(ctx, req.StakingTxHash)
if err != nil {
return nil, err
}
// ensure that the given covenant PK is in the parameter
if !params.HasCovenantPK(req.Pk) {
return nil, types.ErrInvalidCovenantPK.Wrapf("covenant pk: %s", req.Pk.MarshalHex())
}
if btcDel.IsSignedByCovMember(req.Pk) && btcDel.BtcUndelegation.IsSignedByCovMember(req.Pk) {
ms.Logger(ctx).Debug("Received duplicated covenant signature", "covenant pk", req.Pk.MarshalHex())
// return error if the covenant signature is already submitted
// this is to secure the tx refunding against duplicated messages
return nil, types.ErrDuplicatedCovenantSig
}
// ensure BTC delegation is still pending, i.e., not unbonded
btcTipHeight := ms.btclcKeeper.GetTipInfo(ctx).Height
status := btcDel.GetStatus(btcTipHeight, params.CovenantQuorum)
if status == types.BTCDelegationStatus_UNBONDED || status == types.BTCDelegationStatus_EXPIRED {
ms.Logger(ctx).Debug("Received covenant signature after the BTC delegation is already unbonded", "covenant pk", req.Pk.MarshalHex())
return nil, types.ErrInvalidCovenantSig.Wrap("the BTC delegation is already unbonded")
}
// Check that the number of covenant sigs and number of the
// finality providers are matched
if len(req.SlashingTxSigs) != len(btcDel.FpBtcPkList) {
return nil, types.ErrInvalidCovenantSig.Wrapf(
"number of covenant signatures: %d, number of finality providers being staked to: %d",
len(req.SlashingTxSigs), len(btcDel.FpBtcPkList))
}
/*
Verify each covenant adaptor signature over slashing tx
*/
stakingInfo, err := btcDel.GetStakingInfo(params, ms.btcNet)
if err != nil {
panic(fmt.Errorf("failed to get staking info from a verified delegation: %w", err))
}
slashingSpendInfo, err := stakingInfo.SlashingPathSpendInfo()
if err != nil {
// our staking info was constructed by using BuildStakingInfo constructor, so if
// this fails, it is a programming error
panic(err)
}
parsedSlashingAdaptorSignatures, err := btcDel.SlashingTx.ParseEncVerifyAdaptorSignatures(
stakingInfo.StakingOutput,
slashingSpendInfo,
req.Pk,
btcDel.FpBtcPkList,
req.SlashingTxSigs,
)
if err != nil {
return nil, types.ErrInvalidCovenantSig.Wrapf("err: %v", err)
}
// Check that the number of covenant sigs and number of the
// finality providers are matched
if len(req.SlashingUnbondingTxSigs) != len(btcDel.FpBtcPkList) {
return nil, types.ErrInvalidCovenantSig.Wrapf(
"number of covenant signatures: %d, number of finality providers being staked to: %d",
len(req.SlashingUnbondingTxSigs), len(btcDel.FpBtcPkList))
}
/*
Verify Schnorr signature over unbonding tx
*/
unbondingMsgTx, err := bbn.NewBTCTxFromBytes(btcDel.BtcUndelegation.UnbondingTx)
if err != nil {
panic(fmt.Errorf("failed to parse unbonding tx from existing delegation with hash %s : %v", req.StakingTxHash, err))
}
unbondingSpendInfo, err := stakingInfo.UnbondingPathSpendInfo()
if err != nil {
// our staking info was constructed by using BuildStakingInfo constructor, so if
// this fails, it is a programming error
panic(err)
}
if err := btcstaking.VerifyTransactionSigWithOutput(
unbondingMsgTx,
stakingInfo.StakingOutput,
unbondingSpendInfo.GetPkScriptPath(),
req.Pk.MustToBTCPK(),
*req.UnbondingTxSig,
); err != nil {
return nil, types.ErrInvalidCovenantSig.Wrap(err.Error())
}
/*
verify each adaptor signature on slashing unbonding tx
*/
unbondingOutput := unbondingMsgTx.TxOut[0] // unbonding tx always have only one output
unbondingInfo, err := btcDel.GetUnbondingInfo(params, ms.btcNet)
if err != nil {
panic(err)
}
unbondingSlashingSpendInfo, err := unbondingInfo.SlashingPathSpendInfo()
if err != nil {
// our unbonding info was constructed by using BuildStakingInfo constructor, so if
// this fails, it is a programming error
panic(err)
}
parsedUnbondingSlashingAdaptorSignatures, err := btcDel.BtcUndelegation.SlashingTx.ParseEncVerifyAdaptorSignatures(
unbondingOutput,
unbondingSlashingSpendInfo,
req.Pk,
btcDel.FpBtcPkList,
req.SlashingUnbondingTxSigs,
)
if err != nil {
return nil, types.ErrInvalidCovenantSig.Wrapf("err: %v", err)
}
// All is fine add received signatures to the BTC delegation and BtcUndelegation
// and emit corresponding events
ms.addCovenantSigsToBTCDelegation(
ctx,
btcDel,
req.Pk,
parsedSlashingAdaptorSignatures,
req.UnbondingTxSig,
parsedUnbondingSlashingAdaptorSignatures,
params,
btcTipHeight,
)
// at this point, the covenant signatures are verified and are not duplicated.
// Thus, we can safely consider this message as refundable
// NOTE: currently we refund tx fee for covenant signatures even if the BTC
// delegation already has a covenant quorum. This is to ensure that covenant
// members do not spend transaction fee, even if they submit covenant signatures
// late.
ms.iKeeper.IndexRefundableMsg(ctx, req)
return &types.MsgAddCovenantSigsResponse{}, nil
}
func containsInput(tx *wire.MsgTx, inputHash *chainhash.Hash, inputIdx uint32) bool {
for _, txIn := range tx.TxIn {
if txIn.PreviousOutPoint.Hash.IsEqual(inputHash) && txIn.PreviousOutPoint.Index == inputIdx {
return true
}
}
return false
}
// BTCUndelegate adds a signature on the unbonding tx from the BTC delegator
// this effectively proves that the BTC delegator wants to unbond and Babylon
// will consider its BTC delegation unbonded
func (ms msgServer) BTCUndelegate(goCtx context.Context, req *types.MsgBTCUndelegate) (*types.MsgBTCUndelegateResponse, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), types.MetricsKeyBTCUndelegate)
ctx := sdk.UnwrapSDKContext(goCtx)
// basic stateless checks
if err := req.ValidateBasic(); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
btcDel, bsParams, err := ms.getBTCDelWithParams(ctx, req.StakingTxHash)
if err != nil {
return nil, err
}
// ensure the BTC delegation with the given staking tx hash is active
btcTip := ms.btclcKeeper.GetTipInfo(ctx)
btcDelStatus := btcDel.GetStatus(
btcTip.Height,
bsParams.CovenantQuorum,
)
if btcDelStatus == types.BTCDelegationStatus_UNBONDED || btcDelStatus == types.BTCDelegationStatus_EXPIRED {
return nil, types.ErrInvalidBTCUndelegateReq.Wrap("cannot unbond an unbonded BTC delegation")
}
stakeSpendingTx, err := bbn.NewBTCTxFromBytes(req.StakeSpendingTx)
if err != nil {
return nil, types.ErrInvalidBTCUndelegateReq.Wrapf("failed to parse staking spending tx: %v", err)
}
stakerSpendigTxHeader, err := ms.btclcKeeper.GetHeaderByHash(ctx, req.StakeSpendingTxInclusionProof.Key.Hash)
if err != nil {
return nil, types.ErrInvalidBTCUndelegateReq.Wrapf("stake spending tx is not on BTC chain: %v", err)
}
btcHeader := stakerSpendigTxHeader.Header.ToBlockHeader()
proofValid := btcckpttypes.VerifyInclusionProof(
btcutil.NewTx(stakeSpendingTx),
&btcHeader.MerkleRoot,
req.StakeSpendingTxInclusionProof.Proof,
req.StakeSpendingTxInclusionProof.Key.Index,
)
if !proofValid {
return nil, types.ErrInvalidBTCUndelegateReq.Wrap("stake spending tx is not included in the Bitcoin chain: invalid inclusion proof")
}
registeredUnbondingTx, err := bbn.NewBTCTxFromBytes(btcDel.BtcUndelegation.UnbondingTx)
if err != nil {
panic(fmt.Errorf("failed to parse unbonding tx from existing delegation with hash %s: %w", req.StakingTxHash, err))
}
registeredUnbondingTxHash := registeredUnbondingTx.TxHash()
spendStakeTxHash := stakeSpendingTx.TxHash()
var delegatorUnbondingInfo *types.DelegatorUnbondingInfo
// Check if stake spending tx is already registered unbonding tx. If so, we do
// not need to save it in database
if spendStakeTxHash.IsEqual(®isteredUnbondingTxHash) {
delegatorUnbondingInfo = &types.DelegatorUnbondingInfo{
// if the stake spending tx is the same as the registered unbonding tx,
// we do not need to save it in the database
SpendStakeTx: []byte{},
}
types.EmitEarlyUnbondedEvent(ctx, btcDel.MustGetStakingTxHash().String(), stakerSpendigTxHeader.Height)
} else {
// stakeSpendingTx is not unbonding tx, first we need to verify whether it
// actually spends staking output
stakingTxHash, err := chainhash.NewHashFromStr(req.StakingTxHash)
if err != nil {
// panic as we already verified the staking tx hash in the beginning
panic(fmt.Errorf("failed to parse staking tx hash from existing delegation with hash %s: %w", req.StakingTxHash, err))
}
if !containsInput(stakeSpendingTx, stakingTxHash, btcDel.StakingOutputIdx) {
return nil, types.ErrInvalidBTCUndelegateReq.Wrap("stake spending tx does not spend staking output")
}
delegatorUnbondingInfo = &types.DelegatorUnbondingInfo{
SpendStakeTx: req.StakeSpendingTx,
}
types.EmitUnexpectedUnbondingTxEvent(ctx,
btcDel.MustGetStakingTxHash().String(),
spendStakeTxHash.String(),
req.StakeSpendingTxInclusionProof.Key.Hash.MarshalHex(),
req.StakeSpendingTxInclusionProof.Key.Index,
)
}
// all good, add the signature to BTC delegation's undelegation
// and set back
ms.btcUndelegate(ctx, btcDel, delegatorUnbondingInfo, req.StakeSpendingTx, req.StakeSpendingTxInclusionProof)
// At this point, the unbonding signature is verified.
// Thus, we can safely consider this message as refundable
ms.iKeeper.IndexRefundableMsg(ctx, req)
return &types.MsgBTCUndelegateResponse{}, nil
}
// SelectiveSlashingEvidence handles the evidence that a finality provider has
// selectively slashed a BTC delegation
func (ms msgServer) SelectiveSlashingEvidence(goCtx context.Context, req *types.MsgSelectiveSlashingEvidence) (*types.MsgSelectiveSlashingEvidenceResponse, error) {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), types.MetricsKeySelectiveSlashingEvidence)
ctx := sdk.UnwrapSDKContext(goCtx)
btcDel, bsParams, err := ms.getBTCDelWithParams(ctx, req.StakingTxHash)
if err != nil {
return nil, err
}
// ensure the BTC delegation is active, or its BTC undelegation receives an
// unbonding signature from the staker
btcTip := ms.btclcKeeper.GetTipInfo(ctx)
covQuorum := bsParams.CovenantQuorum
if btcDel.GetStatus(btcTip.Height, covQuorum) != types.BTCDelegationStatus_ACTIVE && !btcDel.IsUnbondedEarly() {
return nil, types.ErrBTCDelegationNotFound.Wrap("a BTC delegation that is not active or unbonding early cannot be slashed")
}
// decode the finality provider's BTC SK/PK
fpSK, fpPK := btcec.PrivKeyFromBytes(req.RecoveredFpBtcSk)
fpBTCPK := bbn.NewBIP340PubKeyFromBTCPK(fpPK)
// ensure the BTC delegation is staked to the given finality provider
fpIdx := btcDel.GetFpIdx(fpBTCPK)
if fpIdx == -1 {
return nil, types.ErrFpNotFound.Wrapf("BTC delegation is not staked to the finality provider")
}
// ensure the finality provider exists
fp, err := ms.GetFinalityProvider(ctx, fpBTCPK.MustMarshal())
if err != nil {
panic(types.ErrFpNotFound.Wrapf("failing to find the finality provider with BTC delegations"))
}
// ensure the finality provider is not slashed
if fp.IsSlashed() {
return nil, types.ErrFpAlreadySlashed
}
// at this point, the finality provider must have done selective slashing and must be
// adversarial
// slash the finality provider now
if err := ms.SlashFinalityProvider(ctx, fpBTCPK.MustMarshal()); err != nil {
panic(err) // failed to slash the finality provider, must be programming error
}
// emit selective slashing event
evidence := &types.SelectiveSlashingEvidence{
StakingTxHash: req.StakingTxHash,
FpBtcPk: fpBTCPK,
RecoveredFpBtcSk: fpSK.Serialize(),
}
event := &types.EventSelectiveSlashing{Evidence: evidence}
if err := sdk.UnwrapSDKContext(ctx).EventManager().EmitTypedEvent(event); err != nil {
panic(fmt.Errorf("failed to emit EventSelectiveSlashing event: %w", err))
}
// At this point, the selective slashing evidence is verified and is not duplicated.
// Thus, we can safely consider this message as refundable
ms.iKeeper.IndexRefundableMsg(ctx, req)
return &types.MsgSelectiveSlashingEvidenceResponse{}, nil
}