From 586729ca070da5f6467093df2b32d9b05a7a6d7f Mon Sep 17 00:00:00 2001 From: Robyn Date: Thu, 3 Nov 2022 20:34:07 +0000 Subject: [PATCH] btcutil/psbt: add method Packet.GetTxFee This commit adds a GetTxFee method to the psbt.Packet structure. The method returns the PSBT's fee. --- btcutil/psbt/psbt.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/btcutil/psbt/psbt.go b/btcutil/psbt/psbt.go index 5ea51eea..7241bdb6 100644 --- a/btcutil/psbt/psbt.go +++ b/btcutil/psbt/psbt.go @@ -11,9 +11,9 @@ import ( "bytes" "encoding/base64" "errors" - "io" + "github.com/btcsuite/btcd/btcutil" "github.com/btcsuite/btcd/wire" ) @@ -30,7 +30,7 @@ var ( // MaxPsbtValueLength is the size of the largest transaction serialization // that could be passed in a NonWitnessUtxo field. This is definitely -//less than 4M. +// less than 4M. const MaxPsbtValueLength = 4000000 // MaxPsbtKeyLength is the length of the largest key that we'll successfully @@ -395,3 +395,20 @@ func (p *Packet) SanityCheck() error { return nil } + +// GetTxFee returns the transaction fee. An error is returned if a transaction +// input does not contain any UTXO information. +func (p *Packet) GetTxFee() (btcutil.Amount, error) { + sumInputs, err := SumUtxoInputValues(p) + if err != nil { + return 0, err + } + + var sumOutputs int64 + for _, txOut := range p.UnsignedTx.TxOut { + sumOutputs += txOut.Value + } + + fee := sumInputs - sumOutputs + return btcutil.Amount(fee), nil +}