wallet: refactor txToOutputs to use walletdb.Update

To make sure we don't create any manual DB transactions, we refactor the
txToOutputs method to use walletdb.Update and the new
walletdb.ErrDryRunRollBack error for making sure a rollback is issued.
This commit is contained in:
Oliver Gugger 2021-07-19 13:32:00 +02:00
parent 178152bcd0
commit f07fdfb6b9
No known key found for this signature in database
GPG key ID: 8E4256593F177720

View file

@ -95,7 +95,7 @@ func (s secretSource) GetScript(addr btcutil.Address) ([]byte, error) {
} }
// txToOutputs creates a signed transaction which includes each output from // txToOutputs creates a signed transaction which includes each output from
// outputs. Previous outputs to reedeem are chosen from the passed account's // outputs. Previous outputs to redeem are chosen from the passed account's
// UTXO set and minconf policy. An additional output may be added to return // UTXO set and minconf policy. An additional output may be added to return
// change to the wallet. This output will have an address generated from the // change to the wallet. This output will have an address generated from the
// given key scope and account. If a key scope is not specified, the address // given key scope and account. If a key scope is not specified, the address
@ -109,37 +109,33 @@ func (s secretSource) GetScript(addr btcutil.Address) ([]byte, error) {
func (w *Wallet) txToOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope, func (w *Wallet) txToOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
account uint32, minconf int32, feeSatPerKb btcutil.Amount, account uint32, minconf int32, feeSatPerKb btcutil.Amount,
coinSelectionStrategy CoinSelectionStrategy, dryRun bool) ( coinSelectionStrategy CoinSelectionStrategy, dryRun bool) (
tx *txauthor.AuthoredTx, err error) { *txauthor.AuthoredTx, error) {
chainClient, err := w.requireChainClient() chainClient, err := w.requireChainClient()
if err != nil { if err != nil {
return nil, err return nil, err
} }
dbtx, err := w.db.BeginReadWriteTx()
if err != nil {
return nil, err
}
defer func() { _ = dbtx.Rollback() }()
addrmgrNs, changeSource, err := w.addrMgrWithChangeSource(
dbtx, keyScope, account,
)
if err != nil {
return nil, err
}
// Get current block's height and hash. // Get current block's height and hash.
bs, err := chainClient.BlockStamp() bs, err := chainClient.BlockStamp()
if err != nil { if err != nil {
return nil, err return nil, err
} }
var tx *txauthor.AuthoredTx
err = walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
addrmgrNs, changeSource, err := w.addrMgrWithChangeSource(
dbtx, keyScope, account,
)
if err != nil {
return err
}
eligible, err := w.findEligibleOutputs( eligible, err := w.findEligibleOutputs(
dbtx, keyScope, account, minconf, bs, dbtx, keyScope, account, minconf, bs,
) )
if err != nil { if err != nil {
return nil, err return err
} }
var inputSource txauthor.InputSource var inputSource txauthor.InputSource
@ -150,11 +146,12 @@ func (w *Wallet) txToOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
sort.Sort(sort.Reverse(byAmount(eligible))) sort.Sort(sort.Reverse(byAmount(eligible)))
inputSource = makeInputSource(eligible) inputSource = makeInputSource(eligible)
// Select coins at random. This prevents the creation of ever smaller // Select coins at random. This prevents the creation of ever
// utxos over time that may never become economical to spend. // smaller utxos over time that may never become economical to
// spend.
case CoinSelectionRandom: case CoinSelectionRandom:
// Skip inputs that do not raise the total transaction output // Skip inputs that do not raise the total transaction
// value at the requested fee rate. // output value at the requested fee rate.
var positivelyYielding []wtxmgr.Credit var positivelyYielding []wtxmgr.Credit
for _, output := range eligible { for _, output := range eligible {
output := output output := output
@ -163,7 +160,9 @@ func (w *Wallet) txToOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
continue continue
} }
positivelyYielding = append(positivelyYielding, output) positivelyYielding = append(
positivelyYielding, output,
)
} }
rand.Shuffle(len(positivelyYielding), func(i, j int) { rand.Shuffle(len(positivelyYielding), func(i, j int) {
@ -178,33 +177,35 @@ func (w *Wallet) txToOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
outputs, feeSatPerKb, inputSource, changeSource, outputs, feeSatPerKb, inputSource, changeSource,
) )
if err != nil { if err != nil {
return nil, err return err
} }
// Randomize change position, if change exists, before signing. This // Randomize change position, if change exists, before signing.
// doesn't affect the serialize size, so the change amount will still // This doesn't affect the serialize size, so the change amount
// be valid. // will still be valid.
if tx.ChangeIndex >= 0 { if tx.ChangeIndex >= 0 {
tx.RandomizeChangePosition() tx.RandomizeChangePosition()
} }
// If a dry run was requested, we return now before adding the input // If a dry run was requested, we return now before adding the
// scripts, and don't commit the database transaction. The DB will be // input scripts, and don't commit the database transaction.
// rolled back when this method returns to ensure the dry run didn't // By returning an error, we make sure the walletdb.Update call
// alter the DB in any way. // rolls back the transaction. But we'll react to this specific
// error outside of the DB transaction so we can still return
// the produced chain TX.
if dryRun { if dryRun {
return tx, nil return walletdb.ErrDryRunRollBack
} }
// Before committing the transaction, we'll sign our inputs. If the // Before committing the transaction, we'll sign our inputs. If
// inputs are part of a watch-only account, there's no private key // the inputs are part of a watch-only account, there's no
// information stored, so we'll skip signing such. // private key information stored, so we'll skip signing such.
var watchOnly bool var watchOnly bool
if keyScope == nil { if keyScope == nil {
// If a key scope wasn't specified, then coin selection was // If a key scope wasn't specified, then coin selection
// performed from the default wallet accounts (NP2WKH, P2WKH), // was performed from the default wallet accounts
// so any key scope provided doesn't impact the result of this // (NP2WKH, P2WKH), so any key scope provided doesn't
// call. // impact the result of this call.
watchOnly, err = w.Manager.IsWatchOnlyAccount( watchOnly, err = w.Manager.IsWatchOnlyAccount(
addrmgrNs, waddrmgr.KeyScopeBIP0084, account, addrmgrNs, waddrmgr.KeyScopeBIP0084, account,
) )
@ -214,45 +215,55 @@ func (w *Wallet) txToOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
) )
} }
if err != nil { if err != nil {
return nil, err return err
} }
if !watchOnly { if !watchOnly {
err = tx.AddAllInputScripts(secretSource{w.Manager, addrmgrNs}) err = tx.AddAllInputScripts(
secretSource{w.Manager, addrmgrNs},
)
if err != nil { if err != nil {
return nil, err return err
} }
err = validateMsgTx(tx.Tx, tx.PrevScripts, tx.PrevInputValues) err = validateMsgTx(
tx.Tx, tx.PrevScripts, tx.PrevInputValues,
)
if err != nil { if err != nil {
return nil, err return err
} }
} }
if err := dbtx.Commit(); err != nil {
return nil, err
}
if tx.ChangeIndex >= 0 && account == waddrmgr.ImportedAddrAccount { if tx.ChangeIndex >= 0 && account == waddrmgr.ImportedAddrAccount {
changeAmount := btcutil.Amount(tx.Tx.TxOut[tx.ChangeIndex].Value) changeAmount := btcutil.Amount(
log.Warnf("Spend from imported account produced change: moving"+ tx.Tx.TxOut[tx.ChangeIndex].Value,
" %v from imported account into default account.", changeAmount) )
log.Warnf("Spend from imported account produced "+
"change: moving %v from imported account into "+
"default account.", changeAmount)
} }
// Finally, we'll request the backend to notify us of the transaction // Finally, we'll request the backend to notify us of the
// that pays to the change address, if there is one, when it confirms. // transaction that pays to the change address, if there is one,
// when it confirms.
if tx.ChangeIndex >= 0 { if tx.ChangeIndex >= 0 {
changePkScript := tx.Tx.TxOut[tx.ChangeIndex].PkScript changePkScript := tx.Tx.TxOut[tx.ChangeIndex].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs( _, addrs, _, err := txscript.ExtractPkScriptAddrs(
changePkScript, w.chainParams, changePkScript, w.chainParams,
) )
if err != nil { if err != nil {
return nil, err return err
} }
if err := chainClient.NotifyReceived(addrs); err != nil { if err := chainClient.NotifyReceived(addrs); err != nil {
return nil, err return err
} }
} }
return nil
})
if err != nil && err != walletdb.ErrDryRunRollBack {
return nil, err
}
return tx, nil return tx, nil
} }