-
Notifications
You must be signed in to change notification settings - Fork 12
/
msg_server.go
699 lines (580 loc) · 25.3 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
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)
}
ctx := sdk.UnwrapSDKContext(goCtx)
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
}
// TODO: check to index the finality provider by his address instead of the BTC pk
// find the finality provider with the given BTC PK
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
}
// 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())
}
// 4. Check finality providers to which message delegate
// Ensure all finality providers are known to Babylon, are not slashed
for _, fpBTCPK := range parsedMsg.FinalityProviderKeys.PublicKeysBbnFormat {
// get this finality provider
fp, err := ms.GetFinalityProvider(ctx, fpBTCPK)
if err != nil {
return nil, err
}
// ensure the finality provider is not slashed
if fp.IsSlashed() {
return nil, types.ErrFpAlreadySlashed.Wrapf("finality key: %s", fpBTCPK.MarshalHex())
}
}
// 5. Validate parsed message against parameters
vp := ms.GetParamsWithVersion(ctx)
btccParams := ms.btccKeeper.GetParams(ctx)
paramsValidationResult, err := types.ValidateParsedMessageAgainstTheParams(parsedMsg, &vp.Params, &btccParams, ms.btcNet)
if err != nil {
return nil, err
}
// 6. If the delegation contains the inclusion proof, we need to verify the proof
// and set start height and end height
var startHeight, endHeight uint32
if parsedMsg.StakingTxProofOfInclusion != nil {
timeInfo, err := ms.VerifyInclusionProofAndGetHeight(
ctx,
btcutil.NewTx(parsedMsg.StakingTx.Transaction),
btccParams.BtcConfirmationDepth,
uint32(parsedMsg.StakingTime),
paramsValidationResult.MinUnbondingTime,
parsedMsg.StakingTxProofOfInclusion)
if err != nil {
return nil, fmt.Errorf("invalid inclusion proof: %w", err)
}
startHeight = timeInfo.startHeight
endHeight = timeInfo.endHeight
} else {
// NOTE: here we consume more gas to protect Babylon chain and covenant members against spamming
// i.e creating delegation that will never reach BTC
ctx.GasMeter().ConsumeGas(vp.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: startHeight,
EndHeight: 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: vp.Version, // version of the params against delegations was validated
}
// add this BTC delegation, and emit corresponding events
if err := ms.AddBTCDelegation(ctx, newBTCDel, paramsValidationResult.MinUnbondingTime); err != nil {
panic(fmt.Errorf("failed to add BTC delegation that 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)
minUnbondingTime := types.MinimumUnbondingTime(params, &btccParams)
timeInfo, err := ms.VerifyInclusionProofAndGetHeight(
ctx,
btcutil.NewTx(stakingTx),
btccParams.BtcConfirmationDepth,
btcDel.StakingTime,
minUnbondingTime,
parsedInclusionProof,
)
if err != nil {
return nil, fmt.Errorf("invalid inclusion proof: %w", err)
}
// 6. set start height and end height and save it to db
btcDel.StartHeight = timeInfo.startHeight
btcDel.EndHeight = timeInfo.endHeight
ms.setBTCDelegation(ctx, btcDel)
// 7. 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,
},
)
btcTip := ms.btclcKeeper.GetTipInfo(ctx)
ms.addPowerDistUpdateEvent(ctx, btcTip.Height, activeEvent)
// record event that the BTC delegation will become unbonded at endHeight-w
unbondedEvent := types.NewEventPowerDistUpdateWithBTCDel(&types.EventBTCDelegationStateUpdate{
StakingTxHash: req.StakingTxHash,
NewState: types.BTCDelegationStatus_UNBONDED,
})
// NOTE: we should have verified that EndHeight > btcTip.Height + max(w, min_unbonding_time)
ms.addPowerDistUpdateEvent(ctx, btcDel.EndHeight-minUnbondingTime, unbondedEvent)
// 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
wValue := ms.btccKeeper.GetParams(ctx).CheckpointFinalizationTimeout
status := btcDel.GetStatus(btcTipHeight, wValue, params.CovenantQuorum)
if status == types.BTCDelegationStatus_UNBONDED {
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,
)
// 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)
wValue := ms.btccKeeper.GetParams(ctx).CheckpointFinalizationTimeout
btcDelStatus := btcDel.GetStatus(btcTip.Height, wValue, bsParams.CovenantQuorum)
if btcDelStatus == types.BTCDelegationStatus_UNBONDED {
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 := ms.btclcKeeper.GetHeaderByHash(ctx, req.StakeSpendingTxInclusionProof.Key.Hash)
if stakerSpendigTxHeader == nil {
return nil, types.ErrInvalidBTCUndelegateReq.Wrap("stake spending tx is not on BTC chain")
}
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
// acutally 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)
// 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)
wValue := ms.btccKeeper.GetParams(ctx).CheckpointFinalizationTimeout
covQuorum := bsParams.CovenantQuorum
if btcDel.GetStatus(btcTip.Height, wValue, 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
}