diff --git a/.custom-gcl.yml b/.custom-gcl.yml new file mode 100644 index 0000000000..6ca10094a0 --- /dev/null +++ b/.custom-gcl.yml @@ -0,0 +1,4 @@ +version: v1.57.0 +plugins: + - module: 'github.com/lightningnetwork/lnd/tools/linters' + path: ./tools/linters \ No newline at end of file diff --git a/.gitignore b/.gitignore index 6be439ed7e..5ddd602d3d 100644 --- a/.gitignore +++ b/.gitignore @@ -44,6 +44,9 @@ cmd/cmd *.key *.hex +# Ignore the custom linter binary if it is built. +custom-gcl + cmd/lncli/lncli # Files from mobile build. diff --git a/.golangci.yml b/.golangci.yml index 8114945c6f..f8560a9f5e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,6 +20,18 @@ run: - integration linters-settings: + custom: + ll: + type: "module" + description: "Custom lll linter with 'S' log line exclusion." + settings: + # Max line length, lines longer will be reported. + line-length: 80 + # Tab width in spaces. + tab-width: 8 + # The regex that we will use to detect the start of an `S` log line. + log-regex: "^\\s*.*(L|l)og\\.(Info|Debug|Trace|Warn|Error|Critical)S\\(" + errorlint: # Check for incorrect fmt.Errorf error wrapping. errorf: true @@ -45,16 +57,11 @@ linters-settings: excludes: - G402 # Look for bad TLS connection settings. - G306 # Poor file permissions used when writing to a new file. + - G601 # Implicit memory aliasing in for loop. staticcheck: checks: ["-SA1019"] - lll: - # Max line length, lines longer will be reported. - line-length: 80 - # Tab width in spaces. - tab-width: 8 - funlen: # Checks the number of lines in a function. # If lower than 0, disable the check. @@ -105,6 +112,10 @@ linters-settings: linters: enable-all: true disable: + # We instead use our own custom line length linter called `ll` since + # then we can ignore log lines. + - lll + # Global variables are used in many places throughout the code base. - gochecknoglobals @@ -170,7 +181,7 @@ linters: - wrapcheck # Allow dynamic errors. - - err113 + - goerr113 # We use ErrXXX instead. - errname @@ -186,7 +197,6 @@ linters: # The linter is too aggressive and doesn't add much value since reviewers # will also catch magic numbers that make sense to extract. - gomnd - - mnd # Some of the tests cannot be parallelized. On the other hand, we don't # gain much performance with this check so we disable it for now until @@ -204,6 +214,7 @@ linters: - depguard - gosmopolitan - intrange + - goconst issues: diff --git a/Makefile b/Makefile index ccf95cb902..ee9b1de51f 100644 --- a/Makefile +++ b/Makefile @@ -319,7 +319,7 @@ check-go-version: check-go-version-dockerfile check-go-version-yaml #? lint-source: Run static code analysis lint-source: docker-tools @$(call print, "Linting source.") - $(DOCKER_TOOLS) golangci-lint run -v $(LINT_WORKERS) + $(DOCKER_TOOLS) custom-gcl run -v $(LINT_WORKERS) #? lint: Run static code analysis lint: check-go-version lint-source diff --git a/build/config.go b/build/config.go index 87b9ab9aec..74a2375663 100644 --- a/build/config.go +++ b/build/config.go @@ -23,10 +23,11 @@ const ( // LogConfig holds logging configuration options. // -//nolint:lll +//nolint:ll type LogConfig struct { - Console *consoleLoggerCfg `group:"console" namespace:"console" description:"The logger writing to stdout and stderr."` - File *FileLoggerConfig `group:"file" namespace:"file" description:"The logger writing to LND's standard log file."` + Console *consoleLoggerCfg `group:"console" namespace:"console" description:"The logger writing to stdout and stderr."` + File *FileLoggerConfig `group:"file" namespace:"file" description:"The logger writing to LND's standard log file."` + NoCommitHash bool `long:"no-commit-hash" description:"If set, the commit-hash of the current build will not be included in log lines by default."` } // Validate validates the LogConfig struct values. @@ -41,7 +42,7 @@ func (c *LogConfig) Validate() error { // LoggerConfig holds options for a particular logger. // -//nolint:lll +//nolint:ll type LoggerConfig struct { Disable bool `long:"disable" description:"Disable this logger."` NoTimestamps bool `long:"no-timestamps" description:"Omit timestamps from log lines."` @@ -89,7 +90,7 @@ func (cfg *LoggerConfig) HandlerOptions() []btclog.HandlerOption { // FileLoggerConfig extends LoggerConfig with specific log file options. // -//nolint:lll +//nolint:ll type FileLoggerConfig struct { LoggerConfig Compressor string `long:"compressor" description:"Compression algorithm to use when rotating logs." choice:"gzip" choice:"zstd"` diff --git a/build/config_dev.go b/build/config_dev.go index 09df7d6183..efa8104c91 100644 --- a/build/config_dev.go +++ b/build/config_dev.go @@ -22,7 +22,7 @@ const ( // consoleLoggerCfg extends the LoggerConfig struct by adding a Color option // which is only available for a console logger. // -//nolint:lll +//nolint:ll type consoleLoggerCfg struct { LoggerConfig Style bool `long:"style" description:"If set, the output will be styled with color and fonts"` diff --git a/build/config_prod.go b/build/config_prod.go index 67a43f8ac0..5f2ebffa48 100644 --- a/build/config_prod.go +++ b/build/config_prod.go @@ -6,7 +6,7 @@ package build // consoleLoggerCfg embeds the LoggerConfig struct along with any extensions // specific to a production deployment. // -//nolint:lll +//nolint:ll type consoleLoggerCfg struct { LoggerConfig } diff --git a/build/version.go b/build/version.go index 1238d35a2b..632ebafce4 100644 --- a/build/version.go +++ b/build/version.go @@ -6,9 +6,13 @@ package build import ( + "context" + "encoding/hex" "fmt" "runtime/debug" "strings" + + "github.com/btcsuite/btclog/v2" ) var ( @@ -101,3 +105,28 @@ func Tags() []string { return strings.Split(RawTags, ",") } + +// WithBuildInfo derives a child context with the build information attached as +// attributes. At the moment, this only includes the current build's commit +// hash. +func WithBuildInfo(ctx context.Context, cfg *LogConfig) (context.Context, + error) { + + if cfg.NoCommitHash { + return ctx, nil + } + + // Convert the commit hash to a byte slice. + commitHash, err := hex.DecodeString(CommitHash) + if err != nil { + return nil, fmt.Errorf("unable to decode commit hash: %w", err) + } + + // Include the first 3 bytes of the commit hash in the context as an + // slog attribute. + if len(commitHash) > 3 { + commitHash = commitHash[:3] + } + + return btclog.WithCtx(ctx, btclog.Hex("rev", commitHash)), nil +} diff --git a/chainntnfs/bitcoindnotify/bitcoind.go b/chainntnfs/bitcoindnotify/bitcoind.go index 91c38d8d6e..fc20fbb857 100644 --- a/chainntnfs/bitcoindnotify/bitcoind.go +++ b/chainntnfs/bitcoindnotify/bitcoind.go @@ -256,7 +256,7 @@ out: // TODO(wilmer): add retry logic if rescan fails? b.wg.Add(1) - //nolint:lll + //nolint:ll go func(msg *chainntnfs.HistoricalConfDispatch) { defer b.wg.Done() @@ -301,7 +301,7 @@ out: // TODO(wilmer): add retry logic if rescan fails? b.wg.Add(1) - //nolint:lll + //nolint:ll go func(msg *chainntnfs.HistoricalSpendDispatch) { defer b.wg.Done() diff --git a/chainntnfs/btcdnotify/btcd.go b/chainntnfs/btcdnotify/btcd.go index ff91b5aee6..c3a40a00bf 100644 --- a/chainntnfs/btcdnotify/btcd.go +++ b/chainntnfs/btcdnotify/btcd.go @@ -366,7 +366,7 @@ out: // TODO(wilmer): add retry logic if rescan fails? b.wg.Add(1) - //nolint:lll + //nolint:ll go func(msg *chainntnfs.HistoricalConfDispatch) { defer b.wg.Done() diff --git a/chainntnfs/neutrinonotify/neutrino.go b/chainntnfs/neutrinonotify/neutrino.go index 7b93bcd80d..784f55a475 100644 --- a/chainntnfs/neutrinonotify/neutrino.go +++ b/chainntnfs/neutrinonotify/neutrino.go @@ -439,7 +439,7 @@ func (n *NeutrinoNotifier) notificationDispatcher() { // potentially long rescans. n.wg.Add(1) - //nolint:lll + //nolint:ll go func(msg *chainntnfs.HistoricalConfDispatch) { defer n.wg.Done() diff --git a/chainreg/chainregistry.go b/chainreg/chainregistry.go index e30eafc677..ec17c09f13 100644 --- a/chainreg/chainregistry.go +++ b/chainreg/chainregistry.go @@ -222,7 +222,7 @@ type ChainControl struct { // the parts that can be purely constructed from the passed in global // configuration and doesn't need any wallet instance yet. // -//nolint:lll +//nolint:ll func NewPartialChainControl(cfg *Config) (*PartialChainControl, func(), error) { cc := &PartialChainControl{ Cfg: cfg, diff --git a/chanacceptor/rpcacceptor.go b/chanacceptor/rpcacceptor.go index 6ec7878954..2b30dedc0d 100644 --- a/chanacceptor/rpcacceptor.go +++ b/chanacceptor/rpcacceptor.go @@ -249,7 +249,7 @@ func (r *RPCAcceptor) sendAcceptRequests(errChan chan error, acceptRequests := make(map[[32]byte]*chanAcceptInfo) for { - //nolint:lll + //nolint:ll select { // Consume requests passed to us from our Accept() function and // send them into our stream. diff --git a/channeldb/channel.go b/channeldb/channel.go index 200dc39ff5..9ca57312aa 100644 --- a/channeldb/channel.go +++ b/channeldb/channel.go @@ -1691,7 +1691,7 @@ var ( // DeriveMusig2Shachain derives a shachain producer for the taproot channel // from normal shachain revocation root. -func DeriveMusig2Shachain(revRoot shachain.Producer) (shachain.Producer, error) { //nolint:lll +func DeriveMusig2Shachain(revRoot shachain.Producer) (shachain.Producer, error) { //nolint:ll // In order to obtain the revocation root hash to create the taproot // revocation, we'll encode the producer into a buffer, then use that // to derive the shachain root needed. diff --git a/channeldb/migration/lnwire21/onion_error.go b/channeldb/migration/lnwire21/onion_error.go index 2b03732a2f..e9d1f8f0cb 100644 --- a/channeldb/migration/lnwire21/onion_error.go +++ b/channeldb/migration/lnwire21/onion_error.go @@ -55,7 +55,7 @@ type FailCode uint16 // The currently defined onion failure types within this current version of the // Lightning protocol. // -//nolint:lll +//nolint:ll const ( CodeNone FailCode = 0 CodeInvalidRealm = FlagBadOnion | 1 diff --git a/channeldb/migration32/migration_test.go b/channeldb/migration32/migration_test.go index 703c32a72c..73c1cd4b84 100644 --- a/channeldb/migration32/migration_test.go +++ b/channeldb/migration32/migration_test.go @@ -118,7 +118,7 @@ var ( }, } - //nolint:lll + //nolint:ll resultNew1Hop1 = &mcHop{ channelID: tlv.NewPrimitiveRecord[tlv.TlvType0, uint64](100), pubKeyBytes: tlv.NewRecordT[tlv.TlvType1](testPub), @@ -128,14 +128,14 @@ var ( ), } - //nolint:lll + //nolint:ll resultNew1Hop2 = &mcHop{ channelID: tlv.NewPrimitiveRecord[tlv.TlvType0, uint64](800), pubKeyBytes: tlv.NewRecordT[tlv.TlvType1](testPub), amtToFwd: tlv.NewPrimitiveRecord[tlv.TlvType2, lnwire.MilliSatoshi](4), } - //nolint:lll + //nolint:ll resultNew1Hop3 = &mcHop{ channelID: tlv.NewPrimitiveRecord[tlv.TlvType0, uint64](800), pubKeyBytes: tlv.NewRecordT[tlv.TlvType1](testPub), @@ -145,7 +145,7 @@ var ( ), } - //nolint:lll + //nolint:ll resultNew1Hop4 = &mcHop{ channelID: tlv.NewPrimitiveRecord[tlv.TlvType0, uint64](800), pubKeyBytes: tlv.NewRecordT[tlv.TlvType1](testPub), @@ -158,7 +158,7 @@ var ( ), } - //nolint:lll + //nolint:ll resultNew2Hop1 = &mcHop{ channelID: tlv.NewPrimitiveRecord[tlv.TlvType0, uint64](800), pubKeyBytes: tlv.NewRecordT[tlv.TlvType1](testPub), @@ -171,7 +171,7 @@ var ( ), } - //nolint:lll + //nolint:ll resultNew1 = paymentResultNew{ id: 0, timeFwd: tlv.NewPrimitiveRecord[tlv.TlvType0]( @@ -200,7 +200,7 @@ var ( }), } - //nolint:lll + //nolint:ll resultNew2 = paymentResultNew{ id: 2, timeFwd: tlv.NewPrimitiveRecord[tlv.TlvType0, uint64]( diff --git a/channeldb/payment_control.go b/channeldb/payment_control.go index 6e688cf512..2369d2f7e6 100644 --- a/channeldb/payment_control.go +++ b/channeldb/payment_control.go @@ -380,7 +380,7 @@ func (p *PaymentControl) RegisterAttempt(paymentHash lntypes.Hash, if attempt.Route.FinalHop().TotalAmtMsat != h.Route.FinalHop().TotalAmtMsat { - //nolint:lll + //nolint:ll return ErrBlindedPaymentTotalAmountMismatch } diff --git a/cmd/commands/walletrpc_active.go b/cmd/commands/walletrpc_active.go index bb5982c78b..b098c40b0c 100644 --- a/cmd/commands/walletrpc_active.go +++ b/cmd/commands/walletrpc_active.go @@ -169,7 +169,7 @@ func estimateFeeRate(ctx *cli.Context) error { SatPerKw int64 `json:"sat_per_kw"` SatPerVByte int64 `json:"sat_per_vbyte"` MinRelayFeeSatPerKw int64 `json:"min_relay_fee_sat_per_kw"` - //nolint:lll + //nolint:ll MinRelayFeeSatPerVByte int64 `json:"min_relay_fee_sat_per_vbyte"` }{ SatPerKw: int64(rateKW), diff --git a/config.go b/config.go index 04a4917658..f206b43a50 100644 --- a/config.go +++ b/config.go @@ -290,7 +290,7 @@ var ( // See LoadConfig for further details regarding the configuration // loading+parsing process. // -//nolint:lll +//nolint:ll type Config struct { ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"` @@ -523,7 +523,7 @@ type Config struct { // for more details. Any value of 0 means we use the gRPC internal default // values. // -//nolint:lll +//nolint:ll type GRPCConfig struct { // ServerPingTime is a duration for the amount of time of no activity // after which the server pings the client to see if the transport is @@ -549,7 +549,7 @@ type GRPCConfig struct { // DefaultConfig returns all default values for the Config struct. // -//nolint:lll +//nolint:ll func DefaultConfig() Config { return Config{ LndDir: DefaultLndDir, diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 89c596f7ae..d59829b5e5 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -1372,7 +1372,7 @@ func newRetributionInfo(chanPoint *wire.OutPoint, // For taproot outputs, we also need to hold onto the second // level tap tweak as well. - //nolint:lll + //nolint:ll htlcOutput.secondLevelTapTweak = breachedHtlc.SecondLevelTapTweak breachedOutputs = append(breachedOutputs, htlcOutput) @@ -1729,7 +1729,7 @@ func taprootBriefcaseFromRetInfo(retInfo *retributionInfo) *taprootBriefcase { // For spending from our commitment output on the remote // commitment, we'll need to stash the control block. case input.TaprootRemoteCommitSpend: - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.CommitSweepCtrlBlock = bo.signDesc.ControlBlock bo.resolutionBlob.WhenSome(func(blob tlv.Blob) { @@ -1743,7 +1743,7 @@ func taprootBriefcaseFromRetInfo(retInfo *retributionInfo) *taprootBriefcase { // To spend the revoked output again, we'll store the same // control block value as above, but in a different place. case input.TaprootCommitmentRevoke: - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.RevokeSweepCtrlBlock = bo.signDesc.ControlBlock bo.resolutionBlob.WhenSome(func(blob tlv.Blob) { @@ -1765,10 +1765,10 @@ func taprootBriefcaseFromRetInfo(retInfo *retributionInfo) *taprootBriefcase { copy(firstLevelTweak[:], bo.signDesc.TapTweak) secondLevelTweak := bo.secondLevelTapTweak - //nolint:lll + //nolint:ll tapCase.TapTweaks.Val.BreachedHtlcTweaks[resID] = firstLevelTweak - //nolint:lll + //nolint:ll tapCase.TapTweaks.Val.BreachedSecondLevelHltcTweaks[resID] = secondLevelTweak } } @@ -1788,7 +1788,7 @@ func applyTaprootRetInfo(tapCase *taprootBriefcase, // For spending from our commitment output on the remote // commitment, we'll apply the control block. case input.TaprootRemoteCommitSpend: - //nolint:lll + //nolint:ll bo.signDesc.ControlBlock = tapCase.CtrlBlocks.Val.CommitSweepCtrlBlock tapCase.SettledCommitBlob.WhenSomeV( @@ -1800,7 +1800,7 @@ func applyTaprootRetInfo(tapCase *taprootBriefcase, // To spend the revoked output again, we'll apply the same // control block value as above, but to a different place. case input.TaprootCommitmentRevoke: - //nolint:lll + //nolint:ll bo.signDesc.ControlBlock = tapCase.CtrlBlocks.Val.RevokeSweepCtrlBlock tapCase.BreachedCommitBlob.WhenSomeV( @@ -1816,7 +1816,7 @@ func applyTaprootRetInfo(tapCase *taprootBriefcase, case input.TaprootHtlcOfferedRevoke: resID := newResolverID(bo.OutPoint()) - //nolint:lll + //nolint:ll tap1, ok := tapCase.TapTweaks.Val.BreachedHtlcTweaks[resID] if !ok { return fmt.Errorf("unable to find taproot "+ @@ -1824,7 +1824,7 @@ func applyTaprootRetInfo(tapCase *taprootBriefcase, } bo.signDesc.TapTweak = tap1[:] - //nolint:lll + //nolint:ll tap2, ok := tapCase.TapTweaks.Val.BreachedSecondLevelHltcTweaks[resID] if !ok { return fmt.Errorf("unable to find taproot "+ diff --git a/contractcourt/briefcase.go b/contractcourt/briefcase.go index cd4fd90ccb..a0908ea3fa 100644 --- a/contractcourt/briefcase.go +++ b/contractcourt/briefcase.go @@ -1561,7 +1561,7 @@ func encodeTaprootAuxData(w io.Writer, c *ContractResolutions) error { if c.CommitResolution != nil { commitResolution := c.CommitResolution commitSignDesc := commitResolution.SelfOutputSignDesc - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.CommitSweepCtrlBlock = commitSignDesc.ControlBlock c.CommitResolution.ResolutionBlob.WhenSome(func(b []byte) { @@ -1587,21 +1587,21 @@ func encodeTaprootAuxData(w io.Writer, c *ContractResolutions) error { resID = newResolverID( htlc.SignedSuccessTx.TxIn[0].PreviousOutPoint, ) - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.SecondLevelCtrlBlocks[resID] = ctrlBlock // For HTLCs we need to go to the second level for, we // also need to store the control block needed to // publish the second level transaction. if htlc.SignDetails != nil { - //nolint:lll + //nolint:ll bridgeCtrlBlock := htlc.SignDetails.SignDesc.ControlBlock - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.IncomingHtlcCtrlBlocks[resID] = bridgeCtrlBlock } } else { resID = newResolverID(htlc.ClaimOutpoint) - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.IncomingHtlcCtrlBlocks[resID] = ctrlBlock } @@ -1624,23 +1624,23 @@ func encodeTaprootAuxData(w io.Writer, c *ContractResolutions) error { resID = newResolverID( htlc.SignedTimeoutTx.TxIn[0].PreviousOutPoint, ) - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.SecondLevelCtrlBlocks[resID] = ctrlBlock // For HTLCs we need to go to the second level for, we // also need to store the control block needed to // publish the second level transaction. // - //nolint:lll + //nolint:ll if htlc.SignDetails != nil { - //nolint:lll + //nolint:ll bridgeCtrlBlock := htlc.SignDetails.SignDesc.ControlBlock - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.OutgoingHtlcCtrlBlocks[resID] = bridgeCtrlBlock } } else { resID = newResolverID(htlc.ClaimOutpoint) - //nolint:lll + //nolint:ll tapCase.CtrlBlocks.Val.OutgoingHtlcCtrlBlocks[resID] = ctrlBlock } @@ -1689,11 +1689,11 @@ func decodeTapRootAuxData(r io.Reader, c *ContractResolutions) error { htlc.SignedSuccessTx.TxIn[0].PreviousOutPoint, ) - //nolint:lll + //nolint:ll ctrlBlock := tapCase.CtrlBlocks.Val.SecondLevelCtrlBlocks[resID] htlc.SweepSignDesc.ControlBlock = ctrlBlock - //nolint:lll + //nolint:ll if htlc.SignDetails != nil { bridgeCtrlBlock := tapCase.CtrlBlocks.Val.IncomingHtlcCtrlBlocks[resID] htlc.SignDetails.SignDesc.ControlBlock = bridgeCtrlBlock @@ -1701,7 +1701,7 @@ func decodeTapRootAuxData(r io.Reader, c *ContractResolutions) error { } else { resID = newResolverID(htlc.ClaimOutpoint) - //nolint:lll + //nolint:ll ctrlBlock := tapCase.CtrlBlocks.Val.IncomingHtlcCtrlBlocks[resID] htlc.SweepSignDesc.ControlBlock = ctrlBlock } @@ -1722,11 +1722,11 @@ func decodeTapRootAuxData(r io.Reader, c *ContractResolutions) error { htlc.SignedTimeoutTx.TxIn[0].PreviousOutPoint, ) - //nolint:lll + //nolint:ll ctrlBlock := tapCase.CtrlBlocks.Val.SecondLevelCtrlBlocks[resID] htlc.SweepSignDesc.ControlBlock = ctrlBlock - //nolint:lll + //nolint:ll if htlc.SignDetails != nil { bridgeCtrlBlock := tapCase.CtrlBlocks.Val.OutgoingHtlcCtrlBlocks[resID] htlc.SignDetails.SignDesc.ControlBlock = bridgeCtrlBlock @@ -1734,7 +1734,7 @@ func decodeTapRootAuxData(r io.Reader, c *ContractResolutions) error { } else { resID = newResolverID(htlc.ClaimOutpoint) - //nolint:lll + //nolint:ll ctrlBlock := tapCase.CtrlBlocks.Val.OutgoingHtlcCtrlBlocks[resID] htlc.SweepSignDesc.ControlBlock = ctrlBlock } diff --git a/contractcourt/chain_arbitrator.go b/contractcourt/chain_arbitrator.go index 78a79a3c2f..6d9b30d208 100644 --- a/contractcourt/chain_arbitrator.go +++ b/contractcourt/chain_arbitrator.go @@ -639,7 +639,7 @@ func (c *ChainArbitrator) Start() error { // corresponding more restricted resolver, as we don't have to watch // the chain any longer, only resolve the contracts on the confirmed // commitment. - //nolint:lll + //nolint:ll for _, closeChanInfo := range closingChannels { // We can leave off the CloseContract and ForceCloseChan // methods as the channel is already closed at this point. diff --git a/contractcourt/chain_watcher.go b/contractcourt/chain_watcher.go index 808f41f2ee..e79c8d546b 100644 --- a/contractcourt/chain_watcher.go +++ b/contractcourt/chain_watcher.go @@ -431,7 +431,7 @@ func (c *chainWatcher) handleUnknownLocalState( auxResult, err := fn.MapOptionZ( c.cfg.auxLeafStore, - //nolint:lll + //nolint:ll func(s lnwallet.AuxLeafStore) fn.Result[lnwallet.CommitDiffAuxResult] { return s.FetchLeavesFromCommit( lnwallet.NewAuxChanState(c.cfg.chanState), diff --git a/contractcourt/channel_arbitrator.go b/contractcourt/channel_arbitrator.go index 3a7c2cfe93..319b437e4e 100644 --- a/contractcourt/channel_arbitrator.go +++ b/contractcourt/channel_arbitrator.go @@ -593,11 +593,11 @@ func maybeAugmentTaprootResolvers(chanType channeldb.ChannelType, switch r := resolver.(type) { case *commitSweepResolver: if contractResolutions.CommitResolution != nil { - //nolint:lll + //nolint:ll r.commitResolution = *contractResolutions.CommitResolution } case *htlcOutgoingContestResolver: - //nolint:lll + //nolint:ll htlcResolutions := contractResolutions.HtlcResolutions.OutgoingHTLCs for _, htlcRes := range htlcResolutions { htlcRes := htlcRes @@ -610,7 +610,7 @@ func maybeAugmentTaprootResolvers(chanType channeldb.ChannelType, } case *htlcTimeoutResolver: - //nolint:lll + //nolint:ll htlcResolutions := contractResolutions.HtlcResolutions.OutgoingHTLCs for _, htlcRes := range htlcResolutions { htlcRes := htlcRes @@ -623,7 +623,7 @@ func maybeAugmentTaprootResolvers(chanType channeldb.ChannelType, } case *htlcIncomingContestResolver: - //nolint:lll + //nolint:ll htlcResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs for _, htlcRes := range htlcResolutions { htlcRes := htlcRes @@ -635,7 +635,7 @@ func maybeAugmentTaprootResolvers(chanType channeldb.ChannelType, } } case *htlcSuccessResolver: - //nolint:lll + //nolint:ll htlcResolutions := contractResolutions.HtlcResolutions.IncomingHTLCs for _, htlcRes := range htlcResolutions { htlcRes := htlcRes diff --git a/contractcourt/channel_arbitrator_test.go b/contractcourt/channel_arbitrator_test.go index 3b367bf548..92ad608eb9 100644 --- a/contractcourt/channel_arbitrator_test.go +++ b/contractcourt/channel_arbitrator_test.go @@ -694,7 +694,7 @@ func TestChannelArbitratorLocalForceClose(t *testing.T) { // Now notify about the local force close getting confirmed. // - //nolint:lll + //nolint:ll chanArb.cfg.ChainEvents.LocalUnilateralClosure <- &LocalUnilateralCloseInfo{ SpendDetail: &chainntnfs.SpendDetail{}, LocalForceCloseSummary: &lnwallet.LocalForceCloseSummary{ @@ -991,7 +991,7 @@ func TestChannelArbitratorLocalForceClosePendingHtlc(t *testing.T) { }, } - //nolint:lll + //nolint:ll chanArb.cfg.ChainEvents.LocalUnilateralClosure <- &LocalUnilateralCloseInfo{ SpendDetail: &chainntnfs.SpendDetail{}, LocalForceCloseSummary: &lnwallet.LocalForceCloseSummary{ @@ -1620,7 +1620,7 @@ func TestChannelArbitratorCommitFailure(t *testing.T) { }, { closeType: channeldb.LocalForceClose, - //nolint:lll + //nolint:ll sendEvent: func(chanArb *ChannelArbitrator) { chanArb.cfg.ChainEvents.LocalUnilateralClosure <- &LocalUnilateralCloseInfo{ SpendDetail: &chainntnfs.SpendDetail{}, @@ -1957,7 +1957,7 @@ func TestChannelArbitratorDanglingCommitForceClose(t *testing.T) { // resolutions sent since we have none on our // commitment transaction. // - //nolint:lll + //nolint:ll uniCloseInfo := &LocalUnilateralCloseInfo{ SpendDetail: &chainntnfs.SpendDetail{}, LocalForceCloseSummary: &lnwallet.LocalForceCloseSummary{ @@ -2884,7 +2884,7 @@ func TestChannelArbitratorAnchors(t *testing.T) { }, } - //nolint:lll + //nolint:ll chanArb.cfg.ChainEvents.LocalUnilateralClosure <- &LocalUnilateralCloseInfo{ SpendDetail: &chainntnfs.SpendDetail{}, LocalForceCloseSummary: &lnwallet.LocalForceCloseSummary{ diff --git a/contractcourt/config.go b/contractcourt/config.go index b5466c6e21..7331ceb91f 100644 --- a/contractcourt/config.go +++ b/contractcourt/config.go @@ -28,7 +28,7 @@ const ( // BudgetConfig is a struct that holds the configuration when offering outputs // to the sweeper. // -//nolint:lll +//nolint:ll type BudgetConfig struct { ToLocal btcutil.Amount `long:"tolocal" description:"The amount in satoshis to allocate as the budget to pay fees when sweeping the to_local output. If set, the budget calculated using the ratio (if set) will be capped at this value."` ToLocalRatio float64 `long:"tolocalratio" description:"The ratio of the value in to_local output to allocate as the budget to pay fees when sweeping it."` diff --git a/contractcourt/htlc_incoming_contest_resolver.go b/contractcourt/htlc_incoming_contest_resolver.go index e7e21fff68..73841eb88c 100644 --- a/contractcourt/htlc_incoming_contest_resolver.go +++ b/contractcourt/htlc_incoming_contest_resolver.go @@ -220,7 +220,7 @@ func (h *htlcIncomingContestResolver) Resolve( // // So we'll insert it at the 3rd index of the witness. case isTaproot: - //nolint:lll + //nolint:ll h.htlcResolution.SignedSuccessTx.TxIn[0].Witness[2] = preimage[:] // Within the witness for the success transaction, the diff --git a/contractcourt/htlc_success_resolver.go b/contractcourt/htlc_success_resolver.go index 159b642dde..b2716ad305 100644 --- a/contractcourt/htlc_success_resolver.go +++ b/contractcourt/htlc_success_resolver.go @@ -242,7 +242,7 @@ func (h *htlcSuccessResolver) broadcastReSignedSuccessTx(immediate bool) ( if !h.outputIncubating { var secondLevelInput input.HtlcSecondLevelAnchorInput if isTaproot { - //nolint:lll + //nolint:ll secondLevelInput = input.MakeHtlcSecondLevelSuccessTaprootInput( h.htlcResolution.SignedSuccessTx, h.htlcResolution.SignDetails, h.htlcResolution.Preimage, @@ -252,7 +252,7 @@ func (h *htlcSuccessResolver) broadcastReSignedSuccessTx(immediate bool) ( ), ) } else { - //nolint:lll + //nolint:ll secondLevelInput = input.MakeHtlcSecondLevelSuccessAnchorInput( h.htlcResolution.SignedSuccessTx, h.htlcResolution.SignDetails, h.htlcResolution.Preimage, diff --git a/contractcourt/htlc_timeout_resolver.go b/contractcourt/htlc_timeout_resolver.go index e7ab421691..9954c3c0db 100644 --- a/contractcourt/htlc_timeout_resolver.go +++ b/contractcourt/htlc_timeout_resolver.go @@ -178,7 +178,7 @@ func (h *htlcTimeoutResolver) claimCleanUp( // - // case h.isTaproot() && h.htlcResolution.SignedTimeoutTx == nil: - //nolint:lll + //nolint:ll preimageBytes = spendingInput.Witness[taprootRemotePreimageIndex] // The witness stack when the remote party sweeps the output on a @@ -269,7 +269,7 @@ func (h *htlcTimeoutResolver) chainDetailsToWatch() (*wire.OutPoint, []byte, err // witness script (the last element of the witness stack) to // re-construct the pkScript we need to watch. // - //nolint:lll + //nolint:ll outPointToWatch := h.htlcResolution.SignedTimeoutTx.TxIn[0].PreviousOutPoint witness := h.htlcResolution.SignedTimeoutTx.TxIn[0].Witness @@ -825,7 +825,7 @@ func (h *htlcTimeoutResolver) handleCommitSpend( var csvWitnessType input.StandardWitnessType if h.isTaproot() { - //nolint:lll + //nolint:ll csvWitnessType = input.TaprootHtlcOfferedTimeoutSecondLevel } else { csvWitnessType = input.HtlcOfferedTimeoutSecondLevel diff --git a/contractcourt/htlc_timeout_resolver_test.go b/contractcourt/htlc_timeout_resolver_test.go index 92cc587fc1..f3f23c385c 100644 --- a/contractcourt/htlc_timeout_resolver_test.go +++ b/contractcourt/htlc_timeout_resolver_test.go @@ -290,7 +290,7 @@ func testHtlcTimeoutResolver(t *testing.T, testCase htlcTimeoutTestCase) { resolutionChan := make(chan ResolutionMsg, 1) reportChan := make(chan *channeldb.ResolverReport) - //nolint:lll + //nolint:ll chainCfg := ChannelArbitratorConfig{ ChainArbitratorConfig: ChainArbitratorConfig{ Notifier: notifier, @@ -371,10 +371,10 @@ func testHtlcTimeoutResolver(t *testing.T, testCase htlcTimeoutTestCase) { if testCase.timeout { timeoutTxID := timeoutTx.TxHash() report := &channeldb.ResolverReport{ - OutPoint: timeoutTx.TxIn[0].PreviousOutPoint, //nolint:lll + OutPoint: timeoutTx.TxIn[0].PreviousOutPoint, //nolint:ll Amount: testHtlcAmt.ToSatoshis(), - ResolverType: channeldb.ResolverTypeOutgoingHtlc, //nolint:lll - ResolverOutcome: channeldb.ResolverOutcomeFirstStage, //nolint:lll + ResolverType: channeldb.ResolverTypeOutgoingHtlc, //nolint:ll + ResolverOutcome: channeldb.ResolverOutcomeFirstStage, //nolint:ll SpendTxID: &timeoutTxID, } diff --git a/contractcourt/utxonursery.go b/contractcourt/utxonursery.go index afd6c18c99..aef906a0ad 100644 --- a/contractcourt/utxonursery.go +++ b/contractcourt/utxonursery.go @@ -555,7 +555,7 @@ func (u *UtxoNursery) NurseryReport( // confirmation of the commitment transaction. switch kid.WitnessType() { - //nolint:lll + //nolint:ll case input.TaprootHtlcAcceptedSuccessSecondLevel: fallthrough case input.HtlcAcceptedSuccessSecondLevel: @@ -590,7 +590,7 @@ func (u *UtxoNursery) NurseryReport( // it. report.AddLimboDirectHtlc(&kid) - //nolint:lll + //nolint:ll case input.TaprootHtlcAcceptedSuccessSecondLevel: fallthrough case input.TaprootHtlcOfferedTimeoutSecondLevel: @@ -611,7 +611,7 @@ func (u *UtxoNursery) NurseryReport( // balance. switch kid.WitnessType() { - //nolint:lll + //nolint:ll case input.TaprootHtlcAcceptedSuccessSecondLevel: fallthrough case input.TaprootHtlcOfferedTimeoutSecondLevel: diff --git a/discovery/gossiper_test.go b/discovery/gossiper_test.go index 056069940a..85a4e0657e 100644 --- a/discovery/gossiper_test.go +++ b/discovery/gossiper_test.go @@ -1461,7 +1461,7 @@ func TestSignatureAnnouncementRetryAtStartup(t *testing.T) { return lnwire.ShortChannelID{}, fmt.Errorf("no peer alias") } - //nolint:lll + //nolint:ll gossiper := New(Config{ Notifier: ctx.gossiper.cfg.Notifier, Broadcast: ctx.gossiper.cfg.Broadcast, diff --git a/docs/code_formatting_rules.md b/docs/code_formatting_rules.md index 731bb64069..ad58745d73 100644 --- a/docs/code_formatting_rules.md +++ b/docs/code_formatting_rules.md @@ -178,6 +178,95 @@ be used for calls to formatting functions like `fmt.Errorf`, But not for statements that are important for the flow or logic of the code, like `require.NoErrorf()`. +#### Exceptions and additional styling for structured logging + +When making use of structured logging calls (there are any `btclog.Logger` +methods ending in `S`), a few different rules and exceptions apply. + +1) **Static messages:** Structured log calls take a `context.Context` as a first +parameter and a _static_ string as the second parameter (the `msg` parameter). +Formatted strings should ideally not be used for the construction of the `msg` +parameter. Instead, key-value pairs (or `slog` attributes) should be used to +provide additional variables to the log line. + +**WRONG** +```go +log.DebugS(ctx, fmt.Sprintf("User %d just spent %.8f to open a channel", userID, 0.0154)) +``` + +**RIGHT** +```go +log.InfoS(ctx, "Channel open performed", + slog.Int("user_id", userID), + btclog.Fmt("amount", "%.8f", 0.00154)) +``` + +2) **Key-value attributes**: The third parameter in any structured log method is +a variadic list of the `any` type but it is required that these are provided in +key-value pairs such that an associated `slog.Attr` variable can be created for +each key-value pair. The simplest way to specify this is to directly pass in the +key-value pairs as raw literals as follows: + +```go +log.InfoS(ctx, "Channel open performed", "user_id", userID, "amount", 0.00154) +``` +This does work, but it becomes easy to make a mistake and accidentally leave out +a value for each key provided leading to a nonsensical log line. To avoid this, +it is suggested to make use of the various `slog.Attr` helper functions as +follows: + +```go +log.InfoS(ctx, "Channel open performed", + slog.Int("user_id", userID), + btclog.Fmt("amount", "%.8f", 0.00154)) +``` + +3) **Line wrapping**: Structured log lines are an exception to the 80-character +line wrapping rule. This is so that the key-value pairs can be easily read and +reasoned about. If it is the case that there is only a single key-value pair +and the entire log line is still less than 80 characters, it is acceptable to +have the key-value pair on the same line as the log message. However, if there +are multiple key-value pairs, it is suggested to use the one line per key-value +pair format. Due to this suggestion, it is acceptable for any single key-value +pair line to exceed 80 characters for the sake of readability. + +**WRONG** +```go +// Example 1. +log.InfoS(ctx, "User connected", + "user_id", userID) + +// Example 2. +log.InfoS(ctx, "Channel open performed", "user_id", userID, + btclog.Fmt("amount", "%.8f", 0.00154), "channel_id", channelID) + +// Example 3. +log.InfoS(ctx, "Bytes received", + "user_id", userID, + btclog.Hex("peer_id", peerID.SerializeCompressed()), + btclog.Hex("message", []bytes{ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + }))) +``` + +**RIGHT** +```go +// Example 1. +log.InfoS(ctx, "User connected", "user_id", userID) + +// Example 2. +log.InfoS(ctx, "Channel open performed", + slog.Int("user_id", userID), + btclog.Fmt("amount", "%.8f", 0.00154), + slog.String("channel_id", channelID)) + +// Example 3. +log.InfoS(ctx, "Bytes received", + "user_id", userID, + btclog.Hex("peer_id", peerID.SerializeCompressed()), + btclog.Hex("message", []bytes{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}))) +``` + ### Wrapping long function definitions If one is forced to wrap lines of function arguments that exceed the diff --git a/docs/release-notes/release-notes-0.19.0.md b/docs/release-notes/release-notes-0.19.0.md index 377255bbf9..f3685519ed 100644 --- a/docs/release-notes/release-notes-0.19.0.md +++ b/docs/release-notes/release-notes-0.19.0.md @@ -160,7 +160,13 @@ a log line. The options for this include "off" (default), "short" (source file name and line number) and "long" (full path to source file and line number). Finally, the new `--logging.console.style` option can be used under the `dev` - build tag to add styling to console logging. + build tag to add styling to console logging. + +* [Start adding a commit hash fingerprint to log lines by + default](https://github.com/lightningnetwork/lnd/pull/9314). This can be + disabled with the new `--logging.no-commit-hash"` option. Note that this extra + info will currently only appear in a few log lines, but more will be added in + future as the structured logging change is propagated throughout LND. * [Add max files and max file size](https://github.com/lightningnetwork/lnd/pull/9233) options to the `logging` config namespace under new `--logging.file.max-files` diff --git a/funding/batch.go b/funding/batch.go index fc050cdf53..d95941e847 100644 --- a/funding/batch.go +++ b/funding/batch.go @@ -230,7 +230,7 @@ func (b *Batcher) BatchFund(ctx context.Context, err) } - //nolint:lll + //nolint:ll fundingReq, err := b.cfg.RequestParser(&lnrpc.OpenChannelRequest{ SatPerVbyte: uint64(req.SatPerVbyte), TargetConf: req.TargetConf, diff --git a/funding/commitment_type_negotiation_test.go b/funding/commitment_type_negotiation_test.go index b47e4a1f2f..b9e9f59f0f 100644 --- a/funding/commitment_type_negotiation_test.go +++ b/funding/commitment_type_negotiation_test.go @@ -39,7 +39,7 @@ func TestCommitmentTypeNegotiation(t *testing.T) { lnwire.StaticRemoteKeyOptional, lnwire.AnchorsZeroFeeHtlcTxOptional, ), - //nolint:lll + //nolint:ll expectsCommitType: lnwallet.CommitmentTypeAnchorsZeroFeeHtlcTx, expectsChanType: nil, expectsErr: nil, diff --git a/funding/manager.go b/funding/manager.go index 075be12788..c8a54d9588 100644 --- a/funding/manager.go +++ b/funding/manager.go @@ -4028,7 +4028,7 @@ func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen channelReadyMsg.AliasScid = &alias if firstVerNonce != nil { - channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:lll + channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:ll firstVerNonce.PubNonce, ) } diff --git a/graph/builder.go b/graph/builder.go index 8c2ba2e3b8..c0133e02ec 100644 --- a/graph/builder.go +++ b/graph/builder.go @@ -428,7 +428,7 @@ func (b *Builder) syncGraphWithChain() error { // pruning the channel graph with each new block that hasn't yet been // consumed by the channel graph. var spentOutputs []*wire.OutPoint - for nextHeight := pruneHeight + 1; nextHeight <= uint32(bestHeight); nextHeight++ { //nolint:lll + for nextHeight := pruneHeight + 1; nextHeight <= uint32(bestHeight); nextHeight++ { //nolint:ll // Break out of the rescan early if a shutdown has been // requested, otherwise long rescans will block the daemon from // shutting down promptly. @@ -1236,7 +1236,7 @@ func (b *Builder) processUpdate(msg interface{}, b.cfg.Chain, &channelID, b.quit, ) if err != nil { - //nolint:lll + //nolint:ll // // In order to ensure we don't erroneously mark a // channel as a zombie due to an RPC failure, we'll diff --git a/graph/db/graph.go b/graph/db/graph.go index fc1b26ad0f..a6b23e64b3 100644 --- a/graph/db/graph.go +++ b/graph/db/graph.go @@ -1658,7 +1658,7 @@ func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) ( var keys [][]byte cursor := edgeIndex.ReadWriteCursor() - //nolint:lll + //nolint:ll for k, v := cursor.Seek(chanIDStart[:]); k != nil && bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() { edgeInfoReader := bytes.NewReader(v) @@ -1705,7 +1705,7 @@ func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) ( // the keys in a second loop. var pruneKeys [][]byte pruneCursor := pruneBucket.ReadWriteCursor() - //nolint:lll + //nolint:ll for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil && bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() { pruneKeys = append(pruneKeys, k) @@ -2004,7 +2004,7 @@ func (c *ChannelGraph) ChanUpdatesInHorizon(startTime, // the index collecting the info and policy of each update of // each channel that has a last update within the time range. // - //nolint:lll + //nolint:ll for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil && bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() { @@ -2139,7 +2139,7 @@ func (c *ChannelGraph) NodeUpdatesInHorizon(startTime, // the index collecting info for each node within the time // range. // - //nolint:lll + //nolint:ll for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil && bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() { @@ -2377,7 +2377,7 @@ func (c *ChannelGraph) FilterChannelRange(startHeight, // We'll now iterate through the database, and find each // channel ID that resides within the specified range. // - //nolint:lll + //nolint:ll for k, v := cursor.Seek(chanIDStart[:]); k != nil && bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() { // Don't send alias SCIDs during gossip sync. @@ -3163,7 +3163,7 @@ func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend, // as its prefix. This indicates that we've stepped over into // another node's edges, so we can terminate our scan. edgeCursor := edges.ReadCursor() - for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:lll + for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll // If the prefix still matches, the channel id is // returned in nodeEdge. Channel id is used to lookup // the node at the other end of the channel and both diff --git a/graph/db/graph_test.go b/graph/db/graph_test.go index 82c4965fba..8a02f24ff4 100644 --- a/graph/db/graph_test.go +++ b/graph/db/graph_test.go @@ -1124,7 +1124,7 @@ func TestGraphTraversalCacheable(t *testing.T) { tx, func(tx kvdb.RTx, info *models.ChannelEdgeInfo, policy *models.ChannelEdgePolicy, - policy2 *models.ChannelEdgePolicy) error { //nolint:lll + policy2 *models.ChannelEdgePolicy) error { //nolint:ll delete(chanIndex, info.ChannelID) return nil @@ -2584,7 +2584,7 @@ func TestFilterChannelRange(t *testing.T) { ) require.NoError(t, err) - expRes := channelRanges[test.expStartIndex:test.expEndIndex] //nolint:lll + expRes := channelRanges[test.expStartIndex:test.expEndIndex] //nolint:ll if len(expRes) == 0 { require.Nil(t, resp) @@ -2598,7 +2598,7 @@ func TestFilterChannelRange(t *testing.T) { ) require.NoError(t, err) - expRes = channelRangesWithTimestamps[test.expStartIndex:test.expEndIndex] //nolint:lll + expRes = channelRangesWithTimestamps[test.expStartIndex:test.expEndIndex] //nolint:ll if len(expRes) == 0 { require.Nil(t, resp) @@ -3898,7 +3898,7 @@ func BenchmarkForEachChannel(b *testing.B) { cb := func(tx kvdb.RTx, info *models.ChannelEdgeInfo, policy *models.ChannelEdgePolicy, - policy2 *models.ChannelEdgePolicy) error { //nolint:lll + policy2 *models.ChannelEdgePolicy) error { //nolint:ll // We need to do something with // the data here, otherwise the diff --git a/htlcswitch/hop/iterator.go b/htlcswitch/hop/iterator.go index 83b5e3f52a..2cf2adb543 100644 --- a/htlcswitch/hop/iterator.go +++ b/htlcswitch/hop/iterator.go @@ -377,7 +377,7 @@ func peelBlindedPathDummyHop(r *sphinxHopIterator, cltvExpiryDelta uint32, r.router, onionPkt, sphinxPacket, BlindingKit{ Processor: r.router, UpdateAddBlinding: tlv.SomeRecordT( - tlv.NewPrimitiveRecord[lnwire.BlindingPointTlvType]( //nolint:lll + tlv.NewPrimitiveRecord[lnwire.BlindingPointTlvType]( //nolint:ll nextEph.Val, ), ), @@ -606,7 +606,7 @@ func (b *BlindingKit) getBlindingPoint(payloadBlinding *btcec.PublicKey) ( // // ceil(a/b) = (a + b - 1)/(b). // -//nolint:lll,dupword +//nolint:ll,dupword func calculateForwardingAmount(incomingAmount, baseFee lnwire.MilliSatoshi, proportionalFee uint32) (lnwire.MilliSatoshi, error) { diff --git a/htlcswitch/hop/iterator_test.go b/htlcswitch/hop/iterator_test.go index fff9ae17d2..ab435a9868 100644 --- a/htlcswitch/hop/iterator_test.go +++ b/htlcswitch/hop/iterator_test.go @@ -281,7 +281,7 @@ func TestParseAndValidateRecipientData(t *testing.T) { if testCase.updateAddBlinding != nil { kit.UpdateAddBlinding = tlv.SomeRecordT( - //nolint:lll + //nolint:ll tlv.NewPrimitiveRecord[lnwire.BlindingPointTlvType](testCase.updateAddBlinding), ) } diff --git a/htlcswitch/hop/payload_test.go b/htlcswitch/hop/payload_test.go index 7398813a3e..bd0081cb93 100644 --- a/htlcswitch/hop/payload_test.go +++ b/htlcswitch/hop/payload_test.go @@ -15,7 +15,7 @@ import ( ) var ( - //nolint:lll + //nolint:ll testPrivKeyBytes, _ = hex.DecodeString("e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734") _, testPubKey = btcec.PrivKeyFromBytes(testPrivKeyBytes) ) diff --git a/htlcswitch/link.go b/htlcswitch/link.go index b8f1ce8edd..60062862ef 100644 --- a/htlcswitch/link.go +++ b/htlcswitch/link.go @@ -942,7 +942,7 @@ func (l *channelLink) syncChanStates() error { // very same nonce that we sent above, as they should // take the latest verification nonce we send. if chanState.ChanType.IsTaproot() { - //nolint:lll + //nolint:ll channelReadyMsg.NextLocalNonce = localChanSyncMsg.LocalNonce } @@ -3724,7 +3724,7 @@ func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) { // parse the payload we have no way of knowing whether // we were the introduction node or not. // - //nolint:lll + //nolint:ll obfuscator, failCode := chanIterator.ExtractErrorEncrypter( l.cfg.ExtractErrorEncrypter, // We need our route role here because we @@ -3885,7 +3885,7 @@ func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) { inboundFee := l.cfg.FwrdingPolicy.InboundFee - //nolint:lll + //nolint:ll updatePacket := &htlcPacket{ incomingChanID: l.ShortChanID(), incomingHTLCID: add.ID, @@ -3936,7 +3936,7 @@ func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) { l.log.Errorf("unable to encode the "+ "remaining route %v", err) - cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:lll + cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll return lnwire.NewTemporaryChannelFailure(upd) } @@ -3962,7 +3962,7 @@ func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) { if fwdPkg.State == channeldb.FwdStateLockedIn { inboundFee := l.cfg.FwrdingPolicy.InboundFee - //nolint:lll + //nolint:ll updatePacket := &htlcPacket{ incomingChanID: l.ShortChanID(), incomingHTLCID: add.ID, diff --git a/htlcswitch/link_test.go b/htlcswitch/link_test.go index 4ee538a581..80632b07e9 100644 --- a/htlcswitch/link_test.go +++ b/htlcswitch/link_test.go @@ -4889,7 +4889,7 @@ func (h *persistentLinkHarness) restartLink( // the firing via force feeding. bticker := ticker.NewForce(time.Hour) - //nolint:lll + //nolint:ll aliceCfg := ChannelLinkConfig{ FwrdingPolicy: globalPolicy, Peer: alicePeer, diff --git a/htlcswitch/test_utils.go b/htlcswitch/test_utils.go index 0f4b28fb82..2123465884 100644 --- a/htlcswitch/test_utils.go +++ b/htlcswitch/test_utils.go @@ -1137,7 +1137,7 @@ func (h *hopNetwork) createChannelLink(server, peer *mockServer, return server.htlcSwitch.ForwardPackets(linkQuit, packets...) } - //nolint:lll + //nolint:ll link := NewChannelLink( ChannelLinkConfig{ BestHeight: server.htlcSwitch.BestHeight, diff --git a/input/size.go b/input/size.go index 5d4b15ec16..f1c56ff826 100644 --- a/input/size.go +++ b/input/size.go @@ -699,14 +699,14 @@ const ( // - number_of_witness_elements: 1 byte // - sig_len: 1 byte // - sweep_sig: 65 bytes (worst case w/o sighash default) - //nolint:lll + //nolint:ll TaprootSecondLevelRevokeWitnessSize = TaprootKeyPathCustomSighashWitnessSize // TaprootAcceptedRevokeWitnessSize: // - number_of_witness_elements: 1 byte // - sig_len: 1 byte // - sweep_sig: 65 bytes (worst case w/o sighash default) - //nolint:lll + //nolint:ll TaprootAcceptedRevokeWitnessSize = TaprootKeyPathCustomSighashWitnessSize // TaprootOfferedRevokeWitnessSize: diff --git a/input/size_test.go b/input/size_test.go index 33f9ff5397..2fba2c7b2e 100644 --- a/input/size_test.go +++ b/input/size_test.go @@ -861,11 +861,11 @@ var witnessSizeTests = []witnessSizeTest{ KeyDesc: keychain.KeyDescriptor{ PubKey: testKey.PubKey(), }, - //nolint:lll + //nolint:ll WitnessScript: commitScriptTree.SettleLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } witness, err := input.TaprootCommitSpendSuccess( @@ -895,11 +895,11 @@ var witnessSizeTests = []witnessSizeTest{ KeyDesc: keychain.KeyDescriptor{ PubKey: testKey.PubKey(), }, - //nolint:lll + //nolint:ll WitnessScript: commitScriptTree.RevocationLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } witness, err := input.TaprootCommitSpendRevoke( @@ -919,7 +919,7 @@ var witnessSizeTests = []witnessSizeTest{ require.NoError(t, err) signer := &dummySigner{} - //nolint:lll + //nolint:ll commitScriptTree, err := input.NewRemoteCommitScriptTree( testKey.PubKey(), input.NoneTapLeaf(), ) @@ -929,11 +929,11 @@ var witnessSizeTests = []witnessSizeTest{ KeyDesc: keychain.KeyDescriptor{ PubKey: testKey.PubKey(), }, - //nolint:lll + //nolint:ll WitnessScript: commitScriptTree.SettleLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } witness, err := input.TaprootCommitRemoteSpend( @@ -1174,7 +1174,7 @@ var witnessSizeTests = []witnessSizeTest{ WitnessScript: timeoutLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } witness, err := input.ReceiverHTLCScriptTaprootTimeout( @@ -1222,7 +1222,7 @@ var witnessSizeTests = []witnessSizeTest{ WitnessScript: timeoutLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } receiverSig, err := signer.SignOutputRaw( testTx, receiverDesc, @@ -1236,7 +1236,7 @@ var witnessSizeTests = []witnessSizeTest{ WitnessScript: timeoutLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } witness, err := input.SenderHTLCScriptTaprootTimeout( @@ -1283,7 +1283,7 @@ var witnessSizeTests = []witnessSizeTest{ WitnessScript: successLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } witness, err := input.SenderHTLCScriptTaprootRedeem( @@ -1329,7 +1329,7 @@ var witnessSizeTests = []witnessSizeTest{ WitnessScript: successsLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } senderSig, err := signer.SignOutputRaw( testTx, senderDesc, @@ -1343,7 +1343,7 @@ var witnessSizeTests = []witnessSizeTest{ WitnessScript: successsLeaf.Script, HashType: txscript.SigHashAll, InputIndex: 0, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll } witness, err := input.ReceiverHTLCScriptTaprootRedeem( diff --git a/invoices/invoiceregistry.go b/invoices/invoiceregistry.go index 9d54b6ad8d..f5a6c6a95f 100644 --- a/invoices/invoiceregistry.go +++ b/invoices/invoiceregistry.go @@ -1841,7 +1841,7 @@ func (i *InvoiceRegistry) HodlUnsubscribeAll(subscriber chan<- interface{}) { // copySingleClients copies i.SingleInvoiceSubscription inside a lock. This is // useful when we need to iterate the map to send notifications. -func (i *InvoiceRegistry) copySingleClients() map[uint32]*SingleInvoiceSubscription { //nolint:lll +func (i *InvoiceRegistry) copySingleClients() map[uint32]*SingleInvoiceSubscription { //nolint:ll i.notificationClientMux.RLock() defer i.notificationClientMux.RUnlock() diff --git a/invoices/sql_store.go b/invoices/sql_store.go index e848297d9c..59321e0395 100644 --- a/invoices/sql_store.go +++ b/invoices/sql_store.go @@ -1054,7 +1054,7 @@ func (s *sqlInvoiceUpdater) AddHtlc(circuitKey models.CircuitKey, ) if err != nil { mappedSQLErr := sqldb.MapSQLError(err) - var uniqueConstraintErr *sqldb.ErrSQLUniqueConstraintViolation //nolint:lll + var uniqueConstraintErr *sqldb.ErrSQLUniqueConstraintViolation //nolint:ll if errors.As(mappedSQLErr, &uniqueConstraintErr) { return ErrDuplicateSetID{ SetID: setID, diff --git a/itest/lnd_channel_backup_test.go b/itest/lnd_channel_backup_test.go index 5ae0df9584..5140de5056 100644 --- a/itest/lnd_channel_backup_test.go +++ b/itest/lnd_channel_backup_test.go @@ -382,7 +382,7 @@ func testChannelBackupRestoreBasic(ht *lntest.HarnessTest) { // create a new nodeRestorer that will restore // using the on-disk channel.backup. // - //nolint:lll + //nolint:ll backup := &lnrpc.RestoreChanBackupRequest_MultiChanBackup{ MultiChanBackup: multi, } diff --git a/itest/lnd_channel_force_close_test.go b/itest/lnd_channel_force_close_test.go index 6d02804012..81bdfad431 100644 --- a/itest/lnd_channel_force_close_test.go +++ b/itest/lnd_channel_force_close_test.go @@ -609,7 +609,7 @@ func channelForceClosureTest(ht *lntest.HarnessTest, // We expect alice to have a timeout tx resolution with // an amount equal to the payment amount. - //nolint:lll + //nolint:ll aliceReports[outpoint.String()] = &lnrpc.Resolution{ ResolutionType: lnrpc.ResolutionType_OUTGOING_HTLC, Outcome: lnrpc.ResolutionOutcome_FIRST_STAGE, @@ -622,7 +622,7 @@ func channelForceClosureTest(ht *lntest.HarnessTest, // incoming htlc timeout which reflects the full amount // of the htlc. It has no spend tx, because carol stops // monitoring the htlc once it has timed out. - //nolint:lll + //nolint:ll carolReports[outpoint.String()] = &lnrpc.Resolution{ ResolutionType: lnrpc.ResolutionType_INCOMING_HTLC, Outcome: lnrpc.ResolutionOutcome_TIMEOUT, diff --git a/itest/lnd_estimate_route_fee_test.go b/itest/lnd_estimate_route_fee_test.go index 8ed0be2725..ffff5accaa 100644 --- a/itest/lnd_estimate_route_fee_test.go +++ b/itest/lnd_estimate_route_fee_test.go @@ -19,7 +19,7 @@ var ( probeAmt = int64(probeAmount) * 1_000 failureReasonNone = lnrpc.PaymentFailureReason_FAILURE_REASON_NONE - failureReasonNoRoute = lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE //nolint:lll + failureReasonNoRoute = lnrpc.PaymentFailureReason_FAILURE_REASON_NO_ROUTE //nolint:ll ) const ( diff --git a/itest/lnd_funding_test.go b/itest/lnd_funding_test.go index 7daf95960d..54180abf57 100644 --- a/itest/lnd_funding_test.go +++ b/itest/lnd_funding_test.go @@ -144,7 +144,7 @@ func testBasicChannelFunding(ht *lntest.HarnessTest) { chansCommitType == lnrpc.CommitmentType_ANCHORS: case expType == lnrpc.CommitmentType_STATIC_REMOTE_KEY && - chansCommitType == lnrpc.CommitmentType_STATIC_REMOTE_KEY: //nolint:lll + chansCommitType == lnrpc.CommitmentType_STATIC_REMOTE_KEY: //nolint:ll case expType == lnrpc.CommitmentType_LEGACY && chansCommitType == lnrpc.CommitmentType_LEGACY: diff --git a/itest/lnd_hold_persistence_test.go b/itest/lnd_hold_persistence_test.go index f1c2a7d823..8bb84b2a30 100644 --- a/itest/lnd_hold_persistence_test.go +++ b/itest/lnd_hold_persistence_test.go @@ -21,7 +21,7 @@ func testHoldInvoicePersistence(ht *lntest.HarnessTest) { const ( chanAmt = btcutil.Amount(1000000) numPayments = 10 - reason = lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS //nolint:lll + reason = lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS //nolint:ll ) // Create carol, and clean up when the test finishes. diff --git a/itest/lnd_max_htlcs_test.go b/itest/lnd_max_htlcs_test.go index 971537adf4..ea023190f5 100644 --- a/itest/lnd_max_htlcs_test.go +++ b/itest/lnd_max_htlcs_test.go @@ -114,7 +114,7 @@ func (h *holdSubscription) cancel(ht *lntest.HarnessTest) { ) require.Equal(ht, lnrpc.Payment_FAILED, payUpdate.Status, "expected payment failed") - require.Equal(ht, lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, //nolint:lll + require.Equal(ht, lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, //nolint:ll payUpdate.FailureReason, "expected unknown details") } diff --git a/itest/lnd_multi-hop-error-propagation_test.go b/itest/lnd_multi-hop-error-propagation_test.go index 6fe34fdcfc..853dd4a978 100644 --- a/itest/lnd_multi-hop-error-propagation_test.go +++ b/itest/lnd_multi-hop-error-propagation_test.go @@ -138,7 +138,7 @@ func testHtlcErrorPropagation(ht *lntest.HarnessTest) { } ht.SendPaymentAssertFail( alice, sendReq, - lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, //nolint:lll + lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, //nolint:ll ) ht.AssertLastHTLCError( alice, lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS, @@ -207,7 +207,7 @@ func testHtlcErrorPropagation(ht *lntest.HarnessTest) { } ht.SendPaymentAssertFail( alice, sendReq, - lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, //nolint:lll + lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS, //nolint:ll ) ht.AssertLastHTLCError( alice, lnrpc.Failure_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS, diff --git a/itest/lnd_sweep_test.go b/itest/lnd_sweep_test.go index 17e0910b63..099014aff0 100644 --- a/itest/lnd_sweep_test.go +++ b/itest/lnd_sweep_test.go @@ -1137,7 +1137,7 @@ func testSweepHTLCs(ht *lntest.HarnessTest) { return incoming, outgoing } - //nolint:lll + //nolint:ll // For neutrino backend, we need to give it more time to sync the // blocks. There's a potential bug we need to fix: // 2024-04-18 23:36:07.046 [ERR] NTFN: unable to get missed blocks: starting height 487 is greater than ending height 486 diff --git a/kvdb/etcd/config.go b/kvdb/etcd/config.go index e8cbaf98c5..0136ab98fd 100644 --- a/kvdb/etcd/config.go +++ b/kvdb/etcd/config.go @@ -4,7 +4,7 @@ import "fmt" // Config holds etcd configuration alongside with configuration related to our higher level interface. // -//nolint:lll +//nolint:ll type Config struct { Embedded bool `long:"embedded" description:"Use embedded etcd instance instead of the external one. Note: use for testing only."` diff --git a/kvdb/postgres/config.go b/kvdb/postgres/config.go index 0c2959d16a..b587d13390 100644 --- a/kvdb/postgres/config.go +++ b/kvdb/postgres/config.go @@ -4,7 +4,7 @@ import "time" // Config holds postgres configuration data. // -//nolint:lll +//nolint:ll type Config struct { Dsn string `long:"dsn" description:"Database connection string."` Timeout time.Duration `long:"timeout" description:"Database connection timeout. Set to zero to disable."` diff --git a/kvdb/sqlite/config.go b/kvdb/sqlite/config.go index f60abcfc00..b79bc36e63 100644 --- a/kvdb/sqlite/config.go +++ b/kvdb/sqlite/config.go @@ -4,7 +4,7 @@ import "time" // Config holds sqlite configuration data. // -//nolint:lll +//nolint:ll type Config struct { Timeout time.Duration `long:"timeout" description:"The time after which a database query should be timed out."` BusyTimeout time.Duration `long:"busytimeout" description:"The maximum amount of time to wait for a database connection to become available for a query."` diff --git a/lncfg/autopilot.go b/lncfg/autopilot.go index 60728fb26a..3736048b67 100644 --- a/lncfg/autopilot.go +++ b/lncfg/autopilot.go @@ -2,7 +2,7 @@ package lncfg // AutoPilot holds the configuration options for the daemon's autopilot. // -//nolint:lll +//nolint:ll type AutoPilot struct { Active bool `long:"active" description:"If the autopilot agent should be active or not."` Heuristic map[string]float64 `long:"heuristic" description:"Heuristic to activate, and the weight to give it during scoring."` diff --git a/lncfg/bitcoind.go b/lncfg/bitcoind.go index b574aef169..bbf95b1915 100644 --- a/lncfg/bitcoind.go +++ b/lncfg/bitcoind.go @@ -11,7 +11,7 @@ const ( // Bitcoind holds the configuration options for the daemon's connection to // bitcoind. // -//nolint:lll +//nolint:ll type Bitcoind struct { Dir string `long:"dir" description:"The base directory that contains the node's data, logs, configuration file, etc."` ConfigPath string `long:"config" description:"Configuration filepath. If not set, will default to the default filename under 'dir'."` diff --git a/lncfg/btcd.go b/lncfg/btcd.go index dece35bf04..3609bd995a 100644 --- a/lncfg/btcd.go +++ b/lncfg/btcd.go @@ -2,7 +2,7 @@ package lncfg // Btcd holds the configuration options for the daemon's connection to btcd. // -//nolint:lll +//nolint:ll type Btcd struct { Dir string `long:"dir" description:"The base directory that contains the node's data, logs, configuration file, etc."` RPCHost string `long:"rpchost" description:"The daemon's rpc listening address. If a port is omitted, then the default port for the selected chain parameters will be used."` diff --git a/lncfg/caches.go b/lncfg/caches.go index 5f257d8a1f..2457bb1d04 100644 --- a/lncfg/caches.go +++ b/lncfg/caches.go @@ -21,7 +21,7 @@ const ( // Caches holds the configuration for various caches within lnd. // -//nolint:lll +//nolint:ll type Caches struct { // RejectCacheSize is the maximum number of entries stored in lnd's // reject cache, which is used for efficiently rejecting gossip updates. diff --git a/lncfg/chain.go b/lncfg/chain.go index e84cadb7b8..36586ff3a6 100644 --- a/lncfg/chain.go +++ b/lncfg/chain.go @@ -8,7 +8,7 @@ import ( // Chain holds the configuration options for the daemon's chain settings. // -//nolint:lll +//nolint:ll type Chain struct { Active bool `long:"active" description:"DEPRECATED: If the chain should be active or not. This field is now ignored since only the Bitcoin chain is supported" hidden:"true"` ChainDir string `long:"chaindir" description:"The directory to store the chain's data within."` diff --git a/lncfg/db.go b/lncfg/db.go index 1f7e0ae35d..3d45bb78b1 100644 --- a/lncfg/db.go +++ b/lncfg/db.go @@ -71,7 +71,7 @@ const ( // DB holds database configuration for LND. // -//nolint:lll +//nolint:ll type DB struct { Backend string `long:"backend" description:"The selected database backend."` diff --git a/lncfg/dev_integration.go b/lncfg/dev_integration.go index 0f0227e01f..bbbc080372 100644 --- a/lncfg/dev_integration.go +++ b/lncfg/dev_integration.go @@ -19,7 +19,7 @@ func IsDevBuild() bool { // DevConfig specifies configs used for integration tests. These configs can // only be used in tests and must NOT be exported for production usage. // -//nolint:lll +//nolint:ll type DevConfig struct { ProcessChannelReadyWait time.Duration `long:"processchannelreadywait" description:"Time to sleep before processing remote node's channel_ready message."` ReservationTimeout time.Duration `long:"reservationtimeout" description:"The maximum time we keep a pending channel open flow in memory."` diff --git a/lncfg/fee.go b/lncfg/fee.go index 200ae9e819..c96e58022e 100644 --- a/lncfg/fee.go +++ b/lncfg/fee.go @@ -12,7 +12,7 @@ const DefaultMaxUpdateTimeout = 20 * time.Minute // Fee holds the configuration options for fee estimation. // -//nolint:lll +//nolint:ll type Fee struct { URL string `long:"url" description:"Optional URL for external fee estimation. If no URL is specified, the method for fee estimation will depend on the chosen backend and network. Must be set for neutrino on mainnet."` MinUpdateTimeout time.Duration `long:"min-update-timeout" description:"The minimum interval in which fees will be updated from the specified fee URL."` diff --git a/lncfg/gossip.go b/lncfg/gossip.go index a2c82a7aa8..fbe5aae402 100644 --- a/lncfg/gossip.go +++ b/lncfg/gossip.go @@ -7,7 +7,7 @@ import ( "github.com/lightningnetwork/lnd/routing/route" ) -//nolint:lll +//nolint:ll type Gossip struct { PinnedSyncersRaw []string `long:"pinned-syncers" description:"A set of peers that should always remain in an active sync state, which can be used to closely synchronize the routing tables of two nodes. The value should be a hex-encoded pubkey, the flag can be specified multiple times to add multiple peers. Connected peers matching this pubkey will remain active for the duration of the connection and not count towards the NumActiveSyncer count."` diff --git a/lncfg/healthcheck.go b/lncfg/healthcheck.go index 9a14036879..7904eaceaa 100644 --- a/lncfg/healthcheck.go +++ b/lncfg/healthcheck.go @@ -23,7 +23,7 @@ var ( // HealthCheckConfig contains the configuration for the different health checks // the lnd runs. // -//nolint:lll +//nolint:ll type HealthCheckConfig struct { ChainCheck *CheckConfig `group:"chainbackend" namespace:"chainbackend"` diff --git a/lncfg/htlcswitch.go b/lncfg/htlcswitch.go index 4b553e3547..613b189915 100644 --- a/lncfg/htlcswitch.go +++ b/lncfg/htlcswitch.go @@ -13,7 +13,7 @@ var ( MaxMailboxDeliveryTimeout = 2 * time.Minute ) -//nolint:lll +//nolint:ll type Htlcswitch struct { MailboxDeliveryTimeout time.Duration `long:"mailboxdeliverytimeout" description:"The timeout value when delivering HTLCs to a channel link. Setting this value too small will result in local payment failures if large number of payments are sent over a short period."` } diff --git a/lncfg/invoices.go b/lncfg/invoices.go index 7922885240..9d54c69941 100644 --- a/lncfg/invoices.go +++ b/lncfg/invoices.go @@ -36,7 +36,7 @@ const ( // Invoices holds the configuration options for invoices. // -//nolint:lll +//nolint:ll type Invoices struct { HoldExpiryDelta uint32 `long:"holdexpirydelta" description:"The number of blocks before a hold invoice's htlc expires that the invoice should be canceled to prevent a force close. Force closes will not be prevented if this value is not greater than DefaultIncomingBroadcastDelta."` } diff --git a/lncfg/monitoring_on.go b/lncfg/monitoring_on.go index 12c59e2b21..f76342baf6 100644 --- a/lncfg/monitoring_on.go +++ b/lncfg/monitoring_on.go @@ -6,7 +6,7 @@ package lncfg // Prometheus is the set of configuration data that specifies the listening // address of the Prometheus exporter. // -//nolint:lll +//nolint:ll type Prometheus struct { // Listen is the listening address that we should use to allow the main // Prometheus server to scrape our metrics. diff --git a/lncfg/neutrino.go b/lncfg/neutrino.go index e46c292dc0..d0f508ecf5 100644 --- a/lncfg/neutrino.go +++ b/lncfg/neutrino.go @@ -5,7 +5,7 @@ import "time" // Neutrino holds the configuration options for the daemon's connection to // neutrino. // -//nolint:lll +//nolint:ll type Neutrino struct { AddPeers []string `short:"a" long:"addpeer" description:"Add a peer to connect with at startup"` ConnectPeers []string `long:"connect" description:"Connect only to the specified peers at startup"` diff --git a/lncfg/pprof.go b/lncfg/pprof.go index e136b2a8eb..edb754b1c7 100644 --- a/lncfg/pprof.go +++ b/lncfg/pprof.go @@ -7,7 +7,7 @@ import ( // Pprof holds the configuration options for LND's built-in pprof server. // -//nolint:lll +//nolint:ll type Pprof struct { CPUProfile string `long:"cpuprofile" description:"Write CPU profile to the specified file"` diff --git a/lncfg/protocol.go b/lncfg/protocol.go index 5852d032e0..ed8d4578ae 100644 --- a/lncfg/protocol.go +++ b/lncfg/protocol.go @@ -11,7 +11,7 @@ import ( // compatibility of protocol additions, while defaulting to the latest within // lnd, or to enable experimental protocol changes. // -//nolint:lll +//nolint:ll type ProtocolOptions struct { // LegacyProtocol is a sub-config that houses all the legacy protocol // options. These are mostly used for integration tests as most modern diff --git a/lncfg/protocol_integration.go b/lncfg/protocol_integration.go index e9f32d9dfb..a062c66976 100644 --- a/lncfg/protocol_integration.go +++ b/lncfg/protocol_integration.go @@ -13,7 +13,7 @@ import ( // // TODO(yy): delete this build flag to unify with `lncfg/protocol.go`. // -//nolint:lll +//nolint:ll type ProtocolOptions struct { // LegacyProtocol is a sub-config that houses all the legacy protocol // options. These are mostly used for integration tests as most modern diff --git a/lncfg/protocol_legacy_on.go b/lncfg/protocol_legacy_on.go index a575fb7f38..9b8fd4ebdf 100644 --- a/lncfg/protocol_legacy_on.go +++ b/lncfg/protocol_legacy_on.go @@ -7,7 +7,7 @@ package lncfg // are mostly used for integration tests as most modern nodes should always run // with them on by default. // -//nolint:lll +//nolint:ll type LegacyProtocol struct { // LegacyOnionFormat if set to true, then we won't signal // TLVOnionPayloadOptional. As a result, nodes that include us in the diff --git a/lncfg/remotesigner.go b/lncfg/remotesigner.go index 24ca61cfbd..02479a85e8 100644 --- a/lncfg/remotesigner.go +++ b/lncfg/remotesigner.go @@ -13,7 +13,7 @@ const ( // RemoteSigner holds the configuration options for a remote RPC signer. // -//nolint:lll +//nolint:ll type RemoteSigner struct { Enable bool `long:"enable" description:"Use a remote signer for signing any on-chain related transactions or messages. Only recommended if local wallet is initialized as watch-only. Remote signer must use the same seed/root key as the local watch-only wallet but must have private keys."` RPCHost string `long:"rpchost" description:"The remote signer's RPC host:port"` diff --git a/lncfg/routing.go b/lncfg/routing.go index f8c38d147a..2b21683f64 100644 --- a/lncfg/routing.go +++ b/lncfg/routing.go @@ -4,7 +4,7 @@ import "fmt" // Routing holds the configuration options for routing. // -//nolint:lll +//nolint:ll type Routing struct { AssumeChannelValid bool `long:"assumechanvalid" description:"DEPRECATED: Skip checking channel spentness during graph validation. This speedup comes at the risk of using an unvalidated view of the network for routing. (default: false)" hidden:"true"` @@ -15,7 +15,7 @@ type Routing struct { // BlindedPaths holds the configuration options for blinded path construction. // -//nolint:lll +//nolint:ll type BlindedPaths struct { MinNumRealHops uint8 `long:"min-num-real-hops" description:"The minimum number of real hops to include in a blinded path. This doesn't include our node, so if the minimum is 1, then the path will contain at minimum our node along with an introduction node hop. If it is zero then the shortest path will use our node as an introduction node."` NumHops uint8 `long:"num-hops" description:"The number of hops to include in a blinded path. This doesn't include our node, so if it is 1, then the path will contain our node along with an introduction node or dummy node hop. If paths shorter than NumHops is found, then they will be padded using dummy hops."` diff --git a/lncfg/rpcmiddleware.go b/lncfg/rpcmiddleware.go index 173785e01a..e957f207d6 100644 --- a/lncfg/rpcmiddleware.go +++ b/lncfg/rpcmiddleware.go @@ -16,7 +16,7 @@ const ( // RPCMiddleware holds the configuration for RPC interception middleware. // -//nolint:lll +//nolint:ll type RPCMiddleware struct { Enable bool `long:"enable" description:"Enable the RPC middleware interceptor functionality."` InterceptTimeout time.Duration `long:"intercepttimeout" description:"Time after which a RPC middleware intercept request will time out and return an error if it hasn't yet received a response."` diff --git a/lncfg/sweeper.go b/lncfg/sweeper.go index 037102c69b..6b8339312e 100644 --- a/lncfg/sweeper.go +++ b/lncfg/sweeper.go @@ -19,7 +19,7 @@ const ( MaxAllowedFeeRate = 10_000 ) -//nolint:lll +//nolint:ll type Sweeper struct { BatchWindowDuration time.Duration `long:"batchwindowduration" description:"Duration of the sweep batch window. The sweep is held back during the batch window to allow more inputs to be added and thereby lower the fee per input." hidden:"true"` MaxFeeRate chainfee.SatPerVByte `long:"maxfeerate" description:"Maximum fee rate in sat/vb that the sweeper is allowed to use when sweeping funds, the fee rate derived from budgets are capped at this value. Setting this value too low can result in transactions not being confirmed in time, causing HTLCs to expire hence potentially losing funds."` diff --git a/lncfg/tor.go b/lncfg/tor.go index 4f043128a6..f41d7b09cd 100644 --- a/lncfg/tor.go +++ b/lncfg/tor.go @@ -2,7 +2,7 @@ package lncfg // Tor holds the configuration options for the daemon's connection to tor. // -//nolint:lll +//nolint:ll type Tor struct { Active bool `long:"active" description:"Allow outbound and inbound connections to be routed through Tor"` SOCKS string `long:"socks" description:"The host:port that Tor's exposed SOCKS5 proxy is listening on"` diff --git a/lncfg/watchtower.go b/lncfg/watchtower.go index 851d24e928..463a95b956 100644 --- a/lncfg/watchtower.go +++ b/lncfg/watchtower.go @@ -5,7 +5,7 @@ import "github.com/lightningnetwork/lnd/watchtower" // Watchtower holds the daemon specific configuration parameters for running a // watchtower that shares resources with the daemon. // -//nolint:lll +//nolint:ll type Watchtower struct { Active bool `long:"active" description:"If the watchtower should be active or not"` diff --git a/lncfg/workers.go b/lncfg/workers.go index 30961f063d..3735cd30f8 100644 --- a/lncfg/workers.go +++ b/lncfg/workers.go @@ -19,7 +19,7 @@ const ( // Workers exposes CLI configuration for turning resources consumed by worker // pools. // -//nolint:lll +//nolint:ll type Workers struct { // Read is the maximum number of concurrent read pool workers. Read int `long:"read" description:"Maximum number of concurrent read pool workers. This number should be proportional to the number of peers."` diff --git a/lncfg/wtclient.go b/lncfg/wtclient.go index d4e2c6b27e..fd97146a63 100644 --- a/lncfg/wtclient.go +++ b/lncfg/wtclient.go @@ -9,7 +9,7 @@ import ( // WtClient holds the configuration options for the daemon's watchtower client. // -//nolint:lll +//nolint:ll type WtClient struct { // Active determines whether a watchtower client should be created to // back up channel states with registered watchtowers. diff --git a/lnd.go b/lnd.go index f511811950..2b46e83c93 100644 --- a/lnd.go +++ b/lnd.go @@ -8,6 +8,7 @@ import ( "context" "errors" "fmt" + "log/slog" "net" "net/http" "net/http/pprof" @@ -148,23 +149,45 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, interceptor signal.Interceptor) error { defer func() { - ltndLog.Info("Shutdown complete\n") + ltndLog.Info("Shutdown complete") err := cfg.LogRotator.Close() if err != nil { ltndLog.Errorf("Could not close log rotator: %v", err) } }() - mkErr := func(format string, args ...interface{}) error { - ltndLog.Errorf("Shutting down because error in main "+ - "method: "+format, args...) - return fmt.Errorf(format, args...) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + ctx, err := build.WithBuildInfo(ctx, cfg.LogConfig) + if err != nil { + return fmt.Errorf("unable to add build info to context: %w", + err) + } + + mkErr := func(msg string, err error, attrs ...any) error { + ltndLog.ErrorS(ctx, "Shutting down due to error in main "+ + "method", err, attrs...) + + var ( + params = []any{err} + fmtStr = msg + ": %w" + ) + for _, attr := range attrs { + fmtStr += " %s" + + params = append(params, attr) + } + + return fmt.Errorf(fmtStr, params...) } // Show version at startup. - ltndLog.Infof("Version: %s commit=%s, build=%s, logging=%s, "+ - "debuglevel=%s", build.Version(), build.Commit, - build.Deployment, build.LoggingType, cfg.DebugLevel) + ltndLog.InfoS(ctx, "Version Info", + slog.String("version", build.Version()), + slog.String("commit", build.Commit), + slog.Any("debuglevel", build.Deployment), + slog.String("logging", cfg.DebugLevel)) var network string switch { @@ -184,13 +207,9 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, network = "signet" } - ltndLog.Infof("Active chain: %v (network=%v)", - strings.Title(BitcoinChainName), network, - ) - - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() + ltndLog.InfoS(ctx, "Network Info", + "active_chain", strings.Title(BitcoinChainName), + "network", network) // Enable http profiling server if requested. if cfg.Pprof.Profile != "" { @@ -216,7 +235,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, "/debug/pprof/", http.StatusSeeOther, )) - ltndLog.Infof("Pprof listening on %v", cfg.Pprof.Profile) + ltndLog.InfoS(ctx, "Pprof listening", "addr", cfg.Pprof.Profile) // Create the pprof server. pprofServer := &http.Server{ @@ -227,11 +246,10 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, // Shut the server down when lnd is shutting down. defer func() { - ltndLog.Info("Stopping pprof server...") + ltndLog.InfoS(ctx, "Stopping pprof server...") err := pprofServer.Shutdown(ctx) if err != nil { - ltndLog.Errorf("Stop pprof server got err: %v", - err) + ltndLog.ErrorS(ctx, "Stop pprof server", err) } }() @@ -239,7 +257,8 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, go func() { err := pprofServer.ListenAndServe() if err != nil && !errors.Is(err, http.ErrServerClosed) { - ltndLog.Errorf("Serving pprof got err: %v", err) + ltndLog.ErrorS(ctx, "Could not serve pprof "+ + "server", err) } }() } @@ -248,7 +267,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, if cfg.Pprof.CPUProfile != "" { f, err := os.Create(cfg.Pprof.CPUProfile) if err != nil { - return mkErr("unable to create CPU profile: %v", err) + return mkErr("unable to create CPU profile", err) } _ = runtimePprof.StartCPUProfile(f) defer func() { @@ -261,7 +280,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, // needs to be done early and once during the startup process, before // any DB access. if err := cfg.DB.Init(ctx, cfg.graphDatabaseDir()); err != nil { - return mkErr("error initializing DBs: %v", err) + return mkErr("error initializing DBs", err) } tlsManagerCfg := &TLSManagerCfg{ @@ -286,7 +305,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, serverOpts, restDialOpts, restListen, cleanUp, err := tlsManager.SetCertificateBeforeUnlock() if err != nil { - return mkErr("error setting cert before unlock: %v", err) + return mkErr("error setting cert before unlock", err) } if cleanUp != nil { defer cleanUp() @@ -303,8 +322,12 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, // connections. lis, err := lncfg.ListenOnAddress(grpcEndpoint) if err != nil { - return mkErr("unable to listen on %s: %v", - grpcEndpoint, err) + return mkErr("unable to listen on grpc "+ + "endpoint", err, + slog.String( + "endpoint", + grpcEndpoint.String(), + )) } defer lis.Close() @@ -323,7 +346,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, rpcsLog, cfg.NoMacaroons, cfg.RPCMiddleware.Mandatory, ) if err := interceptorChain.Start(); err != nil { - return mkErr("error starting interceptor chain: %v", err) + return mkErr("error starting interceptor chain", err) } defer func() { err := interceptorChain.Stop() @@ -364,14 +387,14 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, rpcServer := newRPCServer(cfg, interceptorChain, implCfg, interceptor) err = rpcServer.RegisterWithGrpcServer(grpcServer) if err != nil { - return mkErr("error registering gRPC server: %v", err) + return mkErr("error registering gRPC server", err) } // Now that both the WalletUnlocker and LightningService have been // registered with the GRPC server, we can start listening. err = startGrpcListen(cfg, grpcServer, grpcListeners) if err != nil { - return mkErr("error starting gRPC listener: %v", err) + return mkErr("error starting gRPC listener", err) } // Now start the REST proxy for our gRPC server above. We'll ensure @@ -379,10 +402,10 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, // wildcard to prevent certificate issues when accessing the proxy // externally. stopProxy, err := startRestProxy( - cfg, rpcServer, restDialOpts, restListen, + ctx, cfg, rpcServer, restDialOpts, restListen, ) if err != nil { - return mkErr("error starting REST proxy: %v", err) + return mkErr("error starting REST proxy", err) } defer stopProxy() @@ -399,8 +422,8 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, cancelElection() }() - ltndLog.Infof("Using %v leader elector", - cfg.Cluster.LeaderElector) + ltndLog.InfoS(ctx, "Using leader elector", + "elector", cfg.Cluster.LeaderElector) leaderElector, err = cfg.Cluster.MakeLeaderElector( electionCtx, cfg.DB, @@ -414,8 +437,8 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, return } - ltndLog.Infof("Attempting to resign from leader role "+ - "(%v)", cfg.Cluster.ID) + ltndLog.InfoS(ctx, "Attempting to resign from "+ + "leader role", "cluster_id", cfg.Cluster.ID) // Ensure that we don't block the shutdown process if // the leader resigning process takes too long. The @@ -433,24 +456,26 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, } }() - ltndLog.Infof("Starting leadership campaign (%v)", - cfg.Cluster.ID) + ltndLog.InfoS(ctx, "Starting leadership campaign", + "cluster_id", cfg.Cluster.ID) if err := leaderElector.Campaign(electionCtx); err != nil { - return mkErr("leadership campaign failed: %v", err) + return mkErr("leadership campaign failed", err) } elected = true - ltndLog.Infof("Elected as leader (%v)", cfg.Cluster.ID) + ltndLog.InfoS(ctx, "Elected as leader", + "cluster_id", cfg.Cluster.ID) } dbs, cleanUp, err := implCfg.DatabaseBuilder.BuildDatabase(ctx) switch { - case err == channeldb.ErrDryRunMigrationOK: - ltndLog.Infof("%v, exiting", err) + case errors.Is(err, channeldb.ErrDryRunMigrationOK): + ltndLog.InfoS(ctx, "Exiting due to BuildDatabase error", + slog.Any("err", err)) return nil case err != nil: - return mkErr("unable to open databases: %v", err) + return mkErr("unable to open databases", err) } defer cleanUp() @@ -460,7 +485,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, grpcListeners, ) if err != nil { - return mkErr("error creating wallet config: %v", err) + return mkErr("error creating wallet config", err) } defer cleanUp() @@ -469,7 +494,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, partialChainControl, walletConfig, ) if err != nil { - return mkErr("error loading chain control: %v", err) + return mkErr("error loading chain control", err) } defer cleanUp() @@ -482,7 +507,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, }, ) if err != nil { - return mkErr("error deriving node key: %v", err) + return mkErr("error deriving node key", err) } if cfg.Tor.StreamIsolation && cfg.Tor.SkipProxyForClearNetTargets { @@ -491,14 +516,14 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, if cfg.Tor.Active { if cfg.Tor.SkipProxyForClearNetTargets { - srvrLog.Info("Onion services are accessible via Tor! " + - "NOTE: Traffic to clearnet services is not " + - "routed via Tor.") + srvrLog.InfoS(ctx, "Onion services are accessible "+ + "via Tor! NOTE: Traffic to clearnet services "+ + "is not routed via Tor.") } else { - srvrLog.Infof("Proxying all network traffic via Tor "+ - "(stream_isolation=%v)! NOTE: Ensure the "+ - "backend node is proxying over Tor as well", - cfg.Tor.StreamIsolation) + srvrLog.InfoS(ctx, "Proxying all network traffic "+ + "via Tor! NOTE: Ensure the backend node is "+ + "proxying over Tor as well", + "stream_isolation", cfg.Tor.StreamIsolation) } } @@ -515,13 +540,13 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, // Start the tor controller before giving it to any other // subsystems. if err := torController.Start(); err != nil { - return mkErr("unable to initialize tor controller: %v", + return mkErr("unable to initialize tor controller", err) } defer func() { if err := torController.Stop(); err != nil { - ltndLog.Errorf("error stopping tor "+ - "controller: %v", err) + ltndLog.ErrorS(ctx, "Error stopping tor "+ + "controller", err) } }() } @@ -535,7 +560,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, }, ) if err != nil { - return mkErr("error deriving tower key: %v", err) + return mkErr("error deriving tower key", err) } wtCfg := &watchtower.Config{ @@ -576,12 +601,12 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, wtCfg, lncfg.NormalizeAddresses, ) if err != nil { - return mkErr("unable to configure watchtower: %v", err) + return mkErr("unable to configure watchtower", err) } tower, err = watchtower.New(wtConfig) if err != nil { - return mkErr("unable to create watchtower: %v", err) + return mkErr("unable to create watchtower", err) } } @@ -604,7 +629,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, implCfg, ) if err != nil { - return mkErr("unable to create server: %v", err) + return mkErr("unable to create server", err) } // Set up an autopilot manager from the current config. This will be @@ -615,22 +640,21 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, cfg.ActiveNetParams, ) if err != nil { - return mkErr("unable to initialize autopilot: %v", err) + return mkErr("unable to initialize autopilot", err) } atplManager, err := autopilot.NewManager(atplCfg) if err != nil { - return mkErr("unable to create autopilot manager: %v", err) + return mkErr("unable to create autopilot manager", err) } if err := atplManager.Start(); err != nil { - return mkErr("unable to start autopilot manager: %v", err) + return mkErr("unable to start autopilot manager", err) } defer atplManager.Stop() err = tlsManager.LoadPermanentCertificate(activeChainControl.KeyRing) if err != nil { - return mkErr("unable to load permanent TLS certificate: %v", - err) + return mkErr("unable to load permanent TLS certificate", err) } // Now we have created all dependencies necessary to populate and @@ -641,10 +665,10 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, server.invoiceHtlcModifier, ) if err != nil { - return mkErr("unable to add deps to RPC server: %v", err) + return mkErr("unable to add deps to RPC server", err) } if err := rpcServer.Start(); err != nil { - return mkErr("unable to start RPC server: %v", err) + return mkErr("unable to start RPC server", err) } defer rpcServer.Stop() @@ -652,7 +676,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, interceptorChain.SetRPCActive() if err := interceptor.Notifier.NotifyReady(true); err != nil { - return mkErr("error notifying ready: %v", err) + return mkErr("error notifying ready", err) } // We'll wait until we're fully synced to continue the start up of the @@ -661,11 +685,11 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, // funds. _, bestHeight, err := activeChainControl.ChainIO.GetBestBlock() if err != nil { - return mkErr("unable to determine chain tip: %v", err) + return mkErr("unable to determine chain tip", err) } - ltndLog.Infof("Waiting for chain backend to finish sync, "+ - "start_height=%v", bestHeight) + ltndLog.InfoS(ctx, "Waiting for chain backend to finish sync", + slog.Int64("start_height", int64(bestHeight))) type syncResult struct { synced bool @@ -692,12 +716,12 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, case res := <-syncedResChan: if res.err != nil { return mkErr("unable to determine if wallet "+ - "is synced: %v", res.err) + "is synced", res.err) } - ltndLog.Debugf("Syncing to block timestamp: %v, is "+ - "synced=%v", time.Unix(res.bestBlockTime, 0), - res.synced) + ltndLog.DebugS(ctx, "Syncing to block chain", + "best_block_time", time.Unix(res.bestBlockTime, 0), + "is_synced", res.synced) if res.synced { break @@ -719,11 +743,11 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, _, bestHeight, err = activeChainControl.ChainIO.GetBestBlock() if err != nil { - return mkErr("unable to determine chain tip: %v", err) + return mkErr("unable to determine chain tip", err) } - ltndLog.Infof("Chain backend is fully synced (end_height=%v)!", - bestHeight) + ltndLog.InfoS(ctx, "Chain backend is fully synced!", + "end_height", bestHeight) // With all the relevant chains initialized, we can finally start the // server itself. We start the server in an asynchronous goroutine so @@ -737,8 +761,8 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, defer func() { err := server.Stop() if err != nil { - ltndLog.Warnf("Stopping the server including all "+ - "its subsystems failed with %v", err) + ltndLog.WarnS(ctx, "Stopping the server including all "+ + "its subsystems failed with", err) } }() @@ -748,7 +772,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, break } - return mkErr("unable to start server: %v", err) + return mkErr("unable to start server", err) case <-interceptor.ShutdownChannel(): return nil @@ -762,13 +786,13 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, // stopped together with the autopilot service. if cfg.Autopilot.Active { if err := atplManager.StartAgent(); err != nil { - return mkErr("unable to start autopilot agent: %v", err) + return mkErr("unable to start autopilot agent", err) } } if cfg.Watchtower.Active { if err := tower.Start(); err != nil { - return mkErr("unable to start watchtower: %v", err) + return mkErr("unable to start watchtower", err) } defer tower.Stop() } @@ -921,7 +945,8 @@ func startGrpcListen(cfg *Config, grpcServer *grpc.Server, // startRestProxy starts the given REST proxy on the listeners found in the // config. -func startRestProxy(cfg *Config, rpcServer *rpcServer, restDialOpts []grpc.DialOption, +func startRestProxy(ctx context.Context, cfg *Config, rpcServer *rpcServer, + restDialOpts []grpc.DialOption, restListen func(net.Addr) (net.Listener, error)) (func(), error) { // We use the first RPC listener as the destination for our REST proxy. @@ -948,7 +973,6 @@ func startRestProxy(cfg *Config, rpcServer *rpcServer, restDialOpts []grpc.DialO } // Start a REST proxy for our gRPC server. - ctx := context.Background() ctx, cancel := context.WithCancel(ctx) shutdownFuncs = append(shutdownFuncs, cancel) diff --git a/lnrpc/devrpc/dev_server.go b/lnrpc/devrpc/dev_server.go index ebd4591abd..60f30dd7ed 100644 --- a/lnrpc/devrpc/dev_server.go +++ b/lnrpc/devrpc/dev_server.go @@ -298,7 +298,7 @@ func (s *Server) ImportGraph(ctx context.Context, rpcEdge.ChanPoint, err) } - makePolicy := func(rpcPolicy *lnrpc.RoutingPolicy) *models.ChannelEdgePolicy { //nolint:lll + makePolicy := func(rpcPolicy *lnrpc.RoutingPolicy) *models.ChannelEdgePolicy { //nolint:ll policy := &models.ChannelEdgePolicy{ ChannelID: rpcEdge.ChannelId, LastUpdate: time.Unix( diff --git a/lnrpc/invoicesrpc/addinvoice.go b/lnrpc/invoicesrpc/addinvoice.go index 59f7df610b..114e357188 100644 --- a/lnrpc/invoicesrpc/addinvoice.go +++ b/lnrpc/invoicesrpc/addinvoice.go @@ -519,7 +519,7 @@ func AddInvoice(ctx context.Context, cfg *AddInvoiceConfig, finalCLTVDelta := uint32(cltvExpiryDelta) finalCLTVDelta += uint32(routing.BlockPadding) - //nolint:lll + //nolint:ll paths, err := blindedpath.BuildBlindedPaymentPaths( &blindedpath.BuildBlindedPathCfg{ FindRoutes: cfg.QueryBlindedRoutes, @@ -534,7 +534,7 @@ func AddInvoice(ctx context.Context, cfg *AddInvoiceConfig, p *blindedpath.BlindedHopPolicy) ( *blindedpath.BlindedHopPolicy, error) { - //nolint:lll + //nolint:ll return blindedpath.AddPolicyBuffer( p, blindCfg.RoutePolicyIncrMultiplier, blindCfg.RoutePolicyDecrMultiplier, diff --git a/lnrpc/routerrpc/config.go b/lnrpc/routerrpc/config.go index 20e3fa09bf..044c2436fc 100644 --- a/lnrpc/routerrpc/config.go +++ b/lnrpc/routerrpc/config.go @@ -12,7 +12,7 @@ import ( // options, while if able to be populated, the latter fields MUST also be // specified. // -//nolint:lll +//nolint:ll type Config struct { RoutingConfig diff --git a/lnrpc/routerrpc/forward_interceptor.go b/lnrpc/routerrpc/forward_interceptor.go index 7bc366dce0..9da831ac04 100644 --- a/lnrpc/routerrpc/forward_interceptor.go +++ b/lnrpc/routerrpc/forward_interceptor.go @@ -154,7 +154,7 @@ func (r *forwardInterceptor) resolveFromClient( outWireCustomRecords = fn.Some[lnwire.CustomRecords](cr) } - //nolint:lll + //nolint:ll return r.htlcSwitch.Resolve(&htlcswitch.FwdResolution{ Key: circuitKey, Action: htlcswitch.FwdActionResumeModified, diff --git a/lnrpc/routerrpc/router_server.go b/lnrpc/routerrpc/router_server.go index a4112ba646..7f1a7edf07 100644 --- a/lnrpc/routerrpc/router_server.go +++ b/lnrpc/routerrpc/router_server.go @@ -600,7 +600,7 @@ func (s *Server) probePaymentRequest(ctx context.Context, paymentRequest string, // If the payment probe failed we only return the failure reason and // leave the probe result params unaltered. - if resp.FailureReason != lnrpc.PaymentFailureReason_FAILURE_REASON_NONE { //nolint:lll + if resp.FailureReason != lnrpc.PaymentFailureReason_FAILURE_REASON_NONE { //nolint:ll return resp, nil } @@ -786,7 +786,7 @@ func (s *Server) sendProbePayment(ctx context.Context, case lnrpc.Payment_FAILED: // Incorrect payment details point to a // successful probe. - //nolint:lll + //nolint:ll if payment.FailureReason == lnrpc.PaymentFailureReason_FAILURE_REASON_INCORRECT_PAYMENT_DETAILS { return paymentDetails(payment) } @@ -1031,7 +1031,7 @@ func (s *Server) SetMissionControlConfig(ctx context.Context, req.Config.HopProbability, ), AprioriWeight: float64(req.Config.Weight), - CapacityFraction: routing.DefaultCapacityFraction, //nolint:lll + CapacityFraction: routing.DefaultCapacityFraction, //nolint:ll } } diff --git a/lnrpc/routerrpc/router_server_test.go b/lnrpc/routerrpc/router_server_test.go index 22f210ee99..a4047977ec 100644 --- a/lnrpc/routerrpc/router_server_test.go +++ b/lnrpc/routerrpc/router_server_test.go @@ -276,7 +276,7 @@ func TestIsLsp(t *testing.T) { bobExpensiveCopy.FeeProportionalMillionths = 1_000_000 bobExpensiveCopy.CLTVExpiryDelta = bobHopHint.CLTVExpiryDelta - 1 - //nolint:lll + //nolint:ll lspTestCases := []struct { name string routeHints [][]zpay32.HopHint diff --git a/lnrpc/routerrpc/routing_config.go b/lnrpc/routerrpc/routing_config.go index 83699a27f7..f113db94ea 100644 --- a/lnrpc/routerrpc/routing_config.go +++ b/lnrpc/routerrpc/routing_config.go @@ -8,7 +8,7 @@ import ( // RoutingConfig contains the configurable parameters that control routing. // -//nolint:lll +//nolint:ll type RoutingConfig struct { // ProbabilityEstimatorType sets the estimator to use. ProbabilityEstimatorType string `long:"estimator" choice:"apriori" choice:"bimodal" description:"Probability estimator used for pathfinding." ` @@ -48,7 +48,7 @@ type RoutingConfig struct { // AprioriConfig defines parameters for the apriori probability. // -//nolint:lll +//nolint:ll type AprioriConfig struct { // HopProbability is the assumed success probability of a hop in a route // when no other information is available. @@ -73,7 +73,7 @@ type AprioriConfig struct { // BimodalConfig defines parameters for the bimodal probability. // -//nolint:lll +//nolint:ll type BimodalConfig struct { // Scale describes the scale over which channels still have some // liquidity left on both channel ends. A value of 0 means that we diff --git a/lnrpc/walletrpc/walletkit_server.go b/lnrpc/walletrpc/walletkit_server.go index 3b16f4da71..c6dec6fbd5 100644 --- a/lnrpc/walletrpc/walletkit_server.go +++ b/lnrpc/walletrpc/walletkit_server.go @@ -199,7 +199,7 @@ var ( // and the native enum cannot be renumbered because it is stored in the // watchtower and BreachArbitrator databases. // - //nolint:lll + //nolint:ll allWitnessTypes = map[input.WitnessType]WitnessType{ input.CommitmentTimeLock: WitnessType_COMMITMENT_TIME_LOCK, input.CommitmentNoDelay: WitnessType_COMMITMENT_NO_DELAY, diff --git a/lntest/node/config.go b/lntest/node/config.go index 1e8129e7d8..32f24395b6 100644 --- a/lntest/node/config.go +++ b/lntest/node/config.go @@ -203,6 +203,7 @@ func (cfg *BaseNodeConfig) GenArgs() []string { "--bitcoin.defaultchanconfs=1", "--accept-keysend", "--keep-failed-payment-attempts", + "--logging.no-commit-hash", fmt.Sprintf("--db.batch-commit-interval=%v", commitInterval), fmt.Sprintf("--bitcoin.defaultremotedelay=%v", DefaultCSV), fmt.Sprintf("--rpclisten=%v", cfg.RPCAddr()), diff --git a/lntest/rpc/lnd.go b/lntest/rpc/lnd.go index 1657caac8d..c578d05258 100644 --- a/lntest/rpc/lnd.go +++ b/lntest/rpc/lnd.go @@ -705,7 +705,7 @@ func (h *HarnessRPC) GetChanInfo( // LookupHtlcResolution makes a RPC call to the node's LookupHtlcResolution and // returns the response. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) LookupHtlcResolution( req *lnrpc.LookupHtlcResolutionRequest) *lnrpc.LookupHtlcResolutionResponse { diff --git a/lntest/rpc/router.go b/lntest/rpc/router.go index 707c43a11d..ccc7b0ef62 100644 --- a/lntest/rpc/router.go +++ b/lntest/rpc/router.go @@ -15,7 +15,7 @@ import ( // UpdateChanStatus makes a UpdateChanStatus RPC call to node's RouterClient // and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) UpdateChanStatus( req *routerrpc.UpdateChanStatusRequest) *routerrpc.UpdateChanStatusResponse { @@ -76,7 +76,7 @@ func (h *HarnessRPC) SubscribeHtlcEvents() HtlcEventsClient { // GetMissionControlConfig makes a RPC call to the node's // GetMissionControlConfig and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) GetMissionControlConfig() *routerrpc.GetMissionControlConfigResponse { ctxt, cancel := context.WithTimeout(h.runCtx, DefaultTimeout) defer cancel() @@ -142,7 +142,7 @@ func (h *HarnessRPC) SendToRouteV2( // QueryProbability makes a RPC call to the node's QueryProbability and // asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) QueryProbability( req *routerrpc.QueryProbabilityRequest) *routerrpc.QueryProbabilityResponse { diff --git a/lntest/rpc/signer.go b/lntest/rpc/signer.go index 79a680c2b8..62b9ac06d1 100644 --- a/lntest/rpc/signer.go +++ b/lntest/rpc/signer.go @@ -88,7 +88,7 @@ func (h *HarnessRPC) MuSig2CreateSessionErr( // MuSig2CombineKeys makes a RPC call to the node's SignerClient and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) MuSig2CombineKeys( req *signrpc.MuSig2CombineKeysRequest) *signrpc.MuSig2CombineKeysResponse { @@ -117,7 +117,7 @@ func (h *HarnessRPC) MuSig2CombineKeysErr( // MuSig2RegisterNonces makes a RPC call to the node's SignerClient and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) MuSig2RegisterNonces( req *signrpc.MuSig2RegisterNoncesRequest) *signrpc.MuSig2RegisterNoncesResponse { diff --git a/lntest/rpc/wallet_kit.go b/lntest/rpc/wallet_kit.go index 67a2f5fcaa..38545fc0cf 100644 --- a/lntest/rpc/wallet_kit.go +++ b/lntest/rpc/wallet_kit.go @@ -228,7 +228,7 @@ func (h *HarnessRPC) GetTransaction( // RemoveTransaction makes an RPC call to the node's WalletKitClient and // asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) RemoveTransaction( req *walletrpc.GetTransactionRequest) *walletrpc.RemoveTransactionResponse { @@ -256,7 +256,7 @@ func (h *HarnessRPC) BumpFee( // BumpForceCloseFee makes a RPC call to the node's WalletKitClient and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) BumpForceCloseFee( req *walletrpc.BumpForceCloseFeeRequest) *walletrpc.BumpForceCloseFeeResponse { @@ -311,7 +311,7 @@ func (h *HarnessRPC) ImportAccountAssertErr( // ImportPublicKey makes a RPC call to the node's WalletKitClient and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) ImportPublicKey( req *walletrpc.ImportPublicKeyRequest) *walletrpc.ImportPublicKeyResponse { @@ -352,7 +352,7 @@ func (h *HarnessRPC) SignPsbtErr(req *walletrpc.SignPsbtRequest) error { // ImportTapscript makes a RPC call to the node's WalletKitClient and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) ImportTapscript( req *walletrpc.ImportTapscriptRequest) *walletrpc.ImportTapscriptResponse { @@ -367,7 +367,7 @@ func (h *HarnessRPC) ImportTapscript( // RequiredReserve makes a RPC call to the node's WalletKitClient and asserts. // -//nolint:lll +//nolint:ll func (h *HarnessRPC) RequiredReserve( req *walletrpc.RequiredReserveRequest) *walletrpc.RequiredReserveResponse { diff --git a/lntest/utils.go b/lntest/utils.go index feaae57e7b..c1ae8cd238 100644 --- a/lntest/utils.go +++ b/lntest/utils.go @@ -181,7 +181,7 @@ func NodeArgsForCommitType(commitType lnrpc.CommitmentType) []string { // function provides a simple way to allow test balance assertions to take fee // calculations into account. func CalcStaticFee(c lnrpc.CommitmentType, numHTLCs int) btcutil.Amount { - //nolint:lll + //nolint:ll const ( htlcWeight = input.HTLCWeight anchorSize = 330 * 2 @@ -238,7 +238,7 @@ func CalculateMaxHtlc(chanCap btcutil.Amount) uint64 { // CalcStaticFeeBuffer calculates appropriate fee buffer which must be taken // into account when sending htlcs. func CalcStaticFeeBuffer(c lnrpc.CommitmentType, numHTLCs int) btcutil.Amount { - //nolint:lll + //nolint:ll const ( htlcWeight = input.HTLCWeight defaultSatPerVByte = lnwallet.DefaultAnchorsCommitMaxFeeRateSatPerVByte diff --git a/lnwallet/btcwallet/btcwallet.go b/lnwallet/btcwallet/btcwallet.go index ee62bdb277..5d28574cbe 100644 --- a/lnwallet/btcwallet/btcwallet.go +++ b/lnwallet/btcwallet/btcwallet.go @@ -1279,7 +1279,7 @@ func (b *BtcWallet) PublishTransaction(tx *wire.MsgTx, label string) error { // btcwallet error. err = b.chain.MapRPCErr(errors.New(result.RejectReason)) - //nolint:lll + //nolint:ll // These two errors are ignored inside `PublishTransaction`: // https://github.com/btcsuite/btcwallet/blob/master/wallet/wallet.go#L3763 // To keep our current behavior, we need to ignore the same errors @@ -1680,7 +1680,7 @@ out: // Launch a goroutine to re-package and send // notifications for any newly confirmed transactions. - //nolint:lll + //nolint:ll go func(txNtfn *base.TransactionNotifications) { for _, block := range txNtfn.AttachedBlocks { details, err := minedTransactionsToDetails( diff --git a/lnwallet/btcwallet/psbt_test.go b/lnwallet/btcwallet/psbt_test.go index 3f04bc7a8e..694a8c04f1 100644 --- a/lnwallet/btcwallet/psbt_test.go +++ b/lnwallet/btcwallet/psbt_test.go @@ -432,7 +432,7 @@ func TestEstimateInputWeight(t *testing.T) { {}, }, }, - //nolint:lll + //nolint:ll expectedWitnessWeight: input.TaprootKeyPathCustomSighashWitnessSize, }, { name: "p2tr script spend", diff --git a/lnwallet/chancloser/chancloser.go b/lnwallet/chancloser/chancloser.go index 662a38aa76..17112b29e0 100644 --- a/lnwallet/chancloser/chancloser.go +++ b/lnwallet/chancloser/chancloser.go @@ -917,7 +917,7 @@ func (c *ChanCloser) ReceiveClosingSigned( //nolint:funlen ) matchingSig := c.priorFeeOffers[remoteProposedFee] if c.cfg.Channel.ChanType().IsTaproot() { - localWireSig, err := matchingSig.PartialSig.UnwrapOrErrV( //nolint:lll + localWireSig, err := matchingSig.PartialSig.UnwrapOrErrV( //nolint:ll fmt.Errorf("none local sig"), ) if err != nil { @@ -931,7 +931,7 @@ func (c *ChanCloser) ReceiveClosingSigned( //nolint:funlen } muSession := c.cfg.MusigSession - localSig, remoteSig, closeOpts, err = muSession.CombineClosingOpts( //nolint:lll + localSig, remoteSig, closeOpts, err = muSession.CombineClosingOpts( //nolint:ll localWireSig, remoteWireSig, ) if err != nil { @@ -981,7 +981,7 @@ func (c *ChanCloser) ReceiveClosingSigned( //nolint:funlen err = fn.MapOptionZ( c.cfg.AuxCloser, func(aux AuxChanCloser) error { channel := c.cfg.Channel - //nolint:lll + //nolint:ll req := AuxShutdownReq{ ChanPoint: c.chanPoint, ShortChanID: c.cfg.Channel.ShortChanID(), diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 54ef442a9b..7f70e600c6 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2181,7 +2181,7 @@ func NewBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64, // spend (as our output on their revoked tx still needs the // delay), and set the control block. if scriptTree, ok := ourScript.(input.TapscriptDescriptor); ok { - //nolint:lll + //nolint:ll br.LocalOutputSignDesc.SignMethod = input.TaprootScriptSpendSignMethod ctrlBlock, err := scriptTree.CtrlBlockForPath( @@ -2191,7 +2191,7 @@ func NewBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64, return nil, err } - //nolint:lll + //nolint:ll br.LocalOutputSignDesc.ControlBlock, err = ctrlBlock.ToBytes() if err != nil { return nil, err @@ -2262,7 +2262,7 @@ func NewBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64, // parties need to sweep anchors is revealed on chain. scriptTree, ok := theirScript.(input.TapscriptDescriptor) if ok { - //nolint:lll + //nolint:ll br.RemoteOutputSignDesc.SignMethod = input.TaprootScriptSpendSignMethod ctrlBlock, err := scriptTree.CtrlBlockForPath( @@ -2271,7 +2271,7 @@ func NewBreachRetribution(chanState *channeldb.OpenChannel, stateNum uint64, if err != nil { return nil, err } - //nolint:lll + //nolint:ll br.RemoteOutputSignDesc.ControlBlock, err = ctrlBlock.ToBytes() if err != nil { return nil, err @@ -3238,7 +3238,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // If this is a taproot channel, then we'll need to set the // method type to ensure we generate a valid signature. if chanType.IsTaproot() { - //nolint:lll + //nolint:ll sigJob.SignDesc.SignMethod = input.TaprootScriptSpendSignMethod } @@ -3320,7 +3320,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // If this is a taproot channel, then we'll need to set the // method type to ensure we generate a valid signature. if chanType.IsTaproot() { - //nolint:lll + //nolint:ll sigJob.SignDesc.SignMethod = input.TaprootScriptSpendSignMethod } @@ -4786,7 +4786,7 @@ func genHtlcSigValidationJobs(chanState *channeldb.OpenChannel, // If this output index is found within the incoming HTLC // index, then this means that we need to generate an HTLC // success transaction in order to validate the signature. - //nolint:lll + //nolint:ll case localCommitmentView.incomingHTLCIndex[outputIndex] != nil: htlc = localCommitmentView.incomingHTLCIndex[outputIndex] @@ -4825,7 +4825,7 @@ func genHtlcSigValidationJobs(chanState *channeldb.OpenChannel, if chanType.IsTaproot() { // TODO(roasbeef): add abstraction in // front - prevFetcher := txscript.NewCannedPrevOutputFetcher( //nolint:lll + prevFetcher := txscript.NewCannedPrevOutputFetcher( //nolint:ll htlc.ourPkScript, htlcAmt, ) hashCache := txscript.NewTxSigHashes( @@ -4835,7 +4835,7 @@ func genHtlcSigValidationJobs(chanState *channeldb.OpenChannel, htlc.ourWitnessScript, ) - return txscript.CalcTapscriptSignaturehash( //nolint:lll + return txscript.CalcTapscriptSignaturehash( //nolint:ll hashCache, sigHashType, successTx, 0, prevFetcher, tapLeaf, @@ -4880,7 +4880,7 @@ func genHtlcSigValidationJobs(chanState *channeldb.OpenChannel, // Otherwise, if this is an outgoing HTLC, then we'll need to // generate a timeout transaction so we can verify the // signature presented. - //nolint:lll + //nolint:ll case localCommitmentView.outgoingHTLCIndex[outputIndex] != nil: htlc = localCommitmentView.outgoingHTLCIndex[outputIndex] @@ -4919,7 +4919,7 @@ func genHtlcSigValidationJobs(chanState *channeldb.OpenChannel, if chanType.IsTaproot() { // TODO(roasbeef): add abstraction in // front - prevFetcher := txscript.NewCannedPrevOutputFetcher( //nolint:lll + prevFetcher := txscript.NewCannedPrevOutputFetcher( //nolint:ll htlc.ourPkScript, htlcAmt, ) hashCache := txscript.NewTxSigHashes( @@ -4929,7 +4929,7 @@ func genHtlcSigValidationJobs(chanState *channeldb.OpenChannel, htlc.ourWitnessScript, ) - return txscript.CalcTapscriptSignaturehash( //nolint:lll + return txscript.CalcTapscriptSignaturehash( //nolint:ll hashCache, sigHashType, timeoutTx, 0, prevFetcher, tapLeaf, @@ -5246,7 +5246,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error { _ = localCommitTx.Serialize(&txBytes) return &InvalidPartialCommitSigError{ invalidPartialSigError: &sigErr, - InvalidCommitSigError: InvalidCommitSigError{ //nolint:lll + InvalidCommitSigError: InvalidCommitSigError{ //nolint:ll commitHeight: nextHeight, commitTx: txBytes.Bytes(), }, @@ -5302,7 +5302,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error { return &InvalidCommitSigError{ commitHeight: nextHeight, - commitSig: commitSigs.CommitSig.ToSignatureBytes(), //nolint:lll + commitSig: commitSigs.CommitSig.ToSignatureBytes(), //nolint:ll sigHash: sigHash, commitTx: txBytes.Bytes(), } @@ -5377,7 +5377,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error { localCommitmentView.sig = sigBytes[:] } else { - localCommitmentView.sig = commitSigs.CommitSig.ToSignatureBytes() //nolint:lll + localCommitmentView.sig = commitSigs.CommitSig.ToSignatureBytes() //nolint:ll } lc.commitChains.Local.addCommitment(localCommitmentView) @@ -6824,7 +6824,7 @@ func NewUnilateralCloseSummary(chanState *channeldb.OpenChannel, //nolint:funlen // For taproot channels, we'll need to set some additional // fields to ensure the output can be swept. // - //nolint:lll + //nolint:ll if scriptTree, ok := selfScript.(input.TapscriptDescriptor); ok { commitResolution.SelfOutputSignDesc.SignMethod = input.TaprootScriptSpendSignMethod @@ -6835,7 +6835,7 @@ func NewUnilateralCloseSummary(chanState *channeldb.OpenChannel, //nolint:funlen if err != nil { return nil, err } - //nolint:lll + //nolint:ll commitResolution.SelfOutputSignDesc.ControlBlock, err = ctrlBlock.ToBytes() if err != nil { return nil, err @@ -7269,7 +7269,7 @@ func newOutgoingHtlcResolution(signer input.Signer, return nil, err } } else { - //nolint:lll + //nolint:ll secondLevelScriptTree, err := input.TaprootSecondLevelScriptTree( keyRing.RevocationKey, keyRing.ToLocalKey, csvDelay, secondLevelAuxLeaf, @@ -7336,9 +7336,9 @@ func newOutgoingHtlcResolution(signer input.Signer, ChanType: chanType, ShortChanID: chanState.ShortChanID(), Initiator: chanState.IsInitiator, - CommitBlob: chanState.LocalCommitment.CustomBlob, //nolint:lll + CommitBlob: chanState.LocalCommitment.CustomBlob, //nolint:ll FundingBlob: chanState.CustomBlob, - Type: input.TaprootHtlcLocalOfferedTimeout, //nolint:lll + Type: input.TaprootHtlcLocalOfferedTimeout, //nolint:ll CloseType: LocalForceClose, CommitTx: commitTx, ContractPoint: op, @@ -7348,14 +7348,14 @@ func newOutgoingHtlcResolution(signer input.Signer, HtlcAmt: btcutil.Amount(txOut.Value), CommitCsvDelay: csvDelay, CltvDelay: fn.Some(htlc.RefundTimeout), - CommitFee: chanState.LocalCommitment.CommitFee, //nolint:lll + CommitFee: chanState.LocalCommitment.CommitFee, //nolint:ll HtlcID: fn.Some(htlc.HtlcIndex), PayHash: fn.Some(htlc.RHash), AuxSigDesc: fn.Some(AuxSigDesc{ SignDetails: *txSignDetails, AuxSig: func() []byte { - tlvType := htlcCustomSigType.TypeVal() //nolint:lll - return htlc.CustomRecords[uint64(tlvType)] //nolint:lll + tlvType := htlcCustomSigType.TypeVal() //nolint:ll + return htlc.CustomRecords[uint64(tlvType)] //nolint:ll }(), }), } @@ -7451,7 +7451,7 @@ func newIncomingHtlcResolution(signer input.Signer, PrevOutputFetcher: prevFetcher, } - //nolint:lll + //nolint:ll if scriptTree, ok := scriptInfo.(input.TapscriptDescriptor); ok { signDesc.SignMethod = input.TaprootScriptSpendSignMethod ctrlBlock, err := scriptTree.CtrlBlockForPath( @@ -7612,7 +7612,7 @@ func newIncomingHtlcResolution(signer input.Signer, return nil, err } } else { - //nolint:lll + //nolint:ll secondLevelScriptTree, err := input.TaprootSecondLevelScriptTree( keyRing.RevocationKey, keyRing.ToLocalKey, csvDelay, secondLevelAuxLeaf, @@ -7676,8 +7676,8 @@ func newIncomingHtlcResolution(signer input.Signer, ChanType: chanType, ShortChanID: chanState.ShortChanID(), Initiator: chanState.IsInitiator, - CommitBlob: chanState.LocalCommitment.CustomBlob, //nolint:lll - Type: input.TaprootHtlcAcceptedLocalSuccess, //nolint:lll + CommitBlob: chanState.LocalCommitment.CustomBlob, //nolint:ll + Type: input.TaprootHtlcAcceptedLocalSuccess, //nolint:ll FundingBlob: chanState.CustomBlob, CloseType: LocalForceClose, CommitTx: commitTx, @@ -7686,13 +7686,13 @@ func newIncomingHtlcResolution(signer input.Signer, KeyRing: keyRing, HtlcID: fn.Some(htlc.HtlcIndex), CsvDelay: htlcCsvDelay, - CommitFee: chanState.LocalCommitment.CommitFee, //nolint:lll + CommitFee: chanState.LocalCommitment.CommitFee, //nolint:ll PayHash: fn.Some(htlc.RHash), AuxSigDesc: fn.Some(AuxSigDesc{ SignDetails: *txSignDetails, AuxSig: func() []byte { - tlvType := htlcCustomSigType.TypeVal() //nolint:lll - return htlc.CustomRecords[uint64(tlvType)] //nolint:lll + tlvType := htlcCustomSigType.TypeVal() //nolint:ll + return htlc.CustomRecords[uint64(tlvType)] //nolint:ll }(), }), CommitCsvDelay: csvDelay, @@ -8091,7 +8091,7 @@ func NewLocalForceCloseSummary(chanState *channeldb.OpenChannel, if err != nil { return nil, err } - //nolint:lll + //nolint:ll commitResolution.SelfOutputSignDesc.ControlBlock, err = ctrlBlock.ToBytes() if err != nil { return nil, err @@ -8103,9 +8103,9 @@ func NewLocalForceCloseSummary(chanState *channeldb.OpenChannel, resolveBlob := fn.MapOptionZ( auxResolver, func(a AuxContractResolver) fn.Result[tlv.Blob] { - //nolint:lll + //nolint:ll return a.ResolveContract(ResolutionReq{ - ChanPoint: chanState.FundingOutpoint, //nolint:lll + ChanPoint: chanState.FundingOutpoint, //nolint:ll ChanType: chanState.ChanType, ShortChanID: chanState.ShortChanID(), Initiator: chanState.IsInitiator, @@ -8630,7 +8630,7 @@ func NewAnchorResolution(chanState *channeldb.OpenChannel, if scriptTree, ok := localAnchor.(input.TapscriptDescriptor); ok { signDesc.SignMethod = input.TaprootKeySpendSignMethod - //nolint:lll + //nolint:ll signDesc.PrevOutputFetcher = txscript.NewCannedPrevOutputFetcher( localAnchor.PkScript(), int64(AnchorSize), ) @@ -8652,7 +8652,7 @@ func NewAnchorResolution(chanState *channeldb.OpenChannel, // commitment, as this is a "tweakless" channel type, // we don't need a tweak value at all. // - //nolint:lll + //nolint:ll signDesc.KeyDesc = chanState.LocalChanCfg.PaymentBasePoint } @@ -9072,7 +9072,7 @@ func (lc *LightningChannel) generateRevocation(height uint64) (*lnwire.RevokeAnd // If this is a taproot channel, then we also need to generate the // verification nonce for this target state. if lc.channelState.ChanType.IsTaproot() { - nextVerificationNonce, err := channeldb.NewMusigVerificationNonce( //nolint:lll + nextVerificationNonce, err := channeldb.NewMusigVerificationNonce( //nolint:ll lc.channelState.LocalChanCfg.MultiSigKey.PubKey, revHeight, lc.taprootNonceProducer, ) diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index e3b7d07f90..f7ecd32277 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -9829,7 +9829,7 @@ func TestCreateBreachRetribution(t *testing.T) { { name: "fail due to our index too big", revocationLog: &channeldb.RevocationLog{ - //nolint:lll + //nolint:ll OurOutputIndex: tlv.NewPrimitiveRecord[tlv.TlvType0]( uint16(htlcIndex + 1), ), @@ -9839,7 +9839,7 @@ func TestCreateBreachRetribution(t *testing.T) { { name: "fail due to their index too big", revocationLog: &channeldb.RevocationLog{ - //nolint:lll + //nolint:ll TheirOutputIndex: tlv.NewPrimitiveRecord[tlv.TlvType1]( uint16(htlcIndex + 1), ), @@ -10352,7 +10352,7 @@ func TestApplyCommitmentFee(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - //nolint:lll + //nolint:ll balance, bufferAmt, commitFee, err := tc.channel.applyCommitFee( tc.balance, commitWeight, feePerKw, tc.buffer, ) @@ -10832,7 +10832,7 @@ func TestBlindingPointPersistence(t *testing.T) { // Send a HTLC from Alice to Bob that has a blinding point populated. htlc, _ := createHTLC(0, 100_000_000) blinding, err := pubkeyFromHex( - "0228f2af0abe322403480fb3ee172f7f1601e67d1da6cad40b54c4468d48236c39", //nolint:lll + "0228f2af0abe322403480fb3ee172f7f1601e67d1da6cad40b54c4468d48236c39", //nolint:ll ) require.NoError(t, err) htlc.BlindingPoint = tlv.SomeRecordT( diff --git a/lnwallet/commitment.go b/lnwallet/commitment.go index 36ff75edeb..8b364a01df 100644 --- a/lnwallet/commitment.go +++ b/lnwallet/commitment.go @@ -1258,7 +1258,7 @@ func addHTLC(commitTx *wire.MsgTx, whoseCommit lntypes.ChannelParty, } else { paymentDesc.theirPkScript = pkScript - //nolint:lll + //nolint:ll paymentDesc.theirWitnessScript = scriptInfo.WitnessScriptToSign() } diff --git a/lnwallet/reservation.go b/lnwallet/reservation.go index 4c4f58f8be..fd35d95076 100644 --- a/lnwallet/reservation.go +++ b/lnwallet/reservation.go @@ -895,7 +895,7 @@ func (r *ChannelReservation) ChanState() *channeldb.OpenChannel { // CommitmentKeyRings returns the local+remote key ring used for the very first // commitment transaction both parties. // -//nolint:lll +//nolint:ll func (r *ChannelReservation) CommitmentKeyRings() lntypes.Dual[CommitmentKeyRing] { r.RLock() defer r.RUnlock() diff --git a/lnwallet/wallet.go b/lnwallet/wallet.go index a9018437d5..ad6354e2e8 100644 --- a/lnwallet/wallet.go +++ b/lnwallet/wallet.go @@ -2476,13 +2476,13 @@ func (l *LightningWallet) handleSingleFunderSigs(req *addSingleFunderSigsMsg) { fundingTxOut *wire.TxOut ) if chanType.IsTaproot() { - //nolint:lll + //nolint:ll fundingWitnessScript, fundingTxOut, err = input.GenTaprootFundingScript( ourKey.PubKey, theirKey.PubKey, channelValue, pendingReservation.partialState.TapscriptRoot, ) } else { - //nolint:lll + //nolint:ll fundingWitnessScript, fundingTxOut, err = input.GenFundingPkScript( ourKey.PubKey.SerializeCompressed(), theirKey.PubKey.SerializeCompressed(), channelValue, diff --git a/lnwire/channel_update_2.go b/lnwire/channel_update_2.go index 5c6d240958..b41f2f29f1 100644 --- a/lnwire/channel_update_2.go +++ b/lnwire/channel_update_2.go @@ -147,7 +147,7 @@ func (c *ChannelUpdate2) DecodeTLVRecords(r io.Reader) error { // If the proportional fee was not encoded, then set it to the default // value. if _, ok := typeMap[c.FeeProportionalMillionths.TlvType()]; !ok { - c.FeeProportionalMillionths.Val = defaultFeeProportionalMillionths //nolint:lll + c.FeeProportionalMillionths.Val = defaultFeeProportionalMillionths //nolint:ll } if len(tlvRecords) != 0 { diff --git a/lnwire/features.go b/lnwire/features.go index eb00d86906..73a1684edb 100644 --- a/lnwire/features.go +++ b/lnwire/features.go @@ -304,7 +304,7 @@ const ( // // The base 32 encoded tagged fields in invoices are limited to 10 bits // to express the length of the field's data. - //nolint:lll + //nolint:ll // See: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#tagged-fields // // With a maximum length field of 1023 (2^10 -1) and 5 bit encoding, diff --git a/lnwire/lnwire_test.go b/lnwire/lnwire_test.go index 6b9630f58a..952e90a7e6 100644 --- a/lnwire/lnwire_test.go +++ b/lnwire/lnwire_test.go @@ -592,7 +592,7 @@ func TestLightningWireProtocol(t *testing.T) { req.LeaseExpiry = new(LeaseExpiry) *req.LeaseExpiry = LeaseExpiry(1337) - //nolint:lll + //nolint:ll req.LocalNonce = someLocalNonce[NonceRecordTypeT](r) } else { req.UpfrontShutdownScript = []byte{} @@ -667,7 +667,7 @@ func TestLightningWireProtocol(t *testing.T) { req.LeaseExpiry = new(LeaseExpiry) *req.LeaseExpiry = LeaseExpiry(1337) - //nolint:lll + //nolint:ll req.LocalNonce = someLocalNonce[NonceRecordTypeT](r) } else { req.UpfrontShutdownScript = []byte{} @@ -749,7 +749,7 @@ func TestLightningWireProtocol(t *testing.T) { scid := NewShortChanIDFromInt(uint64(r.Int63())) req.AliasScid = &scid - //nolint:lll + //nolint:ll req.NextLocalNonce = someLocalNonce[NonceRecordTypeT](r) } @@ -794,7 +794,7 @@ func TestLightningWireProtocol(t *testing.T) { } if r.Int31()%2 == 0 { - //nolint:lll + //nolint:ll req.ShutdownNonce = someLocalNonce[ShutdownNonceType](r) } @@ -994,7 +994,7 @@ func TestLightningWireProtocol(t *testing.T) { // 50/50 chance to attach a local nonce. if r.Int31()%2 == 0 { - //nolint:lll + //nolint:ll req.LocalNonce = someLocalNonce[NonceRecordTypeT](r) } @@ -1202,7 +1202,7 @@ func TestLightningWireProtocol(t *testing.T) { return } - //nolint:lll + //nolint:ll req.LocalNonce = someLocalNonce[NonceRecordTypeT](r) } @@ -1645,7 +1645,7 @@ func TestLightningWireProtocol(t *testing.T) { // Alternate between the two direction possibilities. if r.Int31()%2 == 0 { req.SecondPeer = tlv.SomeRecordT( - tlv.ZeroRecordT[tlv.TlvType8, TrueBoolean](), //nolint:lll + tlv.ZeroRecordT[tlv.TlvType8, TrueBoolean](), //nolint:ll ) } diff --git a/lnwire/onion_error.go b/lnwire/onion_error.go index 8d54a98951..5f05e1ef9f 100644 --- a/lnwire/onion_error.go +++ b/lnwire/onion_error.go @@ -81,7 +81,7 @@ const ( CodeExpiryTooFar FailCode = 21 CodeInvalidOnionPayload = FlagPerm | 22 CodeMPPTimeout FailCode = 23 - CodeInvalidBlinding = FlagBadOnion | FlagPerm | 24 //nolint:lll + CodeInvalidBlinding = FlagBadOnion | FlagPerm | 24 //nolint:ll ) // String returns the string representation of the failure code. diff --git a/lnwire/update_add_htlc.go b/lnwire/update_add_htlc.go index 5251748f0b..4873cd84b3 100644 --- a/lnwire/update_add_htlc.go +++ b/lnwire/update_add_htlc.go @@ -39,7 +39,7 @@ type ( // BlindingPointRecord holds an optional blinding point on update add // htlc. - //nolint:lll + //nolint:ll BlindingPointRecord = tlv.OptionalRecordT[BlindingPointTlvType, *btcec.PublicKey] ) diff --git a/log.go b/log.go index 795fb4d729..a3efd03335 100644 --- a/log.go +++ b/log.go @@ -120,7 +120,7 @@ func genSubLogger(root *build.SubLoggerManager, // SetupLoggers initializes all package-global logger variables. // -//nolint:lll +//nolint:ll func SetupLoggers(root *build.SubLoggerManager, interceptor signal.Interceptor) { genLogger := genSubLogger(root, interceptor) diff --git a/peer/brontide.go b/peer/brontide.go index 40d3f94c43..6bc49445ee 100644 --- a/peer/brontide.go +++ b/peer/brontide.go @@ -1285,7 +1285,7 @@ func (p *Brontide) addLink(chanPoint *wire.OutPoint, return p.cfg.ChainArb.NotifyContractUpdate(*chanPoint, update) } - //nolint:lll + //nolint:ll linkCfg := htlcswitch.ChannelLinkConfig{ Peer: p, DecodeHopIterators: p.cfg.Sphinx.DecodeHopIterators, diff --git a/protofsm/state_machine.go b/protofsm/state_machine.go index ecbd748347..b71d5efe42 100644 --- a/protofsm/state_machine.go +++ b/protofsm/state_machine.go @@ -187,7 +187,7 @@ type StateMachineCfg[Event any, Env Environment] struct { // an initial state, an environment, and an event to process as if emitted at // the onset of the state machine. Such an event can be used to set up tracking // state such as a txid confirmation event. -func NewStateMachine[Event any, Env Environment](cfg StateMachineCfg[Event, Env], //nolint:lll +func NewStateMachine[Event any, Env Environment](cfg StateMachineCfg[Event, Env], //nolint:ll ) StateMachine[Event, Env] { return StateMachine[Event, Env]{ @@ -346,7 +346,7 @@ func (s *StateMachine[Event, Env]) executeDaemonEvent( // If a post-send event was specified, then we'll funnel // that back into the main state machine now as well. - return fn.MapOptionZ(daemonEvent.PostSendEvent, func(event Event) error { //nolint:lll + return fn.MapOptionZ(daemonEvent.PostSendEvent, func(event Event) error { //nolint:ll return s.wg.Go(func(ctx context.Context) { log.Debugf("FSM(%v): sending "+ "post-send event: %v", @@ -394,7 +394,7 @@ func (s *StateMachine[Event, Env]) executeDaemonEvent( err := sendAndCleanUp() if err != nil { - //nolint:lll + //nolint:ll log.Errorf("FSM(%v): unable to send message: %v", err) } @@ -448,7 +448,7 @@ func (s *StateMachine[Event, Env]) executeDaemonEvent( // we'll send that into the current // state now. postSpend := daemonEvent.PostSpendEvent - postSpend.WhenSome(func(f SpendMapper[Event]) { //nolint:lll + postSpend.WhenSome(func(f SpendMapper[Event]) { //nolint:ll customEvent := f(spend) s.SendEvent(customEvent) }) @@ -519,7 +519,7 @@ func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env], // until we reach a terminal state, or we run out of internal events to // process. // - //nolint:lll + //nolint:ll for nextEvent := eventQueue.Dequeue(); nextEvent.IsSome(); nextEvent = eventQueue.Dequeue() { err := fn.MapOptionZ(nextEvent, func(event Event) error { log.Debugf("FSM(%v): processing event: %v", @@ -537,12 +537,12 @@ func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env], } newEvents := transition.NewEvents - err = fn.MapOptionZ(newEvents, func(events EmittedEvent[Event]) error { //nolint:lll + err = fn.MapOptionZ(newEvents, func(events EmittedEvent[Event]) error { //nolint:ll // With the event processed, we'll process any // new daemon events that were emitted as part // of this new state transition. // - //nolint:lll + //nolint:ll err := fn.MapOptionZ(events.ExternalEvents, func(dEvents DaemonEventSet) error { log.Debugf("FSM(%v): processing "+ "daemon %v daemon events", @@ -566,7 +566,7 @@ func (s *StateMachine[Event, Env]) applyEvents(currentState State[Event, Env], // Next, we'll add any new emitted events to // our event queue. // - //nolint:lll + //nolint:ll events.InternalEvent.WhenSome(func(es []Event) { for _, inEvent := range es { log.Debugf("FSM(%v): adding "+ @@ -659,7 +659,7 @@ func (s *StateMachine[Event, Env]) driveMachine() { // An outside caller is querying our state, so we'll return the // latest state. case stateQuery := <-s.stateQuery: - if !fn.SendOrQuit(stateQuery.CurrentState, currentState, s.quit) { //nolint:lll + if !fn.SendOrQuit(stateQuery.CurrentState, currentState, s.quit) { //nolint:ll return } diff --git a/record/blinded_data_test.go b/record/blinded_data_test.go index 7de8fa295e..bc1230be8b 100644 --- a/record/blinded_data_test.go +++ b/record/blinded_data_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" ) -//nolint:lll +//nolint:ll const pubkeyStr = "02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619" func pubkey(t *testing.T) *btcec.PublicKey { @@ -278,7 +278,7 @@ func TestBlindedRouteDataPadding(t *testing.T) { // TestBlindedRouteVectors tests encoding/decoding of the test vectors for // blinded route data provided in the specification. // -//nolint:lll +//nolint:ll func TestBlindingSpecTestVectors(t *testing.T) { nextBlindingOverrideStr, err := hex.DecodeString("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f") require.NoError(t, err) diff --git a/routing/blindedpath/blinded_path.go b/routing/blindedpath/blinded_path.go index a1f9db7b6b..5c16751858 100644 --- a/routing/blindedpath/blinded_path.go +++ b/routing/blindedpath/blinded_path.go @@ -838,7 +838,7 @@ func calcBlindedPathPolicies(relayInfo []*record.PaymentRelayInfo, ) // Use the algorithms defined in BOLT 4 to calculate the accumulated // relay fees for the route: - //nolint:lll + //nolint:ll // https://github.com/lightning/bolts/blob/db278ab9b2baa0b30cfe79fb3de39280595938d3/04-onion-routing.md?plain=1#L255 for i := len(relayInfo) - 1; i >= 0; i-- { info := relayInfo[i] diff --git a/routing/blindedpath/blinded_path_test.go b/routing/blindedpath/blinded_path_test.go index 35db89afb7..0020f381ca 100644 --- a/routing/blindedpath/blinded_path_test.go +++ b/routing/blindedpath/blinded_path_test.go @@ -375,7 +375,7 @@ func TestPadBlindedHopInfo(t *testing.T) { } if test.existingPadding != nil { - //nolint:lll + //nolint:ll padding := tlv.SomeRecordT( tlv.NewPrimitiveRecord[tlv.TlvType1]( make([]byte, test.existingPadding[i]), diff --git a/routing/pathfind.go b/routing/pathfind.go index db474e1e80..8e40c5bc4b 100644 --- a/routing/pathfind.go +++ b/routing/pathfind.go @@ -1307,7 +1307,7 @@ func processNodeForBlindedPath(g Graph, node route.Vertex, // Process each channel peer to gather any paths that // lead to the peer. - nextPaths, hasMoreChans, err := processNodeForBlindedPath( //nolint:lll + nextPaths, hasMoreChans, err := processNodeForBlindedPath( //nolint:ll g, channel.OtherNode, supportsRouteBlinding, visited, restrictions, ) diff --git a/routing/pathfind_test.go b/routing/pathfind_test.go index 81708d3930..da29c79a25 100644 --- a/routing/pathfind_test.go +++ b/routing/pathfind_test.go @@ -3517,7 +3517,7 @@ func TestLastHopPayloadSize(t *testing.T) { blindedPath := path.BlindedPath.BlindedHops blindedPoint := path.BlindedPath.BlindingPoint - //nolint:lll + //nolint:ll finalHop = route.Hop{ AmtToForward: tc.amount, OutgoingTimeLock: uint32(tc.finalHopExpiry), @@ -3527,7 +3527,7 @@ func TestLastHopPayloadSize(t *testing.T) { finalHop.BlindingPoint = blindedPoint } } else { - //nolint:lll + //nolint:ll finalHop = route.Hop{ AmtToForward: tc.amount, OutgoingTimeLock: uint32(tc.finalHopExpiry), diff --git a/routing/router.go b/routing/router.go index b92aa15023..9eabe0b2ae 100644 --- a/routing/router.go +++ b/routing/router.go @@ -1874,7 +1874,7 @@ func outgoingFromIncoming(incomingAmt lnwire.MilliSatoshi, PPM := big.NewInt(1_000_000) // The following discussion was contributed by user feelancer21, see - //nolint:lll + //nolint:ll // https://github.com/feelancer21/lnd/commit/f6f05fa930985aac0d27c3f6681aada1b599162a. // The incoming amount Ai based on the outgoing amount Ao is computed by diff --git a/routing/router_test.go b/routing/router_test.go index db72bf266c..2923f1fb90 100644 --- a/routing/router_test.go +++ b/routing/router_test.go @@ -618,7 +618,7 @@ func TestSendPaymentErrorRepeatedFeeInsufficient(t *testing.T) { // We'll now modify the SendToSwitch method to return an error for the // outgoing channel to Son goku. This will be a fee related error, so // it should only cause the edge to be pruned after the second attempt. - dispatcher, ok := ctx.router.cfg.Payer.(*mockPaymentAttemptDispatcherOld) //nolint:lll + dispatcher, ok := ctx.router.cfg.Payer.(*mockPaymentAttemptDispatcherOld) //nolint:ll require.True(t, ok) dispatcher.setPaymentResult(func(firstHop lnwire.ShortChannelID) ( @@ -1300,7 +1300,7 @@ func TestUnknownErrorSource(t *testing.T) { // We'll modify the SendToSwitch method so that it simulates hop b as a // node that returns an unparsable failure if approached via the a->b // channel. - dispatcher, ok := ctx.router.cfg.Payer.(*mockPaymentAttemptDispatcherOld) //nolint:lll + dispatcher, ok := ctx.router.cfg.Payer.(*mockPaymentAttemptDispatcherOld) //nolint:ll require.True(t, ok) dispatcher.setPaymentResult(func(firstHop lnwire.ShortChannelID) ( @@ -1327,7 +1327,7 @@ func TestUnknownErrorSource(t *testing.T) { payment.paymentHash) // Next we modify payment result to return an unknown failure. - dispatcher, ok = ctx.router.cfg.Payer.(*mockPaymentAttemptDispatcherOld) //nolint:lll + dispatcher, ok = ctx.router.cfg.Payer.(*mockPaymentAttemptDispatcherOld) //nolint:ll require.True(t, ok) dispatcher.setPaymentResult(func(firstHop lnwire.ShortChannelID) ( @@ -2571,19 +2571,19 @@ func TestSendToRouteTempFailure(t *testing.T) { func TestNewRouteRequest(t *testing.T) { t.Parallel() - //nolint:lll + //nolint:ll source, err := route.NewVertexFromStr("0367cec75158a4129177bfb8b269cb586efe93d751b43800d456485e81c2620ca6") require.NoError(t, err) sourcePubkey, err := btcec.ParsePubKey(source[:]) require.NoError(t, err) - //nolint:lll + //nolint:ll v1, err := route.NewVertexFromStr("026c43a8ac1cd8519985766e90748e1e06871dab0ff6b8af27e8c1a61640481318") require.NoError(t, err) pubkey1, err := btcec.ParsePubKey(v1[:]) require.NoError(t, err) - //nolint:lll + //nolint:ll v2, err := route.NewVertexFromStr("03c19f0027ffbb0ae0e14a4d958788793f9d74e107462473ec0c3891e4feb12e99") require.NoError(t, err) pubkey2, err := btcec.ParsePubKey(v2[:]) diff --git a/sample-lnd.conf b/sample-lnd.conf index 4d3da37796..86ea824858 100644 --- a/sample-lnd.conf +++ b/sample-lnd.conf @@ -994,6 +994,11 @@ [logging] +; Whether to exclude the current build's commit hash from log lines. Note that +; the commit hash will not currently show up in all LND log lines as this new +; feature will take a few versions to propagate through the codebase. +; logging.no-commit-hash=false + ; Disable logging to stdout and stderror. ; logging.console.disable=false diff --git a/server.go b/server.go index d9e86db4b5..f8f8239ed6 100644 --- a/server.go +++ b/server.go @@ -572,7 +572,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, "aux controllers") } - //nolint:lll + //nolint:ll featureMgr, err := feature.NewManager(feature.Config{ NoTLVOnion: cfg.ProtocolOptions.LegacyOnion(), NoStaticRemoteKey: cfg.ProtocolOptions.NoStaticRemoteKey(), @@ -1109,7 +1109,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, RotateTicker: ticker.New(discovery.DefaultSyncerRotationInterval), HistoricalSyncTicker: ticker.New(cfg.HistoricalSyncInterval), NumActiveSyncers: cfg.NumGraphSyncPeers, - NoTimestampQueries: cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll + NoTimestampQueries: cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll MinimumBatchSize: 10, SubBatchDelay: cfg.Gossip.SubBatchDelay, IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters, @@ -1126,7 +1126,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, }, nodeKeyDesc) selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed()) - //nolint:lll + //nolint:ll s.localChanMgr = &localchans.Manager{ SelfPub: nodeKeyDesc.PubKey, DefaultRoutingPolicy: cc.RoutingPolicy, @@ -1245,7 +1245,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, }, ) - //nolint:lll + //nolint:ll s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{ ChainHash: *s.cfg.ActiveNetParams.GenesisHash, IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta, @@ -1442,7 +1442,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr, devCfg, reservationTimeout, zombieSweeperInterval) } - //nolint:lll + //nolint:ll s.fundingMgr, err = funding.NewFundingManager(funding.Config{ Dev: devCfg, NoWumboChans: !cfg.ProtocolOptions.Wumbo(), diff --git a/sqldb/config.go b/sqldb/config.go index 5bc807806a..24e58b498a 100644 --- a/sqldb/config.go +++ b/sqldb/config.go @@ -21,7 +21,7 @@ const ( // SqliteConfig holds all the config arguments needed to interact with our // sqlite DB. // -//nolint:lll +//nolint:ll type SqliteConfig struct { Timeout time.Duration `long:"timeout" description:"The time after which a database query should be timed out."` BusyTimeout time.Duration `long:"busytimeout" description:"The maximum amount of time to wait for a database connection to become available for a query."` @@ -32,7 +32,7 @@ type SqliteConfig struct { // PostgresConfig holds the postgres database configuration. // -//nolint:lll +//nolint:ll type PostgresConfig struct { Dsn string `long:"dsn" description:"Database connection string."` Timeout time.Duration `long:"timeout" description:"Database connection timeout. Set to zero to disable."` diff --git a/sqldb/postgres.go b/sqldb/postgres.go index 6a4123ed36..c855391574 100644 --- a/sqldb/postgres.go +++ b/sqldb/postgres.go @@ -9,7 +9,7 @@ import ( "time" pgx_migrate "github.com/golang-migrate/migrate/v4/database/pgx/v5" - _ "github.com/golang-migrate/migrate/v4/source/file" // Read migrations from files. // nolint:lll + _ "github.com/golang-migrate/migrate/v4/source/file" // Read migrations from files. // nolint:ll _ "github.com/jackc/pgx/v5" "github.com/lightningnetwork/lnd/sqldb/sqlc" ) diff --git a/sweep/aggregator.go b/sweep/aggregator.go index cd809e81a9..a0a1b0a540 100644 --- a/sweep/aggregator.go +++ b/sweep/aggregator.go @@ -218,7 +218,7 @@ func (b *BudgetAggregator) filterInputs(inputs InputsMap) InputsMap { continue } - //nolint:lll + //nolint:ll // Calculate the size if the input is included in the tx. // // NOTE: When including this input, we need to account the diff --git a/sweep/sweeper_test.go b/sweep/sweeper_test.go index 6d9c6c3d2e..2b61f67933 100644 --- a/sweep/sweeper_test.go +++ b/sweep/sweeper_test.go @@ -669,7 +669,7 @@ func TestSweepPendingInputs(t *testing.T) { Aggregator: aggregator, Publisher: publisher, GenSweepScript: func() fn.Result[lnwallet.AddrWithKey] { - //nolint:lll + //nolint:ll return fn.Ok(lnwallet.AddrWithKey{ DeliveryAddress: testPubKey.SerializeCompressed(), }) diff --git a/tools/.custom-gcl.yml b/tools/.custom-gcl.yml new file mode 100644 index 0000000000..dc91e4b164 --- /dev/null +++ b/tools/.custom-gcl.yml @@ -0,0 +1,4 @@ +version: v1.57.0 +plugins: + - module: 'github.com/lightningnetwork/lnd/tools/linters' + path: ./linters \ No newline at end of file diff --git a/tools/Dockerfile b/tools/Dockerfile index 47a081b683..f59c68cfb1 100644 --- a/tools/Dockerfile +++ b/tools/Dockerfile @@ -11,6 +11,8 @@ RUN cd /tmp \ && mkdir -p /tmp/build/.modcache \ && cd /tmp/tools \ && go install -trimpath github.com/golangci/golangci-lint/cmd/golangci-lint \ + && golangci-lint custom \ + && mv ./custom-gcl /usr/local/bin/custom-gcl \ && chmod -R 777 /tmp/build/ \ && git config --global --add safe.directory /build diff --git a/tools/linters/go.mod b/tools/linters/go.mod new file mode 100644 index 0000000000..b296832350 --- /dev/null +++ b/tools/linters/go.mod @@ -0,0 +1,15 @@ +module github.com/lightningnetwork/lnd/tools/linters + +go 1.22.6 + +require ( + github.com/golangci/plugin-module-register v0.1.1 + github.com/stretchr/testify v1.10.0 + golang.org/x/tools v0.27.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/tools/linters/go.sum b/tools/linters/go.sum new file mode 100644 index 0000000000..507c105870 --- /dev/null +++ b/tools/linters/go.sum @@ -0,0 +1,14 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golangci/plugin-module-register v0.1.1 h1:TCmesur25LnyJkpsVrupv1Cdzo+2f7zX0H6Jkw1Ol6c= +github.com/golangci/plugin-module-register v0.1.1/go.mod h1:TTpqoB6KkwOJMV8u7+NyXMrkwwESJLOkfl9TxR1DGFc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/tools v0.27.0 h1:qEKojBykQkQ4EynWy4S8Weg69NumxKdn40Fce3uc/8o= +golang.org/x/tools v0.27.0/go.mod h1:sUi0ZgbwW9ZPAq26Ekut+weQPR5eIM6GQLQ1Yjm1H0Q= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/tools/linters/ll.go b/tools/linters/ll.go new file mode 100644 index 0000000000..7170447dee --- /dev/null +++ b/tools/linters/ll.go @@ -0,0 +1,266 @@ +// The following code is based on code from GolangCI. +// Source: https://github.com/golangci-lint/pkg/golinters/lll/lll.go +// License: GNU + +package linters + +import ( + "bufio" + "errors" + "fmt" + "go/ast" + "go/token" + "os" + "path/filepath" + "regexp" + "strings" + "unicode/utf8" + + "github.com/golangci/plugin-module-register/register" + "golang.org/x/tools/go/analysis" +) + +const ( + linterName = "ll" + goCommentDirectivePrefix = "//go:" + + defaultMaxLineLen = 80 + defaultTabWidthInSpaces = 8 + defaultLogRegex = `^\s*.*(L|l)og\.` +) + +// LLConfig is the configuration for the ll linter. +type LLConfig struct { + LineLength int `json:"line-length"` + TabWidth int `json:"tab-width"` + LogRegex string `json:"log-regex"` +} + +// New creates a new LLPlugin from the given settings. It satisfies the +// signature required by the golangci-lint linter for plugins. +func New(settings any) (register.LinterPlugin, error) { + cfg, err := register.DecodeSettings[LLConfig](settings) + if err != nil { + return nil, err + } + + // Fill in default config values if they are not set. + if cfg.LineLength == 0 { + cfg.LineLength = defaultMaxLineLen + } + if cfg.TabWidth == 0 { + cfg.TabWidth = defaultTabWidthInSpaces + } + if cfg.LogRegex == "" { + cfg.LogRegex = defaultLogRegex + } + + return &LLPlugin{cfg: cfg}, nil +} + +// LLPlugin is a golangci-linter plugin that can be used to check that code line +// lengths do not exceed a certain limit. +type LLPlugin struct { + cfg LLConfig +} + +// BuildAnalyzers creates the analyzers for the ll linter. +// +// NOTE: This is part of the register.LinterPlugin interface. +func (l *LLPlugin) BuildAnalyzers() ([]*analysis.Analyzer, error) { + return []*analysis.Analyzer{ + { + Name: linterName, + Doc: "Reports long lines", + Run: l.run, + }, + }, nil +} + +// GetLoadMode returns the load mode for the ll linter. +// +// NOTE: This is part of the register.LinterPlugin interface. +func (l *LLPlugin) GetLoadMode() string { + return register.LoadModeSyntax +} + +func (l *LLPlugin) run(pass *analysis.Pass) (any, error) { + var ( + spaces = strings.Repeat(" ", l.cfg.TabWidth) + logRegex = regexp.MustCompile(l.cfg.LogRegex) + ) + + for _, f := range pass.Files { + fileName := getFileName(pass, f) + + issues, err := getLLLIssuesForFile( + fileName, l.cfg.LineLength, spaces, logRegex, + ) + if err != nil { + return nil, err + } + + file := pass.Fset.File(f.Pos()) + for _, issue := range issues { + pos := file.LineStart(issue.pos.Line) + + pass.Report(analysis.Diagnostic{ + Pos: pos, + End: 0, + Category: linterName, + Message: issue.text, + }) + } + + } + + return nil, nil +} + +type issue struct { + pos token.Position + text string +} + +func getLLLIssuesForFile(filename string, maxLineLen int, + tabSpaces string, logRegex *regexp.Regexp) ([]*issue, error) { + + f, err := os.Open(filename) + if err != nil { + return nil, fmt.Errorf("can't open file %s: %w", filename, err) + } + defer f.Close() + + var ( + res []*issue + lineNumber int + multiImportEnabled bool + multiLinedLog bool + ) + + // Scan over each line. + scanner := bufio.NewScanner(f) + for scanner.Scan() { + lineNumber++ + + // Replace all tabs with spaces. + line := scanner.Text() + line = strings.ReplaceAll(line, "\t", tabSpaces) + + // Ignore any //go: directives since these cant be wrapped onto + // a new line. + if strings.HasPrefix(line, goCommentDirectivePrefix) { + continue + } + + // We never want the linter to run on imports since these cannot + // be wrapped onto a new line. If this is a single line import + // we can skip the line entirely. If this is a multi-line import + // skip until the closing bracket. + // + // NOTE: We trim the line space around the line here purely for + // the purpose of being able to test this part of the linter + // without the risk of the `gosimports` tool reformatting the + // test case and removing the import. + if strings.HasPrefix(strings.TrimSpace(line), "import") { + multiImportEnabled = strings.HasSuffix(line, "(") + continue + } + + // If we have marked the start of a multi-line import, we should + // skip until the closing bracket of the import block. + if multiImportEnabled { + if line == ")" { + multiImportEnabled = false + } + + continue + } + + // Check if the line matches the log pattern. + if logRegex.MatchString(line) { + multiLinedLog = !strings.HasSuffix(line, ")") + continue + } + + if multiLinedLog { + // Check for the end of a multiline log call. + if strings.HasSuffix(line, ")") { + multiLinedLog = false + } + + continue + } + + // Otherwise, we can check the length of the line and report if + // it exceeds the maximum line length. + lineLen := utf8.RuneCountInString(line) + if lineLen > maxLineLen { + res = append(res, &issue{ + pos: token.Position{ + Filename: filename, + Line: lineNumber, + }, + text: fmt.Sprintf("the line is %d "+ + "characters long, which exceeds the "+ + "maximum of %d characters.", lineLen, + maxLineLen), + }) + } + } + + if err := scanner.Err(); err != nil { + if errors.Is(err, bufio.ErrTooLong) && + maxLineLen < bufio.MaxScanTokenSize { + + // scanner.Scan() might fail if the line is longer than + // bufio.MaxScanTokenSize. In the case where the + // specified maxLineLen is smaller than + // bufio.MaxScanTokenSize we can return this line as a + // long line instead of returning an error. The reason + // for this change is that this case might happen with + // autogenerated files. The go-bindata tool for instance + // might generate a file with a very long line. In this + // case, as it's an auto generated file, the warning + // returned by lll will be ignored. + // But if we return a linter error here, and this error + // happens for an autogenerated file the error will be + // discarded (fine), but all the subsequent errors for + // lll will be discarded for other files, and we'll miss + // legit error. + res = append(res, &issue{ + pos: token.Position{ + Filename: filename, + Line: lineNumber, + Column: 1, + }, + text: fmt.Sprintf("line is more than "+ + "%d characters", + bufio.MaxScanTokenSize), + }) + } else { + return nil, fmt.Errorf("can't scan file %s: %w", + filename, err) + } + } + + return res, nil +} + +func getFileName(pass *analysis.Pass, file *ast.File) string { + fileName := pass.Fset.PositionFor(file.Pos(), true).Filename + ext := filepath.Ext(fileName) + if ext != "" && ext != ".go" { + // The position has been adjusted to a non-go file, + // revert to original file. + position := pass.Fset.PositionFor(file.Pos(), false) + fileName = position.Filename + } + + return fileName +} + +func init() { + // Register the linter with the plugin module register. + register.Plugin(linterName, New) +} diff --git a/tools/linters/ll_test.go b/tools/linters/ll_test.go new file mode 100644 index 0000000000..1ab4ae3524 --- /dev/null +++ b/tools/linters/ll_test.go @@ -0,0 +1,155 @@ +package linters + +import ( + "os" + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestGetLLLIssuesForFile tests the line-too-long linter. +// +//nolint:ll +func TestGetLLLIssuesForFile(t *testing.T) { + // Test data + testCases := []struct { + name string + content string + logRegex string + expectedIssue []string + }{ + { + name: "Single long line", + content: ` + fmt.Println("This is a very long line that exceeds the maximum length and should be flagged by the linter.")`, + logRegex: defaultLogRegex, + expectedIssue: []string{ + "the line is 140 characters long, which " + + "exceeds the maximum of 80 characters.", + }, + }, + { + name: "Multiple long lines", + content: ` + fmt.Println("This is a very long line that exceeds the maximum length and should be flagged by the linter.") + fmt.Println("This is a another very long line that exceeds the maximum length and should be flagged by the linter.")`, + logRegex: defaultLogRegex, + expectedIssue: []string{ + "the line is 140 characters long, which " + + "exceeds the maximum of 80 characters.", + "the line is 148 characters long, which " + + "exceeds the maximum of 80 characters.", + }, + }, + { + name: "Short lines", + logRegex: defaultLogRegex, + content: ` + fmt.Println("Short line")`, + }, + { + name: "Directive ignored", + logRegex: defaultLogRegex, + content: `//go:generate something very very very very very very very very very long and complex here wowowow`, + }, + { + name: "Long single line import", + logRegex: defaultLogRegex, + content: `import "github.com/lightningnetwork/lnd/lnrpc/walletrpc/more/more/more/more/more/more/ok/that/is/enough"`, + }, + { + name: "Multi-line import", + logRegex: defaultLogRegex, + content: ` + import ( + "os" + "fmt" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc/more/ok/that/is/enough" + )`, + }, + { + name: "Long single line log", + logRegex: defaultLogRegex, + content: ` + log.Infof("This is a very long log line but since it is a log line, it should be skipped by the linter."), + rpcLog.Info("Another long log line with a slightly different name and should still be skipped")`, + }, + { + name: "Long single line log followed by a non-log line", + logRegex: defaultLogRegex, + content: ` + log.Infof("This is a very long log line but since it is a log line, it should be skipped by the linter.") + fmt.Println("This is a very long line that exceeds the maximum length and should be flagged by the linter.")`, + expectedIssue: []string{ + "the line is 140 characters long, which " + + "exceeds the maximum of 80 characters.", + }, + }, + { + name: "Multi-line log", + logRegex: defaultLogRegex, + content: ` + log.Infof("This is a very long log line but + since it is a log line, it + should be skipped by the linter.")`, + }, + { + name: "Multi-line log followed by a non-log line", + logRegex: defaultLogRegex, + content: ` + log.Infof("This is a very long log line but + since it is a log line, it + should be skipped by the linter.") + fmt.Println("This is a very long line that + exceeds the maximum length and + should be flagged by the linter.")`, + expectedIssue: []string{ + "the line is 82 characters long, which " + + "exceeds the maximum of 80 characters.", + }, + }, + { + name: "Only skip 'S' logs", + logRegex: `^\s*.*(L|l)og\.(Info|Debug|Trace|Warn|Error|Critical)S\(`, + content: ` + log.Infof("A long log line but it is not an S log and so should be caught") + log.InfoS("This is a very long log line but + since it is an 'S' log line, it + should be skipped by the linter.") + log.TraceS("Another S log that should be skipped by the linter")`, + expectedIssue: []string{ + "the line is 107 characters long, which " + + "exceeds the maximum of 80 characters.", + }, + }, + } + + tabSpaces := strings.Repeat(" ", defaultTabWidthInSpaces) + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + logRegex := regexp.MustCompile(tc.logRegex) + + // Write content to a temporary file. + tmpFile := t.TempDir() + "/test.go" + err := os.WriteFile(tmpFile, []byte(tc.content), 0644) + require.NoError(t, err) + + // Run the linter on the file. + issues, err := getLLLIssuesForFile( + tmpFile, defaultMaxLineLen, tabSpaces, logRegex, + ) + require.NoError(t, err) + + require.Len(t, issues, len(tc.expectedIssue)) + + for i, issue := range issues { + require.Equal( + t, tc.expectedIssue[i], issue.text, + ) + } + }) + } +} diff --git a/watchtower/wtclient/backup_task_internal_test.go b/watchtower/wtclient/backup_task_internal_test.go index 8eb0ba9fbe..7eb34f6e37 100644 --- a/watchtower/wtclient/backup_task_internal_test.go +++ b/watchtower/wtclient/backup_task_internal_test.go @@ -166,7 +166,7 @@ func genTaskTest( PkScript: pkScript, }, WitnessScript: scriptTree.RevocationLeaf.Script, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll HashType: txscript.SigHashDefault, ControlBlock: ctrlBytes, } @@ -217,7 +217,7 @@ func genTaskTest( PubKey: toRemotePK, }, WitnessScript: scriptTree.SettleLeaf.Script, - SignMethod: input.TaprootScriptSpendSignMethod, //nolint:lll + SignMethod: input.TaprootScriptSpendSignMethod, //nolint:ll Output: &wire.TxOut{ Value: toRemoteAmt, PkScript: pkScript, diff --git a/zpay32/invoice_test.go b/zpay32/invoice_test.go index de59422aba..a4753431e7 100644 --- a/zpay32/invoice_test.go +++ b/zpay32/invoice_test.go @@ -180,7 +180,7 @@ func init() { // Invoice object, and that reencoding the decoded invoice gets us back to the // original encoded string. // -//nolint:lll +//nolint:ll func TestDecodeEncode(t *testing.T) { t.Parallel() @@ -966,7 +966,7 @@ func TestNewInvoice(t *testing.T) { ) }, valid: true, - //nolint:lll + //nolint:ll encodedInvoice: "lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdq5xysxxatsyp3k7enxv4js5fdqqqqq2qqqqqpgqyzqqqqqqqqqqqqyqqqqqqqqqqqvsqqqqlnxy0ffrlt2y2jgtzw89kgr3zg4dlwtlfycn3yuek8x5eucnuchqps82xf0m2u6sx5wnjw7xxgnxz5kf09quqsv5zvkgj7d5kpzttp4qz7q5qsyqcyq5pzq2feycsemrh7wvendc4kw3tsmkt25a36ev6kfehrv7ecfkrp5zs9q5zqxqspqtr4avek5quzjn427asptzews5wrczfhychr2sq6ue9phmn35tjqcrspqgpsgpgxquyqjzstpsxsu59zqqqqqpqqqqqqyqq2qqqqqqqqqqqqqqqqqqqqqqqqpgqqqqk8t6endgpc99824amqzk9japgu8synwf3wx4qp4ej2r0h8rghypsqsygpf8ynzr8vwleenxdhzke69wrwed2nk8t9n2e8xudnm8pxcvxs2q5qsyqcyq5y4rdlhtf84f8rgdj34275juwls2ftxtcfh035863q3p9k6s94hpxhdmzfn5gxpsazdznxs56j4vt3fdhe00g9v2l3szher50hp4xlggqkxf77f", }, }