Merge pull request #8503 from ffranr/fix-err-wrap

Correct `fmt.Errorf` error wrapping instances
This commit is contained in:
Oliver Gugger authored and GitHub committed 2024-02-27 12:20:16 -06:00
commit 48a3d56335
106 files changed
+438 -396

No files matched your search

+4
View File
@@ -30,6 +30,10 @@ run:
- integration - integration
linters-settings: linters-settings:
errorlint:
# Check for incorrect fmt.Errorf error wrapping.
errorf: true
govet: govet:
# Don't report about shadowed variables # Don't report about shadowed variables
check-shadowing: false check-shadowing: false
+2 -2
View File
@@ -629,7 +629,7 @@ func (a *Agent) openChans(availableFunds btcutil.Amount, numChans uint32,
nodes[nID] = struct{}{} nodes[nID] = struct{}{}
return nil return nil
}); err != nil { }); err != nil {
return fmt.Errorf("unable to get graph nodes: %v", err) return fmt.Errorf("unable to get graph nodes: %w", err)
} }
// Use the heuristic to calculate a score for each node in the // Use the heuristic to calculate a score for each node in the
@@ -639,7 +639,7 @@ func (a *Agent) openChans(availableFunds btcutil.Amount, numChans uint32,
a.cfg.Graph, totalChans, chanSize, nodes, a.cfg.Graph, totalChans, chanSize, nodes,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to calculate node scores : %v", err) return fmt.Errorf("unable to calculate node scores : %w", err)
} }
log.Debugf("Got scores for %d nodes", len(scores)) log.Debugf("Got scores for %d nodes", len(scores))
+1 -1
View File
@@ -274,7 +274,7 @@ func TestWriteMessageChunking(t *testing.T) {
bytesWritten, err := localConn.Write(largeMessage) bytesWritten, err := localConn.Write(largeMessage)
if err != nil { if err != nil {
errCh <- fmt.Errorf("unable to write message: %v", err) errCh <- fmt.Errorf("unable to write message: %w", err)
return return
} }
+2 -2
View File
@@ -64,13 +64,13 @@ func (r *RotatingLogWriter) InitLogRotator(logFile string, maxLogFileSize int,
logDir, _ := filepath.Split(logFile) logDir, _ := filepath.Split(logFile)
err := os.MkdirAll(logDir, 0700) err := os.MkdirAll(logDir, 0700)
if err != nil { if err != nil {
return fmt.Errorf("failed to create log directory: %v", err) return fmt.Errorf("failed to create log directory: %w", err)
} }
r.logRotator, err = rotator.New( r.logRotator, err = rotator.New(
logFile, int64(maxLogFileSize*1024), false, maxLogFiles, logFile, int64(maxLogFileSize*1024), false, maxLogFiles,
) )
if err != nil { if err != nil {
return fmt.Errorf("failed to create file rotator: %v", err) return fmt.Errorf("failed to create file rotator: %w", err)
} }
// Run rotator as a goroutine now but make sure we catch any errors // Run rotator as a goroutine now but make sure we catch any errors
+4 -3
View File
@@ -636,7 +636,7 @@ func (b *BitcoindNotifier) handleBlockConnected(block chainntnfs.BlockEpoch) err
// clients. // clients.
rawBlock, err := b.GetBlock(block.Hash) rawBlock, err := b.GetBlock(block.Hash)
if err != nil { if err != nil {
return fmt.Errorf("unable to get block: %v", err) return fmt.Errorf("unable to get block: %w", err)
} }
utilBlock := btcutil.NewBlock(rawBlock) utilBlock := btcutil.NewBlock(rawBlock)
@@ -645,7 +645,7 @@ func (b *BitcoindNotifier) handleBlockConnected(block chainntnfs.BlockEpoch) err
// us. // us.
err = b.txNotifier.ConnectTip(utilBlock, uint32(block.Height)) err = b.txNotifier.ConnectTip(utilBlock, uint32(block.Height))
if err != nil { if err != nil {
return fmt.Errorf("unable to connect tip: %v", err) return fmt.Errorf("unable to connect tip: %w", err)
} }
chainntnfs.Log.Infof("New block: height=%v, sha=%v", block.Height, chainntnfs.Log.Infof("New block: height=%v, sha=%v", block.Height,
@@ -719,7 +719,8 @@ func (b *BitcoindNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
pkScript, b.chainParams, pkScript, b.chainParams,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse script: %v", err) return nil, fmt.Errorf("unable to parse script: %w",
err)
} }
if err := b.chainConn.NotifyReceived(addrs); err != nil { if err := b.chainConn.NotifyReceived(addrs); err != nil {
return nil, err return nil, err
+6 -4
View File
@@ -692,7 +692,7 @@ func (b *BtcdNotifier) handleBlockConnected(epoch chainntnfs.BlockEpoch) error {
// clients. // clients.
rawBlock, err := b.GetBlock(epoch.Hash) rawBlock, err := b.GetBlock(epoch.Hash)
if err != nil { if err != nil {
return fmt.Errorf("unable to get block: %v", err) return fmt.Errorf("unable to get block: %w", err)
} }
newBlock := &filteredBlock{ newBlock := &filteredBlock{
hash: *epoch.Hash, hash: *epoch.Hash,
@@ -706,7 +706,7 @@ func (b *BtcdNotifier) handleBlockConnected(epoch chainntnfs.BlockEpoch) error {
// us. // us.
err = b.txNotifier.ConnectTip(newBlock.block, newBlock.height) err = b.txNotifier.ConnectTip(newBlock.block, newBlock.height)
if err != nil { if err != nil {
return fmt.Errorf("unable to connect tip: %v", err) return fmt.Errorf("unable to connect tip: %w", err)
} }
chainntnfs.Log.Infof("New block: height=%v, sha=%v", epoch.Height, chainntnfs.Log.Infof("New block: height=%v, sha=%v", epoch.Height,
@@ -785,7 +785,8 @@ func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
pkScript, b.chainParams, pkScript, b.chainParams,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse script: %v", err) return nil, fmt.Errorf("unable to parse script: %w",
err)
} }
if err := b.chainConn.NotifyReceived(addrs); err != nil { if err := b.chainConn.NotifyReceived(addrs); err != nil {
return nil, err return nil, err
@@ -823,7 +824,8 @@ func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
pkScript, b.chainParams, pkScript, b.chainParams,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse address: %v", err) return nil, fmt.Errorf("unable to parse address: %w",
err)
} }
asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil) asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil)
+1 -1
View File
@@ -541,7 +541,7 @@ func GetClientMissedBlocks(chainConn ChainConn, clientBestBlock *BlockEpoch,
chainConn, startingHeight+1, notifierBestHeight+1, chainConn, startingHeight+1, notifierBestHeight+1,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to get missed blocks: %v", err) return nil, fmt.Errorf("unable to get missed blocks: %w", err)
} }
return missedBlocks, nil return missedBlocks, nil
+10 -8
View File
@@ -609,7 +609,8 @@ func (n *NeutrinoNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequ
key := builder.DeriveKey(blockHash) key := builder.DeriveKey(blockHash)
match, err := regFilter.Match(key, confRequest.PkScript.Script()) match, err := regFilter.Match(key, confRequest.PkScript.Script())
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to query filter: %v", err) return nil, fmt.Errorf("unable to query filter: %w",
err)
} }
// If there's no match, then we can continue forward to the // If there's no match, then we can continue forward to the
@@ -623,7 +624,8 @@ func (n *NeutrinoNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequ
// to send the proper response. // to send the proper response.
block, err := n.GetBlock(*blockHash) block, err := n.GetBlock(*blockHash)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to get block from network: %v", err) return nil, fmt.Errorf("unable to get block from "+
"network: %w", err)
} }
// For every transaction in the block, check which one matches // For every transaction in the block, check which one matches
@@ -663,11 +665,11 @@ func (n *NeutrinoNotifier) handleBlockConnected(newBlock *filteredBlock) error {
// result in the items we care about being dispatched. // result in the items we care about being dispatched.
rawBlock, err := n.GetBlock(newBlock.hash) rawBlock, err := n.GetBlock(newBlock.hash)
if err != nil { if err != nil {
return fmt.Errorf("unable to get full block: %v", err) return fmt.Errorf("unable to get full block: %w", err)
} }
err = n.txNotifier.ConnectTip(rawBlock, newBlock.height) err = n.txNotifier.ConnectTip(rawBlock, newBlock.height)
if err != nil { if err != nil {
return fmt.Errorf("unable to connect tip: %v", err) return fmt.Errorf("unable to connect tip: %w", err)
} }
chainntnfs.Log.Infof("New block: height=%v, sha=%v", newBlock.height, chainntnfs.Log.Infof("New block: height=%v, sha=%v", newBlock.height,
@@ -692,7 +694,7 @@ func (n *NeutrinoNotifier) handleBlockConnected(newBlock *filteredBlock) error {
func (n *NeutrinoNotifier) getFilteredBlock(epoch chainntnfs.BlockEpoch) (*filteredBlock, error) { func (n *NeutrinoNotifier) getFilteredBlock(epoch chainntnfs.BlockEpoch) (*filteredBlock, error) {
rawBlock, err := n.GetBlock(*epoch.Hash) rawBlock, err := n.GetBlock(*epoch.Hash)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to get block: %v", err) return nil, fmt.Errorf("unable to get block: %w", err)
} }
txns := rawBlock.Transactions() txns := rawBlock.Transactions()
@@ -800,7 +802,7 @@ func (n *NeutrinoNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
return nil, chainntnfs.ErrChainNotifierShuttingDown return nil, chainntnfs.ErrChainNotifierShuttingDown
} }
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to update filter: %v", err) return nil, fmt.Errorf("unable to update filter: %w", err)
} }
// If the txNotifier didn't return any details to perform a historical // If the txNotifier didn't return any details to perform a historical
@@ -937,7 +939,7 @@ func (n *NeutrinoNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
params := n.p2pNode.ChainParams() params := n.p2pNode.ChainParams()
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, &params) _, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, &params)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to extract script: %v", err) return nil, fmt.Errorf("unable to extract script: %w", err)
} }
// We'll send the filter update request to the notifier's main event // We'll send the filter update request to the notifier's main event
@@ -962,7 +964,7 @@ func (n *NeutrinoNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
return nil, chainntnfs.ErrChainNotifierShuttingDown return nil, chainntnfs.ErrChainNotifierShuttingDown
} }
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to update filter: %v", err) return nil, fmt.Errorf("unable to update filter: %w", err)
} }
// If a historical rescan was not requested by the txNotifier, then we // If a historical rescan was not requested by the txNotifier, then we
+2 -1
View File
@@ -67,7 +67,8 @@ func randPubKeyHashScript() ([]byte, *btcec.PrivateKey, error) {
func GetTestTxidAndScript(h *rpctest.Harness) (*chainhash.Hash, []byte, error) { func GetTestTxidAndScript(h *rpctest.Harness) (*chainhash.Hash, []byte, error) {
pkScript, _, err := randPubKeyHashScript() pkScript, _, err := randPubKeyHashScript()
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("unable to generate pkScript: %v", err) return nil, nil, fmt.Errorf("unable to generate pkScript: %w",
err)
} }
output := &wire.TxOut{Value: 2e8, PkScript: pkScript} output := &wire.TxOut{Value: 2e8, PkScript: pkScript}
txid, err := h.SendOutputs([]*wire.TxOut{output}, 10) txid, err := h.SendOutputs([]*wire.TxOut{output}, 10)
+1 -1
View File
@@ -72,7 +72,7 @@ func FetchBackupForChan(chanPoint wire.OutPoint, chanSource LiveChannelSource,
// the source to obtain any extra information that we may need. // the source to obtain any extra information that we may need.
staticChanBackup, err := assembleChanBackup(addrSource, targetChan) staticChanBackup, err := assembleChanBackup(addrSource, targetChan)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to create chan backup: %v", err) return nil, fmt.Errorf("unable to create chan backup: %w", err)
} }
return staticChanBackup, nil return staticChanBackup, nil
+5 -4
View File
@@ -93,17 +93,18 @@ func (b *MultiFile) UpdateAndSwap(newBackup PackedMulti) error {
var err error var err error
b.tempFile, err = os.Create(b.tempFileName) b.tempFile, err = os.Create(b.tempFileName)
if err != nil { if err != nil {
return fmt.Errorf("unable to create temp file: %v", err) return fmt.Errorf("unable to create temp file: %w", err)
} }
// With the file created, we'll write the new packed multi backup and // With the file created, we'll write the new packed multi backup and
// remove the temporary file all together once this method exits. // remove the temporary file all together once this method exits.
_, err = b.tempFile.Write([]byte(newBackup)) _, err = b.tempFile.Write([]byte(newBackup))
if err != nil { if err != nil {
return fmt.Errorf("unable to write backup to temp file: %v", err) return fmt.Errorf("unable to write backup to temp file: %w",
err)
} }
if err := b.tempFile.Sync(); err != nil { if err := b.tempFile.Sync(); err != nil {
return fmt.Errorf("unable to sync temp file: %v", err) return fmt.Errorf("unable to sync temp file: %w", err)
} }
defer os.Remove(b.tempFileName) defer os.Remove(b.tempFileName)
@@ -114,7 +115,7 @@ func (b *MultiFile) UpdateAndSwap(newBackup PackedMulti) error {
// sure to close the current file as some OSes don't support // sure to close the current file as some OSes don't support
// renaming a file that's already open (Windows). // renaming a file that's already open (Windows).
if err := b.tempFile.Close(); err != nil { if err := b.tempFile.Close(); err != nil {
return fmt.Errorf("unable to close file: %v", err) return fmt.Errorf("unable to close file: %w", err)
} }
// Finally, we'll attempt to atomically rename the temporary file to // Finally, we'll attempt to atomically rename the temporary file to
+1 -1
View File
@@ -16,7 +16,7 @@ import (
func makeFakePackedMulti() (PackedMulti, error) { func makeFakePackedMulti() (PackedMulti, error) {
newPackedMulti := make([]byte, 50) newPackedMulti := make([]byte, 50)
if _, err := rand.Read(newPackedMulti[:]); err != nil { if _, err := rand.Read(newPackedMulti[:]); err != nil {
return nil, fmt.Errorf("unable to make test backup: %v", err) return nil, fmt.Errorf("unable to make test backup: %w", err)
} }
return PackedMulti(newPackedMulti), nil return PackedMulti(newPackedMulti), nil
+2 -2
View File
@@ -92,7 +92,7 @@ func (m Multi) PackToWriter(w io.Writer, keyRing keychain.KeyRing) error {
// directly to the passed writer. // directly to the passed writer.
e, err := lnencrypt.KeyRingEncrypter(keyRing) e, err := lnencrypt.KeyRingEncrypter(keyRing)
if err != nil { if err != nil {
return fmt.Errorf("unable to generate encrypt key %v", err) return fmt.Errorf("unable to generate encrypt key %w", err)
} }
return e.EncryptPayloadToWriter(multiBackupBuffer.Bytes(), w) return e.EncryptPayloadToWriter(multiBackupBuffer.Bytes(), w)
@@ -107,7 +107,7 @@ func (m *Multi) UnpackFromReader(r io.Reader, keyRing keychain.KeyRing) error {
// encryption keys. // encryption keys.
e, err := lnencrypt.KeyRingEncrypter(keyRing) e, err := lnencrypt.KeyRingEncrypter(keyRing)
if err != nil { if err != nil {
return fmt.Errorf("unable to generate encrypt key %v", err) return fmt.Errorf("unable to generate encrypt key %w", err)
} }
plaintextBackup, err := e.DecryptPayloadFromReader(r) plaintextBackup, err := e.DecryptPayloadFromReader(r)
if err != nil { if err != nil {
+2 -2
View File
@@ -226,7 +226,7 @@ func (s *SubSwapper) updateBackupFile(closedChans ...wire.OutPoint) error {
var b bytes.Buffer var b bytes.Buffer
err = newMulti.PackToWriter(&b, s.keyRing) err = newMulti.PackToWriter(&b, s.keyRing)
if err != nil { if err != nil {
return fmt.Errorf("unable to pack multi backup: %v", err) return fmt.Errorf("unable to pack multi backup: %w", err)
} }
// Finally, we'll swap out the old backup for this new one in a single // Finally, we'll swap out the old backup for this new one in a single
@@ -234,7 +234,7 @@ func (s *SubSwapper) updateBackupFile(closedChans ...wire.OutPoint) error {
// channels. // channels.
err = s.Swapper.UpdateAndSwap(PackedMulti(b.Bytes())) err = s.Swapper.UpdateAndSwap(PackedMulti(b.Bytes()))
if err != nil { if err != nil {
return fmt.Errorf("unable to update multi backup: %v", err) return fmt.Errorf("unable to update multi backup: %w", err)
} }
return nil return nil
+1 -1
View File
@@ -36,7 +36,7 @@ func (m *mockSwapper) UpdateAndSwap(newBackup PackedMulti) error {
swapState, err := newBackup.Unpack(m.keyChain) swapState, err := newBackup.Unpack(m.keyChain)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode on disk swaps: %v", err) return fmt.Errorf("unable to decode on disk swaps: %w", err)
} }
m.swapState = swapState m.swapState = swapState
+2 -2
View File
@@ -362,7 +362,7 @@ func (s *Single) PackToWriter(w io.Writer, keyRing keychain.KeyRing) error {
// nonce that we used to the passed io.Reader. // nonce that we used to the passed io.Reader.
e, err := lnencrypt.KeyRingEncrypter(keyRing) e, err := lnencrypt.KeyRingEncrypter(keyRing)
if err != nil { if err != nil {
return fmt.Errorf("unable to generate encrypt key %v", err) return fmt.Errorf("unable to generate encrypt key %w", err)
} }
return e.EncryptPayloadToWriter(rawBytes.Bytes(), w) return e.EncryptPayloadToWriter(rawBytes.Bytes(), w)
} }
@@ -544,7 +544,7 @@ func (s *Single) Deserialize(r io.Reader) error {
func (s *Single) UnpackFromReader(r io.Reader, keyRing keychain.KeyRing) error { func (s *Single) UnpackFromReader(r io.Reader, keyRing keychain.KeyRing) error {
e, err := lnencrypt.KeyRingEncrypter(keyRing) e, err := lnencrypt.KeyRingEncrypter(keyRing)
if err != nil { if err != nil {
return fmt.Errorf("unable to generate key decrypter %v", err) return fmt.Errorf("unable to generate key decrypter %w", err)
} }
plaintext, err := e.DecryptPayloadFromReader(r) plaintext, err := e.DecryptPayloadFromReader(r)
if err != nil { if err != nil {
+20 -13
View File
@@ -1015,7 +1015,7 @@ func (c *OpenChannel) Refresh() error {
// We'll re-populating the in-memory channel with the info // We'll re-populating the in-memory channel with the info
// fetched from disk. // fetched from disk.
if err := fetchChanInfo(chanBucket, c); err != nil { if err := fetchChanInfo(chanBucket, c); err != nil {
return fmt.Errorf("unable to fetch chan info: %v", err) return fmt.Errorf("unable to fetch chan info: %w", err)
} }
// Also populate the channel's commitment states for both sides // Also populate the channel's commitment states for both sides
@@ -1869,13 +1869,13 @@ func putOpenChannel(chanBucket kvdb.RwBucket, channel *OpenChannel) error {
// First, we'll write out all the relatively static fields, that are // First, we'll write out all the relatively static fields, that are
// decided upon initial channel creation. // decided upon initial channel creation.
if err := putChanInfo(chanBucket, channel); err != nil { if err := putChanInfo(chanBucket, channel); err != nil {
return fmt.Errorf("unable to store chan info: %v", err) return fmt.Errorf("unable to store chan info: %w", err)
} }
// With the static channel info written out, we'll now write out the // With the static channel info written out, we'll now write out the
// current commitment state for both parties. // current commitment state for both parties.
if err := putChanCommitments(chanBucket, channel); err != nil { if err := putChanCommitments(chanBucket, channel); err != nil {
return fmt.Errorf("unable to store chan commitments: %v", err) return fmt.Errorf("unable to store chan commitments: %w", err)
} }
// Next, if this is a frozen channel, we'll add in the axillary // Next, if this is a frozen channel, we'll add in the axillary
@@ -1885,14 +1885,15 @@ func putOpenChannel(chanBucket kvdb.RwBucket, channel *OpenChannel) error {
chanBucket, channel.ThawHeight, chanBucket, channel.ThawHeight,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to store thaw height: %v", err) return fmt.Errorf("unable to store thaw height: %w",
err)
} }
} }
// Finally, we'll write out the revocation state for both parties // Finally, we'll write out the revocation state for both parties
// within a distinct key space. // within a distinct key space.
if err := putChanRevocationState(chanBucket, channel); err != nil { if err := putChanRevocationState(chanBucket, channel); err != nil {
return fmt.Errorf("unable to store chan revocations: %v", err) return fmt.Errorf("unable to store chan revocations: %w", err)
} }
return nil return nil
@@ -1910,13 +1911,14 @@ func fetchOpenChannel(chanBucket kvdb.RBucket,
// First, we'll read all the static information that changes less // First, we'll read all the static information that changes less
// frequently from disk. // frequently from disk.
if err := fetchChanInfo(chanBucket, channel); err != nil { if err := fetchChanInfo(chanBucket, channel); err != nil {
return nil, fmt.Errorf("unable to fetch chan info: %v", err) return nil, fmt.Errorf("unable to fetch chan info: %w", err)
} }
// With the static information read, we'll now read the current // With the static information read, we'll now read the current
// commitment state for both sides of the channel. // commitment state for both sides of the channel.
if err := fetchChanCommitments(chanBucket, channel); err != nil { if err := fetchChanCommitments(chanBucket, channel); err != nil {
return nil, fmt.Errorf("unable to fetch chan commitments: %v", err) return nil, fmt.Errorf("unable to fetch chan commitments: %w",
err)
} }
// Next, if this is a frozen channel, we'll add in the axillary // Next, if this is a frozen channel, we'll add in the axillary
@@ -1934,7 +1936,8 @@ func fetchOpenChannel(chanBucket kvdb.RBucket,
// Finally, we'll retrieve the current revocation state so we can // Finally, we'll retrieve the current revocation state so we can
// properly // properly
if err := fetchChanRevocationState(chanBucket, channel); err != nil { if err := fetchChanRevocationState(chanBucket, channel); err != nil {
return nil, fmt.Errorf("unable to fetch chan revocations: %v", err) return nil, fmt.Errorf("unable to fetch chan revocations: %w",
err)
} }
channel.Packager = NewChannelPackager(channel.ShortChannelID) channel.Packager = NewChannelPackager(channel.ShortChannelID)
@@ -2043,7 +2046,7 @@ func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment,
} }
if err = putChanInfo(chanBucket, c); err != nil { if err = putChanInfo(chanBucket, c); err != nil {
return fmt.Errorf("unable to store chan info: %v", err) return fmt.Errorf("unable to store chan info: %w", err)
} }
// With the proper bucket fetched, we'll now write the latest // With the proper bucket fetched, we'll now write the latest
@@ -2130,12 +2133,14 @@ func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment,
var b3 bytes.Buffer var b3 bytes.Buffer
err = serializeLogUpdates(&b3, unsignedUpdates) err = serializeLogUpdates(&b3, unsignedUpdates)
if err != nil { if err != nil {
return fmt.Errorf("unable to serialize log updates: %v", err) return fmt.Errorf("unable to serialize log updates: %w",
err)
} }
err = chanBucket.Put(remoteUnsignedLocalUpdatesKey, b3.Bytes()) err = chanBucket.Put(remoteUnsignedLocalUpdatesKey, b3.Bytes())
if err != nil { if err != nil {
return fmt.Errorf("unable to restore chanbucket: %v", err) return fmt.Errorf("unable to restore chanbucket: %w",
err)
} }
return nil return nil
@@ -3003,12 +3008,14 @@ func (c *OpenChannel) AdvanceCommitChainTail(fwdPkg *FwdPkg,
var b bytes.Buffer var b bytes.Buffer
err = serializeLogUpdates(&b, validUpdates) err = serializeLogUpdates(&b, validUpdates)
if err != nil { if err != nil {
return fmt.Errorf("unable to serialize log updates: %v", err) return fmt.Errorf("unable to serialize log updates: %w",
err)
} }
err = chanBucket.Put(unsignedAckedUpdatesKey, b.Bytes()) err = chanBucket.Put(unsignedAckedUpdatesKey, b.Bytes())
if err != nil { if err != nil {
return fmt.Errorf("unable to store under unsignedAckedUpdatesKey: %v", err) return fmt.Errorf("unable to store under "+
"unsignedAckedUpdatesKey: %w", err)
} }
// Persist the local updates the peer hasn't yet signed so they // Persist the local updates the peer hasn't yet signed so they
+1 -1
View File
@@ -497,7 +497,7 @@ func initChannelDB(db kvdb.Backend) error {
return putMeta(meta, tx) return putMeta(meta, tx)
}, func() {}) }, func() {})
if err != nil { if err != nil {
return fmt.Errorf("unable to create new channeldb: %v", err) return fmt.Errorf("unable to create new channeldb: %w", err)
} }
return nil return nil
+1 -1
View File
@@ -385,7 +385,7 @@ func initChannelGraph(db kvdb.Backend) error {
return err return err
}, func() {}) }, func() {})
if err != nil { if err != nil {
return fmt.Errorf("unable to create new channel graph: %v", err) return fmt.Errorf("unable to create new channel graph: %w", err)
} }
return nil return nil
+3 -3
View File
@@ -1212,7 +1212,7 @@ func DecodeFailure(r io.Reader, pver uint32) (FailureMessage, error) {
// is a 2 byte length followed by the payload itself. // is a 2 byte length followed by the payload itself.
var failureLength uint16 var failureLength uint16
if err := ReadElement(r, &failureLength); err != nil { if err := ReadElement(r, &failureLength); err != nil {
return nil, fmt.Errorf("unable to read error len: %v", err) return nil, fmt.Errorf("unable to read error len: %w", err)
} }
if failureLength > FailureMessageLength { if failureLength > FailureMessageLength {
return nil, fmt.Errorf("failure message is too "+ return nil, fmt.Errorf("failure message is too "+
@@ -1236,7 +1236,7 @@ func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) {
// the first two bytes of the buffer. // the first two bytes of the buffer.
var codeBytes [2]byte var codeBytes [2]byte
if _, err := io.ReadFull(r, codeBytes[:]); err != nil { if _, err := io.ReadFull(r, codeBytes[:]); err != nil {
return nil, fmt.Errorf("unable to read failure code: %v", err) return nil, fmt.Errorf("unable to read failure code: %w", err)
} }
failCode := FailCode(binary.BigEndian.Uint16(codeBytes[:])) failCode := FailCode(binary.BigEndian.Uint16(codeBytes[:]))
@@ -1244,7 +1244,7 @@ func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) {
// additional data if needed. // additional data if needed.
failure, err := makeEmptyOnionError(failCode) failure, err := makeEmptyOnionError(failCode)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to make empty error: %v", err) return nil, fmt.Errorf("unable to make empty error: %w", err)
} }
// Finally, if this failure has a payload, then we'll read that now as // Finally, if this failure has a payload, then we'll read that now as
@@ -223,7 +223,8 @@ func decodeShortChanIDs(r io.Reader) (ShortChanIDEncoding, []ShortChannelID, err
N: maxZlibBufSize, N: maxZlibBufSize,
}) })
if err != nil { if err != nil {
return 0, nil, fmt.Errorf("unable to create zlib reader: %v", err) return 0, nil, fmt.Errorf("unable to create zlib "+
"reader: %w", err)
} }
var ( var (
+3 -3
View File
@@ -86,7 +86,7 @@ func findOpenChannels(openChanBucket kvdb.RBucket) ([]*OpenChannel, error) {
} }
// Get the old channel info. // Get the old channel info.
if err := fetchChanInfo(chanBucket, c, true); err != nil { if err := fetchChanInfo(chanBucket, c, true); err != nil {
return fmt.Errorf("unable to fetch chan info: %v", err) return fmt.Errorf("unable to fetch chan info: %w", err)
} }
// Fetch the channel commitments, which are useful for freshly // Fetch the channel commitments, which are useful for freshly
@@ -154,7 +154,7 @@ func migrateBalances(tx kvdb.RwTx, c *OpenChannel) error {
// Get the initial balances. // Get the initial balances.
localAmt, remoteAmt, err := c.balancesAtHeight(chanBucket, 0) localAmt, remoteAmt, err := c.balancesAtHeight(chanBucket, 0)
if err != nil { if err != nil {
return fmt.Errorf("unable to get initial balances: %v", err) return fmt.Errorf("unable to get initial balances: %w", err)
} }
c.InitialLocalBalance = localAmt c.InitialLocalBalance = localAmt
@@ -162,7 +162,7 @@ func migrateBalances(tx kvdb.RwTx, c *OpenChannel) error {
// Update the channel info. // Update the channel info.
if err := putChanInfo(chanBucket, c, false); err != nil { if err := putChanInfo(chanBucket, c, false); err != nil {
return fmt.Errorf("unable to put chan info: %v", err) return fmt.Errorf("unable to put chan info: %w", err)
} }
return nil return nil
+2 -2
View File
@@ -76,7 +76,7 @@ func findOpenChannels(openChanBucket kvdb.RBucket) ([]*OpenChannel, error) {
// Get the old channel info. // Get the old channel info.
if err := FetchChanInfo(chanBucket, c, true); err != nil { if err := FetchChanInfo(chanBucket, c, true); err != nil {
return fmt.Errorf("unable to fetch chan info: %v", err) return fmt.Errorf("unable to fetch chan info: %w", err)
} }
channels = append(channels, c) channels = append(channels, c)
@@ -139,7 +139,7 @@ func migrateBalances(tx kvdb.RwTx, c *OpenChannel) error {
// `c.InitialRemoteBalance` then create the new tlv stream as // `c.InitialRemoteBalance` then create the new tlv stream as
// requested. // requested.
if err := PutChanInfo(chanBucket, c, false); err != nil { if err := PutChanInfo(chanBucket, c, false); err != nil {
return fmt.Errorf("unable to put chan info: %v", err) return fmt.Errorf("unable to put chan info: %w", err)
} }
return nil return nil
+8 -8
View File
@@ -82,7 +82,7 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error {
&c.IdentityPub, &c.Capacity, &c.TotalMSatSent, &c.IdentityPub, &c.Capacity, &c.TotalMSatSent,
&c.TotalMSatReceived, &c.TotalMSatReceived,
); err != nil { ); err != nil {
return fmt.Errorf("ReadElements got: %v", err) return fmt.Errorf("ReadElements got: %w", err)
} }
c.ChanType = mig25.ChannelType(chanType) c.ChanType = mig25.ChannelType(chanType)
@@ -92,15 +92,15 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error {
// transaction to, read the funding txn. // transaction to, read the funding txn.
if c.FundingTxPresent() { if c.FundingTxPresent() {
if err := mig.ReadElement(r, &c.FundingTxn); err != nil { if err := mig.ReadElement(r, &c.FundingTxn); err != nil {
return fmt.Errorf("read FundingTxn got: %v", err) return fmt.Errorf("read FundingTxn got: %w", err)
} }
} }
if err := mig.ReadChanConfig(r, &c.LocalChanCfg); err != nil { if err := mig.ReadChanConfig(r, &c.LocalChanCfg); err != nil {
return fmt.Errorf("read LocalChanCfg got: %v", err) return fmt.Errorf("read LocalChanCfg got: %w", err)
} }
if err := mig.ReadChanConfig(r, &c.RemoteChanCfg); err != nil { if err := mig.ReadChanConfig(r, &c.RemoteChanCfg); err != nil {
return fmt.Errorf("read RemoteChanCfg got: %v", err) return fmt.Errorf("read RemoteChanCfg got: %w", err)
} }
// Retrieve the boolean stored under lastWasRevokeKey. // Retrieve the boolean stored under lastWasRevokeKey.
@@ -114,7 +114,7 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error {
revokeReader := bytes.NewReader(lastWasRevokeBytes) revokeReader := bytes.NewReader(lastWasRevokeBytes)
err := mig.ReadElements(revokeReader, &c.LastWasRevoke) err := mig.ReadElements(revokeReader, &c.LastWasRevoke)
if err != nil { if err != nil {
return fmt.Errorf("read LastWasRevoke got: %v", err) return fmt.Errorf("read LastWasRevoke got: %w", err)
} }
} }
@@ -147,11 +147,11 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error {
) )
} }
if err != nil { if err != nil {
return fmt.Errorf("create tlv stream got: %v", err) return fmt.Errorf("create tlv stream got: %w", err)
} }
if err := ts.Decode(r); err != nil { if err := ts.Decode(r); err != nil {
return fmt.Errorf("decode tlv stream got: %v", err) return fmt.Errorf("decode tlv stream got: %w", err)
} }
// For the new format, attach the balance fields. // For the new format, attach the balance fields.
@@ -164,7 +164,7 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error {
if err := mig25.GetOptionalUpfrontShutdownScript( if err := mig25.GetOptionalUpfrontShutdownScript(
chanBucket, localUpfrontShutdownKey, &c.LocalShutdownScript, chanBucket, localUpfrontShutdownKey, &c.LocalShutdownScript,
); err != nil { ); err != nil {
return fmt.Errorf("local shutdown script got: %v", err) return fmt.Errorf("local shutdown script got: %w", err)
} }
return mig25.GetOptionalUpfrontShutdownScript( return mig25.GetOptionalUpfrontShutdownScript(
+2 -2
View File
@@ -65,7 +65,7 @@ func findHistoricalChannels(historicalBucket kvdb.RBucket) ([]*OpenChannel,
chanPointBuf := bytes.NewBuffer(cp) chanPointBuf := bytes.NewBuffer(cp)
err := mig.ReadOutpoint(chanPointBuf, &c.FundingOutpoint) err := mig.ReadOutpoint(chanPointBuf, &c.FundingOutpoint)
if err != nil { if err != nil {
return fmt.Errorf("read funding outpoint got: %v", err) return fmt.Errorf("read funding outpoint got: %w", err)
} }
// Read the sub-bucket. // Read the sub-bucket.
@@ -141,7 +141,7 @@ func migrateBalances(rootBucket kvdb.RwBucket, c *OpenChannel) error {
// Update the channel info. // Update the channel info.
if err := PutChanInfo(chanBucket, c, false); err != nil { if err := PutChanInfo(chanBucket, c, false); err != nil {
return fmt.Errorf("unable to put chan info: %v", err) return fmt.Errorf("unable to put chan info: %w", err)
} }
return nil return nil
+8 -8
View File
@@ -117,7 +117,7 @@ func MigrateRevocationLog(db kvdb.Backend, cfg MigrateRevLogConfig) error {
// make sure the logs are migrated as expected. // make sure the logs are migrated as expected.
err = kvdb.Update(db, validateMigration, func() {}) err = kvdb.Update(db, validateMigration, func() {})
if err != nil { if err != nil {
return fmt.Errorf("validate migration failed: %v", err) return fmt.Errorf("validate migration failed: %w", err)
} }
log.Info("Migration check passed, now deleting the old logs...") log.Info("Migration check passed, now deleting the old logs...")
@@ -125,7 +125,7 @@ func MigrateRevocationLog(db kvdb.Backend, cfg MigrateRevLogConfig) error {
// Once the migration completes, we can now safety delete the old // Once the migration completes, we can now safety delete the old
// revocation logs. // revocation logs.
if err := deleteOldBuckets(db); err != nil { if err := deleteOldBuckets(db); err != nil {
return fmt.Errorf("deleteOldBuckets err: %v", err) return fmt.Errorf("deleteOldBuckets err: %w", err)
} }
log.Info("Old revocation log buckets removed!") log.Info("Old revocation log buckets removed!")
@@ -146,7 +146,7 @@ func processMigration(tx kvdb.RwTx, cfg MigrateRevLogConfig) (bool, error) {
// Locate the next migration height. // Locate the next migration height.
locator, err := locateNextUpdateNum(openChanBucket) locator, err := locateNextUpdateNum(openChanBucket)
if err != nil { if err != nil {
return false, fmt.Errorf("locator got error: %v", err) return false, fmt.Errorf("locator got error: %w", err)
} }
// If the returned locator is nil, we've done migrating the logs. // If the returned locator is nil, we've done migrating the logs.
@@ -157,7 +157,7 @@ func processMigration(tx kvdb.RwTx, cfg MigrateRevLogConfig) (bool, error) {
// Read a list of old revocation logs. // Read a list of old revocation logs.
entryMap, err := readOldRevocationLogs(openChanBucket, locator, cfg) entryMap, err := readOldRevocationLogs(openChanBucket, locator, cfg)
if err != nil { if err != nil {
return false, fmt.Errorf("read old logs err: %v", err) return false, fmt.Errorf("read old logs err: %w", err)
} }
// Migrate the revocation logs. // Migrate the revocation logs.
@@ -232,7 +232,7 @@ func writeRevocationLogs(openChanBucket kvdb.RwBucket,
// Find the channel bucket. // Find the channel bucket.
chanBucket, err := locator.locateChanBucket(openChanBucket) chanBucket, err := locator.locateChanBucket(openChanBucket)
if err != nil { if err != nil {
return fmt.Errorf("locateChanBucket err: %v", err) return fmt.Errorf("locateChanBucket err: %w", err)
} }
// Create the new log bucket. // Create the new log bucket.
@@ -240,7 +240,7 @@ func writeRevocationLogs(openChanBucket kvdb.RwBucket,
revocationLogBucket, revocationLogBucket,
) )
if err != nil { if err != nil {
return fmt.Errorf("create log bucket err: %v", err) return fmt.Errorf("create log bucket err: %w", err)
} }
// Write the new logs. // Write the new logs.
@@ -345,7 +345,7 @@ func fetchLogStats(tx kvdb.RwTx) (uint64, uint64, error) {
// Locate the next migration height. // Locate the next migration height.
locator, err := locateNextUpdateNum(openChanBucket) locator, err := locateNextUpdateNum(openChanBucket)
if err != nil { if err != nil {
return 0, 0, fmt.Errorf("locator got error: %v", err) return 0, 0, fmt.Errorf("locator got error: %w", err)
} }
// If the returned locator is not nil, we still have un-migrated // If the returned locator is not nil, we still have un-migrated
@@ -491,7 +491,7 @@ func readOldRevocationLogs(openChanBucket kvdb.RwBucket,
c := &mig26.OpenChannel{} c := &mig26.OpenChannel{}
err := mig26.FetchChanInfo(chanBucket, c, false) err := mig26.FetchChanInfo(chanBucket, c, false)
if err != nil { if err != nil {
return fmt.Errorf("unable to fetch chan info: %v", err) return fmt.Errorf("unable to fetch chan info: %w", err)
} }
err = fetchChanRevocationState(chanBucket, c) err = fetchChanRevocationState(chanBucket, c)
+3 -3
View File
@@ -334,18 +334,18 @@ func setupTestLogs(db kvdb.Backend, c *mig26.OpenChannel,
// Save channel info. // Save channel info.
if err := mig26.PutChanInfo(chanBucket, c, false); err != nil { if err := mig26.PutChanInfo(chanBucket, c, false); err != nil {
return fmt.Errorf("PutChanInfo got %v", err) return fmt.Errorf("PutChanInfo got %w", err)
} }
// Save revocation state. // Save revocation state.
if err := putChanRevocationState(chanBucket, c); err != nil { if err := putChanRevocationState(chanBucket, c); err != nil {
return fmt.Errorf("putChanRevocationState got %v", err) return fmt.Errorf("putChanRevocationState got %w", err)
} }
// Create old logs. // Create old logs.
err = writeOldRevocationLogs(chanBucket, oldLogs) err = writeOldRevocationLogs(chanBucket, oldLogs)
if err != nil { if err != nil {
return fmt.Errorf("write old logs: %v", err) return fmt.Errorf("write old logs: %w", err)
} }
// Create new logs. // Create new logs.
@@ -156,7 +156,7 @@ func signDigestCompact(hash []byte) ([]byte, error) {
// ecdsa.SignCompact returns a pubkey-recoverable signature // ecdsa.SignCompact returns a pubkey-recoverable signature
sig, err := ecdsa.SignCompact(privKey, hash, isCompressedKey) sig, err := ecdsa.SignCompact(privKey, hash, isCompressedKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("can't sign the hash: %v", err) return nil, fmt.Errorf("can't sign the hash: %w", err)
} }
return sig, nil return sig, nil
+11 -10
View File
@@ -22,13 +22,13 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error {
// where these items will be housed. // where these items will be housed.
nodes, err := tx.CreateTopLevelBucket(nodeBucket) nodes, err := tx.CreateTopLevelBucket(nodeBucket)
if err != nil { if err != nil {
return fmt.Errorf("unable to create node bucket: %v", err) return fmt.Errorf("unable to create node bucket: %w", err)
} }
nodeUpdateIndex, err := nodes.CreateBucketIfNotExists( nodeUpdateIndex, err := nodes.CreateBucketIfNotExists(
nodeUpdateIndexBucket, nodeUpdateIndexBucket,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to create node update index: %v", err) return fmt.Errorf("unable to create node update index: %w", err)
} }
log.Infof("Populating new node update index bucket") log.Infof("Populating new node update index bucket")
@@ -57,7 +57,7 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error {
return nodeUpdateIndex.Put(indexKey[:], nil) return nodeUpdateIndex.Put(indexKey[:], nil)
}) })
if err != nil { if err != nil {
return fmt.Errorf("unable to update node indexes: %v", err) return fmt.Errorf("unable to update node indexes: %w", err)
} }
log.Infof("Populating new edge update index bucket") log.Infof("Populating new edge update index bucket")
@@ -66,13 +66,13 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error {
// corresponding entry in the edge update index. // corresponding entry in the edge update index.
edges, err := tx.CreateTopLevelBucket(edgeBucket) edges, err := tx.CreateTopLevelBucket(edgeBucket)
if err != nil { if err != nil {
return fmt.Errorf("unable to create edge bucket: %v", err) return fmt.Errorf("unable to create edge bucket: %w", err)
} }
edgeUpdateIndex, err := edges.CreateBucketIfNotExists( edgeUpdateIndex, err := edges.CreateBucketIfNotExists(
edgeUpdateIndexBucket, edgeUpdateIndexBucket,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to create edge update index: %v", err) return fmt.Errorf("unable to create edge update index: %w", err)
} }
// We'll now run through each edge policy in the database, and update // We'll now run through each edge policy in the database, and update
@@ -109,7 +109,7 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error {
return edgeUpdateIndex.Put(indexKey[:], nil) return edgeUpdateIndex.Put(indexKey[:], nil)
}) })
if err != nil { if err != nil {
return fmt.Errorf("unable to update edge indexes: %v", err) return fmt.Errorf("unable to update edge indexes: %w", err)
} }
log.Infof("Migration to node and edge update indexes complete!") log.Infof("Migration to node and edge update indexes complete!")
@@ -169,7 +169,7 @@ func MigrateInvoiceTimeSeries(tx kvdb.RwTx) error {
invoiceReader := bytes.NewReader(invoiceBytesCopy) invoiceReader := bytes.NewReader(invoiceBytesCopy)
invoice, err := deserializeInvoiceLegacy(invoiceReader) invoice, err := deserializeInvoiceLegacy(invoiceReader)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode invoice: %v", err) return fmt.Errorf("unable to decode invoice: %w", err)
} }
// Now that we have the fully decoded invoice, we can update // Now that we have the fully decoded invoice, we can update
@@ -307,7 +307,8 @@ func MigrateInvoiceTimeSeriesOutgoingPayments(tx kvdb.RwTx) error {
paymentReader := bytes.NewReader(paymentCopy) paymentReader := bytes.NewReader(paymentCopy)
_, err := deserializeOutgoingPayment(paymentReader) _, err := deserializeOutgoingPayment(paymentReader)
if err != nil { if err != nil {
return fmt.Errorf("unable to deserialize payment: %v", err) return fmt.Errorf("unable to deserialize payment: %w",
err)
} }
// Now that we know the modifications was successful, we'll // Now that we know the modifications was successful, we'll
@@ -400,7 +401,7 @@ func MigrateEdgePolicies(tx kvdb.RwTx) error {
}) })
if err != nil { if err != nil {
return fmt.Errorf("unable to update edge policies: %v", err) return fmt.Errorf("unable to update edge policies: %w", err)
} }
log.Infof("Migration of edge policies complete!") log.Infof("Migration of edge policies complete!")
@@ -649,7 +650,7 @@ func MigrateOptionalChannelCloseSummaryFields(tx kvdb.RwTx) error {
return nil return nil
}) })
if err != nil { if err != nil {
return fmt.Errorf("unable to update closed channels: %v", err) return fmt.Errorf("unable to update closed channels: %w", err)
} }
// Now put the new format back into the DB. // Now put the new format back into the DB.
+8 -6
View File
@@ -57,31 +57,33 @@ func (c *chanDBRestorer) openChannelShell(backup chanbackup.Single) (
backup.LocalChanCfg.MultiSigKey.KeyLocator, backup.LocalChanCfg.MultiSigKey.KeyLocator,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to derive multi sig key: %v", err) return nil, fmt.Errorf("unable to derive multi sig key: %w",
err)
} }
backup.LocalChanCfg.RevocationBasePoint, err = c.secretKeys.DeriveKey( backup.LocalChanCfg.RevocationBasePoint, err = c.secretKeys.DeriveKey(
backup.LocalChanCfg.RevocationBasePoint.KeyLocator, backup.LocalChanCfg.RevocationBasePoint.KeyLocator,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to derive revocation key: %v", err) return nil, fmt.Errorf("unable to derive revocation key: %w",
err)
} }
backup.LocalChanCfg.PaymentBasePoint, err = c.secretKeys.DeriveKey( backup.LocalChanCfg.PaymentBasePoint, err = c.secretKeys.DeriveKey(
backup.LocalChanCfg.PaymentBasePoint.KeyLocator, backup.LocalChanCfg.PaymentBasePoint.KeyLocator,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to derive payment key: %v", err) return nil, fmt.Errorf("unable to derive payment key: %w", err)
} }
backup.LocalChanCfg.DelayBasePoint, err = c.secretKeys.DeriveKey( backup.LocalChanCfg.DelayBasePoint, err = c.secretKeys.DeriveKey(
backup.LocalChanCfg.DelayBasePoint.KeyLocator, backup.LocalChanCfg.DelayBasePoint.KeyLocator,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to derive delay key: %v", err) return nil, fmt.Errorf("unable to derive delay key: %w", err)
} }
backup.LocalChanCfg.HtlcBasePoint, err = c.secretKeys.DeriveKey( backup.LocalChanCfg.HtlcBasePoint, err = c.secretKeys.DeriveKey(
backup.LocalChanCfg.HtlcBasePoint.KeyLocator, backup.LocalChanCfg.HtlcBasePoint.KeyLocator,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to derive htlc key: %v", err) return nil, fmt.Errorf("unable to derive htlc key: %w", err)
} }
// The shachain root that seeds RevocationProducer for this channel. // The shachain root that seeds RevocationProducer for this channel.
@@ -161,7 +163,7 @@ func (c *chanDBRestorer) openChannelShell(backup chanbackup.Single) (
chanType |= channeldb.SimpleTaprootFeatureBit chanType |= channeldb.SimpleTaprootFeatureBit
default: default:
return nil, fmt.Errorf("unknown Single version: %v", err) return nil, fmt.Errorf("unknown Single version: %w", err)
} }
ltndLog.Infof("SCB Recovery: created channel shell for ChannelPoint"+ ltndLog.Infof("SCB Recovery: created channel shell for ChannelPoint"+
+3 -3
View File
@@ -43,12 +43,12 @@ func importMissionControl(ctx *cli.Context) error {
sourceNode, err := route.NewVertexFromStr(args[0]) sourceNode, err := route.NewVertexFromStr(args[0])
if err != nil { if err != nil {
return fmt.Errorf("please provide valid source node: %v", err) return fmt.Errorf("please provide valid source node: %w", err)
} }
destNode, err := route.NewVertexFromStr(args[1]) destNode, err := route.NewVertexFromStr(args[1])
if err != nil { if err != nil {
return fmt.Errorf("please provide valid dest node: %v", err) return fmt.Errorf("please provide valid dest node: %w", err)
} }
ts, err := strconv.ParseInt(args[2], 10, 64) ts, err := strconv.ParseInt(args[2], 10, 64)
@@ -63,7 +63,7 @@ func importMissionControl(ctx *cli.Context) error {
amt, err := strconv.ParseInt(args[3], 10, 64) amt, err := strconv.ParseInt(args[3], 10, 64)
if err != nil { if err != nil {
return fmt.Errorf("please provide amount in msat: %v", err) return fmt.Errorf("please provide amount in msat: %w", err)
} }
if amt <= 0 { if amt <= 0 {
+5 -4
View File
@@ -98,7 +98,8 @@ func addInvoice(ctx *cli.Context) error {
amt, err = strconv.ParseInt(args.First(), 10, 64) amt, err = strconv.ParseInt(args.First(), 10, 64)
args = args.Tail() args = args.Tail()
if err != nil { if err != nil {
return fmt.Errorf("unable to decode amt argument: %v", err) return fmt.Errorf("unable to decode amt argument: %w",
err)
} }
} }
@@ -110,12 +111,12 @@ func addInvoice(ctx *cli.Context) error {
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to parse preimage: %v", err) return fmt.Errorf("unable to parse preimage: %w", err)
} }
descHash, err = hex.DecodeString(ctx.String("description_hash")) descHash, err = hex.DecodeString(ctx.String("description_hash"))
if err != nil { if err != nil {
return fmt.Errorf("unable to parse description_hash: %v", err) return fmt.Errorf("unable to parse description_hash: %w", err)
} }
invoice := &lnrpc.Invoice{ invoice := &lnrpc.Invoice{
@@ -175,7 +176,7 @@ func lookupInvoice(ctx *cli.Context) error {
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to decode rhash argument: %v", err) return fmt.Errorf("unable to decode rhash argument: %w", err)
} }
req := &lnrpc.PaymentHash{ req := &lnrpc.PaymentHash{
+3 -3
View File
@@ -372,7 +372,7 @@ func printMacaroon(ctx *cli.Context) error {
// Decode the macaroon and its protobuf encoded internal identifier. // Decode the macaroon and its protobuf encoded internal identifier.
mac := &macaroon.Macaroon{} mac := &macaroon.Macaroon{}
if err = mac.UnmarshalBinary(macBytes); err != nil { if err = mac.UnmarshalBinary(macBytes); err != nil {
return fmt.Errorf("unable to decode macaroon: %v", err) return fmt.Errorf("unable to decode macaroon: %w", err)
} }
rawID := mac.Id() rawID := mac.Id()
if rawID[0] != byte(bakery.LatestVersion) { if rawID[0] != byte(bakery.LatestVersion) {
@@ -382,7 +382,7 @@ func printMacaroon(ctx *cli.Context) error {
idProto := rawID[1:] idProto := rawID[1:]
err = proto.Unmarshal(idProto, decodedID) err = proto.Unmarshal(idProto, decodedID)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode macaroon version: %v", err) return fmt.Errorf("unable to decode macaroon version: %w", err)
} }
// Prepare everything to be printed in a more human-readable format. // Prepare everything to be printed in a more human-readable format.
@@ -550,7 +550,7 @@ func applyMacaroonConstraints(ctx *cli.Context,
constrainedMac, err := macaroons.AddConstraints(mac, macConstraints...) constrainedMac, err := macaroons.AddConstraints(mac, macConstraints...)
if err != nil { if err != nil {
return nil, fmt.Errorf("error adding constraints: %v", err) return nil, fmt.Errorf("error adding constraints: %w", err)
} }
return constrainedMac, nil return constrainedMac, nil
+3 -3
View File
@@ -312,17 +312,17 @@ func queryProb(ctx *cli.Context) error {
fromNode, err := route.NewVertexFromStr(args.Get(0)) fromNode, err := route.NewVertexFromStr(args.Get(0))
if err != nil { if err != nil {
return fmt.Errorf("invalid from node key: %v", err) return fmt.Errorf("invalid from node key: %w", err)
} }
toNode, err := route.NewVertexFromStr(args.Get(1)) toNode, err := route.NewVertexFromStr(args.Get(1))
if err != nil { if err != nil {
return fmt.Errorf("invalid to node key: %v", err) return fmt.Errorf("invalid to node key: %w", err)
} }
amtSat, err := strconv.ParseUint(args.Get(2), 10, 64) amtSat, err := strconv.ParseUint(args.Get(2), 10, 64)
if err != nil { if err != nil {
return fmt.Errorf("invalid amt: %v", err) return fmt.Errorf("invalid amt: %w", err)
} }
amtMsat := lnwire.NewMSatFromSatoshis( amtMsat := lnwire.NewMSatFromSatoshis(
+6 -6
View File
@@ -382,7 +382,7 @@ func openChannel(ctx *cli.Context) error {
args.First(), 10, 64, args.First(), 10, 64,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to decode local amt: %v", err) return fmt.Errorf("unable to decode local amt: %w", err)
} }
args = args.Tail() args = args.Tail()
case !ctx.Bool("fundmax"): case !ctx.Bool("fundmax"):
@@ -420,7 +420,7 @@ func openChannel(ctx *cli.Context) error {
} else if args.Present() { } else if args.Present() {
req.PushSat, err = strconv.ParseInt(args.First(), 10, 64) req.PushSat, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode push amt: %v", err) return fmt.Errorf("unable to decode push amt: %w", err)
} }
} }
@@ -534,14 +534,14 @@ func openChannelPsbt(rpcCtx context.Context, ctx *cli.Context,
if basePsbt != "" { if basePsbt != "" {
basePsbtBytes, err = base64.StdEncoding.DecodeString(basePsbt) basePsbtBytes, err = base64.StdEncoding.DecodeString(basePsbt)
if err != nil { if err != nil {
return fmt.Errorf("error parsing base PSBT: %v", err) return fmt.Errorf("error parsing base PSBT: %w", err)
} }
} }
// Generate a new, random pending channel ID that we'll use as the main // Generate a new, random pending channel ID that we'll use as the main
// identifier when sending update messages to the RPC server. // identifier when sending update messages to the RPC server.
if _, err := rand.Read(pendingChanID[:]); err != nil { if _, err := rand.Read(pendingChanID[:]); err != nil {
return fmt.Errorf("unable to generate random chan ID: %v", err) return fmt.Errorf("unable to generate random chan ID: %w", err)
} }
fmt.Printf("Starting PSBT funding flow with pending channel ID %x.\n", fmt.Printf("Starting PSBT funding flow with pending channel ID %x.\n",
pendingChanID) pendingChanID)
@@ -591,7 +591,7 @@ func openChannelPsbt(rpcCtx context.Context, ctx *cli.Context,
// explicitly capture the signal. // explicitly capture the signal.
stream, err := client.OpenChannel(ctxc, req) stream, err := client.OpenChannel(ctxc, req)
if err != nil { if err != nil {
return fmt.Errorf("opening stream to server failed: %v", err) return fmt.Errorf("opening stream to server failed: %w", err)
} }
// We also need to spawn a goroutine that reads from the server. This // We also need to spawn a goroutine that reads from the server. This
@@ -859,7 +859,7 @@ func batchOpenChannel(ctx *cli.Context) error {
// marshaler that keeps the original snake case. // marshaler that keeps the original snake case.
var jsonChannels []*batchChannelJSON var jsonChannels []*batchChannelJSON
if err := json.Unmarshal([]byte(args.First()), &jsonChannels); err != nil { if err := json.Unmarshal([]byte(args.First()), &jsonChannels); err != nil {
return fmt.Errorf("error parsing channels JSON: %v", err) return fmt.Errorf("error parsing channels JSON: %w", err)
} }
req.Channels = make([]*lnrpc.BatchOpenChannel, len(jsonChannels)) req.Channels = make([]*lnrpc.BatchOpenChannel, len(jsonChannels))
+7 -5
View File
@@ -376,7 +376,8 @@ func sendPayment(ctx *cli.Context) error {
amount, err = strconv.ParseInt(args.First(), 10, 64) amount, err = strconv.ParseInt(args.First(), 10, 64)
args = args.Tail() args = args.Tail()
if err != nil { if err != nil {
return fmt.Errorf("unable to decode payment amount: %v", err) return fmt.Errorf("unable to decode payment amount: %w",
err)
} }
} }
@@ -1147,7 +1148,8 @@ func queryRoutes(ctx *cli.Context) error {
case args.Present(): case args.Present():
amt, err = strconv.ParseInt(args.First(), 10, 64) amt, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode amt argument: %v", err) return fmt.Errorf("unable to decode amt argument: %w",
err)
} }
default: default:
return fmt.Errorf("amt argument missing") return fmt.Errorf("amt argument missing")
@@ -1490,7 +1492,7 @@ func forwardingHistory(ctx *cli.Context) error {
startTime = uint64(now.Add(-time.Hour * 24).Unix()) startTime = uint64(now.Add(-time.Hour * 24).Unix())
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to decode start_time: %v", err) return fmt.Errorf("unable to decode start_time: %w", err)
} }
switch { switch {
@@ -1503,7 +1505,7 @@ func forwardingHistory(ctx *cli.Context) error {
endTime = uint64(now.Unix()) endTime = uint64(now.Unix())
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to decode end_time: %v", err) return fmt.Errorf("unable to decode end_time: %w", err)
} }
switch { switch {
@@ -1786,7 +1788,7 @@ func deletePayments(ctx *cli.Context) error {
}, },
) )
if err != nil { if err != nil {
return fmt.Errorf("error deleting payments: %v", err) return fmt.Errorf("error deleting payments: %w", err)
} }
} }
+8 -8
View File
@@ -119,7 +119,7 @@ func profileAdd(ctx *cli.Context) error {
// Create a profile struct from all the global options. // Create a profile struct from all the global options.
profile, err := profileFromContext(ctx, true, false) profile, err := profileFromContext(ctx, true, false)
if err != nil { if err != nil {
return fmt.Errorf("could not load global options: %v", err) return fmt.Errorf("could not load global options: %w", err)
} }
// Finally, all that's left is to get the profile name from either // Finally, all that's left is to get the profile name from either
@@ -181,7 +181,7 @@ func profileRemove(ctx *cli.Context) error {
// Load the default profile file. // Load the default profile file.
f, err := loadProfileFile(defaultProfileFile) f, err := loadProfileFile(defaultProfileFile)
if err != nil { if err != nil {
return fmt.Errorf("could not load profile file: %v", err) return fmt.Errorf("could not load profile file: %w", err)
} }
// Get the profile name from either positional argument or flag. // Get the profile name from either positional argument or flag.
@@ -260,7 +260,7 @@ func profileSetDefault(ctx *cli.Context) error {
// Load the default profile file. // Load the default profile file.
f, err := loadProfileFile(defaultProfileFile) f, err := loadProfileFile(defaultProfileFile)
if err != nil { if err != nil {
return fmt.Errorf("could not load profile file: %v", err) return fmt.Errorf("could not load profile file: %w", err)
} }
// Get the profile name from either positional argument or flag. // Get the profile name from either positional argument or flag.
@@ -313,7 +313,7 @@ func profileUnsetDefault(_ *cli.Context) error {
// Load the default profile file. // Load the default profile file.
f, err := loadProfileFile(defaultProfileFile) f, err := loadProfileFile(defaultProfileFile)
if err != nil { if err != nil {
return fmt.Errorf("could not load profile file: %v", err) return fmt.Errorf("could not load profile file: %w", err)
} }
// Save the file with the flag disabled. // Save the file with the flag disabled.
@@ -359,7 +359,7 @@ func profileAddMacaroon(ctx *cli.Context) error {
// yet. // yet.
f, err := loadProfileFile(defaultProfileFile) f, err := loadProfileFile(defaultProfileFile)
if err != nil { if err != nil {
return fmt.Errorf("could not load profile file: %v", err) return fmt.Errorf("could not load profile file: %w", err)
} }
// Finally, all that's left is to get the profile name from either // Finally, all that's left is to get the profile name from either
@@ -425,17 +425,17 @@ func profileAddMacaroon(ctx *cli.Context) error {
macPath := lncfg.CleanAndExpandPath(ctx.GlobalString("macaroonpath")) macPath := lncfg.CleanAndExpandPath(ctx.GlobalString("macaroonpath"))
macBytes, err := ioutil.ReadFile(macPath) macBytes, err := ioutil.ReadFile(macPath)
if err != nil { if err != nil {
return fmt.Errorf("unable to read macaroon path: %v", err) return fmt.Errorf("unable to read macaroon path: %w", err)
} }
mac := &macaroon.Macaroon{} mac := &macaroon.Macaroon{}
if err = mac.UnmarshalBinary(macBytes); err != nil { if err = mac.UnmarshalBinary(macBytes); err != nil {
return fmt.Errorf("unable to decode macaroon: %v", err) return fmt.Errorf("unable to decode macaroon: %w", err)
} }
macEntry := &macaroonEntry{ macEntry := &macaroonEntry{
Name: macName, Name: macName,
} }
if err = macEntry.storeMacaroon(mac, nil); err != nil { if err = macEntry.storeMacaroon(mac, nil); err != nil {
return fmt.Errorf("unable to store macaroon: %v", err) return fmt.Errorf("unable to store macaroon: %w", err)
} }
// All done, store the updated profile file. // All done, store the updated profile file.
+1 -1
View File
@@ -43,7 +43,7 @@ func version(ctx *cli.Context) error {
lndVersion, err := client.GetVersion(ctxc, &verrpc.VersionRequest{}) lndVersion, err := client.GetVersion(ctxc, &verrpc.VersionRequest{})
if err != nil { if err != nil {
printRespJSON(versions) printRespJSON(versions)
return fmt.Errorf("unable fetch version from lnd: %v", err) return fmt.Errorf("unable fetch version from lnd: %w", err)
} }
versions.Lnd = lndVersion versions.Lnd = lndVersion
+3 -3
View File
@@ -141,7 +141,7 @@ func create(ctx *cli.Context) error {
// Passed an invalid channel backup file. // Passed an invalid channel backup file.
case err != nil: case err != nil:
return fmt.Errorf("unable to parse chan backups: %v", err) return fmt.Errorf("unable to parse chan backups: %w", err)
// We have an SCB recovery option with a valid backup file. // We have an SCB recovery option with a valid backup file.
default: default:
@@ -356,7 +356,7 @@ mnemonicCheck:
} }
seedResp, err := client.GenSeed(ctxc, genSeedReq) seedResp, err := client.GenSeed(ctxc, genSeedReq)
if err != nil { if err != nil {
return fmt.Errorf("unable to generate seed: %v", err) return fmt.Errorf("unable to generate seed: %w", err)
} }
cipherSeedMnemonic = seedResp.CipherSeedMnemonic cipherSeedMnemonic = seedResp.CipherSeedMnemonic
@@ -721,7 +721,7 @@ func createWatchOnly(ctx *cli.Context) error {
jsonAccts := &walletrpc.ListAccountsResponse{} jsonAccts := &walletrpc.ListAccountsResponse{}
err = lnrpc.ProtoJSONUnmarshalOpts.Unmarshal(jsonBytes, jsonAccts) err = lnrpc.ProtoJSONUnmarshalOpts.Unmarshal(jsonBytes, jsonAccts)
if err != nil { if err != nil {
return fmt.Errorf("error parsing JSON: %v", err) return fmt.Errorf("error parsing JSON: %w", err)
} }
if len(jsonAccts.Accounts) == 0 { if len(jsonAccts.Accounts) == 0 {
return fmt.Errorf("cannot import empty account list") return fmt.Errorf("cannot import empty account list")
+13 -11
View File
@@ -365,7 +365,7 @@ func sendCoins(ctx *cli.Context) error {
return fmt.Errorf("Amount argument missing") return fmt.Errorf("Amount argument missing")
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to decode amount: %v", err) return fmt.Errorf("unable to decode amount: %w", err)
} }
if amt != 0 && ctx.Bool("sweepall") { if amt != 0 && ctx.Bool("sweepall") {
@@ -1015,7 +1015,7 @@ func closeAllChannels(ctx *cli.Context) error {
listReq := &lnrpc.ListChannelsRequest{} listReq := &lnrpc.ListChannelsRequest{}
openChannels, err := client.ListChannels(ctxc, listReq) openChannels, err := client.ListChannels(ctxc, listReq)
if err != nil { if err != nil {
return fmt.Errorf("unable to fetch open channels: %v", err) return fmt.Errorf("unable to fetch open channels: %w", err)
} }
if len(openChannels.Channels) == 0 { if len(openChannels.Channels) == 0 {
@@ -1302,7 +1302,8 @@ func parseChannelPoint(ctx *cli.Context) (*lnrpc.ChannelPoint, error) {
case args.Present(): case args.Present():
index, err := strconv.ParseUint(args.First(), 10, 32) index, err := strconv.ParseUint(args.First(), 10, 32)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to decode output index: %v", err) return nil, fmt.Errorf("unable to decode output "+
"index: %w", err)
} }
channelPoint.OutputIndex = uint32(index) channelPoint.OutputIndex = uint32(index)
default: default:
@@ -1548,7 +1549,7 @@ func listChannels(ctx *cli.Context) error {
if len(peer) > 0 { if len(peer) > 0 {
pk, err := route.NewVertexFromStr(peer) pk, err := route.NewVertexFromStr(peer)
if err != nil { if err != nil {
return fmt.Errorf("invalid --peer pubkey: %v", err) return fmt.Errorf("invalid --peer pubkey: %w", err)
} }
peerKey = pk[:] peerKey = pk[:]
@@ -2154,12 +2155,12 @@ func parseChanPoint(s string) (*lnrpc.ChannelPoint, error) {
index, err := strconv.ParseInt(split[1], 10, 64) index, err := strconv.ParseInt(split[1], 10, 64)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to decode output index: %v", err) return nil, fmt.Errorf("unable to decode output index: %w", err)
} }
txid, err := chainhash.NewHashFromStr(split[0]) txid, err := chainhash.NewHashFromStr(split[0])
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse hex string: %v", err) return nil, fmt.Errorf("unable to parse hex string: %w", err)
} }
return &lnrpc.ChannelPoint{ return &lnrpc.ChannelPoint{
@@ -2207,7 +2208,8 @@ func updateChannelPolicy(ctx *cli.Context) error {
case args.Present(): case args.Present():
baseFee, err = strconv.ParseInt(args.First(), 10, 64) baseFee, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode base_fee_msat: %v", err) return fmt.Errorf("unable to decode base_fee_msat: %w",
err)
} }
args = args.Tail() args = args.Tail()
default: default:
@@ -2224,7 +2226,7 @@ func updateChannelPolicy(ctx *cli.Context) error {
case args.Present(): case args.Present():
feeRate, err = strconv.ParseFloat(args.First(), 64) feeRate, err = strconv.ParseFloat(args.First(), 64)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode fee_rate: %v", err) return fmt.Errorf("unable to decode fee_rate: %w", err)
} }
args = args.Tail() args = args.Tail()
@@ -2265,7 +2267,7 @@ func updateChannelPolicy(ctx *cli.Context) error {
if chanPointStr != "" { if chanPointStr != "" {
chanPoint, err = parseChanPoint(chanPointStr) chanPoint, err = parseChanPoint(chanPointStr)
if err != nil { if err != nil {
return fmt.Errorf("unable to parse chan_point: %v", err) return fmt.Errorf("unable to parse chan_point: %w", err)
} }
} }
@@ -2425,7 +2427,7 @@ func exportChanBackup(ctx *cli.Context) error {
if chanPointStr != "" { if chanPointStr != "" {
chanPointRPC, err := parseChanPoint(chanPointStr) chanPointRPC, err := parseChanPoint(chanPointStr)
if err != nil { if err != nil {
return fmt.Errorf("unable to parse chan_point: %v", err) return fmt.Errorf("unable to parse chan_point: %w", err)
} }
chanBackup, err := client.ExportChannelBackup( chanBackup, err := client.ExportChannelBackup(
@@ -2751,7 +2753,7 @@ func restoreChanBackup(ctx *cli.Context) error {
_, err = client.RestoreChannelBackups(ctxc, &req) _, err = client.RestoreChannelBackups(ctxc, &req)
if err != nil { if err != nil {
return fmt.Errorf("unable to restore chan backups: %v", err) return fmt.Errorf("unable to restore chan backups: %w", err)
} }
return nil return nil
+5 -6
View File
@@ -1,7 +1,7 @@
package main package main
import ( import (
"errors" "encoding/hex"
"fmt" "fmt"
"math" "math"
"strconv" "strconv"
@@ -52,19 +52,18 @@ func TestParseChanPoint(t *testing.T) {
"3a5a467dc0bc:string", "3a5a467dc0bc:string",
true, true,
0, 0,
errors.New("unable to decode output index: strconv." + strconv.ErrSyntax,
"ParseInt: parsing \"string\": invalid syntax"),
}, { }, {
"not_hex:0", "not_hex:0",
true, true,
0, 0,
errors.New("unable to parse hex string: encoding/hex:" + hex.InvalidByteError('n'),
" invalid byte: U+006E 'n'"),
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
cp, err := parseChanPoint(tc.channelPoinStr) cp, err := parseChanPoint(tc.channelPoinStr)
require.Equal(t, tc.err, err) require.ErrorIs(t, err, tc.err)
require.Equal(t, tc.channelPointIsNil, cp == nil) require.Equal(t, tc.channelPointIsNil, cp == nil)
if !tc.channelPointIsNil { if !tc.channelPointIsNil {
require.Equal(t, tc.outputIndex, cp.OutputIndex) require.Equal(t, tc.outputIndex, cp.OutputIndex)
+1 -1
View File
@@ -50,7 +50,7 @@ func importGraph(ctx *cli.Context) error {
jsonGraph := &lnrpc.ChannelGraph{} jsonGraph := &lnrpc.ChannelGraph{}
err = lnrpc.ProtoJSONUnmarshalOpts.Unmarshal(jsonBytes, jsonGraph) err = lnrpc.ProtoJSONUnmarshalOpts.Unmarshal(jsonBytes, jsonGraph)
if err != nil { if err != nil {
return fmt.Errorf("error parsing JSON: %v", err) return fmt.Errorf("error parsing JSON: %w", err)
} }
res, err := client.ImportGraph(ctxc, jsonGraph) res, err := client.ImportGraph(ctxc, jsonGraph)
if err != nil { if err != nil {
+6 -5
View File
@@ -69,7 +69,7 @@ func settleInvoice(ctx *cli.Context) error {
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to parse preimage: %v", err) return fmt.Errorf("unable to parse preimage: %w", err)
} }
invoice := &invoicesrpc.SettleInvoiceMsg{ invoice := &invoicesrpc.SettleInvoiceMsg{
@@ -123,7 +123,7 @@ func cancelInvoice(ctx *cli.Context) error {
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to parse preimage: %v", err) return fmt.Errorf("unable to parse preimage: %w", err)
} }
invoice := &invoicesrpc.CancelInvoiceMsg{ invoice := &invoicesrpc.CancelInvoiceMsg{
@@ -212,7 +212,7 @@ func addHoldInvoice(ctx *cli.Context) error {
hash, err := hex.DecodeString(args.First()) hash, err := hex.DecodeString(args.First())
if err != nil { if err != nil {
return fmt.Errorf("unable to parse hash: %v", err) return fmt.Errorf("unable to parse hash: %w", err)
} }
args = args.Tail() args = args.Tail()
@@ -223,13 +223,14 @@ func addHoldInvoice(ctx *cli.Context) error {
if !ctx.IsSet("amt") && !ctx.IsSet("amt_msat") && args.Present() { if !ctx.IsSet("amt") && !ctx.IsSet("amt_msat") && args.Present() {
amt, err = strconv.ParseInt(args.First(), 10, 64) amt, err = strconv.ParseInt(args.First(), 10, 64)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode amt argument: %v", err) return fmt.Errorf("unable to decode amt argument: %w",
err)
} }
} }
descHash, err = hex.DecodeString(ctx.String("description_hash")) descHash, err = hex.DecodeString(ctx.String("description_hash"))
if err != nil { if err != nil {
return fmt.Errorf("unable to parse description_hash: %v", err) return fmt.Errorf("unable to parse description_hash: %w", err)
} }
invoice := &invoicesrpc.AddHoldInvoiceRequest{ invoice := &invoicesrpc.AddHoldInvoiceRequest{
+4 -4
View File
@@ -81,7 +81,7 @@ func (e *macaroonEntry) loadMacaroon(
// Parse the macaroon data into its native struct. // Parse the macaroon data into its native struct.
mac := &macaroon.Macaroon{} mac := &macaroon.Macaroon{}
if err := mac.UnmarshalBinary(macBytes); err != nil { if err := mac.UnmarshalBinary(macBytes); err != nil {
return nil, fmt.Errorf("unable to decode macaroon: %v", err) return nil, fmt.Errorf("unable to decode macaroon: %w", err)
} }
return mac, nil return mac, nil
} }
@@ -93,7 +93,7 @@ func (e *macaroonEntry) storeMacaroon(mac *macaroon.Macaroon, pw []byte) error {
// First of all, make sure we can serialize the macaroon. // First of all, make sure we can serialize the macaroon.
macBytes, err := mac.MarshalBinary() macBytes, err := mac.MarshalBinary()
if err != nil { if err != nil {
return fmt.Errorf("unable to marshal macaroon: %v", err) return fmt.Errorf("unable to marshal macaroon: %w", err)
} }
if len(pw) == 0 { if len(pw) == 0 {
@@ -106,14 +106,14 @@ func (e *macaroonEntry) storeMacaroon(mac *macaroon.Macaroon, pw []byte) error {
&pw, snacl.DefaultN, snacl.DefaultR, snacl.DefaultP, &pw, snacl.DefaultN, snacl.DefaultR, snacl.DefaultP,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to create encryption key: %v", err) return fmt.Errorf("unable to create encryption key: %w", err)
} }
// Encrypt the macaroon data with the derived key and store it in the // Encrypt the macaroon data with the derived key and store it in the
// human readable format snacl:<key_base64>:<encrypted_macaroon_base64>. // human readable format snacl:<key_base64>:<encrypted_macaroon_base64>.
encryptedMac, err := key.Encrypt(macBytes) encryptedMac, err := key.Encrypt(macBytes)
if err != nil { if err != nil {
return fmt.Errorf("unable to encrypt macaroon: %v", err) return fmt.Errorf("unable to encrypt macaroon: %w", err)
} }
keyB64 := base64.StdEncoding.EncodeToString(key.Marshal()) keyB64 := base64.StdEncoding.EncodeToString(key.Marshal())
+5 -5
View File
@@ -99,7 +99,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn {
// created from the global options in the CLI context. // created from the global options in the CLI context.
profile, err := getGlobalOptions(ctx, skipMacaroons) profile, err := getGlobalOptions(ctx, skipMacaroons)
if err != nil { if err != nil {
fatal(fmt.Errorf("could not load global options: %v", err)) fatal(fmt.Errorf("could not load global options: %w", err))
} }
// Create a dial options array. // Create a dial options array.
@@ -118,7 +118,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn {
// Load the specified TLS certificate. // Load the specified TLS certificate.
certPool, err := profile.cert() certPool, err := profile.cert()
if err != nil { if err != nil {
fatal(fmt.Errorf("could not create cert pool: %v", err)) fatal(fmt.Errorf("could not create cert pool: %w", err))
} }
// Build transport credentials from the certificate pool. If // Build transport credentials from the certificate pool. If
@@ -164,7 +164,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn {
// don't need to ask for it every time. // don't need to ask for it every time.
mac, err := macEntry.loadMacaroon(readPassword) mac, err := macEntry.loadMacaroon(readPassword)
if err != nil { if err != nil {
fatal(fmt.Errorf("could not load macaroon: %v", err)) fatal(fmt.Errorf("could not load macaroon: %w", err))
} }
macConstraints := []macaroons.Constraint{ macConstraints := []macaroons.Constraint{
@@ -199,7 +199,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn {
// Now we append the macaroon credentials to the dial options. // Now we append the macaroon credentials to the dial options.
cred, err := macaroons.NewMacaroonCredential(constrainedMac) cred, err := macaroons.NewMacaroonCredential(constrainedMac)
if err != nil { if err != nil {
fatal(fmt.Errorf("error cloning mac: %v", err)) fatal(fmt.Errorf("error cloning mac: %w", err))
} }
opts = append(opts, grpc.WithPerRPCCredentials(cred)) opts = append(opts, grpc.WithPerRPCCredentials(cred))
} }
@@ -228,7 +228,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn {
conn, err := grpc.Dial(profile.RPCServer, opts...) conn, err := grpc.Dial(profile.RPCServer, opts...)
if err != nil { if err != nil {
fatal(fmt.Errorf("unable to connect to RPC server: %v", err)) fatal(fmt.Errorf("unable to connect to RPC server: %w", err))
} }
return conn return conn
+4 -4
View File
@@ -174,7 +174,7 @@ func profileFromContext(ctx *cli.Context, store, skipMacaroons bool) (
} }
mac := &macaroon.Macaroon{} mac := &macaroon.Macaroon{}
if err = mac.UnmarshalBinary(macBytes); err != nil { if err = mac.UnmarshalBinary(macBytes); err != nil {
return nil, fmt.Errorf("unable to decode macaroon: %v", err) return nil, fmt.Errorf("unable to decode macaroon: %w", err)
} }
var pw []byte var pw []byte
@@ -193,7 +193,7 @@ func profileFromContext(ctx *cli.Context, store, skipMacaroons bool) (
} }
macEntry := &macaroonEntry{} macEntry := &macaroonEntry{}
if err = macEntry.storeMacaroon(mac, pw); err != nil { if err = macEntry.storeMacaroon(mac, pw); err != nil {
return nil, fmt.Errorf("unable to store macaroon: %v", err) return nil, fmt.Errorf("unable to store macaroon: %w", err)
} }
// We determine the name of the macaroon from the file itself but cut // We determine the name of the macaroon from the file itself but cut
@@ -241,7 +241,7 @@ func loadProfileFile(file string) (*profileFile, error) {
func saveProfileFile(file string, f *profileFile) error { func saveProfileFile(file string, f *profileFile) error {
content, err := f.marshalJSON() content, err := f.marshalJSON()
if err != nil { if err != nil {
return fmt.Errorf("could not marshal profile: %v", err) return fmt.Errorf("could not marshal profile: %w", err)
} }
return ioutil.WriteFile(file, content, 0644) return ioutil.WriteFile(file, content, 0644)
} }
@@ -269,7 +269,7 @@ func (f *profileFile) marshalJSON() ([]byte, error) {
var out bytes.Buffer var out bytes.Buffer
err = json.Indent(&out, b, "", " ") err = json.Indent(&out, b, "", " ")
if err != nil { if err != nil {
return nil, fmt.Errorf("error indenting profile JSON: %v", err) return nil, fmt.Errorf("error indenting profile JSON: %w", err)
} }
out.WriteString("\n") out.WriteString("\n")
return out.Bytes(), nil return out.Bytes(), nil
+1 -1
View File
@@ -34,7 +34,7 @@ func NewProtoOutPoint(op string) (*lnrpc.OutPoint, error) {
} }
outputIndex, err := strconv.Atoi(parts[1]) outputIndex, err := strconv.Atoi(parts[1])
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid output index: %v", err) return nil, fmt.Errorf("invalid output index: %w", err)
} }
return &lnrpc.OutPoint{ return &lnrpc.OutPoint{
TxidStr: txid, TxidStr: txid,
+6 -5
View File
@@ -1449,7 +1449,7 @@ func leaseOutput(ctx *cli.Context) error {
outpointStr := ctx.String("outpoint") outpointStr := ctx.String("outpoint")
outpoint, err := NewProtoOutPoint(outpointStr) outpoint, err := NewProtoOutPoint(outpointStr)
if err != nil { if err != nil {
return fmt.Errorf("error parsing outpoint: %v", err) return fmt.Errorf("error parsing outpoint: %w", err)
} }
lockIDStr := ctx.String("lockid") lockIDStr := ctx.String("lockid")
@@ -1458,7 +1458,7 @@ func leaseOutput(ctx *cli.Context) error {
} }
lockID, err := hex.DecodeString(lockIDStr) lockID, err := hex.DecodeString(lockIDStr)
if err != nil { if err != nil {
return fmt.Errorf("error parsing lockid: %v", err) return fmt.Errorf("error parsing lockid: %w", err)
} }
expiry := ctx.Uint64("expiry") expiry := ctx.Uint64("expiry")
@@ -1534,7 +1534,7 @@ func releaseOutput(ctx *cli.Context) error {
outpoint, err := NewProtoOutPoint(outpointStr) outpoint, err := NewProtoOutPoint(outpointStr)
if err != nil { if err != nil {
return fmt.Errorf("error parsing outpoint: %v", err) return fmt.Errorf("error parsing outpoint: %w", err)
} }
lockID := walletrpc.LndInternalLockID[:] lockID := walletrpc.LndInternalLockID[:]
@@ -1543,7 +1543,7 @@ func releaseOutput(ctx *cli.Context) error {
var err error var err error
lockID, err = hex.DecodeString(lockIDStr) lockID, err = hex.DecodeString(lockIDStr)
if err != nil { if err != nil {
return fmt.Errorf("error parsing lockid: %v", err) return fmt.Errorf("error parsing lockid: %w", err)
} }
} }
@@ -2003,7 +2003,8 @@ func importAccount(ctx *cli.Context) error {
ctx.String("master_key_fingerprint"), ctx.String("master_key_fingerprint"),
) )
if err != nil { if err != nil {
return fmt.Errorf("invalid master key fingerprint: %v", err) return fmt.Errorf("invalid master key fingerprint: %w",
err)
} }
} }
+3 -3
View File
@@ -67,7 +67,7 @@ func addTower(ctx *cli.Context) error {
} }
pubKey, err := hex.DecodeString(parts[0]) pubKey, err := hex.DecodeString(parts[0])
if err != nil { if err != nil {
return fmt.Errorf("invalid public key: %v", err) return fmt.Errorf("invalid public key: %w", err)
} }
address := parts[1] address := parts[1]
@@ -160,7 +160,7 @@ func removeTower(ctx *cli.Context) error {
} }
pubKey, err := hex.DecodeString(parts[0]) pubKey, err := hex.DecodeString(parts[0])
if err != nil { if err != nil {
return fmt.Errorf("invalid public key: %v", err) return fmt.Errorf("invalid public key: %w", err)
} }
var address string var address string
if len(parts) == 2 { if len(parts) == 2 {
@@ -264,7 +264,7 @@ func getTower(ctx *cli.Context) error {
// about. // about.
pubKey, err := hex.DecodeString(ctx.Args().Get(0)) pubKey, err := hex.DecodeString(ctx.Args().Get(0))
if err != nil { if err != nil {
return fmt.Errorf("invalid public key: %v", err) return fmt.Errorf("invalid public key: %w", err)
} }
client, cleanUp := getWtclient(ctx) client, cleanUp := getWtclient(ctx)
+8 -8
View File
@@ -425,7 +425,7 @@ func (d *DefaultWalletImpl) BuildWalletConfig(ctx context.Context,
// wallet unlocker. // wallet unlocker.
err = macaroonService.CreateUnlock(&privateWalletPw) err = macaroonService.CreateUnlock(&privateWalletPw)
if err != nil && err != macaroons.ErrAlreadyUnlocked { if err != nil && err != macaroons.ErrAlreadyUnlocked {
err := fmt.Errorf("unable to unlock macaroons: %v", err) err := fmt.Errorf("unable to unlock macaroons: %w", err)
d.logger.Error(err) d.logger.Error(err)
return nil, nil, nil, err return nil, nil, nil, err
} }
@@ -674,7 +674,7 @@ func (d *DefaultWalletImpl) BuildChainControl(
*walletConfig, partialChainControl.Cfg.BlockCache, *walletConfig, partialChainControl.Cfg.BlockCache,
) )
if err != nil { if err != nil {
err := fmt.Errorf("unable to create wallet controller: %v", err) err := fmt.Errorf("unable to create wallet controller: %w", err)
d.logger.Error(err) d.logger.Error(err)
return nil, nil, err return nil, nil, err
} }
@@ -730,7 +730,7 @@ func (d *DefaultWalletImpl) BuildChainControl(
lnWalletConfig, walletController, partialChainControl, lnWalletConfig, walletController, partialChainControl,
) )
if err != nil { if err != nil {
err := fmt.Errorf("unable to create chain control: %v", err) err := fmt.Errorf("unable to create chain control: %w", err)
d.logger.Error(err) d.logger.Error(err)
return nil, nil, err return nil, nil, err
} }
@@ -778,7 +778,7 @@ func (d *RPCSignerWalletImpl) BuildChainControl(
*walletConfig, partialChainControl.Cfg.BlockCache, *walletConfig, partialChainControl.Cfg.BlockCache,
) )
if err != nil { if err != nil {
err := fmt.Errorf("unable to create wallet controller: %v", err) err := fmt.Errorf("unable to create wallet controller: %w", err)
d.logger.Error(err) d.logger.Error(err)
return nil, nil, err return nil, nil, err
} }
@@ -818,7 +818,7 @@ func (d *RPCSignerWalletImpl) BuildChainControl(
lnWalletConfig, rpcKeyRing, partialChainControl, lnWalletConfig, rpcKeyRing, partialChainControl,
) )
if err != nil { if err != nil {
err := fmt.Errorf("unable to create chain control: %v", err) err := fmt.Errorf("unable to create chain control: %w", err)
d.logger.Error(err) d.logger.Error(err)
return nil, nil, err return nil, nil, err
} }
@@ -993,7 +993,7 @@ func (d *DefaultDatabaseBuilder) BuildDatabase(
case err != nil: case err != nil:
cleanUp() cleanUp()
err := fmt.Errorf("unable to open graph DB: %v", err) err := fmt.Errorf("unable to open graph DB: %w", err)
d.logger.Error(err) d.logger.Error(err)
return nil, nil, err return nil, nil, err
} }
@@ -1404,12 +1404,12 @@ func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) {
height, err := strconv.ParseUint(split[0], 10, 32) height, err := strconv.ParseUint(split[0], 10, 32)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid filter header height: %v", err) return nil, fmt.Errorf("invalid filter header height: %w", err)
} }
hash, err := chainhash.NewHashFromStr(split[1]) hash, err := chainhash.NewHashFromStr(split[1])
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid filter header hash: %v", err) return nil, fmt.Errorf("invalid filter header hash: %w", err)
} }
return &headerfs.FilterHeader{ return &headerfs.FilterHeader{
+1 -1
View File
@@ -924,7 +924,7 @@ func (b *BreachArbitrator) cleanupBreach(chanPoint *wire.OutPoint) error {
// With the channel closed, mark it in the database as such. // With the channel closed, mark it in the database as such.
err := b.cfg.DB.MarkChanFullyClosed(chanPoint) err := b.cfg.DB.MarkChanFullyClosed(chanPoint)
if err != nil { if err != nil {
return fmt.Errorf("unable to mark chan as closed: %v", err) return fmt.Errorf("unable to mark chan as closed: %w", err)
} }
// Justice has been carried out; we can safely delete the retribution // Justice has been carried out; we can safely delete the retribution
+1 -1
View File
@@ -1202,7 +1202,7 @@ func (c *chainWatcher) dispatchContractBreach(spendEvent *chainntnfs.SpendDetail
c.cfg.chanState.FundingOutpoint, broadcastStateNum) c.cfg.chanState.FundingOutpoint, broadcastStateNum)
if err := c.cfg.chanState.MarkBorked(); err != nil { if err := c.cfg.chanState.MarkBorked(); err != nil {
return fmt.Errorf("unable to mark channel as borked: %v", err) return fmt.Errorf("unable to mark channel as borked: %w", err)
} }
spendHeight := uint32(spendEvent.SpendingHeight) spendHeight := uint32(spendEvent.SpendingHeight)
+2 -2
View File
@@ -1659,7 +1659,7 @@ func (d *AuthenticatedGossiper) retransmitStaleAnns(now time.Time) error {
chanToUpdate.info, chanToUpdate.edge, chanToUpdate.info, chanToUpdate.edge,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to update channel: %v", err) return fmt.Errorf("unable to update channel: %w", err)
} }
// If we have a valid announcement to transmit, then we'll send // If we have a valid announcement to transmit, then we'll send
@@ -1715,7 +1715,7 @@ func (d *AuthenticatedGossiper) retransmitStaleAnns(now time.Time) error {
// With all the wire announcements properly crafted, we'll broadcast // With all the wire announcements properly crafted, we'll broadcast
// our known outgoing channels to all our immediate peers. // our known outgoing channels to all our immediate peers.
if err := d.cfg.Broadcast(nil, signedUpdates...); err != nil { if err := d.cfg.Broadcast(nil, signedUpdates...); err != nil {
return fmt.Errorf("unable to re-broadcast channels: %v", err) return fmt.Errorf("unable to re-broadcast channels: %w", err)
} }
return nil return nil
+1 -1
View File
@@ -806,7 +806,7 @@ func createTestCtx(t *testing.T, startHeight uint32) (*testCtx, error) {
}, selfKeyDesc) }, selfKeyDesc)
if err := gossiper.Start(); err != nil { if err := gossiper.Start(); err != nil {
return nil, fmt.Errorf("unable to start router: %v", err) return nil, fmt.Errorf("unable to start router: %w", err)
} }
// Mark the graph as synced in order to allow the announcements to be // Mark the graph as synced in order to allow the announcements to be
+3 -2
View File
@@ -904,7 +904,7 @@ func (g *GossipSyncer) processChanRangeReply(msg *lnwire.ReplyChannelRange) erro
g.cfg.isStillZombieChannel, g.cfg.isStillZombieChannel,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to filter chan ids: %v", err) return fmt.Errorf("unable to filter chan ids: %w", err)
} }
// As we've received the entirety of the reply, we no longer need to // As we've received the entirety of the reply, we no longer need to
@@ -1599,7 +1599,8 @@ func (g *GossipSyncer) handleSyncTransition(req *syncTransitionReq) error {
err := g.sendGossipTimestampRange(firstTimestamp, timestampRange) err := g.sendGossipTimestampRange(firstTimestamp, timestampRange)
if err != nil { if err != nil {
return fmt.Errorf("unable to send local update horizon: %v", err) return fmt.Errorf("unable to send local update horizon: %w",
err)
} }
g.setSyncType(req.newSyncType) g.setSyncType(req.newSyncType)
+2 -1
View File
@@ -1045,7 +1045,8 @@ func TestGossipSyncerReplyChanRangeQueryBlockRange(t *testing.T) {
go func() { go func() {
for _, query := range queryReqs { for _, query := range queryReqs {
if err := syncer.replyChanRangeQuery(query); err != nil { if err := syncer.replyChanRangeQuery(query); err != nil {
errCh <- fmt.Errorf("unable to issue query: %v", err) errCh <- fmt.Errorf("unable to issue query: %w",
err)
return return
} }
} }
@@ -272,6 +272,9 @@
interface](https://github.com/lightningnetwork/lnd/pull/7736) to simplify the interface](https://github.com/lightningnetwork/lnd/pull/7736) to simplify the
code. code.
* [Correct `fmt.Errorf` error wrapping
instances](https://github.com/lightningnetwork/lnd/pull/8503)
## Breaking Changes ## Breaking Changes
## Performance Improvements ## Performance Improvements
+4 -4
View File
@@ -72,7 +72,7 @@ func (c *batchChannel) processPendingUpdate(u *lnrpc.OpenStatusUpdate) error {
hash, err := chainhash.NewHash(pendingUpd.Txid) hash, err := chainhash.NewHash(pendingUpd.Txid)
if err != nil { if err != nil {
return fmt.Errorf("could not parse outpoint TX hash: %v", err) return fmt.Errorf("could not parse outpoint TX hash: %w", err)
} }
c.chanPoint = &wire.OutPoint{ c.chanPoint = &wire.OutPoint{
@@ -373,7 +373,7 @@ func (b *Batcher) BatchFund(ctx context.Context,
channel.pendingChanID, unsignedPacket, false, channel.pendingChanID, unsignedPacket, false,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error verifying PSBT: %v", err) return nil, fmt.Errorf("error verifying PSBT: %w", err)
} }
} }
@@ -391,7 +391,7 @@ func (b *Batcher) BatchFund(ctx context.Context,
finalTx := &wire.MsgTx{} finalTx := &wire.MsgTx{}
txReader := bytes.NewReader(finalizePsbtResp.RawFinalTx) txReader := bytes.NewReader(finalizePsbtResp.RawFinalTx)
if err := finalTx.Deserialize(txReader); err != nil { if err := finalTx.Deserialize(txReader); err != nil {
return nil, fmt.Errorf("error parsing signed raw TX: %v", err) return nil, fmt.Errorf("error parsing signed raw TX: %w", err)
} }
log.Tracef("[batchopenchannel] signed PSBT: %s", log.Tracef("[batchopenchannel] signed PSBT: %s",
base64.StdEncoding.EncodeToString(finalizePsbtResp.SignedPsbt)) base64.StdEncoding.EncodeToString(finalizePsbtResp.SignedPsbt))
@@ -403,7 +403,7 @@ func (b *Batcher) BatchFund(ctx context.Context,
channel.pendingChanID, nil, finalTx, channel.pendingChanID, nil, finalTx,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error finalizing PSBT: %v", err) return nil, fmt.Errorf("error finalizing PSBT: %w", err)
} }
} }
+6 -6
View File
@@ -1656,7 +1656,7 @@ func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer,
if err != nil { if err != nil {
f.failFundingFlow( f.failFundingFlow(
peer, cid, peer, cid,
fmt.Errorf("getUpfrontShutdownScript error: %v", err), fmt.Errorf("getUpfrontShutdownScript error: %w", err),
) )
return return
} }
@@ -3046,7 +3046,7 @@ func (f *Manager) handleFundingConfirmation(
err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx) err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
if err != nil { if err != nil {
// TODO(roasbeef): delete chan state? // TODO(roasbeef): delete chan state?
return fmt.Errorf("unable to validate channel: %v", err) return fmt.Errorf("unable to validate channel: %w", err)
} }
// Now that the channel has been validated, we'll persist an alias for // Now that the channel has been validated, we'll persist an alias for
@@ -3054,14 +3054,14 @@ func (f *Manager) handleFundingConfirmation(
if completeChan.NegotiatedAliasFeature() { if completeChan.NegotiatedAliasFeature() {
aliasScid, err := f.cfg.AliasManager.RequestAlias() aliasScid, err := f.cfg.AliasManager.RequestAlias()
if err != nil { if err != nil {
return fmt.Errorf("unable to request alias: %v", err) return fmt.Errorf("unable to request alias: %w", err)
} }
err = f.cfg.AliasManager.AddLocalAlias( err = f.cfg.AliasManager.AddLocalAlias(
aliasScid, confChannel.shortChanID, true, aliasScid, confChannel.shortChanID, true,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to request alias: %v", err) return fmt.Errorf("unable to request alias: %w", err)
} }
} }
@@ -3122,7 +3122,7 @@ func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
// will be unable to propose state transitions. // will be unable to propose state transitions.
nextRevocation, err := channel.NextRevocationKey() nextRevocation, err := channel.NextRevocationKey()
if err != nil { if err != nil {
return fmt.Errorf("unable to create next revocation: %v", err) return fmt.Errorf("unable to create next revocation: %w", err)
} }
channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation) channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
@@ -3574,7 +3574,7 @@ func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel,
// occur due to inconsistency in the OpenChannel struct. // occur due to inconsistency in the OpenChannel struct.
err = c.Refresh() err = c.Refresh()
if err != nil { if err != nil {
return fmt.Errorf("unable to refresh channel state: %v", err) return fmt.Errorf("unable to refresh channel state: %w", err)
} }
// Now that we have the confirmed transaction and the proper SCID, // Now that we have the confirmed transaction and the proper SCID,
+2 -2
View File
@@ -307,7 +307,7 @@ func createTestCircuit(ks htlcswitch.Keystone, cm htlcswitch.CircuitMap) error {
// should succeed. // should succeed.
_, err := cm.CommitCircuits(circuit) _, err := cm.CommitCircuits(circuit)
if err != nil { if err != nil {
return fmt.Errorf("failed to commit circuits: %v", err) return fmt.Errorf("failed to commit circuits: %w", err)
} }
// If the keystone has no outgoing key, we won't open it. // If the keystone has no outgoing key, we won't open it.
@@ -318,7 +318,7 @@ func createTestCircuit(ks htlcswitch.Keystone, cm htlcswitch.CircuitMap) error {
// Open the circuit, implicitly creates a keystone on disk. // Open the circuit, implicitly creates a keystone on disk.
err = cm.OpenCircuits(ks) err = cm.OpenCircuits(ks)
if err != nil { if err != nil {
return fmt.Errorf("failed to open circuits: %v", err) return fmt.Errorf("failed to open circuits: %w", err)
} }
return nil return nil
+1 -1
View File
@@ -63,7 +63,7 @@ func NewBoltBackendCreator(dbPath,
db, err := kvdb.GetBoltBackend(cfg) db, err := kvdb.GetBoltBackend(cfg)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not open boltdb: %v", err) return nil, fmt.Errorf("could not open boltdb: %w", err)
} }
return db, nil return db, nil
+1 -1
View File
@@ -686,7 +686,7 @@ func (f *interceptedForward) FailWithCode(code lnwire.FailCode) error {
// of the failure. // of the failure.
reason, err := f.packet.obfuscator.EncryptFirstHop(failureMsg) reason, err := f.packet.obfuscator.EncryptFirstHop(failureMsg)
if err != nil { if err != nil {
return fmt.Errorf("failed to encrypt failure reason %v", err) return fmt.Errorf("failed to encrypt failure reason %w", err)
} }
return f.resolve(&lnwire.UpdateFailHTLC{ return f.resolve(&lnwire.UpdateFailHTLC{
+1 -1
View File
@@ -3545,7 +3545,7 @@ func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
preimage, pd.HtlcIndex, pd.SourceRef, nil, nil, preimage, pd.HtlcIndex, pd.SourceRef, nil, nil,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to settle htlc: %v", err) return fmt.Errorf("unable to settle htlc: %w", err)
} }
// If the link is in hodl.BogusSettle mode, replace the preimage with a // If the link is in hodl.BogusSettle mode, replace the preimage with a
+4 -3
View File
@@ -497,7 +497,7 @@ func (s *Switch) GetAttemptResult(attemptID uint64, paymentHash lntypes.Hash,
deobfuscator, n, attemptID, paymentHash, deobfuscator, n, attemptID, paymentHash,
) )
if err != nil { if err != nil {
e := fmt.Errorf("unable to extract result: %v", err) e := fmt.Errorf("unable to extract result: %w", err)
log.Error(e) log.Error(e)
resultChan <- &PaymentResult{ resultChan <- &PaymentResult{
Error: e, Error: e,
@@ -709,7 +709,8 @@ func (s *Switch) ForwardPackets(linkQuit chan struct{},
default: default:
err := s.routeAsync(packet, fwdChan, linkQuit) err := s.routeAsync(packet, fwdChan, linkQuit)
if err != nil { if err != nil {
return fmt.Errorf("failed to forward packet %v", err) return fmt.Errorf("failed to forward packet %w",
err)
} }
numSent++ numSent++
} }
@@ -754,7 +755,7 @@ func (s *Switch) ForwardPackets(linkQuit chan struct{},
for _, packet := range addedPackets { for _, packet := range addedPackets {
err := s.routeAsync(packet, fwdChan, linkQuit) err := s.routeAsync(packet, fwdChan, linkQuit)
if err != nil { if err != nil {
return fmt.Errorf("failed to forward packet %v", err) return fmt.Errorf("failed to forward packet %w", err)
} }
numSent++ numSent++
} }
+1 -1
View File
@@ -1173,7 +1173,7 @@ func (h *hopNetwork) createChannelLink(server, peer *mockServer,
channel, channel,
) )
if err := server.htlcSwitch.AddLink(link); err != nil { if err := server.htlcSwitch.AddLink(link); err != nil {
return nil, fmt.Errorf("unable to add channel link: %v", err) return nil, fmt.Errorf("unable to add channel link: %w", err)
} }
go func() { go func() {
+6 -6
View File
@@ -268,7 +268,7 @@ func TestMuSig2KeyAggTestVectors(t *testing.T) {
func mustParseHex(str string) []byte { func mustParseHex(str string) []byte {
b, err := hex.DecodeString(str) b, err := hex.DecodeString(str)
if err != nil { if err != nil {
panic(fmt.Errorf("unable to parse hex: %v", err)) panic(fmt.Errorf("unable to parse hex: %w", err))
} }
return b return b
@@ -1868,10 +1868,10 @@ func getInfinityBytes() []byte {
func mustParseHex32(str string) [32]byte { func mustParseHex32(str string) [32]byte {
b, err := hex.DecodeString(str) b, err := hex.DecodeString(str)
if err != nil { if err != nil {
panic(fmt.Errorf("unable to parse hex: %v", err)) panic(fmt.Errorf("unable to parse hex: %w", err))
} }
if len(b) != 32 { if len(b) != 32 {
panic(fmt.Errorf("not a 32 byte slice: %v", err)) panic(fmt.Errorf("not a 32 byte slice: %w", err))
} }
return to32ByteSlice(b) return to32ByteSlice(b)
@@ -1880,10 +1880,10 @@ func mustParseHex32(str string) [32]byte {
func mustParsePubNonce(str string) [PubNonceSize]byte { func mustParsePubNonce(str string) [PubNonceSize]byte {
b, err := hex.DecodeString(str) b, err := hex.DecodeString(str)
if err != nil { if err != nil {
panic(fmt.Errorf("unable to parse hex: %v", err)) panic(fmt.Errorf("unable to parse hex: %w", err))
} }
if len(b) != PubNonceSize { if len(b) != PubNonceSize {
panic(fmt.Errorf("not a public nonce: %v", err)) panic(fmt.Errorf("not a public nonce: %w", err))
} }
return toPubNonceSlice(b) return toPubNonceSlice(b)
} }
@@ -1891,7 +1891,7 @@ func mustParsePubNonce(str string) [PubNonceSize]byte {
func canParsePubNonce(str string) [PubNonceSize]byte { func canParsePubNonce(str string) [PubNonceSize]byte {
b, err := hex.DecodeString(str) b, err := hex.DecodeString(str)
if err != nil { if err != nil {
panic(fmt.Errorf("unable to parse hex: %v", err)) panic(fmt.Errorf("unable to parse hex: %w", err))
} }
return toPubNonceSlice(b) return toPubNonceSlice(b)
} }
+3 -3
View File
@@ -157,10 +157,10 @@ func compactAndSwap(cfg *BoltBackendConfig) error {
// temporary DB file and close it before we write the new DB to it. // temporary DB file and close it before we write the new DB to it.
tempFile, err := os.Create(tempDestFilePath) tempFile, err := os.Create(tempDestFilePath)
if err != nil { if err != nil {
return fmt.Errorf("unable to create temp DB file: %v", err) return fmt.Errorf("unable to create temp DB file: %w", err)
} }
if err := tempFile.Close(); err != nil { if err := tempFile.Close(); err != nil {
return fmt.Errorf("unable to close file: %v", err) return fmt.Errorf("unable to close file: %w", err)
} }
// With the file created, we'll start the compaction and remove the // With the file created, we'll start the compaction and remove the
@@ -178,7 +178,7 @@ func compactAndSwap(cfg *BoltBackendConfig) error {
} }
initialSize, newSize, err := c.execute() initialSize, newSize, err := c.execute()
if err != nil { if err != nil {
return fmt.Errorf("error during compact: %v", err) return fmt.Errorf("error during compact: %w", err)
} }
log.Infof("DB compaction of %v successful, %d -> %d bytes (gain=%.2fx)", log.Infof("DB compaction of %v successful, %d -> %d bytes (gain=%.2fx)",
+1 -1
View File
@@ -115,7 +115,7 @@ func (cmd *compacter) execute() (int64, int64, error) {
// Run compaction. // Run compaction.
if err := cmd.compact(dst, src); err != nil { if err := cmd.compact(dst, src); err != nil {
return 0, 0, fmt.Errorf("error running compaction: %v", err) return 0, 0, fmt.Errorf("error running compaction: %w", err)
} }
// Report stats on new size. // Report stats on new size.
+6 -3
View File
@@ -287,7 +287,8 @@ func ParseLNAddressString(strAddress string, defaultPort string,
// Finally, parse the address string using our generic address parser. // Finally, parse the address string using our generic address parser.
addr, err := ParseAddressString(parsedAddr, defaultPort, tcpResolver) addr, err := ParseAddressString(parsedAddr, defaultPort, tcpResolver)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid lightning address address: %v", err) return nil, fmt.Errorf("invalid lightning address address: %w",
err)
} }
return &lnwire.NetAddress{ return &lnwire.NetAddress{
@@ -316,7 +317,8 @@ func ParseLNAddressPubkey(strAddress string) (*btcec.PublicKey, string, error) {
// Decode the hex pubkey to get the raw compressed pubkey bytes. // Decode the hex pubkey to get the raw compressed pubkey bytes.
pubKeyBytes, err := hex.DecodeString(parsedPubKey) pubKeyBytes, err := hex.DecodeString(parsedPubKey)
if err != nil { if err != nil {
return nil, "", fmt.Errorf("invalid lightning address pubkey: %v", err) return nil, "", fmt.Errorf("invalid lightning address "+
"pubkey: %w", err)
} }
// The compressed pubkey should have a length of exactly 33 bytes. // The compressed pubkey should have a length of exactly 33 bytes.
@@ -329,7 +331,8 @@ func ParseLNAddressPubkey(strAddress string) (*btcec.PublicKey, string, error) {
// key on the secp256k1 curve. // key on the secp256k1 curve.
pubKey, err := btcec.ParsePubKey(pubKeyBytes) pubKey, err := btcec.ParsePubKey(pubKeyBytes)
if err != nil { if err != nil {
return nil, "", fmt.Errorf("invalid lightning address pubkey: %v", err) return nil, "", fmt.Errorf("invalid lightning address "+
"pubkey: %w", err)
} }
return pubKey, parsedAddr, nil return pubKey, parsedAddr, nil
+4 -4
View File
@@ -263,7 +263,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath,
db.Etcd.CloneWithSubNamespace(NSChannelDB), db.Etcd.CloneWithSubNamespace(NSChannelDB),
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error opening etcd DB: %v", err) return nil, fmt.Errorf("error opening etcd DB: %w", err)
} }
closeFuncs[NSChannelDB] = etcdBackend.Close closeFuncs[NSChannelDB] = etcdBackend.Close
@@ -545,7 +545,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath,
AutoCompactMinAge: db.Bolt.AutoCompactMinAge, AutoCompactMinAge: db.Bolt.AutoCompactMinAge,
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("error opening bolt DB: %v", err) return nil, fmt.Errorf("error opening bolt DB: %w", err)
} }
closeFuncs[NSChannelDB] = boltBackend.Close closeFuncs[NSChannelDB] = boltBackend.Close
@@ -558,7 +558,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath,
AutoCompactMinAge: db.Bolt.AutoCompactMinAge, AutoCompactMinAge: db.Bolt.AutoCompactMinAge,
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("error opening macaroon DB: %v", err) return nil, fmt.Errorf("error opening macaroon DB: %w", err)
} }
closeFuncs[NSMacaroonDB] = macaroonBackend.Close closeFuncs[NSMacaroonDB] = macaroonBackend.Close
@@ -571,7 +571,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath,
AutoCompactMinAge: db.Bolt.AutoCompactMinAge, AutoCompactMinAge: db.Bolt.AutoCompactMinAge,
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("error opening decayed log DB: %v", err) return nil, fmt.Errorf("error opening decayed log DB: %w", err)
} }
closeFuncs[NSDecayedLogDB] = decayedLogBackend.Close closeFuncs[NSDecayedLogDB] = decayedLogBackend.Close
+2 -2
View File
@@ -72,7 +72,7 @@ func AdminAuthOptions(cfg *Config, skipMacaroons bool) ([]grpc.DialOption,
creds, err := credentials.NewClientTLSFromFile(cfg.TLSCertPath, "") creds, err := credentials.NewClientTLSFromFile(cfg.TLSCertPath, "")
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to read TLS cert: %v", err) return nil, fmt.Errorf("unable to read TLS cert: %w", err)
} }
// Create a dial options array. // Create a dial options array.
@@ -98,7 +98,7 @@ func AdminAuthOptions(cfg *Config, skipMacaroons bool) ([]grpc.DialOption,
// Now we append the macaroon credentials to the dial options. // Now we append the macaroon credentials to the dial options.
cred, err := macaroons.NewMacaroonCredential(mac) cred, err := macaroons.NewMacaroonCredential(mac)
if err != nil { if err != nil {
return nil, fmt.Errorf("error cloning mac: %v", err) return nil, fmt.Errorf("error cloning mac: %w", err)
} }
opts = append(opts, grpc.WithPerRPCCredentials(cred)) opts = append(opts, grpc.WithPerRPCCredentials(cred))
} }
+2 -2
View File
@@ -181,12 +181,12 @@ func parseOutPoint(s string) (*wire.OutPoint, error) {
index, err := strconv.ParseInt(split[1], 10, 32) index, err := strconv.ParseInt(split[1], 10, 32)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to decode output index: %v", err) return nil, fmt.Errorf("unable to decode output index: %w", err)
} }
txid, err := chainhash.NewHashFromStr(split[0]) txid, err := chainhash.NewHashFromStr(split[0])
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse hex string: %v", err) return nil, fmt.Errorf("unable to parse hex string: %w", err)
} }
return &wire.OutPoint{ return &wire.OutPoint{
+1 -1
View File
@@ -198,7 +198,7 @@ func (s *Server) Status(ctx context.Context,
bestBlock, err := s.cfg.NeutrinoCS.BestBlock() bestBlock, err := s.cfg.NeutrinoCS.BestBlock()
if err != nil { if err != nil {
return nil, fmt.Errorf("could not get best block: %v", err) return nil, fmt.Errorf("could not get best block: %w", err)
} }
peers := s.cfg.NeutrinoCS.Peers() peers := s.cfg.NeutrinoCS.Peers()
+2 -2
View File
@@ -335,7 +335,7 @@ func (s *Server) UpdateNodeAnnouncement(_ context.Context,
if req.Color != "" { if req.Color != "" {
color, err := lncfg.ParseHexColor(req.Color) color, err := lncfg.ParseHexColor(req.Color)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse color: %v", err) return nil, fmt.Errorf("unable to parse color: %w", err)
} }
if color != currentNodeAnn.RGBColor { if color != currentNodeAnn.RGBColor {
@@ -355,7 +355,7 @@ func (s *Server) UpdateNodeAnnouncement(_ context.Context,
if req.Alias != "" { if req.Alias != "" {
alias, err := lnwire.NewNodeAlias(req.Alias) alias, err := lnwire.NewNodeAlias(req.Alias)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid alias value: %v", err) return nil, fmt.Errorf("invalid alias value: %w", err)
} }
if alias != currentNodeAnn.Alias { if alias != currentNodeAnn.Alias {
resp.Ops = append(resp.Ops, &lnrpc.Op{ resp.Ops = append(resp.Ops, &lnrpc.Op{
+24 -24
View File
@@ -293,7 +293,7 @@ func (s *Server) SignOutputRaw(_ context.Context, in *SignReq) (*SignResp,
) )
txReader := bytes.NewReader(in.RawTxBytes) txReader := bytes.NewReader(in.RawTxBytes)
if err := txToSign.Deserialize(txReader); err != nil { if err := txToSign.Deserialize(txReader); err != nil {
return nil, fmt.Errorf("unable to decode tx: %v", err) return nil, fmt.Errorf("unable to decode tx: %w", err)
} }
var ( var (
@@ -520,7 +520,7 @@ func (s *Server) ComputeInputScript(ctx context.Context,
var txToSign wire.MsgTx var txToSign wire.MsgTx
txReader := bytes.NewReader(in.RawTxBytes) txReader := bytes.NewReader(in.RawTxBytes)
if err := txToSign.Deserialize(txReader); err != nil { if err := txToSign.Deserialize(txReader); err != nil {
return nil, fmt.Errorf("unable to decode tx: %v", err) return nil, fmt.Errorf("unable to decode tx: %w", err)
} }
var ( var (
@@ -636,7 +636,7 @@ func (s *Server) SignMessage(_ context.Context,
in.SchnorrSigTapTweak, in.Tag, in.SchnorrSigTapTweak, in.Tag,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("can't sign the hash: %v", err) return nil, fmt.Errorf("can't sign the hash: %w", err)
} }
sigParsed, err := schnorr.ParseSignature(sig.Serialize()) sigParsed, err := schnorr.ParseSignature(sig.Serialize())
@@ -659,7 +659,7 @@ func (s *Server) SignMessage(_ context.Context,
keyLocator, in.Msg, in.DoubleHash, keyLocator, in.Msg, in.DoubleHash,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("can't sign the hash: %v", err) return nil, fmt.Errorf("can't sign the hash: %w", err)
} }
return &SignMessageResp{ return &SignMessageResp{
@@ -673,11 +673,11 @@ func (s *Server) SignMessage(_ context.Context,
keyLocator, in.Msg, in.DoubleHash, keyLocator, in.Msg, in.DoubleHash,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("can't sign the hash: %v", err) return nil, fmt.Errorf("can't sign the hash: %w", err)
} }
wireSig, err := lnwire.NewSigFromSignature(sig) wireSig, err := lnwire.NewSigFromSignature(sig)
if err != nil { if err != nil {
return nil, fmt.Errorf("can't convert to wire format: %v", err) return nil, fmt.Errorf("can't convert to wire format: %w", err)
} }
return &SignMessageResp{ return &SignMessageResp{
Signature: wireSig.ToSignatureBytes(), Signature: wireSig.ToSignatureBytes(),
@@ -736,13 +736,13 @@ func (s *Server) VerifyMessage(_ context.Context,
pubkey, err := btcec.ParsePubKey(in.Pubkey) pubkey, err := btcec.ParsePubKey(in.Pubkey)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse pubkey: %v", err) return nil, fmt.Errorf("unable to parse pubkey: %w", err)
} }
// The signature must be fixed-size LN wire format encoded. // The signature must be fixed-size LN wire format encoded.
wireSig, err := lnwire.NewSigFromECDSARawSignature(in.Signature) wireSig, err := lnwire.NewSigFromECDSARawSignature(in.Signature)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to decode signature: %v", err) return nil, fmt.Errorf("failed to decode signature: %w", err)
} }
sig, err := wireSig.ToSignature() sig, err := wireSig.ToSignature()
if err != nil { if err != nil {
@@ -772,7 +772,7 @@ func (s *Server) DeriveSharedKey(_ context.Context, in *SharedKeyRequest) (
// Check that EphemeralPubkey is valid. // Check that EphemeralPubkey is valid.
ephemeralPubkey, err := parseRawKeyBytes(in.EphemeralPubkey) ephemeralPubkey, err := parseRawKeyBytes(in.EphemeralPubkey)
if err != nil { if err != nil {
return nil, fmt.Errorf("error in ephemeral pubkey: %v", err) return nil, fmt.Errorf("error in ephemeral pubkey: %w", err)
} }
if ephemeralPubkey == nil { if ephemeralPubkey == nil {
return nil, fmt.Errorf("must provide ephemeral pubkey") return nil, fmt.Errorf("must provide ephemeral pubkey")
@@ -820,7 +820,7 @@ func (s *Server) DeriveSharedKey(_ context.Context, in *SharedKeyRequest) (
// *btcec.PublicKey is returned instead. // *btcec.PublicKey is returned instead.
pk, err := parseRawKeyBytes(rawKeyBytes) pk, err := parseRawKeyBytes(rawKeyBytes)
if err != nil { if err != nil {
return nil, fmt.Errorf("error in raw pubkey: %v", err) return nil, fmt.Errorf("error in raw pubkey: %w", err)
} }
// Create a key descriptor. When the KeyIndex is not specified, it uses // Create a key descriptor. When the KeyIndex is not specified, it uses
@@ -838,7 +838,7 @@ func (s *Server) DeriveSharedKey(_ context.Context, in *SharedKeyRequest) (
// compressed shared point. // compressed shared point.
sharedKeyHash, err := s.cfg.KeyRing.ECDH(keyDescriptor, ephemeralPubkey) sharedKeyHash, err := s.cfg.KeyRing.ECDH(keyDescriptor, ephemeralPubkey)
if err != nil { if err != nil {
err := fmt.Errorf("unable to derive shared key: %v", err) err := fmt.Errorf("unable to derive shared key: %w", err)
log.Error(err) log.Error(err)
return nil, err return nil, err
} }
@@ -883,7 +883,7 @@ func (s *Server) MuSig2CombineKeys(_ context.Context,
version, allSignerPubKeys, true, tweaks, version, allSignerPubKeys, true, tweaks,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error combining keys: %v", err) return nil, fmt.Errorf("error combining keys: %w", err)
} }
var internalKeyBytes []byte var internalKeyBytes []byte
@@ -1008,7 +1008,7 @@ func (s *Server) MuSig2CreateSession(_ context.Context,
in.OtherSignerPublicNonces, true, in.OtherSignerPublicNonces, true,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing other nonces: %v", err) return nil, fmt.Errorf("error parsing other nonces: %w", err)
} }
// Are there any tweaks to apply to the combined public key? // Are there any tweaks to apply to the combined public key?
@@ -1024,7 +1024,7 @@ func (s *Server) MuSig2CreateSession(_ context.Context,
localNonces, localNonces,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error registering session: %v", err) return nil, fmt.Errorf("error registering session: %w", err)
} }
var internalKeyBytes []byte var internalKeyBytes []byte
@@ -1054,7 +1054,7 @@ func (s *Server) MuSig2RegisterNonces(_ context.Context,
// Check session ID length. // Check session ID length.
sessionID, err := parseMuSig2SessionID(in.SessionId) sessionID, err := parseMuSig2SessionID(in.SessionId)
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing session ID: %v", err) return nil, fmt.Errorf("error parsing session ID: %w", err)
} }
// Parse the other signing participants' nonces. We can't validate the // Parse the other signing participants' nonces. We can't validate the
@@ -1067,7 +1067,7 @@ func (s *Server) MuSig2RegisterNonces(_ context.Context,
in.OtherSignerPublicNonces, false, in.OtherSignerPublicNonces, false,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing other nonces: %v", err) return nil, fmt.Errorf("error parsing other nonces: %w", err)
} }
// Register the nonces now. // Register the nonces now.
@@ -1075,7 +1075,7 @@ func (s *Server) MuSig2RegisterNonces(_ context.Context,
sessionID, otherSignerNonces, sessionID, otherSignerNonces,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error registering nonces: %v", err) return nil, fmt.Errorf("error registering nonces: %w", err)
} }
return &MuSig2RegisterNoncesResponse{HaveAllNonces: haveAllNonces}, nil return &MuSig2RegisterNoncesResponse{HaveAllNonces: haveAllNonces}, nil
@@ -1093,7 +1093,7 @@ func (s *Server) MuSig2Sign(_ context.Context,
// Check session ID length. // Check session ID length.
sessionID, err := parseMuSig2SessionID(in.SessionId) sessionID, err := parseMuSig2SessionID(in.SessionId)
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing session ID: %v", err) return nil, fmt.Errorf("error parsing session ID: %w", err)
} }
// Schnorr signatures only work reliably if the message is 32 bytes. // Schnorr signatures only work reliably if the message is 32 bytes.
@@ -1107,12 +1107,12 @@ func (s *Server) MuSig2Sign(_ context.Context,
// Create our own partial signature with the local signing key. // Create our own partial signature with the local signing key.
partialSig, err := s.cfg.Signer.MuSig2Sign(sessionID, msg, in.Cleanup) partialSig, err := s.cfg.Signer.MuSig2Sign(sessionID, msg, in.Cleanup)
if err != nil { if err != nil {
return nil, fmt.Errorf("error signing: %v", err) return nil, fmt.Errorf("error signing: %w", err)
} }
serializedPartialSig, err := input.SerializePartialSignature(partialSig) serializedPartialSig, err := input.SerializePartialSignature(partialSig)
if err != nil { if err != nil {
return nil, fmt.Errorf("error serializing sig: %v", err) return nil, fmt.Errorf("error serializing sig: %w", err)
} }
return &MuSig2SignResponse{ return &MuSig2SignResponse{
@@ -1129,7 +1129,7 @@ func (s *Server) MuSig2CombineSig(_ context.Context,
// Check session ID length. // Check session ID length.
sessionID, err := parseMuSig2SessionID(in.SessionId) sessionID, err := parseMuSig2SessionID(in.SessionId)
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing session ID: %v", err) return nil, fmt.Errorf("error parsing session ID: %w", err)
} }
// Parse all other signatures. This can be called multiple times, so we // Parse all other signatures. This can be called multiple times, so we
@@ -1149,7 +1149,7 @@ func (s *Server) MuSig2CombineSig(_ context.Context,
sessionID, partialSigs, sessionID, partialSigs,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error combining signatures: %v", err) return nil, fmt.Errorf("error combining signatures: %w", err)
} }
resp := &MuSig2CombineSigResponse{ resp := &MuSig2CombineSigResponse{
@@ -1170,12 +1170,12 @@ func (s *Server) MuSig2Cleanup(_ context.Context,
// Check session ID length. // Check session ID length.
sessionID, err := parseMuSig2SessionID(in.SessionId) sessionID, err := parseMuSig2SessionID(in.SessionId)
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing session ID: %v", err) return nil, fmt.Errorf("error parsing session ID: %w", err)
} }
err = s.cfg.Signer.MuSig2Cleanup(sessionID) err = s.cfg.Signer.MuSig2Cleanup(sessionID)
if err != nil { if err != nil {
return nil, fmt.Errorf("error cleaning up session: %v", err) return nil, fmt.Errorf("error cleaning up session: %w", err)
} }
return &MuSig2CleanupResponse{}, nil return &MuSig2CleanupResponse{}, nil
+10 -10
View File
@@ -1434,7 +1434,7 @@ func (w *WalletKit) fundPsbtInternalWallet(account string,
packet, minConfs, feeSatPerKW, account, keyScope, packet, minConfs, feeSatPerKW, account, keyScope,
) )
if err != nil { if err != nil {
return fmt.Errorf("wallet couldn't fund PSBT: %v", err) return fmt.Errorf("wallet couldn't fund PSBT: %w", err)
} }
// Now we have obtained a set of coins that can be used to fund // Now we have obtained a set of coins that can be used to fund
@@ -1865,7 +1865,7 @@ func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) (
if err != nil { if err != nil {
log.Debugf("Error parsing PSBT: %v, raw input: %x", err, log.Debugf("Error parsing PSBT: %v, raw input: %x", err,
req.FundedPsbt) req.FundedPsbt)
return nil, fmt.Errorf("error parsing PSBT: %v", err) return nil, fmt.Errorf("error parsing PSBT: %w", err)
} }
// Before we attempt to sign the packet, ensure that every input either // Before we attempt to sign the packet, ensure that every input either
@@ -1886,14 +1886,14 @@ func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) (
// witness data attached, they will just be skipped. // witness data attached, they will just be skipped.
signedInputs, err := w.cfg.Wallet.SignPsbt(packet) signedInputs, err := w.cfg.Wallet.SignPsbt(packet)
if err != nil { if err != nil {
return nil, fmt.Errorf("error signing PSBT: %v", err) return nil, fmt.Errorf("error signing PSBT: %w", err)
} }
// Serialize the signed PSBT in both the packet and wire format. // Serialize the signed PSBT in both the packet and wire format.
var signedPsbtBytes bytes.Buffer var signedPsbtBytes bytes.Buffer
err = packet.Serialize(&signedPsbtBytes) err = packet.Serialize(&signedPsbtBytes)
if err != nil { if err != nil {
return nil, fmt.Errorf("error serializing PSBT: %v", err) return nil, fmt.Errorf("error serializing PSBT: %w", err)
} }
return &SignPsbtResponse{ return &SignPsbtResponse{
@@ -1928,7 +1928,7 @@ func (w *WalletKit) FinalizePsbt(_ context.Context,
bytes.NewReader(req.FundedPsbt), false, bytes.NewReader(req.FundedPsbt), false,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing PSBT: %v", err) return nil, fmt.Errorf("error parsing PSBT: %w", err)
} }
// The only check done at this level is to validate that the PSBT is // The only check done at this level is to validate that the PSBT is
@@ -1942,7 +1942,7 @@ func (w *WalletKit) FinalizePsbt(_ context.Context,
// witness data attached, this will fail. // witness data attached, this will fail.
err = w.cfg.Wallet.FinalizePsbt(packet, account) err = w.cfg.Wallet.FinalizePsbt(packet, account)
if err != nil { if err != nil {
return nil, fmt.Errorf("error finalizing PSBT: %v", err) return nil, fmt.Errorf("error finalizing PSBT: %w", err)
} }
var ( var (
@@ -1953,15 +1953,15 @@ func (w *WalletKit) FinalizePsbt(_ context.Context,
// Serialize the finalized PSBT in both the packet and wire format. // Serialize the finalized PSBT in both the packet and wire format.
err = packet.Serialize(&finalPsbtBytes) err = packet.Serialize(&finalPsbtBytes)
if err != nil { if err != nil {
return nil, fmt.Errorf("error serializing PSBT: %v", err) return nil, fmt.Errorf("error serializing PSBT: %w", err)
} }
finalTx, err := psbt.Extract(packet) finalTx, err := psbt.Extract(packet)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to extract final TX: %v", err) return nil, fmt.Errorf("unable to extract final TX: %w", err)
} }
err = finalTx.Serialize(&finalTxBytes) err = finalTx.Serialize(&finalTxBytes)
if err != nil { if err != nil {
return nil, fmt.Errorf("error serializing final TX: %v", err) return nil, fmt.Errorf("error serializing final TX: %w", err)
} }
return &FinalizePsbtResponse{ return &FinalizePsbtResponse{
@@ -2544,7 +2544,7 @@ func (w *WalletKit) ImportTapscript(_ context.Context,
internalKey, err := schnorr.ParsePubKey(req.InternalPublicKey) internalKey, err := schnorr.ParsePubKey(req.InternalPublicKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing internal key: %v", err) return nil, fmt.Errorf("error parsing internal key: %w", err)
} }
var tapscript *waddrmgr.Tapscript var tapscript *waddrmgr.Tapscript
+2 -2
View File
@@ -107,7 +107,7 @@ func newBackend(miner string, netParams *chaincfg.Params, extraArgs []string,
tempBitcoindDir, err := ioutil.TempDir("", "bitcoind") tempBitcoindDir, err := ioutil.TempDir("", "bitcoind")
if err != nil { if err != nil {
return nil, nil, return nil, nil,
fmt.Errorf("unable to create temp directory: %v", err) fmt.Errorf("unable to create temp directory: %w", err)
} }
zmqBlockAddr := fmt.Sprintf("tcp://127.0.0.1:%d", zmqBlockAddr := fmt.Sprintf("tcp://127.0.0.1:%d",
@@ -138,7 +138,7 @@ func newBackend(miner string, netParams *chaincfg.Params, extraArgs []string,
fmt.Printf("unable to remote temp dir %v: %v", fmt.Printf("unable to remote temp dir %v: %v",
tempBitcoindDir, err) tempBitcoindDir, err)
} }
return nil, nil, fmt.Errorf("couldn't start bitcoind: %v", err) return nil, nil, fmt.Errorf("couldn't start bitcoind: %w", err)
} }
cleanUp := func() error { cleanUp := func() error {
+5 -5
View File
@@ -327,7 +327,7 @@ func (hn *HarnessNode) ConnectRPCWithMacaroon(mac *macaroon.Macaroon) (
return err return err
}, wait.DefaultTimeout) }, wait.DefaultTimeout)
if err != nil { if err != nil {
return nil, fmt.Errorf("error reading TLS cert: %v", err) return nil, fmt.Errorf("error reading TLS cert: %w", err)
} }
opts := []grpc.DialOption{ opts := []grpc.DialOption{
@@ -343,7 +343,7 @@ func (hn *HarnessNode) ConnectRPCWithMacaroon(mac *macaroon.Macaroon) (
} }
macCred, err := macaroons.NewMacaroonCredential(mac) macCred, err := macaroons.NewMacaroonCredential(mac)
if err != nil { if err != nil {
return nil, fmt.Errorf("error cloning mac: %v", err) return nil, fmt.Errorf("error cloning mac: %w", err)
} }
opts = append(opts, grpc.WithPerRPCCredentials(macCred)) opts = append(opts, grpc.WithPerRPCCredentials(macCred))
@@ -452,7 +452,7 @@ func (hn *HarnessNode) Start(ctxt context.Context) error {
// Wait till the server is starting. // Wait till the server is starting.
if err := hn.WaitUntilStarted(); err != nil { if err := hn.WaitUntilStarted(); err != nil {
return fmt.Errorf("waiting for start got: %v", err) return fmt.Errorf("waiting for start got: %w", err)
} }
// Subscribe for topology updates. // Subscribe for topology updates.
@@ -544,7 +544,7 @@ func (hn *HarnessNode) waitTillServerState(
case <-time.After(wait.NodeStartTimeout): case <-time.After(wait.NodeStartTimeout):
return fmt.Errorf("timeout waiting for server state") return fmt.Errorf("timeout waiting for server state")
case err := <-errChan: case err := <-errChan:
return fmt.Errorf("receive server state err: %v", err) return fmt.Errorf("receive server state err: %w", err)
case <-done: case <-done:
return nil return nil
@@ -906,7 +906,7 @@ func executePgQuery(query string) error {
postgresDatabaseDsn("postgres"), postgresDatabaseDsn("postgres"),
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to connect to database: %v", err) return fmt.Errorf("unable to connect to database: %w", err)
} }
defer pool.Close() defer pool.Close()
+2 -2
View File
@@ -245,7 +245,7 @@ func (nw *nodeWatcher) WaitForChannelPolicyUpdate(
case <-timer: case <-timer:
expected, err := json.MarshalIndent(policy, "", "\t") expected, err := json.MarshalIndent(policy, "", "\t")
if err != nil { if err != nil {
return fmt.Errorf("encode policy err: %v", err) return fmt.Errorf("encode policy err: %w", err)
} }
policies, err := syncMapToJSON( policies, err := syncMapToJSON(
&nw.state.policyUpdates.Map, &nw.state.policyUpdates.Map,
@@ -274,7 +274,7 @@ func syncMapToJSON(state *sync.Map) ([]byte, error) {
}) })
policies, err := json.MarshalIndent(m, "", "\t") policies, err := json.MarshalIndent(m, "", "\t")
if err != nil { if err != nil {
return nil, fmt.Errorf("encode polices err: %v", err) return nil, fmt.Errorf("encode polices err: %w", err)
} }
return policies, nil return policies, nil
+1 -1
View File
@@ -246,7 +246,7 @@ func serializeTxWitness(txWitness wire.TxWitness) ([]byte, error) {
var witnessBytes bytes.Buffer var witnessBytes bytes.Buffer
err := psbt.WriteTxWitness(&witnessBytes, txWitness) err := psbt.WriteTxWitness(&witnessBytes, txWitness)
if err != nil { if err != nil {
return nil, fmt.Errorf("error serializing witness: %v", err) return nil, fmt.Errorf("error serializing witness: %w", err)
} }
return witnessBytes.Bytes(), nil return witnessBytes.Bytes(), nil
+1 -1
View File
@@ -1077,7 +1077,7 @@ func ParseUpfrontShutdownAddress(address string,
address, params, address, params,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid address: %v", err) return nil, fmt.Errorf("invalid address: %w", err)
} }
if !addr.IsForNet(params) { if !addr.IsForNet(params) {
+8 -8
View File
@@ -227,7 +227,7 @@ func (i *PsbtIntent) Verify(packet *psbt.Packet, skipFinalize bool) error {
// Try to locate the channel funding multisig output. // Try to locate the channel funding multisig output.
_, expectedOutput, err := i.FundingOutput() _, expectedOutput, err := i.FundingOutput()
if err != nil { if err != nil {
return fmt.Errorf("funding output cannot be created: %v", err) return fmt.Errorf("funding output cannot be created: %w", err)
} }
outputFound := false outputFound := false
outputSum := int64(0) outputSum := int64(0)
@@ -250,7 +250,7 @@ func (i *PsbtIntent) Verify(packet *psbt.Packet, skipFinalize bool) error {
} }
sum, err := psbt.SumUtxoInputValues(packet) sum, err := psbt.SumUtxoInputValues(packet)
if err != nil { if err != nil {
return fmt.Errorf("error determining input sum: %v", err) return fmt.Errorf("error determining input sum: %w", err)
} }
if sum <= outputSum { if sum <= outputSum {
return fmt.Errorf("input amount sum must be larger than " + return fmt.Errorf("input amount sum must be larger than " +
@@ -304,11 +304,11 @@ func (i *PsbtIntent) Finalize(packet *psbt.Packet) error {
// broadcast. // broadcast.
err := psbt.MaybeFinalizeAll(packet) err := psbt.MaybeFinalizeAll(packet)
if err != nil { if err != nil {
return fmt.Errorf("error finalizing PSBT: %v", err) return fmt.Errorf("error finalizing PSBT: %w", err)
} }
rawTx, err := psbt.Extract(packet) rawTx, err := psbt.Extract(packet)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract funding TX: %v", err) return fmt.Errorf("unable to extract funding TX: %w", err)
} }
return i.FinalizeRawTX(rawTx) return i.FinalizeRawTX(rawTx)
@@ -340,13 +340,13 @@ func (i *PsbtIntent) FinalizeRawTX(rawTx *wire.MsgTx) error {
rawTx.TxOut, i.PendingPsbt.UnsignedTx.TxOut, rawTx.TxOut, i.PendingPsbt.UnsignedTx.TxOut,
) )
if err != nil { if err != nil {
return fmt.Errorf("outputs differ from verified PSBT: %v", err) return fmt.Errorf("outputs differ from verified PSBT: %w", err)
} }
err = psbt.VerifyInputPrevOutpointsEqual( err = psbt.VerifyInputPrevOutpointsEqual(
rawTx.TxIn, i.PendingPsbt.UnsignedTx.TxIn, rawTx.TxIn, i.PendingPsbt.UnsignedTx.TxIn,
) )
if err != nil { if err != nil {
return fmt.Errorf("inputs differ from verified PSBT: %v", err) return fmt.Errorf("inputs differ from verified PSBT: %w", err)
} }
// We also check that we have a signed TX. This is only necessary if the // We also check that we have a signed TX. This is only necessary if the
@@ -354,7 +354,7 @@ func (i *PsbtIntent) FinalizeRawTX(rawTx *wire.MsgTx) error {
// extracting the TX from a PSBT. // extracting the TX from a PSBT.
err = verifyInputsSigned(rawTx.TxIn) err = verifyInputsSigned(rawTx.TxIn)
if err != nil { if err != nil {
return fmt.Errorf("inputs not signed: %v", err) return fmt.Errorf("inputs not signed: %w", err)
} }
// As far as we can tell, this TX is ok to be used as a funding // As far as we can tell, this TX is ok to be used as a funding
@@ -383,7 +383,7 @@ func (i *PsbtIntent) CompileFundingTx() (*wire.MsgTx, error) {
// Identify our funding outpoint now that we know everything's ready. // Identify our funding outpoint now that we know everything's ready.
_, txOut, err := i.FundingOutput() _, txOut, err := i.FundingOutput()
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot get funding output: %v", err) return nil, fmt.Errorf("cannot get funding output: %w", err)
} }
ok, idx := input.FindScriptOutputIndex(i.FinalTX, txOut.PkScript) ok, idx := input.FindScriptOutputIndex(i.FinalTX, txOut.PkScript)
if !ok { if !ok {
+2 -2
View File
@@ -6796,10 +6796,10 @@ func compareLogs(a, b *updateLog) error {
} }
if err := compareIndexes(a.updateIndex, b.updateIndex); err != nil { if err := compareIndexes(a.updateIndex, b.updateIndex); err != nil {
return fmt.Errorf("update indexes don't match: %v", err) return fmt.Errorf("update indexes don't match: %w", err)
} }
if err := compareIndexes(a.htlcIndex, b.htlcIndex); err != nil { if err := compareIndexes(a.htlcIndex, b.htlcIndex); err != nil {
return fmt.Errorf("htlc indexes don't match: %v", err) return fmt.Errorf("htlc indexes don't match: %w", err)
} }
if a.Len() != b.Len() { if a.Len() != b.Len() {
+11 -11
View File
@@ -156,7 +156,7 @@ func (r *RPCKeyRing) SendOutputs(outputs []*wire.TxOut,
&txIn.PreviousOutPoint, &txIn.PreviousOutPoint,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error looking up utxo: %v", err) return nil, fmt.Errorf("error looking up utxo: %w", err)
} }
if txscript.IsPayToTaproot(info.PkScript) { if txscript.IsPayToTaproot(info.PkScript) {
@@ -201,7 +201,7 @@ func (r *RPCKeyRing) SignPsbt(packet *psbt.Packet) ([]uint32, error) {
var buf bytes.Buffer var buf bytes.Buffer
if err := packet.Serialize(&buf); err != nil { if err := packet.Serialize(&buf); err != nil {
return nil, fmt.Errorf("error serializing PSBT: %v", err) return nil, fmt.Errorf("error serializing PSBT: %w", err)
} }
resp, err := r.walletClient.SignPsbt(ctxt, &walletrpc.SignPsbtRequest{ resp, err := r.walletClient.SignPsbt(ctxt, &walletrpc.SignPsbtRequest{
@@ -217,7 +217,7 @@ func (r *RPCKeyRing) SignPsbt(packet *psbt.Packet) ([]uint32, error) {
bytes.NewReader(resp.SignedPsbt), false, bytes.NewReader(resp.SignedPsbt), false,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing signed PSBT: %v", err) return nil, fmt.Errorf("error parsing signed PSBT: %w", err)
} }
// The caller expects the packet to be modified instead of a new // The caller expects the packet to be modified instead of a new
@@ -349,7 +349,7 @@ func (r *RPCKeyRing) FinalizePsbt(packet *psbt.Packet, _ string) error {
var witnessBytes bytes.Buffer var witnessBytes bytes.Buffer
err = psbt.WriteTxWitness(&witnessBytes, script.Witness) err = psbt.WriteTxWitness(&witnessBytes, script.Witness)
if err != nil { if err != nil {
return fmt.Errorf("error serializing witness: %v", err) return fmt.Errorf("error serializing witness: %w", err)
} }
packet.Inputs[idx].FinalScriptWitness = witnessBytes.Bytes() packet.Inputs[idx].FinalScriptWitness = witnessBytes.Bytes()
packet.Inputs[idx].FinalScriptSig = script.SigScript packet.Inputs[idx].FinalScriptSig = script.SigScript
@@ -359,7 +359,7 @@ func (r *RPCKeyRing) FinalizePsbt(packet *psbt.Packet, _ string) error {
// broadcast. // broadcast.
err = psbt.MaybeFinalizeAll(packet) err = psbt.MaybeFinalizeAll(packet)
if err != nil { if err != nil {
return fmt.Errorf("error finalizing PSBT: %v", err) return fmt.Errorf("error finalizing PSBT: %w", err)
} }
return nil return nil
@@ -732,7 +732,7 @@ func (r *RPCKeyRing) MuSig2CreateSession(bipVersion input.MuSig2Version,
info.CombinedKey, err = schnorr.ParsePubKey(resp.CombinedKey) info.CombinedKey, err = schnorr.ParsePubKey(resp.CombinedKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing combined key: %v", err) return nil, fmt.Errorf("error parsing combined key: %w", err)
} }
if tweaks.HasTaprootTweak() { if tweaks.HasTaprootTweak() {
@@ -891,7 +891,7 @@ func (r *RPCKeyRing) remoteSign(tx *wire.MsgTx, signDesc *input.SignDescriptor,
packet, err := packetFromTx(tx) packet, err := packetFromTx(tx)
if err != nil { if err != nil {
return nil, fmt.Errorf("error converting TX into PSBT: %v", err) return nil, fmt.Errorf("error converting TX into PSBT: %w", err)
} }
// We need to add witness information for all inputs! Otherwise, we'll // We need to add witness information for all inputs! Otherwise, we'll
@@ -1157,7 +1157,7 @@ func (r *RPCKeyRing) remoteSign(tx *wire.MsgTx, signDesc *input.SignDescriptor,
var buf bytes.Buffer var buf bytes.Buffer
if err := packet.Serialize(&buf); err != nil { if err := packet.Serialize(&buf); err != nil {
return nil, fmt.Errorf("error serializing PSBT: %v", err) return nil, fmt.Errorf("error serializing PSBT: %w", err)
} }
resp, err := r.walletClient.SignPsbt( resp, err := r.walletClient.SignPsbt(
@@ -1173,7 +1173,7 @@ func (r *RPCKeyRing) remoteSign(tx *wire.MsgTx, signDesc *input.SignDescriptor,
bytes.NewReader(resp.SignedPsbt), false, bytes.NewReader(resp.SignedPsbt), false,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing signed PSBT: %v", err) return nil, fmt.Errorf("error parsing signed PSBT: %w", err)
} }
// We expect a signature in the input now. // We expect a signature in the input now.
@@ -1278,12 +1278,12 @@ func connectRPC(hostPort, tlsCertPath, macaroonPath string,
} }
mac := &macaroon.Macaroon{} mac := &macaroon.Macaroon{}
if err := mac.UnmarshalBinary(macBytes); err != nil { if err := mac.UnmarshalBinary(macBytes); err != nil {
return nil, fmt.Errorf("error decoding macaroon: %v", err) return nil, fmt.Errorf("error decoding macaroon: %w", err)
} }
macCred, err := macaroons.NewMacaroonCredential(mac) macCred, err := macaroons.NewMacaroonCredential(mac)
if err != nil { if err != nil {
return nil, fmt.Errorf("error creating creds: %v", err) return nil, fmt.Errorf("error creating creds: %w", err)
} }
opts := []grpc.DialOption{ opts := []grpc.DialOption{
+11 -11
View File
@@ -264,7 +264,7 @@ func loadTestCredits(miner *rpctest.Harness, w *lnwallet.LightningWallet,
// give us btcPerOutput with each output. // give us btcPerOutput with each output.
satoshiPerOutput, err := btcutil.NewAmount(btcPerOutput) satoshiPerOutput, err := btcutil.NewAmount(btcPerOutput)
if err != nil { if err != nil {
return fmt.Errorf("unable to create amt: %v", err) return fmt.Errorf("unable to create amt: %w", err)
} }
expectedBalance, err := w.ConfirmedBalance(1, lnwallet.DefaultAccountName) expectedBalance, err := w.ConfirmedBalance(1, lnwallet.DefaultAccountName)
if err != nil { if err != nil {
@@ -1511,11 +1511,11 @@ func scriptFromKey(pubkey *btcec.PublicKey) ([]byte, error) {
pubkeyHash, &chaincfg.RegressionNetParams, pubkeyHash, &chaincfg.RegressionNetParams,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to create addr: %v", err) return nil, fmt.Errorf("unable to create addr: %w", err)
} }
keyScript, err := txscript.PayToAddrScript(keyAddr) keyScript, err := txscript.PayToAddrScript(keyAddr)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to generate script: %v", err) return nil, fmt.Errorf("unable to generate script: %w", err)
} }
return keyScript, nil return keyScript, nil
@@ -1526,17 +1526,17 @@ func mineAndAssert(r *rpctest.Harness, tx *wire.MsgTx) error {
txid := tx.TxHash() txid := tx.TxHash()
err := waitForMempoolTx(r, &txid) err := waitForMempoolTx(r, &txid)
if err != nil { if err != nil {
return fmt.Errorf("tx not relayed to miner: %v", err) return fmt.Errorf("tx not relayed to miner: %w", err)
} }
blockHashes, err := r.Client.Generate(1) blockHashes, err := r.Client.Generate(1)
if err != nil { if err != nil {
return fmt.Errorf("unable to generate block: %v", err) return fmt.Errorf("unable to generate block: %w", err)
} }
block, err := r.Client.GetBlock(blockHashes[0]) block, err := r.Client.GetBlock(blockHashes[0])
if err != nil { if err != nil {
return fmt.Errorf("unable to find block: %v", err) return fmt.Errorf("unable to find block: %w", err)
} }
if len(block.Transactions) != 2 { if len(block.Transactions) != 2 {
@@ -1564,7 +1564,7 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey,
// Generate the script we want to spend from. // Generate the script we want to spend from.
keyScript, err := scriptFromKey(fromPubKey) keyScript, err := scriptFromKey(fromPubKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to generate script: %v", err) return nil, fmt.Errorf("unable to generate script: %w", err)
} }
// We assume the output was paid to the keyScript made earlier. // We assume the output was paid to the keyScript made earlier.
@@ -1599,7 +1599,7 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey,
// Create a script to pay to. // Create a script to pay to.
payToScript, err := scriptFromKey(payToPubKey) payToScript, err := scriptFromKey(payToPubKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to generate script: %v", err) return nil, fmt.Errorf("unable to generate script: %w", err)
} }
tx1.AddTxOut(&wire.TxOut{ tx1.AddTxOut(&wire.TxOut{
Value: outputValue - int64(txFee), Value: outputValue - int64(txFee),
@@ -1623,7 +1623,7 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey,
// manually create a valid witness stack we'll use for signing. // manually create a valid witness stack we'll use for signing.
spendSig, err := signer.SignOutputRaw(tx1, signDesc) spendSig, err := signer.SignOutputRaw(tx1, signDesc)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to generate signature: %v", err) return nil, fmt.Errorf("unable to generate signature: %w", err)
} }
witness := make([][]byte, 2) witness := make([][]byte, 2)
witness[0] = append(spendSig.Serialize(), byte(txscript.SigHashAll)) witness[0] = append(spendSig.Serialize(), byte(txscript.SigHashAll))
@@ -1640,10 +1640,10 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey,
), ),
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to create engine: %v", err) return nil, fmt.Errorf("unable to create engine: %w", err)
} }
if err := vm.Execute(); err != nil { if err := vm.Execute(); err != nil {
return nil, fmt.Errorf("spend is invalid: %v", err) return nil, fmt.Errorf("spend is invalid: %w", err)
} }
return tx1, nil return tx1, nil
+7 -5
View File
@@ -721,7 +721,7 @@ func (l *LightningWallet) PsbtFundingVerify(pendingChanID [32]byte,
err := psbtIntent.Verify(packet, skipFinalize) err := psbtIntent.Verify(packet, skipFinalize)
if err != nil { if err != nil {
return fmt.Errorf("error verifying PSBT: %v", err) return fmt.Errorf("error verifying PSBT: %w", err)
} }
// Get the channel reservation for that corresponds to this pending // Get the channel reservation for that corresponds to this pending
@@ -773,13 +773,13 @@ func (l *LightningWallet) PsbtFundingFinalize(pid [32]byte, packet *psbt.Packet,
case packet != nil && rawTx == nil: case packet != nil && rawTx == nil:
err := psbtIntent.Finalize(packet) err := psbtIntent.Finalize(packet)
if err != nil { if err != nil {
return fmt.Errorf("error finalizing PSBT: %v", err) return fmt.Errorf("error finalizing PSBT: %w", err)
} }
case rawTx != nil && packet == nil: case rawTx != nil && packet == nil:
err := psbtIntent.FinalizeRawTX(rawTx) err := psbtIntent.FinalizeRawTX(rawTx)
if err != nil { if err != nil {
return fmt.Errorf("error finalizing raw TX: %v", err) return fmt.Errorf("error finalizing raw TX: %w", err)
} }
default: default:
@@ -1554,7 +1554,8 @@ func (l *LightningWallet) handleContributionMsg(req *addContributionMsg) {
case *chanfunding.ShimIntent: case *chanfunding.ShimIntent:
chanPoint, err = fundingIntent.ChanPoint() chanPoint, err = fundingIntent.ChanPoint()
if err != nil { if err != nil {
req.err <- fmt.Errorf("unable to obtain chan point: %v", err) req.err <- fmt.Errorf("unable to obtain chan point: %w",
err)
return return
} }
@@ -1996,7 +1997,8 @@ func (l *LightningWallet) verifyFundingInputs(fundingTx *wire.MsgTx,
txin.SignatureScript, txin.Witness, txin.SignatureScript, txin.Witness,
) )
if err != nil { if err != nil {
return fmt.Errorf("cannot create script: %v", err) return fmt.Errorf("cannot create script: %w",
err)
} }
output, err := l.Cfg.ChainIO.GetUtxo( output, err := l.Cfg.ChainIO.GetUtxo(
&txin.PreviousOutPoint, &txin.PreviousOutPoint,
+2 -2
View File
@@ -1336,7 +1336,7 @@ func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) {
// the first two bytes of the buffer. // the first two bytes of the buffer.
var codeBytes [2]byte var codeBytes [2]byte
if _, err := io.ReadFull(r, codeBytes[:]); err != nil { if _, err := io.ReadFull(r, codeBytes[:]); err != nil {
return nil, fmt.Errorf("unable to read failure code: %v", err) return nil, fmt.Errorf("unable to read failure code: %w", err)
} }
failCode := FailCode(binary.BigEndian.Uint16(codeBytes[:])) failCode := FailCode(binary.BigEndian.Uint16(codeBytes[:]))
@@ -1344,7 +1344,7 @@ func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) {
// additional data if needed. // additional data if needed.
failure, err := makeEmptyOnionError(failCode) failure, err := makeEmptyOnionError(failCode)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to make empty error: %v", err) return nil, fmt.Errorf("unable to make empty error: %w", err)
} }
// Finally, if this failure has a payload, then we'll read that now as // Finally, if this failure has a payload, then we'll read that now as
+2 -1
View File
@@ -214,7 +214,8 @@ func decodeShortChanIDs(r io.Reader) (QueryEncoding, []ShortChannelID, error) {
N: maxZlibBufSize, N: maxZlibBufSize,
}) })
if err != nil { if err != nil {
return 0, nil, fmt.Errorf("unable to create zlib reader: %v", err) return 0, nil, fmt.Errorf("unable to create zlib "+
"reader: %w", err)
} }
var ( var (
+1 -1
View File
@@ -37,7 +37,7 @@ func (n *NodeSigner) SignMessage(keyLoc keychain.KeyLocator,
// Otherwise, we'll sign the double-sha256 of the target message. // Otherwise, we'll sign the double-sha256 of the target message.
sig, err := n.keySigner.SignMessage(msg, doubleHash) sig, err := n.keySigner.SignMessage(msg, doubleHash)
if err != nil { if err != nil {
return nil, fmt.Errorf("can't sign the message: %v", err) return nil, fmt.Errorf("can't sign the message: %w", err)
} }
return sig, nil return sig, nil
+1 -1
View File
@@ -30,7 +30,7 @@ func SignAnnouncement(signer lnwallet.MessageSigner, keyLoc keychain.KeyLocator,
return nil, fmt.Errorf("can't sign %T message", m) return nil, fmt.Errorf("can't sign %T message", m)
} }
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to get data to sign: %v", err) return nil, fmt.Errorf("unable to get data to sign: %w", err)
} }
return signer.SignMessage(keyLoc, data, true) return signer.SignMessage(keyLoc, data, true)
+5 -5
View File
@@ -630,7 +630,7 @@ func (p *Brontide) Start() error {
// Exchange local and global features, the init message should be very // Exchange local and global features, the init message should be very
// first between two nodes. // first between two nodes.
if err := p.sendInitMsg(haveLegacyChan); err != nil { if err := p.sendInitMsg(haveLegacyChan); err != nil {
return fmt.Errorf("unable to send init msg: %v", err) return fmt.Errorf("unable to send init msg: %w", err)
} }
// Before we launch any of the helper goroutines off the peer struct, // Before we launch any of the helper goroutines off the peer struct,
@@ -660,7 +660,7 @@ func (p *Brontide) Start() error {
handshakeTimeout) handshakeTimeout)
case err := <-readErr: case err := <-readErr:
if err != nil { if err != nil {
return fmt.Errorf("unable to read init msg: %v", err) return fmt.Errorf("unable to read init msg: %w", err)
} }
} }
@@ -696,7 +696,7 @@ func (p *Brontide) Start() error {
msgs, err := p.loadActiveChannels(activeChans) msgs, err := p.loadActiveChannels(activeChans)
if err != nil { if err != nil {
return fmt.Errorf("unable to load channels: %v", err) return fmt.Errorf("unable to load channels: %w", err)
} }
p.startTime = time.Now() p.startTime = time.Now()
@@ -3332,7 +3332,7 @@ func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
// didn't set any required bits that we don't know of. // didn't set any required bits that we don't know of.
err = feature.ValidateRequired(p.remoteFeatures) err = feature.ValidateRequired(p.remoteFeatures)
if err != nil { if err != nil {
return fmt.Errorf("invalid remote features: %v", err) return fmt.Errorf("invalid remote features: %w", err)
} }
// Ensure the remote party's feature vector contains all transitive // Ensure the remote party's feature vector contains all transitive
@@ -3340,7 +3340,7 @@ func (p *Brontide) handleInitMsg(msg *lnwire.Init) error {
// during the feature manager's instantiation. // during the feature manager's instantiation.
err = feature.ValidateDeps(p.remoteFeatures) err = feature.ValidateDeps(p.remoteFeatures)
if err != nil { if err != nil {
return fmt.Errorf("invalid remote features: %v", err) return fmt.Errorf("invalid remote features: %w", err)
} }
// Now that we know we understand their requirements, we'll check to // Now that we know we understand their requirements, we'll check to
+1 -1
View File
@@ -352,7 +352,7 @@ func submitGeneric(p interface{}, sem <-chan struct{}) error {
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to submit task: %v", err) return fmt.Errorf("unable to submit task: %w", err)
} }
return nil return nil
+1 -1
View File
@@ -143,7 +143,7 @@ func VerifyChannelUpdateSignature(msg *lnwire.ChannelUpdate,
data, err := msg.DataToSign() data, err := msg.DataToSign()
if err != nil { if err != nil {
return fmt.Errorf("unable to reconstruct message data: %v", err) return fmt.Errorf("unable to reconstruct message data: %w", err)
} }
dataHash := chainhash.DoubleHashB(data) dataHash := chainhash.DoubleHashB(data)
+2 -2
View File
@@ -247,7 +247,7 @@ func (c *CfFilteredChainView) FilterBlock(blockHash *chainhash.Hash) (*FilteredB
// outpoint that have been spent. // outpoint that have been spent.
filter, err := c.p2pNode.GetCFilter(*blockHash, wire.GCSFilterRegular) filter, err := c.p2pNode.GetCFilter(*blockHash, wire.GCSFilterRegular)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to fetch filter: %v", err) return nil, fmt.Errorf("unable to fetch filter: %w", err)
} }
// Before we can match the filter, we'll need to map each item in our // Before we can match the filter, we'll need to map each item in our
@@ -349,7 +349,7 @@ func (c *CfFilteredChainView) UpdateFilter(ops []channeldb.EdgePoint,
} }
err := c.chainView.Update(rescanUpdate...) err := c.chainView.Update(rescanUpdate...)
if err != nil { if err != nil {
return fmt.Errorf("unable to update rescan: %v", err) return fmt.Errorf("unable to update rescan: %w", err)
} }
return nil return nil
} }
+3 -3
View File
@@ -1057,14 +1057,14 @@ func (r *ChannelRouter) pruneZombieChans() error {
r.cfg.StrictZombiePruning, true, toPrune..., r.cfg.StrictZombiePruning, true, toPrune...,
) )
if err != nil { if err != nil {
return fmt.Errorf("unable to delete zombie channels: %v", err) return fmt.Errorf("unable to delete zombie channels: %w", err)
} }
// With the channels pruned, we'll also attempt to prune any nodes that // With the channels pruned, we'll also attempt to prune any nodes that
// were a part of them. // were a part of them.
err = r.cfg.Graph.PruneGraphNodes() err = r.cfg.Graph.PruneGraphNodes()
if err != nil && err != channeldb.ErrGraphNodesNotFound { if err != nil && err != channeldb.ErrGraphNodesNotFound {
return fmt.Errorf("unable to prune graph nodes: %v", err) return fmt.Errorf("unable to prune graph nodes: %w", err)
} }
return nil return nil
@@ -1612,7 +1612,7 @@ func (r *ChannelRouter) processUpdate(msg interface{},
scid := lnwire.NewShortChanIDFromInt(msg.ChannelID) scid := lnwire.NewShortChanIDFromInt(msg.ChannelID)
if r.cfg.AssumeChannelValid || r.cfg.IsAlias(scid) { if r.cfg.AssumeChannelValid || r.cfg.IsAlias(scid) {
if err := r.cfg.Graph.AddChannelEdge(msg, op...); err != nil { if err := r.cfg.Graph.AddChannelEdge(msg, op...); err != nil {
return fmt.Errorf("unable to add edge: %v", err) return fmt.Errorf("unable to add edge: %w", err)
} }
log.Tracef("New channel discovered! Link "+ log.Tracef("New channel discovered! Link "+
"connects %x and %x with ChannelID(%v)", "connects %x and %x with ChannelID(%v)",
+2 -2
View File
@@ -586,11 +586,11 @@ func replaceProtoMsg(target interface{}, replacement interface{}) error {
replacementBytes, err := proto.Marshal(replacementMsg) replacementBytes, err := proto.Marshal(replacementMsg)
if err != nil { if err != nil {
return fmt.Errorf("error marshaling replacement: %v", err) return fmt.Errorf("error marshaling replacement: %w", err)
} }
err = proto.Unmarshal(replacementBytes, targetMsg) err = proto.Unmarshal(replacementBytes, targetMsg)
if err != nil { if err != nil {
return fmt.Errorf("error unmarshaling replacement: %v", err) return fmt.Errorf("error unmarshaling replacement: %w", err)
} }
return nil return nil
+21 -19
View File
@@ -1612,7 +1612,7 @@ func (r *rpcServer) VerifyMessage(ctx context.Context,
// The signature should be zbase32 encoded // The signature should be zbase32 encoded
sig, err := zbase32.DecodeString(in.Signature) sig, err := zbase32.DecodeString(in.Signature)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to decode signature: %v", err) return nil, fmt.Errorf("failed to decode signature: %w", err)
} }
// The signature is over the double-sha256 hash of the message. // The signature is over the double-sha256 hash of the message.
@@ -1636,7 +1636,7 @@ func (r *rpcServer) VerifyMessage(ctx context.Context,
graph := r.server.graphDB graph := r.server.graphDB
_, active, err := graph.HasLightningNode(pub) _, active, err := graph.HasLightningNode(pub)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to query graph: %v", err) return nil, fmt.Errorf("failed to query graph: %w", err)
} }
return &lnrpc.VerifyMessageResponse{ return &lnrpc.VerifyMessageResponse{
@@ -1730,18 +1730,19 @@ func (r *rpcServer) DisconnectPeer(ctx context.Context,
// public key. // public key.
pubKeyBytes, err := hex.DecodeString(in.PubKey) pubKeyBytes, err := hex.DecodeString(in.PubKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to decode pubkey bytes: %v", err) return nil, fmt.Errorf("unable to decode pubkey bytes: %w", err)
} }
peerPubKey, err := btcec.ParsePubKey(pubKeyBytes) peerPubKey, err := btcec.ParsePubKey(pubKeyBytes)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse pubkey: %v", err) return nil, fmt.Errorf("unable to parse pubkey: %w", err)
} }
// Next, we'll fetch the pending/active channels we have with a // Next, we'll fetch the pending/active channels we have with a
// particular peer. // particular peer.
nodeChannels, err := r.server.chanStateDB.FetchOpenChannels(peerPubKey) nodeChannels, err := r.server.chanStateDB.FetchOpenChannels(peerPubKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to fetch channels for peer: %v", err) return nil, fmt.Errorf("unable to fetch channels for peer: %w",
err)
} }
// In order to avoid erroneously disconnecting from a peer that we have // In order to avoid erroneously disconnecting from a peer that we have
@@ -1768,7 +1769,7 @@ func (r *rpcServer) DisconnectPeer(ctx context.Context,
// server disconnects from the peer. // server disconnects from the peer.
err = r.server.DisconnectPeer(peerPubKey) err = r.server.DisconnectPeer(peerPubKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to disconnect peer: %v", err) return nil, fmt.Errorf("unable to disconnect peer: %w", err)
} }
return &lnrpc.DisconnectPeerResponse{}, nil return &lnrpc.DisconnectPeerResponse{}, nil
@@ -2458,7 +2459,7 @@ func (r *rpcServer) BatchOpenChannel(ctx context.Context,
// a close height, so we'll just use the current best known height. // a close height, so we'll just use the current best known height.
_, bestHeight, err := r.server.cc.ChainIO.GetBestBlock() _, bestHeight, err := r.server.cc.ChainIO.GetBestBlock()
if err != nil { if err != nil {
return nil, fmt.Errorf("error fetching best block: %v", err) return nil, fmt.Errorf("error fetching best block: %w", err)
} }
// So far everything looks good and we can now start the heavy lifting // So far everything looks good and we can now start the heavy lifting
@@ -2482,7 +2483,7 @@ func (r *rpcServer) BatchOpenChannel(ctx context.Context,
}) })
rpcPoints, err := batcher.BatchFund(ctx, in) rpcPoints, err := batcher.BatchFund(ctx, in)
if err != nil { if err != nil {
return nil, fmt.Errorf("batch funding failed: %v", err) return nil, fmt.Errorf("batch funding failed: %w", err)
} }
// Now all that's left to do is send back the response with the channel // Now all that's left to do is send back the response with the channel
@@ -2972,7 +2973,7 @@ func (r *rpcServer) GetInfo(_ context.Context,
bestHash, bestHeight, err := r.server.cc.ChainIO.GetBestBlock() bestHash, bestHeight, err := r.server.cc.ChainIO.GetBestBlock()
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to get best block info: %v", err) return nil, fmt.Errorf("unable to get best block info: %w", err)
} }
isSynced, bestHeaderTimestamp, err := r.server.cc.Wallet.IsSynced() isSynced, bestHeaderTimestamp, err := r.server.cc.Wallet.IsSynced()
@@ -3093,7 +3094,8 @@ func (r *rpcServer) GetRecoveryInfo(ctx context.Context,
isRecoveryMode, progress, err := r.server.cc.Wallet.GetRecoveryInfo() isRecoveryMode, progress, err := r.server.cc.Wallet.GetRecoveryInfo()
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to get wallet recovery info: %v", err) return nil, fmt.Errorf("unable to get wallet recovery info: %w",
err)
} }
rpcsLog.Debugf("[getrecoveryinfo] is recovery mode=%v, progress=%v", rpcsLog.Debugf("[getrecoveryinfo] is recovery mode=%v, progress=%v",
@@ -4190,7 +4192,7 @@ func (r *rpcServer) ListChannels(ctx context.Context,
if len(in.Peer) > 0 && len(in.Peer) != 33 { if len(in.Peer) > 0 && len(in.Peer) != 33 {
_, err := route.NewVertexFromBytes(in.Peer) _, err := route.NewVertexFromBytes(in.Peer)
return nil, fmt.Errorf("invalid `peer` key: %v", err) return nil, fmt.Errorf("invalid `peer` key: %w", err)
} }
resp := &lnrpc.ListChannelsResponse{} resp := &lnrpc.ListChannelsResponse{}
@@ -5806,7 +5808,7 @@ func (r *rpcServer) ListInvoices(ctx context.Context,
invoiceSlice, err := r.server.miscDB.QueryInvoices(ctx, q) invoiceSlice, err := r.server.miscDB.QueryInvoices(ctx, q)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to query invoices: %v", err) return nil, fmt.Errorf("unable to query invoices: %w", err)
} }
// Before returning the response, we'll need to convert each invoice // Before returning the response, we'll need to convert each invoice
@@ -6929,7 +6931,7 @@ func (r *rpcServer) FeeReport(ctx context.Context,
} }
dayFees, err := computeFeeSum(dayQuery) dayFees, err := computeFeeSum(dayQuery)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to retrieve day fees: %v", err) return nil, fmt.Errorf("unable to retrieve day fees: %w", err)
} }
weekQuery := channeldb.ForwardingEventQuery{ weekQuery := channeldb.ForwardingEventQuery{
@@ -6939,7 +6941,7 @@ func (r *rpcServer) FeeReport(ctx context.Context,
} }
weekFees, err := computeFeeSum(weekQuery) weekFees, err := computeFeeSum(weekQuery)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to retrieve day fees: %v", err) return nil, fmt.Errorf("unable to retrieve day fees: %w", err)
} }
monthQuery := channeldb.ForwardingEventQuery{ monthQuery := channeldb.ForwardingEventQuery{
@@ -6949,7 +6951,7 @@ func (r *rpcServer) FeeReport(ctx context.Context,
} }
monthFees, err := computeFeeSum(monthQuery) monthFees, err := computeFeeSum(monthQuery)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to retrieve day fees: %v", err) return nil, fmt.Errorf("unable to retrieve day fees: %w", err)
} }
return &lnrpc.FeeReportResponse{ return &lnrpc.FeeReportResponse{
@@ -7273,7 +7275,7 @@ func (r *rpcServer) ExportChannelBackup(ctx context.Context,
r.server.cc.KeyRing, r.server.cc.KeyRing,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("packing of back ups failed: %v", err) return nil, fmt.Errorf("packing of back ups failed: %w", err)
} }
// Before we proceed, we'll ensure that we received a backup for this // Before we proceed, we'll ensure that we received a backup for this
@@ -7400,7 +7402,7 @@ func (r *rpcServer) createBackupSnapshot(backups []chanbackup.Single) (
} }
err = unpackedMultiBackup.PackToWriter(&b, r.server.cc.KeyRing) err = unpackedMultiBackup.PackToWriter(&b, r.server.cc.KeyRing)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to multi-pack backups: %v", err) return nil, fmt.Errorf("unable to multi-pack backups: %w", err)
} }
multiBackupResp := &lnrpc.MultiChanBackup{ multiBackupResp := &lnrpc.MultiChanBackup{
@@ -7903,7 +7905,7 @@ func (r *rpcServer) FundingStateStep(ctx context.Context,
bytes.NewReader(in.GetPsbtVerify().FundedPsbt), false, bytes.NewReader(in.GetPsbtVerify().FundedPsbt), false,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing psbt: %v", err) return nil, fmt.Errorf("error parsing psbt: %w", err)
} }
err = r.server.cc.Wallet.PsbtFundingVerify( err = r.server.cc.Wallet.PsbtFundingVerify(
@@ -8070,7 +8072,7 @@ func (r *rpcServer) RegisterRPCMiddleware(
// Add the RPC middleware to the interceptor chain and defer its // Add the RPC middleware to the interceptor chain and defer its
// removal. // removal.
if err := r.interceptorChain.RegisterMiddleware(middleware); err != nil { if err := r.interceptorChain.RegisterMiddleware(middleware); err != nil {
return fmt.Errorf("error registering middleware: %v", err) return fmt.Errorf("error registering middleware: %w", err)
} }
defer r.interceptorChain.RemoveMiddleware(registerMsg.MiddlewareName) defer r.interceptorChain.RemoveMiddleware(registerMsg.MiddlewareName)
+9 -9
View File
@@ -830,7 +830,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr,
// network so we can properly sign it. // network so we can properly sign it.
nodeAnn, err := selfNode.NodeAnnouncement(false) nodeAnn, err := selfNode.NodeAnnouncement(false)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to gen self node ann: %v", err) return nil, fmt.Errorf("unable to gen self node ann: %w", err)
} }
// With the announcement generated, we'll sign it to properly // With the announcement generated, we'll sign it to properly
@@ -853,7 +853,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr,
// Finally, we'll update the representation on disk, and update our // Finally, we'll update the representation on disk, and update our
// cached in-memory version as well. // cached in-memory version as well.
if err := chanGraph.SetSourceNode(selfNode); err != nil { if err := chanGraph.SetSourceNode(selfNode); err != nil {
return nil, fmt.Errorf("can't set self node: %v", err) return nil, fmt.Errorf("can't set self node: %w", err)
} }
s.currentNodeAnn = nodeAnn s.currentNodeAnn = nodeAnn
@@ -925,7 +925,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr,
dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg, dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("can't create mission control: %v", err) return nil, fmt.Errorf("can't create mission control: %w", err)
} }
srvrLog.Debugf("Instantiating payment session source with config: "+ srvrLog.Debugf("Instantiating payment session source with config: "+
@@ -944,7 +944,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr,
sourceNode, err := chanGraph.SourceNode() sourceNode, err := chanGraph.SourceNode()
if err != nil { if err != nil {
return nil, fmt.Errorf("error getting source node: %v", err) return nil, fmt.Errorf("error getting source node: %w", err)
} }
paymentSessionSource := &routing.SessionSource{ paymentSessionSource := &routing.SessionSource{
Graph: chanGraph, Graph: chanGraph,
@@ -981,7 +981,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr,
IsAlias: aliasmgr.IsAlias, IsAlias: aliasmgr.IsAlias,
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("can't create router: %v", err) return nil, fmt.Errorf("can't create router: %w", err)
} }
chanSeries := discovery.NewChanSeries(s.graphDB) chanSeries := discovery.NewChanSeries(s.graphDB)
@@ -2905,7 +2905,7 @@ func (s *server) createNewHiddenService() error {
} }
copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed()) copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
if err := s.graphDB.SetSourceNode(selfNode); err != nil { if err := s.graphDB.SetSourceNode(selfNode); err != nil {
return fmt.Errorf("can't set self node: %v", err) return fmt.Errorf("can't set self node: %w", err)
} }
return nil return nil
@@ -3005,7 +3005,7 @@ func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
// don't risk overwriting any existing values. // don't risk overwriting any existing values.
selfNode, err := s.graphDB.SourceNode() selfNode, err := s.graphDB.SourceNode()
if err != nil { if err != nil {
return fmt.Errorf("unable to get current source node: %v", err) return fmt.Errorf("unable to get current source node: %w", err)
} }
selfNode.HaveNodeAnnouncement = true selfNode.HaveNodeAnnouncement = true
@@ -3019,7 +3019,7 @@ func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed()) copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
if err := s.graphDB.SetSourceNode(selfNode); err != nil { if err := s.graphDB.SetSourceNode(selfNode); err != nil {
return fmt.Errorf("can't set self node: %v", err) return fmt.Errorf("can't set self node: %w", err)
} }
// Finally, propagate it to the nodes in the network. // Finally, propagate it to the nodes in the network.
@@ -3967,7 +3967,7 @@ func (s *server) peerInitializer(p *peer.Brontide) {
srvrLog.Warnf("Starting peer=%v got error: %v", srvrLog.Warnf("Starting peer=%v got error: %v",
p.IdentityKey(), err) p.IdentityKey(), err)
p.Disconnect(fmt.Errorf("unable to start peer: %v", err)) p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
return return
} }
+5 -5
View File
@@ -360,7 +360,7 @@ func (s *UtxoSweeper) Start() error {
// if we don't provide any epoch. We'll wait for that in the collector. // if we don't provide any epoch. We'll wait for that in the collector.
blockEpochs, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil) blockEpochs, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
if err != nil { if err != nil {
return fmt.Errorf("register block epoch ntfn: %v", err) return fmt.Errorf("register block epoch ntfn: %w", err)
} }
// Start sweeper main loop. // Start sweeper main loop.
@@ -1157,7 +1157,7 @@ func (s *UtxoSweeper) sweep(inputs inputSet, feeRate chainfee.SatPerKWeight,
if s.currentOutputScript == nil { if s.currentOutputScript == nil {
pkScript, err := s.cfg.GenSweepScript() pkScript, err := s.cfg.GenSweepScript()
if err != nil { if err != nil {
return fmt.Errorf("gen sweep script: %v", err) return fmt.Errorf("gen sweep script: %w", err)
} }
s.currentOutputScript = pkScript s.currentOutputScript = pkScript
} }
@@ -1168,7 +1168,7 @@ func (s *UtxoSweeper) sweep(inputs inputSet, feeRate chainfee.SatPerKWeight,
feeRate, s.cfg.MaxFeeRate.FeePerKWeight(), s.cfg.Signer, feeRate, s.cfg.MaxFeeRate.FeePerKWeight(), s.cfg.Signer,
) )
if err != nil { if err != nil {
return fmt.Errorf("create sweep tx: %v", err) return fmt.Errorf("create sweep tx: %w", err)
} }
// Add tx before publication, so that we will always know that a spend // Add tx before publication, so that we will always know that a spend
@@ -1178,7 +1178,7 @@ func (s *UtxoSweeper) sweep(inputs inputSet, feeRate chainfee.SatPerKWeight,
// then and would also not add the hash to the store. // then and would also not add the hash to the store.
err = s.cfg.Store.NotifyPublishTx(tx) err = s.cfg.Store.NotifyPublishTx(tx)
if err != nil { if err != nil {
return fmt.Errorf("notify publish tx: %v", err) return fmt.Errorf("notify publish tx: %w", err)
} }
// Reschedule the inputs that we just tried to sweep. This is done in // Reschedule the inputs that we just tried to sweep. This is done in
@@ -1268,7 +1268,7 @@ func (s *UtxoSweeper) monitorSpend(outpoint wire.OutPoint,
&outpoint, script, heightHint, &outpoint, script, heightHint,
) )
if err != nil { if err != nil {
return nil, fmt.Errorf("register spend ntfn: %v", err) return nil, fmt.Errorf("register spend ntfn: %w", err)
} }
s.wg.Add(1) s.wg.Add(1)
+4 -4
View File
@@ -161,7 +161,7 @@ func (c *Controller) Start() error {
conn, err := textproto.Dial("tcp", c.controlAddr) conn, err := textproto.Dial("tcp", c.controlAddr)
if err != nil { if err != nil {
return fmt.Errorf("unable to connect to Tor server: %v", err) return fmt.Errorf("unable to connect to Tor server: %w", err)
} }
c.conn = conn c.conn = conn
@@ -507,7 +507,7 @@ func (c *Controller) authenticateViaSafeCookie(info protocolInfo) error {
// the AUTHCHALLENGE command followed by a hex-encoded 32-byte nonce. // the AUTHCHALLENGE command followed by a hex-encoded 32-byte nonce.
clientNonce := make([]byte, nonceLen) clientNonce := make([]byte, nonceLen)
if _, err := rand.Read(clientNonce); err != nil { if _, err := rand.Read(clientNonce); err != nil {
return fmt.Errorf("unable to generate client nonce: %v", err) return fmt.Errorf("unable to generate client nonce: %w", err)
} }
cmd := fmt.Sprintf("AUTHCHALLENGE SAFECOOKIE %x", clientNonce) cmd := fmt.Sprintf("AUTHCHALLENGE SAFECOOKIE %x", clientNonce)
@@ -536,7 +536,7 @@ func (c *Controller) authenticateViaSafeCookie(info protocolInfo) error {
} }
decodedServerHash, err := hex.DecodeString(serverHash) decodedServerHash, err := hex.DecodeString(serverHash)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode server hash: %v", err) return fmt.Errorf("unable to decode server hash: %w", err)
} }
if len(decodedServerHash) != sha256.Size { if len(decodedServerHash) != sha256.Size {
return errors.New("invalid server hash length") return errors.New("invalid server hash length")
@@ -548,7 +548,7 @@ func (c *Controller) authenticateViaSafeCookie(info protocolInfo) error {
} }
decodedServerNonce, err := hex.DecodeString(serverNonce) decodedServerNonce, err := hex.DecodeString(serverNonce)
if err != nil { if err != nil {
return fmt.Errorf("unable to decode server nonce: %v", err) return fmt.Errorf("unable to decode server nonce: %w", err)
} }
if len(decodedServerNonce) != nonceLen { if len(decodedServerNonce) != nonceLen {
return errors.New("invalid server nonce length") return errors.New("invalid server nonce length")
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more