Skip to content

Commit

Permalink
tapfreighter+tapgarden: Add TX sanity checks
Browse files Browse the repository at this point in the history
  • Loading branch information
jharveyb committed Oct 9, 2023
1 parent b8af77d commit 914831e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
17 changes: 17 additions & 0 deletions tapfreighter/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import (
"sync"
"time"

"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/psbt"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
Expand Down Expand Up @@ -1397,6 +1399,12 @@ func (f *AssetWallet) AnchorVirtualTransactions(ctx context.Context,
return nil, fmt.Errorf("unable to extract psbt: %w", err)
}

// Final TX sanity check.
err = blockchain.CheckTransactionSanity(btcutil.NewTx(finalTx))
if err != nil {
return nil, fmt.Errorf("anchor TX failed final checks: %w", err)
}

return &AnchorTransaction{
FundedPsbt: &anchorPkt,
FinalTx: finalTx,
Expand Down Expand Up @@ -1654,6 +1662,15 @@ func addAnchorPsbtInputs(btcPkt *psbt.Packet, vPkt *tappsbt.VPacket,
lastIdx := len(btcPkt.UnsignedTx.TxOut) - 1
currentFee := inputAmt - outputAmt
feeDelta := int64(requiredFee) - currentFee
changeValue := btcPkt.UnsignedTx.TxOut[lastIdx].Value

// The fee may exceed the total value of the change output, which means
// this spend is impossible with the given inputs and fee rate.
if changeValue-feeDelta < 0 {
return fmt.Errorf("fee of %d sats exceeds change amount of %d"+
"sats", requiredFee, changeValue)
}

btcPkt.UnsignedTx.TxOut[lastIdx].Value -= feeDelta

log.Infof("Adjusting send pkt by delta of %v from %d sats to %d sats",
Expand Down
14 changes: 14 additions & 0 deletions tapgarden/caretaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"sync"
"time"

"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/psbt"
Expand Down Expand Up @@ -697,6 +698,19 @@ func (b *BatchCaretaker) stateStep(currentState BatchState) (BatchState, error)
if err != nil {
return 0, fmt.Errorf("unable to sign psbt: %w", err)
}

// Final TX sanity check.
signedTx, err := psbt.Extract(signedPkt)
if err != nil {
return 0, fmt.Errorf("unable to extract psbt: %w", err)
}

err = blockchain.CheckTransactionSanity(btcutil.NewTx(signedTx))
if err != nil {
return 0, fmt.Errorf("genesis TX failed final checks: "+
"%w", err)
}

b.cfg.Batch.GenesisPacket.Pkt = signedPkt

// Populate how much this tx paid in on-chain fees.
Expand Down

0 comments on commit 914831e

Please sign in to comment.