diff --git a/autopilot/agent.go b/autopilot/agent.go index b74eaba9a..9aef4f9f4 100644 --- a/autopilot/agent.go +++ b/autopilot/agent.go @@ -629,7 +629,7 @@ func (a *Agent) openChans(availableFunds btcutil.Amount, numChans uint32, nodes[nID] = struct{}{} return 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 @@ -639,7 +639,7 @@ func (a *Agent) openChans(availableFunds btcutil.Amount, numChans uint32, a.cfg.Graph, totalChans, chanSize, nodes, ) 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)) diff --git a/brontide/noise_test.go b/brontide/noise_test.go index 1539ece0f..8ff7e5836 100644 --- a/brontide/noise_test.go +++ b/brontide/noise_test.go @@ -274,7 +274,7 @@ func TestWriteMessageChunking(t *testing.T) { bytesWritten, err := localConn.Write(largeMessage) if err != nil { - errCh <- fmt.Errorf("unable to write message: %v", err) + errCh <- fmt.Errorf("unable to write message: %w", err) return } diff --git a/build/logrotator.go b/build/logrotator.go index 22559b162..b6e697f9b 100644 --- a/build/logrotator.go +++ b/build/logrotator.go @@ -64,13 +64,13 @@ func (r *RotatingLogWriter) InitLogRotator(logFile string, maxLogFileSize int, logDir, _ := filepath.Split(logFile) err := os.MkdirAll(logDir, 0700) 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( logFile, int64(maxLogFileSize*1024), false, maxLogFiles, ) 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 diff --git a/chainntnfs/bitcoindnotify/bitcoind.go b/chainntnfs/bitcoindnotify/bitcoind.go index 18615fae4..d268c8374 100644 --- a/chainntnfs/bitcoindnotify/bitcoind.go +++ b/chainntnfs/bitcoindnotify/bitcoind.go @@ -636,7 +636,7 @@ func (b *BitcoindNotifier) handleBlockConnected(block chainntnfs.BlockEpoch) err // clients. rawBlock, err := b.GetBlock(block.Hash) 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) @@ -645,7 +645,7 @@ func (b *BitcoindNotifier) handleBlockConnected(block chainntnfs.BlockEpoch) err // us. err = b.txNotifier.ConnectTip(utilBlock, uint32(block.Height)) 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, @@ -719,7 +719,8 @@ func (b *BitcoindNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint, pkScript, b.chainParams, ) 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 { return nil, err diff --git a/chainntnfs/btcdnotify/btcd.go b/chainntnfs/btcdnotify/btcd.go index 3025a8346..430a10661 100644 --- a/chainntnfs/btcdnotify/btcd.go +++ b/chainntnfs/btcdnotify/btcd.go @@ -692,7 +692,7 @@ func (b *BtcdNotifier) handleBlockConnected(epoch chainntnfs.BlockEpoch) error { // clients. rawBlock, err := b.GetBlock(epoch.Hash) if err != nil { - return fmt.Errorf("unable to get block: %v", err) + return fmt.Errorf("unable to get block: %w", err) } newBlock := &filteredBlock{ hash: *epoch.Hash, @@ -706,7 +706,7 @@ func (b *BtcdNotifier) handleBlockConnected(epoch chainntnfs.BlockEpoch) error { // us. err = b.txNotifier.ConnectTip(newBlock.block, newBlock.height) 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, @@ -785,7 +785,8 @@ func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint, pkScript, b.chainParams, ) 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 { return nil, err @@ -823,7 +824,8 @@ func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint, pkScript, b.chainParams, ) 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) diff --git a/chainntnfs/interface.go b/chainntnfs/interface.go index d8e325fb2..0f2fe27e4 100644 --- a/chainntnfs/interface.go +++ b/chainntnfs/interface.go @@ -541,7 +541,7 @@ func GetClientMissedBlocks(chainConn ChainConn, clientBestBlock *BlockEpoch, chainConn, startingHeight+1, notifierBestHeight+1, ) 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 diff --git a/chainntnfs/neutrinonotify/neutrino.go b/chainntnfs/neutrinonotify/neutrino.go index 3faf8528b..b2e00da80 100644 --- a/chainntnfs/neutrinonotify/neutrino.go +++ b/chainntnfs/neutrinonotify/neutrino.go @@ -609,7 +609,8 @@ func (n *NeutrinoNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequ key := builder.DeriveKey(blockHash) match, err := regFilter.Match(key, confRequest.PkScript.Script()) 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 @@ -623,7 +624,8 @@ func (n *NeutrinoNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequ // to send the proper response. block, err := n.GetBlock(*blockHash) 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 @@ -663,11 +665,11 @@ func (n *NeutrinoNotifier) handleBlockConnected(newBlock *filteredBlock) error { // result in the items we care about being dispatched. rawBlock, err := n.GetBlock(newBlock.hash) 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) 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, @@ -692,7 +694,7 @@ func (n *NeutrinoNotifier) handleBlockConnected(newBlock *filteredBlock) error { func (n *NeutrinoNotifier) getFilteredBlock(epoch chainntnfs.BlockEpoch) (*filteredBlock, error) { rawBlock, err := n.GetBlock(*epoch.Hash) 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() @@ -800,7 +802,7 @@ func (n *NeutrinoNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint, return nil, chainntnfs.ErrChainNotifierShuttingDown } 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 @@ -937,7 +939,7 @@ func (n *NeutrinoNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash, params := n.p2pNode.ChainParams() _, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, ¶ms) 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 @@ -962,7 +964,7 @@ func (n *NeutrinoNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash, return nil, chainntnfs.ErrChainNotifierShuttingDown } 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 diff --git a/chainntnfs/test_utils.go b/chainntnfs/test_utils.go index fa6b7cd56..8bd994f07 100644 --- a/chainntnfs/test_utils.go +++ b/chainntnfs/test_utils.go @@ -67,7 +67,8 @@ func randPubKeyHashScript() ([]byte, *btcec.PrivateKey, error) { func GetTestTxidAndScript(h *rpctest.Harness) (*chainhash.Hash, []byte, error) { pkScript, _, err := randPubKeyHashScript() 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} txid, err := h.SendOutputs([]*wire.TxOut{output}, 10) diff --git a/chanbackup/backup.go b/chanbackup/backup.go index 9a61d23cd..f6768898a 100644 --- a/chanbackup/backup.go +++ b/chanbackup/backup.go @@ -72,7 +72,7 @@ func FetchBackupForChan(chanPoint wire.OutPoint, chanSource LiveChannelSource, // the source to obtain any extra information that we may need. staticChanBackup, err := assembleChanBackup(addrSource, targetChan) 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 diff --git a/chanbackup/backupfile.go b/chanbackup/backupfile.go index d2d6b788c..9c1e788c1 100644 --- a/chanbackup/backupfile.go +++ b/chanbackup/backupfile.go @@ -93,17 +93,18 @@ func (b *MultiFile) UpdateAndSwap(newBackup PackedMulti) error { var err error b.tempFile, err = os.Create(b.tempFileName) 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 // remove the temporary file all together once this method exits. _, err = b.tempFile.Write([]byte(newBackup)) 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 { - 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) @@ -114,7 +115,7 @@ func (b *MultiFile) UpdateAndSwap(newBackup PackedMulti) error { // sure to close the current file as some OSes don't support // renaming a file that's already open (Windows). 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 diff --git a/chanbackup/backupfile_test.go b/chanbackup/backupfile_test.go index 1bc94f38a..fbd0cc7dd 100644 --- a/chanbackup/backupfile_test.go +++ b/chanbackup/backupfile_test.go @@ -16,7 +16,7 @@ import ( func makeFakePackedMulti() (PackedMulti, error) { newPackedMulti := make([]byte, 50) 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 diff --git a/chanbackup/multi.go b/chanbackup/multi.go index 40e09f451..a7b9b2da1 100644 --- a/chanbackup/multi.go +++ b/chanbackup/multi.go @@ -92,7 +92,7 @@ func (m Multi) PackToWriter(w io.Writer, keyRing keychain.KeyRing) error { // directly to the passed writer. e, err := lnencrypt.KeyRingEncrypter(keyRing) 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) @@ -107,7 +107,7 @@ func (m *Multi) UnpackFromReader(r io.Reader, keyRing keychain.KeyRing) error { // encryption keys. e, err := lnencrypt.KeyRingEncrypter(keyRing) 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) if err != nil { diff --git a/chanbackup/pubsub.go b/chanbackup/pubsub.go index 5323f97aa..987678d92 100644 --- a/chanbackup/pubsub.go +++ b/chanbackup/pubsub.go @@ -226,7 +226,7 @@ func (s *SubSwapper) updateBackupFile(closedChans ...wire.OutPoint) error { var b bytes.Buffer err = newMulti.PackToWriter(&b, s.keyRing) 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 @@ -234,7 +234,7 @@ func (s *SubSwapper) updateBackupFile(closedChans ...wire.OutPoint) error { // channels. err = s.Swapper.UpdateAndSwap(PackedMulti(b.Bytes())) 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 diff --git a/chanbackup/pubsub_test.go b/chanbackup/pubsub_test.go index 9586605ca..6ab1cb181 100644 --- a/chanbackup/pubsub_test.go +++ b/chanbackup/pubsub_test.go @@ -36,7 +36,7 @@ func (m *mockSwapper) UpdateAndSwap(newBackup PackedMulti) error { swapState, err := newBackup.Unpack(m.keyChain) 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 diff --git a/chanbackup/single.go b/chanbackup/single.go index ab982d59c..dd63bf1f6 100644 --- a/chanbackup/single.go +++ b/chanbackup/single.go @@ -362,7 +362,7 @@ func (s *Single) PackToWriter(w io.Writer, keyRing keychain.KeyRing) error { // nonce that we used to the passed io.Reader. e, err := lnencrypt.KeyRingEncrypter(keyRing) 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) } @@ -544,7 +544,7 @@ func (s *Single) Deserialize(r io.Reader) error { func (s *Single) UnpackFromReader(r io.Reader, keyRing keychain.KeyRing) error { e, err := lnencrypt.KeyRingEncrypter(keyRing) 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) if err != nil { diff --git a/channeldb/channel.go b/channeldb/channel.go index 4a0350329..75eb4cde9 100644 --- a/channeldb/channel.go +++ b/channeldb/channel.go @@ -1015,7 +1015,7 @@ func (c *OpenChannel) Refresh() error { // We'll re-populating the in-memory channel with the info // fetched from disk. 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 @@ -1869,13 +1869,13 @@ func putOpenChannel(chanBucket kvdb.RwBucket, channel *OpenChannel) error { // First, we'll write out all the relatively static fields, that are // decided upon initial channel creation. 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 // current commitment state for both parties. 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 @@ -1885,14 +1885,15 @@ func putOpenChannel(chanBucket kvdb.RwBucket, channel *OpenChannel) error { chanBucket, channel.ThawHeight, ) 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 // within a distinct key space. 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 @@ -1910,13 +1911,14 @@ func fetchOpenChannel(chanBucket kvdb.RBucket, // First, we'll read all the static information that changes less // frequently from disk. 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 // commitment state for both sides of the channel. 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 @@ -1934,7 +1936,8 @@ func fetchOpenChannel(chanBucket kvdb.RBucket, // Finally, we'll retrieve the current revocation state so we can // properly 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) @@ -2043,7 +2046,7 @@ func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment, } 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 @@ -2130,12 +2133,14 @@ func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment, var b3 bytes.Buffer err = serializeLogUpdates(&b3, unsignedUpdates) 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()) if err != nil { - return fmt.Errorf("unable to restore chanbucket: %v", err) + return fmt.Errorf("unable to restore chanbucket: %w", + err) } return nil @@ -3003,12 +3008,14 @@ func (c *OpenChannel) AdvanceCommitChainTail(fwdPkg *FwdPkg, var b bytes.Buffer err = serializeLogUpdates(&b, validUpdates) 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()) 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 diff --git a/channeldb/db.go b/channeldb/db.go index d1b9f684e..aff70d462 100644 --- a/channeldb/db.go +++ b/channeldb/db.go @@ -497,7 +497,7 @@ func initChannelDB(db kvdb.Backend) error { return putMeta(meta, tx) }, func() {}) 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 diff --git a/channeldb/graph.go b/channeldb/graph.go index bb7774895..8ad90f808 100644 --- a/channeldb/graph.go +++ b/channeldb/graph.go @@ -385,7 +385,7 @@ func initChannelGraph(db kvdb.Backend) error { return err }, func() {}) 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 diff --git a/channeldb/migration/lnwire21/onion_error.go b/channeldb/migration/lnwire21/onion_error.go index 362ab48b0..a2923b076 100644 --- a/channeldb/migration/lnwire21/onion_error.go +++ b/channeldb/migration/lnwire21/onion_error.go @@ -1212,7 +1212,7 @@ func DecodeFailure(r io.Reader, pver uint32) (FailureMessage, error) { // is a 2 byte length followed by the payload itself. var failureLength uint16 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 { 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. var codeBytes [2]byte 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[:])) @@ -1244,7 +1244,7 @@ func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) { // additional data if needed. failure, err := makeEmptyOnionError(failCode) 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 diff --git a/channeldb/migration/lnwire21/query_short_chan_ids.go b/channeldb/migration/lnwire21/query_short_chan_ids.go index 3c2b99487..7e8d1e68f 100644 --- a/channeldb/migration/lnwire21/query_short_chan_ids.go +++ b/channeldb/migration/lnwire21/query_short_chan_ids.go @@ -223,7 +223,8 @@ func decodeShortChanIDs(r io.Reader) (ShortChanIDEncoding, []ShortChannelID, err N: maxZlibBufSize, }) 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 ( diff --git a/channeldb/migration25/migration.go b/channeldb/migration25/migration.go index 5e708e4bc..257d8272c 100644 --- a/channeldb/migration25/migration.go +++ b/channeldb/migration25/migration.go @@ -86,7 +86,7 @@ func findOpenChannels(openChanBucket kvdb.RBucket) ([]*OpenChannel, error) { } // Get the old channel info. 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 @@ -154,7 +154,7 @@ func migrateBalances(tx kvdb.RwTx, c *OpenChannel) error { // Get the initial balances. localAmt, remoteAmt, err := c.balancesAtHeight(chanBucket, 0) 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 @@ -162,7 +162,7 @@ func migrateBalances(tx kvdb.RwTx, c *OpenChannel) error { // Update the channel info. 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 diff --git a/channeldb/migration26/migration.go b/channeldb/migration26/migration.go index a1b8606e9..469687f8c 100644 --- a/channeldb/migration26/migration.go +++ b/channeldb/migration26/migration.go @@ -76,7 +76,7 @@ func findOpenChannels(openChanBucket kvdb.RBucket) ([]*OpenChannel, error) { // Get the old channel info. 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) @@ -139,7 +139,7 @@ func migrateBalances(tx kvdb.RwTx, c *OpenChannel) error { // `c.InitialRemoteBalance` then create the new tlv stream as // requested. 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 diff --git a/channeldb/migration27/channel.go b/channeldb/migration27/channel.go index 7fd87a0b4..1cd9ec591 100644 --- a/channeldb/migration27/channel.go +++ b/channeldb/migration27/channel.go @@ -82,7 +82,7 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error { &c.IdentityPub, &c.Capacity, &c.TotalMSatSent, &c.TotalMSatReceived, ); err != nil { - return fmt.Errorf("ReadElements got: %v", err) + return fmt.Errorf("ReadElements got: %w", err) } 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. if c.FundingTxPresent() { 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 { - 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 { - return fmt.Errorf("read RemoteChanCfg got: %v", err) + return fmt.Errorf("read RemoteChanCfg got: %w", err) } // Retrieve the boolean stored under lastWasRevokeKey. @@ -114,7 +114,7 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error { revokeReader := bytes.NewReader(lastWasRevokeBytes) err := mig.ReadElements(revokeReader, &c.LastWasRevoke) 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 { - 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 { - 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. @@ -164,7 +164,7 @@ func FetchChanInfo(chanBucket kvdb.RBucket, c *OpenChannel, legacy bool) error { if err := mig25.GetOptionalUpfrontShutdownScript( chanBucket, localUpfrontShutdownKey, &c.LocalShutdownScript, ); err != nil { - return fmt.Errorf("local shutdown script got: %v", err) + return fmt.Errorf("local shutdown script got: %w", err) } return mig25.GetOptionalUpfrontShutdownScript( diff --git a/channeldb/migration27/migration.go b/channeldb/migration27/migration.go index a538c2e93..a6f7b1a96 100644 --- a/channeldb/migration27/migration.go +++ b/channeldb/migration27/migration.go @@ -65,7 +65,7 @@ func findHistoricalChannels(historicalBucket kvdb.RBucket) ([]*OpenChannel, chanPointBuf := bytes.NewBuffer(cp) err := mig.ReadOutpoint(chanPointBuf, &c.FundingOutpoint) 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. @@ -141,7 +141,7 @@ func migrateBalances(rootBucket kvdb.RwBucket, c *OpenChannel) error { // Update the channel info. 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 diff --git a/channeldb/migration30/migration.go b/channeldb/migration30/migration.go index 6c743b4b3..406cc291a 100644 --- a/channeldb/migration30/migration.go +++ b/channeldb/migration30/migration.go @@ -117,7 +117,7 @@ func MigrateRevocationLog(db kvdb.Backend, cfg MigrateRevLogConfig) error { // make sure the logs are migrated as expected. err = kvdb.Update(db, validateMigration, func() {}) 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...") @@ -125,7 +125,7 @@ func MigrateRevocationLog(db kvdb.Backend, cfg MigrateRevLogConfig) error { // Once the migration completes, we can now safety delete the old // revocation logs. 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!") @@ -146,7 +146,7 @@ func processMigration(tx kvdb.RwTx, cfg MigrateRevLogConfig) (bool, error) { // Locate the next migration height. locator, err := locateNextUpdateNum(openChanBucket) 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. @@ -157,7 +157,7 @@ func processMigration(tx kvdb.RwTx, cfg MigrateRevLogConfig) (bool, error) { // Read a list of old revocation logs. entryMap, err := readOldRevocationLogs(openChanBucket, locator, cfg) 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. @@ -232,7 +232,7 @@ func writeRevocationLogs(openChanBucket kvdb.RwBucket, // Find the channel bucket. chanBucket, err := locator.locateChanBucket(openChanBucket) if err != nil { - return fmt.Errorf("locateChanBucket err: %v", err) + return fmt.Errorf("locateChanBucket err: %w", err) } // Create the new log bucket. @@ -240,7 +240,7 @@ func writeRevocationLogs(openChanBucket kvdb.RwBucket, revocationLogBucket, ) 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. @@ -345,7 +345,7 @@ func fetchLogStats(tx kvdb.RwTx) (uint64, uint64, error) { // Locate the next migration height. locator, err := locateNextUpdateNum(openChanBucket) 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 @@ -491,7 +491,7 @@ func readOldRevocationLogs(openChanBucket kvdb.RwBucket, c := &mig26.OpenChannel{} err := mig26.FetchChanInfo(chanBucket, c, false) 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) diff --git a/channeldb/migration30/test_utils.go b/channeldb/migration30/test_utils.go index c66b796b5..e272cf41c 100644 --- a/channeldb/migration30/test_utils.go +++ b/channeldb/migration30/test_utils.go @@ -334,18 +334,18 @@ func setupTestLogs(db kvdb.Backend, c *mig26.OpenChannel, // Save channel info. 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. if err := putChanRevocationState(chanBucket, c); err != nil { - return fmt.Errorf("putChanRevocationState got %v", err) + return fmt.Errorf("putChanRevocationState got %w", err) } // Create old logs. err = writeOldRevocationLogs(chanBucket, oldLogs) if err != nil { - return fmt.Errorf("write old logs: %v", err) + return fmt.Errorf("write old logs: %w", err) } // Create new logs. diff --git a/channeldb/migration_01_to_11/migration_11_invoices_test.go b/channeldb/migration_01_to_11/migration_11_invoices_test.go index 567150ec4..553a8cfee 100644 --- a/channeldb/migration_01_to_11/migration_11_invoices_test.go +++ b/channeldb/migration_01_to_11/migration_11_invoices_test.go @@ -156,7 +156,7 @@ func signDigestCompact(hash []byte) ([]byte, error) { // ecdsa.SignCompact returns a pubkey-recoverable signature sig, err := ecdsa.SignCompact(privKey, hash, isCompressedKey) 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 diff --git a/channeldb/migration_01_to_11/migrations.go b/channeldb/migration_01_to_11/migrations.go index 918a9317d..6ae25e210 100644 --- a/channeldb/migration_01_to_11/migrations.go +++ b/channeldb/migration_01_to_11/migrations.go @@ -22,13 +22,13 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error { // where these items will be housed. nodes, err := tx.CreateTopLevelBucket(nodeBucket) 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( nodeUpdateIndexBucket, ) 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") @@ -57,7 +57,7 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error { return nodeUpdateIndex.Put(indexKey[:], 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") @@ -66,13 +66,13 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error { // corresponding entry in the edge update index. edges, err := tx.CreateTopLevelBucket(edgeBucket) 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( edgeUpdateIndexBucket, ) 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 @@ -109,7 +109,7 @@ func MigrateNodeAndEdgeUpdateIndex(tx kvdb.RwTx) error { return edgeUpdateIndex.Put(indexKey[:], 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!") @@ -169,7 +169,7 @@ func MigrateInvoiceTimeSeries(tx kvdb.RwTx) error { invoiceReader := bytes.NewReader(invoiceBytesCopy) invoice, err := deserializeInvoiceLegacy(invoiceReader) 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 @@ -307,7 +307,8 @@ func MigrateInvoiceTimeSeriesOutgoingPayments(tx kvdb.RwTx) error { paymentReader := bytes.NewReader(paymentCopy) _, err := deserializeOutgoingPayment(paymentReader) 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 @@ -400,7 +401,7 @@ func MigrateEdgePolicies(tx kvdb.RwTx) error { }) 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!") @@ -649,7 +650,7 @@ func MigrateOptionalChannelCloseSummaryFields(tx kvdb.RwTx) error { return 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. diff --git a/chanrestore.go b/chanrestore.go index 2e011c971..27f6d6d9e 100644 --- a/chanrestore.go +++ b/chanrestore.go @@ -57,31 +57,33 @@ func (c *chanDBRestorer) openChannelShell(backup chanbackup.Single) ( backup.LocalChanCfg.MultiSigKey.KeyLocator, ) 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.KeyLocator, ) 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.KeyLocator, ) 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.KeyLocator, ) 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.KeyLocator, ) 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. @@ -161,7 +163,7 @@ func (c *chanDBRestorer) openChannelShell(backup chanbackup.Single) ( chanType |= channeldb.SimpleTaprootFeatureBit 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"+ diff --git a/cmd/lncli/cmd_import_mission_control.go b/cmd/lncli/cmd_import_mission_control.go index 22ca217f7..23935753d 100644 --- a/cmd/lncli/cmd_import_mission_control.go +++ b/cmd/lncli/cmd_import_mission_control.go @@ -43,12 +43,12 @@ func importMissionControl(ctx *cli.Context) error { sourceNode, err := route.NewVertexFromStr(args[0]) 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]) 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) @@ -63,7 +63,7 @@ func importMissionControl(ctx *cli.Context) error { amt, err := strconv.ParseInt(args[3], 10, 64) 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 { diff --git a/cmd/lncli/cmd_invoice.go b/cmd/lncli/cmd_invoice.go index 3419f8192..4c60294ca 100644 --- a/cmd/lncli/cmd_invoice.go +++ b/cmd/lncli/cmd_invoice.go @@ -98,7 +98,8 @@ func addInvoice(ctx *cli.Context) error { amt, err = strconv.ParseInt(args.First(), 10, 64) args = args.Tail() 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 { - 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")) 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{ @@ -175,7 +176,7 @@ func lookupInvoice(ctx *cli.Context) error { } 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{ diff --git a/cmd/lncli/cmd_macaroon.go b/cmd/lncli/cmd_macaroon.go index e5b170752..92a96c43c 100644 --- a/cmd/lncli/cmd_macaroon.go +++ b/cmd/lncli/cmd_macaroon.go @@ -372,7 +372,7 @@ func printMacaroon(ctx *cli.Context) error { // Decode the macaroon and its protobuf encoded internal identifier. mac := &macaroon.Macaroon{} 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() if rawID[0] != byte(bakery.LatestVersion) { @@ -382,7 +382,7 @@ func printMacaroon(ctx *cli.Context) error { idProto := rawID[1:] err = proto.Unmarshal(idProto, decodedID) 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. @@ -550,7 +550,7 @@ func applyMacaroonConstraints(ctx *cli.Context, constrainedMac, err := macaroons.AddConstraints(mac, macConstraints...) if err != nil { - return nil, fmt.Errorf("error adding constraints: %v", err) + return nil, fmt.Errorf("error adding constraints: %w", err) } return constrainedMac, nil diff --git a/cmd/lncli/cmd_mission_control.go b/cmd/lncli/cmd_mission_control.go index 9749bcf2f..323acdff6 100644 --- a/cmd/lncli/cmd_mission_control.go +++ b/cmd/lncli/cmd_mission_control.go @@ -312,17 +312,17 @@ func queryProb(ctx *cli.Context) error { fromNode, err := route.NewVertexFromStr(args.Get(0)) 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)) 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) if err != nil { - return fmt.Errorf("invalid amt: %v", err) + return fmt.Errorf("invalid amt: %w", err) } amtMsat := lnwire.NewMSatFromSatoshis( diff --git a/cmd/lncli/cmd_open_channel.go b/cmd/lncli/cmd_open_channel.go index 28e1b4b2a..45f032f53 100644 --- a/cmd/lncli/cmd_open_channel.go +++ b/cmd/lncli/cmd_open_channel.go @@ -382,7 +382,7 @@ func openChannel(ctx *cli.Context) error { args.First(), 10, 64, ) 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() case !ctx.Bool("fundmax"): @@ -420,7 +420,7 @@ func openChannel(ctx *cli.Context) error { } else if args.Present() { req.PushSat, err = strconv.ParseInt(args.First(), 10, 64) 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 != "" { basePsbtBytes, err = base64.StdEncoding.DecodeString(basePsbt) 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 // identifier when sending update messages to the RPC server. 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", pendingChanID) @@ -591,7 +591,7 @@ func openChannelPsbt(rpcCtx context.Context, ctx *cli.Context, // explicitly capture the signal. stream, err := client.OpenChannel(ctxc, req) 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 @@ -859,7 +859,7 @@ func batchOpenChannel(ctx *cli.Context) error { // marshaler that keeps the original snake case. var jsonChannels []*batchChannelJSON 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)) diff --git a/cmd/lncli/cmd_payments.go b/cmd/lncli/cmd_payments.go index 42b902ff7..bee74e31c 100644 --- a/cmd/lncli/cmd_payments.go +++ b/cmd/lncli/cmd_payments.go @@ -376,7 +376,8 @@ func sendPayment(ctx *cli.Context) error { amount, err = strconv.ParseInt(args.First(), 10, 64) args = args.Tail() 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(): amt, err = strconv.ParseInt(args.First(), 10, 64) if err != nil { - return fmt.Errorf("unable to decode amt argument: %v", err) + return fmt.Errorf("unable to decode amt argument: %w", + err) } default: return fmt.Errorf("amt argument missing") @@ -1490,7 +1492,7 @@ func forwardingHistory(ctx *cli.Context) error { startTime = uint64(now.Add(-time.Hour * 24).Unix()) } if err != nil { - return fmt.Errorf("unable to decode start_time: %v", err) + return fmt.Errorf("unable to decode start_time: %w", err) } switch { @@ -1503,7 +1505,7 @@ func forwardingHistory(ctx *cli.Context) error { endTime = uint64(now.Unix()) } if err != nil { - return fmt.Errorf("unable to decode end_time: %v", err) + return fmt.Errorf("unable to decode end_time: %w", err) } switch { @@ -1786,7 +1788,7 @@ func deletePayments(ctx *cli.Context) error { }, ) if err != nil { - return fmt.Errorf("error deleting payments: %v", err) + return fmt.Errorf("error deleting payments: %w", err) } } diff --git a/cmd/lncli/cmd_profile.go b/cmd/lncli/cmd_profile.go index 428daede8..0f350e5c2 100644 --- a/cmd/lncli/cmd_profile.go +++ b/cmd/lncli/cmd_profile.go @@ -119,7 +119,7 @@ func profileAdd(ctx *cli.Context) error { // Create a profile struct from all the global options. profile, err := profileFromContext(ctx, true, false) 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 @@ -181,7 +181,7 @@ func profileRemove(ctx *cli.Context) error { // Load the default profile file. f, err := loadProfileFile(defaultProfileFile) 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. @@ -260,7 +260,7 @@ func profileSetDefault(ctx *cli.Context) error { // Load the default profile file. f, err := loadProfileFile(defaultProfileFile) 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. @@ -313,7 +313,7 @@ func profileUnsetDefault(_ *cli.Context) error { // Load the default profile file. f, err := loadProfileFile(defaultProfileFile) 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. @@ -359,7 +359,7 @@ func profileAddMacaroon(ctx *cli.Context) error { // yet. f, err := loadProfileFile(defaultProfileFile) 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 @@ -425,17 +425,17 @@ func profileAddMacaroon(ctx *cli.Context) error { macPath := lncfg.CleanAndExpandPath(ctx.GlobalString("macaroonpath")) macBytes, err := ioutil.ReadFile(macPath) 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{} 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{ Name: macName, } 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. diff --git a/cmd/lncli/cmd_version.go b/cmd/lncli/cmd_version.go index bd8dd66a5..99cc72995 100644 --- a/cmd/lncli/cmd_version.go +++ b/cmd/lncli/cmd_version.go @@ -43,7 +43,7 @@ func version(ctx *cli.Context) error { lndVersion, err := client.GetVersion(ctxc, &verrpc.VersionRequest{}) if err != nil { 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 diff --git a/cmd/lncli/cmd_walletunlocker.go b/cmd/lncli/cmd_walletunlocker.go index cbf900f82..9227d10d4 100644 --- a/cmd/lncli/cmd_walletunlocker.go +++ b/cmd/lncli/cmd_walletunlocker.go @@ -141,7 +141,7 @@ func create(ctx *cli.Context) error { // Passed an invalid channel backup file. 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. default: @@ -356,7 +356,7 @@ mnemonicCheck: } seedResp, err := client.GenSeed(ctxc, genSeedReq) if err != nil { - return fmt.Errorf("unable to generate seed: %v", err) + return fmt.Errorf("unable to generate seed: %w", err) } cipherSeedMnemonic = seedResp.CipherSeedMnemonic @@ -721,7 +721,7 @@ func createWatchOnly(ctx *cli.Context) error { jsonAccts := &walletrpc.ListAccountsResponse{} err = lnrpc.ProtoJSONUnmarshalOpts.Unmarshal(jsonBytes, jsonAccts) if err != nil { - return fmt.Errorf("error parsing JSON: %v", err) + return fmt.Errorf("error parsing JSON: %w", err) } if len(jsonAccts.Accounts) == 0 { return fmt.Errorf("cannot import empty account list") diff --git a/cmd/lncli/commands.go b/cmd/lncli/commands.go index 8d68c4cdf..cc8efc5f0 100644 --- a/cmd/lncli/commands.go +++ b/cmd/lncli/commands.go @@ -365,7 +365,7 @@ func sendCoins(ctx *cli.Context) error { return fmt.Errorf("Amount argument missing") } 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") { @@ -1015,7 +1015,7 @@ func closeAllChannels(ctx *cli.Context) error { listReq := &lnrpc.ListChannelsRequest{} openChannels, err := client.ListChannels(ctxc, listReq) 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 { @@ -1302,7 +1302,8 @@ func parseChannelPoint(ctx *cli.Context) (*lnrpc.ChannelPoint, error) { case args.Present(): index, err := strconv.ParseUint(args.First(), 10, 32) 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) default: @@ -1548,7 +1549,7 @@ func listChannels(ctx *cli.Context) error { if len(peer) > 0 { pk, err := route.NewVertexFromStr(peer) if err != nil { - return fmt.Errorf("invalid --peer pubkey: %v", err) + return fmt.Errorf("invalid --peer pubkey: %w", err) } peerKey = pk[:] @@ -2154,12 +2155,12 @@ func parseChanPoint(s string) (*lnrpc.ChannelPoint, error) { index, err := strconv.ParseInt(split[1], 10, 64) 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]) 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{ @@ -2207,7 +2208,8 @@ func updateChannelPolicy(ctx *cli.Context) error { case args.Present(): baseFee, err = strconv.ParseInt(args.First(), 10, 64) 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() default: @@ -2224,7 +2226,7 @@ func updateChannelPolicy(ctx *cli.Context) error { case args.Present(): feeRate, err = strconv.ParseFloat(args.First(), 64) 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() @@ -2265,7 +2267,7 @@ func updateChannelPolicy(ctx *cli.Context) error { if chanPointStr != "" { chanPoint, err = parseChanPoint(chanPointStr) 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 != "" { chanPointRPC, err := parseChanPoint(chanPointStr) 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( @@ -2751,7 +2753,7 @@ func restoreChanBackup(ctx *cli.Context) error { _, err = client.RestoreChannelBackups(ctxc, &req) 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 diff --git a/cmd/lncli/devrpc_active.go b/cmd/lncli/devrpc_active.go index 02cdcdee6..da3f08a97 100644 --- a/cmd/lncli/devrpc_active.go +++ b/cmd/lncli/devrpc_active.go @@ -50,7 +50,7 @@ func importGraph(ctx *cli.Context) error { jsonGraph := &lnrpc.ChannelGraph{} err = lnrpc.ProtoJSONUnmarshalOpts.Unmarshal(jsonBytes, jsonGraph) 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) if err != nil { diff --git a/cmd/lncli/invoicesrpc_active.go b/cmd/lncli/invoicesrpc_active.go index 095911b66..2ce900695 100644 --- a/cmd/lncli/invoicesrpc_active.go +++ b/cmd/lncli/invoicesrpc_active.go @@ -69,7 +69,7 @@ func settleInvoice(ctx *cli.Context) error { } if err != nil { - return fmt.Errorf("unable to parse preimage: %v", err) + return fmt.Errorf("unable to parse preimage: %w", err) } invoice := &invoicesrpc.SettleInvoiceMsg{ @@ -123,7 +123,7 @@ func cancelInvoice(ctx *cli.Context) error { } if err != nil { - return fmt.Errorf("unable to parse preimage: %v", err) + return fmt.Errorf("unable to parse preimage: %w", err) } invoice := &invoicesrpc.CancelInvoiceMsg{ @@ -212,7 +212,7 @@ func addHoldInvoice(ctx *cli.Context) error { hash, err := hex.DecodeString(args.First()) if err != nil { - return fmt.Errorf("unable to parse hash: %v", err) + return fmt.Errorf("unable to parse hash: %w", err) } args = args.Tail() @@ -223,13 +223,14 @@ func addHoldInvoice(ctx *cli.Context) error { if !ctx.IsSet("amt") && !ctx.IsSet("amt_msat") && args.Present() { amt, err = strconv.ParseInt(args.First(), 10, 64) 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")) 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{ diff --git a/cmd/lncli/macaroon_jar.go b/cmd/lncli/macaroon_jar.go index 29b364904..2c140fa6d 100644 --- a/cmd/lncli/macaroon_jar.go +++ b/cmd/lncli/macaroon_jar.go @@ -81,7 +81,7 @@ func (e *macaroonEntry) loadMacaroon( // Parse the macaroon data into its native struct. mac := &macaroon.Macaroon{} 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 } @@ -93,7 +93,7 @@ func (e *macaroonEntry) storeMacaroon(mac *macaroon.Macaroon, pw []byte) error { // First of all, make sure we can serialize the macaroon. macBytes, err := mac.MarshalBinary() 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 { @@ -106,14 +106,14 @@ func (e *macaroonEntry) storeMacaroon(mac *macaroon.Macaroon, pw []byte) error { &pw, snacl.DefaultN, snacl.DefaultR, snacl.DefaultP, ) 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 // human readable format snacl::. encryptedMac, err := key.Encrypt(macBytes) 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()) diff --git a/cmd/lncli/main.go b/cmd/lncli/main.go index bd5834403..b0ef75b40 100644 --- a/cmd/lncli/main.go +++ b/cmd/lncli/main.go @@ -99,7 +99,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn { // created from the global options in the CLI context. profile, err := getGlobalOptions(ctx, skipMacaroons) 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. @@ -118,7 +118,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn { // Load the specified TLS certificate. certPool, err := profile.cert() 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 @@ -164,7 +164,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn { // don't need to ask for it every time. mac, err := macEntry.loadMacaroon(readPassword) if err != nil { - fatal(fmt.Errorf("could not load macaroon: %v", err)) + fatal(fmt.Errorf("could not load macaroon: %w", err)) } 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. cred, err := macaroons.NewMacaroonCredential(constrainedMac) 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)) } @@ -228,7 +228,7 @@ func getClientConn(ctx *cli.Context, skipMacaroons bool) *grpc.ClientConn { conn, err := grpc.Dial(profile.RPCServer, opts...) 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 diff --git a/cmd/lncli/profile.go b/cmd/lncli/profile.go index 0b91bbe68..9c6680542 100644 --- a/cmd/lncli/profile.go +++ b/cmd/lncli/profile.go @@ -174,7 +174,7 @@ func profileFromContext(ctx *cli.Context, store, skipMacaroons bool) ( } mac := &macaroon.Macaroon{} 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 @@ -193,7 +193,7 @@ func profileFromContext(ctx *cli.Context, store, skipMacaroons bool) ( } macEntry := &macaroonEntry{} 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 @@ -241,7 +241,7 @@ func loadProfileFile(file string) (*profileFile, error) { func saveProfileFile(file string, f *profileFile) error { content, err := f.marshalJSON() 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) } @@ -269,7 +269,7 @@ func (f *profileFile) marshalJSON() ([]byte, error) { var out bytes.Buffer err = json.Indent(&out, b, "", " ") 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") return out.Bytes(), nil diff --git a/cmd/lncli/types.go b/cmd/lncli/types.go index 5e85d0d18..b878811a0 100644 --- a/cmd/lncli/types.go +++ b/cmd/lncli/types.go @@ -34,7 +34,7 @@ func NewProtoOutPoint(op string) (*lnrpc.OutPoint, error) { } outputIndex, err := strconv.Atoi(parts[1]) if err != nil { - return nil, fmt.Errorf("invalid output index: %v", err) + return nil, fmt.Errorf("invalid output index: %w", err) } return &lnrpc.OutPoint{ TxidStr: txid, diff --git a/cmd/lncli/walletrpc_active.go b/cmd/lncli/walletrpc_active.go index 3c210d0f0..f09560169 100644 --- a/cmd/lncli/walletrpc_active.go +++ b/cmd/lncli/walletrpc_active.go @@ -1449,7 +1449,7 @@ func leaseOutput(ctx *cli.Context) error { outpointStr := ctx.String("outpoint") outpoint, err := NewProtoOutPoint(outpointStr) if err != nil { - return fmt.Errorf("error parsing outpoint: %v", err) + return fmt.Errorf("error parsing outpoint: %w", err) } lockIDStr := ctx.String("lockid") @@ -1458,7 +1458,7 @@ func leaseOutput(ctx *cli.Context) error { } lockID, err := hex.DecodeString(lockIDStr) if err != nil { - return fmt.Errorf("error parsing lockid: %v", err) + return fmt.Errorf("error parsing lockid: %w", err) } expiry := ctx.Uint64("expiry") @@ -1534,7 +1534,7 @@ func releaseOutput(ctx *cli.Context) error { outpoint, err := NewProtoOutPoint(outpointStr) if err != nil { - return fmt.Errorf("error parsing outpoint: %v", err) + return fmt.Errorf("error parsing outpoint: %w", err) } lockID := walletrpc.LndInternalLockID[:] @@ -1543,7 +1543,7 @@ func releaseOutput(ctx *cli.Context) error { var err error lockID, err = hex.DecodeString(lockIDStr) 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"), ) if err != nil { - return fmt.Errorf("invalid master key fingerprint: %v", err) + return fmt.Errorf("invalid master key fingerprint: %w", + err) } } diff --git a/cmd/lncli/wtclient.go b/cmd/lncli/wtclient.go index ac844ef45..d73f6ca61 100644 --- a/cmd/lncli/wtclient.go +++ b/cmd/lncli/wtclient.go @@ -67,7 +67,7 @@ func addTower(ctx *cli.Context) error { } pubKey, err := hex.DecodeString(parts[0]) if err != nil { - return fmt.Errorf("invalid public key: %v", err) + return fmt.Errorf("invalid public key: %w", err) } address := parts[1] @@ -160,7 +160,7 @@ func removeTower(ctx *cli.Context) error { } pubKey, err := hex.DecodeString(parts[0]) if err != nil { - return fmt.Errorf("invalid public key: %v", err) + return fmt.Errorf("invalid public key: %w", err) } var address string if len(parts) == 2 { @@ -264,7 +264,7 @@ func getTower(ctx *cli.Context) error { // about. pubKey, err := hex.DecodeString(ctx.Args().Get(0)) if err != nil { - return fmt.Errorf("invalid public key: %v", err) + return fmt.Errorf("invalid public key: %w", err) } client, cleanUp := getWtclient(ctx) diff --git a/config_builder.go b/config_builder.go index 3fcfbb376..27e9f47f6 100644 --- a/config_builder.go +++ b/config_builder.go @@ -425,7 +425,7 @@ func (d *DefaultWalletImpl) BuildWalletConfig(ctx context.Context, // wallet unlocker. err = macaroonService.CreateUnlock(&privateWalletPw) 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) return nil, nil, nil, err } @@ -674,7 +674,7 @@ func (d *DefaultWalletImpl) BuildChainControl( *walletConfig, partialChainControl.Cfg.BlockCache, ) 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) return nil, nil, err } @@ -730,7 +730,7 @@ func (d *DefaultWalletImpl) BuildChainControl( lnWalletConfig, walletController, partialChainControl, ) 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) return nil, nil, err } @@ -778,7 +778,7 @@ func (d *RPCSignerWalletImpl) BuildChainControl( *walletConfig, partialChainControl.Cfg.BlockCache, ) 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) return nil, nil, err } @@ -818,7 +818,7 @@ func (d *RPCSignerWalletImpl) BuildChainControl( lnWalletConfig, rpcKeyRing, partialChainControl, ) 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) return nil, nil, err } @@ -993,7 +993,7 @@ func (d *DefaultDatabaseBuilder) BuildDatabase( case err != nil: 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) return nil, nil, err } @@ -1404,12 +1404,12 @@ func parseHeaderStateAssertion(state string) (*headerfs.FilterHeader, error) { height, err := strconv.ParseUint(split[0], 10, 32) 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]) 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{ diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index c8238df43..0e33dc571 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -924,7 +924,7 @@ func (b *BreachArbitrator) cleanupBreach(chanPoint *wire.OutPoint) error { // With the channel closed, mark it in the database as such. err := b.cfg.DB.MarkChanFullyClosed(chanPoint) 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 diff --git a/contractcourt/chain_watcher.go b/contractcourt/chain_watcher.go index b560795df..55ac0979c 100644 --- a/contractcourt/chain_watcher.go +++ b/contractcourt/chain_watcher.go @@ -1202,7 +1202,7 @@ func (c *chainWatcher) dispatchContractBreach(spendEvent *chainntnfs.SpendDetail c.cfg.chanState.FundingOutpoint, broadcastStateNum) 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) diff --git a/discovery/gossiper.go b/discovery/gossiper.go index 8fd18bf5e..2c353bf6a 100644 --- a/discovery/gossiper.go +++ b/discovery/gossiper.go @@ -1659,7 +1659,7 @@ func (d *AuthenticatedGossiper) retransmitStaleAnns(now time.Time) error { chanToUpdate.info, chanToUpdate.edge, ) 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 @@ -1715,7 +1715,7 @@ func (d *AuthenticatedGossiper) retransmitStaleAnns(now time.Time) error { // With all the wire announcements properly crafted, we'll broadcast // our known outgoing channels to all our immediate peers. 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 diff --git a/discovery/gossiper_test.go b/discovery/gossiper_test.go index a47d98bb9..a7b850529 100644 --- a/discovery/gossiper_test.go +++ b/discovery/gossiper_test.go @@ -806,7 +806,7 @@ func createTestCtx(t *testing.T, startHeight uint32) (*testCtx, error) { }, selfKeyDesc) 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 diff --git a/discovery/syncer.go b/discovery/syncer.go index dc1565371..b567a6940 100644 --- a/discovery/syncer.go +++ b/discovery/syncer.go @@ -904,7 +904,7 @@ func (g *GossipSyncer) processChanRangeReply(msg *lnwire.ReplyChannelRange) erro g.cfg.isStillZombieChannel, ) 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 @@ -1599,7 +1599,8 @@ func (g *GossipSyncer) handleSyncTransition(req *syncTransitionReq) error { err := g.sendGossipTimestampRange(firstTimestamp, timestampRange) 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) diff --git a/discovery/syncer_test.go b/discovery/syncer_test.go index 3a77e046c..7a649f466 100644 --- a/discovery/syncer_test.go +++ b/discovery/syncer_test.go @@ -1045,7 +1045,8 @@ func TestGossipSyncerReplyChanRangeQueryBlockRange(t *testing.T) { go func() { for _, query := range queryReqs { 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 } } diff --git a/funding/batch.go b/funding/batch.go index a45c7e96c..163c33b7e 100644 --- a/funding/batch.go +++ b/funding/batch.go @@ -72,7 +72,7 @@ func (c *batchChannel) processPendingUpdate(u *lnrpc.OpenStatusUpdate) error { hash, err := chainhash.NewHash(pendingUpd.Txid) 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{ @@ -373,7 +373,7 @@ func (b *Batcher) BatchFund(ctx context.Context, channel.pendingChanID, unsignedPacket, false, ) 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{} txReader := bytes.NewReader(finalizePsbtResp.RawFinalTx) 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", base64.StdEncoding.EncodeToString(finalizePsbtResp.SignedPsbt)) @@ -403,7 +403,7 @@ func (b *Batcher) BatchFund(ctx context.Context, channel.pendingChanID, nil, finalTx, ) if err != nil { - return nil, fmt.Errorf("error finalizing PSBT: %v", err) + return nil, fmt.Errorf("error finalizing PSBT: %w", err) } } diff --git a/funding/manager.go b/funding/manager.go index 42aa7bc12..de537b1f2 100644 --- a/funding/manager.go +++ b/funding/manager.go @@ -1656,7 +1656,7 @@ func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer, if err != nil { f.failFundingFlow( peer, cid, - fmt.Errorf("getUpfrontShutdownScript error: %v", err), + fmt.Errorf("getUpfrontShutdownScript error: %w", err), ) return } @@ -3046,7 +3046,7 @@ func (f *Manager) handleFundingConfirmation( err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx) if err != nil { // 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 @@ -3054,14 +3054,14 @@ func (f *Manager) handleFundingConfirmation( if completeChan.NegotiatedAliasFeature() { aliasScid, err := f.cfg.AliasManager.RequestAlias() 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( aliasScid, confChannel.shortChanID, true, ) 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. nextRevocation, err := channel.NextRevocationKey() 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) @@ -3574,7 +3574,7 @@ func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel, // occur due to inconsistency in the OpenChannel struct. err = c.Refresh() 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, diff --git a/htlcswitch/circuit_map_test.go b/htlcswitch/circuit_map_test.go index af9af3fd7..9bbb2c051 100644 --- a/htlcswitch/circuit_map_test.go +++ b/htlcswitch/circuit_map_test.go @@ -307,7 +307,7 @@ func createTestCircuit(ks htlcswitch.Keystone, cm htlcswitch.CircuitMap) error { // should succeed. _, err := cm.CommitCircuits(circuit) 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. @@ -318,7 +318,7 @@ func createTestCircuit(ks htlcswitch.Keystone, cm htlcswitch.CircuitMap) error { // Open the circuit, implicitly creates a keystone on disk. err = cm.OpenCircuits(ks) if err != nil { - return fmt.Errorf("failed to open circuits: %v", err) + return fmt.Errorf("failed to open circuits: %w", err) } return nil diff --git a/htlcswitch/decayedlog.go b/htlcswitch/decayedlog.go index 44e4d1c51..026c6d641 100644 --- a/htlcswitch/decayedlog.go +++ b/htlcswitch/decayedlog.go @@ -63,7 +63,7 @@ func NewBoltBackendCreator(dbPath, db, err := kvdb.GetBoltBackend(cfg) 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 diff --git a/htlcswitch/interceptable_switch.go b/htlcswitch/interceptable_switch.go index 09646bf2d..62f7c93dd 100644 --- a/htlcswitch/interceptable_switch.go +++ b/htlcswitch/interceptable_switch.go @@ -686,7 +686,7 @@ func (f *interceptedForward) FailWithCode(code lnwire.FailCode) error { // of the failure. reason, err := f.packet.obfuscator.EncryptFirstHop(failureMsg) 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{ diff --git a/htlcswitch/link.go b/htlcswitch/link.go index a700c9714..f8f87ca8f 100644 --- a/htlcswitch/link.go +++ b/htlcswitch/link.go @@ -3545,7 +3545,7 @@ func (l *channelLink) settleHTLC(preimage lntypes.Preimage, preimage, pd.HtlcIndex, pd.SourceRef, nil, 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 diff --git a/htlcswitch/switch.go b/htlcswitch/switch.go index dab25aaeb..fa98cca11 100644 --- a/htlcswitch/switch.go +++ b/htlcswitch/switch.go @@ -497,7 +497,7 @@ func (s *Switch) GetAttemptResult(attemptID uint64, paymentHash lntypes.Hash, deobfuscator, n, attemptID, paymentHash, ) if err != nil { - e := fmt.Errorf("unable to extract result: %v", err) + e := fmt.Errorf("unable to extract result: %w", err) log.Error(e) resultChan <- &PaymentResult{ Error: e, @@ -709,7 +709,8 @@ func (s *Switch) ForwardPackets(linkQuit chan struct{}, default: err := s.routeAsync(packet, fwdChan, linkQuit) if err != nil { - return fmt.Errorf("failed to forward packet %v", err) + return fmt.Errorf("failed to forward packet %w", + err) } numSent++ } @@ -754,7 +755,7 @@ func (s *Switch) ForwardPackets(linkQuit chan struct{}, for _, packet := range addedPackets { err := s.routeAsync(packet, fwdChan, linkQuit) if err != nil { - return fmt.Errorf("failed to forward packet %v", err) + return fmt.Errorf("failed to forward packet %w", err) } numSent++ } diff --git a/htlcswitch/test_utils.go b/htlcswitch/test_utils.go index da36e214c..e33c5fe20 100644 --- a/htlcswitch/test_utils.go +++ b/htlcswitch/test_utils.go @@ -1173,7 +1173,7 @@ func (h *hopNetwork) createChannelLink(server, peer *mockServer, channel, ) 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() { diff --git a/internal/musig2v040/musig2_test.go b/internal/musig2v040/musig2_test.go index c9bcabb52..9ba74f417 100644 --- a/internal/musig2v040/musig2_test.go +++ b/internal/musig2v040/musig2_test.go @@ -268,7 +268,7 @@ func TestMuSig2KeyAggTestVectors(t *testing.T) { func mustParseHex(str string) []byte { b, err := hex.DecodeString(str) if err != nil { - panic(fmt.Errorf("unable to parse hex: %v", err)) + panic(fmt.Errorf("unable to parse hex: %w", err)) } return b @@ -1868,10 +1868,10 @@ func getInfinityBytes() []byte { func mustParseHex32(str string) [32]byte { b, err := hex.DecodeString(str) 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 { - panic(fmt.Errorf("not a 32 byte slice: %v", err)) + panic(fmt.Errorf("not a 32 byte slice: %w", err)) } return to32ByteSlice(b) @@ -1880,10 +1880,10 @@ func mustParseHex32(str string) [32]byte { func mustParsePubNonce(str string) [PubNonceSize]byte { b, err := hex.DecodeString(str) 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 { - panic(fmt.Errorf("not a public nonce: %v", err)) + panic(fmt.Errorf("not a public nonce: %w", err)) } return toPubNonceSlice(b) } @@ -1891,7 +1891,7 @@ func mustParsePubNonce(str string) [PubNonceSize]byte { func canParsePubNonce(str string) [PubNonceSize]byte { b, err := hex.DecodeString(str) if err != nil { - panic(fmt.Errorf("unable to parse hex: %v", err)) + panic(fmt.Errorf("unable to parse hex: %w", err)) } return toPubNonceSlice(b) } diff --git a/kvdb/backend.go b/kvdb/backend.go index 76599311b..c8d1e53bb 100644 --- a/kvdb/backend.go +++ b/kvdb/backend.go @@ -157,10 +157,10 @@ func compactAndSwap(cfg *BoltBackendConfig) error { // temporary DB file and close it before we write the new DB to it. tempFile, err := os.Create(tempDestFilePath) 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 { - 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 @@ -178,7 +178,7 @@ func compactAndSwap(cfg *BoltBackendConfig) error { } initialSize, newSize, err := c.execute() 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)", diff --git a/kvdb/bolt_compact.go b/kvdb/bolt_compact.go index 766616f07..6597eb2d5 100644 --- a/kvdb/bolt_compact.go +++ b/kvdb/bolt_compact.go @@ -115,7 +115,7 @@ func (cmd *compacter) execute() (int64, int64, error) { // Run compaction. 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. diff --git a/lncfg/address.go b/lncfg/address.go index 1d962a52f..381ff2a54 100644 --- a/lncfg/address.go +++ b/lncfg/address.go @@ -287,7 +287,8 @@ func ParseLNAddressString(strAddress string, defaultPort string, // Finally, parse the address string using our generic address parser. addr, err := ParseAddressString(parsedAddr, defaultPort, tcpResolver) 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{ @@ -316,7 +317,8 @@ func ParseLNAddressPubkey(strAddress string) (*btcec.PublicKey, string, error) { // Decode the hex pubkey to get the raw compressed pubkey bytes. pubKeyBytes, err := hex.DecodeString(parsedPubKey) 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. @@ -329,7 +331,8 @@ func ParseLNAddressPubkey(strAddress string) (*btcec.PublicKey, string, error) { // key on the secp256k1 curve. pubKey, err := btcec.ParsePubKey(pubKeyBytes) 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 diff --git a/lncfg/db.go b/lncfg/db.go index ed0bdf6b7..d1ecf6386 100644 --- a/lncfg/db.go +++ b/lncfg/db.go @@ -263,7 +263,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath, db.Etcd.CloneWithSubNamespace(NSChannelDB), ) 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 @@ -545,7 +545,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath, AutoCompactMinAge: db.Bolt.AutoCompactMinAge, }) 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 @@ -558,7 +558,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath, AutoCompactMinAge: db.Bolt.AutoCompactMinAge, }) 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 @@ -571,7 +571,7 @@ func (db *DB) GetBackends(ctx context.Context, chanDBPath, AutoCompactMinAge: db.Bolt.AutoCompactMinAge, }) 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 diff --git a/lnd.go b/lnd.go index 5412360e0..0034f134b 100644 --- a/lnd.go +++ b/lnd.go @@ -72,7 +72,7 @@ func AdminAuthOptions(cfg *Config, skipMacaroons bool) ([]grpc.DialOption, creds, err := credentials.NewClientTLSFromFile(cfg.TLSCertPath, "") 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. @@ -98,7 +98,7 @@ func AdminAuthOptions(cfg *Config, skipMacaroons bool) ([]grpc.DialOption, // Now we append the macaroon credentials to the dial options. cred, err := macaroons.NewMacaroonCredential(mac) 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)) } diff --git a/lnrpc/devrpc/dev_server.go b/lnrpc/devrpc/dev_server.go index afe30b361..e2b98efa7 100644 --- a/lnrpc/devrpc/dev_server.go +++ b/lnrpc/devrpc/dev_server.go @@ -181,12 +181,12 @@ func parseOutPoint(s string) (*wire.OutPoint, error) { index, err := strconv.ParseInt(split[1], 10, 32) 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]) 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{ diff --git a/lnrpc/neutrinorpc/neutrino_server.go b/lnrpc/neutrinorpc/neutrino_server.go index 1abd95f73..65b0c8a6e 100644 --- a/lnrpc/neutrinorpc/neutrino_server.go +++ b/lnrpc/neutrinorpc/neutrino_server.go @@ -198,7 +198,7 @@ func (s *Server) Status(ctx context.Context, bestBlock, err := s.cfg.NeutrinoCS.BestBlock() 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() diff --git a/lnrpc/peersrpc/peers_server.go b/lnrpc/peersrpc/peers_server.go index 6981f7949..14e039f61 100644 --- a/lnrpc/peersrpc/peers_server.go +++ b/lnrpc/peersrpc/peers_server.go @@ -335,7 +335,7 @@ func (s *Server) UpdateNodeAnnouncement(_ context.Context, if req.Color != "" { color, err := lncfg.ParseHexColor(req.Color) 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 { @@ -355,7 +355,7 @@ func (s *Server) UpdateNodeAnnouncement(_ context.Context, if req.Alias != "" { alias, err := lnwire.NewNodeAlias(req.Alias) 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 { resp.Ops = append(resp.Ops, &lnrpc.Op{ diff --git a/lnrpc/signrpc/signer_server.go b/lnrpc/signrpc/signer_server.go index c01c2d77a..a84ea68ff 100644 --- a/lnrpc/signrpc/signer_server.go +++ b/lnrpc/signrpc/signer_server.go @@ -293,7 +293,7 @@ func (s *Server) SignOutputRaw(_ context.Context, in *SignReq) (*SignResp, ) txReader := bytes.NewReader(in.RawTxBytes) 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 ( @@ -520,7 +520,7 @@ func (s *Server) ComputeInputScript(ctx context.Context, var txToSign wire.MsgTx txReader := bytes.NewReader(in.RawTxBytes) 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 ( @@ -636,7 +636,7 @@ func (s *Server) SignMessage(_ context.Context, in.SchnorrSigTapTweak, in.Tag, ) 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()) @@ -659,7 +659,7 @@ func (s *Server) SignMessage(_ context.Context, keyLocator, in.Msg, in.DoubleHash, ) 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{ @@ -673,11 +673,11 @@ func (s *Server) SignMessage(_ context.Context, keyLocator, in.Msg, in.DoubleHash, ) 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) 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{ Signature: wireSig.ToSignatureBytes(), @@ -736,13 +736,13 @@ func (s *Server) VerifyMessage(_ context.Context, pubkey, err := btcec.ParsePubKey(in.Pubkey) 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. wireSig, err := lnwire.NewSigFromECDSARawSignature(in.Signature) 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() if err != nil { @@ -772,7 +772,7 @@ func (s *Server) DeriveSharedKey(_ context.Context, in *SharedKeyRequest) ( // Check that EphemeralPubkey is valid. ephemeralPubkey, err := parseRawKeyBytes(in.EphemeralPubkey) 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 { 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. pk, err := parseRawKeyBytes(rawKeyBytes) 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 @@ -838,7 +838,7 @@ func (s *Server) DeriveSharedKey(_ context.Context, in *SharedKeyRequest) ( // compressed shared point. sharedKeyHash, err := s.cfg.KeyRing.ECDH(keyDescriptor, ephemeralPubkey) 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) return nil, err } @@ -883,7 +883,7 @@ func (s *Server) MuSig2CombineKeys(_ context.Context, version, allSignerPubKeys, true, tweaks, ) if err != nil { - return nil, fmt.Errorf("error combining keys: %v", err) + return nil, fmt.Errorf("error combining keys: %w", err) } var internalKeyBytes []byte @@ -1008,7 +1008,7 @@ func (s *Server) MuSig2CreateSession(_ context.Context, in.OtherSignerPublicNonces, true, ) 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? @@ -1024,7 +1024,7 @@ func (s *Server) MuSig2CreateSession(_ context.Context, localNonces, ) if err != nil { - return nil, fmt.Errorf("error registering session: %v", err) + return nil, fmt.Errorf("error registering session: %w", err) } var internalKeyBytes []byte @@ -1054,7 +1054,7 @@ func (s *Server) MuSig2RegisterNonces(_ context.Context, // Check session ID length. sessionID, err := parseMuSig2SessionID(in.SessionId) 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 @@ -1067,7 +1067,7 @@ func (s *Server) MuSig2RegisterNonces(_ context.Context, in.OtherSignerPublicNonces, false, ) 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. @@ -1075,7 +1075,7 @@ func (s *Server) MuSig2RegisterNonces(_ context.Context, sessionID, otherSignerNonces, ) 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 @@ -1093,7 +1093,7 @@ func (s *Server) MuSig2Sign(_ context.Context, // Check session ID length. sessionID, err := parseMuSig2SessionID(in.SessionId) 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. @@ -1107,12 +1107,12 @@ func (s *Server) MuSig2Sign(_ context.Context, // Create our own partial signature with the local signing key. partialSig, err := s.cfg.Signer.MuSig2Sign(sessionID, msg, in.Cleanup) if err != nil { - return nil, fmt.Errorf("error signing: %v", err) + return nil, fmt.Errorf("error signing: %w", err) } serializedPartialSig, err := input.SerializePartialSignature(partialSig) if err != nil { - return nil, fmt.Errorf("error serializing sig: %v", err) + return nil, fmt.Errorf("error serializing sig: %w", err) } return &MuSig2SignResponse{ @@ -1129,7 +1129,7 @@ func (s *Server) MuSig2CombineSig(_ context.Context, // Check session ID length. sessionID, err := parseMuSig2SessionID(in.SessionId) 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 @@ -1149,7 +1149,7 @@ func (s *Server) MuSig2CombineSig(_ context.Context, sessionID, partialSigs, ) if err != nil { - return nil, fmt.Errorf("error combining signatures: %v", err) + return nil, fmt.Errorf("error combining signatures: %w", err) } resp := &MuSig2CombineSigResponse{ @@ -1170,12 +1170,12 @@ func (s *Server) MuSig2Cleanup(_ context.Context, // Check session ID length. sessionID, err := parseMuSig2SessionID(in.SessionId) 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) 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 diff --git a/lnrpc/walletrpc/walletkit_server.go b/lnrpc/walletrpc/walletkit_server.go index f005a8bff..3e71070aa 100644 --- a/lnrpc/walletrpc/walletkit_server.go +++ b/lnrpc/walletrpc/walletkit_server.go @@ -1434,7 +1434,7 @@ func (w *WalletKit) fundPsbtInternalWallet(account string, packet, minConfs, feeSatPerKW, account, keyScope, ) 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 @@ -1865,7 +1865,7 @@ func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) ( if err != nil { log.Debugf("Error parsing PSBT: %v, raw input: %x", err, 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 @@ -1886,14 +1886,14 @@ func (w *WalletKit) SignPsbt(_ context.Context, req *SignPsbtRequest) ( // witness data attached, they will just be skipped. signedInputs, err := w.cfg.Wallet.SignPsbt(packet) 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. var signedPsbtBytes bytes.Buffer err = packet.Serialize(&signedPsbtBytes) if err != nil { - return nil, fmt.Errorf("error serializing PSBT: %v", err) + return nil, fmt.Errorf("error serializing PSBT: %w", err) } return &SignPsbtResponse{ @@ -1928,7 +1928,7 @@ func (w *WalletKit) FinalizePsbt(_ context.Context, bytes.NewReader(req.FundedPsbt), false, ) 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 @@ -1942,7 +1942,7 @@ func (w *WalletKit) FinalizePsbt(_ context.Context, // witness data attached, this will fail. err = w.cfg.Wallet.FinalizePsbt(packet, account) if err != nil { - return nil, fmt.Errorf("error finalizing PSBT: %v", err) + return nil, fmt.Errorf("error finalizing PSBT: %w", err) } var ( @@ -1953,15 +1953,15 @@ func (w *WalletKit) FinalizePsbt(_ context.Context, // Serialize the finalized PSBT in both the packet and wire format. err = packet.Serialize(&finalPsbtBytes) 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) 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) 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{ @@ -2544,7 +2544,7 @@ func (w *WalletKit) ImportTapscript(_ context.Context, internalKey, err := schnorr.ParsePubKey(req.InternalPublicKey) 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 diff --git a/lntest/bitcoind_common.go b/lntest/bitcoind_common.go index 8cac2e5af..9ce962dc2 100644 --- a/lntest/bitcoind_common.go +++ b/lntest/bitcoind_common.go @@ -107,7 +107,7 @@ func newBackend(miner string, netParams *chaincfg.Params, extraArgs []string, tempBitcoindDir, err := ioutil.TempDir("", "bitcoind") if err != 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", @@ -138,7 +138,7 @@ func newBackend(miner string, netParams *chaincfg.Params, extraArgs []string, fmt.Printf("unable to remote temp dir %v: %v", 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 { diff --git a/lntest/node/harness_node.go b/lntest/node/harness_node.go index 750245116..64c5eb9b6 100644 --- a/lntest/node/harness_node.go +++ b/lntest/node/harness_node.go @@ -327,7 +327,7 @@ func (hn *HarnessNode) ConnectRPCWithMacaroon(mac *macaroon.Macaroon) ( return err }, wait.DefaultTimeout) 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{ @@ -343,7 +343,7 @@ func (hn *HarnessNode) ConnectRPCWithMacaroon(mac *macaroon.Macaroon) ( } macCred, err := macaroons.NewMacaroonCredential(mac) 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)) @@ -452,7 +452,7 @@ func (hn *HarnessNode) Start(ctxt context.Context) error { // Wait till the server is starting. 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. @@ -544,7 +544,7 @@ func (hn *HarnessNode) waitTillServerState( case <-time.After(wait.NodeStartTimeout): return fmt.Errorf("timeout waiting for server state") case err := <-errChan: - return fmt.Errorf("receive server state err: %v", err) + return fmt.Errorf("receive server state err: %w", err) case <-done: return nil @@ -906,7 +906,7 @@ func executePgQuery(query string) error { postgresDatabaseDsn("postgres"), ) 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() diff --git a/lntest/node/watcher.go b/lntest/node/watcher.go index e89bcf6d1..a87e6c2ba 100644 --- a/lntest/node/watcher.go +++ b/lntest/node/watcher.go @@ -245,7 +245,7 @@ func (nw *nodeWatcher) WaitForChannelPolicyUpdate( case <-timer: expected, err := json.MarshalIndent(policy, "", "\t") if err != nil { - return fmt.Errorf("encode policy err: %v", err) + return fmt.Errorf("encode policy err: %w", err) } policies, err := syncMapToJSON( &nw.state.policyUpdates.Map, @@ -274,7 +274,7 @@ func syncMapToJSON(state *sync.Map) ([]byte, error) { }) policies, err := json.MarshalIndent(m, "", "\t") if err != nil { - return nil, fmt.Errorf("encode polices err: %v", err) + return nil, fmt.Errorf("encode polices err: %w", err) } return policies, nil diff --git a/lnwallet/btcwallet/psbt_test.go b/lnwallet/btcwallet/psbt_test.go index d3cf3f413..3f04bc7a8 100644 --- a/lnwallet/btcwallet/psbt_test.go +++ b/lnwallet/btcwallet/psbt_test.go @@ -246,7 +246,7 @@ func serializeTxWitness(txWitness wire.TxWitness) ([]byte, error) { var witnessBytes bytes.Buffer err := psbt.WriteTxWitness(&witnessBytes, txWitness) 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 diff --git a/lnwallet/chancloser/chancloser.go b/lnwallet/chancloser/chancloser.go index 97f5f4a63..98efa7095 100644 --- a/lnwallet/chancloser/chancloser.go +++ b/lnwallet/chancloser/chancloser.go @@ -1077,7 +1077,7 @@ func ParseUpfrontShutdownAddress(address string, address, params, ) if err != nil { - return nil, fmt.Errorf("invalid address: %v", err) + return nil, fmt.Errorf("invalid address: %w", err) } if !addr.IsForNet(params) { diff --git a/lnwallet/chanfunding/psbt_assembler.go b/lnwallet/chanfunding/psbt_assembler.go index f1e1f2c95..5132f1296 100644 --- a/lnwallet/chanfunding/psbt_assembler.go +++ b/lnwallet/chanfunding/psbt_assembler.go @@ -227,7 +227,7 @@ func (i *PsbtIntent) Verify(packet *psbt.Packet, skipFinalize bool) error { // Try to locate the channel funding multisig output. _, expectedOutput, err := i.FundingOutput() 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 outputSum := int64(0) @@ -250,7 +250,7 @@ func (i *PsbtIntent) Verify(packet *psbt.Packet, skipFinalize bool) error { } sum, err := psbt.SumUtxoInputValues(packet) if err != nil { - return fmt.Errorf("error determining input sum: %v", err) + return fmt.Errorf("error determining input sum: %w", err) } if sum <= outputSum { return fmt.Errorf("input amount sum must be larger than " + @@ -304,11 +304,11 @@ func (i *PsbtIntent) Finalize(packet *psbt.Packet) error { // broadcast. err := psbt.MaybeFinalizeAll(packet) if err != nil { - return fmt.Errorf("error finalizing PSBT: %v", err) + return fmt.Errorf("error finalizing PSBT: %w", err) } rawTx, err := psbt.Extract(packet) 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) @@ -340,13 +340,13 @@ func (i *PsbtIntent) FinalizeRawTX(rawTx *wire.MsgTx) error { rawTx.TxOut, i.PendingPsbt.UnsignedTx.TxOut, ) 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( rawTx.TxIn, i.PendingPsbt.UnsignedTx.TxIn, ) 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 @@ -354,7 +354,7 @@ func (i *PsbtIntent) FinalizeRawTX(rawTx *wire.MsgTx) error { // extracting the TX from a PSBT. err = verifyInputsSigned(rawTx.TxIn) 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 @@ -383,7 +383,7 @@ func (i *PsbtIntent) CompileFundingTx() (*wire.MsgTx, error) { // Identify our funding outpoint now that we know everything's ready. _, txOut, err := i.FundingOutput() 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) if !ok { diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 32a00e769..6d3f928b6 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -6796,10 +6796,10 @@ func compareLogs(a, b *updateLog) error { } 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 { - 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() { diff --git a/lnwallet/rpcwallet/rpcwallet.go b/lnwallet/rpcwallet/rpcwallet.go index 0ee8b215c..50a38cd94 100644 --- a/lnwallet/rpcwallet/rpcwallet.go +++ b/lnwallet/rpcwallet/rpcwallet.go @@ -156,7 +156,7 @@ func (r *RPCKeyRing) SendOutputs(outputs []*wire.TxOut, &txIn.PreviousOutPoint, ) 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) { @@ -201,7 +201,7 @@ func (r *RPCKeyRing) SignPsbt(packet *psbt.Packet) ([]uint32, error) { var buf bytes.Buffer 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{ @@ -217,7 +217,7 @@ func (r *RPCKeyRing) SignPsbt(packet *psbt.Packet) ([]uint32, error) { bytes.NewReader(resp.SignedPsbt), false, ) 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 @@ -349,7 +349,7 @@ func (r *RPCKeyRing) FinalizePsbt(packet *psbt.Packet, _ string) error { var witnessBytes bytes.Buffer err = psbt.WriteTxWitness(&witnessBytes, script.Witness) 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].FinalScriptSig = script.SigScript @@ -359,7 +359,7 @@ func (r *RPCKeyRing) FinalizePsbt(packet *psbt.Packet, _ string) error { // broadcast. err = psbt.MaybeFinalizeAll(packet) if err != nil { - return fmt.Errorf("error finalizing PSBT: %v", err) + return fmt.Errorf("error finalizing PSBT: %w", err) } return nil @@ -732,7 +732,7 @@ func (r *RPCKeyRing) MuSig2CreateSession(bipVersion input.MuSig2Version, info.CombinedKey, err = schnorr.ParsePubKey(resp.CombinedKey) 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() { @@ -891,7 +891,7 @@ func (r *RPCKeyRing) remoteSign(tx *wire.MsgTx, signDesc *input.SignDescriptor, packet, err := packetFromTx(tx) 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 @@ -1157,7 +1157,7 @@ func (r *RPCKeyRing) remoteSign(tx *wire.MsgTx, signDesc *input.SignDescriptor, var buf bytes.Buffer 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( @@ -1173,7 +1173,7 @@ func (r *RPCKeyRing) remoteSign(tx *wire.MsgTx, signDesc *input.SignDescriptor, bytes.NewReader(resp.SignedPsbt), false, ) 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. @@ -1278,12 +1278,12 @@ func connectRPC(hostPort, tlsCertPath, macaroonPath string, } mac := &macaroon.Macaroon{} 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) if err != nil { - return nil, fmt.Errorf("error creating creds: %v", err) + return nil, fmt.Errorf("error creating creds: %w", err) } opts := []grpc.DialOption{ diff --git a/lnwallet/test/test_interface.go b/lnwallet/test/test_interface.go index e4e4fd24c..f97b6500c 100644 --- a/lnwallet/test/test_interface.go +++ b/lnwallet/test/test_interface.go @@ -264,7 +264,7 @@ func loadTestCredits(miner *rpctest.Harness, w *lnwallet.LightningWallet, // give us btcPerOutput with each output. satoshiPerOutput, err := btcutil.NewAmount(btcPerOutput) 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) if err != nil { @@ -1511,11 +1511,11 @@ func scriptFromKey(pubkey *btcec.PublicKey) ([]byte, error) { pubkeyHash, &chaincfg.RegressionNetParams, ) 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) 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 @@ -1526,17 +1526,17 @@ func mineAndAssert(r *rpctest.Harness, tx *wire.MsgTx) error { txid := tx.TxHash() err := waitForMempoolTx(r, &txid) 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) 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]) 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 { @@ -1564,7 +1564,7 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey, // Generate the script we want to spend from. keyScript, err := scriptFromKey(fromPubKey) 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. @@ -1599,7 +1599,7 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey, // Create a script to pay to. payToScript, err := scriptFromKey(payToPubKey) 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{ 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. spendSig, err := signer.SignOutputRaw(tx1, signDesc) 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[0] = append(spendSig.Serialize(), byte(txscript.SigHashAll)) @@ -1640,10 +1640,10 @@ func txFromOutput(tx *wire.MsgTx, signer input.Signer, fromPubKey, ), ) 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 { - return nil, fmt.Errorf("spend is invalid: %v", err) + return nil, fmt.Errorf("spend is invalid: %w", err) } return tx1, nil diff --git a/lnwallet/wallet.go b/lnwallet/wallet.go index 12cd3e1d7..6a8ced33b 100644 --- a/lnwallet/wallet.go +++ b/lnwallet/wallet.go @@ -721,7 +721,7 @@ func (l *LightningWallet) PsbtFundingVerify(pendingChanID [32]byte, err := psbtIntent.Verify(packet, skipFinalize) 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 @@ -773,13 +773,13 @@ func (l *LightningWallet) PsbtFundingFinalize(pid [32]byte, packet *psbt.Packet, case packet != nil && rawTx == nil: err := psbtIntent.Finalize(packet) if err != nil { - return fmt.Errorf("error finalizing PSBT: %v", err) + return fmt.Errorf("error finalizing PSBT: %w", err) } case rawTx != nil && packet == nil: err := psbtIntent.FinalizeRawTX(rawTx) if err != nil { - return fmt.Errorf("error finalizing raw TX: %v", err) + return fmt.Errorf("error finalizing raw TX: %w", err) } default: @@ -1554,7 +1554,8 @@ func (l *LightningWallet) handleContributionMsg(req *addContributionMsg) { case *chanfunding.ShimIntent: chanPoint, err = fundingIntent.ChanPoint() 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 } @@ -1996,7 +1997,8 @@ func (l *LightningWallet) verifyFundingInputs(fundingTx *wire.MsgTx, txin.SignatureScript, txin.Witness, ) 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( &txin.PreviousOutPoint, diff --git a/lnwire/onion_error.go b/lnwire/onion_error.go index af2db1d23..8b7fc733b 100644 --- a/lnwire/onion_error.go +++ b/lnwire/onion_error.go @@ -1336,7 +1336,7 @@ func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) { // the first two bytes of the buffer. var codeBytes [2]byte 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[:])) @@ -1344,7 +1344,7 @@ func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) { // additional data if needed. failure, err := makeEmptyOnionError(failCode) 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 diff --git a/lnwire/query_short_chan_ids.go b/lnwire/query_short_chan_ids.go index 6a90bed75..cb1bfa22c 100644 --- a/lnwire/query_short_chan_ids.go +++ b/lnwire/query_short_chan_ids.go @@ -214,7 +214,8 @@ func decodeShortChanIDs(r io.Reader) (QueryEncoding, []ShortChannelID, error) { N: maxZlibBufSize, }) 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 ( diff --git a/netann/node_signer.go b/netann/node_signer.go index e0b439b14..4cb8cea01 100644 --- a/netann/node_signer.go +++ b/netann/node_signer.go @@ -37,7 +37,7 @@ func (n *NodeSigner) SignMessage(keyLoc keychain.KeyLocator, // Otherwise, we'll sign the double-sha256 of the target message. sig, err := n.keySigner.SignMessage(msg, doubleHash) 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 diff --git a/netann/sign.go b/netann/sign.go index 86634f628..429533136 100644 --- a/netann/sign.go +++ b/netann/sign.go @@ -30,7 +30,7 @@ func SignAnnouncement(signer lnwallet.MessageSigner, keyLoc keychain.KeyLocator, return nil, fmt.Errorf("can't sign %T message", m) } 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) diff --git a/peer/brontide.go b/peer/brontide.go index 6692ee3c1..696ad8610 100644 --- a/peer/brontide.go +++ b/peer/brontide.go @@ -630,7 +630,7 @@ func (p *Brontide) Start() error { // Exchange local and global features, the init message should be very // first between two nodes. 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, @@ -660,7 +660,7 @@ func (p *Brontide) Start() error { handshakeTimeout) case err := <-readErr: 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) 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() @@ -3332,7 +3332,7 @@ func (p *Brontide) handleInitMsg(msg *lnwire.Init) error { // didn't set any required bits that we don't know of. err = feature.ValidateRequired(p.remoteFeatures) 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 @@ -3340,7 +3340,7 @@ func (p *Brontide) handleInitMsg(msg *lnwire.Init) error { // during the feature manager's instantiation. err = feature.ValidateDeps(p.remoteFeatures) 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 diff --git a/pool/worker_test.go b/pool/worker_test.go index e4e73b5f2..c4d8ca694 100644 --- a/pool/worker_test.go +++ b/pool/worker_test.go @@ -352,7 +352,7 @@ func submitGeneric(p interface{}, sem <-chan struct{}) error { } if err != nil { - return fmt.Errorf("unable to submit task: %v", err) + return fmt.Errorf("unable to submit task: %w", err) } return nil diff --git a/routing/ann_validation.go b/routing/ann_validation.go index 35f0afd4d..aca071e17 100644 --- a/routing/ann_validation.go +++ b/routing/ann_validation.go @@ -143,7 +143,7 @@ func VerifyChannelUpdateSignature(msg *lnwire.ChannelUpdate, data, err := msg.DataToSign() 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) diff --git a/routing/chainview/neutrino.go b/routing/chainview/neutrino.go index d5b4ca647..6134cf991 100644 --- a/routing/chainview/neutrino.go +++ b/routing/chainview/neutrino.go @@ -247,7 +247,7 @@ func (c *CfFilteredChainView) FilterBlock(blockHash *chainhash.Hash) (*FilteredB // outpoint that have been spent. filter, err := c.p2pNode.GetCFilter(*blockHash, wire.GCSFilterRegular) 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 @@ -349,7 +349,7 @@ func (c *CfFilteredChainView) UpdateFilter(ops []channeldb.EdgePoint, } err := c.chainView.Update(rescanUpdate...) if err != nil { - return fmt.Errorf("unable to update rescan: %v", err) + return fmt.Errorf("unable to update rescan: %w", err) } return nil } diff --git a/routing/router.go b/routing/router.go index 00c0ded57..4abfe54b4 100644 --- a/routing/router.go +++ b/routing/router.go @@ -1057,14 +1057,14 @@ func (r *ChannelRouter) pruneZombieChans() error { r.cfg.StrictZombiePruning, true, toPrune..., ) 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 // were a part of them. err = r.cfg.Graph.PruneGraphNodes() 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 @@ -1612,7 +1612,7 @@ func (r *ChannelRouter) processUpdate(msg interface{}, scid := lnwire.NewShortChanIDFromInt(msg.ChannelID) if r.cfg.AssumeChannelValid || r.cfg.IsAlias(scid) { 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 "+ "connects %x and %x with ChannelID(%v)", diff --git a/rpcperms/middleware_handler.go b/rpcperms/middleware_handler.go index b18fc0d16..9b1d77a54 100644 --- a/rpcperms/middleware_handler.go +++ b/rpcperms/middleware_handler.go @@ -586,11 +586,11 @@ func replaceProtoMsg(target interface{}, replacement interface{}) error { replacementBytes, err := proto.Marshal(replacementMsg) if err != nil { - return fmt.Errorf("error marshaling replacement: %v", err) + return fmt.Errorf("error marshaling replacement: %w", err) } err = proto.Unmarshal(replacementBytes, targetMsg) if err != nil { - return fmt.Errorf("error unmarshaling replacement: %v", err) + return fmt.Errorf("error unmarshaling replacement: %w", err) } return nil diff --git a/rpcserver.go b/rpcserver.go index e415606b7..fdfb8ebd6 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -1612,7 +1612,7 @@ func (r *rpcServer) VerifyMessage(ctx context.Context, // The signature should be zbase32 encoded sig, err := zbase32.DecodeString(in.Signature) 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. @@ -1636,7 +1636,7 @@ func (r *rpcServer) VerifyMessage(ctx context.Context, graph := r.server.graphDB _, active, err := graph.HasLightningNode(pub) 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{ @@ -1730,18 +1730,19 @@ func (r *rpcServer) DisconnectPeer(ctx context.Context, // public key. pubKeyBytes, err := hex.DecodeString(in.PubKey) 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) 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 // particular peer. nodeChannels, err := r.server.chanStateDB.FetchOpenChannels(peerPubKey) 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 @@ -1768,7 +1769,7 @@ func (r *rpcServer) DisconnectPeer(ctx context.Context, // server disconnects from the peer. err = r.server.DisconnectPeer(peerPubKey) 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 @@ -2458,7 +2459,7 @@ func (r *rpcServer) BatchOpenChannel(ctx context.Context, // a close height, so we'll just use the current best known height. _, bestHeight, err := r.server.cc.ChainIO.GetBestBlock() 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 @@ -2482,7 +2483,7 @@ func (r *rpcServer) BatchOpenChannel(ctx context.Context, }) rpcPoints, err := batcher.BatchFund(ctx, in) 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 @@ -2972,7 +2973,7 @@ func (r *rpcServer) GetInfo(_ context.Context, bestHash, bestHeight, err := r.server.cc.ChainIO.GetBestBlock() 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() @@ -3093,7 +3094,8 @@ func (r *rpcServer) GetRecoveryInfo(ctx context.Context, isRecoveryMode, progress, err := r.server.cc.Wallet.GetRecoveryInfo() 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", @@ -4190,7 +4192,7 @@ func (r *rpcServer) ListChannels(ctx context.Context, if len(in.Peer) > 0 && len(in.Peer) != 33 { _, 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{} @@ -5806,7 +5808,7 @@ func (r *rpcServer) ListInvoices(ctx context.Context, invoiceSlice, err := r.server.miscDB.QueryInvoices(ctx, q) 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 @@ -6929,7 +6931,7 @@ func (r *rpcServer) FeeReport(ctx context.Context, } dayFees, err := computeFeeSum(dayQuery) 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{ @@ -6939,7 +6941,7 @@ func (r *rpcServer) FeeReport(ctx context.Context, } weekFees, err := computeFeeSum(weekQuery) 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{ @@ -6949,7 +6951,7 @@ func (r *rpcServer) FeeReport(ctx context.Context, } monthFees, err := computeFeeSum(monthQuery) 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{ @@ -7273,7 +7275,7 @@ func (r *rpcServer) ExportChannelBackup(ctx context.Context, r.server.cc.KeyRing, ) 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 @@ -7400,7 +7402,7 @@ func (r *rpcServer) createBackupSnapshot(backups []chanbackup.Single) ( } err = unpackedMultiBackup.PackToWriter(&b, r.server.cc.KeyRing) 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{ @@ -7903,7 +7905,7 @@ func (r *rpcServer) FundingStateStep(ctx context.Context, bytes.NewReader(in.GetPsbtVerify().FundedPsbt), false, ) 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( @@ -8070,7 +8072,7 @@ func (r *rpcServer) RegisterRPCMiddleware( // Add the RPC middleware to the interceptor chain and defer its // removal. 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) diff --git a/server.go b/server.go index f7f78d6dd..cb1540a2c 100644 --- a/server.go +++ b/server.go @@ -830,7 +830,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, // network so we can properly sign it. nodeAnn, err := selfNode.NodeAnnouncement(false) 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 @@ -853,7 +853,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, // Finally, we'll update the representation on disk, and update our // cached in-memory version as well. 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 @@ -925,7 +925,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg, ) 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: "+ @@ -944,7 +944,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, sourceNode, err := chanGraph.SourceNode() 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{ Graph: chanGraph, @@ -981,7 +981,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, IsAlias: aliasmgr.IsAlias, }) 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) @@ -2905,7 +2905,7 @@ func (s *server) createNewHiddenService() error { } copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed()) 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 @@ -3005,7 +3005,7 @@ func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector, // don't risk overwriting any existing values. selfNode, err := s.graphDB.SourceNode() 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 @@ -3019,7 +3019,7 @@ func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector, copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed()) 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. @@ -3967,7 +3967,7 @@ func (s *server) peerInitializer(p *peer.Brontide) { srvrLog.Warnf("Starting peer=%v got error: %v", p.IdentityKey(), err) - p.Disconnect(fmt.Errorf("unable to start peer: %v", err)) + p.Disconnect(fmt.Errorf("unable to start peer: %w", err)) return } diff --git a/sweep/sweeper.go b/sweep/sweeper.go index a533f1fda..49e9e0994 100644 --- a/sweep/sweeper.go +++ b/sweep/sweeper.go @@ -360,7 +360,7 @@ func (s *UtxoSweeper) Start() error { // if we don't provide any epoch. We'll wait for that in the collector. blockEpochs, err := s.cfg.Notifier.RegisterBlockEpochNtfn(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. @@ -1157,7 +1157,7 @@ func (s *UtxoSweeper) sweep(inputs inputSet, feeRate chainfee.SatPerKWeight, if s.currentOutputScript == nil { pkScript, err := s.cfg.GenSweepScript() if err != nil { - return fmt.Errorf("gen sweep script: %v", err) + return fmt.Errorf("gen sweep script: %w", err) } s.currentOutputScript = pkScript } @@ -1168,7 +1168,7 @@ func (s *UtxoSweeper) sweep(inputs inputSet, feeRate chainfee.SatPerKWeight, feeRate, s.cfg.MaxFeeRate.FeePerKWeight(), s.cfg.Signer, ) 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 @@ -1178,7 +1178,7 @@ func (s *UtxoSweeper) sweep(inputs inputSet, feeRate chainfee.SatPerKWeight, // then and would also not add the hash to the store. err = s.cfg.Store.NotifyPublishTx(tx) 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 @@ -1268,7 +1268,7 @@ func (s *UtxoSweeper) monitorSpend(outpoint wire.OutPoint, &outpoint, script, heightHint, ) 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) diff --git a/tor/controller.go b/tor/controller.go index 340aec780..241b3ddbe 100644 --- a/tor/controller.go +++ b/tor/controller.go @@ -161,7 +161,7 @@ func (c *Controller) Start() error { conn, err := textproto.Dial("tcp", c.controlAddr) 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 @@ -507,7 +507,7 @@ func (c *Controller) authenticateViaSafeCookie(info protocolInfo) error { // the AUTHCHALLENGE command followed by a hex-encoded 32-byte nonce. clientNonce := make([]byte, nonceLen) 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) @@ -536,7 +536,7 @@ func (c *Controller) authenticateViaSafeCookie(info protocolInfo) error { } decodedServerHash, err := hex.DecodeString(serverHash) 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 { return errors.New("invalid server hash length") @@ -548,7 +548,7 @@ func (c *Controller) authenticateViaSafeCookie(info protocolInfo) error { } decodedServerNonce, err := hex.DecodeString(serverNonce) 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 { return errors.New("invalid server nonce length") diff --git a/watchtower/lookout/justice_descriptor.go b/watchtower/lookout/justice_descriptor.go index b39d5c73a..2c0623e65 100644 --- a/watchtower/lookout/justice_descriptor.go +++ b/watchtower/lookout/justice_descriptor.go @@ -196,7 +196,7 @@ func (p *JusticeDescriptor) assembleJusticeTxn(txWeight int64, if err := vm.Execute(); err != nil { log.Debugf("Failed to validate justice transaction: %s", spew.Sdump(justiceTxn)) - return nil, fmt.Errorf("error validating TX: %v", err) + return nil, fmt.Errorf("error validating TX: %w", err) } } diff --git a/watchtower/wtclient/client.go b/watchtower/wtclient/client.go index 167a98268..aef0fe505 100644 --- a/watchtower/wtclient/client.go +++ b/watchtower/wtclient/client.go @@ -982,7 +982,7 @@ func (c *client) readMessage(peer wtserver.Peer) (wtwire.Message, error) { // received in a timely manner. err := peer.SetReadDeadline(time.Now().Add(c.cfg.ReadTimeout)) if err != nil { - err = fmt.Errorf("unable to set read deadline: %v", err) + err = fmt.Errorf("unable to set read deadline: %w", err) c.log.Errorf("Unable to read msg: %v", err) return nil, err } @@ -990,7 +990,7 @@ func (c *client) readMessage(peer wtserver.Peer) (wtwire.Message, error) { // Pull the next message off the wire, rawMsg, err := peer.ReadNextMessage() if err != nil { - err = fmt.Errorf("unable to read message: %v", err) + err = fmt.Errorf("unable to read message: %w", err) c.log.Errorf("Unable to read msg: %v", err) return nil, err } @@ -1000,7 +1000,7 @@ func (c *client) readMessage(peer wtserver.Peer) (wtwire.Message, error) { msgReader := bytes.NewReader(rawMsg) msg, err := wtwire.ReadMessage(msgReader, 0) if err != nil { - err = fmt.Errorf("unable to parse message: %v", err) + err = fmt.Errorf("unable to parse message: %w", err) c.log.Errorf("Unable to read msg: %v", err) return nil, err } @@ -1019,7 +1019,7 @@ func (c *client) sendMessage(peer wtserver.Peer, var b bytes.Buffer _, err := wtwire.WriteMessage(&b, msg, 0) if err != nil { - err = fmt.Errorf("Unable to encode msg: %v", err) + err = fmt.Errorf("unable to encode msg: %w", err) c.log.Errorf("Unable to send msg: %v", err) return err } @@ -1028,7 +1028,7 @@ func (c *client) sendMessage(peer wtserver.Peer, // connection if nothing is sent in a timely manner. err = peer.SetWriteDeadline(time.Now().Add(c.cfg.WriteTimeout)) if err != nil { - err = fmt.Errorf("unable to set write deadline: %v", err) + err = fmt.Errorf("unable to set write deadline: %w", err) c.log.Errorf("Unable to send msg: %v", err) return err } diff --git a/watchtower/wtclient/session_negotiator.go b/watchtower/wtclient/session_negotiator.go index ad359233e..65d5060ae 100644 --- a/watchtower/wtclient/session_negotiator.go +++ b/watchtower/wtclient/session_negotiator.go @@ -413,13 +413,13 @@ func (n *sessionNegotiator) tryAddress(sessionKey keychain.SingleKeyECDH, // Send local Init message. err = n.cfg.SendMessage(conn, n.localInit) if err != nil { - return fmt.Errorf("unable to send Init: %v", err) + return fmt.Errorf("unable to send Init: %w", err) } // Receive remote Init message. remoteMsg, err := n.cfg.ReadMessage(conn) if err != nil { - return fmt.Errorf("unable to read Init: %v", err) + return fmt.Errorf("unable to read Init: %w", err) } // Check that returned message is wtwire.Init. @@ -446,13 +446,13 @@ func (n *sessionNegotiator) tryAddress(sessionKey keychain.SingleKeyECDH, // Send CreateSession message. err = n.cfg.SendMessage(conn, createSession) if err != nil { - return fmt.Errorf("unable to send CreateSession: %v", err) + return fmt.Errorf("unable to send CreateSession: %w", err) } // Receive CreateSessionReply message. remoteMsg, err = n.cfg.ReadMessage(conn) if err != nil { - return fmt.Errorf("unable to read CreateSessionReply: %v", err) + return fmt.Errorf("unable to read CreateSessionReply: %w", err) } // Check that returned message is wtwire.CreateSessionReply. diff --git a/watchtower/wtdb/client_db.go b/watchtower/wtdb/client_db.go index 9731dfef8..b6f6affce 100644 --- a/watchtower/wtdb/client_db.go +++ b/watchtower/wtdb/client_db.go @@ -233,7 +233,7 @@ func NewBoltBackendCreator(active bool, dbPath, db, err := kvdb.GetBoltBackend(cfg) 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 diff --git a/watchtower/wtserver/server.go b/watchtower/wtserver/server.go index 8f0e80369..a88d8db0e 100644 --- a/watchtower/wtserver/server.go +++ b/watchtower/wtserver/server.go @@ -313,7 +313,7 @@ func (s *Server) readMessage(peer Peer) (wtwire.Message, error) { // timely manner. err := peer.SetReadDeadline(time.Now().Add(s.cfg.ReadTimeout)) if err != nil { - err = fmt.Errorf("unable to set read deadline: %v", err) + err = fmt.Errorf("unable to set read deadline: %w", err) return nil, err } @@ -321,14 +321,14 @@ func (s *Server) readMessage(peer Peer) (wtwire.Message, error) { // watchtower wire specification. rawMsg, err := peer.ReadNextMessage() if err != nil { - err = fmt.Errorf("unable to read message: %v", err) + err = fmt.Errorf("unable to read message: %w", err) return nil, err } msgReader := bytes.NewReader(rawMsg) msg, err := wtwire.ReadMessage(msgReader, 0) if err != nil { - err = fmt.Errorf("unable to parse message: %v", err) + err = fmt.Errorf("unable to parse message: %w", err) return nil, err } @@ -344,13 +344,13 @@ func (s *Server) sendMessage(peer Peer, msg wtwire.Message) error { var b bytes.Buffer _, err := wtwire.WriteMessage(&b, msg, 0) if err != nil { - err = fmt.Errorf("unable to encode msg: %v", err) + err = fmt.Errorf("unable to encode msg: %w", err) return err } err = peer.SetWriteDeadline(time.Now().Add(s.cfg.WriteTimeout)) if err != nil { - err = fmt.Errorf("unable to set write deadline: %v", err) + err = fmt.Errorf("unable to set write deadline: %w", err) return err } diff --git a/zpay32/encode.go b/zpay32/encode.go index f8e1795e1..bf544d062 100644 --- a/zpay32/encode.go +++ b/zpay32/encode.go @@ -39,11 +39,11 @@ func (invoice *Invoice) Encode(signer MessageSigner) (string, error) { zeroes := make([]byte, timestampBase32Len-len(timestampBase32)) _, err := bufferBase32.Write(zeroes) if err != nil { - return "", fmt.Errorf("unable to write to buffer: %v", err) + return "", fmt.Errorf("unable to write to buffer: %w", err) } _, err = bufferBase32.Write(timestampBase32) if err != nil { - return "", fmt.Errorf("unable to write to buffer: %v", err) + return "", fmt.Errorf("unable to write to buffer: %w", err) } // We now write the tagged fields to the buffer, which will fill the @@ -332,15 +332,15 @@ func writeTaggedField(bufferBase32 *bytes.Buffer, dataType byte, data []byte) er err := bufferBase32.WriteByte(dataType) if err != nil { - return fmt.Errorf("unable to write to buffer: %v", err) + return fmt.Errorf("unable to write to buffer: %w", err) } _, err = bufferBase32.Write(lenBase32) if err != nil { - return fmt.Errorf("unable to write to buffer: %v", err) + return fmt.Errorf("unable to write to buffer: %w", err) } _, err = bufferBase32.Write(data) if err != nil { - return fmt.Errorf("unable to write to buffer: %v", err) + return fmt.Errorf("unable to write to buffer: %w", err) } return nil