Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Revantark committed Jul 20, 2024
1 parent 5c86242 commit b600524
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 105 deletions.
79 changes: 21 additions & 58 deletions btc/batcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import (
)

var (
SegwitSpendWeight int = txsizes.RedeemP2WPKHInputWitnessWeight
DefaultContextTimeout = 5 * time.Second
SegwitSpendWeight = txsizes.RedeemP2WPKHInputWitnessWeight
DefaultAPITimeout = 5 * time.Second
)
var (
ErrBatchNotFound = errors.New("batch not found")
Expand Down Expand Up @@ -107,16 +107,20 @@ type BatcherRequest struct {
}

type BatcherOptions struct {
PTI time.Duration // Periodic Time Interval for batching
// Periodic Time Interval for batching
PTI time.Duration
TxOptions TxOptions
Strategy Strategy
}

// Strategy defines the batching strategy to be used by the BatcherWallet
// It can be one of RBF, CPFP, RBF_CPFP, Multi_CPFP
// RBF - Replace By Fee
// CPFP - Child Pays For Parent
// Multi_CPFP - Multiple CPFP threads are maintained across multiple addresses
// Strategy defines the batching strategy to be used by the BatcherWallet.
// It can be one of RBF, CPFP, RBF_CPFP, Multi_CPFP.
//
// 1. RBF - Replace By Fee
//
// 2. CPFP - Child Pays For Parent
//
// 3. Multi_CPFP - Multiple CPFP threads are maintained across multiple addresses
type Strategy string

var (
Expand All @@ -127,14 +131,6 @@ var (
)

type TxOptions struct {
MaxOutputs int
MaxInputs int

MaxUnconfirmedAge int

MaxBatches int
MaxBatchSize int

FeeLevel FeeLevel
MaxFeeRate int
MinFeeDelta int
Expand All @@ -157,9 +153,10 @@ type batcherWallet struct {
cache Cache
}
type Batch struct {
Tx Transaction
RequestIds map[string]bool
IsStable bool
Tx Transaction
RequestIds map[string]bool
// true indicates that the batch is finalized and will not be replaced by more fee.
isFinalized bool
IsConfirmed bool
Strategy Strategy
SelfUtxos UTXOs
Expand Down Expand Up @@ -202,14 +199,6 @@ func defaultBatcherOptions() BatcherOptions {
return BatcherOptions{
PTI: 1 * time.Minute,
TxOptions: TxOptions{
MaxOutputs: 0,
MaxInputs: 0,

MaxUnconfirmedAge: 0,

MaxBatches: 0,
MaxBatchSize: 0,

FeeLevel: HighFee,
MaxFeeRate: 0,
MinFeeDelta: 0,
Expand Down Expand Up @@ -456,7 +445,7 @@ func (w *batcherWallet) validateBatchRequest(ctx context.Context, strategy Strat

spendsAmount := int64(0)
spendsUtxos := UTXOs{}
err = withContextTimeout(ctx, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(ctx, DefaultAPITimeout, func(ctx context.Context) error {
spendsUtxos, _, spendsAmount, err = getUTXOsForSpendRequest(ctx, w.indexer, spends)
return err
})
Expand All @@ -466,8 +455,8 @@ func (w *batcherWallet) validateBatchRequest(ctx context.Context, strategy Strat

var sacpsIn int64
var sacpOut int64
err = withContextTimeout(ctx, DefaultContextTimeout, func(ctx context.Context) error {
sacpsIn, sacpOut, err = getTotalInAndOutSACPs(ctx, sacps, w.indexer)
err = withContextTimeout(ctx, DefaultAPITimeout, func(ctx context.Context) error {
sacpsIn, sacpOut, err = getSACPAmounts(ctx, sacps, w.indexer)
return err
})

Expand Down Expand Up @@ -527,7 +516,7 @@ func filterPendingBatches(batches []Batch, indexer IndexerClient) ([]Batch, []st
confirmedTxs := []string{}
pendingTxs := []string{}
for _, batch := range batches {
ctx, cancel := context.WithTimeout(context.Background(), DefaultContextTimeout)
ctx, cancel := context.WithTimeout(context.Background(), DefaultAPITimeout)
defer cancel()
tx, err := indexer.GetTx(ctx, batch.Tx.TxID)
if err != nil {
Expand All @@ -548,7 +537,7 @@ func getTransaction(indexer IndexerClient, txid string) (Transaction, error) {
return Transaction{}, ErrTxIdEmpty
}
for i := 1; i < 5; i++ {
ctx, cancel := context.WithTimeout(context.Background(), DefaultContextTimeout)
ctx, cancel := context.WithTimeout(context.Background(), DefaultAPITimeout)
defer cancel()
tx, err := indexer.GetTx(ctx, txid)
if err != nil {
Expand All @@ -566,32 +555,6 @@ func withContextTimeout(parentContext context.Context, duration time.Duration, f
return fn(ctx)
}

// getFeeUsedInSACPs returns the amount of fee used in the given SACPs
func getTotalInAndOutSACPs(ctx context.Context, sacps [][]byte, indexer IndexerClient) (int64, int64, error) {
tx, _, err := buildTxFromSacps(sacps)
if err != nil {
return 0, 0, err
}

// go through each input and get the amount it holds
// add all the inputs and subtract the outputs to get the fee
totalInputAmount := int64(0)
for _, in := range tx.TxIn {
txFromIndexer, err := indexer.GetTx(ctx, in.PreviousOutPoint.Hash.String())
if err != nil {
return 0, 0, err
}
totalInputAmount += int64(txFromIndexer.VOUTs[in.PreviousOutPoint.Index].Value)
}

totalOutputAmount := int64(0)
for _, out := range tx.TxOut {
totalOutputAmount += out.Value
}

return totalInputAmount, totalOutputAmount, nil
}

// unpackBatcherRequests unpacks the batcher requests into spend requests, send requests and SACPs
func unpackBatcherRequests(reqs []BatcherRequest) ([]SpendRequest, []SendRequest, [][]byte, map[string]bool) {
spendRequests := []SpendRequest{}
Expand Down
34 changes: 17 additions & 17 deletions btc/cpfp.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {

// Read all pending requests added to the cache
// All requests are executed in a single batch
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
requests, err = w.cache.ReadPendingRequests(ctx)
return err
})
Expand All @@ -43,7 +43,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {

// Read pending batches from the cache
var batches []Batch
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
batches, err = w.cache.ReadPendingBatches(ctx, w.opts.Strategy)
return err
})
Expand All @@ -57,7 +57,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {
return err
}

err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
return w.cache.ConfirmBatchStatuses(ctx, confirmedTxs, false, CPFP)
})
if err != nil {
Expand All @@ -79,7 +79,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {

// Fetch UTXOs from the indexer
var utxos []UTXO
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
utxos, err = w.indexer.GetUTXOs(ctx, w.address)
return err
})
Expand All @@ -105,7 +105,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {
}

// Submit the CPFP transaction to the indexer
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
return w.indexer.SubmitTx(ctx, tx)
})
if err != nil {
Expand All @@ -114,7 +114,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {

// Retrieve the transaction details from the indexer
var transaction Transaction
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
transaction, err = getTransaction(w.indexer, tx.TxHash().String())
return err
})
Expand All @@ -126,7 +126,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {
batch := Batch{
Tx: transaction,
RequestIds: reqIds,
IsStable: true,
isFinalized: true,
IsConfirmed: false,
Strategy: CPFP,
SelfUtxos: UTXOs{
Expand All @@ -138,7 +138,7 @@ func (w *batcherWallet) createCPFPBatch(c context.Context) error {
},
}

err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
return w.cache.SaveBatch(ctx, batch)
})
if err != nil {
Expand All @@ -155,7 +155,7 @@ func (w *batcherWallet) updateCPFP(c context.Context, requiredFeeRate int) error
var err error

// Read pending batches from the cache
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
batches, err = w.cache.ReadPendingBatches(ctx, w.opts.Strategy)
return err
})
Expand All @@ -169,7 +169,7 @@ func (w *batcherWallet) updateCPFP(c context.Context, requiredFeeRate int) error
return err
}

err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
return w.cache.ConfirmBatchStatuses(ctx, confirmedTxs, false, CPFP)
})
if err != nil {
Expand All @@ -183,7 +183,7 @@ func (w *batcherWallet) updateCPFP(c context.Context, requiredFeeRate int) error

// Fetch UTXOs from the indexer
var utxos []UTXO
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
utxos, err = w.indexer.GetUTXOs(ctx, w.address)
return err
})
Expand Down Expand Up @@ -220,15 +220,15 @@ func (w *batcherWallet) updateCPFP(c context.Context, requiredFeeRate int) error
}

// Submit the CPFP transaction to the indexer
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
return w.indexer.SubmitTx(ctx, tx)
})
if err != nil {
return err
}

// Update the fee of all batches that got bumped
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
return w.cache.UpdateBatchFees(ctx, pendingTxs, int64(requiredFeeRate))
})
if err != nil {
Expand Down Expand Up @@ -266,7 +266,7 @@ func (w *batcherWallet) buildCPFPTx(c context.Context, utxos []UTXO, spendReques
var err error

// Get UTXOs for spend requests
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
spendUTXOs, spendUTXOsMap, balanceOfScripts, err = getUTXOsForSpendRequest(ctx, w.indexer, spendRequests)
return err
})
Expand Down Expand Up @@ -322,7 +322,7 @@ func (w *batcherWallet) buildCPFPTx(c context.Context, utxos []UTXO, spendReques
}

// Sign the spend inputs
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
return signSpendTx(ctx, tx, signIdx, spendRequests, spendUTXOsMap, w.indexer, w.privateKey)
})
if err != nil {
Expand All @@ -341,8 +341,8 @@ func (w *batcherWallet) buildCPFPTx(c context.Context, utxos []UTXO, spendReques

var sacpsInAmount int64
var sacpOutAmount int64
err = withContextTimeout(c, DefaultContextTimeout, func(ctx context.Context) error {
sacpsInAmount, sacpOutAmount, err = getTotalInAndOutSACPs(ctx, sacps, w.indexer)
err = withContextTimeout(c, DefaultAPITimeout, func(ctx context.Context) error {
sacpsInAmount, sacpOutAmount, err = getSACPAmounts(ctx, sacps, w.indexer)
return err
})

Expand Down
Loading

0 comments on commit b600524

Please sign in to comment.