From 1ea1ea3a03501b5b7ebd36cfe2e0f777857ee4d8 Mon Sep 17 00:00:00 2001 From: Gurjot Date: Mon, 13 Jan 2025 15:18:49 +0530 Subject: [PATCH] handle unexpected unbonding tx --- internal/services/watch_btc_events.go | 48 ++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/internal/services/watch_btc_events.go b/internal/services/watch_btc_events.go index e7a97ea..b64aec1 100644 --- a/internal/services/watch_btc_events.go +++ b/internal/services/watch_btc_events.go @@ -3,6 +3,7 @@ package services import ( "bytes" "context" + "encoding/hex" "errors" "fmt" @@ -180,7 +181,22 @@ func (s *Service) handleSpendingStakingTransaction( Err(err). Str("staking_tx", delegation.StakingTxHashHex). Str("spending_tx", spendingTx.TxHash().String()). - Msg("found an invalid unbonding tx") + Msg("found an unexpected unbonding tx") + + registeredUnbondingTxBytes, parseErr := hex.DecodeString(delegation.UnbondingTx) + if parseErr != nil { + return fmt.Errorf("failed to decode unbonding tx: %w", parseErr) + } + + registeredUnbondingTx, parseErr := bbn.NewBTCTxFromBytes(registeredUnbondingTxBytes) + if parseErr != nil { + return fmt.Errorf("failed to parse unbonding tx: %w", parseErr) + } + + registeredUnbondingTxHash := registeredUnbondingTx.TxHash().String() + if registeredUnbondingTxHash != spendingTx.TxHash().String() { + return s.handleUnexpectedUnbondingTx(ctx, spendingTx, delegation) + } return nil } @@ -350,6 +366,36 @@ func (s *Service) handleWithdrawal( ) } +func (s *Service) handleUnexpectedUnbondingTx( + ctx context.Context, + spendingTx *wire.MsgTx, + delegation *model.BTCDelegationDetails, +) error { + log.Debug(). + Str("staking_tx", delegation.StakingTxHashHex). + Str("unbonding_tx", spendingTx.TxHash().String()). + Msg("handling unexpected unbonding tx") + + // Emit consumer event + if err := s.emitUnbondingDelegationEvent(ctx, delegation); err != nil { + return err + } + + // Update delegation state to unbonding + subState := types.SubStateEarlyUnbonding + if err := s.db.UpdateBTCDelegationState( + ctx, + delegation.StakingTxHashHex, + types.QualifiedStatesForUnbondedEarly(), + types.StateUnbonding, + &subState, + ); err != nil { + return fmt.Errorf("failed to update BTC delegation state: %w", err) + } + + return nil +} + func (s *Service) startWatchingSlashingChange( ctx context.Context, slashingTx *wire.MsgTx,