From f552bc06b16365d003a8d65d355fba93d3ed3918 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Wed, 6 Mar 2019 18:20:51 -0800 Subject: [PATCH] utils: remove utils package in favor of new swap package --- swap/fees.go | 46 +++++++++++++++ {utils => swap}/htlc.go | 2 +- swap/keychain.go | 9 +++ swap/net.go | 27 +++++++++ swap/tx.go | 64 +++++++++++++++++++++ utils/config.go | 9 --- utils/swaplog.go | 41 -------------- utils/utils.go | 123 ---------------------------------------- 8 files changed, 147 insertions(+), 174 deletions(-) create mode 100644 swap/fees.go rename {utils => swap}/htlc.go (99%) create mode 100644 swap/keychain.go create mode 100644 swap/net.go create mode 100644 swap/tx.go delete mode 100644 utils/config.go delete mode 100644 utils/swaplog.go delete mode 100644 utils/utils.go diff --git a/swap/fees.go b/swap/fees.go new file mode 100644 index 0000000..b104f9a --- /dev/null +++ b/swap/fees.go @@ -0,0 +1,46 @@ +package swap + +import ( + "errors" + + "github.com/btcsuite/btcd/chaincfg" + "github.com/btcsuite/btcutil" + "github.com/lightningnetwork/lnd/zpay32" +) + +const ( + // FeeRateTotalParts defines the granularity of the fee rate. + // Throughout the codebase, we'll use fix based arithmetic to compute + // fees. + FeeRateTotalParts = 1e6 +) + +// CalcFee returns the swap fee for a given swap amount. +func CalcFee(amount, feeBase btcutil.Amount, feeRate int64) btcutil.Amount { + return feeBase + amount*btcutil.Amount(feeRate)/ + btcutil.Amount(FeeRateTotalParts) +} + +// FeeRateAsPercentage converts a feerate to a percentage. +func FeeRateAsPercentage(feeRate int64) float64 { + return float64(feeRate) / (FeeRateTotalParts / 100) +} + +// GetInvoiceAmt gets the invoice amount. It requires an amount to be +// specified. +func GetInvoiceAmt(params *chaincfg.Params, + payReq string) (btcutil.Amount, error) { + + swapPayReq, err := zpay32.Decode( + payReq, params, + ) + if err != nil { + return 0, err + } + + if swapPayReq.MilliSat == nil { + return 0, errors.New("no amount in invoice") + } + + return swapPayReq.MilliSat.ToSatoshis(), nil +} diff --git a/utils/htlc.go b/swap/htlc.go similarity index 99% rename from utils/htlc.go rename to swap/htlc.go index 71bc033..380e4ea 100644 --- a/utils/htlc.go +++ b/swap/htlc.go @@ -1,4 +1,4 @@ -package utils +package swap import ( "bytes" diff --git a/swap/keychain.go b/swap/keychain.go new file mode 100644 index 0000000..164999f --- /dev/null +++ b/swap/keychain.go @@ -0,0 +1,9 @@ +package swap + +var ( + // KeyFamily is the key family used to generate keys that allow + // spending of the htlc. + // + // TODO(joost): decide on actual value + KeyFamily = int32(99) +) diff --git a/swap/net.go b/swap/net.go new file mode 100644 index 0000000..581c76d --- /dev/null +++ b/swap/net.go @@ -0,0 +1,27 @@ +package swap + +import ( + "errors" + + "github.com/btcsuite/btcd/chaincfg" +) + +// ChainParamsFromNetwork returns chain parameters based on a network name. +func ChainParamsFromNetwork(network string) (*chaincfg.Params, error) { + switch network { + case "mainnet": + return &chaincfg.MainNetParams, nil + + case "testnet": + return &chaincfg.TestNet3Params, nil + + case "regtest": + return &chaincfg.RegressionNetParams, nil + + case "simnet": + return &chaincfg.SimNetParams, nil + + default: + return nil, errors.New("unknown network") + } +} diff --git a/swap/tx.go b/swap/tx.go new file mode 100644 index 0000000..2212c05 --- /dev/null +++ b/swap/tx.go @@ -0,0 +1,64 @@ +package swap + +import ( + "bytes" + "errors" + "fmt" + + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcutil" +) + +// EncodeTx encodes a tx to raw bytes. +func EncodeTx(tx *wire.MsgTx) ([]byte, error) { + var buffer bytes.Buffer + err := tx.BtcEncode(&buffer, 0, wire.WitnessEncoding) + if err != nil { + return nil, err + } + rawTx := buffer.Bytes() + + return rawTx, nil +} + +// DecodeTx decodes raw tx bytes. +func DecodeTx(rawTx []byte) (*wire.MsgTx, error) { + tx := wire.MsgTx{} + r := bytes.NewReader(rawTx) + err := tx.BtcDecode(r, 0, wire.WitnessEncoding) + if err != nil { + return nil, err + } + + return &tx, nil +} + +// GetScriptOutput locates the given script in the outputs of a transaction and +// returns its outpoint and value. +func GetScriptOutput(htlcTx *wire.MsgTx, scriptHash []byte) ( + *wire.OutPoint, btcutil.Amount, error) { + + for idx, output := range htlcTx.TxOut { + if bytes.Equal(output.PkScript, scriptHash) { + return &wire.OutPoint{ + Hash: htlcTx.TxHash(), + Index: uint32(idx), + }, btcutil.Amount(output.Value), nil + } + } + + return nil, 0, fmt.Errorf("cannot determine outpoint") +} + +// GetTxInputByOutpoint returns a tx input based on a given input outpoint. +func GetTxInputByOutpoint(tx *wire.MsgTx, input *wire.OutPoint) ( + *wire.TxIn, error) { + + for _, in := range tx.TxIn { + if in.PreviousOutPoint == *input { + return in, nil + } + } + + return nil, errors.New("input not found") +} diff --git a/utils/config.go b/utils/config.go deleted file mode 100644 index 82d3794..0000000 --- a/utils/config.go +++ /dev/null @@ -1,9 +0,0 @@ -package utils - -var ( - // SwapKeyFamily is the key family used to generate keys that allow - // spending of the htlc. - // - // TODO(joost): decide on actual value - SwapKeyFamily = int32(99) -) diff --git a/utils/swaplog.go b/utils/swaplog.go deleted file mode 100644 index a746389..0000000 --- a/utils/swaplog.go +++ /dev/null @@ -1,41 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/btcsuite/btclog" - "github.com/lightningnetwork/lnd/lntypes" -) - -// SwapLog logs with a short swap hash prefix. -type SwapLog struct { - Logger btclog.Logger - Hash lntypes.Hash -} - -// Infof formats message according to format specifier and writes to -// log with LevelInfo. -func (s *SwapLog) Infof(format string, params ...interface{}) { - s.Logger.Infof( - fmt.Sprintf("%v %s", ShortHash(&s.Hash), format), - params..., - ) -} - -// Warnf formats message according to format specifier and writes to -// to log with LevelError. -func (s *SwapLog) Warnf(format string, params ...interface{}) { - s.Logger.Warnf( - fmt.Sprintf("%v %s", ShortHash(&s.Hash), format), - params..., - ) -} - -// Errorf formats message according to format specifier and writes to -// to log with LevelError. -func (s *SwapLog) Errorf(format string, params ...interface{}) { - s.Logger.Errorf( - fmt.Sprintf("%v %s", ShortHash(&s.Hash), format), - params..., - ) - -} diff --git a/utils/utils.go b/utils/utils.go deleted file mode 100644 index 953b233..0000000 --- a/utils/utils.go +++ /dev/null @@ -1,123 +0,0 @@ -package utils - -import ( - "bytes" - "errors" - "fmt" - "os" - - "github.com/btcsuite/btcd/chaincfg" - "github.com/btcsuite/btcutil" - "github.com/lightningnetwork/lnd/lntypes" - "github.com/lightningnetwork/lnd/zpay32" - - "github.com/btcsuite/btcd/wire" -) - -const ( - // FeeRateTotalParts defines the granularity of the fee rate. - FeeRateTotalParts = 1e6 -) - -// ShortHash returns a shortened version of the hash suitable for use in -// logging. -func ShortHash(hash *lntypes.Hash) string { - return hash.String()[:6] -} - -// EncodeTx encodes a tx to raw bytes. -func EncodeTx(tx *wire.MsgTx) ([]byte, error) { - var buffer bytes.Buffer - err := tx.BtcEncode(&buffer, 0, wire.WitnessEncoding) - if err != nil { - return nil, err - } - rawTx := buffer.Bytes() - - return rawTx, nil -} - -// DecodeTx decodes raw tx bytes. -func DecodeTx(rawTx []byte) (*wire.MsgTx, error) { - tx := wire.MsgTx{} - r := bytes.NewReader(rawTx) - err := tx.BtcDecode(r, 0, wire.WitnessEncoding) - if err != nil { - return nil, err - } - - return &tx, nil -} - -// GetInvoiceAmt gets the invoice amount. It requires an amount to be specified. -func GetInvoiceAmt(params *chaincfg.Params, - payReq string) (btcutil.Amount, error) { - - swapPayReq, err := zpay32.Decode( - payReq, params, - ) - if err != nil { - return 0, err - } - - if swapPayReq.MilliSat == nil { - return 0, errors.New("no amount in invoice") - } - - return swapPayReq.MilliSat.ToSatoshis(), nil -} - -// FileExists returns true if the file exists, and false otherwise. -func FileExists(path string) bool { - if _, err := os.Stat(path); err != nil { - if os.IsNotExist(err) { - return false - } - } - - return true -} - -// ChainParamsFromNetwork returns chain parameters based on a network name. -func ChainParamsFromNetwork(network string) (*chaincfg.Params, error) { - switch network { - case "mainnet": - return &chaincfg.MainNetParams, nil - case "testnet": - return &chaincfg.TestNet3Params, nil - case "regtest": - return &chaincfg.RegressionNetParams, nil - case "simnet": - return &chaincfg.SimNetParams, nil - default: - return nil, errors.New("unknown network") - } -} - -// GetScriptOutput locates the given script in the outputs of a transaction and -// returns its outpoint and value. -func GetScriptOutput(htlcTx *wire.MsgTx, scriptHash []byte) ( - *wire.OutPoint, btcutil.Amount, error) { - - for idx, output := range htlcTx.TxOut { - if bytes.Equal(output.PkScript, scriptHash) { - return &wire.OutPoint{ - Hash: htlcTx.TxHash(), - Index: uint32(idx), - }, btcutil.Amount(output.Value), nil - } - } - - return nil, 0, fmt.Errorf("cannot determine outpoint") -} - -// CalcFee returns the swap fee for a given swap amount. -func CalcFee(amount, feeBase btcutil.Amount, feeRate int64) btcutil.Amount { - return feeBase + amount*btcutil.Amount(feeRate)/ - btcutil.Amount(FeeRateTotalParts) -} - -// FeeRateAsPercentage converts a feerate to a percentage. -func FeeRateAsPercentage(feeRate int64) float64 { - return float64(feeRate) / (FeeRateTotalParts / 100) -}