From acbcb771af3baa2c511e16850b7701c33474e6ab Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Fri, 29 Nov 2024 10:39:32 +0200 Subject: [PATCH 01/13] tools/linters: Add copied golangci-lint `lll` linter code In this commit, we copy the implementation of the golangci-lint lll linter which we currently use in our CI flow during the `make lint` check. This commit copies the code mostly as is (the only exception being the line which trims white space before checking if a line starts with "import"), and formats it to fit our codebase guidelines. A test is also added so that we can be sure that the following commits which adjust the implementation have the intended results. The custom linter is put into its own module as this is requied by the `golangci-lint custom` when building the custom linter binary which includes the plugin. --- tools/linters/go.mod | 44 ++++++++ tools/linters/go.sum | 90 ++++++++++++++++ tools/linters/ll.go | 219 +++++++++++++++++++++++++++++++++++++++ tools/linters/ll_test.go | 97 +++++++++++++++++ 4 files changed, 450 insertions(+) create mode 100644 tools/linters/go.mod create mode 100644 tools/linters/go.sum create mode 100644 tools/linters/ll.go create mode 100644 tools/linters/ll_test.go diff --git a/tools/linters/go.mod b/tools/linters/go.mod new file mode 100644 index 00000000000..dd0b3dda8f2 --- /dev/null +++ b/tools/linters/go.mod @@ -0,0 +1,44 @@ +module github.com/lightningnetwork/lnd/tools/linters + +go 1.22.6 + +require ( + github.com/golangci/golangci-lint v1.62.2 + 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/fatih/color v1.18.0 // indirect + github.com/fsnotify/fsnotify v1.5.4 // indirect + github.com/go-viper/mapstructure/v2 v2.2.1 // indirect + github.com/hashicorp/go-version v1.7.0 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/ldez/gomoddirectives v0.2.4 // indirect + github.com/magiconair/properties v1.8.6 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/pelletier/go-toml v1.9.5 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.5.0 // indirect + github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/viper v1.12.0 // indirect + github.com/stretchr/objx v0.5.2 // indirect + github.com/subosito/gotenv v1.4.1 // indirect + golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect + golang.org/x/mod v0.22.0 // indirect + golang.org/x/sync v0.9.0 // indirect + golang.org/x/sys v0.27.0 // indirect + golang.org/x/text v0.18.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v2 v2.4.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 00000000000..7f4b0737b89 --- /dev/null +++ b/tools/linters/go.sum @@ -0,0 +1,90 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +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/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= +github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= +github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= +github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/golangci/golangci-lint v1.62.2 h1:b8K5K9PN+rZN1+mKLtsZHz2XXS9aYKzQ9i25x3Qnxxw= +github.com/golangci/golangci-lint v1.62.2/go.mod h1:ILWWyeFUrctpHVGMa1dg2xZPKoMUTc5OIMgW7HZr34g= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY= +github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/ldez/gomoddirectives v0.2.4 h1:j3YjBIjEBbqZ0NKtBNzr8rtMHTOrLPeiwTkfUJZ3alg= +github.com/ldez/gomoddirectives v0.2.4/go.mod h1:oWu9i62VcQDYp9EQ0ONTfqLNh+mDLWWDO+SO0qSQw5g= +github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= +github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= +github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +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/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= +github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= +github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.12.0 h1:CZ7eSOd3kZoaYDLbXnmzgQI5RlciuXBMA+18HwHRfZQ= +github.com/spf13/viper v1.12.0/go.mod h1:b6COn30jlNxbm/V2IqWiNWkJ+vZNiMNksliPCiuKtSI= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= +github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= +golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk= +golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY= +golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= +golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ= +golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= +golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +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/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +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 00000000000..80f571c8f79 --- /dev/null +++ b/tools/linters/ll.go @@ -0,0 +1,219 @@ +// 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/token" + "os" + "path/filepath" + "strings" + "sync" + "unicode/utf8" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/result" + "golang.org/x/tools/go/analysis" +) + +const ( + linterName = "lll" + goCommentDirectivePrefix = "//go:" +) + +// New creates a new lll linter from the given settings. It satisfies the +// signature required by the golangci-lint linter for plugins. +func New(settings *config.LllSettings) *goanalysis.Linter { + var ( + mu sync.Mutex + resIssues []goanalysis.Issue + ) + + analyzer := &analysis.Analyzer{ + Name: linterName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (any, error) { + issues, err := runLll(pass, settings) + if err != nil { + return nil, err + } + + if len(issues) == 0 { + return nil, nil + } + + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() + + return nil, nil + }, + } + + return goanalysis.NewLinter( + linterName, "Reports long lines", + []*analysis.Analyzer{analyzer}, nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} + +func runLll(pass *analysis.Pass, settings *config.LllSettings) ( + []goanalysis.Issue, error) { + + var ( + fileNames = getFileNames(pass) + spaces = strings.Repeat(" ", settings.TabWidth) + issues []goanalysis.Issue + ) + + for _, f := range fileNames { + lintIssues, err := getLLLIssuesForFile( + f, settings.LineLength, spaces, + ) + if err != nil { + return nil, err + } + + for i := range lintIssues { + issues = append(issues, goanalysis.NewIssue( + &lintIssues[i], pass, + )) + } + } + + return issues, nil +} + +func getLLLIssuesForFile(filename string, maxLineLen int, + tabSpaces string) ([]result.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 []result.Issue + lineNumber int + multiImportEnabled 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 + } + + // 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, result.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), + FromLinter: linterName, + }) + } + } + + 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, result.Issue{ + Pos: token.Position{ + Filename: filename, + Line: lineNumber, + Column: 1, + }, + Text: fmt.Sprintf("line is more than "+ + "%d characters", + bufio.MaxScanTokenSize), + FromLinter: linterName, + }) + } else { + return nil, fmt.Errorf("can't scan file %s: %w", + filename, err) + } + } + + return res, nil +} + +func getFileNames(pass *analysis.Pass) []string { + var fileNames []string + for _, f := range pass.Files { + fileName := pass.Fset.PositionFor(f.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(f.Pos(), false) + fileName = position.Filename + } + fileNames = append(fileNames, fileName) + } + return fileNames +} diff --git a/tools/linters/ll_test.go b/tools/linters/ll_test.go new file mode 100644 index 00000000000..238435531c4 --- /dev/null +++ b/tools/linters/ll_test.go @@ -0,0 +1,97 @@ +package linters + +import ( + "os" + "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 + 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.")`, + 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.")`, + 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", + content: ` + fmt.Println("Short line")`, + }, + { + name: "Directive ignored", + content: `//go:generate something very very very very very very very very very long and complex here wowowow`, + }, + { + name: "Long single line import", + content: `import "github.com/lightningnetwork/lnd/lnrpc/walletrpc/more/more/more/more/more/more/ok/that/is/enough"`, + }, + { + name: "Multi-line import", + content: ` + import ( + "os" + "fmt" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc/more/ok/that/is/enough" + )`, + }, + { + name: "Long single line log", + content: ` + log.Infof("This is a very long log line but since it is a log line, it should be skipped by the linter.")`, + expectedIssue: []string{ + "the line is 121 characters long, which " + + "exceeds the maximum of 80 characters.", + }, + }, + } + + tabSpaces := strings.Repeat(" ", 8) + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // 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, 80, tabSpaces, + ) + require.NoError(t, err) + + require.Len(t, issues, len(tc.expectedIssue)) + + for i, issue := range issues { + require.Equal(t, tc.expectedIssue[i], issue.Text) + } + }) + } +} From 9637a8132e1fc69208c4a81c929ff12894e3f683 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Fri, 29 Nov 2024 11:01:27 +0200 Subject: [PATCH 02/13] tools/linters: convert to LinterPlugin implementation This commit introduces the `LLPlugin` type and converts the existing lll code such that the LLPlugin implements the register.LinterPlugin interface. This will allow us to plug it into golangci-linter as a plugin. --- tools/linters/go.mod | 31 +------- tools/linters/go.sum | 80 +------------------ tools/linters/ll.go | 166 ++++++++++++++++++++++----------------- tools/linters/ll_test.go | 4 +- 4 files changed, 100 insertions(+), 181 deletions(-) diff --git a/tools/linters/go.mod b/tools/linters/go.mod index dd0b3dda8f2..b2968323505 100644 --- a/tools/linters/go.mod +++ b/tools/linters/go.mod @@ -3,42 +3,13 @@ module github.com/lightningnetwork/lnd/tools/linters go 1.22.6 require ( - github.com/golangci/golangci-lint v1.62.2 + 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/fatih/color v1.18.0 // indirect - github.com/fsnotify/fsnotify v1.5.4 // indirect - github.com/go-viper/mapstructure/v2 v2.2.1 // indirect - github.com/hashicorp/go-version v1.7.0 // indirect - github.com/hashicorp/hcl v1.0.0 // indirect - github.com/ldez/gomoddirectives v0.2.4 // indirect - github.com/magiconair/properties v1.8.6 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mitchellh/go-homedir v1.1.0 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/pelletier/go-toml v1.9.5 // indirect - github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rogpeppe/go-internal v1.13.1 // indirect - github.com/sirupsen/logrus v1.9.3 // indirect - github.com/spf13/afero v1.11.0 // indirect - github.com/spf13/cast v1.5.0 // indirect - github.com/spf13/jwalterweatherman v1.1.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/spf13/viper v1.12.0 // indirect - github.com/stretchr/objx v0.5.2 // indirect - github.com/subosito/gotenv v1.4.1 // indirect - golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect - golang.org/x/mod v0.22.0 // indirect - golang.org/x/sync v0.9.0 // indirect - golang.org/x/sys v0.27.0 // indirect - golang.org/x/text v0.18.0 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/tools/linters/go.sum b/tools/linters/go.sum index 7f4b0737b89..507c1058708 100644 --- a/tools/linters/go.sum +++ b/tools/linters/go.sum @@ -1,90 +1,14 @@ -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= -github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= -github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= -github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= -github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= -github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= -github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= -github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/golangci/golangci-lint v1.62.2 h1:b8K5K9PN+rZN1+mKLtsZHz2XXS9aYKzQ9i25x3Qnxxw= -github.com/golangci/golangci-lint v1.62.2/go.mod h1:ILWWyeFUrctpHVGMa1dg2xZPKoMUTc5OIMgW7HZr34g= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY= -github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/ldez/gomoddirectives v0.2.4 h1:j3YjBIjEBbqZ0NKtBNzr8rtMHTOrLPeiwTkfUJZ3alg= -github.com/ldez/gomoddirectives v0.2.4/go.mod h1:oWu9i62VcQDYp9EQ0ONTfqLNh+mDLWWDO+SO0qSQw5g= -github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= -github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= -github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= -github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +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/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= -github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= -github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= -github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= -github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= -github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.12.0 h1:CZ7eSOd3kZoaYDLbXnmzgQI5RlciuXBMA+18HwHRfZQ= -github.com/spf13/viper v1.12.0/go.mod h1:b6COn30jlNxbm/V2IqWiNWkJ+vZNiMNksliPCiuKtSI= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= -github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= -golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk= -golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY= -golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= -golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= -golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ= -golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= -golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= -golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 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/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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 index 80f571c8f79..2aff7e19b73 100644 --- a/tools/linters/ll.go +++ b/tools/linters/ll.go @@ -8,91 +8,113 @@ import ( "bufio" "errors" "fmt" + "go/ast" "go/token" "os" "path/filepath" "strings" - "sync" "unicode/utf8" - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" + "github.com/golangci/plugin-module-register/register" "golang.org/x/tools/go/analysis" ) const ( - linterName = "lll" + linterName = "ll" goCommentDirectivePrefix = "//go:" + + defaultMaxLineLen = 80 + defaultTabWidthInSpaces = 8 ) -// New creates a new lll linter from the given settings. It satisfies the +// LLConfig is the configuration for the ll linter. +type LLConfig struct { + LineLength int `json:"line-length"` + TabWidth int `json:"tab-width"` +} + +// New creates a new LLPlugin from the given settings. It satisfies the // signature required by the golangci-lint linter for plugins. -func New(settings *config.LllSettings) *goanalysis.Linter { - var ( - mu sync.Mutex - resIssues []goanalysis.Issue - ) +func New(settings any) (register.LinterPlugin, error) { + cfg, err := register.DecodeSettings[LLConfig](settings) + if err != nil { + return nil, err + } - analyzer := &analysis.Analyzer{ - Name: linterName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues, err := runLll(pass, 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 len(issues) == 0 { - return nil, nil - } + return &LLPlugin{cfg: cfg}, nil +} - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() +// 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 +} - return nil, nil +// 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 +} - return goanalysis.NewLinter( - linterName, "Reports long lines", - []*analysis.Analyzer{analyzer}, nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) +// 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 runLll(pass *analysis.Pass, settings *config.LllSettings) ( - []goanalysis.Issue, error) { +func (l *LLPlugin) run(pass *analysis.Pass) (any, error) { + var spaces = strings.Repeat(" ", l.cfg.TabWidth) - var ( - fileNames = getFileNames(pass) - spaces = strings.Repeat(" ", settings.TabWidth) - issues []goanalysis.Issue - ) + for _, f := range pass.Files { + fileName := getFileName(pass, f) - for _, f := range fileNames { - lintIssues, err := getLLLIssuesForFile( - f, settings.LineLength, spaces, + issues, err := getLLLIssuesForFile( + fileName, l.cfg.LineLength, spaces, ) if err != nil { return nil, err } - for i := range lintIssues { - issues = append(issues, goanalysis.NewIssue( - &lintIssues[i], pass, - )) + 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 issues, nil + return nil, nil +} + +type issue struct { + pos token.Position + text string } func getLLLIssuesForFile(filename string, maxLineLen int, - tabSpaces string) ([]result.Issue, error) { + tabSpaces string) ([]*issue, error) { f, err := os.Open(filename) if err != nil { @@ -101,7 +123,7 @@ func getLLLIssuesForFile(filename string, maxLineLen int, defer f.Close() var ( - res []result.Issue + res []*issue lineNumber int multiImportEnabled bool ) @@ -149,16 +171,15 @@ func getLLLIssuesForFile(filename string, maxLineLen int, // it exceeds the maximum line length. lineLen := utf8.RuneCountInString(line) if lineLen > maxLineLen { - res = append(res, result.Issue{ - Pos: token.Position{ + res = append(res, &issue{ + pos: token.Position{ Filename: filename, Line: lineNumber, }, - Text: fmt.Sprintf("the line is %d "+ + text: fmt.Sprintf("the line is %d "+ "characters long, which exceeds the "+ "maximum of %d characters.", lineLen, maxLineLen), - FromLinter: linterName, }) } } @@ -182,16 +203,15 @@ func getLLLIssuesForFile(filename string, maxLineLen int, // discarded (fine), but all the subsequent errors for // lll will be discarded for other files, and we'll miss // legit error. - res = append(res, result.Issue{ - Pos: token.Position{ + res = append(res, &issue{ + pos: token.Position{ Filename: filename, Line: lineNumber, Column: 1, }, - Text: fmt.Sprintf("line is more than "+ + text: fmt.Sprintf("line is more than "+ "%d characters", bufio.MaxScanTokenSize), - FromLinter: linterName, }) } else { return nil, fmt.Errorf("can't scan file %s: %w", @@ -202,18 +222,20 @@ func getLLLIssuesForFile(filename string, maxLineLen int, return res, nil } -func getFileNames(pass *analysis.Pass) []string { - var fileNames []string - for _, f := range pass.Files { - fileName := pass.Fset.PositionFor(f.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(f.Pos(), false) - fileName = position.Filename - } - fileNames = append(fileNames, fileName) +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 fileNames + + 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 index 238435531c4..9c3b7b44a2e 100644 --- a/tools/linters/ll_test.go +++ b/tools/linters/ll_test.go @@ -90,7 +90,9 @@ func TestGetLLLIssuesForFile(t *testing.T) { require.Len(t, issues, len(tc.expectedIssue)) for i, issue := range issues { - require.Equal(t, tc.expectedIssue[i], issue.Text) + require.Equal( + t, tc.expectedIssue[i], issue.text, + ) } }) } From bd55b2795bd2887906db513e50d32d4437ea3809 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Fri, 29 Nov 2024 11:08:19 +0200 Subject: [PATCH 03/13] tools/linters: ignore log lines This commit adds a feature to our custom lll linter which will ignore log lines (both single and multi-lined log lines) for the lll linter. --- tools/linters/ll.go | 35 +++++++++++++++--- tools/linters/ll_test.go | 78 ++++++++++++++++++++++++++++++++++------ 2 files changed, 97 insertions(+), 16 deletions(-) diff --git a/tools/linters/ll.go b/tools/linters/ll.go index 2aff7e19b73..7170447dee2 100644 --- a/tools/linters/ll.go +++ b/tools/linters/ll.go @@ -12,6 +12,7 @@ import ( "go/token" "os" "path/filepath" + "regexp" "strings" "unicode/utf8" @@ -25,12 +26,14 @@ const ( 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"` + 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 @@ -48,6 +51,9 @@ func New(settings any) (register.LinterPlugin, error) { if cfg.TabWidth == 0 { cfg.TabWidth = defaultTabWidthInSpaces } + if cfg.LogRegex == "" { + cfg.LogRegex = defaultLogRegex + } return &LLPlugin{cfg: cfg}, nil } @@ -79,13 +85,16 @@ func (l *LLPlugin) GetLoadMode() string { } func (l *LLPlugin) run(pass *analysis.Pass) (any, error) { - var spaces = strings.Repeat(" ", l.cfg.TabWidth) + 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, + fileName, l.cfg.LineLength, spaces, logRegex, ) if err != nil { return nil, err @@ -114,7 +123,7 @@ type issue struct { } func getLLLIssuesForFile(filename string, maxLineLen int, - tabSpaces string) ([]*issue, error) { + tabSpaces string, logRegex *regexp.Regexp) ([]*issue, error) { f, err := os.Open(filename) if err != nil { @@ -126,6 +135,7 @@ func getLLLIssuesForFile(filename string, maxLineLen int, res []*issue lineNumber int multiImportEnabled bool + multiLinedLog bool ) // Scan over each line. @@ -167,6 +177,21 @@ func getLLLIssuesForFile(filename string, maxLineLen int, 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) diff --git a/tools/linters/ll_test.go b/tools/linters/ll_test.go index 9c3b7b44a2e..1ab4ae35244 100644 --- a/tools/linters/ll_test.go +++ b/tools/linters/ll_test.go @@ -2,6 +2,7 @@ package linters import ( "os" + "regexp" "strings" "testing" @@ -16,12 +17,14 @@ func TestGetLLLIssuesForFile(t *testing.T) { 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.", @@ -32,6 +35,7 @@ func TestGetLLLIssuesForFile(t *testing.T) { 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.", @@ -40,20 +44,24 @@ func TestGetLLLIssuesForFile(t *testing.T) { }, }, { - name: "Short lines", + name: "Short lines", + logRegex: defaultLogRegex, content: ` fmt.Println("Short line")`, }, { - name: "Directive ignored", - content: `//go:generate something very very very very very very very very very long and complex here wowowow`, + 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", - content: `import "github.com/lightningnetwork/lnd/lnrpc/walletrpc/more/more/more/more/more/more/ok/that/is/enough"`, + 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", + name: "Multi-line import", + logRegex: defaultLogRegex, content: ` import ( "os" @@ -62,20 +70,68 @@ func TestGetLLLIssuesForFile(t *testing.T) { )`, }, { - name: "Long single line log", + 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.")`, + 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 121 characters long, which " + + "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(" ", 8) + 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) @@ -83,7 +139,7 @@ func TestGetLLLIssuesForFile(t *testing.T) { // Run the linter on the file. issues, err := getLLLIssuesForFile( - tmpFile, 80, tabSpaces, + tmpFile, defaultMaxLineLen, tabSpaces, logRegex, ) require.NoError(t, err) From 88f5369066f5ab9affeec139a2b6c5e48883c64b Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Fri, 29 Nov 2024 11:12:00 +0200 Subject: [PATCH 04/13] tools+.: add custom linter configuration file Add this file both to the main LND directory so that devs can use it for local linter runs and also add it to the `tools` directory so that the docker environment used to run the linter in CI has access to it. A custom linter binary can be built via `golangci-lint custom`. This will pull in and register all the plugins listed in the new config file when building the new binary. The new binary can then be run using `custom-gcl run`. --- .custom-gcl.yml | 4 ++++ Makefile | 2 +- tools/.custom-gcl.yml | 4 ++++ tools/Dockerfile | 2 ++ 4 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 .custom-gcl.yml create mode 100644 tools/.custom-gcl.yml diff --git a/.custom-gcl.yml b/.custom-gcl.yml new file mode 100644 index 00000000000..6ca10094a07 --- /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/Makefile b/Makefile index ccf95cb902f..ee9b1de51fc 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/tools/.custom-gcl.yml b/tools/.custom-gcl.yml new file mode 100644 index 00000000000..dc91e4b1641 --- /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 47a081b6837..f59c68cfb11 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 From ab7aae07085ec244f7888e990e8d8cc6ae6dfa83 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Fri, 29 Nov 2024 11:16:13 +0200 Subject: [PATCH 05/13] multi: rename nolint:lll to nolint:ll Find and replace all nolint instances refering to the `lll` linter and replace with `ll` which is the name of our custom version of the `lll` linter which can be used to ignore log lines during linting. The next commit will do the configuration of the custom linter and disable the default one. --- build/config.go | 6 +- build/config_dev.go | 2 +- build/config_prod.go | 2 +- chainntnfs/bitcoindnotify/bitcoind.go | 4 +- chainntnfs/btcdnotify/btcd.go | 2 +- chainntnfs/neutrinonotify/neutrino.go | 2 +- chainreg/chainregistry.go | 2 +- chanacceptor/rpcacceptor.go | 2 +- channeldb/channel.go | 2 +- channeldb/migration/lnwire21/onion_error.go | 2 +- channeldb/migration32/migration_test.go | 14 ++-- channeldb/payment_control.go | 2 +- cmd/commands/walletrpc_active.go | 2 +- config.go | 6 +- contractcourt/breach_arbitrator.go | 18 ++--- contractcourt/briefcase.go | 32 ++++----- contractcourt/chain_arbitrator.go | 2 +- contractcourt/chain_watcher.go | 2 +- contractcourt/channel_arbitrator.go | 10 +-- contractcourt/channel_arbitrator_test.go | 10 +-- contractcourt/config.go | 2 +- .../htlc_incoming_contest_resolver.go | 2 +- contractcourt/htlc_success_resolver.go | 4 +- contractcourt/htlc_timeout_resolver.go | 6 +- contractcourt/htlc_timeout_resolver_test.go | 8 +-- contractcourt/utxonursery.go | 6 +- discovery/gossiper_test.go | 2 +- funding/batch.go | 2 +- funding/commitment_type_negotiation_test.go | 2 +- funding/manager.go | 2 +- graph/builder.go | 4 +- graph/db/graph.go | 12 ++-- graph/db/graph_test.go | 8 +-- htlcswitch/hop/iterator.go | 4 +- htlcswitch/hop/iterator_test.go | 2 +- htlcswitch/hop/payload_test.go | 2 +- htlcswitch/link.go | 10 +-- htlcswitch/link_test.go | 2 +- htlcswitch/test_utils.go | 2 +- input/size.go | 4 +- input/size_test.go | 26 +++---- invoices/invoiceregistry.go | 2 +- invoices/sql_store.go | 2 +- itest/lnd_channel_backup_test.go | 2 +- itest/lnd_channel_force_close_test.go | 4 +- itest/lnd_estimate_route_fee_test.go | 2 +- itest/lnd_funding_test.go | 2 +- itest/lnd_hold_persistence_test.go | 2 +- itest/lnd_max_htlcs_test.go | 2 +- itest/lnd_multi-hop-error-propagation_test.go | 4 +- itest/lnd_sweep_test.go | 2 +- kvdb/etcd/config.go | 2 +- kvdb/postgres/config.go | 2 +- kvdb/sqlite/config.go | 2 +- lncfg/autopilot.go | 2 +- lncfg/bitcoind.go | 2 +- lncfg/btcd.go | 2 +- lncfg/caches.go | 2 +- lncfg/chain.go | 2 +- lncfg/db.go | 2 +- lncfg/dev_integration.go | 2 +- lncfg/fee.go | 2 +- lncfg/gossip.go | 2 +- lncfg/healthcheck.go | 2 +- lncfg/htlcswitch.go | 2 +- lncfg/invoices.go | 2 +- lncfg/monitoring_on.go | 2 +- lncfg/neutrino.go | 2 +- lncfg/pprof.go | 2 +- lncfg/protocol.go | 2 +- lncfg/protocol_integration.go | 2 +- lncfg/protocol_legacy_on.go | 2 +- lncfg/remotesigner.go | 2 +- lncfg/routing.go | 4 +- lncfg/rpcmiddleware.go | 2 +- lncfg/sweeper.go | 2 +- lncfg/tor.go | 2 +- lncfg/watchtower.go | 2 +- lncfg/workers.go | 2 +- lncfg/wtclient.go | 2 +- lnrpc/devrpc/dev_server.go | 2 +- lnrpc/invoicesrpc/addinvoice.go | 4 +- lnrpc/routerrpc/config.go | 2 +- lnrpc/routerrpc/forward_interceptor.go | 2 +- lnrpc/routerrpc/router_server.go | 6 +- lnrpc/routerrpc/router_server_test.go | 2 +- lnrpc/routerrpc/routing_config.go | 6 +- lnrpc/walletrpc/walletkit_server.go | 2 +- lntest/rpc/lnd.go | 2 +- lntest/rpc/router.go | 6 +- lntest/rpc/signer.go | 4 +- lntest/rpc/wallet_kit.go | 10 +-- lntest/utils.go | 4 +- lnwallet/btcwallet/btcwallet.go | 4 +- lnwallet/btcwallet/psbt_test.go | 2 +- lnwallet/chancloser/chancloser.go | 6 +- lnwallet/channel.go | 72 +++++++++---------- lnwallet/channel_test.go | 8 +-- lnwallet/commitment.go | 2 +- lnwallet/reservation.go | 2 +- lnwallet/wallet.go | 4 +- lnwire/channel_update_2.go | 2 +- lnwire/features.go | 2 +- lnwire/lnwire_test.go | 14 ++-- lnwire/onion_error.go | 2 +- lnwire/update_add_htlc.go | 2 +- log.go | 2 +- peer/brontide.go | 2 +- protofsm/state_machine.go | 18 ++--- record/blinded_data_test.go | 4 +- routing/blindedpath/blinded_path.go | 2 +- routing/blindedpath/blinded_path_test.go | 2 +- routing/pathfind.go | 2 +- routing/pathfind_test.go | 4 +- routing/router.go | 2 +- routing/router_test.go | 12 ++-- server.go | 10 +-- sqldb/config.go | 4 +- sqldb/postgres.go | 2 +- sweep/aggregator.go | 2 +- sweep/sweeper_test.go | 2 +- .../wtclient/backup_task_internal_test.go | 4 +- zpay32/invoice_test.go | 4 +- 123 files changed, 286 insertions(+), 286 deletions(-) diff --git a/build/config.go b/build/config.go index 87b9ab9aec3..e937614165d 100644 --- a/build/config.go +++ b/build/config.go @@ -23,7 +23,7 @@ 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."` @@ -41,7 +41,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 +89,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 09df7d61831..efa8104c912 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 67a43f8ac0e..5f2ebffa489 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/chainntnfs/bitcoindnotify/bitcoind.go b/chainntnfs/bitcoindnotify/bitcoind.go index 91c38d8d6eb..fc20fbb8578 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 ff91b5aee65..c3a40a00bfb 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 7b93bcd80db..784f55a4750 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 e30eafc6771..ec17c09f13a 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 6ec78789549..2b30dedc0d4 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 200dc39ff53..9ca57312aa1 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 2b03732a2fe..e9d1f8f0cb1 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 703c32a72c4..73c1cd4b845 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 6e688cf5128..2369d2f7e6d 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 bb5982c78b9..b098c40b0c6 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 04a4917658e..f206b43a50c 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 89c596f7aef..d59829b5e5f 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 cd4fd90ccbb..a0908ea3fa9 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 78a79a3c2f1..6d9b30d2086 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 808f41f2eee..e79c8d546b7 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 3a7c2cfe93c..319b437e4e3 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 3b367bf548b..92ad608eb96 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 b5466c6e212..7331ceb91f5 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 e7e21fff688..73841eb88c5 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 159b642dde8..b2716ad3056 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 e7ab4216917..9954c3c0dbc 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 92cc587fc13..f3f23c385c7 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 afd6c18c995..aef906a0ad3 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 056069940a1..85a4e0657ea 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/funding/batch.go b/funding/batch.go index fc050cdf53e..d95941e8476 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 b47e4a1f2f6..b9e9f59f0f0 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 075be127880..c8a54d9588d 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 8c2ba2e3b82..c0133e02ece 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 fc1b26ad0fd..a6b23e64b35 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 82c4965fba5..8a02f24ff41 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 83b5e3f52ac..2cf2adb543a 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 fff9ae17d22..ab435a98684 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 7398813a3e5..bd0081cb937 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 b8f1ce8edd6..60062862ef5 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 4ee538a581d..80632b07e9b 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 0f4b28fb829..2123465884f 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 5d4b15ec16d..f1c56ff8263 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 33f9ff53973..2fba2c7b2e8 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 9d54b6ad8d2..f5a6c6a95fc 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 e848297d9ca..59321e0395e 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 5ae0df9584d..5140de5056d 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 6d028040123..81bdfad4316 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 8ed0be2725f..ffff5accaac 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 7daf95960d6..54180abf57a 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 f1c2a7d8236..8bb84b2a300 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 971537adf43..ea023190f57 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 6fe34fdcfcd..853dd4a9787 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 17e0910b63b..099014aff0c 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 e8cbaf98c5e..0136ab98fd1 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 0c2959d16a9..b587d13390e 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 f60abcfc009..b79bc36e637 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 60728fb26af..3736048b678 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 b574aef1692..bbf95b19157 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 dece35bf04c..3609bd995af 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 5f257d8a1f3..2457bb1d04a 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 e84cadb7b80..36586ff3a6f 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 1f7e0ae35d6..3d45bb78b1b 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 0f0227e01f4..bbbc0803728 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 200ae9e8198..c96e58022e5 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 a2c82a7aa80..fbe5aae4027 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 9a140368796..7904eaceaa4 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 4b553e35476..613b189915f 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 7922885240c..9d54c699411 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 12c59e2b212..f76342baf60 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 e46c292dc09..d0f508ecf55 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 e136b2a8eb0..edb754b1c7c 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 5852d032e08..ed8d4578aea 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 e9f32d9dfb9..a062c669762 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 a575fb7f38b..9b8fd4ebdf7 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 24ca61cfbd4..02479a85e8e 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 f8c38d147a4..2b21683f640 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 173785e01a9..e957f207d61 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 037102c69b7..6b8339312e3 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 4f043128a63..f41d7b09cd7 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 851d24e9280..463a95b9568 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 30961f063d7..3735cd30f8f 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 d4e2c6b27ed..fd97146a635 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/lnrpc/devrpc/dev_server.go b/lnrpc/devrpc/dev_server.go index ebd4591abd8..60f30dd7ed5 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 59f7df610bb..114e3571888 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 20e3fa09bf8..044c2436fc7 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 7bc366dce0c..9da831ac04a 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 a4112ba646e..7f1a7edf073 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 22f210ee992..a4047977ec2 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 83699a27f72..f113db94ea2 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 3b16f4da719..c6dec6fbd56 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/rpc/lnd.go b/lntest/rpc/lnd.go index 1657caac8dd..c578d052584 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 707c43a11d8..ccc7b0ef62a 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 79a680c2b80..62b9ac06d14 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 67a2f5fcaa2..38545fc0cfe 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 feaae57e7b6..c1ae8cd238e 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 ee62bdb2771..5d28574cbe5 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 3f04bc7a8e4..694a8c04f11 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 662a38aa769..17112b29e0b 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 54ef442a9b5..7f70e600c64 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 e3b7d07f90c..f7ecd322772 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 36ff75edeb4..8b364a01df0 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 4c4f58f8be0..fd35d950768 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 a9018437d5c..ad6354e2e8a 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 5c6d240958c..b41f2f29f19 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 eb00d869067..73a1684edb0 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 6b9630f58ad..952e90a7e67 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 8d54a98951f..5f05e1ef9f1 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 5251748f0bc..4873cd84b32 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 795fb4d729b..a3efd033351 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 40d3f94c43b..6bc49445eee 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 ecbd7483478..b71d5efe42e 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 7de8fa295eb..bc1230be8b9 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 a1f9db7b6b9..5c16751858b 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 35db89afb78..0020f381caf 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 db474e1e802..8e40c5bc4b4 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 81708d3930d..da29c79a25a 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 b92aa150230..9eabe0b2ae6 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 db72bf266c2..2923f1fb90a 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/server.go b/server.go index d9e86db4b56..f8f8239ed67 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 5bc807806a7..24e58b498a4 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 6a4123ed36e..c8553915741 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 cd809e81a96..a0a1b0a5406 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 6d9c6c3d2e5..2b61f679334 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/watchtower/wtclient/backup_task_internal_test.go b/watchtower/wtclient/backup_task_internal_test.go index 8eb0ba9fbea..7eb34f6e376 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 de59422aba3..a4753431e7f 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", }, } From c5d849e044d43cc1fd7138a784074c8bc4469143 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Fri, 29 Nov 2024 11:27:03 +0200 Subject: [PATCH 06/13] .golangci: Replace lll with custom ll --- .gitignore | 3 +++ .golangci.yml | 27 +++++++++++++++++++-------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 6be439ed7e9..5ddd602d3d0 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 8114945c6f9..f8560a9f5ef 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: From a04f8dfd4f3afb4a2c64b5d2e2319bbb4e874a2b Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Thu, 21 Nov 2024 20:06:40 +0200 Subject: [PATCH 07/13] lnd: pass ctx to rest proxy --- lnd.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lnd.go b/lnd.go index f511811950b..77456fa1532 100644 --- a/lnd.go +++ b/lnd.go @@ -379,7 +379,7 @@ 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) @@ -921,7 +921,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 +949,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) From efe08b836ed9b1d9a2dfbeb85463a5ba48468597 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Wed, 27 Nov 2024 09:55:17 +0200 Subject: [PATCH 08/13] docs: add structured logging docs in code formatting rules doc --- docs/code_formatting_rules.md | 89 +++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/docs/code_formatting_rules.md b/docs/code_formatting_rules.md index 731bb64069f..ad58745d732 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 From 755ad4944015396e7e9b1593a832f76a155ceaa0 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Wed, 27 Nov 2024 10:03:10 +0200 Subject: [PATCH 09/13] build: Append commit hash to the main LND context It can be disabled via the new `logging.no-commit-hash` config option. --- build/config.go | 5 +++-- build/version.go | 29 +++++++++++++++++++++++++++++ lnd.go | 13 +++++++++---- lntest/node/config.go | 1 + sample-lnd.conf | 5 +++++ 5 files changed, 47 insertions(+), 6 deletions(-) diff --git a/build/config.go b/build/config.go index e937614165d..74a23756634 100644 --- a/build/config.go +++ b/build/config.go @@ -25,8 +25,9 @@ const ( // //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. diff --git a/build/version.go b/build/version.go index 1238d35a2b8..632ebafce42 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/lnd.go b/lnd.go index 77456fa1532..5fa84e30b98 100644 --- a/lnd.go +++ b/lnd.go @@ -155,6 +155,15 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, } }() + 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(format string, args ...interface{}) error { ltndLog.Errorf("Shutting down because error in main "+ "method: "+format, args...) @@ -188,10 +197,6 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, strings.Title(BitcoinChainName), network, ) - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - // Enable http profiling server if requested. if cfg.Pprof.Profile != "" { // Create the http handler. diff --git a/lntest/node/config.go b/lntest/node/config.go index 1e8129e7d80..32f24395b6b 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/sample-lnd.conf b/sample-lnd.conf index 4d3da37796d..86ea8248587 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 From 32fbea2f85f4e6de6e99fab3d69442f20075cbce Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Wed, 27 Nov 2024 10:12:11 +0200 Subject: [PATCH 10/13] lnd: use structured logs in `mkErr` helper --- lnd.go | 89 ++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 52 insertions(+), 37 deletions(-) diff --git a/lnd.go b/lnd.go index 5fa84e30b98..5507b2b8085 100644 --- a/lnd.go +++ b/lnd.go @@ -8,6 +8,7 @@ import ( "context" "errors" "fmt" + "log/slog" "net" "net/http" "net/http/pprof" @@ -164,10 +165,21 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, err) } - mkErr := func(format string, args ...interface{}) error { - ltndLog.Errorf("Shutting down because error in main "+ - "method: "+format, args...) - return fmt.Errorf(format, args...) + 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. @@ -253,7 +265,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() { @@ -266,7 +278,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{ @@ -291,7 +303,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() @@ -308,8 +320,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() @@ -328,7 +344,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() @@ -369,14 +385,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 @@ -387,7 +403,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, 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() @@ -442,7 +458,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, 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 @@ -455,7 +471,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, ltndLog.Infof("%v, exiting", err) return nil case err != nil: - return mkErr("unable to open databases: %v", err) + return mkErr("unable to open databases", err) } defer cleanUp() @@ -465,7 +481,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() @@ -474,7 +490,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() @@ -487,7 +503,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 { @@ -520,7 +536,7 @@ 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() { @@ -540,7 +556,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{ @@ -581,12 +597,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) } } @@ -609,7 +625,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 @@ -620,22 +636,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 @@ -646,10 +661,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() @@ -657,7 +672,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 @@ -666,7 +681,7 @@ 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, "+ @@ -697,7 +712,7 @@ 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 "+ @@ -724,7 +739,7 @@ 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)!", @@ -753,7 +768,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 @@ -767,13 +782,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() } From ed4279b6f330bea5a70b2256e8bdab528107a164 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Wed, 27 Nov 2024 10:15:07 +0200 Subject: [PATCH 11/13] lnd: update Main logs to use structured logging --- lnd.go | 80 ++++++++++++++++++++++++++++++---------------------------- 1 file changed, 42 insertions(+), 38 deletions(-) diff --git a/lnd.go b/lnd.go index 5507b2b8085..d00294bc272 100644 --- a/lnd.go +++ b/lnd.go @@ -149,7 +149,7 @@ 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) @@ -183,9 +183,11 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, } // 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 { @@ -205,9 +207,9 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, network = "signet" } - ltndLog.Infof("Active chain: %v (network=%v)", - strings.Title(BitcoinChainName), network, - ) + ltndLog.InfoS(ctx, "Network Info", + "active_chain", strings.Title(BitcoinChainName), + "network", network) // Enable http profiling server if requested. if cfg.Pprof.Profile != "" { @@ -233,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{ @@ -244,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) } }() @@ -256,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) } }() } @@ -420,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, @@ -435,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 @@ -454,21 +456,23 @@ 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", 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) + ltndLog.InfoS(ctx, "Exiting due to BuildDatabase error", + slog.Any("err", err)) return nil case err != nil: return mkErr("unable to open databases", err) @@ -512,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) } } @@ -541,8 +545,8 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, } defer func() { if err := torController.Stop(); err != nil { - ltndLog.Errorf("error stopping tor "+ - "controller: %v", err) + ltndLog.ErrorS(ctx, "Error stopping tor "+ + "controller", err) } }() } @@ -684,8 +688,8 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, 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 @@ -715,9 +719,9 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, "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 @@ -742,8 +746,8 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, 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 @@ -757,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) } }() From 8862ce99d5f6517d75387d522bb2be2bd6fd164f Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Wed, 27 Nov 2024 10:15:30 +0200 Subject: [PATCH 12/13] lnd: use errors.Is for error comparison --- lnd.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lnd.go b/lnd.go index d00294bc272..2b46e83c937 100644 --- a/lnd.go +++ b/lnd.go @@ -470,7 +470,7 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg, dbs, cleanUp, err := implCfg.DatabaseBuilder.BuildDatabase(ctx) switch { - case err == channeldb.ErrDryRunMigrationOK: + case errors.Is(err, channeldb.ErrDryRunMigrationOK): ltndLog.InfoS(ctx, "Exiting due to BuildDatabase error", slog.Any("err", err)) return nil From afbb9aa41c9354ad00882226568141702eedaf89 Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Wed, 27 Nov 2024 10:19:14 +0200 Subject: [PATCH 13/13] docs: add release note entry --- docs/release-notes/release-notes-0.19.0.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/release-notes-0.19.0.md b/docs/release-notes/release-notes-0.19.0.md index 377255bbf98..f3685519ed8 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`