diff --git a/.golangci.yml b/.golangci.yml index 122f14206bd..4b7d8bac9a9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,30 +1,52 @@ +run: + tests: false + timeout: 5m + linters: - enable: - - asciicheck - - bodyclose - - depguard - - dogsled - - dupl - - errcheck - - exportloopref - - goconst - - gofmt - - goimports - - revive - - gosec - - gosimple - - govet - - ineffassign - - misspell - - nakedret - - nolintlint - - prealloc - - staticcheck - # - structcheck // to be fixed by golangci-lint - - stylecheck + enable-all: true + disable: + - containedctx + - contextcheck + - cyclop + - dupword + - errname + - errorlint + - exhaustive + - exhaustivestruct + - exhaustruct + - forbidigo + - forcetypeassert + - funlen + - gochecknoglobals + - gochecknoinits + - gocognit + - gocyclo + - godox + - goerr113 + - golint + - gomnd + - gomoddirectives + - ifshort + - interfacebloat + - interfacer + - ireturn + - lll + - maintidx + - maligned + - nestif + - nilnil + - nlreturn + - nonamedreturns + - nosnakecase + - predeclared + - tagliatelle - typecheck - - unconvert - - unused + - varnamelen + - wrapcheck + - wsl + - scopelint + - unparam + - revive issues: exclude-rules: @@ -42,8 +64,6 @@ issues: linters-settings: dogsled: max-blank-identifiers: 3 - golint: - min-confidence: 0 goconst: ignore-tests: true maligned: diff --git a/Makefile b/Makefile index e7334d30da2..fbaf8553c5a 100644 --- a/Makefile +++ b/Makefile @@ -232,6 +232,11 @@ lint: @go run github.com/golangci/golangci-lint/cmd/golangci-lint@latest run .PHONY: lint +lint-format: + @go run github.com/golangci/golangci-lint/cmd/golangci-lint@latest run --fix + @go run mvdan.cc/gofumpt -l -w ./.. +.PHONY: lint-format + vulncheck: @go run golang.org/x/vuln/cmd/govulncheck@latest ./... .PHONY: vulncheck diff --git a/abci/client/client.go b/abci/client/client.go index 587dfd04bcd..1573a0f2fce 100644 --- a/abci/client/client.go +++ b/abci/client/client.go @@ -28,22 +28,22 @@ type Client interface { // TODO: remove as each method now returns an error Error() error // TODO: remove as this is not implemented - Flush(context.Context) error - Echo(context.Context, string) (*types.EchoResponse, error) + Flush(ctx context.Context) error + Echo(ctx context.Context, echo string) (*types.EchoResponse, error) // FIXME: All other operations are run synchronously and rely // on the caller to dictate concurrency (i.e. run a go routine), // with the exception of `CheckTxAsync` which we maintain // for the v0 mempool. We should explore refactoring the // mempool to remove this vestige behavior. - SetResponseCallback(Callback) - CheckTxAsync(context.Context, *types.CheckTxRequest) (*ReqRes, error) + SetResponseCallback(cb Callback) + CheckTxAsync(ctx context.Context, req *types.CheckTxRequest) (*ReqRes, error) } //---------------------------------------- // NewClient returns a new ABCI client of the specified transport type. -// It returns an error if the transport is not "socket" or "grpc" +// It returns an error if the transport is not "socket" or "grpc". func NewClient(addr, transport string, mustConnect bool) (client Client, err error) { switch transport { case "socket": diff --git a/abci/client/errors.go b/abci/client/errors.go index f8bfb1ec8bc..fdace3d3139 100644 --- a/abci/client/errors.go +++ b/abci/client/errors.go @@ -6,7 +6,7 @@ import ( "github.com/cometbft/cometbft/abci/types" ) -// ErrUnknownAbciTransport is returned when trying to create a client with an invalid transport option +// ErrUnknownAbciTransport is returned when trying to create a client with an invalid transport option. type ErrUnknownAbciTransport struct { Transport string } diff --git a/abci/client/grpc_client.go b/abci/client/grpc_client.go index 87e4e9b1032..2aada664593 100644 --- a/abci/client/grpc_client.go +++ b/abci/client/grpc_client.go @@ -7,18 +7,17 @@ import ( "sync" "time" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - "github.com/cometbft/cometbft/abci/types" cmtnet "github.com/cometbft/cometbft/internal/net" "github.com/cometbft/cometbft/internal/service" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" ) var _ Client = (*grpcClient)(nil) // A stripped copy of the remoteClient that makes -// synchronous calls using grpc +// synchronous calls using grpc. type grpcClient struct { service.BaseService mustConnect bool diff --git a/abci/client/grpc_client_test.go b/abci/client/grpc_client_test.go index 568a6aabec4..8fb87bce29e 100644 --- a/abci/client/grpc_client_test.go +++ b/abci/client/grpc_client_test.go @@ -8,19 +8,14 @@ import ( "testing" "time" + abciserver "github.com/cometbft/cometbft/abci/server" + "github.com/cometbft/cometbft/abci/types" + cmtnet "github.com/cometbft/cometbft/internal/net" + "github.com/cometbft/cometbft/libs/log" "github.com/stretchr/testify/require" - - "google.golang.org/grpc" - "golang.org/x/net/context" - + "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - - cmtnet "github.com/cometbft/cometbft/internal/net" - "github.com/cometbft/cometbft/libs/log" - - abciserver "github.com/cometbft/cometbft/abci/server" - "github.com/cometbft/cometbft/abci/types" ) func TestGRPC(t *testing.T) { @@ -77,7 +72,6 @@ func TestGRPC(t *testing.T) { time.Sleep(time.Second * 1) // Wait for a bit to allow counter overflow }() } - } } diff --git a/abci/client/mocks/client.go b/abci/client/mocks/client.go index 6c408e8da21..e18372bde4e 100644 --- a/abci/client/mocks/client.go +++ b/abci/client/mocks/client.go @@ -19,9 +19,9 @@ type Client struct { mock.Mock } -// ApplySnapshotChunk provides a mock function with given fields: _a0, _a1 -func (_m *Client) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error) { - ret := _m.Called(_a0, _a1) +// ApplySnapshotChunk provides a mock function with given fields: ctx, req +func (_m *Client) ApplySnapshotChunk(ctx context.Context, req *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ApplySnapshotChunk") @@ -30,10 +30,10 @@ func (_m *Client) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnapshotC var r0 *v1.ApplySnapshotChunkResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ApplySnapshotChunkRequest) *v1.ApplySnapshotChunkResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ApplySnapshotChunkResponse) @@ -41,7 +41,7 @@ func (_m *Client) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnapshotC } if rf, ok := ret.Get(1).(func(context.Context, *v1.ApplySnapshotChunkRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -49,9 +49,9 @@ func (_m *Client) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnapshotC return r0, r1 } -// CheckTx provides a mock function with given fields: _a0, _a1 -func (_m *Client) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1.CheckTxResponse, error) { - ret := _m.Called(_a0, _a1) +// CheckTx provides a mock function with given fields: ctx, req +func (_m *Client) CheckTx(ctx context.Context, req *v1.CheckTxRequest) (*v1.CheckTxResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for CheckTx") @@ -60,10 +60,10 @@ func (_m *Client) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1.Chec var r0 *v1.CheckTxResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) (*v1.CheckTxResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) *v1.CheckTxResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.CheckTxResponse) @@ -71,7 +71,7 @@ func (_m *Client) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1.Chec } if rf, ok := ret.Get(1).(func(context.Context, *v1.CheckTxRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -79,9 +79,9 @@ func (_m *Client) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1.Chec return r0, r1 } -// CheckTxAsync provides a mock function with given fields: _a0, _a1 -func (_m *Client) CheckTxAsync(_a0 context.Context, _a1 *v1.CheckTxRequest) (*abcicli.ReqRes, error) { - ret := _m.Called(_a0, _a1) +// CheckTxAsync provides a mock function with given fields: ctx, req +func (_m *Client) CheckTxAsync(ctx context.Context, req *v1.CheckTxRequest) (*abcicli.ReqRes, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for CheckTxAsync") @@ -90,10 +90,10 @@ func (_m *Client) CheckTxAsync(_a0 context.Context, _a1 *v1.CheckTxRequest) (*ab var r0 *abcicli.ReqRes var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) (*abcicli.ReqRes, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) *abcicli.ReqRes); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*abcicli.ReqRes) @@ -101,7 +101,7 @@ func (_m *Client) CheckTxAsync(_a0 context.Context, _a1 *v1.CheckTxRequest) (*ab } if rf, ok := ret.Get(1).(func(context.Context, *v1.CheckTxRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -109,9 +109,9 @@ func (_m *Client) CheckTxAsync(_a0 context.Context, _a1 *v1.CheckTxRequest) (*ab return r0, r1 } -// Commit provides a mock function with given fields: _a0, _a1 -func (_m *Client) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.CommitResponse, error) { - ret := _m.Called(_a0, _a1) +// Commit provides a mock function with given fields: ctx, req +func (_m *Client) Commit(ctx context.Context, req *v1.CommitRequest) (*v1.CommitResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Commit") @@ -120,10 +120,10 @@ func (_m *Client) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.Commit var r0 *v1.CommitResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.CommitRequest) (*v1.CommitResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.CommitRequest) *v1.CommitResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.CommitResponse) @@ -131,7 +131,7 @@ func (_m *Client) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.Commit } if rf, ok := ret.Get(1).(func(context.Context, *v1.CommitRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -139,9 +139,9 @@ func (_m *Client) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.Commit return r0, r1 } -// Echo provides a mock function with given fields: _a0, _a1 -func (_m *Client) Echo(_a0 context.Context, _a1 string) (*v1.EchoResponse, error) { - ret := _m.Called(_a0, _a1) +// Echo provides a mock function with given fields: ctx, echo +func (_m *Client) Echo(ctx context.Context, echo string) (*v1.EchoResponse, error) { + ret := _m.Called(ctx, echo) if len(ret) == 0 { panic("no return value specified for Echo") @@ -150,10 +150,10 @@ func (_m *Client) Echo(_a0 context.Context, _a1 string) (*v1.EchoResponse, error var r0 *v1.EchoResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, string) (*v1.EchoResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, echo) } if rf, ok := ret.Get(0).(func(context.Context, string) *v1.EchoResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, echo) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.EchoResponse) @@ -161,7 +161,7 @@ func (_m *Client) Echo(_a0 context.Context, _a1 string) (*v1.EchoResponse, error } if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, echo) } else { r1 = ret.Error(1) } @@ -187,9 +187,9 @@ func (_m *Client) Error() error { return r0 } -// ExtendVote provides a mock function with given fields: _a0, _a1 -func (_m *Client) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error) { - ret := _m.Called(_a0, _a1) +// ExtendVote provides a mock function with given fields: ctx, req +func (_m *Client) ExtendVote(ctx context.Context, req *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ExtendVote") @@ -198,10 +198,10 @@ func (_m *Client) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest) (*v var r0 *v1.ExtendVoteResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ExtendVoteRequest) *v1.ExtendVoteResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ExtendVoteResponse) @@ -209,7 +209,7 @@ func (_m *Client) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest) (*v } if rf, ok := ret.Get(1).(func(context.Context, *v1.ExtendVoteRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -217,9 +217,9 @@ func (_m *Client) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest) (*v return r0, r1 } -// FinalizeBlock provides a mock function with given fields: _a0, _a1 -func (_m *Client) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error) { - ret := _m.Called(_a0, _a1) +// FinalizeBlock provides a mock function with given fields: ctx, req +func (_m *Client) FinalizeBlock(ctx context.Context, req *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for FinalizeBlock") @@ -228,10 +228,10 @@ func (_m *Client) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockReques var r0 *v1.FinalizeBlockResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.FinalizeBlockRequest) *v1.FinalizeBlockResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.FinalizeBlockResponse) @@ -239,7 +239,7 @@ func (_m *Client) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockReques } if rf, ok := ret.Get(1).(func(context.Context, *v1.FinalizeBlockRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -247,9 +247,9 @@ func (_m *Client) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockReques return r0, r1 } -// Flush provides a mock function with given fields: _a0 -func (_m *Client) Flush(_a0 context.Context) error { - ret := _m.Called(_a0) +// Flush provides a mock function with given fields: ctx +func (_m *Client) Flush(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Flush") @@ -257,7 +257,7 @@ func (_m *Client) Flush(_a0 context.Context) error { var r0 error if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(_a0) + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -265,9 +265,9 @@ func (_m *Client) Flush(_a0 context.Context) error { return r0 } -// Info provides a mock function with given fields: _a0, _a1 -func (_m *Client) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoResponse, error) { - ret := _m.Called(_a0, _a1) +// Info provides a mock function with given fields: ctx, req +func (_m *Client) Info(ctx context.Context, req *v1.InfoRequest) (*v1.InfoResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Info") @@ -276,10 +276,10 @@ func (_m *Client) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoRespon var r0 *v1.InfoResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.InfoRequest) (*v1.InfoResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.InfoRequest) *v1.InfoResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.InfoResponse) @@ -287,7 +287,7 @@ func (_m *Client) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoRespon } if rf, ok := ret.Get(1).(func(context.Context, *v1.InfoRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -295,9 +295,9 @@ func (_m *Client) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoRespon return r0, r1 } -// InitChain provides a mock function with given fields: _a0, _a1 -func (_m *Client) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) (*v1.InitChainResponse, error) { - ret := _m.Called(_a0, _a1) +// InitChain provides a mock function with given fields: ctx, req +func (_m *Client) InitChain(ctx context.Context, req *v1.InitChainRequest) (*v1.InitChainResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for InitChain") @@ -306,10 +306,10 @@ func (_m *Client) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) (*v1. var r0 *v1.InitChainResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.InitChainRequest) (*v1.InitChainResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.InitChainRequest) *v1.InitChainResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.InitChainResponse) @@ -317,7 +317,7 @@ func (_m *Client) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) (*v1. } if rf, ok := ret.Get(1).(func(context.Context, *v1.InitChainRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -343,9 +343,9 @@ func (_m *Client) IsRunning() bool { return r0 } -// ListSnapshots provides a mock function with given fields: _a0, _a1 -func (_m *Client) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error) { - ret := _m.Called(_a0, _a1) +// ListSnapshots provides a mock function with given fields: ctx, req +func (_m *Client) ListSnapshots(ctx context.Context, req *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ListSnapshots") @@ -354,10 +354,10 @@ func (_m *Client) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsReques var r0 *v1.ListSnapshotsResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ListSnapshotsRequest) *v1.ListSnapshotsResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ListSnapshotsResponse) @@ -365,7 +365,7 @@ func (_m *Client) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsReques } if rf, ok := ret.Get(1).(func(context.Context, *v1.ListSnapshotsRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -373,9 +373,9 @@ func (_m *Client) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsReques return r0, r1 } -// LoadSnapshotChunk provides a mock function with given fields: _a0, _a1 -func (_m *Client) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error) { - ret := _m.Called(_a0, _a1) +// LoadSnapshotChunk provides a mock function with given fields: ctx, req +func (_m *Client) LoadSnapshotChunk(ctx context.Context, req *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for LoadSnapshotChunk") @@ -384,10 +384,10 @@ func (_m *Client) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapshotChu var r0 *v1.LoadSnapshotChunkResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.LoadSnapshotChunkRequest) *v1.LoadSnapshotChunkResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.LoadSnapshotChunkResponse) @@ -395,7 +395,7 @@ func (_m *Client) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapshotChu } if rf, ok := ret.Get(1).(func(context.Context, *v1.LoadSnapshotChunkRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -403,9 +403,9 @@ func (_m *Client) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapshotChu return r0, r1 } -// OfferSnapshot provides a mock function with given fields: _a0, _a1 -func (_m *Client) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error) { - ret := _m.Called(_a0, _a1) +// OfferSnapshot provides a mock function with given fields: ctx, req +func (_m *Client) OfferSnapshot(ctx context.Context, req *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for OfferSnapshot") @@ -414,10 +414,10 @@ func (_m *Client) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotReques var r0 *v1.OfferSnapshotResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.OfferSnapshotRequest) *v1.OfferSnapshotResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.OfferSnapshotResponse) @@ -425,7 +425,7 @@ func (_m *Client) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotReques } if rf, ok := ret.Get(1).(func(context.Context, *v1.OfferSnapshotRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -474,9 +474,9 @@ func (_m *Client) OnStop() { _m.Called() } -// PrepareProposal provides a mock function with given fields: _a0, _a1 -func (_m *Client) PrepareProposal(_a0 context.Context, _a1 *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error) { - ret := _m.Called(_a0, _a1) +// PrepareProposal provides a mock function with given fields: ctx, req +func (_m *Client) PrepareProposal(ctx context.Context, req *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for PrepareProposal") @@ -485,10 +485,10 @@ func (_m *Client) PrepareProposal(_a0 context.Context, _a1 *v1.PrepareProposalRe var r0 *v1.PrepareProposalResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.PrepareProposalRequest) *v1.PrepareProposalResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.PrepareProposalResponse) @@ -496,7 +496,7 @@ func (_m *Client) PrepareProposal(_a0 context.Context, _a1 *v1.PrepareProposalRe } if rf, ok := ret.Get(1).(func(context.Context, *v1.PrepareProposalRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -504,9 +504,9 @@ func (_m *Client) PrepareProposal(_a0 context.Context, _a1 *v1.PrepareProposalRe return r0, r1 } -// ProcessProposal provides a mock function with given fields: _a0, _a1 -func (_m *Client) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error) { - ret := _m.Called(_a0, _a1) +// ProcessProposal provides a mock function with given fields: ctx, req +func (_m *Client) ProcessProposal(ctx context.Context, req *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ProcessProposal") @@ -515,10 +515,10 @@ func (_m *Client) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessProposalRe var r0 *v1.ProcessProposalResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ProcessProposalRequest) *v1.ProcessProposalResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ProcessProposalResponse) @@ -526,7 +526,7 @@ func (_m *Client) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessProposalRe } if rf, ok := ret.Get(1).(func(context.Context, *v1.ProcessProposalRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -534,9 +534,9 @@ func (_m *Client) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessProposalRe return r0, r1 } -// Query provides a mock function with given fields: _a0, _a1 -func (_m *Client) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.QueryResponse, error) { - ret := _m.Called(_a0, _a1) +// Query provides a mock function with given fields: ctx, req +func (_m *Client) Query(ctx context.Context, req *v1.QueryRequest) (*v1.QueryResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Query") @@ -545,10 +545,10 @@ func (_m *Client) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.QueryRes var r0 *v1.QueryResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.QueryRequest) (*v1.QueryResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.QueryRequest) *v1.QueryResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.QueryResponse) @@ -556,7 +556,7 @@ func (_m *Client) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.QueryRes } if rf, ok := ret.Get(1).(func(context.Context, *v1.QueryRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -602,14 +602,14 @@ func (_m *Client) Reset() error { return r0 } -// SetLogger provides a mock function with given fields: _a0 -func (_m *Client) SetLogger(_a0 log.Logger) { - _m.Called(_a0) +// SetLogger provides a mock function with given fields: l +func (_m *Client) SetLogger(l log.Logger) { + _m.Called(l) } -// SetResponseCallback provides a mock function with given fields: _a0 -func (_m *Client) SetResponseCallback(_a0 abcicli.Callback) { - _m.Called(_a0) +// SetResponseCallback provides a mock function with given fields: cb +func (_m *Client) SetResponseCallback(cb abcicli.Callback) { + _m.Called(cb) } // Start provides a mock function with given fields: @@ -666,9 +666,9 @@ func (_m *Client) String() string { return r0 } -// VerifyVoteExtension provides a mock function with given fields: _a0, _a1 -func (_m *Client) VerifyVoteExtension(_a0 context.Context, _a1 *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error) { - ret := _m.Called(_a0, _a1) +// VerifyVoteExtension provides a mock function with given fields: ctx, req +func (_m *Client) VerifyVoteExtension(ctx context.Context, req *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for VerifyVoteExtension") @@ -677,10 +677,10 @@ func (_m *Client) VerifyVoteExtension(_a0 context.Context, _a1 *v1.VerifyVoteExt var r0 *v1.VerifyVoteExtensionResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.VerifyVoteExtensionRequest) *v1.VerifyVoteExtensionResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.VerifyVoteExtensionResponse) @@ -688,7 +688,7 @@ func (_m *Client) VerifyVoteExtension(_a0 context.Context, _a1 *v1.VerifyVoteExt } if rf, ok := ret.Get(1).(func(context.Context, *v1.VerifyVoteExtensionRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } diff --git a/abci/client/socket_client_test.go b/abci/client/socket_client_test.go index 943ad117eba..e0213689fe4 100644 --- a/abci/client/socket_client_test.go +++ b/abci/client/socket_client_test.go @@ -9,14 +9,13 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abcicli "github.com/cometbft/cometbft/abci/client" "github.com/cometbft/cometbft/abci/server" "github.com/cometbft/cometbft/abci/types" cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/internal/service" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCalls(t *testing.T) { diff --git a/abci/cmd/abci-cli/abci-cli.go b/abci/cmd/abci-cli/abci-cli.go index f291019975d..470b27a138f 100644 --- a/abci/cmd/abci-cli/abci-cli.go +++ b/abci/cmd/abci-cli/abci-cli.go @@ -9,11 +9,6 @@ import ( "os" "strings" - "github.com/spf13/cobra" - - cmtos "github.com/cometbft/cometbft/internal/os" - "github.com/cometbft/cometbft/libs/log" - abcicli "github.com/cometbft/cometbft/abci/client" "github.com/cometbft/cometbft/abci/example/kvstore" "github.com/cometbft/cometbft/abci/server" @@ -21,28 +16,31 @@ import ( "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/abci/version" crypto "github.com/cometbft/cometbft/api/cometbft/crypto/v1" + cmtos "github.com/cometbft/cometbft/internal/os" + "github.com/cometbft/cometbft/libs/log" + "github.com/spf13/cobra" ) -// client is a global variable so it can be reused by the console +// client is a global variable so it can be reused by the console. var ( client abcicli.Client logger log.Logger ) -// flags +// flags. var ( - // global + // global. flagAddress string flagAbci string flagVerbose bool // for the println output flagLogLevel string // for the logger - // query + // query. flagPath string flagHeight int flagProve bool - // kvstore + // kvstore. flagPersist string ) @@ -279,7 +277,7 @@ var testCmd = &cobra.Command{ RunE: cmdTest, } -// Generates new Args array based off of previous call args to maintain flag persistence +// Generates new Args array based off of previous call args to maintain flag persistence. func persistentArgs(line []byte) []string { // generate the arguments to run from original os.Args // to maintain flag arguments @@ -364,7 +362,6 @@ func cmdBatch(cmd *cobra.Command, _ []string) error { bufReader := bufio.NewReader(os.Stdin) LOOP: for { - line, more, err := bufReader.ReadLine() switch { case more: @@ -492,7 +489,7 @@ func cmdUnimplemented(cmd *cobra.Command, args []string) error { return nil } -// Have the application echo a message +// Have the application echo a message. func cmdEcho(cmd *cobra.Command, args []string) error { msg := "" if len(args) > 0 { @@ -510,7 +507,7 @@ func cmdEcho(cmd *cobra.Command, args []string) error { return nil } -// Get some info from the application +// Get some info from the application. func cmdInfo(cmd *cobra.Command, args []string) error { var version string if len(args) == 1 { @@ -528,7 +525,7 @@ func cmdInfo(cmd *cobra.Command, args []string) error { const codeBad uint32 = 10 -// Append new txs to application +// Append new txs to application. func cmdFinalizeBlock(cmd *cobra.Command, args []string) error { if len(args) == 0 { printResponse(cmd, args, response{ @@ -565,7 +562,7 @@ func cmdFinalizeBlock(cmd *cobra.Command, args []string) error { return nil } -// Validate a tx +// Validate a tx. func cmdCheckTx(cmd *cobra.Command, args []string) error { if len(args) == 0 { printResponse(cmd, args, response{ @@ -594,7 +591,7 @@ func cmdCheckTx(cmd *cobra.Command, args []string) error { return nil } -// Get application Merkle root hash +// Get application Merkle root hash. func cmdCommit(cmd *cobra.Command, args []string) error { _, err := client.Commit(cmd.Context(), &types.CommitRequest{}) if err != nil { @@ -604,7 +601,7 @@ func cmdCommit(cmd *cobra.Command, args []string) error { return nil } -// Query application state +// Query application state. func cmdQuery(cmd *cobra.Command, args []string) error { if len(args) == 0 { printResponse(cmd, args, response{ @@ -780,7 +777,7 @@ func printResponse(cmd *cobra.Command, args []string, rsps ...response) { } } -// NOTE: s is interpreted as a string unless prefixed with 0x +// NOTE: s is interpreted as a string unless prefixed with 0x. func stringOrHexToBytes(s string) ([]byte, error) { if len(s) > 2 && strings.ToLower(s[:2]) == "0x" { b, err := hex.DecodeString(s[2:]) diff --git a/abci/example/kvstore/code.go b/abci/example/kvstore/code.go index f58cfb83c77..06944f750fd 100644 --- a/abci/example/kvstore/code.go +++ b/abci/example/kvstore/code.go @@ -1,6 +1,6 @@ package kvstore -// Return codes for the examples +// Return codes for the examples. const ( CodeTypeOK uint32 = 0 CodeTypeEncodingError uint32 = 1 diff --git a/abci/example/kvstore/helpers.go b/abci/example/kvstore/helpers.go index 5160285af51..34a60ee4a0f 100644 --- a/abci/example/kvstore/helpers.go +++ b/abci/example/kvstore/helpers.go @@ -13,7 +13,7 @@ import ( ) // RandVal creates one random validator, with a key derived -// from the input value +// from the input value. func RandVal() types.ValidatorUpdate { pubkey := cmtrand.Bytes(32) power := cmtrand.Uint16() + 1 @@ -24,7 +24,7 @@ func RandVal() types.ValidatorUpdate { // RandVals returns a list of cnt validators for initializing // the application. Note that the keys are deterministically // derived from the index in the array, while the power is -// random (Change this if not desired) +// random (Change this if not desired). func RandVals(cnt int) []types.ValidatorUpdate { res := make([]types.ValidatorUpdate, cnt) for i := 0; i < cnt; i++ { @@ -35,7 +35,7 @@ func RandVals(cnt int) []types.ValidatorUpdate { // InitKVStore initializes the kvstore app with some data, // which allows tests to pass and is fine as long as you -// don't make any tx that modify the validator state +// don't make any tx that modify the validator state. func InitKVStore(ctx context.Context, app *Application) error { _, err := app.InitChain(ctx, &types.InitChainRequest{ Validators: RandVals(1), @@ -43,7 +43,7 @@ func InitKVStore(ctx context.Context, app *Application) error { return err } -// Create a new transaction +// Create a new transaction. func NewTx(key, value string) []byte { return []byte(strings.Join([]string{key, value}, "=")) } diff --git a/abci/example/kvstore/kvstore.go b/abci/example/kvstore/kvstore.go index bcf525130d2..5a362cb44cb 100644 --- a/abci/example/kvstore/kvstore.go +++ b/abci/example/kvstore/kvstore.go @@ -11,7 +11,6 @@ import ( "strings" dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/abci/types" cryptoproto "github.com/cometbft/cometbft/api/cometbft/crypto/v1" cryptoencoding "github.com/cometbft/cometbft/crypto/encoding" @@ -33,7 +32,7 @@ var _ types.Application = (*Application)(nil) // Application is the kvstore state machine. It complies with the abci.Application interface. // It takes transactions in the form of key=value and saves them in a database. This is -// a somewhat trivial example as there is no real state execution +// a somewhat trivial example as there is no real state execution. type Application struct { types.BaseApplication @@ -51,7 +50,7 @@ type Application struct { genBlockEvents bool } -// NewApplication creates an instance of the kvstore from the provided database +// NewApplication creates an instance of the kvstore from the provided database. func NewApplication(db dbm.DB) *Application { return &Application{ logger: log.NewNopLogger(), @@ -60,7 +59,7 @@ func NewApplication(db dbm.DB) *Application { } } -// NewPersistentApplication creates a new application using the goleveldb database engine +// NewPersistentApplication creates a new application using the goleveldb database engine. func NewPersistentApplication(dbDir string) *Application { name := "kvstore" db, err := dbm.NewGoLevelDB(name, dbDir) @@ -83,7 +82,7 @@ func (app *Application) SetGenBlockEvents() { // Info returns information about the state of the application. This is generally used every time a Tendermint instance // begins and let's the application know what Tendermint versions it's interacting with. Based from this information, // Tendermint will ensure it is in sync with the application by potentially replaying the blocks it has. If the -// Application returns a 0 appBlockHeight, Tendermint will call InitChain to initialize the application with consensus related data +// Application returns a 0 appBlockHeight, Tendermint will call InitChain to initialize the application with consensus related data. func (app *Application) Info(context.Context, *types.InfoRequest) (*types.InfoResponse, error) { // Tendermint expects the application to persist validators, on start-up we need to reload them to memory if they exist if len(app.valAddrToPubKeyMap) == 0 && app.state.Height > 0 { @@ -126,11 +125,12 @@ func (app *Application) InitChain(_ context.Context, req *types.InitChainRequest // For the KVStore we check that each transaction has the valid tx format: // - Contains one and only one `=` // - `=` is not the first or last byte. -// - if key is `val` that the validator update transaction is also valid +// - if key is `val` that the validator update transaction is also valid. func (app *Application) CheckTx(_ context.Context, req *types.CheckTxRequest) (*types.CheckTxResponse, error) { // If it is a validator update transaction, check that it is correctly formatted if isValidatorTx(req.Tx) { if _, _, err := parseValidatorTx(req.Tx); err != nil { + //nolint:nilerr return &types.CheckTxResponse{Code: CodeTypeInvalidTxFormat}, nil } } else if !isValidTx(req.Tx) { @@ -142,7 +142,7 @@ func (app *Application) CheckTx(_ context.Context, req *types.CheckTxRequest) (* // Tx must have a format like key:value or key=value. That is: // - it must have one and only one ":" or "=" -// - It must not begin or end with these special characters +// - It must not begin or end with these special characters. func isValidTx(tx []byte) bool { if bytes.Count(tx, []byte(":")) == 1 && bytes.Count(tx, []byte("=")) == 0 { if !bytes.HasPrefix(tx, []byte(":")) && !bytes.HasSuffix(tx, []byte(":")) { @@ -165,7 +165,7 @@ func (app *Application) PrepareProposal(ctx context.Context, req *types.PrepareP } // formatTxs validates and excludes invalid transactions -// also substitutes all the transactions with x:y to x=y +// also substitutes all the transactions with x:y to x=y. func (app *Application) formatTxs(ctx context.Context, blockData [][]byte) [][]byte { txs := make([][]byte, 0, len(blockData)) for _, tx := range blockData { @@ -182,6 +182,7 @@ func (app *Application) ProcessProposal(ctx context.Context, req *types.ProcessP for _, tx := range req.Txs { // As CheckTx is a full validity check we can simply reuse this if resp, err := app.CheckTx(ctx, &types.CheckTxRequest{Tx: tx, Type: types.CHECK_TX_TYPE_CHECK}); err != nil || resp.Code != CodeTypeOK { + //nolint:nilerr return &types.ProcessProposalResponse{Status: types.PROCESS_PROPOSAL_STATUS_REJECT}, nil } } @@ -323,7 +324,7 @@ func (app *Application) FinalizeBlock(_ context.Context, req *types.FinalizeBloc // Commit is called after FinalizeBlock and after Tendermint state which includes the updates to // AppHash, ConsensusParams and ValidatorSet has occurred. -// The KVStore persists the validator updates and the new key values +// The KVStore persists the validator updates and the new key values. func (app *Application) Commit(context.Context, *types.CommitRequest) (*types.CommitResponse, error) { // apply the validator updates to state (note this is really the validator set at h + 2) for _, valUpdate := range app.valUpdates { @@ -442,7 +443,7 @@ func parseValidatorTx(tx []byte) ([]byte, int64, error) { return pubkey, power, nil } -// add, update, or remove a validator +// add, update, or remove a validator. func (app *Application) updateValidator(v types.ValidatorUpdate) { pubkey, err := cryptoencoding.PubKeyFromProto(v.PubKey) if err != nil { @@ -540,7 +541,7 @@ func saveState(state State) { // as the size or number of transactions processed within the state. Note that this isn't // a strong guarantee of state machine replication because states could // have different kv values but still have the same size. -// This function is used as the "AppHash" +// This function is used as the "AppHash". func (s State) Hash() []byte { appHash := make([]byte, 8) binary.PutVarint(appHash, s.Size) diff --git a/abci/example/kvstore/kvstore_test.go b/abci/example/kvstore/kvstore_test.go index e4f11f52317..bd8a0b6b2d8 100644 --- a/abci/example/kvstore/kvstore_test.go +++ b/abci/example/kvstore/kvstore_test.go @@ -6,14 +6,12 @@ import ( "sort" "testing" - "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/internal/service" - "github.com/cometbft/cometbft/libs/log" - abcicli "github.com/cometbft/cometbft/abci/client" abciserver "github.com/cometbft/cometbft/abci/server" "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/internal/service" + "github.com/cometbft/cometbft/libs/log" + "github.com/stretchr/testify/require" ) const ( @@ -135,7 +133,7 @@ func TestPersistentKVStoreInfo(t *testing.T) { require.Equal(t, height, resInfo.LastBlockHeight) } -// add a validator, remove a validator, update a validator +// add a validator, remove a validator, update a validator. func TestValUpdates(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -274,7 +272,7 @@ func makeApplyBlock( valsEqual(t, diff, resFinalizeBlock.ValidatorUpdates) } -// order doesn't matter +// order doesn't matter. func valsEqual(t *testing.T, vals1, vals2 []types.ValidatorUpdate) { t.Helper() if len(vals1) != len(vals2) { diff --git a/abci/server/errors.go b/abci/server/errors.go index d60eacb2a82..02da0c2c303 100644 --- a/abci/server/errors.go +++ b/abci/server/errors.go @@ -15,7 +15,7 @@ func (e ErrUnknownServerType) Error() string { return fmt.Sprintf("unknown server type %s", e.ServerType) } -// ErrConnectionDoesNotExist is returned when trying to access non-existent network connection +// ErrConnectionDoesNotExist is returned when trying to access non-existent network connection. type ErrConnectionDoesNotExist struct { ConnID int } diff --git a/abci/server/grpc_server.go b/abci/server/grpc_server.go index f3e6364c143..31b1fc299dd 100644 --- a/abci/server/grpc_server.go +++ b/abci/server/grpc_server.go @@ -4,11 +4,10 @@ import ( "context" "net" - "google.golang.org/grpc" - "github.com/cometbft/cometbft/abci/types" cmtnet "github.com/cometbft/cometbft/internal/net" "github.com/cometbft/cometbft/internal/service" + "google.golang.org/grpc" ) type GRPCServer struct { @@ -22,7 +21,7 @@ type GRPCServer struct { app types.Application } -// NewGRPCServer returns a new gRPC ABCI server +// NewGRPCServer returns a new gRPC ABCI server. func NewGRPCServer(protoAddr string, app types.Application) service.Service { proto, addr := cmtnet.ProtocolAndAddress(protoAddr) s := &GRPCServer{ @@ -62,7 +61,7 @@ func (s *GRPCServer) OnStop() { //------------------------------------------------------- -// gRPCApplication is a gRPC shim for Application +// gRPCApplication is a gRPC shim for Application. type gRPCApplication struct { types.Application } diff --git a/abci/server/server.go b/abci/server/server.go index 51c53f2d6ea..4ed2e695296 100644 --- a/abci/server/server.go +++ b/abci/server/server.go @@ -13,7 +13,7 @@ import ( ) // NewServer is a utility function for out of process applications to set up either a socket or -// grpc server that can listen to requests from the equivalent Tendermint client +// grpc server that can listen to requests from the equivalent Tendermint client. func NewServer(protoAddr, transport string, app types.Application) (service.Service, error) { var s service.Service var err error diff --git a/abci/server/socket_server.go b/abci/server/socket_server.go index 1e704353787..9f72a3c236d 100644 --- a/abci/server/socket_server.go +++ b/abci/server/socket_server.go @@ -21,7 +21,7 @@ import ( // for out-of-process go applications. Note, in the case of an application written in golang, // the developer may also run both Tendermint and the application within the same process. // -// The socket server deliver +// The socket server deliver. type SocketServer struct { service.BaseService isLoggerSet bool @@ -97,7 +97,7 @@ func (s *SocketServer) addConn(conn net.Conn) int { return connID } -// deletes conn even if close errs +// deletes conn even if close errs. func (s *SocketServer) rmConn(connID int) error { s.connsMtx.Lock() defer s.connsMtx.Unlock() @@ -159,7 +159,7 @@ func (s *SocketServer) waitForClose(closeConn chan error, connID int) { } } -// Read requests from conn and deal with them +// Read requests from conn and deal with them. func (s *SocketServer) handleRequests(closeConn chan error, conn io.Reader, responses chan<- *types.Response) { var count int bufReader := bufio.NewReader(conn) @@ -183,7 +183,6 @@ func (s *SocketServer) handleRequests(closeConn chan error, conn io.Reader, resp }() for { - req := &types.Request{} err := types.ReadMessage(bufReader, req) if err != nil { @@ -209,7 +208,7 @@ func (s *SocketServer) handleRequests(closeConn chan error, conn io.Reader, resp } } -// handleRequests takes a request and calls the application passing the returned +// handleRequests takes a request and calls the application passing the returned. func (s *SocketServer) handleRequest(ctx context.Context, req *types.Request) (*types.Response, error) { switch r := req.Value.(type) { case *types.Request_Echo: diff --git a/abci/tests/client_server_test.go b/abci/tests/client_server_test.go index 79737a203c0..d3c837dee05 100644 --- a/abci/tests/client_server_test.go +++ b/abci/tests/client_server_test.go @@ -3,11 +3,10 @@ package tests import ( "testing" - "github.com/stretchr/testify/assert" - abciclient "github.com/cometbft/cometbft/abci/client" "github.com/cometbft/cometbft/abci/example/kvstore" abciserver "github.com/cometbft/cometbft/abci/server" + "github.com/stretchr/testify/assert" ) func TestClientServerNoAddrPrefix(t *testing.T) { diff --git a/abci/types/application.go b/abci/types/application.go index d8805811eab..5e9b2d12abb 100644 --- a/abci/types/application.go +++ b/abci/types/application.go @@ -8,30 +8,30 @@ import "context" // to be driven by a blockchain-based replication engine via the ABCI. type Application interface { // Info/Query Connection - Info(context.Context, *InfoRequest) (*InfoResponse, error) // Return application info - Query(context.Context, *QueryRequest) (*QueryResponse, error) // Query for state + Info(ctx context.Context, req *InfoRequest) (*InfoResponse, error) // Return application info + Query(ctx context.Context, req *QueryRequest) (*QueryResponse, error) // Query for state // Mempool Connection - CheckTx(context.Context, *CheckTxRequest) (*CheckTxResponse, error) // Validate a tx for the mempool + CheckTx(ctx context.Context, req *CheckTxRequest) (*CheckTxResponse, error) // Validate a tx for the mempool // Consensus Connection - InitChain(context.Context, *InitChainRequest) (*InitChainResponse, error) // Initialize blockchain w validators/other info from CometBFT - PrepareProposal(context.Context, *PrepareProposalRequest) (*PrepareProposalResponse, error) - ProcessProposal(context.Context, *ProcessProposalRequest) (*ProcessProposalResponse, error) + InitChain(ctx context.Context, req *InitChainRequest) (*InitChainResponse, error) // Initialize blockchain w validators/other info from CometBFT + PrepareProposal(ctx context.Context, req *PrepareProposalRequest) (*PrepareProposalResponse, error) + ProcessProposal(ctx context.Context, req *ProcessProposalRequest) (*ProcessProposalResponse, error) // Deliver the decided block with its txs to the Application - FinalizeBlock(context.Context, *FinalizeBlockRequest) (*FinalizeBlockResponse, error) + FinalizeBlock(ctx context.Context, req *FinalizeBlockRequest) (*FinalizeBlockResponse, error) // Create application specific vote extension - ExtendVote(context.Context, *ExtendVoteRequest) (*ExtendVoteResponse, error) + ExtendVote(ctx context.Context, req *ExtendVoteRequest) (*ExtendVoteResponse, error) // Verify application's vote extension data - VerifyVoteExtension(context.Context, *VerifyVoteExtensionRequest) (*VerifyVoteExtensionResponse, error) + VerifyVoteExtension(ctx context.Context, req *VerifyVoteExtensionRequest) (*VerifyVoteExtensionResponse, error) // Commit the state and return the application Merkle root hash - Commit(context.Context, *CommitRequest) (*CommitResponse, error) + Commit(ctx context.Context, req *CommitRequest) (*CommitResponse, error) // State Sync Connection - ListSnapshots(context.Context, *ListSnapshotsRequest) (*ListSnapshotsResponse, error) // List available snapshots - OfferSnapshot(context.Context, *OfferSnapshotRequest) (*OfferSnapshotResponse, error) // Offer a snapshot to the application - LoadSnapshotChunk(context.Context, *LoadSnapshotChunkRequest) (*LoadSnapshotChunkResponse, error) // Load a snapshot chunk - ApplySnapshotChunk(context.Context, *ApplySnapshotChunkRequest) (*ApplySnapshotChunkResponse, error) // Apply a snapshot chunk + ListSnapshots(ctx context.Context, req *ListSnapshotsRequest) (*ListSnapshotsResponse, error) // List available snapshots + OfferSnapshot(ctx context.Context, req *OfferSnapshotRequest) (*OfferSnapshotResponse, error) // Offer a snapshot to the application + LoadSnapshotChunk(ctx context.Context, req *LoadSnapshotChunkRequest) (*LoadSnapshotChunkResponse, error) // Load a snapshot chunk + ApplySnapshotChunk(ctx context.Context, req *ApplySnapshotChunkRequest) (*ApplySnapshotChunkResponse, error) // Apply a snapshot chunk } //------------------------------------------------------- diff --git a/abci/types/messages.go b/abci/types/messages.go index 42407083a11..b8e2fe41d41 100644 --- a/abci/types/messages.go +++ b/abci/types/messages.go @@ -4,10 +4,9 @@ import ( "io" "math" - "github.com/cosmos/gogoproto/proto" - pb "github.com/cometbft/cometbft/api/cometbft/abci/v1" "github.com/cometbft/cometbft/internal/protoio" + "github.com/cosmos/gogoproto/proto" ) const ( diff --git a/abci/types/messages_test.go b/abci/types/messages_test.go index f22b868eb00..7f30ebe76e4 100644 --- a/abci/types/messages_test.go +++ b/abci/types/messages_test.go @@ -6,10 +6,9 @@ import ( "strings" "testing" + cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/assert" - - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" ) func TestMarshalJSON(t *testing.T) { diff --git a/abci/types/mocks/application.go b/abci/types/mocks/application.go index 5b447124dad..e055d367803 100644 --- a/abci/types/mocks/application.go +++ b/abci/types/mocks/application.go @@ -15,9 +15,9 @@ type Application struct { mock.Mock } -// ApplySnapshotChunk provides a mock function with given fields: _a0, _a1 -func (_m *Application) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error) { - ret := _m.Called(_a0, _a1) +// ApplySnapshotChunk provides a mock function with given fields: ctx, req +func (_m *Application) ApplySnapshotChunk(ctx context.Context, req *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ApplySnapshotChunk") @@ -26,10 +26,10 @@ func (_m *Application) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnap var r0 *v1.ApplySnapshotChunkResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ApplySnapshotChunkRequest) *v1.ApplySnapshotChunkResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ApplySnapshotChunkResponse) @@ -37,7 +37,7 @@ func (_m *Application) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnap } if rf, ok := ret.Get(1).(func(context.Context, *v1.ApplySnapshotChunkRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -45,9 +45,9 @@ func (_m *Application) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnap return r0, r1 } -// CheckTx provides a mock function with given fields: _a0, _a1 -func (_m *Application) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1.CheckTxResponse, error) { - ret := _m.Called(_a0, _a1) +// CheckTx provides a mock function with given fields: ctx, req +func (_m *Application) CheckTx(ctx context.Context, req *v1.CheckTxRequest) (*v1.CheckTxResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for CheckTx") @@ -56,10 +56,10 @@ func (_m *Application) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1 var r0 *v1.CheckTxResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) (*v1.CheckTxResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) *v1.CheckTxResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.CheckTxResponse) @@ -67,7 +67,7 @@ func (_m *Application) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1 } if rf, ok := ret.Get(1).(func(context.Context, *v1.CheckTxRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -75,9 +75,9 @@ func (_m *Application) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1 return r0, r1 } -// Commit provides a mock function with given fields: _a0, _a1 -func (_m *Application) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.CommitResponse, error) { - ret := _m.Called(_a0, _a1) +// Commit provides a mock function with given fields: ctx, req +func (_m *Application) Commit(ctx context.Context, req *v1.CommitRequest) (*v1.CommitResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Commit") @@ -86,10 +86,10 @@ func (_m *Application) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.C var r0 *v1.CommitResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.CommitRequest) (*v1.CommitResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.CommitRequest) *v1.CommitResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.CommitResponse) @@ -97,7 +97,7 @@ func (_m *Application) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.C } if rf, ok := ret.Get(1).(func(context.Context, *v1.CommitRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -105,9 +105,9 @@ func (_m *Application) Commit(_a0 context.Context, _a1 *v1.CommitRequest) (*v1.C return r0, r1 } -// ExtendVote provides a mock function with given fields: _a0, _a1 -func (_m *Application) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error) { - ret := _m.Called(_a0, _a1) +// ExtendVote provides a mock function with given fields: ctx, req +func (_m *Application) ExtendVote(ctx context.Context, req *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ExtendVote") @@ -116,10 +116,10 @@ func (_m *Application) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest var r0 *v1.ExtendVoteResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ExtendVoteRequest) *v1.ExtendVoteResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ExtendVoteResponse) @@ -127,7 +127,7 @@ func (_m *Application) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest } if rf, ok := ret.Get(1).(func(context.Context, *v1.ExtendVoteRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -135,9 +135,9 @@ func (_m *Application) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest return r0, r1 } -// FinalizeBlock provides a mock function with given fields: _a0, _a1 -func (_m *Application) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error) { - ret := _m.Called(_a0, _a1) +// FinalizeBlock provides a mock function with given fields: ctx, req +func (_m *Application) FinalizeBlock(ctx context.Context, req *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for FinalizeBlock") @@ -146,10 +146,10 @@ func (_m *Application) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockR var r0 *v1.FinalizeBlockResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.FinalizeBlockRequest) *v1.FinalizeBlockResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.FinalizeBlockResponse) @@ -157,7 +157,7 @@ func (_m *Application) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockR } if rf, ok := ret.Get(1).(func(context.Context, *v1.FinalizeBlockRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -165,9 +165,9 @@ func (_m *Application) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockR return r0, r1 } -// Info provides a mock function with given fields: _a0, _a1 -func (_m *Application) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoResponse, error) { - ret := _m.Called(_a0, _a1) +// Info provides a mock function with given fields: ctx, req +func (_m *Application) Info(ctx context.Context, req *v1.InfoRequest) (*v1.InfoResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Info") @@ -176,10 +176,10 @@ func (_m *Application) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoR var r0 *v1.InfoResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.InfoRequest) (*v1.InfoResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.InfoRequest) *v1.InfoResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.InfoResponse) @@ -187,7 +187,7 @@ func (_m *Application) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoR } if rf, ok := ret.Get(1).(func(context.Context, *v1.InfoRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -195,9 +195,9 @@ func (_m *Application) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoR return r0, r1 } -// InitChain provides a mock function with given fields: _a0, _a1 -func (_m *Application) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) (*v1.InitChainResponse, error) { - ret := _m.Called(_a0, _a1) +// InitChain provides a mock function with given fields: ctx, req +func (_m *Application) InitChain(ctx context.Context, req *v1.InitChainRequest) (*v1.InitChainResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for InitChain") @@ -206,10 +206,10 @@ func (_m *Application) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) var r0 *v1.InitChainResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.InitChainRequest) (*v1.InitChainResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.InitChainRequest) *v1.InitChainResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.InitChainResponse) @@ -217,7 +217,7 @@ func (_m *Application) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) } if rf, ok := ret.Get(1).(func(context.Context, *v1.InitChainRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -225,9 +225,9 @@ func (_m *Application) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) return r0, r1 } -// ListSnapshots provides a mock function with given fields: _a0, _a1 -func (_m *Application) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error) { - ret := _m.Called(_a0, _a1) +// ListSnapshots provides a mock function with given fields: ctx, req +func (_m *Application) ListSnapshots(ctx context.Context, req *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ListSnapshots") @@ -236,10 +236,10 @@ func (_m *Application) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsR var r0 *v1.ListSnapshotsResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ListSnapshotsRequest) *v1.ListSnapshotsResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ListSnapshotsResponse) @@ -247,7 +247,7 @@ func (_m *Application) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsR } if rf, ok := ret.Get(1).(func(context.Context, *v1.ListSnapshotsRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -255,9 +255,9 @@ func (_m *Application) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsR return r0, r1 } -// LoadSnapshotChunk provides a mock function with given fields: _a0, _a1 -func (_m *Application) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error) { - ret := _m.Called(_a0, _a1) +// LoadSnapshotChunk provides a mock function with given fields: ctx, req +func (_m *Application) LoadSnapshotChunk(ctx context.Context, req *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for LoadSnapshotChunk") @@ -266,10 +266,10 @@ func (_m *Application) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapsh var r0 *v1.LoadSnapshotChunkResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.LoadSnapshotChunkRequest) *v1.LoadSnapshotChunkResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.LoadSnapshotChunkResponse) @@ -277,7 +277,7 @@ func (_m *Application) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapsh } if rf, ok := ret.Get(1).(func(context.Context, *v1.LoadSnapshotChunkRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -285,9 +285,9 @@ func (_m *Application) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapsh return r0, r1 } -// OfferSnapshot provides a mock function with given fields: _a0, _a1 -func (_m *Application) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error) { - ret := _m.Called(_a0, _a1) +// OfferSnapshot provides a mock function with given fields: ctx, req +func (_m *Application) OfferSnapshot(ctx context.Context, req *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for OfferSnapshot") @@ -296,10 +296,10 @@ func (_m *Application) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotR var r0 *v1.OfferSnapshotResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.OfferSnapshotRequest) *v1.OfferSnapshotResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.OfferSnapshotResponse) @@ -307,7 +307,7 @@ func (_m *Application) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotR } if rf, ok := ret.Get(1).(func(context.Context, *v1.OfferSnapshotRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -315,9 +315,9 @@ func (_m *Application) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotR return r0, r1 } -// PrepareProposal provides a mock function with given fields: _a0, _a1 -func (_m *Application) PrepareProposal(_a0 context.Context, _a1 *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error) { - ret := _m.Called(_a0, _a1) +// PrepareProposal provides a mock function with given fields: ctx, req +func (_m *Application) PrepareProposal(ctx context.Context, req *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for PrepareProposal") @@ -326,10 +326,10 @@ func (_m *Application) PrepareProposal(_a0 context.Context, _a1 *v1.PreparePropo var r0 *v1.PrepareProposalResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.PrepareProposalRequest) *v1.PrepareProposalResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.PrepareProposalResponse) @@ -337,7 +337,7 @@ func (_m *Application) PrepareProposal(_a0 context.Context, _a1 *v1.PreparePropo } if rf, ok := ret.Get(1).(func(context.Context, *v1.PrepareProposalRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -345,9 +345,9 @@ func (_m *Application) PrepareProposal(_a0 context.Context, _a1 *v1.PreparePropo return r0, r1 } -// ProcessProposal provides a mock function with given fields: _a0, _a1 -func (_m *Application) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error) { - ret := _m.Called(_a0, _a1) +// ProcessProposal provides a mock function with given fields: ctx, req +func (_m *Application) ProcessProposal(ctx context.Context, req *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ProcessProposal") @@ -356,10 +356,10 @@ func (_m *Application) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessPropo var r0 *v1.ProcessProposalResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ProcessProposalRequest) *v1.ProcessProposalResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ProcessProposalResponse) @@ -367,7 +367,7 @@ func (_m *Application) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessPropo } if rf, ok := ret.Get(1).(func(context.Context, *v1.ProcessProposalRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -375,9 +375,9 @@ func (_m *Application) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessPropo return r0, r1 } -// Query provides a mock function with given fields: _a0, _a1 -func (_m *Application) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.QueryResponse, error) { - ret := _m.Called(_a0, _a1) +// Query provides a mock function with given fields: ctx, req +func (_m *Application) Query(ctx context.Context, req *v1.QueryRequest) (*v1.QueryResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Query") @@ -386,10 +386,10 @@ func (_m *Application) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.Que var r0 *v1.QueryResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.QueryRequest) (*v1.QueryResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.QueryRequest) *v1.QueryResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.QueryResponse) @@ -397,7 +397,7 @@ func (_m *Application) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.Que } if rf, ok := ret.Get(1).(func(context.Context, *v1.QueryRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -405,9 +405,9 @@ func (_m *Application) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.Que return r0, r1 } -// VerifyVoteExtension provides a mock function with given fields: _a0, _a1 -func (_m *Application) VerifyVoteExtension(_a0 context.Context, _a1 *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error) { - ret := _m.Called(_a0, _a1) +// VerifyVoteExtension provides a mock function with given fields: ctx, req +func (_m *Application) VerifyVoteExtension(ctx context.Context, req *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for VerifyVoteExtension") @@ -416,10 +416,10 @@ func (_m *Application) VerifyVoteExtension(_a0 context.Context, _a1 *v1.VerifyVo var r0 *v1.VerifyVoteExtensionResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.VerifyVoteExtensionRequest) *v1.VerifyVoteExtensionResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.VerifyVoteExtensionResponse) @@ -427,7 +427,7 @@ func (_m *Application) VerifyVoteExtension(_a0 context.Context, _a1 *v1.VerifyVo } if rf, ok := ret.Get(1).(func(context.Context, *v1.VerifyVoteExtensionRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } diff --git a/abci/types/types.go b/abci/types/types.go index 2a925e8ceb8..9499fa08ad4 100644 --- a/abci/types/types.go +++ b/abci/types/types.go @@ -1,12 +1,11 @@ -//nolint:revive,stylecheck +//nolint:stylecheck,revive package types import ( "encoding/json" - "github.com/cosmos/gogoproto/grpc" - v1 "github.com/cometbft/cometbft/api/cometbft/abci/v1" + "github.com/cosmos/gogoproto/grpc" ) type ( @@ -181,7 +180,7 @@ const ( // have accidental runtime surprises later on. // jsonEncodingRoundTripper ensures that asserted -// interfaces implement both MarshalJSON and UnmarshalJSON +// interfaces implement both MarshalJSON and UnmarshalJSON. type jsonRoundTripper interface { json.Marshaler json.Unmarshaler @@ -207,7 +206,7 @@ func DeterministicExecTxResult(response *ExecTxResult) *ExecTxResult { } } -// MarshalTxResults encodes the the TxResults as a list of byte +// MarshalTxResults encodes the TxResults as a list of byte // slices. It strips off the non-deterministic pieces of the TxResults // so that the resulting data can be used for hash comparisons and used // in Merkle proofs. diff --git a/abci/types/types_test.go b/abci/types/types_test.go index 9c4e62d4c2a..381fd65dfaa 100644 --- a/abci/types/types_test.go +++ b/abci/types/types_test.go @@ -3,11 +3,10 @@ package types_test import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/crypto/merkle" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestHashAndProveResults(t *testing.T) { diff --git a/abci/types/util.go b/abci/types/util.go index 8205fef7e9d..8bee3b08bb6 100644 --- a/abci/types/util.go +++ b/abci/types/util.go @@ -6,7 +6,7 @@ import ( //------------------------------------------------------------------------------ -// ValidatorUpdates is a list of validators that implements the Sort interface +// ValidatorUpdates is a list of validators that implements the Sort interface. type ValidatorUpdates []ValidatorUpdate var _ sort.Interface = (ValidatorUpdates)(nil) @@ -21,7 +21,7 @@ func (v ValidatorUpdates) Len() int { return len(v) } -// XXX: doesn't distinguish same validator with different power +// XXX: doesn't distinguish same validator with different power. func (v ValidatorUpdates) Less(i, j int) bool { return v[i].PubKey.Compare(v[j].PubKey) <= 0 } diff --git a/cmd/cometbft/commands/compact.go b/cmd/cometbft/commands/compact.go index 327e1dbca68..b3a6b5aeeca 100644 --- a/cmd/cometbft/commands/compact.go +++ b/cmd/cometbft/commands/compact.go @@ -5,12 +5,11 @@ import ( "path/filepath" "sync" + "github.com/cometbft/cometbft/libs/log" "github.com/spf13/cobra" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" "github.com/syndtr/goleveldb/leveldb/util" - - "github.com/cometbft/cometbft/libs/log" ) var CompactGoLevelDBCmd = &cobra.Command{ diff --git a/cmd/cometbft/commands/debug/debug.go b/cmd/cometbft/commands/debug/debug.go index 2476968048b..149d9e81b18 100644 --- a/cmd/cometbft/commands/debug/debug.go +++ b/cmd/cometbft/commands/debug/debug.go @@ -3,9 +3,8 @@ package debug import ( "os" - "github.com/spf13/cobra" - "github.com/cometbft/cometbft/libs/log" + "github.com/spf13/cobra" ) var ( diff --git a/cmd/cometbft/commands/debug/dump.go b/cmd/cometbft/commands/debug/dump.go index e38462933dd..5fa9d642860 100644 --- a/cmd/cometbft/commands/debug/dump.go +++ b/cmd/cometbft/commands/debug/dump.go @@ -7,12 +7,11 @@ import ( "path/filepath" "time" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/libs/cli" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var dumpCmd = &cobra.Command{ diff --git a/cmd/cometbft/commands/debug/io.go b/cmd/cometbft/commands/debug/io.go index 01a14ea710f..ec8e04e0eb2 100644 --- a/cmd/cometbft/commands/debug/io.go +++ b/cmd/cometbft/commands/debug/io.go @@ -67,7 +67,6 @@ func zipDir(src, dest string) error { _, err = io.Copy(headerWriter, file) return err }) - } // copyFile copies a file from src to dest and returns an error upon failure. The diff --git a/cmd/cometbft/commands/debug/kill.go b/cmd/cometbft/commands/debug/kill.go index da1e62836e2..847e8cdbf1f 100644 --- a/cmd/cometbft/commands/debug/kill.go +++ b/cmd/cometbft/commands/debug/kill.go @@ -10,12 +10,11 @@ import ( "syscall" "time" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/libs/cli" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var killCmd = &cobra.Command{ diff --git a/cmd/cometbft/commands/debug/util.go b/cmd/cometbft/commands/debug/util.go index 0972a03a1da..1396c662183 100644 --- a/cmd/cometbft/commands/debug/util.go +++ b/cmd/cometbft/commands/debug/util.go @@ -67,7 +67,7 @@ func copyConfig(home, dir string) error { func dumpProfile(dir, addr, profile string, debug int) error { endpoint := fmt.Sprintf("%s/debug/pprof/%s?debug=%d", addr, profile, debug) - //nolint:gosec,nolintlint + //nolint:gosec,nolintlint,noctx resp, err := http.Get(endpoint) if err != nil { return fmt.Errorf("failed to query for %s profile: %w", profile, err) diff --git a/cmd/cometbft/commands/gen_node_key.go b/cmd/cometbft/commands/gen_node_key.go index c96f2564885..83ca95234fa 100644 --- a/cmd/cometbft/commands/gen_node_key.go +++ b/cmd/cometbft/commands/gen_node_key.go @@ -3,10 +3,9 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - cmtos "github.com/cometbft/cometbft/internal/os" "github.com/cometbft/cometbft/p2p" + "github.com/spf13/cobra" ) // GenNodeKeyCmd allows the generation of a node key. It prints node's ID to diff --git a/cmd/cometbft/commands/gen_validator.go b/cmd/cometbft/commands/gen_validator.go index 072b26576dd..6cfa7087767 100644 --- a/cmd/cometbft/commands/gen_validator.go +++ b/cmd/cometbft/commands/gen_validator.go @@ -3,10 +3,9 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - cmtjson "github.com/cometbft/cometbft/libs/json" "github.com/cometbft/cometbft/privval" + "github.com/spf13/cobra" ) // GenValidatorCmd allows the generation of a keypair for a diff --git a/cmd/cometbft/commands/init.go b/cmd/cometbft/commands/init.go index 495c8a993a1..bf14893c1ac 100644 --- a/cmd/cometbft/commands/init.go +++ b/cmd/cometbft/commands/init.go @@ -3,8 +3,6 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - cfg "github.com/cometbft/cometbft/config" cmtos "github.com/cometbft/cometbft/internal/os" cmtrand "github.com/cometbft/cometbft/internal/rand" @@ -12,6 +10,7 @@ import ( "github.com/cometbft/cometbft/privval" "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" + "github.com/spf13/cobra" ) // InitFilesCmd initializes a fresh CometBFT instance. diff --git a/cmd/cometbft/commands/inspect.go b/cmd/cometbft/commands/inspect.go index c417fdb2a5a..0721223674c 100644 --- a/cmd/cometbft/commands/inspect.go +++ b/cmd/cometbft/commands/inspect.go @@ -6,14 +6,13 @@ import ( "os/signal" "syscall" - "github.com/spf13/cobra" - cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/internal/inspect" "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/state/indexer/block" "github.com/cometbft/cometbft/internal/store" "github.com/cometbft/cometbft/types" + "github.com/spf13/cobra" ) // InspectCmd is the command for starting an inspect server. diff --git a/cmd/cometbft/commands/light.go b/cmd/cometbft/commands/light.go index 79c61272958..05fb7290367 100644 --- a/cmd/cometbft/commands/light.go +++ b/cmd/cometbft/commands/light.go @@ -11,10 +11,7 @@ import ( "strings" "time" - "github.com/spf13/cobra" - dbm "github.com/cometbft/cometbft-db" - cmtos "github.com/cometbft/cometbft/internal/os" "github.com/cometbft/cometbft/libs/log" cmtmath "github.com/cometbft/cometbft/libs/math" @@ -23,9 +20,10 @@ import ( lrpc "github.com/cometbft/cometbft/light/rpc" dbs "github.com/cometbft/cometbft/light/store/db" rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" + "github.com/spf13/cobra" ) -// LightCmd represents the base command when called without any subcommands +// LightCmd represents the base command when called without any subcommands. var LightCmd = &cobra.Command{ Use: "light [chainID]", Short: "Run a light client proxy server, verifying CometBFT rpc", diff --git a/cmd/cometbft/commands/reindex_event.go b/cmd/cometbft/commands/reindex_event.go index cc398f1e286..778c62b566f 100644 --- a/cmd/cometbft/commands/reindex_event.go +++ b/cmd/cometbft/commands/reindex_event.go @@ -5,10 +5,7 @@ import ( "fmt" "strings" - "github.com/spf13/cobra" - dbm "github.com/cometbft/cometbft-db" - abcitypes "github.com/cometbft/cometbft/abci/types" cmtcfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/internal/progressbar" @@ -19,6 +16,7 @@ import ( "github.com/cometbft/cometbft/internal/state/txindex" "github.com/cometbft/cometbft/internal/state/txindex/kv" "github.com/cometbft/cometbft/types" + "github.com/spf13/cobra" ) const ( diff --git a/cmd/cometbft/commands/reset.go b/cmd/cometbft/commands/reset.go index ab17352c3b7..0a1c2d001eb 100644 --- a/cmd/cometbft/commands/reset.go +++ b/cmd/cometbft/commands/reset.go @@ -4,11 +4,10 @@ import ( "os" "path/filepath" - "github.com/spf13/cobra" - cmtos "github.com/cometbft/cometbft/internal/os" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/privval" + "github.com/spf13/cobra" ) // ResetAllCmd removes the database of this CometBFT core diff --git a/cmd/cometbft/commands/rollback.go b/cmd/cometbft/commands/rollback.go index 3525b8a5514..af231b1df06 100644 --- a/cmd/cometbft/commands/rollback.go +++ b/cmd/cometbft/commands/rollback.go @@ -4,14 +4,12 @@ import ( "fmt" "path/filepath" - "github.com/spf13/cobra" - dbm "github.com/cometbft/cometbft-db" - cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/internal/os" "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/store" + "github.com/spf13/cobra" ) var removeBlock = false diff --git a/cmd/cometbft/commands/root.go b/cmd/cometbft/commands/root.go index c21b415758d..fedaeb530b2 100644 --- a/cmd/cometbft/commands/root.go +++ b/cmd/cometbft/commands/root.go @@ -4,13 +4,12 @@ import ( "fmt" "os" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/libs/cli" cmtflags "github.com/cometbft/cometbft/libs/cli/flags" "github.com/cometbft/cometbft/libs/log" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var ( @@ -27,7 +26,7 @@ func registerFlagsRootCmd(cmd *cobra.Command) { } // ParseConfig retrieves the default environment configuration, -// sets up the CometBFT root and ensures that the root exists +// sets up the CometBFT root and ensures that the root exists. func ParseConfig(cmd *cobra.Command) (*cfg.Config, error) { conf := cfg.DefaultConfig() err := viper.Unmarshal(conf) @@ -36,13 +35,14 @@ func ParseConfig(cmd *cobra.Command) (*cfg.Config, error) { } var home string - if os.Getenv("CMTHOME") != "" { + switch { + case os.Getenv("CMTHOME") != "": home = os.Getenv("CMTHOME") - } else if os.Getenv("TMHOME") != "" { + case os.Getenv("TMHOME") != "": // XXX: Deprecated. home = os.Getenv("TMHOME") logger.Error("Deprecated environment variable TMHOME identified. CMTHOME should be used instead.") - } else { + default: home, err = cmd.Flags().GetString(cli.HomeFlag) if err != nil { return nil, err diff --git a/cmd/cometbft/commands/run_node.go b/cmd/cometbft/commands/run_node.go index 262e6803918..bd9baca683d 100644 --- a/cmd/cometbft/commands/run_node.go +++ b/cmd/cometbft/commands/run_node.go @@ -4,16 +4,15 @@ import ( "encoding/hex" "fmt" - "github.com/spf13/cobra" - cmtos "github.com/cometbft/cometbft/internal/os" nm "github.com/cometbft/cometbft/node" + "github.com/spf13/cobra" ) var genesisHash []byte // AddNodeFlags exposes some common configuration options on the command-line -// These are exposed for convenience of commands embedding a CometBFT node +// These are exposed for convenience of commands embedding a CometBFT node. func AddNodeFlags(cmd *cobra.Command) { // bind flags cmd.Flags().String("moniker", config.Moniker, "node name") diff --git a/cmd/cometbft/commands/show_node_id.go b/cmd/cometbft/commands/show_node_id.go index 17bc0ed20c4..53edd7a750e 100644 --- a/cmd/cometbft/commands/show_node_id.go +++ b/cmd/cometbft/commands/show_node_id.go @@ -3,9 +3,8 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - "github.com/cometbft/cometbft/p2p" + "github.com/spf13/cobra" ) // ShowNodeIDCmd dumps node's ID to the standard output. diff --git a/cmd/cometbft/commands/show_validator.go b/cmd/cometbft/commands/show_validator.go index 4d8d97f4881..630084fb474 100644 --- a/cmd/cometbft/commands/show_validator.go +++ b/cmd/cometbft/commands/show_validator.go @@ -3,11 +3,10 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - cmtos "github.com/cometbft/cometbft/internal/os" cmtjson "github.com/cometbft/cometbft/libs/json" "github.com/cometbft/cometbft/privval" + "github.com/spf13/cobra" ) // ShowValidatorCmd adds capabilities for showing the validator info. diff --git a/cmd/cometbft/commands/testnet.go b/cmd/cometbft/commands/testnet.go index b9cd505792e..b4a9a318460 100644 --- a/cmd/cometbft/commands/testnet.go +++ b/cmd/cometbft/commands/testnet.go @@ -7,9 +7,6 @@ import ( "path/filepath" "strings" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/cometbft/cometbft/config" cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/libs/bytes" @@ -17,6 +14,8 @@ import ( "github.com/cometbft/cometbft/privval" "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var ( diff --git a/cmd/cometbft/commands/version.go b/cmd/cometbft/commands/version.go index 58802297dd4..77e50dec561 100644 --- a/cmd/cometbft/commands/version.go +++ b/cmd/cometbft/commands/version.go @@ -4,9 +4,8 @@ import ( "encoding/json" "fmt" - "github.com/spf13/cobra" - "github.com/cometbft/cometbft/version" + "github.com/spf13/cobra" ) // VersionCmd ... @@ -20,7 +19,7 @@ var VersionCmd = &cobra.Command{ } if verbose { - values, _ := json.MarshalIndent(struct { + values, err := json.MarshalIndent(struct { CometBFT string `json:"cometbft"` ABCI string `json:"abci"` BlockProtocol uint64 `json:"block_protocol"` @@ -31,6 +30,9 @@ var VersionCmd = &cobra.Command{ BlockProtocol: version.BlockProtocol, P2PProtocol: version.P2PProtocol, }, "", " ") + if err != nil { + panic(fmt.Sprintf("failed to marshal version info: %v", err)) + } fmt.Println(string(values)) } else { fmt.Println(cmtVersion) diff --git a/cmd/priv_val_server/main.go b/cmd/priv_val_server/main.go index 81913cead75..4d3926a55a7 100644 --- a/cmd/priv_val_server/main.go +++ b/cmd/priv_val_server/main.go @@ -9,7 +9,6 @@ import ( cmtnet "github.com/cometbft/cometbft/internal/net" cmtos "github.com/cometbft/cometbft/internal/os" "github.com/cometbft/cometbft/libs/log" - "github.com/cometbft/cometbft/privval" ) diff --git a/config/config.go b/config/config.go index 1c71885c01c..d74e8084aa5 100644 --- a/config/config.go +++ b/config/config.go @@ -12,19 +12,18 @@ import ( "time" cmterrors "github.com/cometbft/cometbft/types/errors" - "github.com/cometbft/cometbft/version" ) const ( - // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep + // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep. FuzzModeDrop = iota - // FuzzModeDelay is a mode in which we randomly sleep + // FuzzModeDelay is a mode in which we randomly sleep. FuzzModeDelay - // LogFormatPlain is a format for colored text + // LogFormatPlain is a format for colored text. LogFormatPlain = "plain" - // LogFormatJSON is a format for json output + // LogFormatJSON is a format for json output. LogFormatJSON = "json" // DefaultLogLevel defines a default log level as INFO. @@ -75,7 +74,7 @@ var ( semverRegexp = regexp.MustCompile(`^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)(?:-(?P(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`) ) -// Config defines the top level configuration for a CometBFT node +// Config defines the top level configuration for a CometBFT node. type Config struct { // Top level options use an anonymous struct BaseConfig `mapstructure:",squash"` @@ -93,7 +92,7 @@ type Config struct { Instrumentation *InstrumentationConfig `mapstructure:"instrumentation"` } -// DefaultConfig returns a default configuration for a CometBFT node +// DefaultConfig returns a default configuration for a CometBFT node. func DefaultConfig() *Config { return &Config{ BaseConfig: DefaultBaseConfig(), @@ -110,7 +109,7 @@ func DefaultConfig() *Config { } } -// TestConfig returns a configuration that can be used for testing +// TestConfig returns a configuration that can be used for testing. func TestConfig() *Config { return &Config{ BaseConfig: TestBaseConfig(), @@ -127,7 +126,7 @@ func TestConfig() *Config { } } -// SetRoot sets the RootDir for all Config structs +// SetRoot sets the RootDir for all Config structs. func (cfg *Config) SetRoot(root string) *Config { cfg.BaseConfig.RootDir = root cfg.RPC.RootDir = root @@ -176,7 +175,7 @@ func (cfg *Config) ValidateBasic() error { return nil } -// CheckDeprecated returns any deprecation warnings. These are printed to the operator on startup +// CheckDeprecated returns any deprecation warnings. These are printed to the operator on startup. func (cfg *Config) CheckDeprecated() []string { var warnings []string return warnings @@ -185,9 +184,8 @@ func (cfg *Config) CheckDeprecated() []string { //----------------------------------------------------------------------------- // BaseConfig -// BaseConfig defines the base configuration for a CometBFT node -type BaseConfig struct { //nolint: maligned - +// BaseConfig defines the base configuration for a CometBFT node. +type BaseConfig struct { // The version of the CometBFT binary that created // or last modified the config file Version string `mapstructure:"version"` @@ -257,7 +255,7 @@ type BaseConfig struct { //nolint: maligned FilterPeers bool `mapstructure:"filter_peers"` // false } -// DefaultBaseConfig returns a default base configuration for a CometBFT node +// DefaultBaseConfig returns a default base configuration for a CometBFT node. func DefaultBaseConfig() BaseConfig { return BaseConfig{ Version: version.CMTSemVer, @@ -276,7 +274,7 @@ func DefaultBaseConfig() BaseConfig { } } -// TestBaseConfig returns a base configuration for testing a CometBFT node +// TestBaseConfig returns a base configuration for testing a CometBFT node. func TestBaseConfig() BaseConfig { cfg := DefaultBaseConfig() cfg.ProxyApp = "kvstore" @@ -284,27 +282,27 @@ func TestBaseConfig() BaseConfig { return cfg } -// GenesisFile returns the full path to the genesis.json file +// GenesisFile returns the full path to the genesis.json file. func (cfg BaseConfig) GenesisFile() string { return rootify(cfg.Genesis, cfg.RootDir) } -// PrivValidatorKeyFile returns the full path to the priv_validator_key.json file +// PrivValidatorKeyFile returns the full path to the priv_validator_key.json file. func (cfg BaseConfig) PrivValidatorKeyFile() string { return rootify(cfg.PrivValidatorKey, cfg.RootDir) } -// PrivValidatorFile returns the full path to the priv_validator_state.json file +// PrivValidatorFile returns the full path to the priv_validator_state.json file. func (cfg BaseConfig) PrivValidatorStateFile() string { return rootify(cfg.PrivValidatorState, cfg.RootDir) } -// NodeKeyFile returns the full path to the node_key.json file +// NodeKeyFile returns the full path to the node_key.json file. func (cfg BaseConfig) NodeKeyFile() string { return rootify(cfg.NodeKey, cfg.RootDir) } -// DBDir returns the full path to the database directory +// DBDir returns the full path to the database directory. func (cfg BaseConfig) DBDir() string { return rootify(cfg.DBPath, cfg.RootDir) } @@ -329,7 +327,7 @@ func (cfg BaseConfig) ValidateBasic() error { //----------------------------------------------------------------------------- // RPCConfig -// RPCConfig defines the configuration options for the CometBFT RPC server +// RPCConfig defines the configuration options for the CometBFT RPC server. type RPCConfig struct { RootDir string `mapstructure:"home"` @@ -427,7 +425,7 @@ type RPCConfig struct { PprofListenAddress string `mapstructure:"pprof_laddr"` } -// DefaultRPCConfig returns a default configuration for the RPC server +// DefaultRPCConfig returns a default configuration for the RPC server. func DefaultRPCConfig() *RPCConfig { return &RPCConfig{ ListenAddress: "tcp://127.0.0.1:26657", @@ -452,7 +450,7 @@ func DefaultRPCConfig() *RPCConfig { } } -// TestRPCConfig returns a configuration for testing the RPC server +// TestRPCConfig returns a configuration for testing the RPC server. func TestRPCConfig() *RPCConfig { cfg := DefaultRPCConfig() cfg.ListenAddress = "tcp://127.0.0.1:36657" @@ -670,7 +668,7 @@ func TestGRPCPruningServiceConfig() *GRPCPruningServiceConfig { //----------------------------------------------------------------------------- // P2PConfig -// P2PConfig defines the configuration options for the CometBFT peer-to-peer networking layer +// P2PConfig defines the configuration options for the CometBFT peer-to-peer networking layer. type P2PConfig struct { //nolint: maligned RootDir string `mapstructure:"home"` @@ -746,7 +744,7 @@ type P2PConfig struct { //nolint: maligned TestFuzzConfig *FuzzConnConfig `mapstructure:"test_fuzz_config"` } -// DefaultP2PConfig returns a default configuration for the peer-to-peer layer +// DefaultP2PConfig returns a default configuration for the peer-to-peer layer. func DefaultP2PConfig() *P2PConfig { return &P2PConfig{ ListenAddress: "tcp://0.0.0.0:26656", @@ -771,7 +769,7 @@ func DefaultP2PConfig() *P2PConfig { } } -// TestP2PConfig returns a configuration for testing the peer-to-peer layer +// TestP2PConfig returns a configuration for testing the peer-to-peer layer. func TestP2PConfig() *P2PConfig { cfg := DefaultP2PConfig() cfg.ListenAddress = "tcp://127.0.0.1:36656" @@ -780,7 +778,7 @@ func TestP2PConfig() *P2PConfig { return cfg } -// AddrBookFile returns the full path to the address book +// AddrBookFile returns the full path to the address book. func (cfg *P2PConfig) AddrBookFile() string { return rootify(cfg.AddrBook, cfg.RootDir) } @@ -907,7 +905,7 @@ type MempoolConfig struct { ExperimentalMaxGossipConnectionsToNonPersistentPeers int `mapstructure:"experimental_max_gossip_connections_to_non_persistent_peers"` } -// DefaultMempoolConfig returns a default configuration for the CometBFT mempool +// DefaultMempoolConfig returns a default configuration for the CometBFT mempool. func DefaultMempoolConfig() *MempoolConfig { return &MempoolConfig{ Type: MempoolTypeFlood, @@ -925,14 +923,14 @@ func DefaultMempoolConfig() *MempoolConfig { } } -// TestMempoolConfig returns a configuration for testing the CometBFT mempool +// TestMempoolConfig returns a configuration for testing the CometBFT mempool. func TestMempoolConfig() *MempoolConfig { cfg := DefaultMempoolConfig() cfg.CacheSize = 1000 return cfg } -// WalDir returns the full path to the mempool's write-ahead log +// WalDir returns the full path to the mempool's write-ahead log. func (cfg *MempoolConfig) WalDir() string { return rootify(cfg.WalPath, cfg.RootDir) } @@ -975,7 +973,7 @@ func (cfg *MempoolConfig) ValidateBasic() error { //----------------------------------------------------------------------------- // StateSyncConfig -// StateSyncConfig defines the configuration for the CometBFT state sync service +// StateSyncConfig defines the configuration for the CometBFT state sync service. type StateSyncConfig struct { Enable bool `mapstructure:"enable"` TempDir string `mapstructure:"temp_dir"` @@ -997,7 +995,7 @@ func (cfg *StateSyncConfig) TrustHashBytes() []byte { return bytes } -// DefaultStateSyncConfig returns a default configuration for the state sync service +// DefaultStateSyncConfig returns a default configuration for the state sync service. func DefaultStateSyncConfig() *StateSyncConfig { return &StateSyncConfig{ TrustPeriod: 168 * time.Hour, @@ -1007,7 +1005,7 @@ func DefaultStateSyncConfig() *StateSyncConfig { } } -// TestStateSyncConfig returns a default configuration for the state sync service +// TestStateSyncConfig returns a default configuration for the state sync service. func TestStateSyncConfig() *StateSyncConfig { return DefaultStateSyncConfig() } @@ -1065,12 +1063,12 @@ func (cfg *StateSyncConfig) ValidateBasic() error { //----------------------------------------------------------------------------- // BlockSyncConfig -// BlockSyncConfig (formerly known as FastSync) defines the configuration for the CometBFT block sync service +// BlockSyncConfig (formerly known as FastSync) defines the configuration for the CometBFT block sync service. type BlockSyncConfig struct { Version string `mapstructure:"version"` } -// DefaultBlockSyncConfig returns a default configuration for the block sync service +// DefaultBlockSyncConfig returns a default configuration for the block sync service. func DefaultBlockSyncConfig() *BlockSyncConfig { return &BlockSyncConfig{ Version: "v0", @@ -1137,7 +1135,7 @@ type ConsensusConfig struct { DoubleSignCheckHeight int64 `mapstructure:"double_sign_check_height"` } -// DefaultConsensusConfig returns a default configuration for the consensus service +// DefaultConsensusConfig returns a default configuration for the consensus service. func DefaultConsensusConfig() *ConsensusConfig { return &ConsensusConfig{ WalPath: filepath.Join(DefaultDataDir, "cs.wal", "wal"), @@ -1158,7 +1156,7 @@ func DefaultConsensusConfig() *ConsensusConfig { } } -// TestConsensusConfig returns a configuration for testing the consensus service +// TestConsensusConfig returns a configuration for testing the consensus service. func TestConsensusConfig() *ConsensusConfig { cfg := DefaultConsensusConfig() cfg.TimeoutPropose = 40 * time.Millisecond @@ -1176,26 +1174,26 @@ func TestConsensusConfig() *ConsensusConfig { return cfg } -// WaitForTxs returns true if the consensus should wait for transactions before entering the propose step +// WaitForTxs returns true if the consensus should wait for transactions before entering the propose step. func (cfg *ConsensusConfig) WaitForTxs() bool { return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0 } -// Propose returns the amount of time to wait for a proposal +// Propose returns the amount of time to wait for a proposal. func (cfg *ConsensusConfig) Propose(round int32) time.Duration { return time.Duration( cfg.TimeoutPropose.Nanoseconds()+cfg.TimeoutProposeDelta.Nanoseconds()*int64(round), ) * time.Nanosecond } -// Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes +// Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes. func (cfg *ConsensusConfig) Prevote(round int32) time.Duration { return time.Duration( cfg.TimeoutPrevote.Nanoseconds()+cfg.TimeoutPrevoteDelta.Nanoseconds()*int64(round), ) * time.Nanosecond } -// Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits +// Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits. func (cfg *ConsensusConfig) Precommit(round int32) time.Duration { return time.Duration( cfg.TimeoutPrecommit.Nanoseconds()+cfg.TimeoutPrecommitDelta.Nanoseconds()*int64(round), @@ -1208,7 +1206,7 @@ func (cfg *ConsensusConfig) Commit(t time.Time) time.Time { return t.Add(cfg.TimeoutCommit) } -// WalFile returns the full path to the write-ahead log file +// WalFile returns the full path to the write-ahead log file. func (cfg *ConsensusConfig) WalFile() string { if cfg.walFile != "" { return cfg.walFile @@ -1216,7 +1214,7 @@ func (cfg *ConsensusConfig) WalFile() string { return rootify(cfg.WalPath, cfg.RootDir) } -// SetWalFile sets the path to the write-ahead log file +// SetWalFile sets the path to the write-ahead log file. func (cfg *ConsensusConfig) SetWalFile(walFile string) { cfg.walFile = walFile } @@ -1405,7 +1403,7 @@ func (cfg *InstrumentationConfig) IsPrometheusEnabled() bool { //----------------------------------------------------------------------------- // Utils -// helper function to make config creation independent of root dir +// helper function to make config creation independent of root dir. func rootify(path, root string) string { if filepath.IsAbs(path) { return path diff --git a/config/db.go b/config/db.go index 1064a64935e..77c5b2ba279 100644 --- a/config/db.go +++ b/config/db.go @@ -4,7 +4,6 @@ import ( "context" dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/internal/service" "github.com/cometbft/cometbft/libs/log" ) diff --git a/config/toml.go b/config/toml.go index d696978b187..eeb567deee5 100644 --- a/config/toml.go +++ b/config/toml.go @@ -48,7 +48,7 @@ func EnsureRoot(rootDir string) { } // XXX: this func should probably be called by cmd/cometbft/commands/init.go -// alongside the writing of the genesis.json and priv_validator.json +// alongside the writing of the genesis.json and priv_validator.json. func writeDefaultConfigFile(configFilePath string) { WriteConfigFile(configFilePath, DefaultConfig()) } @@ -65,7 +65,7 @@ func WriteConfigFile(configFilePath string, config *Config) { } // Note: any changes to the comments/variables/mapstructure -// must be reflected in the appropriate struct in config/config.go +// must be reflected in the appropriate struct in config/config.go. const defaultConfigTemplate = `# This is a TOML config file. # For more information, see https://github.com/toml-lang/toml diff --git a/crypto/crypto.go b/crypto/crypto.go index e4825b13259..6507e5f0cbf 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -23,7 +23,7 @@ type PubKey interface { Address() Address Bytes() []byte VerifySignature(msg []byte, sig []byte) bool - Equals(PubKey) bool + Equals(other PubKey) bool Type() string } @@ -31,7 +31,7 @@ type PrivKey interface { Bytes() []byte Sign(msg []byte) ([]byte, error) PubKey() PubKey - Equals(PrivKey) bool + Equals(other PrivKey) bool Type() string } @@ -42,7 +42,7 @@ type Symmetric interface { } // If a new key type implements batch verification, -// the key type must be registered in github.com/cometbft/cometbft/crypto/batch +// the key type must be registered in github.com/cometbft/cometbft/crypto/batch. type BatchVerifier interface { // Add appends an entry into the BatchVerifier. Add(key PubKey, message, signature []byte) error diff --git a/crypto/ed25519/bench_test.go b/crypto/ed25519/bench_test.go index 114e872735b..9f325430dd8 100644 --- a/crypto/ed25519/bench_test.go +++ b/crypto/ed25519/bench_test.go @@ -5,10 +5,9 @@ import ( "io" "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/internal/benchmarking" + "github.com/stretchr/testify/require" ) func BenchmarkKeyGeneration(b *testing.B) { diff --git a/crypto/ed25519/ed25519.go b/crypto/ed25519/ed25519.go index 544cfc87dd5..6f36822edfa 100644 --- a/crypto/ed25519/ed25519.go +++ b/crypto/ed25519/ed25519.go @@ -7,12 +7,11 @@ import ( "fmt" "io" - "github.com/oasisprotocol/curve25519-voi/primitives/ed25519" - "github.com/oasisprotocol/curve25519-voi/primitives/ed25519/extra/cache" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/tmhash" cmtjson "github.com/cometbft/cometbft/libs/json" + "github.com/oasisprotocol/curve25519-voi/primitives/ed25519" + "github.com/oasisprotocol/curve25519-voi/primitives/ed25519/extra/cache" ) var ( @@ -47,7 +46,7 @@ var ( const ( PrivKeyName = "tendermint/PrivKeyEd25519" PubKeyName = "tendermint/PubKeyEd25519" - // PubKeySize is is the size, in bytes, of public keys as used in this package. + // PubKeySize is the size, in bytes, of public keys as used in this package. PubKeySize = 32 // PrivateKeySize is the size, in bytes, of private keys as used in this package. PrivateKeySize = 64 diff --git a/crypto/ed25519/ed25519_test.go b/crypto/ed25519/ed25519_test.go index 65696290929..3697f28bdac 100644 --- a/crypto/ed25519/ed25519_test.go +++ b/crypto/ed25519/ed25519_test.go @@ -3,11 +3,10 @@ package ed25519_test import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/ed25519" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSignAndValidateEd25519(t *testing.T) { diff --git a/crypto/encoding/codec.go b/crypto/encoding/codec.go index 511cbe52130..c9f4b8906a6 100644 --- a/crypto/encoding/codec.go +++ b/crypto/encoding/codec.go @@ -37,7 +37,7 @@ func init() { json.RegisterType((*pc.PublicKey_Secp256K1)(nil), "tendermint.crypto.PublicKey_Secp256K1") } -// PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey +// PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey. func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) { var kp pc.PublicKey switch k := k.(type) { @@ -59,7 +59,7 @@ func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) { return kp, nil } -// PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey +// PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey. func PubKeyFromProto(k pc.PublicKey) (crypto.PubKey, error) { switch k := k.Sum.(type) { case *pc.PublicKey_Ed25519: diff --git a/crypto/internal/benchmarking/bench.go b/crypto/internal/benchmarking/bench.go index de1c97974bb..20b5964b920 100644 --- a/crypto/internal/benchmarking/bench.go +++ b/crypto/internal/benchmarking/bench.go @@ -38,7 +38,6 @@ func BenchmarkSigning(b *testing.B, priv crypto.PrivKey) { b.ResetTimer() for i := 0; i < b.N; i++ { _, err := priv.Sign(message) - if err != nil { b.FailNow() } diff --git a/crypto/merkle/hash.go b/crypto/merkle/hash.go index be2010aefcc..2acbb1ef3e5 100644 --- a/crypto/merkle/hash.go +++ b/crypto/merkle/hash.go @@ -6,23 +6,23 @@ import ( "github.com/cometbft/cometbft/crypto/tmhash" ) -// TODO: make these have a large predefined capacity +// TODO: make these have a large predefined capacity. var ( leafPrefix = []byte{0} innerPrefix = []byte{1} ) -// returns tmhash() +// returns tmhash(). func emptyHash() []byte { return tmhash.Sum([]byte{}) } -// returns tmhash(0x00 || leaf) +// returns tmhash(0x00 || leaf). func leafHash(leaf []byte) []byte { return tmhash.Sum(append(leafPrefix, leaf...)) } -// returns tmhash(0x00 || leaf) +// returns tmhash(0x00 || leaf). func leafHashOpt(s hash.Hash, leaf []byte) []byte { s.Reset() s.Write(leafPrefix) @@ -30,7 +30,7 @@ func leafHashOpt(s hash.Hash, leaf []byte) []byte { return s.Sum(nil) } -// returns tmhash(0x01 || left || right) +// returns tmhash(0x01 || left || right). func innerHash(left []byte, right []byte) []byte { data := make([]byte, len(innerPrefix)+len(left)+len(right)) n := copy(data, innerPrefix) diff --git a/crypto/merkle/proof.go b/crypto/merkle/proof.go index 05afa7f711a..5fbd413d545 100644 --- a/crypto/merkle/proof.go +++ b/crypto/merkle/proof.go @@ -74,7 +74,7 @@ func ProofsFromByteSlices(items [][]byte) (rootHash []byte, proofs []*Proof) { } // Verify that the Proof proves the root hash. -// Check sp.Index/sp.Total manually if needed +// Check sp.Index/sp.Total manually if needed. func (sp *Proof) Verify(rootHash []byte, leaf []byte) error { if rootHash == nil { return ErrInvalidHash{ diff --git a/crypto/merkle/proof_key_path_test.go b/crypto/merkle/proof_key_path_test.go index 0d6d3354d33..1a6f8ac61fc 100644 --- a/crypto/merkle/proof_key_path_test.go +++ b/crypto/merkle/proof_key_path_test.go @@ -2,7 +2,7 @@ package merkle import ( // it is ok to use math/rand here: we do not need a cryptographically secure random - // number generator here and we can run the tests a bit faster + // number generator here and we can run the tests a bit faster. crand "crypto/rand" "math/rand" "testing" diff --git a/crypto/merkle/proof_op.go b/crypto/merkle/proof_op.go index 49a98be8464..1db58128633 100644 --- a/crypto/merkle/proof_op.go +++ b/crypto/merkle/proof_op.go @@ -21,7 +21,7 @@ var ErrKeyPathNotConsumed = errors.New("merkle: keypath not consumed") // ProofOp() encodes the ProofOperator in a generic way so it can later be // decoded with OpDecoder. type ProofOperator interface { - Run([][]byte) ([][]byte, error) + Run(leaves [][]byte) ([][]byte, error) GetKey() []byte ProofOp() cmtcrypto.ProofOp } @@ -31,7 +31,7 @@ type ProofOperator interface { // ProofOperators is a slice of ProofOperator(s). // Each operator will be applied to the input value sequentially -// and the last Merkle root will be verified with already known data +// and the last Merkle root will be verified with already known data. type ProofOperators []ProofOperator func (poz ProofOperators) VerifyValue(root []byte, keypath string, value []byte) (err error) { diff --git a/crypto/merkle/proof_test.go b/crypto/merkle/proof_test.go index 30b41a701fd..87771841168 100644 --- a/crypto/merkle/proof_test.go +++ b/crypto/merkle/proof_test.go @@ -6,11 +6,10 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - cmtcrypto "github.com/cometbft/cometbft/api/cometbft/crypto/v1" "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ProofOpDomino = "test:domino" diff --git a/crypto/merkle/tree.go b/crypto/merkle/tree.go index 896b67c5952..467a8527c66 100644 --- a/crypto/merkle/tree.go +++ b/crypto/merkle/tree.go @@ -97,7 +97,7 @@ func HashFromByteSlicesIterative(input [][]byte) []byte { } } -// getSplitPoint returns the largest power of 2 less than length +// getSplitPoint returns the largest power of 2 less than length. func getSplitPoint(length int64) int64 { if length < 1 { panic("Trying to split a tree with size < 1") diff --git a/crypto/merkle/tree_test.go b/crypto/merkle/tree_test.go index 69dca60a35f..d53409a92f3 100644 --- a/crypto/merkle/tree_test.go +++ b/crypto/merkle/tree_test.go @@ -4,13 +4,11 @@ import ( "encoding/hex" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - + "github.com/cometbft/cometbft/crypto/tmhash" cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/libs/test" - - "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testItem []byte diff --git a/crypto/merkle/types.go b/crypto/merkle/types.go index 6a5c7e6a362..3dc805ad80d 100644 --- a/crypto/merkle/types.go +++ b/crypto/merkle/types.go @@ -20,13 +20,13 @@ type Tree interface { Save() (hash []byte) Load(hash []byte) Copy() Tree - Iterate(func(key []byte, value []byte) (stop bool)) (stopped bool) + Iterate(fx func(key []byte, value []byte) (stop bool)) (stopped bool) IterateRange(start []byte, end []byte, ascending bool, fx func(key []byte, value []byte) (stop bool)) (stopped bool) } //----------------------------------------------------------------------- -// Uvarint length prefixed byteslice +// Uvarint length prefixed byteslice. func encodeByteSlice(w io.Writer, bz []byte) (err error) { var buf [binary.MaxVarintLen64]byte n := binary.PutUvarint(buf[:], uint64(len(bz))) diff --git a/crypto/random.go b/crypto/random.go index 275fb1044f2..543b7c91133 100644 --- a/crypto/random.go +++ b/crypto/random.go @@ -6,7 +6,7 @@ import ( "io" ) -// This only uses the OS's randomness +// This only uses the OS's randomness. func randBytes(numBytes int) []byte { b := make([]byte, numBytes) _, err := crand.Read(b) @@ -16,7 +16,7 @@ func randBytes(numBytes int) []byte { return b } -// This only uses the OS's randomness +// This only uses the OS's randomness. func CRandBytes(numBytes int) []byte { return randBytes(numBytes) } diff --git a/crypto/random_test.go b/crypto/random_test.go index 1c7bd1fb0a3..487c6d5b903 100644 --- a/crypto/random_test.go +++ b/crypto/random_test.go @@ -3,9 +3,8 @@ package crypto_test import ( "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" + "github.com/stretchr/testify/require" ) // the purpose of this test is primarily to ensure that the randomness diff --git a/crypto/secp256k1/secp256k1.go b/crypto/secp256k1/secp256k1.go index c6e31f1e794..6193bd8c6d2 100644 --- a/crypto/secp256k1/secp256k1.go +++ b/crypto/secp256k1/secp256k1.go @@ -10,13 +10,12 @@ import ( secp256k1 "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2/ecdsa" - "golang.org/x/crypto/ripemd160" //nolint: staticcheck // necessary for Bitcoin address format - "github.com/cometbft/cometbft/crypto" cmtjson "github.com/cometbft/cometbft/libs/json" + "golang.org/x/crypto/ripemd160" //nolint: staticcheck // necessary for Bitcoin address format ) -// ------------------------------------- +// -------------------------------------. const ( PrivKeyName = "tendermint/PrivKeySecp256k1" PubKeyName = "tendermint/PubKeySecp256k1" @@ -152,7 +151,7 @@ const PubKeySize = 33 // This prefix is followed with the x-coordinate. type PubKey []byte -// Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey)) +// Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey)). func (pubKey PubKey) Address() crypto.Address { if len(pubKey) != PubKeySize { panic("length of pubkey is incorrect") @@ -205,7 +204,7 @@ func (pubKey PubKey) VerifySignature(msg []byte, sigStr []byte) bool { // see: https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93 // Serialize() would negate S value if it is over half order. // Hence, if the signature is different after Serialize() if should be rejected. - var modifiedSignature, parseErr = ecdsa.ParseDERSignature(signature.Serialize()) + modifiedSignature, parseErr := ecdsa.ParseDERSignature(signature.Serialize()) if parseErr != nil { return false } diff --git a/crypto/secp256k1/secp256k1_internal_test.go b/crypto/secp256k1/secp256k1_internal_test.go index ae1f55e4926..2e8c7d13354 100644 --- a/crypto/secp256k1/secp256k1_internal_test.go +++ b/crypto/secp256k1/secp256k1_internal_test.go @@ -5,13 +5,11 @@ import ( "math/big" "testing" - "github.com/stretchr/testify/require" - secp256k1 "github.com/btcsuite/btcd/btcec/v2" + "github.com/stretchr/testify/require" ) func Test_genPrivKey(t *testing.T) { - empty := make([]byte, 32) oneB := big.NewInt(1).Bytes() onePadded := make([]byte, 32) diff --git a/crypto/secp256k1/secp256k1_test.go b/crypto/secp256k1/secp256k1_test.go index a9fc1edc6b9..5ed4fac0627 100644 --- a/crypto/secp256k1/secp256k1_test.go +++ b/crypto/secp256k1/secp256k1_test.go @@ -5,14 +5,12 @@ import ( "math/big" "testing" + underlyingSecp256k1 "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcutil/base58" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/secp256k1" - - underlyingSecp256k1 "github.com/btcsuite/btcd/btcec/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type keyData struct { diff --git a/crypto/sr25519/batch.go b/crypto/sr25519/batch.go index 05b71dc6334..7b0918fd10d 100644 --- a/crypto/sr25519/batch.go +++ b/crypto/sr25519/batch.go @@ -4,9 +4,8 @@ import ( "errors" "fmt" - "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" - "github.com/cometbft/cometbft/crypto" + "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" ) var _ crypto.BatchVerifier = &BatchVerifier{} diff --git a/crypto/sr25519/bench_test.go b/crypto/sr25519/bench_test.go index bee3f4f2470..0cccf6d3579 100644 --- a/crypto/sr25519/bench_test.go +++ b/crypto/sr25519/bench_test.go @@ -5,10 +5,9 @@ import ( "io" "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/internal/benchmarking" + "github.com/stretchr/testify/require" ) func BenchmarkKeyGeneration(b *testing.B) { diff --git a/crypto/sr25519/privkey.go b/crypto/sr25519/privkey.go index bc1c6820101..0431c07466a 100644 --- a/crypto/sr25519/privkey.go +++ b/crypto/sr25519/privkey.go @@ -5,9 +5,8 @@ import ( "fmt" "io" - "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" - "github.com/cometbft/cometbft/crypto" + "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" ) var ( diff --git a/crypto/sr25519/pubkey.go b/crypto/sr25519/pubkey.go index b25718f9a43..854854e8216 100644 --- a/crypto/sr25519/pubkey.go +++ b/crypto/sr25519/pubkey.go @@ -4,10 +4,9 @@ import ( "bytes" "fmt" - "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/tmhash" + "github.com/oasisprotocol/curve25519-voi/primitives/sr25519" ) var _ crypto.PubKey = PubKey{} diff --git a/crypto/sr25519/sr25519_test.go b/crypto/sr25519/sr25519_test.go index b2437be797f..b7783d364fa 100644 --- a/crypto/sr25519/sr25519_test.go +++ b/crypto/sr25519/sr25519_test.go @@ -5,11 +5,10 @@ import ( "encoding/json" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/sr25519" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSignAndValidateSr25519(t *testing.T) { diff --git a/crypto/tmhash/hash.go b/crypto/tmhash/hash.go index f9b9582420d..f714c405e5d 100644 --- a/crypto/tmhash/hash.go +++ b/crypto/tmhash/hash.go @@ -34,6 +34,7 @@ type sha256trunc struct { func (h sha256trunc) Write(p []byte) (n int, err error) { return h.sha256.Write(p) } + func (h sha256trunc) Sum(b []byte) []byte { shasum := h.sha256.Sum(b) return shasum[:TruncatedSize] diff --git a/crypto/tmhash/hash_test.go b/crypto/tmhash/hash_test.go index 0849391e576..2dfbc8684b3 100644 --- a/crypto/tmhash/hash_test.go +++ b/crypto/tmhash/hash_test.go @@ -4,10 +4,9 @@ import ( "crypto/sha256" "testing" + "github.com/cometbft/cometbft/crypto/tmhash" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/crypto/tmhash" ) func TestHash(t *testing.T) { diff --git a/crypto/xchacha20poly1305/xchachapoly.go b/crypto/xchacha20poly1305/xchachapoly.go index 6ae8e6ce9d3..b8020300686 100644 --- a/crypto/xchacha20poly1305/xchachapoly.go +++ b/crypto/xchacha20poly1305/xchachapoly.go @@ -10,7 +10,7 @@ import ( "golang.org/x/crypto/chacha20poly1305" ) -// Implements crypto.AEAD +// Implements crypto.AEAD. type xchacha20poly1305 struct { key [KeySize]byte } @@ -20,12 +20,12 @@ const ( KeySize = 32 // NonceSize is the size of the nonce used with this AEAD, in bytes. NonceSize = 24 - // TagSize is the size added from poly1305 + // TagSize is the size added from poly1305. TagSize = 16 - // MaxPlaintextSize is the max size that can be passed into a single call of Seal + // MaxPlaintextSize is the max size that can be passed into a single call of Seal. MaxPlaintextSize = (1 << 38) - 64 // MaxCiphertextSize is the max size that can be passed into a single call of Open, - // this differs from plaintext size due to the tag + // this differs from plaintext size due to the tag. MaxCiphertextSize = (1 << 38) - 48 // sigma are constants used in xchacha. @@ -42,7 +42,7 @@ var ( ErrInvalidCipherTextLen = errors.New("xchacha20poly1305: ciphertext too large") ) -// New returns a new xchachapoly1305 AEAD +// New returns a new xchachapoly1305 AEAD. func New(key []byte) (cipher.AEAD, error) { if len(key) != KeySize { return nil, ErrInvalidKeyLen diff --git a/crypto/xsalsa20symmetric/symmetric.go b/crypto/xsalsa20symmetric/symmetric.go index cfb0466af6e..7d7dd382901 100644 --- a/crypto/xsalsa20symmetric/symmetric.go +++ b/crypto/xsalsa20symmetric/symmetric.go @@ -4,9 +4,8 @@ import ( "errors" "fmt" - "golang.org/x/crypto/nacl/secretbox" - "github.com/cometbft/cometbft/crypto" + "golang.org/x/crypto/nacl/secretbox" ) // TODO, make this into a struct that implements crypto.Symmetric. diff --git a/crypto/xsalsa20symmetric/symmetric_test.go b/crypto/xsalsa20symmetric/symmetric_test.go index 7f0da23b391..a9e4a8ee34e 100644 --- a/crypto/xsalsa20symmetric/symmetric_test.go +++ b/crypto/xsalsa20symmetric/symmetric_test.go @@ -3,16 +3,13 @@ package xsalsa20symmetric import ( "testing" + "github.com/cometbft/cometbft/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "golang.org/x/crypto/bcrypt" - - "github.com/cometbft/cometbft/crypto" ) func TestSimple(t *testing.T) { - plaintext := []byte("sometext") secret := []byte("somesecretoflengththirtytwo===32") ciphertext := EncryptSymmetric(plaintext, secret) @@ -23,7 +20,6 @@ func TestSimple(t *testing.T) { } func TestSimpleWithKDF(t *testing.T) { - plaintext := []byte("sometext") secretPass := []byte("somesecret") secret, err := bcrypt.GenerateFromPassword(secretPass, 12) diff --git a/internal/async/async.go b/internal/async/async.go index e716821b633..2fb6173e3d8 100644 --- a/internal/async/async.go +++ b/internal/async/async.go @@ -54,7 +54,7 @@ func (trs *TaskResultSet) LatestResult(index int) (TaskResult, bool) { // Writes results to trs.results without waiting for all tasks to complete. func (trs *TaskResultSet) Reap() *TaskResultSet { for i := 0; i < len(trs.results); i++ { - var trch = trs.chz[i] + trch := trs.chz[i] select { case result, ok := <-trch: if ok { @@ -78,7 +78,7 @@ func (trs *TaskResultSet) Reap() *TaskResultSet { // Like Reap() but waits until all tasks have returned or panic'd. func (trs *TaskResultSet) Wait() *TaskResultSet { for i := 0; i < len(trs.results); i++ { - var trch = trs.chz[i] + trch := trs.chz[i] result, ok := <-trch if ok { // Write result. @@ -125,9 +125,9 @@ func (trs *TaskResultSet) FirstError() error { // concurrent quit-like primitives, passed implicitly via Task closures. (e.g. // it's not Parallel's concern how you quit/abort your tasks). func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) { - var taskResultChz = make([]TaskResultCh, len(tasks)) // To return. - var taskDoneCh = make(chan bool, len(tasks)) // A "wait group" channel, early abort if any true received. - var numPanics = new(int32) // Keep track of panics to set ok=false later. + taskResultChz := make([]TaskResultCh, len(tasks)) // To return. + taskDoneCh := make(chan bool, len(tasks)) // A "wait group" channel, early abort if any true received. + numPanics := new(int32) // Keep track of panics to set ok=false later. // We will set it to false iff any tasks panic'd or returned abort. ok = true @@ -136,7 +136,7 @@ func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) { // When the task is complete, it will appear in the // respective taskResultCh (associated by task index). for i, task := range tasks { - var taskResultCh = make(chan TaskResult, 1) // Capacity for 1 result. + taskResultCh := make(chan TaskResult, 1) // Capacity for 1 result. taskResultChz[i] = taskResultCh go func(i int, task Task, taskResultCh chan TaskResult) { // Recovery @@ -155,7 +155,7 @@ func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) { } }() // Run the task. - var val, abort, err = task(i) + val, abort, err := task(i) // Send val/err to taskResultCh. // NOTE: Below this line, nothing must panic/ taskResultCh <- TaskResult{val, err} diff --git a/internal/async/async_test.go b/internal/async/async_test.go index 4faead4443e..476059d9c5e 100644 --- a/internal/async/async_test.go +++ b/internal/async/async_test.go @@ -11,10 +11,9 @@ import ( ) func TestParallel(t *testing.T) { - // Create tasks. - var counter = new(int32) - var tasks = make([]Task, 100*1000) + counter := new(int32) + tasks := make([]Task, 100*1000) for i := 0; i < len(tasks); i++ { tasks[i] = func(i int) (res interface{}, abort bool, err error) { atomic.AddInt32(counter, 1) @@ -23,7 +22,7 @@ func TestParallel(t *testing.T) { } // Run in parallel. - var trs, ok = Parallel(tasks...) + trs, ok := Parallel(tasks...) assert.True(t, ok) // Verify. @@ -52,14 +51,13 @@ func TestParallel(t *testing.T) { } func TestParallelAbort(t *testing.T) { - var flow1 = make(chan struct{}, 1) var flow2 = make(chan struct{}, 1) var flow3 = make(chan struct{}, 1) // Cap must be > 0 to prevent blocking. var flow4 = make(chan struct{}, 1) // Create tasks. - var tasks = []Task{ + tasks := []Task{ func(i int) (res interface{}, abort bool, err error) { assert.Equal(t, i, 0) flow1 <- struct{}{} @@ -83,7 +81,7 @@ func TestParallelAbort(t *testing.T) { } // Run in parallel. - var taskResultSet, ok = Parallel(tasks...) + taskResultSet, ok := Parallel(tasks...) assert.False(t, ok, "ok should be false since we aborted task #2.") // Verify task #3. @@ -104,9 +102,8 @@ func TestParallelAbort(t *testing.T) { } func TestParallelRecover(t *testing.T) { - // Create tasks. - var tasks = []Task{ + tasks := []Task{ func(i int) (res interface{}, abort bool, err error) { return 0, false, nil }, @@ -119,7 +116,7 @@ func TestParallelRecover(t *testing.T) { } // Run in parallel. - var taskResultSet, ok = Parallel(tasks...) + taskResultSet, ok := Parallel(tasks...) assert.False(t, ok, "ok should be false since we panic'd in task #2.") // Verify task #0, #1, #2. @@ -128,9 +125,10 @@ func TestParallelRecover(t *testing.T) { checkResult(t, taskResultSet, 2, nil, nil, fmt.Errorf("panic in task %v", 2).Error()) } -// Wait for result +// Wait for result. func checkResult(t *testing.T, taskResultSet *TaskResultSet, index int, - val interface{}, err error, pnk interface{}) { + val interface{}, err error, pnk interface{}, +) { taskResult, ok := taskResultSet.LatestResult(index) taskName := fmt.Sprintf("Task #%v", index) assert.True(t, ok, "TaskResultCh unexpectedly closed for %v", taskName) @@ -145,7 +143,7 @@ func checkResult(t *testing.T, taskResultSet *TaskResultSet, index int, } } -// Wait for timeout (no result) +// Wait for timeout (no result). func waitTimeout(t *testing.T, taskResultCh TaskResultCh, taskName string) { select { case _, ok := <-taskResultCh: diff --git a/internal/autofile/autofile_test.go b/internal/autofile/autofile_test.go index d651f225ab5..fe748d9e839 100644 --- a/internal/autofile/autofile_test.go +++ b/internal/autofile/autofile_test.go @@ -7,10 +7,9 @@ import ( "testing" "time" + cmtos "github.com/cometbft/cometbft/internal/os" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - cmtos "github.com/cometbft/cometbft/internal/os" ) func TestSIGHUP(t *testing.T) { diff --git a/internal/autofile/cmd/logjack.go b/internal/autofile/cmd/logjack.go index 3da475820c5..66b09e3bcff 100644 --- a/internal/autofile/cmd/logjack.go +++ b/internal/autofile/cmd/logjack.go @@ -17,7 +17,7 @@ const ( readBufferSize = 1024 // 1KB at a time ) -// Parse command-line options +// Parse command-line options. func parseFlags() (headPath string, chopSize int64, limitSize int64, version bool) { flagSet := flag.NewFlagSet(os.Args[0], flag.ExitOnError) var chopSizeStr, limitSizeStr string diff --git a/internal/autofile/group.go b/internal/autofile/group.go index 1ba0ded42cc..61e98d22ad3 100644 --- a/internal/autofile/group.go +++ b/internal/autofile/group.go @@ -200,7 +200,7 @@ func (g *Group) MinIndex() int { // returns the number of bytes written. If nn < len(p), it also returns an // error explaining why the write is short. // NOTE: Writes are buffered so they don't write synchronously -// TODO: Make it halt if space is unavailable +// TODO: Make it halt if space is unavailable. func (g *Group) Write(p []byte) (nn int, err error) { g.mtx.Lock() defer g.mtx.Unlock() @@ -209,7 +209,7 @@ func (g *Group) Write(p []byte) (nn int, err error) { // WriteLine writes line into the current head of the group. It also appends "\n". // NOTE: Writes are buffered so they don't write synchronously -// TODO: Make it halt if space is unavailable +// TODO: Make it halt if space is unavailable. func (g *Group) WriteLine(line string) error { g.mtx.Lock() defer g.mtx.Unlock() @@ -353,7 +353,7 @@ func (g *Group) ReadGroupInfo() GroupInfo { } // Index includes the head. -// CONTRACT: caller should have called g.mtx.Lock +// CONTRACT: caller should have called g.mtx.Lock. func (g *Group) readGroupInfo() GroupInfo { groupDir := filepath.Dir(g.Head.Path) headBase := filepath.Base(g.Head.Path) @@ -496,7 +496,7 @@ func (gr *GroupReader) Read(p []byte) (n int, err error) { } // IF index > gr.Group.maxIndex, returns io.EOF -// CONTRACT: caller should hold gr.mtx +// CONTRACT: caller should hold gr.mtx. func (gr *GroupReader) openFile(index int) error { // Lock on Group to ensure that head doesn't move in the meanwhile. gr.Group.mtx.Lock() diff --git a/internal/autofile/group_test.go b/internal/autofile/group_test.go index 0af578804ca..ea4ef8d6b36 100644 --- a/internal/autofile/group_test.go +++ b/internal/autofile/group_test.go @@ -6,11 +6,10 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - cmtos "github.com/cometbft/cometbft/internal/os" cmtrand "github.com/cometbft/cometbft/internal/rand" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createTestGroupWithHeadSizeLimit(t *testing.T, headSizeLimit int64) *Group { diff --git a/internal/bits/bit_array.go b/internal/bits/bit_array.go index d63a97b85c8..504a3a0f837 100644 --- a/internal/bits/bit_array.go +++ b/internal/bits/bit_array.go @@ -31,7 +31,7 @@ func NewBitArray(bits int) *BitArray { } } -// Size returns the number of bits in the bitarray +// Size returns the number of bits in the bitarray. func (bA *BitArray) Size() int { if bA == nil { return 0 @@ -40,7 +40,7 @@ func (bA *BitArray) Size() int { } // GetIndex returns the bit at index i within the bit array. -// The behavior is undefined if i >= bA.Bits +// The behavior is undefined if i >= bA.Bits. func (bA *BitArray) GetIndex(i int) bool { if bA == nil { return false @@ -58,7 +58,7 @@ func (bA *BitArray) getIndex(i int) bool { } // SetIndex sets the bit at index i within the bit array. -// The behavior is undefined if i >= bA.Bits +// The behavior is undefined if i >= bA.Bits. func (bA *BitArray) SetIndex(i int, v bool) bool { if bA == nil { return false @@ -178,7 +178,7 @@ func (bA *BitArray) not() *BitArray { // Sub subtracts the two bit-arrays bitwise, without carrying the bits. // Note that carryless subtraction of a - b is (a and not b). // The output is the same as bA, regardless of o's size. -// If bA is longer than o, o is right padded with zeroes +// If bA is longer than o, o is right padded with zeroes. func (bA *BitArray) Sub(o *BitArray) *BitArray { if bA == nil || o == nil { // TODO: Decide if we should do 1's complement here? @@ -202,7 +202,7 @@ func (bA *BitArray) Sub(o *BitArray) *BitArray { return c } -// IsEmpty returns true iff all bits in the bit array are 0 +// IsEmpty returns true iff all bits in the bit array are 0. func (bA *BitArray) IsEmpty() bool { if bA == nil { return true // should this be opposite? @@ -418,7 +418,7 @@ func (bA *BitArray) UnmarshalJSON(bz []byte) error { return nil } -// ToProto converts BitArray to protobuf +// ToProto converts BitArray to protobuf. func (bA *BitArray) ToProto() *cmtprotobits.BitArray { if bA == nil || len(bA.Elems) == 0 { return nil @@ -433,6 +433,7 @@ func (bA *BitArray) ToProto() *cmtprotobits.BitArray { // FromProto sets a protobuf BitArray to the given pointer. func (bA *BitArray) FromProto(protoBitArray *cmtprotobits.BitArray) { if protoBitArray == nil { + //nolint:wastedassign bA = nil return } diff --git a/internal/bits/bit_array_test.go b/internal/bits/bit_array_test.go index 457609b552f..04a882f8713 100644 --- a/internal/bits/bit_array_test.go +++ b/internal/bits/bit_array_test.go @@ -6,10 +6,9 @@ import ( "fmt" "testing" + cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - cmtrand "github.com/cometbft/cometbft/internal/rand" ) func randBitArray(bits int) (*BitArray, []byte) { diff --git a/internal/blocksync/errors.go b/internal/blocksync/errors.go index 04926db9945..bafe2d1ac41 100644 --- a/internal/blocksync/errors.go +++ b/internal/blocksync/errors.go @@ -7,12 +7,10 @@ import ( "github.com/cosmos/gogoproto/proto" ) -var ( - // ErrNilMessage is returned when provided message is empty - ErrNilMessage = errors.New("message cannot be nil") -) +// ErrNilMessage is returned when provided message is empty. +var ErrNilMessage = errors.New("message cannot be nil") -// ErrInvalidBase is returned when peer informs of a status with invalid height +// ErrInvalidBase is returned when peer informs of a status with invalid height. type ErrInvalidHeight struct { Height int64 Reason string @@ -22,7 +20,7 @@ func (e ErrInvalidHeight) Error() string { return fmt.Sprintf("invalid height %v: %s", e.Height, e.Reason) } -// ErrInvalidBase is returned when peer informs of a status with invalid base +// ErrInvalidBase is returned when peer informs of a status with invalid base. type ErrInvalidBase struct { Base int64 Reason string diff --git a/internal/blocksync/metrics.go b/internal/blocksync/metrics.go index 204b127ba4a..f120b4f7c44 100644 --- a/internal/blocksync/metrics.go +++ b/internal/blocksync/metrics.go @@ -1,9 +1,8 @@ package blocksync import ( - "github.com/go-kit/kit/metrics" - "github.com/cometbft/cometbft/types" + "github.com/go-kit/kit/metrics" ) const ( diff --git a/internal/blocksync/msgs.go b/internal/blocksync/msgs.go index 574938a052d..08f4a99ac60 100644 --- a/internal/blocksync/msgs.go +++ b/internal/blocksync/msgs.go @@ -3,14 +3,13 @@ package blocksync import ( "fmt" - "github.com/cosmos/gogoproto/proto" - bcproto "github.com/cometbft/cometbft/api/cometbft/blocksync/v1" "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/proto" ) const ( - // NOTE: keep up to date with bcproto.BlockResponse + // NOTE: keep up to date with bcproto.BlockResponse. BlockResponseMessagePrefixSize = 4 BlockResponseMessageFieldKeySize = 1 MaxMsgSize = types.MaxBlockSizeBytes + diff --git a/internal/blocksync/pool.go b/internal/blocksync/pool.go index b9a2c66c7ce..e702b97acba 100644 --- a/internal/blocksync/pool.go +++ b/internal/blocksync/pool.go @@ -35,8 +35,8 @@ const ( requestRetrySeconds = 30 // Minimum recv rate to ensure we're receiving blocks from a peer fast - // enough. If a peer is not sending us data at at least that rate, we - // consider them to have timedout and we disconnect. + // enough. If a peer is not sending us data at least that rate, we consider + // them to have timed out, and we disconnect. // // Assuming a DSL connection (not a good choice) 128 Kbps (upload) ~ 15 KB/s, // sending data across atlantic ~ 7.5 KB/s. @@ -104,7 +104,7 @@ func (pool *BlockPool) OnStart() error { return nil } -// spawns requesters as needed +// spawns requesters as needed. func (pool *BlockPool) makeRequestersRoutine() { for { if !pool.IsRunning() { @@ -619,7 +619,7 @@ func (bpr *bpRequester) redo(peerID p2p.ID) { } // Responsible for making more requests as necessary -// Returns only when a block is found (e.g. AddBlock() is called) +// Returns only when a block is found (e.g. AddBlock() is called). func (bpr *bpRequester) requestRoutine() { OUTER_LOOP: for { @@ -676,7 +676,7 @@ OUTER_LOOP: } // BlockRequest stores a block request identified by the block Height and the PeerID responsible for -// delivering the block +// delivering the block. type BlockRequest struct { Height int64 PeerID p2p.ID diff --git a/internal/blocksync/reactor.go b/internal/blocksync/reactor.go index 6fe68cfa841..969b8336614 100644 --- a/internal/blocksync/reactor.go +++ b/internal/blocksync/reactor.go @@ -14,18 +14,18 @@ import ( ) const ( - // BlocksyncChannel is a channel for blocks and status updates (`BlockStore` height) + // BlocksyncChannel is a channel for blocks and status updates (`BlockStore` height). BlocksyncChannel = byte(0x40) trySyncIntervalMS = 10 // stop syncing when last block's time is // within this much of the system time. - // stopSyncingDurationMinutes = 10 + // stopSyncingDurationMinutes = 10. - // ask for best height every 10s + // ask for best height every 10s. statusUpdateIntervalSeconds = 10 - // check if we should switch to consensus reactor + // check if we should switch to consensus reactor. switchToConsensusIntervalSeconds = 1 ) @@ -153,7 +153,7 @@ func (bcR *Reactor) OnStop() { } } -// GetChannels implements Reactor +// GetChannels implements Reactor. func (bcR *Reactor) GetChannels() []*p2p.ChannelDescriptor { return []*p2p.ChannelDescriptor{ { @@ -339,7 +339,6 @@ func (bcR *Reactor) poolRoutine(stateSynced bool) { case <-statusUpdateTicker.C: // ask for status updates go bcR.BroadcastStatusRequest() - } } }() @@ -471,10 +470,8 @@ FOR_LOOP: // if vote extensions were required at this height, ensure they exist. if state.ConsensusParams.ABCI.VoteExtensionsEnabled(first.Height) { err = extCommit.EnsureExtensions(true) - } else { - if extCommit != nil { - err = fmt.Errorf("received non-nil extCommit for height %d (extensions disabled)", first.Height) - } + } else if extCommit != nil { + err = fmt.Errorf("received non-nil extCommit for height %d (extensions disabled)", first.Height) } } if err != nil { diff --git a/internal/clist/clist.go b/internal/clist/clist.go index 57e7d262c33..236740e5f31 100644 --- a/internal/clist/clist.go +++ b/internal/clist/clist.go @@ -177,7 +177,7 @@ func (e *CElement) SetNext(newNext *CElement) { } // NOTE: This function needs to be safe for -// concurrent goroutines waiting on prevWg +// concurrent goroutines waiting on prevWg. func (e *CElement) SetPrev(newPrev *CElement) { e.mtx.Lock() diff --git a/internal/clist/clist_test.go b/internal/clist/clist_test.go index ff46b8b6c4b..ce64c246fa8 100644 --- a/internal/clist/clist_test.go +++ b/internal/clist/clist_test.go @@ -7,9 +7,8 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - cmtrand "github.com/cometbft/cometbft/internal/rand" + "github.com/stretchr/testify/assert" ) func TestPanicOnMaxLength(t *testing.T) { @@ -220,7 +219,6 @@ func TestScanRightDeleteRandom(t *testing.T) { if i%100000 == 0 { fmt.Printf("Pushed %vK elements so far...\n", i/1000) } - } // Stop scanners diff --git a/internal/cmap/cmap.go b/internal/cmap/cmap.go index f6b379eced5..515b2b19291 100644 --- a/internal/cmap/cmap.go +++ b/internal/cmap/cmap.go @@ -4,7 +4,7 @@ import ( cmtsync "github.com/cometbft/cometbft/internal/sync" ) -// CMap is a goroutine-safe map +// CMap is a goroutine-safe map. type CMap struct { m map[string]interface{} l cmtsync.Mutex diff --git a/internal/consensus/errors.go b/internal/consensus/errors.go index e37e3dc7605..6f2e3fc4b6e 100644 --- a/internal/consensus/errors.go +++ b/internal/consensus/errors.go @@ -14,7 +14,7 @@ var ( ErrProposalWithoutPreviousCommit = errors.New("propose step; cannot propose anything without commit for the previous block") ) -// Consensus sentinel errors +// Consensus sentinel errors. var ( ErrInvalidProposalSignature = errors.New("error invalid proposal signature") ErrInvalidProposalPOLRound = errors.New("error invalid proposal POL round") diff --git a/internal/consensus/metrics.go b/internal/consensus/metrics.go index dd63e49a8d3..52cbdb0f074 100644 --- a/internal/consensus/metrics.go +++ b/internal/consensus/metrics.go @@ -4,10 +4,9 @@ import ( "strings" "time" - "github.com/go-kit/kit/metrics" - cstypes "github.com/cometbft/cometbft/internal/consensus/types" "github.com/cometbft/cometbft/types" + "github.com/go-kit/kit/metrics" ) const ( @@ -30,7 +29,7 @@ type Metrics struct { Rounds metrics.Gauge // Histogram of round duration. - RoundDurationSeconds metrics.Histogram `metrics_buckettype:"exprange" metrics_bucketsizes:"0.1, 100, 8"` + RoundDurationSeconds metrics.Histogram `metrics_bucketsizes:"0.1, 100, 8" metrics_buckettype:"exprange"` // Number of validators. Validators metrics.Gauge @@ -71,7 +70,7 @@ type Metrics struct { DuplicateVote metrics.Counter // Histogram of durations for each step in the consensus protocol. - StepDurationSeconds metrics.Histogram `metrics_labels:"step" metrics_buckettype:"exprange" metrics_bucketsizes:"0.1, 100, 8"` + StepDurationSeconds metrics.Histogram `metrics_bucketsizes:"0.1, 100, 8" metrics_buckettype:"exprange" metrics_labels:"step"` stepStart time.Time // Number of block parts received by the node, separated by whether the part diff --git a/internal/consensus/msgs.go b/internal/consensus/msgs.go index a5f229c7ae1..442e2272d03 100644 --- a/internal/consensus/msgs.go +++ b/internal/consensus/msgs.go @@ -3,10 +3,6 @@ package consensus import ( "fmt" - "github.com/cosmos/gogoproto/proto" - - cmterrors "github.com/cometbft/cometbft/types/errors" - cmtcons "github.com/cometbft/cometbft/api/cometbft/consensus/v1" cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cometbft/cometbft/internal/bits" @@ -14,6 +10,8 @@ import ( cmtmath "github.com/cometbft/cometbft/libs/math" "github.com/cometbft/cometbft/p2p" "github.com/cometbft/cometbft/types" + cmterrors "github.com/cometbft/cometbft/types/errors" + "github.com/cosmos/gogoproto/proto" ) // TODO: This needs to be removed, but WALToProto depends on this. @@ -125,7 +123,7 @@ func MsgToWrappedProto(msg Message) (cmtcons.Message, error) { return pb, nil } -// MsgFromProto takes a consensus proto message and returns the native go type +// MsgFromProto takes a consensus proto message and returns the native go type. func MsgFromProto(p proto.Message) (Message, error) { if p == nil { return nil, ErrNilMessage @@ -250,7 +248,7 @@ func MsgFromProto(p proto.Message) (Message, error) { return pb, nil } -// WALToProto takes a WAL message and return a proto walMessage and error +// WALToProto takes a WAL message and return a proto walMessage and error. func WALToProto(msg WALMessage) (*cmtcons.WALMessage, error) { var pb cmtcons.WALMessage @@ -304,7 +302,7 @@ func WALToProto(msg WALMessage) (*cmtcons.WALMessage, error) { return &pb, nil } -// WALFromProto takes a proto wal message and return a consensus walMessage and error +// WALFromProto takes a proto wal message and return a consensus walMessage and error. func WALFromProto(msg *cmtcons.WALMessage) (WALMessage, error) { if msg == nil { return nil, ErrNilMessage diff --git a/internal/consensus/reactor.go b/internal/consensus/reactor.go index 05b00d6cabf..87927261848 100644 --- a/internal/consensus/reactor.go +++ b/internal/consensus/reactor.go @@ -7,8 +7,6 @@ import ( "sync/atomic" "time" - cmterrors "github.com/cometbft/cometbft/types/errors" - cmtcons "github.com/cometbft/cometbft/api/cometbft/consensus/v1" "github.com/cometbft/cometbft/internal/bits" cstypes "github.com/cometbft/cometbft/internal/consensus/types" @@ -20,6 +18,7 @@ import ( "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/p2p" "github.com/cometbft/cometbft/types" + cmterrors "github.com/cometbft/cometbft/types/errors" cmttime "github.com/cometbft/cometbft/types/time" ) @@ -149,7 +148,7 @@ conR: } } -// GetChannels implements Reactor +// GetChannels implements Reactor. func (conR *Reactor) GetChannels() []*p2p.ChannelDescriptor { // TODO optimize return []*p2p.ChannelDescriptor{ @@ -236,7 +235,7 @@ func (conR *Reactor) RemovePeer(p2p.Peer, interface{}) { // Messages affect either a peer state or the consensus state. // Peer state updates can happen in parallel, but processing of // proposals, block parts, and votes are ordered by the receiveRoutine -// NOTE: blocks on consensus state for proposals, block parts, and votes +// NOTE: blocks on consensus state for proposals, block parts, and votes. func (conR *Reactor) Receive(e p2p.Envelope) { if !conR.IsRunning() { conR.Logger.Debug("Receive", "src", e.Src, "chId", e.ChannelID) @@ -741,7 +740,6 @@ func (conR *Reactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) { OUTER_LOOP: for { - // Manage disconnects from self or peer. if !peer.IsRunning() || !conR.IsRunning() { return @@ -906,7 +904,6 @@ OUTER_LOOP: prs := ps.GetRoundState() if rs.Height == prs.Height { if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok { - peer.TrySend(p2p.Envelope{ ChannelID: StateChannel, Message: &cmtcons.VoteSetMaj23{ @@ -947,7 +944,6 @@ OUTER_LOOP: prs := ps.GetRoundState() if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 { if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok { - peer.TrySend(p2p.Envelope{ ChannelID: StateChannel, Message: &cmtcons.VoteSetMaj23{ @@ -1039,7 +1035,7 @@ func (conR *Reactor) String() string { return "ConsensusReactor" // conR.StringIndented("") } -// StringIndented returns an indented string representation of the Reactor +// StringIndented returns an indented string representation of the Reactor. func (conR *Reactor) StringIndented(indent string) string { s := "ConsensusReactor{\n" s += indent + " " + conR.conS.StringIndented(indent+" ") + "\n" @@ -1054,7 +1050,7 @@ func (conR *Reactor) StringIndented(indent string) string { return s } -// ReactorMetrics sets the metrics +// ReactorMetrics sets the metrics. func ReactorMetrics(metrics *Metrics) ReactorOption { return func(conR *Reactor) { conR.Metrics = metrics } } @@ -1085,7 +1081,7 @@ func (pss peerStateStats) String() string { pss.Votes, pss.BlockParts) } -// NewPeerState returns a new PeerState for the given Peer +// NewPeerState returns a new PeerState for the given Peer. func NewPeerState(peer p2p.Peer) *PeerState { return &PeerState{ peer: peer, @@ -1127,7 +1123,7 @@ func (ps *PeerState) MarshalJSON() ([]byte, error) { } // GetHeight returns an atomic snapshot of the PeerRoundState's height -// used by the mempool to ensure peers are caught up before broadcasting new txs +// used by the mempool to ensure peers are caught up before broadcasting new txs. func (ps *PeerState) GetHeight() int64 { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -1388,7 +1384,7 @@ func (ps *PeerState) BlockPartsSent() int { return ps.Stats.BlockParts } -// SetHasVote sets the given vote as known by the peer +// SetHasVote sets the given vote as known by the peer. func (ps *PeerState) SetHasVote(vote *types.Vote) { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -1544,12 +1540,12 @@ func (ps *PeerState) ApplyVoteSetBitsMessage(msg *VoteSetBitsMessage, ourVotes * } } -// String returns a string representation of the PeerState +// String returns a string representation of the PeerState. func (ps *PeerState) String() string { return ps.StringIndented("") } -// StringIndented returns a string representation of the PeerState +// StringIndented returns a string representation of the PeerState. func (ps *PeerState) StringIndented(indent string) string { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -1567,7 +1563,7 @@ func (ps *PeerState) StringIndented(indent string) string { //----------------------------------------------------------------------------- // Messages -// Message is a message that can be sent and received on the Reactor +// Message is a message that can be sent and received on the Reactor. type Message interface { ValidateBasic() error } @@ -1588,7 +1584,7 @@ func init() { //------------------------------------- // NewRoundStepMessage is sent for every step taken in the ConsensusState. -// For every height/round/step transition +// For every height/round/step transition. type NewRoundStepMessage struct { Height int64 Round int32 diff --git a/internal/consensus/state.go b/internal/consensus/state.go index d2719b1ed6a..d52ba562dd5 100644 --- a/internal/consensus/state.go +++ b/internal/consensus/state.go @@ -11,8 +11,6 @@ import ( "sort" "time" - "github.com/cosmos/gogoproto/proto" - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/crypto" @@ -30,17 +28,18 @@ import ( "github.com/cometbft/cometbft/types" cmterrors "github.com/cometbft/cometbft/types/errors" cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cosmos/gogoproto/proto" ) var msgQueueSize = 1000 -// msgs from the reactor which may update the state +// msgs from the reactor which may update the state. type msgInfo struct { Msg Message `json:"msg"` PeerID p2p.ID `json:"peer_key"` } -// internally generated messages which may update the state +// internally generated messages which may update the state. type timeoutInfo struct { Duration time.Duration `json:"duration"` Height int64 `json:"height"` @@ -52,12 +51,12 @@ func (ti *timeoutInfo) String() string { return fmt.Sprintf("%v ; %d/%d %v", ti.Duration, ti.Height, ti.Round, ti.Step) } -// interface to the mempool +// interface to the mempool. type txNotifier interface { TxsAvailable() <-chan struct{} } -// interface to the evidence pool +// interface to the evidence pool. type evidencePool interface { // reports conflicting votes to the evidence pool to be processed into evidence ReportConflictingVotes(voteA, voteB *types.Vote) @@ -256,7 +255,7 @@ func (cs *State) GetRoundStateJSON() ([]byte, error) { return cmtjson.Marshal(cs.RoundState) } -// GetRoundStateSimpleJSON returns a json of RoundStateSimple +// GetRoundStateSimpleJSON returns a json of RoundStateSimple. func (cs *State) GetRoundStateSimpleJSON() ([]byte, error) { cs.mtx.RLock() defer cs.mtx.RUnlock() @@ -395,7 +394,9 @@ func (cs *State) OnStart() error { } // timeoutRoutine: receive requests for timeouts on tickChan and fire timeouts on tockChan -// receiveRoutine: serializes processing of proposoals, block parts, votes; coordinates state transitions +// receiveRoutine: serializes processing of proposoals, block parts, votes; coordinates state transitions. +// +//nolint:unused func (cs *State) startRoutines(maxSteps int) { err := cs.timeoutTicker.Start() if err != nil { @@ -432,7 +433,7 @@ func (cs *State) OnStop() { // Wait waits for the the main routine to return. // NOTE: be sure to Stop() the event switch and drain -// any event channels or this may deadlock +// any event channels or this may deadlock. func (cs *State) Wait() { <-cs.done } @@ -502,7 +503,7 @@ func (cs *State) AddProposalBlockPart(height int64, round int32, part *types.Par // SetProposalAndBlock inputs the proposal and all block parts. func (cs *State) SetProposalAndBlock( proposal *types.Proposal, - block *types.Block, //nolint:revive + block *types.Block, parts *types.PartSet, peerID p2p.ID, ) error { @@ -549,12 +550,12 @@ func (cs *State) scheduleRound0(rs *cstypes.RoundState) { cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight) } -// Attempt to schedule a timeout (by sending timeoutInfo on the tickChan) +// Attempt to schedule a timeout (by sending timeoutInfo on the tickChan). func (cs *State) scheduleTimeout(duration time.Duration, height int64, round int32, step cstypes.RoundStepType) { cs.timeoutTicker.ScheduleTimeout(timeoutInfo{duration, height, round, step}) } -// send a msg into the receiveRoutine regarding our own proposal, block part, or vote +// send a msg into the receiveRoutine regarding our own proposal, block part, or vote. func (cs *State) sendInternalMessage(mi msgInfo) { select { case cs.internalMsgQueue <- mi: @@ -861,7 +862,7 @@ func (cs *State) receiveRoutine(maxSteps int) { } } -// state transitions on complete-proposal, 2/3-any, 2/3-one +// state transitions on complete-proposal, 2/3-any, 2/3-one. func (cs *State) handleMsg(mi msgInfo) { cs.mtx.Lock() defer cs.mtx.Unlock() @@ -1104,7 +1105,7 @@ func (cs *State) enterNewRound(height int64, round int32) { } // needProofBlock returns true on the first height (so the genesis app hash is signed right away) -// and where the last block (height-1) caused the app hash to change +// and where the last block (height-1) caused the app hash to change. func (cs *State) needProofBlock(height int64) bool { if height == cs.state.InitialHeight { return true @@ -1125,7 +1126,7 @@ func (cs *State) needProofBlock(height int64) bool { // // after enterNewRound(height,round), after timeout of CreateEmptyBlocksInterval // -// Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool +// Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool. func (cs *State) enterPropose(height int64, round int32) { logger := cs.Logger.With("height", height, "round", round) @@ -1644,7 +1645,7 @@ func (cs *State) enterPrecommitWait(height int64, round int32) { cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait) } -// Enter: +2/3 precommits for block +// Enter: +2/3 precommits for block. func (cs *State) enterCommit(height int64, commitRound int32) { logger := cs.Logger.With("height", height, "commit_round", commitRound) @@ -1735,7 +1736,7 @@ func (cs *State) tryFinalizeCommit(height int64) { cs.finalizeCommit(height) } -// Increment height and goto cstypes.RoundStepNewHeight +// Increment height and goto cstypes.RoundStepNewHeight. func (cs *State) finalizeCommit(height int64) { logger := cs.Logger.With("height", height) @@ -1909,7 +1910,6 @@ func (cs *State) recordMetrics(height int64, block *types.Block) { cs.metrics.ValidatorMissedBlocks.With(label...).Add(float64(1)) } } - } } cs.metrics.MissingValidators.Set(float64(missingValidators)) @@ -2106,7 +2106,7 @@ func (cs *State) handleCompleteProposal(blockHeight int64) { } } -// Attempt to add the vote. if its a duplicate signature, dupeout the validator +// Attempt to add the vote. if its a duplicate signature, dupeout the validator. func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) { added, err := cs.addVote(vote, peerID) // NOTE: some of these errors are swallowed here @@ -2230,7 +2230,6 @@ func (cs *State) addVote(vote *types.Vote, peerID p2p.ID) (added bool, err error // https://github.com/tendermint/tendermint/issues/8487 if vote.Type == types.PrecommitType && !vote.BlockID.IsNil() && !bytes.Equal(vote.ValidatorAddress, myAddr) { // Skip the VerifyVoteExtension call if the vote was issued by this validator. - // The core fields of the vote message were already validated in the // consensus reactor when the vote was received. // Here, we verify the signature of the vote extension included in the vote @@ -2246,16 +2245,14 @@ func (cs *State) addVote(vote *types.Vote, peerID p2p.ID) (added bool, err error return false, err } } - } else { + } else if len(vote.Extension) > 0 || len(vote.ExtensionSignature) > 0 { // Vote extensions are not enabled on the network. // Reject the vote, as it is malformed // // TODO punish a peer if it sent a vote with an extension when the feature // is disabled on the network. // https://github.com/tendermint/tendermint/issues/8565 - if len(vote.Extension) > 0 || len(vote.ExtensionSignature) > 0 { - return false, fmt.Errorf("received vote with vote extension for height %v (extensions disabled) from peer ID %s", vote.Height, peerID) - } + return false, fmt.Errorf("received vote with vote extension for height %v (extensions disabled) from peer ID %s", vote.Height, peerID) } height := cs.Height @@ -2448,7 +2445,7 @@ func (cs *State) voteTime() time.Time { } // sign the vote and publish on internalMsgQueue -// block information is only used to extend votes (precommit only); should be nil in all other cases +// block information is only used to extend votes (precommit only); should be nil in all other cases. func (cs *State) signAddVote( msgType types.SignedMsgType, hash []byte, @@ -2502,7 +2499,7 @@ func (cs *State) updatePrivValidatorPubKey() error { return nil } -// look back to check existence of the node's consensus votes before joining consensus +// look back to check existence of the node's consensus votes before joining consensus. func (cs *State) checkDoubleSigningRisk(height int64) error { if cs.privValidator != nil && cs.privValidatorPubKey != nil && cs.config.DoubleSignCheckHeight > 0 && height > 0 { valAddr := cs.privValidatorPubKey.Address() @@ -2607,5 +2604,6 @@ func repairWalFile(src, dst string) error { } } + //nolint:nilerr return nil } diff --git a/internal/consensus/ticker.go b/internal/consensus/ticker.go index a9b8be20c03..f6b1e13ee8a 100644 --- a/internal/consensus/ticker.go +++ b/internal/consensus/ticker.go @@ -18,7 +18,7 @@ type TimeoutTicker interface { Chan() <-chan timeoutInfo // on which to receive a timeout ScheduleTimeout(ti timeoutInfo) // reset the timer - SetLogger(log.Logger) + SetLogger(l log.Logger) } // timeoutTicker wraps time.Timer, @@ -73,7 +73,7 @@ func (t *timeoutTicker) ScheduleTimeout(ti timeoutInfo) { //------------------------------------------------------------- -// stop the timer and drain if necessary +// stop the timer and drain if necessary. func (t *timeoutTicker) stopTimer() { // Stop() returns false if it was already fired or was stopped if !t.timer.Stop() { @@ -87,7 +87,7 @@ func (t *timeoutTicker) stopTimer() { // send on tickChan to start a new timer. // timers are interrupted and replaced by new ticks from later steps -// timeouts of 0 on the tickChan will be immediately relayed to the tockChan +// timeouts of 0 on the tickChan will be immediately relayed to the tockChan. func (t *timeoutTicker) timeoutRoutine() { t.Logger.Debug("Starting timeout routine") var ti timeoutInfo diff --git a/internal/consensus/types/height_vote_set.go b/internal/consensus/types/height_vote_set.go index 67bba53b335..406992b8e0d 100644 --- a/internal/consensus/types/height_vote_set.go +++ b/internal/consensus/types/height_vote_set.go @@ -17,10 +17,8 @@ type RoundVoteSet struct { Precommits *types.VoteSet } -var ( - ErrGotVoteFromUnwantedRound = errors.New( - "peer has sent a vote that does not match our round for more than one round", - ) +var ErrGotVoteFromUnwantedRound = errors.New( + "peer has sent a vote that does not match our round for more than one round", ) /* @@ -199,12 +197,13 @@ func (hvs *HeightVoteSet) getVoteSet(round int32, voteType types.SignedMsgType) // If a peer claims that it has 2/3 majority for given blockKey, call this. // NOTE: if there are too many peers, or too much peer churn, // this can cause memory issues. -// TODO: implement ability to remove peers too +// TODO: implement ability to remove peers too. func (hvs *HeightVoteSet) SetPeerMaj23( round int32, voteType types.SignedMsgType, peerID p2p.ID, - blockID types.BlockID) error { + blockID types.BlockID, +) error { hvs.mtx.Lock() defer hvs.mtx.Unlock() if !types.IsVoteTypeValid(voteType) { diff --git a/internal/consensus/types/peer_round_state.go b/internal/consensus/types/peer_round_state.go index 955354cd12e..7bc2da3e3c1 100644 --- a/internal/consensus/types/peer_round_state.go +++ b/internal/consensus/types/peer_round_state.go @@ -43,12 +43,12 @@ type PeerRoundState struct { CatchupCommit *bits.BitArray `json:"catchup_commit"` } -// String returns a string representation of the PeerRoundState +// String returns a string representation of the PeerRoundState. func (prs PeerRoundState) String() string { return prs.StringIndented("") } -// StringIndented returns a string representation of the PeerRoundState +// StringIndented returns a string representation of the PeerRoundState. func (prs PeerRoundState) StringIndented(indent string) string { return fmt.Sprintf(`PeerRoundState{ %s %v/%v/%v @%v diff --git a/internal/consensus/types/round_state.go b/internal/consensus/types/round_state.go index 6749d4265a0..d631754def7 100644 --- a/internal/consensus/types/round_state.go +++ b/internal/consensus/types/round_state.go @@ -12,10 +12,10 @@ import ( //----------------------------------------------------------------------------- // RoundStepType enum type -// RoundStepType enumerates the state of the consensus state machine +// RoundStepType enumerates the state of the consensus state machine. type RoundStepType uint8 // These must be numeric, ordered. -// RoundStepType +// RoundStepType. const ( RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose @@ -35,7 +35,7 @@ func (rs RoundStepType) IsValid() bool { return uint8(rs) >= 0x01 && uint8(rs) <= 0x08 } -// String returns a string +// String returns a string. func (rs RoundStepType) String() string { switch rs { case RoundStepNewHeight: @@ -63,7 +63,7 @@ func (rs RoundStepType) String() string { // RoundState defines the internal consensus state. // NOTE: Not thread safe. Should only be manipulated by functions downstream -// of the cs.receiveRoutine +// of the cs.receiveRoutine. type RoundState struct { Height int64 `json:"height"` // Height we are working on Round int32 `json:"round"` @@ -102,7 +102,7 @@ type RoundState struct { TriggeredTimeoutPrecommit bool `json:"triggered_timeout_precommit"` } -// Compressed version of the RoundState for use in RPC +// Compressed version of the RoundState for use in RPC. type RoundStateSimple struct { HeightRoundStep string `json:"height/round/step"` StartTime time.Time `json:"start_time"` @@ -113,7 +113,7 @@ type RoundStateSimple struct { Proposer types.ValidatorInfo `json:"proposer"` } -// Compress the RoundState to RoundStateSimple +// Compress the RoundState to RoundStateSimple. func (rs *RoundState) RoundStateSimple() RoundStateSimple { votesJSON, err := rs.Votes.MarshalJSON() if err != nil { @@ -179,12 +179,12 @@ func (rs *RoundState) RoundStateEvent() types.EventDataRoundState { } } -// String returns a string +// String returns a string. func (rs *RoundState) String() string { return rs.StringIndented("") } -// StringIndented returns a string +// StringIndented returns a string. func (rs *RoundState) StringIndented(indent string) string { return fmt.Sprintf(`RoundState{ %s H:%v R:%v S:%v @@ -217,7 +217,7 @@ func (rs *RoundState) StringIndented(indent string) string { indent) } -// StringShort returns a string +// StringShort returns a string. func (rs *RoundState) StringShort() string { return fmt.Sprintf(`RoundState{H:%v R:%v S:%v ST:%v}`, rs.Height, rs.Round, rs.Step, rs.StartTime) diff --git a/internal/consensus/wal.go b/internal/consensus/wal.go index f5d6986f97d..53bbdc10463 100644 --- a/internal/consensus/wal.go +++ b/internal/consensus/wal.go @@ -9,8 +9,6 @@ import ( "path/filepath" "time" - "github.com/cosmos/gogoproto/proto" - cmtcons "github.com/cometbft/cometbft/api/cometbft/consensus/v1" auto "github.com/cometbft/cometbft/internal/autofile" cmtos "github.com/cometbft/cometbft/internal/os" @@ -19,13 +17,14 @@ import ( "github.com/cometbft/cometbft/libs/log" cmterrors "github.com/cometbft/cometbft/types/errors" cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cosmos/gogoproto/proto" ) const ( - // time.Time + max consensus msg size + // time.Time + max consensus msg size. maxMsgSizeBytes = maxMsgSize + 24 - // how often the WAL should be sync'd during period sync'ing + // how often the WAL should be sync'd during period sync'ing. walDefaultFlushInterval = 2 * time.Second ) @@ -57,8 +56,8 @@ func init() { // WAL is an interface for any write-ahead logger. type WAL interface { - Write(WALMessage) error - WriteSync(WALMessage) error + Write(msg WALMessage) error + WriteSync(msg WALMessage) error FlushAndSync() error SearchForEndHeight(height int64, options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) @@ -154,7 +153,7 @@ func (wal *BaseWAL) processFlushTicks() { } // FlushAndSync flushes and fsync's the underlying group's data to disk. -// See auto#FlushAndSync +// See auto#FlushAndSync. func (wal *BaseWAL) FlushAndSync() error { return wal.group.FlushAndSync() } @@ -181,7 +180,7 @@ func (wal *BaseWAL) Wait() { // Write is called in newStep and for each receive on the // peerMsgQueue and the timeoutTicker. -// NOTE: does not call fsync() +// NOTE: does not call fsync(). func (wal *BaseWAL) Write(msg WALMessage) error { if wal == nil { return nil @@ -198,7 +197,7 @@ func (wal *BaseWAL) Write(msg WALMessage) error { // WriteSync is called when we receive a msg from ourselves // so that we write to disk before sending signed messages. -// NOTE: calls fsync() +// NOTE: calls fsync(). func (wal *BaseWAL) WriteSync(msg WALMessage) error { if wal == nil { return nil @@ -286,7 +285,7 @@ func (wal *BaseWAL) SearchForEndHeight( // A WALEncoder writes custom-encoded WAL messages to an output stream. // -// Format: 4 bytes CRC sum + 4 bytes length + arbitrary-length value +// Format: 4 bytes CRC sum + 4 bytes length + arbitrary-length value. type WALEncoder struct { wr io.Writer } diff --git a/internal/consensus/wal_generator.go b/internal/consensus/wal_generator.go index 9f2d5709c0d..dd21baefd35 100644 --- a/internal/consensus/wal_generator.go +++ b/internal/consensus/wal_generator.go @@ -10,13 +10,11 @@ import ( "time" db "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/abci/example/kvstore" cfg "github.com/cometbft/cometbft/config" cmtrand "github.com/cometbft/cometbft/internal/rand" sm "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/store" - "github.com/cometbft/cometbft/internal/test" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/privval" "github.com/cometbft/cometbft/proxy" @@ -29,6 +27,8 @@ import ( // (byteBufferWAL) and waits until numBlocks are created. // If the node fails to produce given numBlocks, it returns an error. func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int, config *cfg.Config) (err error) { + t.Helper() + app := kvstore.NewPersistentApplication(filepath.Join(config.DBDir(), "wal_generator")) logger := log.TestingLogger().With("wal_generator", "wal_generator") @@ -122,6 +122,8 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int, config *cfg.C // WALWithNBlocks returns a WAL content with numBlocks. func WALWithNBlocks(t *testing.T, numBlocks int, config *cfg.Config) (data []byte, err error) { + t.Helper() + var b bytes.Buffer wr := bufio.NewWriter(&b) @@ -133,29 +135,20 @@ func WALWithNBlocks(t *testing.T, numBlocks int, config *cfg.Config) (data []byt return b.Bytes(), nil } +//nolint:unused func randPort() int { // returns between base and base + spread base, spread := 20000, 20000 return base + cmtrand.Intn(spread) } +//nolint:deadcode,unused func makeAddrs() (string, string) { start := randPort() return fmt.Sprintf("tcp://127.0.0.1:%d", start), fmt.Sprintf("tcp://127.0.0.1:%d", start+1) } -// getConfig returns a config for test cases -func getConfig(t *testing.T) *cfg.Config { - c := test.ResetTestRoot(t.Name()) - - // and we use random ports to run in parallel - cmt, rpc := makeAddrs() - c.P2P.ListenAddress = cmt - c.RPC.ListenAddress = rpc - return c -} - // byteBufferWAL is a WAL which writes all msgs to a byte buffer. Writing stops // when the heightToStop is reached. Client will be notified via // signalWhenStopsTo channel. @@ -168,7 +161,7 @@ type byteBufferWAL struct { logger log.Logger } -// needed for determinism +// needed for determinism. var fixedTime, _ = time.Parse(time.RFC3339, "2017-01-02T15:04:05Z") func newByteBufferWAL(logger log.Logger, enc *WALEncoder, nBlocks int64, signalStop chan<- struct{}) *byteBufferWAL { diff --git a/internal/consensus/wal_test.go b/internal/consensus/wal_test.go index 202506ad0ef..608a7c0ad55 100644 --- a/internal/consensus/wal_test.go +++ b/internal/consensus/wal_test.go @@ -13,9 +13,11 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/crypto/merkle" "github.com/cometbft/cometbft/internal/autofile" "github.com/cometbft/cometbft/internal/consensus/types" + "github.com/cometbft/cometbft/internal/test" "github.com/cometbft/cometbft/libs/log" cmttypes "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" @@ -288,3 +290,14 @@ func BenchmarkWalDecode100MB(b *testing.B) { func BenchmarkWalDecode1GB(b *testing.B) { benchmarkWalDecode(b, 1024*1024*1024) } + +// getConfig returns a config for test cases. +func getConfig(t *testing.T) *cfg.Config { + c := test.ResetTestRoot(t.Name()) + + // and we use random ports to run in parallel + cmt, rpc := makeAddrs() + c.P2P.ListenAddress = cmt + c.RPC.ListenAddress = rpc + return c +} diff --git a/internal/events/event_cache.go b/internal/events/event_cache.go index f508e873da0..6a840003737 100644 --- a/internal/events/event_cache.go +++ b/internal/events/event_cache.go @@ -1,20 +1,20 @@ package events // An EventCache buffers events for a Fireable -// All events are cached. Filtering happens on Flush +// All events are cached. Filtering happens on Flush. type EventCache struct { evsw Fireable events []eventInfo } -// Create a new EventCache with an EventSwitch as backend +// Create a new EventCache with an EventSwitch as backend. func NewEventCache(evsw Fireable) *EventCache { return &EventCache{ evsw: evsw, } } -// a cached event +// a cached event. type eventInfo struct { event string data EventData @@ -27,7 +27,7 @@ func (evc *EventCache) FireEvent(event string, data EventData) { } // Fire events by running evsw.FireEvent on all cached events. Blocks. -// Clears cached events +// Clears cached events. func (evc *EventCache) Flush() { for _, ei := range evc.events { evc.evsw.FireEvent(ei.event, ei.data) diff --git a/internal/events/events_test.go b/internal/events/events_test.go index 717e0a9fbfb..f459af0f8e9 100644 --- a/internal/events/events_test.go +++ b/internal/events/events_test.go @@ -5,10 +5,9 @@ import ( "testing" "time" + "github.com/cometbft/cometbft/internal/rand" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/internal/rand" ) // TestAddListenerForEventFireOnce sets up an EventSwitch, subscribes a single @@ -298,7 +297,7 @@ func TestAddAndRemoveListener(t *testing.T) { } } -// TestRemoveListener does basic tests on adding and removing +// TestRemoveListener does basic tests on adding and removing. func TestRemoveListener(t *testing.T) { evsw := NewEventSwitch() err := evsw.Start() diff --git a/internal/evidence/errors.go b/internal/evidence/errors.go index e4f9a280c3e..3ed7e0cbbea 100644 --- a/internal/evidence/errors.go +++ b/internal/evidence/errors.go @@ -26,7 +26,7 @@ type ( Evidence types.Evidence } - // ErrVotingPowerDoesNotMatch is returned when voting power from trusted validator set does not match voting power from evidence + // ErrVotingPowerDoesNotMatch is returned when voting power from trusted validator set does not match voting power from evidence. ErrVotingPowerDoesNotMatch struct { TrustedVotingPower int64 EvidenceVotingPower int64 @@ -37,18 +37,18 @@ type ( Height int64 } - // ErrValidatorAddressesDoNotMatch is returned when provided DuplicateVoteEvidence's votes have different validators as signers + // ErrValidatorAddressesDoNotMatch is returned when provided DuplicateVoteEvidence's votes have different validators as signers. ErrValidatorAddressesDoNotMatch struct { ValidatorA bytes.HexBytes ValidatorB bytes.HexBytes } - // ErrSameBlockIDs is returned if a duplicate vote evidence has votes from the same block id (should be different) + // ErrSameBlockIDs is returned if a duplicate vote evidence has votes from the same block id (should be different). ErrSameBlockIDs struct { BlockID types.BlockID } - // ErrInvalidEvidenceValidators is returned when evidence validation spots an error related to validator set + // ErrInvalidEvidenceValidators is returned when evidence validation spots an error related to validator set. ErrInvalidEvidenceValidators struct { ValError error } @@ -122,5 +122,4 @@ func (e ErrDuplicateEvidenceHRTMismatch) Error() string { return fmt.Sprintf("h/r/t does not match: %d/%d/%v vs %d/%d/%v", e.VoteA.Height, e.VoteA.Round, e.VoteA.Type, e.VoteB.Height, e.VoteB.Round, e.VoteB.Type) - } diff --git a/internal/evidence/pool.go b/internal/evidence/pool.go index 87df97871c4..e4f0fddae23 100644 --- a/internal/evidence/pool.go +++ b/internal/evidence/pool.go @@ -7,18 +7,15 @@ import ( "sync/atomic" "time" - "github.com/cosmos/gogoproto/proto" - gogotypes "github.com/cosmos/gogoproto/types" - - cmterrors "github.com/cometbft/cometbft/types/errors" - dbm "github.com/cometbft/cometbft-db" - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" clist "github.com/cometbft/cometbft/internal/clist" sm "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/types" + cmterrors "github.com/cometbft/cometbft/types/errors" + "github.com/cosmos/gogoproto/proto" + gogotypes "github.com/cosmos/gogoproto/types" ) const ( @@ -26,7 +23,7 @@ const ( baseKeyPending = byte(0x01) ) -// Pool maintains a pool of valid evidence to be broadcasted and committed +// Pool maintains a pool of valid evidence to be broadcasted and committed. type Pool struct { logger log.Logger @@ -193,7 +190,6 @@ func (evpool *Pool) ReportConflictingVotes(voteA, voteB *types.Vote) { func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error { hashes := make([][]byte, len(evList)) for idx, ev := range evList { - _, isLightEv := ev.(*types.LightClientAttackEvidence) // We must verify light client attack evidence regardless because there could be a @@ -230,12 +226,12 @@ func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error { return nil } -// EvidenceFront goes to the first evidence in the clist +// EvidenceFront goes to the first evidence in the clist. func (evpool *Pool) EvidenceFront() *clist.CElement { return evpool.evidenceList.Front() } -// EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil +// EvidenceWaitChan is a channel that closes once the first evidence in the list is there. i.e Front is not nil. func (evpool *Pool) EvidenceWaitChan() <-chan struct{} { return evpool.evidenceList.WaitChan() } @@ -262,7 +258,7 @@ func (evpool *Pool) Close() error { } // IsExpired checks whether evidence or a polc is expired by checking whether a height and time is older -// than set by the evidence consensus parameters +// than set by the evidence consensus parameters. func (evpool *Pool) isExpired(height int64, time time.Time) bool { var ( params = evpool.State().ConsensusParams.Evidence @@ -461,7 +457,6 @@ func (evpool *Pool) processConsensusBuffer(state sm.State) { evpool.mtx.Lock() defer evpool.mtx.Unlock() for _, voteSet := range evpool.consensusBuffer { - // Check the height of the conflicting votes and fetch the corresponding time and validator set // to produce the valid evidence var ( @@ -556,7 +551,7 @@ func evMapKey(ev types.Evidence) string { return string(ev.Hash()) } -// big endian padded hex +// big endian padded hex. func bE(h int64) string { return fmt.Sprintf("%0.16X", h) } diff --git a/internal/evidence/reactor.go b/internal/evidence/reactor.go index 37a928a6a48..47430c27d40 100644 --- a/internal/evidence/reactor.go +++ b/internal/evidence/reactor.go @@ -4,13 +4,12 @@ import ( "fmt" "time" - "github.com/cosmos/gogoproto/proto" - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" clist "github.com/cometbft/cometbft/internal/clist" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/p2p" "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/proto" ) const ( @@ -23,7 +22,7 @@ const ( // Most evidence should be committed in the very next block that is why we wait // just over the block production rate before sending evidence again. broadcastEvidenceIntervalS = 10 - // If a message fails wait this much before sending it again + // If a message fails wait this much before sending it again. peerRetryMessageIntervalMS = 100 ) @@ -190,7 +189,6 @@ func (evR Reactor) prepareEvidenceMessage( if peerHeight <= evHeight { // peer is behind. sleep while he catches up return nil } else if ageNumBlocks > params.MaxAgeNumBlocks { // evidence is too old relative to the peer, skip - // NOTE: if evidence is too old for an honest peer, then we're behind and // either it already got committed or it never will! evR.Logger.Info("Not sending peer old evidence", @@ -215,7 +213,7 @@ type PeerState interface { } // encodemsg takes a array of evidence -// returns the byte encoding of the List Message +// returns the byte encoding of the List Message. func evidenceListToProto(evis []types.Evidence) (*cmtproto.EvidenceList, error) { evi := make([]cmtproto.Evidence, len(evis)) for i := 0; i < len(evis); i++ { diff --git a/internal/evidence/verify.go b/internal/evidence/verify.go index 505172c8d52..206c4165da9 100644 --- a/internal/evidence/verify.go +++ b/internal/evidence/verify.go @@ -15,7 +15,7 @@ import ( // - it is sufficiently recent (MaxAge) // - it is from a key who was a validator at the given height // - it is internally consistent with state -// - it was properly signed by the alleged equivocator and meets the individual evidence verification requirements +// - it was properly signed by the alleged equivocator and meets the individual evidence verification requirements. func (evpool *Pool) verify(evidence types.Evidence) error { var ( state = evpool.State() @@ -112,8 +112,8 @@ func VerifyLightClientAttack( e *types.LightClientAttackEvidence, commonHeader, trustedHeader *types.SignedHeader, commonVals *types.ValidatorSet, - now time.Time, //nolint:revive - trustPeriod time.Duration, //nolint:revive + now time.Time, + trustPeriod time.Duration, ) error { // TODO: Should the current time and trust period be used in this method? // If not, why were the parameters present? @@ -217,7 +217,7 @@ func VerifyDuplicateVote(e *types.DuplicateVoteEvidence, chainID string, valSet } // validateABCIEvidence validates the ABCI component of the light client attack -// evidence i.e voting power and byzantine validators +// evidence i.e voting power and byzantine validators. func validateABCIEvidence( ev *types.LightClientAttackEvidence, commonVals *types.ValidatorSet, @@ -279,7 +279,7 @@ func getSignedHeader(blockStore BlockStore, height int64) (*types.SignedHeader, }, nil } -// check that the evidence hasn't expired +// check that the evidence hasn't expired. func IsEvidenceExpired(heightNow int64, timeNow time.Time, heightEv int64, timeEv time.Time, evidenceParams types.EvidenceParams) bool { ageDuration := timeNow.Sub(timeEv) ageNumBlocks := heightNow - heightEv diff --git a/internal/fail/fail.go b/internal/fail/fail.go index 38cec9a2969..70b8e169c54 100644 --- a/internal/fail/fail.go +++ b/internal/fail/fail.go @@ -22,7 +22,7 @@ func envSet() int { return callIndexToFail } -// Fail when FAIL_TEST_INDEX == callIndex +// Fail when FAIL_TEST_INDEX == callIndex. var callIndex int // indexes Fail calls func Fail() { diff --git a/internal/flowrate/io_test.go b/internal/flowrate/io_test.go index 4d7de417e46..09c1b6ee526 100644 --- a/internal/flowrate/io_test.go +++ b/internal/flowrate/io_test.go @@ -155,8 +155,10 @@ func TestWriter(t *testing.T) { } } -const maxDeviationForDuration = 50 * time.Millisecond -const maxDeviationForRate int64 = 50 +const ( + maxDeviationForDuration = 50 * time.Millisecond + maxDeviationForRate int64 = 50 +) // statusesAreEqual returns true if s1 is equal to s2. Equality here means // general equality of fields except for the duration and rates, which can diff --git a/internal/flowrate/util.go b/internal/flowrate/util.go index b33ddc70138..ab931d970fb 100644 --- a/internal/flowrate/util.go +++ b/internal/flowrate/util.go @@ -29,6 +29,7 @@ func clockToTime(c time.Duration) time.Time { // clockRound returns d rounded to the nearest clockRate increment. func clockRound(d time.Duration) time.Duration { + //nolint:durationcheck return (d + clockRate>>1) / clockRate * clockRate } diff --git a/internal/indexer/indexer_utils.go b/internal/indexer/indexer_utils.go index 51be263cd85..196c21a5c69 100644 --- a/internal/indexer/indexer_utils.go +++ b/internal/indexer/indexer_utils.go @@ -8,7 +8,7 @@ import ( ) // If the actual event value is a float, we get the condition and parse it as a float -// to compare against +// to compare against. func compareFloat(op1 *big.Float, op2 interface{}) (int, bool, error) { switch opVal := op2.(type) { case *big.Int: @@ -62,7 +62,7 @@ func CheckBounds(ranges indexer.QueryRange, v interface{}) (bool, error) { // *Explanation for the isFloat condition below.* // In LowerBoundValue(), for floating points, we cannot simply add 1 due to the reasons explained in - // in the comment at the beginning. The same is true for subtracting one for UpperBoundValue(). + // the comment at the beginning. The same is true for subtracting one for UpperBoundValue(). // That means that for integers, if the condition is >=, cmp will be either 0 or 1 // ( cmp == -1 should always be false). // But if the lowerBound is a float, we have not subtracted one, so returning a 0 diff --git a/internal/inspect/inspect.go b/internal/inspect/inspect.go index 92e08813994..87decd60d14 100644 --- a/internal/inspect/inspect.go +++ b/internal/inspect/inspect.go @@ -17,7 +17,6 @@ import ( "github.com/cometbft/cometbft/libs/log" rpccore "github.com/cometbft/cometbft/rpc/core" "github.com/cometbft/cometbft/types" - "golang.org/x/sync/errgroup" ) @@ -47,7 +46,7 @@ type Inspector struct { // The sinks are used to enable block and transaction querying via the RPC server. // The caller is responsible for starting and stopping the Inspector service. // -//nolint:lll + func New( cfg *config.RPCConfig, bs state.BlockStore, diff --git a/internal/inspect/rpc/rpc.go b/internal/inspect/rpc/rpc.go index 331b5251318..03ecba13235 100644 --- a/internal/inspect/rpc/rpc.go +++ b/internal/inspect/rpc/rpc.go @@ -5,8 +5,6 @@ import ( "net/http" "time" - "github.com/rs/cors" - "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/state/indexer" @@ -14,6 +12,7 @@ import ( "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/rpc/core" "github.com/cometbft/cometbft/rpc/jsonrpc/server" + "github.com/rs/cors" ) // Server defines parameters for running an Inspector rpc server. diff --git a/internal/net/net_test.go b/internal/net/net_test.go index 38cd58f6a24..975e4f6d0f7 100644 --- a/internal/net/net_test.go +++ b/internal/net/net_test.go @@ -7,7 +7,6 @@ import ( ) func TestProtocolAndAddress(t *testing.T) { - cases := []struct { fullAddr string proto string diff --git a/internal/os/os_test.go b/internal/os/os_test.go index 4de51844423..7c43476e884 100644 --- a/internal/os/os_test.go +++ b/internal/os/os_test.go @@ -44,30 +44,30 @@ func TestEnsureDir(t *testing.T) { defer os.RemoveAll(tmp) // Should be possible to create a new directory. - err = EnsureDir(filepath.Join(tmp, "dir"), 0755) + err = EnsureDir(filepath.Join(tmp, "dir"), 0o755) require.NoError(t, err) require.DirExists(t, filepath.Join(tmp, "dir")) // Should succeed on existing directory. - err = EnsureDir(filepath.Join(tmp, "dir"), 0755) + err = EnsureDir(filepath.Join(tmp, "dir"), 0o755) require.NoError(t, err) // Should fail on file. - err = os.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0644) + err = os.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0o644) require.NoError(t, err) - err = EnsureDir(filepath.Join(tmp, "file"), 0755) + err = EnsureDir(filepath.Join(tmp, "file"), 0o755) require.Error(t, err) // Should allow symlink to dir. err = os.Symlink(filepath.Join(tmp, "dir"), filepath.Join(tmp, "linkdir")) require.NoError(t, err) - err = EnsureDir(filepath.Join(tmp, "linkdir"), 0755) + err = EnsureDir(filepath.Join(tmp, "linkdir"), 0o755) require.NoError(t, err) // Should error on symlink to file. err = os.Symlink(filepath.Join(tmp, "file"), filepath.Join(tmp, "linkfile")) require.NoError(t, err) - err = EnsureDir(filepath.Join(tmp, "linkfile"), 0755) + err = EnsureDir(filepath.Join(tmp, "linkfile"), 0o755) require.Error(t, err) } @@ -83,7 +83,7 @@ func TestTrickedTruncation(t *testing.T) { originalWALPath := filepath.Join(tmpDir, "wal") originalWALContent := []byte("I AM BECOME DEATH, DESTROYER OF ALL WORLDS!") - if err := os.WriteFile(originalWALPath, originalWALContent, 0755); err != nil { + if err := os.WriteFile(originalWALPath, originalWALContent, 0o755); err != nil { t.Fatal(err) } diff --git a/internal/protoio/io.go b/internal/protoio/io.go index b23545f10c5..9835f5b4070 100644 --- a/internal/protoio/io.go +++ b/internal/protoio/io.go @@ -37,7 +37,7 @@ import ( ) type Writer interface { - WriteMsg(proto.Message) (int, error) + WriteMsg(msg proto.Message) (int, error) } type WriteCloser interface { diff --git a/internal/protoio/io_test.go b/internal/protoio/io_test.go index 702dac26a16..5f2b16561f9 100644 --- a/internal/protoio/io_test.go +++ b/internal/protoio/io_test.go @@ -37,11 +37,10 @@ import ( "testing" "time" + "github.com/cometbft/cometbft/internal/protoio" "github.com/cosmos/gogoproto/proto" "github.com/cosmos/gogoproto/test" "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/internal/protoio" ) func iotest(writer protoio.WriteCloser, reader protoio.ReadCloser) error { @@ -131,7 +130,7 @@ func TestVarintNoClose(t *testing.T) { require.NoError(t, err) } -// issue 32 +// issue 32. func TestVarintMaxSize(t *testing.T) { buf := newBuffer() writer := protoio.NewDelimitedWriter(buf) diff --git a/internal/pubsub/example_test.go b/internal/pubsub/example_test.go index 2d30acbb858..bb703c11609 100644 --- a/internal/pubsub/example_test.go +++ b/internal/pubsub/example_test.go @@ -4,12 +4,10 @@ import ( "context" "testing" - "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cometbft/cometbft/internal/pubsub" "github.com/cometbft/cometbft/internal/pubsub/query" + "github.com/cometbft/cometbft/libs/log" + "github.com/stretchr/testify/require" ) func TestExample(t *testing.T) { diff --git a/internal/pubsub/pubsub.go b/internal/pubsub/pubsub.go index b4bb8e9a98f..aa9cda81954 100644 --- a/internal/pubsub/pubsub.go +++ b/internal/pubsub/pubsub.go @@ -290,7 +290,7 @@ func (s *Server) OnStop() { s.cmds <- cmd{op: shutdown} } -// NOTE: not goroutine safe +// NOTE: not goroutine safe. type state struct { // query string -> client -> subscription subscriptions map[string]map[string]*Subscription @@ -314,7 +314,7 @@ func (s *Server) OnStart() error { return nil } -// OnReset implements Service.OnReset +// OnReset implements Service.OnReset. func (s *Server) OnReset() error { return nil } diff --git a/internal/pubsub/pubsub_test.go b/internal/pubsub/pubsub_test.go index 02952e54dc0..805c80cb5ee 100644 --- a/internal/pubsub/pubsub_test.go +++ b/internal/pubsub/pubsub_test.go @@ -7,13 +7,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cometbft/cometbft/internal/pubsub" "github.com/cometbft/cometbft/internal/pubsub/query" + "github.com/cometbft/cometbft/libs/log" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( diff --git a/internal/pubsub/query/query_test.go b/internal/pubsub/query/query_test.go index 17fe1cbd1ae..9ea3c14a2d9 100644 --- a/internal/pubsub/query/query_test.go +++ b/internal/pubsub/query/query_test.go @@ -8,12 +8,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/internal/pubsub" "github.com/cometbft/cometbft/internal/pubsub/query" "github.com/cometbft/cometbft/internal/pubsub/query/syntax" + "github.com/stretchr/testify/require" ) var _ pubsub.Query = (*query.Query)(nil) diff --git a/internal/pubsub/query/syntax/parser.go b/internal/pubsub/query/syntax/parser.go index 26c8554908a..e64f94b7fc4 100644 --- a/internal/pubsub/query/syntax/parser.go +++ b/internal/pubsub/query/syntax/parser.go @@ -95,7 +95,6 @@ func (a *Arg) Number() *big.Float { return nil } return f - } // Time returns the value of the argument text as a time, or the zero value if diff --git a/internal/pubsub/query/syntax/scanner.go b/internal/pubsub/query/syntax/scanner.go index 332e3f7b145..f8c0583f813 100644 --- a/internal/pubsub/query/syntax/scanner.go +++ b/internal/pubsub/query/syntax/scanner.go @@ -126,7 +126,7 @@ func (s *Scanner) Pos() int { return s.pos } func (s *Scanner) Err() error { return s.err } // scanNumber scans for numbers with optional fractional parts. -// Examples: 0, 1, 3.14 +// Examples: 0, 1, 3.14. func (s *Scanner) scanNumber(first rune) error { s.buf.WriteRune(first) if err := s.scanWhile(isDigit); err != nil { @@ -266,13 +266,14 @@ func (s *Scanner) scanDatestamp() error { func (s *Scanner) scanWhile(ok func(rune) bool) error { for { ch, err := s.rune() - if err == io.EOF { + switch { + case err == io.EOF: return nil - } else if err != nil { - return s.fail(err) - } else if !ok(ch) { + case !ok(ch): s.unrune() return nil + case err != nil: + return s.fail(err) } s.buf.WriteRune(ch) } diff --git a/internal/pubsub/subscription.go b/internal/pubsub/subscription.go index 5d6bb981843..0a9dba40363 100644 --- a/internal/pubsub/subscription.go +++ b/internal/pubsub/subscription.go @@ -19,7 +19,7 @@ var ( // consists of three things: // 1) channel onto which messages and events are published // 2) channel which is closed if a client is too slow or choose to unsubscribe -// 3) err indicating the reason for (2) +// 3) err indicating the reason for (2). type Subscription struct { out chan Message diff --git a/internal/rand/random.go b/internal/rand/random.go index 768962ebb94..77d4d2ce80f 100644 --- a/internal/rand/random.go +++ b/internal/rand/random.go @@ -284,7 +284,7 @@ func (r *Rand) Intn(n int) int { return i } -// Bool returns a uniformly random boolean +// Bool returns a uniformly random boolean. func (r *Rand) Bool() bool { // See https://github.com/golang/go/issues/23804#issuecomment-365370418 // for reasoning behind computing like this diff --git a/internal/service/service.go b/internal/service/service.go index 7a46e5e20b4..359d2e3a62e 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -49,7 +49,7 @@ type Service interface { String() string // SetLogger sets a logger. - SetLogger(log.Logger) + SetLogger(l log.Logger) } /* @@ -159,7 +159,7 @@ func (bs *BaseService) Start() error { // OnStart implements Service by doing nothing. // NOTE: Do not put anything in here, -// that way users don't need to call BaseService.OnStart() +// that way users don't need to call BaseService.OnStart(). func (bs *BaseService) OnStart() error { return nil } // Stop implements Service by calling OnStop (if defined) and closing quit @@ -192,7 +192,7 @@ func (bs *BaseService) Stop() error { // OnStop implements Service by doing nothing. // NOTE: Do not put anything in here, -// that way users don't need to call BaseService.OnStop() +// that way users don't need to call BaseService.OnStop(). func (bs *BaseService) OnStop() {} // Reset implements Service by calling OnReset callback (if defined). An error diff --git a/internal/state/execution.go b/internal/state/execution.go index 3041b12cad9..6b3411bd124 100644 --- a/internal/state/execution.go +++ b/internal/state/execution.go @@ -260,7 +260,7 @@ func (blockExec *BlockExecutor) ApplyBlock( // validate the validator updates and convert to CometBFT types err = validateValidatorUpdates(abciResponse.ValidatorUpdates, state.ConsensusParams.Validator) if err != nil { - return state, fmt.Errorf("error in validator updates: %v", err) + return state, fmt.Errorf("error in validator updates: %w", err) } validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciResponse.ValidatorUpdates) @@ -278,13 +278,13 @@ func (blockExec *BlockExecutor) ApplyBlock( // Update the state with the block and responses. state, err = updateState(state, blockID, &block.Header, abciResponse, validatorUpdates) if err != nil { - return state, fmt.Errorf("commit failed for application: %v", err) + return state, fmt.Errorf("commit failed for application: %w", err) } // Lock mempool, commit app state, update mempoool. retainHeight, err := blockExec.Commit(state, block, abciResponse) if err != nil { - return state, fmt.Errorf("commit failed for application: %v", err) + return state, fmt.Errorf("commit failed for application: %w", err) } // Update evpool with the latest state. @@ -601,7 +601,7 @@ func updateState( if err != nil { return state, fmt.Errorf("changing validator set: %w", err) } - // Change results from this height but only applies to the next next height. + // Change results from this height but only applies to the height + 2. lastHeightValsChanged = header.Height + 1 + 1 } diff --git a/internal/state/indexer/block.go b/internal/state/indexer/block.go index 31c1ef15670..f889f59183c 100644 --- a/internal/state/indexer/block.go +++ b/internal/state/indexer/block.go @@ -17,7 +17,7 @@ type BlockIndexer interface { Has(height int64) (bool, error) // Index indexes FinalizeBlock events for a given block by its height. - Index(types.EventDataNewBlockEvents) error + Index(events types.EventDataNewBlockEvents) error // Search performs a query for block heights that match a given FinalizeBlock // event search criteria. diff --git a/internal/state/indexer/block/indexer.go b/internal/state/indexer/block/indexer.go index d6db5e6bccb..97049be550c 100644 --- a/internal/state/indexer/block/indexer.go +++ b/internal/state/indexer/block/indexer.go @@ -5,7 +5,6 @@ import ( "fmt" dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/internal/state/indexer" blockidxkv "github.com/cometbft/cometbft/internal/state/indexer/block/kv" diff --git a/internal/state/indexer/block/kv/kv.go b/internal/state/indexer/block/kv/kv.go index 1f182ad9667..29ca0b13057 100644 --- a/internal/state/indexer/block/kv/kv.go +++ b/internal/state/indexer/block/kv/kv.go @@ -10,19 +10,16 @@ import ( "strconv" "strings" - "github.com/google/orderedcode" - - "github.com/cometbft/cometbft/internal/state" - dbm "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" idxutil "github.com/cometbft/cometbft/internal/indexer" "github.com/cometbft/cometbft/internal/pubsub/query" "github.com/cometbft/cometbft/internal/pubsub/query/syntax" + "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/state/indexer" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/types" + "github.com/google/orderedcode" ) var ( @@ -68,7 +65,7 @@ func (idx *BlockerIndexer) Has(height int64) (bool, error) { // The following is indexed: // // primary key: encode(block.height | height) => encode(height) -// FinalizeBlock events: encode(eventType.eventAttr|eventValue|height|finalize_block|eventSeq) => encode(height) +// FinalizeBlock events: encode(eventType.eventAttr|eventValue|height|finalize_block|eventSeq) => encode(height). func (idx *BlockerIndexer) Index(bh types.EventDataNewBlockEvents) error { batch := idx.store.NewBatch() defer batch.Close() @@ -91,6 +88,7 @@ func (idx *BlockerIndexer) Index(bh types.EventDataNewBlockEvents) error { return batch.WriteSync() } +//nolint:deadcode,unused func getKeys(indexer BlockerIndexer) [][]byte { var keys [][]byte @@ -461,10 +459,8 @@ LOOP: } if err != nil { idx.log.Error("failed to parse bounds:", err) - } else { - if withinBounds { - idx.setTmpHeights(tmpHeights, it) - } + } else if withinBounds { + idx.setTmpHeights(tmpHeights, it) } } @@ -552,7 +548,6 @@ func (idx *BlockerIndexer) match( defer it.Close() for ; it.Valid(); it.Next() { - keyHeight, err := parseHeightFromEventKey(it.Key()) if err != nil { idx.log.Error("failure to parse height from key:", err) @@ -591,7 +586,6 @@ func (idx *BlockerIndexer) match( defer it.Close() for ; it.Valid(); it.Next() { - keyHeight, err := parseHeightFromEventKey(it.Key()) if err != nil { idx.log.Error("failure to parse height from key:", err) @@ -704,7 +698,7 @@ func (idx *BlockerIndexer) indexEvents(batch dbm.Batch, events []abci.Event, hei heightBz := int64ToBytes(height) for _, event := range events { - idx.eventSeq = idx.eventSeq + 1 + idx.eventSeq++ // only index events with a non-empty type if len(event.Type) == 0 { continue diff --git a/internal/state/indexer/block/kv/util.go b/internal/state/indexer/block/kv/util.go index 63374ab0f0d..d54f39e71ff 100644 --- a/internal/state/indexer/block/kv/util.go +++ b/internal/state/indexer/block/kv/util.go @@ -6,12 +6,11 @@ import ( "math/big" "strconv" - "github.com/google/orderedcode" - idxutil "github.com/cometbft/cometbft/internal/indexer" "github.com/cometbft/cometbft/internal/pubsub/query/syntax" "github.com/cometbft/cometbft/internal/state/indexer" "github.com/cometbft/cometbft/types" + "github.com/google/orderedcode" ) type HeightInfo struct { @@ -197,7 +196,7 @@ func parseEventSeqFromEventKey(key []byte) (int64, error) { // Remove all occurrences of height equality queries except one. While we are traversing the conditions, check whether the only condition in // addition to match events is the height equality or height range query. At the same time, if we do have a height range condition // ignore the height equality condition. If a height equality exists, place the condition index in the query and the desired height -// into the heightInfo struct +// into the heightInfo struct. func dedupHeight(conditions []syntax.Condition) (dedupConditions []syntax.Condition, heightInfo HeightInfo, found bool) { heightInfo.heightEqIdx = -1 heightRangeExists := false @@ -249,10 +248,9 @@ func checkHeightConditions(heightInfo HeightInfo, keyHeight int64) (bool, error) if err != nil || !withinBounds { return false, err } - } else { - if heightInfo.height != 0 && keyHeight != heightInfo.height { - return false, nil - } + } else if heightInfo.height != 0 && keyHeight != heightInfo.height { + return false, nil } + return true, nil } diff --git a/internal/state/indexer/mocks/block_indexer.go b/internal/state/indexer/mocks/block_indexer.go index 504aec243fc..4034997ba16 100644 --- a/internal/state/indexer/mocks/block_indexer.go +++ b/internal/state/indexer/mocks/block_indexer.go @@ -75,9 +75,9 @@ func (_m *BlockIndexer) Has(height int64) (bool, error) { return r0, r1 } -// Index provides a mock function with given fields: _a0 -func (_m *BlockIndexer) Index(_a0 types.EventDataNewBlockEvents) error { - ret := _m.Called(_a0) +// Index provides a mock function with given fields: events +func (_m *BlockIndexer) Index(events types.EventDataNewBlockEvents) error { + ret := _m.Called(events) if len(ret) == 0 { panic("no return value specified for Index") @@ -85,7 +85,7 @@ func (_m *BlockIndexer) Index(_a0 types.EventDataNewBlockEvents) error { var r0 error if rf, ok := ret.Get(0).(func(types.EventDataNewBlockEvents) error); ok { - r0 = rf(_a0) + r0 = rf(events) } else { r0 = ret.Error(0) } diff --git a/internal/state/indexer/query_range.go b/internal/state/indexer/query_range.go index 26dd9d189bc..2cecd874856 100644 --- a/internal/state/indexer/query_range.go +++ b/internal/state/indexer/query_range.go @@ -10,7 +10,7 @@ import ( // QueryRanges defines a mapping between a composite event key and a QueryRange. // -// e.g.account.number => queryRange{lowerBound: 1, upperBound: 5} +// e.g.account.number => queryRange{lowerBound: 1, upperBound: 5}. type QueryRanges map[string]QueryRange // QueryRange defines a range within a query condition. @@ -144,7 +144,7 @@ func LookForRangesWithHeight(conditions []syntax.Condition) (queryRange QueryRan return queryRange, indexes, heightRange } -// Deprecated: This function is not used anymore and will be replaced with LookForRangesWithHeight +// Deprecated: This function is not used anymore and will be replaced with LookForRangesWithHeight. func LookForRanges(conditions []syntax.Condition) (ranges QueryRanges, indexes []int) { ranges = make(QueryRanges) for i, c := range conditions { diff --git a/internal/state/indexer/sink/psql/backport.go b/internal/state/indexer/sink/psql/backport.go index 7f9de817158..294cafd11ff 100644 --- a/internal/state/indexer/sink/psql/backport.go +++ b/internal/state/indexer/sink/psql/backport.go @@ -17,18 +17,13 @@ import ( "context" "errors" - "github.com/cometbft/cometbft/libs/log" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/internal/pubsub/query" "github.com/cometbft/cometbft/internal/state/txindex" + "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/types" ) -const ( - eventTypeFinalizeBlock = "finalize_block" -) - // TxIndexer returns a bridge from es to the CometBFT v0.34 transaction indexer. func (es *EventSink) TxIndexer() BackportTxIndexer { return BackportTxIndexer{psql: es} diff --git a/internal/state/indexer/sink/psql/psql.go b/internal/state/indexer/sink/psql/psql.go index a33a4fee6d2..83b5fcfc6f7 100644 --- a/internal/state/indexer/sink/psql/psql.go +++ b/internal/state/indexer/sink/psql/psql.go @@ -6,14 +6,14 @@ import ( "database/sql" "errors" "fmt" + "strconv" "strings" "time" - "github.com/cosmos/gogoproto/proto" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/internal/pubsub/query" "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/proto" ) const ( @@ -165,7 +165,7 @@ INSERT INTO `+tableBlocks+` (height, chain_id, created_at) // Insert the special block meta-event for height. if err := insertEvents(dbtx, blockID, 0, []abci.Event{ - makeIndexedEvent(types.BlockHeightKey, fmt.Sprint(h.Height)), + makeIndexedEvent(types.BlockHeightKey, strconv.FormatInt(h.Height, 10)), }); err != nil { return fmt.Errorf("block meta-events: %w", err) } @@ -216,7 +216,7 @@ INSERT INTO `+tableTxResults+` (block_id, index, created_at, tx_hash, tx_result) // Insert the special transaction meta-events for hash and height. if err := insertEvents(dbtx, blockID, txID, []abci.Event{ makeIndexedEvent(types.TxHashKey, txHash), - makeIndexedEvent(types.TxHeightKey, fmt.Sprint(txr.Height)), + makeIndexedEvent(types.TxHeightKey, strconv.FormatInt(txr.Height, 10)), }); err != nil { return fmt.Errorf("indexing transaction meta-events: %w", err) } diff --git a/internal/state/indexer/sink/psql/psql_test.go b/internal/state/indexer/sink/psql/psql_test.go index da411727909..2fbc641381c 100644 --- a/internal/state/indexer/sink/psql/psql_test.go +++ b/internal/state/indexer/sink/psql/psql_test.go @@ -46,6 +46,8 @@ const ( viewBlockEvents = "block_events" viewTxEvents = "tx_events" + + eventTypeFinalizeBlock = "finalize_block" ) func TestMain(m *testing.M) { diff --git a/internal/state/metrics.go b/internal/state/metrics.go index 0547daf99ec..dc28be6a67f 100644 --- a/internal/state/metrics.go +++ b/internal/state/metrics.go @@ -15,16 +15,16 @@ const ( // Metrics contains metrics exposed by this package. type Metrics struct { // Time spent processing FinalizeBlock - BlockProcessingTime metrics.Histogram `metrics_buckettype:"lin" metrics_bucketsizes:"1, 10, 10"` + BlockProcessingTime metrics.Histogram `metrics_bucketsizes:"1, 10, 10" metrics_buckettype:"lin"` // ConsensusParamUpdates is the total number of times the application has // updated the consensus params since process start. - //metrics:Number of consensus parameter updates returned by the application since process start. + // metrics:Number of consensus parameter updates returned by the application since process start. ConsensusParamUpdates metrics.Counter // ValidatorSetUpdates is the total number of times the application has // updated the validator set since process start. - //metrics:Number of validator set updates returned by the application since process start. + // metrics:Number of validator set updates returned by the application since process start. ValidatorSetUpdates metrics.Counter // PruningServiceBlockRetainHeight is the accepted block diff --git a/internal/state/mocks/evidence_pool.go b/internal/state/mocks/evidence_pool.go index 5da02a55a6b..abc87e6076b 100644 --- a/internal/state/mocks/evidence_pool.go +++ b/internal/state/mocks/evidence_pool.go @@ -14,9 +14,9 @@ type EvidencePool struct { mock.Mock } -// AddEvidence provides a mock function with given fields: _a0 -func (_m *EvidencePool) AddEvidence(_a0 types.Evidence) error { - ret := _m.Called(_a0) +// AddEvidence provides a mock function with given fields: ev +func (_m *EvidencePool) AddEvidence(ev types.Evidence) error { + ret := _m.Called(ev) if len(ret) == 0 { panic("no return value specified for AddEvidence") @@ -24,7 +24,7 @@ func (_m *EvidencePool) AddEvidence(_a0 types.Evidence) error { var r0 error if rf, ok := ret.Get(0).(func(types.Evidence) error); ok { - r0 = rf(_a0) + r0 = rf(ev) } else { r0 = ret.Error(0) } @@ -32,9 +32,9 @@ func (_m *EvidencePool) AddEvidence(_a0 types.Evidence) error { return r0 } -// CheckEvidence provides a mock function with given fields: _a0 -func (_m *EvidencePool) CheckEvidence(_a0 types.EvidenceList) error { - ret := _m.Called(_a0) +// CheckEvidence provides a mock function with given fields: evList +func (_m *EvidencePool) CheckEvidence(evList types.EvidenceList) error { + ret := _m.Called(evList) if len(ret) == 0 { panic("no return value specified for CheckEvidence") @@ -42,7 +42,7 @@ func (_m *EvidencePool) CheckEvidence(_a0 types.EvidenceList) error { var r0 error if rf, ok := ret.Get(0).(func(types.EvidenceList) error); ok { - r0 = rf(_a0) + r0 = rf(evList) } else { r0 = ret.Error(0) } @@ -80,9 +80,9 @@ func (_m *EvidencePool) PendingEvidence(maxBytes int64) ([]types.Evidence, int64 return r0, r1 } -// Update provides a mock function with given fields: _a0, _a1 -func (_m *EvidencePool) Update(_a0 state.State, _a1 types.EvidenceList) { - _m.Called(_a0, _a1) +// Update provides a mock function with given fields: _a0, evList +func (_m *EvidencePool) Update(_a0 state.State, evList types.EvidenceList) { + _m.Called(_a0, evList) } // NewEvidencePool creates a new instance of EvidencePool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. diff --git a/internal/state/mocks/store.go b/internal/state/mocks/store.go index e68d0a1c2b1..e9b1e0f5a99 100644 --- a/internal/state/mocks/store.go +++ b/internal/state/mocks/store.go @@ -250,9 +250,9 @@ func (_m *Store) LoadFinalizeBlockResponse(height int64) (*v1.FinalizeBlockRespo return r0, r1 } -// LoadFromDBOrGenesisDoc provides a mock function with given fields: _a0 -func (_m *Store) LoadFromDBOrGenesisDoc(_a0 *types.GenesisDoc) (state.State, error) { - ret := _m.Called(_a0) +// LoadFromDBOrGenesisDoc provides a mock function with given fields: doc +func (_m *Store) LoadFromDBOrGenesisDoc(doc *types.GenesisDoc) (state.State, error) { + ret := _m.Called(doc) if len(ret) == 0 { panic("no return value specified for LoadFromDBOrGenesisDoc") @@ -261,16 +261,16 @@ func (_m *Store) LoadFromDBOrGenesisDoc(_a0 *types.GenesisDoc) (state.State, err var r0 state.State var r1 error if rf, ok := ret.Get(0).(func(*types.GenesisDoc) (state.State, error)); ok { - return rf(_a0) + return rf(doc) } if rf, ok := ret.Get(0).(func(*types.GenesisDoc) state.State); ok { - r0 = rf(_a0) + r0 = rf(doc) } else { r0 = ret.Get(0).(state.State) } if rf, ok := ret.Get(1).(func(*types.GenesisDoc) error); ok { - r1 = rf(_a0) + r1 = rf(doc) } else { r1 = ret.Error(1) } @@ -278,9 +278,9 @@ func (_m *Store) LoadFromDBOrGenesisDoc(_a0 *types.GenesisDoc) (state.State, err return r0, r1 } -// LoadFromDBOrGenesisFile provides a mock function with given fields: _a0 -func (_m *Store) LoadFromDBOrGenesisFile(_a0 string) (state.State, error) { - ret := _m.Called(_a0) +// LoadFromDBOrGenesisFile provides a mock function with given fields: filepath +func (_m *Store) LoadFromDBOrGenesisFile(filepath string) (state.State, error) { + ret := _m.Called(filepath) if len(ret) == 0 { panic("no return value specified for LoadFromDBOrGenesisFile") @@ -289,16 +289,16 @@ func (_m *Store) LoadFromDBOrGenesisFile(_a0 string) (state.State, error) { var r0 state.State var r1 error if rf, ok := ret.Get(0).(func(string) (state.State, error)); ok { - return rf(_a0) + return rf(filepath) } if rf, ok := ret.Get(0).(func(string) state.State); ok { - r0 = rf(_a0) + r0 = rf(filepath) } else { r0 = ret.Get(0).(state.State) } if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) + r1 = rf(filepath) } else { r1 = ret.Error(1) } diff --git a/internal/state/pruner.go b/internal/state/pruner.go index c76384f40c7..740ec53234f 100644 --- a/internal/state/pruner.go +++ b/internal/state/pruner.go @@ -292,7 +292,7 @@ func (p *Pruner) GetABCIResRetainHeight() (int64, error) { } // GetTxIndexerRetainHeight is a convenience method for accessing the -// GetTxIndexerRetainHeight method of the underlying indexer +// GetTxIndexerRetainHeight method of the underlying indexer. func (p *Pruner) GetTxIndexerRetainHeight() (int64, error) { return p.txIndexer.GetRetainHeight() } diff --git a/internal/state/services.go b/internal/state/services.go index dfcb43a7f2f..f067474b3c6 100644 --- a/internal/state/services.go +++ b/internal/state/services.go @@ -50,13 +50,13 @@ type BlockStore interface { // EvidencePool defines the EvidencePool interface used by State. type EvidencePool interface { PendingEvidence(maxBytes int64) (ev []types.Evidence, size int64) - AddEvidence(types.Evidence) error - Update(State, types.EvidenceList) - CheckEvidence(types.EvidenceList) error + AddEvidence(ev types.Evidence) error + Update(state State, evList types.EvidenceList) + CheckEvidence(evList types.EvidenceList) error } // EmptyEvidencePool is an empty implementation of EvidencePool, useful for testing. It also complies -// to the consensus evidence pool interface +// to the consensus evidence pool interface. type EmptyEvidencePool struct{} func (EmptyEvidencePool) PendingEvidence(int64) (ev []types.Evidence, size int64) { diff --git a/internal/state/state.go b/internal/state/state.go index 69e8f9ee6b6..879737ddae1 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -7,16 +7,15 @@ import ( "os" "time" - "github.com/cosmos/gogoproto/proto" - cmtstate "github.com/cometbft/cometbft/api/cometbft/state/v1" cmtversion "github.com/cometbft/cometbft/api/cometbft/version/v1" "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" "github.com/cometbft/cometbft/version" + "github.com/cosmos/gogoproto/proto" ) -// database keys +// database keys. var ( stateKey = []byte("stateKey") ) @@ -129,7 +128,7 @@ func (state State) IsEmpty() bool { return state.Validators == nil // XXX can't compare to Empty } -// ToProto takes the local state type and returns the equivalent proto type +// ToProto takes the local state type and returns the equivalent proto type. func (state *State) ToProto() (*cmtstate.State, error) { if state == nil { return nil, errors.New("state is nil") @@ -173,7 +172,7 @@ func (state *State) ToProto() (*cmtstate.State, error) { return sm, nil } -// FromProto takes a state proto message & returns the local state type +// FromProto takes a state proto message & returns the local state type. func FromProto(pb *cmtstate.State) (*State, error) { //nolint:golint if pb == nil { return nil, errors.New("nil State") @@ -302,11 +301,11 @@ func MakeGenesisStateFromFile(genDocFile string) (State, error) { func MakeGenesisDocFromFile(genDocFile string) (*types.GenesisDoc, error) { genDocJSON, err := os.ReadFile(genDocFile) if err != nil { - return nil, fmt.Errorf("couldn't read GenesisDoc file: %v", err) + return nil, fmt.Errorf("couldn't read GenesisDoc file: %w", err) } genDoc, err := types.GenesisDocFromJSON(genDocJSON) if err != nil { - return nil, fmt.Errorf("error reading GenesisDoc: %v", err) + return nil, fmt.Errorf("error reading GenesisDoc: %w", err) } return genDoc, nil } diff --git a/internal/state/store.go b/internal/state/store.go index a0f5626ced1..9ae380dada6 100644 --- a/internal/state/store.go +++ b/internal/state/store.go @@ -5,23 +5,21 @@ import ( "errors" "fmt" - "github.com/cosmos/gogoproto/proto" - dbm "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" cmtstate "github.com/cometbft/cometbft/api/cometbft/state/v1" cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" cmtos "github.com/cometbft/cometbft/internal/os" cmtmath "github.com/cometbft/cometbft/libs/math" "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/proto" ) const ( // persist validators every valSetCheckpointInterval blocks to avoid // LoadValidators taking too much time. // https://github.com/tendermint/tendermint/pull/3438 - // 100000 results in ~ 100ms to get 100 validators (see BenchmarkLoadValidators) + // 100000 results in ~ 100ms to get 100 validators (see BenchmarkLoadValidators). valSetCheckpointInterval = 100000 ) @@ -57,14 +55,14 @@ var ( // Store defines the state store interface // // It is used to retrieve current state and save and load ABCI responses, -// validators and consensus parameters +// validators and consensus parameters. type Store interface { // LoadFromDBOrGenesisFile loads the most recent state. // If the chain is new it will use the genesis file from the provided genesis file path as the current state. - LoadFromDBOrGenesisFile(string) (State, error) + LoadFromDBOrGenesisFile(filepath string) (State, error) // LoadFromDBOrGenesisDoc loads the most recent state. // If the chain is new it will use the genesis doc as the current state. - LoadFromDBOrGenesisDoc(*types.GenesisDoc) (State, error) + LoadFromDBOrGenesisDoc(doc *types.GenesisDoc) (State, error) // Load loads the current state of the blockchain Load() (State, error) // LoadValidators loads the validator set at a given height @@ -105,7 +103,7 @@ type Store interface { Close() error } -// dbStore wraps a db (github.com/cometbft/cometbft-db) +// dbStore wraps a db (github.com/cometbft/cometbft-db). type dbStore struct { db dbm.DB @@ -474,7 +472,7 @@ func (store dbStore) PruneABCIResponses(targetRetainHeight int64) (int64, int64, // TxResultsHash returns the root hash of a Merkle tree of // ExecTxResulst responses (see ABCIResults.Hash) // -// See merkle.SimpleHashFromByteSlices +// See merkle.SimpleHashFromByteSlices. func TxResultsHash(txResults []*abci.ExecTxResult) []byte { return types.NewResults(txResults).Hash() } @@ -614,7 +612,7 @@ func (store dbStore) getValue(key []byte) ([]byte, error) { return bz, nil } -// ApplicationRetainHeight +// ApplicationRetainHeight. func (store dbStore) SaveApplicationRetainHeight(height int64) error { return store.db.SetSync(AppRetainHeightKey, int64ToBytes(height)) } @@ -633,7 +631,7 @@ func (store dbStore) GetApplicationRetainHeight() (int64, error) { return height, nil } -// DataCompanionRetainHeight +// DataCompanionRetainHeight. func (store dbStore) SaveCompanionBlockRetainHeight(height int64) error { return store.db.SetSync(CompanionBlockRetainHeightKey, int64ToBytes(height)) } @@ -652,7 +650,7 @@ func (store dbStore) GetCompanionBlockRetainHeight() (int64, error) { return height, nil } -// DataCompanionRetainHeight +// DataCompanionRetainHeight. func (store dbStore) SaveABCIResRetainHeight(height int64) error { return store.db.SetSync(ABCIResultsRetainHeightKey, int64ToBytes(height)) } @@ -879,7 +877,7 @@ func (store dbStore) SetOfflineStateSyncHeight(height int64) error { return nil } -// Gets the height at which the store is bootstrapped after out of band statesync +// Gets the height at which the store is bootstrapped after out of band statesync. func (store dbStore) GetOfflineStateSyncHeight() (int64, error) { buf, err := store.db.Get(offlineStateSyncHeight) if err != nil { @@ -909,7 +907,7 @@ func min(a int64, b int64) int64 { } // responseFinalizeBlockFromLegacy is a convenience function that takes the old abci responses and morphs -// it to the finalize block response. Note that the app hash is missing +// it to the finalize block response. Note that the app hash is missing. func responseFinalizeBlockFromLegacy(legacyResp *cmtstate.LegacyABCIResponses) *abci.FinalizeBlockResponse { return &abci.FinalizeBlockResponse{ TxResults: legacyResp.DeliverTxs, @@ -921,7 +919,7 @@ func responseFinalizeBlockFromLegacy(legacyResp *cmtstate.LegacyABCIResponses) * } } -// ----- Util +// ----- Util. func int64FromBytes(bz []byte) int64 { v, _ := binary.Varint(bz) return v diff --git a/internal/state/txindex/indexer.go b/internal/state/txindex/indexer.go index f0db9c3e5dd..4828c45f2ca 100644 --- a/internal/state/txindex/indexer.go +++ b/internal/state/txindex/indexer.go @@ -4,10 +4,9 @@ import ( "context" "errors" - "github.com/cometbft/cometbft/libs/log" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/internal/pubsub/query" + "github.com/cometbft/cometbft/libs/log" ) // XXX/TODO: These types should be moved to the indexer package. @@ -63,5 +62,5 @@ func (b *Batch) Size() int { return len(b.Ops) } -// ErrorEmptyHash indicates empty hash +// ErrorEmptyHash indicates empty hash. var ErrorEmptyHash = errors.New("transaction hash cannot be empty") diff --git a/internal/state/txindex/kv/kv.go b/internal/state/txindex/kv/kv.go index 18d0282f4b7..9c16972ba95 100644 --- a/internal/state/txindex/kv/kv.go +++ b/internal/state/txindex/kv/kv.go @@ -12,20 +12,17 @@ import ( "strconv" "strings" - "github.com/cometbft/cometbft/internal/state" - "github.com/cometbft/cometbft/libs/log" - - "github.com/cosmos/gogoproto/proto" - dbm "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" idxutil "github.com/cometbft/cometbft/internal/indexer" "github.com/cometbft/cometbft/internal/pubsub/query" "github.com/cometbft/cometbft/internal/pubsub/query/syntax" + "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/state/indexer" "github.com/cometbft/cometbft/internal/state/txindex" + "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/proto" ) const ( @@ -351,7 +348,7 @@ func (txi *TxIndex) deleteEvents(result *abci.TxResult, batch dbm.Batch) error { func (txi *TxIndex) indexEvents(result *abci.TxResult, hash []byte, store dbm.Batch) error { for _, event := range result.Result.Events { - txi.eventSeq = txi.eventSeq + 1 + txi.eventSeq++ // only index events with a non-empty type if len(event.Type) == 0 { continue @@ -442,7 +439,6 @@ func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*abci.TxResul skipIndexes = append(skipIndexes, rangeIndexes...) for _, qr := range ranges { - // If we have a query range over height and want to still look for // specific event values we do not want to simply return all // transactios in this height range. We remember the height range info @@ -491,7 +487,6 @@ func (txi *TxIndex) Search(ctx context.Context, q *query.Query) ([]*abci.TxResul resultMap := make(map[string]struct{}) RESULTS_LOOP: for _, h := range filteredHashes { - res, err := txi.Get(h) if err != nil { return nil, fmt.Errorf("failed to get Tx{%X}: %w", h, err) @@ -558,7 +553,6 @@ func (txi *TxIndex) match( EQ_LOOP: for ; it.Valid(); it.Next() { - // If we have a height range in a query, we need only transactions // for this height keyHeight, err := extractHeightFromKey(it.Key()) @@ -743,7 +737,6 @@ LOOP: if err != nil { continue LOOP } - } if qr.Key != types.TxHeightKey { keyHeight, err := extractHeightFromKey(it.Key()) @@ -769,10 +762,8 @@ LOOP: } if err != nil { txi.log.Error("failed to parse bounds:", err) - } else { - if withinBounds { - txi.setTmpHashes(tmpHashes, it) - } + } else if withinBounds { + txi.setTmpHashes(tmpHashes, it) } // XXX: passing time in a ABCI Events is not yet implemented @@ -837,14 +828,14 @@ func isTagKey(key []byte) bool { } func extractHeightFromKey(key []byte) (int64, error) { - parts := strings.SplitN(string(key), tagKeySeparator, -1) + parts := strings.Split(string(key), tagKeySeparator) return strconv.ParseInt(parts[len(parts)-2], 10, 64) } func extractValueFromKey(key []byte) string { keyString := string(key) - parts := strings.SplitN(keyString, tagKeySeparator, -1) + parts := strings.Split(keyString, tagKeySeparator) partsLen := len(parts) value := strings.TrimPrefix(keyString, parts[0]+tagKeySeparator) @@ -858,7 +849,7 @@ func extractValueFromKey(key []byte) string { } func extractEventSeqFromKey(key []byte) string { - parts := strings.SplitN(string(key), tagKeySeparator, -1) + parts := strings.Split(string(key), tagKeySeparator) lastEl := parts[len(parts)-1] @@ -900,7 +891,7 @@ func startKeyForCondition(c syntax.Condition, height int64) []byte { func startKey(fields ...interface{}) []byte { var b bytes.Buffer for _, f := range fields { - b.Write([]byte(fmt.Sprintf("%v", f) + tagKeySeparator)) + b.WriteString(fmt.Sprintf("%v", f) + tagKeySeparator) } return b.Bytes() } diff --git a/internal/state/txindex/kv/utils.go b/internal/state/txindex/kv/utils.go index 1dacd15af37..ccf2fb495a4 100644 --- a/internal/state/txindex/kv/utils.go +++ b/internal/state/txindex/kv/utils.go @@ -5,13 +5,12 @@ import ( "fmt" "math/big" - "github.com/google/orderedcode" - abci "github.com/cometbft/cometbft/abci/types" idxutil "github.com/cometbft/cometbft/internal/indexer" cmtsyntax "github.com/cometbft/cometbft/internal/pubsub/query/syntax" "github.com/cometbft/cometbft/internal/state/indexer" "github.com/cometbft/cometbft/types" + "github.com/google/orderedcode" ) type HeightInfo struct { @@ -102,11 +101,10 @@ func checkHeightConditions(heightInfo HeightInfo, keyHeight int64) (bool, error) if err != nil || !withinBounds { return false, err } - } else { - if heightInfo.height != 0 && keyHeight != heightInfo.height { - return false, nil - } + } else if heightInfo.height != 0 && keyHeight != heightInfo.height { + return false, nil } + return true, nil } @@ -121,6 +119,7 @@ func int64ToBytes(i int64) []byte { return buf[:n] } +//nolint:deadcode,unused func getKeys(indexer *TxIndex) [][]byte { var keys [][]byte diff --git a/internal/state/txindex/null/null.go b/internal/state/txindex/null/null.go index fcf5bc57707..06a32a4281c 100644 --- a/internal/state/txindex/null/null.go +++ b/internal/state/txindex/null/null.go @@ -4,11 +4,10 @@ import ( "context" "errors" - "github.com/cometbft/cometbft/libs/log" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/internal/pubsub/query" "github.com/cometbft/cometbft/internal/state/txindex" + "github.com/cometbft/cometbft/libs/log" ) var _ txindex.TxIndexer = (*TxIndex)(nil) diff --git a/internal/statesync/messages.go b/internal/statesync/messages.go index 182941c0250..716664df231 100644 --- a/internal/statesync/messages.go +++ b/internal/statesync/messages.go @@ -4,15 +4,14 @@ import ( "errors" "fmt" - "github.com/cosmos/gogoproto/proto" - ssproto "github.com/cometbft/cometbft/api/cometbft/statesync/v1" + "github.com/cosmos/gogoproto/proto" ) const ( - // snapshotMsgSize is the maximum size of a snapshotResponseMessage + // snapshotMsgSize is the maximum size of a snapshotResponseMessage. snapshotMsgSize = int(4e6) - // chunkMsgSize is the maximum size of a chunkResponseMessage + // chunkMsgSize is the maximum size of a chunkResponseMessage. chunkMsgSize = int(16e6) ) diff --git a/internal/statesync/reactor.go b/internal/statesync/reactor.go index b45cfed7fa3..9c04f6a9b72 100644 --- a/internal/statesync/reactor.go +++ b/internal/statesync/reactor.go @@ -17,9 +17,9 @@ import ( ) const ( - // SnapshotChannel exchanges snapshot metadata + // SnapshotChannel exchanges snapshot metadata. SnapshotChannel = byte(0x60) - // ChunkChannel exchanges chunk contents + // ChunkChannel exchanges chunk contents. ChunkChannel = byte(0x61) // recentSnapshots is the number of recent snapshots to send and receive per peer. recentSnapshots = 10 @@ -225,7 +225,7 @@ func (r *Reactor) Receive(e p2p.Envelope) { } } -// recentSnapshots fetches the n most recent snapshots from the app +// recentSnapshots fetches the n most recent snapshots from the app. func (r *Reactor) recentSnapshots(n uint32) ([]*snapshot, error) { resp, err := r.conn.ListSnapshots(context.TODO(), &abci.ListSnapshotsRequest{}) if err != nil { diff --git a/internal/statesync/snapshots.go b/internal/statesync/snapshots.go index 97a267fec01..28c3e7cad5a 100644 --- a/internal/statesync/snapshots.go +++ b/internal/statesync/snapshots.go @@ -55,7 +55,7 @@ type snapshotPool struct { snapshotBlacklist map[snapshotKey]bool } -// newSnapshotPool creates a new snapshot pool. The state source is used for +// newSnapshotPool creates a new snapshot pool. The state source is used for. func newSnapshotPool() *snapshotPool { return &snapshotPool{ snapshots: make(map[snapshotKey]*snapshot), diff --git a/internal/statesync/stateprovider.go b/internal/statesync/stateprovider.go index 38c22bfff48..192e1d3454c 100644 --- a/internal/statesync/stateprovider.go +++ b/internal/statesync/stateprovider.go @@ -7,7 +7,6 @@ import ( "time" dbm "github.com/cometbft/cometbft-db" - cmtstate "github.com/cometbft/cometbft/api/cometbft/state/v1" sm "github.com/cometbft/cometbft/internal/state" cmtsync "github.com/cometbft/cometbft/internal/sync" @@ -191,7 +190,7 @@ func (s *lightClientStateProvider) State(ctx context.Context, height uint64) (sm return state, nil } -// rpcClient sets up a new RPC client +// rpcClient sets up a new RPC client. func rpcClient(server string) (*rpchttp.HTTP, error) { if !strings.Contains(server, "://") { server = "http://" + server diff --git a/internal/statesync/syncer.go b/internal/statesync/syncer.go index 45b5b3ee400..7fc9a5a087d 100644 --- a/internal/statesync/syncer.go +++ b/internal/statesync/syncer.go @@ -480,7 +480,7 @@ func (s *syncer) requestChunk(snapshot *snapshot, chunk uint32) { }) } -// verifyApp verifies the sync, checking the app hash, last block height and app version +// verifyApp verifies the sync, checking the app hash, last block height and app version. func (s *syncer) verifyApp(snapshot *snapshot, appVersion uint64) error { resp, err := s.connQuery.Info(context.TODO(), proxy.InfoRequest) if err != nil { diff --git a/internal/store/store.go b/internal/store/store.go index bf0c9630b2e..2c617ad944c 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -5,18 +5,15 @@ import ( "fmt" "strconv" - "github.com/cosmos/gogoproto/proto" - - cmterrors "github.com/cometbft/cometbft/types/errors" - dbm "github.com/cometbft/cometbft-db" - cmtstore "github.com/cometbft/cometbft/api/cometbft/store/v1" cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cometbft/cometbft/internal/evidence" sm "github.com/cometbft/cometbft/internal/state" cmtsync "github.com/cometbft/cometbft/internal/sync" "github.com/cometbft/cometbft/types" + cmterrors "github.com/cometbft/cometbft/types/errors" + "github.com/cosmos/gogoproto/proto" ) // Assuming the length of a block part is 64kB (`types.BlockPartSizeBytes`), @@ -69,7 +66,7 @@ func NewBlockStore(db dbm.DB) *BlockStore { func (bs *BlockStore) IsEmpty() bool { bs.mtx.RLock() defer bs.mtx.RUnlock() - return bs.base == bs.height && bs.base == 0 + return bs.base == 0 && bs.height == 0 } // Base returns the first known contiguous block height, or 0 for empty block stores. @@ -342,7 +339,6 @@ func (bs *BlockStore) PruneBlocks(height int64, state sm.State) (uint64, int64, evidencePoint := height for h := base; h < height; h++ { - meta := bs.LoadBlockMeta(h) if meta == nil { // assume already deleted continue @@ -466,8 +462,8 @@ func (bs *BlockStore) saveBlockToBatch( block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit, - batch dbm.Batch) error { - + batch dbm.Batch, +) error { if block == nil { panic("BlockStore can only save a non-nil block") } @@ -508,7 +504,7 @@ func (bs *BlockStore) saveBlockToBatch( if err := batch.Set(calcBlockMetaKey(height), metaBytes); err != nil { return err } - if err := batch.Set(calcBlockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil { + if err := batch.Set(calcBlockHashKey(hash), []byte(strconv.FormatInt(height, 10))); err != nil { return err } @@ -646,7 +642,7 @@ func LoadBlockStoreState(db dbm.DB) cmtstore.BlockStoreState { return bsj } -// mustEncode proto encodes a proto.message and panics if fails +// mustEncode proto encodes a proto.message and panics if fails. func mustEncode(pb proto.Message) []byte { bz, err := proto.Marshal(pb) if err != nil { diff --git a/internal/strings/string.go b/internal/strings/string.go index f012d761b0e..9f93247cb9f 100644 --- a/internal/strings/string.go +++ b/internal/strings/string.go @@ -82,7 +82,7 @@ func ASCIITrim(s string) string { return string(r) } -// StringSliceEqual checks if string slices a and b are equal +// StringSliceEqual checks if string slices a and b are equal. func StringSliceEqual(a, b []string) bool { if len(a) != len(b) { return false diff --git a/internal/strings/string_test.go b/internal/strings/string_test.go index 1ec7b0d56be..56c4d789d76 100644 --- a/internal/strings/string_test.go +++ b/internal/strings/string_test.go @@ -3,9 +3,8 @@ package strings import ( "testing" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStringInSlice(t *testing.T) { diff --git a/internal/tempfile/tempfile.go b/internal/tempfile/tempfile.go index 24e9dec70c9..4fd5ba14c51 100644 --- a/internal/tempfile/tempfile.go +++ b/internal/tempfile/tempfile.go @@ -15,18 +15,18 @@ import ( const ( atomicWriteFilePrefix = "write-file-atomic-" // Maximum number of atomic write file conflicts before we start reseeding - // (reduced from golang's default 10 due to using an increased randomness space) + // (reduced from golang's default 10 due to using an increased randomness space). atomicWriteFileMaxNumConflicts = 5 // Maximum number of attempts to make at writing the write file before giving up - // (reduced from golang's default 10000 due to using an increased randomness space) + // (reduced from golang's default 10000 due to using an increased randomness space). atomicWriteFileMaxNumWriteAttempts = 1000 // LCG constants from Donald Knuth MMIX - // This LCG's has a period equal to 2**64 + // This LCG's has a period equal to 2**64. lcgA = 6364136223846793005 lcgC = 1442695040888963407 // Create in case it doesn't exist and force kernel // flush, which still leaves the potential of lingering disk cache. - // Never overwrites files + // Never overwrites files. atomicWriteFileFlag = os.O_WRONLY | os.O_CREATE | os.O_SYNC | os.O_TRUNC | os.O_EXCL ) diff --git a/internal/tempfile/tempfile_test.go b/internal/tempfile/tempfile_test.go index b0c7b2c7c63..96283e1d95c 100644 --- a/internal/tempfile/tempfile_test.go +++ b/internal/tempfile/tempfile_test.go @@ -8,9 +8,8 @@ import ( "os" testing "testing" - "github.com/stretchr/testify/require" - cmtrand "github.com/cometbft/cometbft/internal/rand" + "github.com/stretchr/testify/require" ) func TestWriteFileAtomic(t *testing.T) { diff --git a/internal/test/block.go b/internal/test/block.go index 31587cf1712..bd30c8de008 100644 --- a/internal/test/block.go +++ b/internal/test/block.go @@ -4,21 +4,18 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/tmhash" "github.com/cometbft/cometbft/types" "github.com/cometbft/cometbft/version" + "github.com/stretchr/testify/require" ) const ( DefaultTestChainID = "test-chain" ) -var ( - DefaultTestTime = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) -) +var DefaultTestTime = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) func RandomAddress() []byte { return crypto.CRandBytes(crypto.AddressSize) @@ -43,7 +40,7 @@ func MakeBlockIDWithHash(hash []byte) types.BlockID { } // MakeHeader fills the rest of the contents of the header such that it passes -// validate basic +// validate basic. func MakeHeader(t *testing.T, h *types.Header) *types.Header { t.Helper() if h.Version.Block == 0 { diff --git a/internal/test/genesis.go b/internal/test/genesis.go index 22b8028b8e1..7e71f1d5207 100644 --- a/internal/test/genesis.go +++ b/internal/test/genesis.go @@ -12,7 +12,6 @@ func GenesisDoc( consensusParams *types.ConsensusParams, chainID string, ) *types.GenesisDoc { - genesisValidators := make([]types.GenesisValidator, len(validators)) for i := range validators { diff --git a/internal/test/params.go b/internal/test/params.go index c4421d53cc4..f2cfe849395 100644 --- a/internal/test/params.go +++ b/internal/test/params.go @@ -5,7 +5,7 @@ import ( ) // ConsensusParams returns a default set of ConsensusParams that are suitable -// for use in testing +// for use in testing. func ConsensusParams() *types.ConsensusParams { c := types.DefaultConsensusParams() // enable vote extensions diff --git a/internal/test/validator.go b/internal/test/validator.go index ddc471ee8e6..9ad0b0b79d4 100644 --- a/internal/test/validator.go +++ b/internal/test/validator.go @@ -5,9 +5,8 @@ import ( "sort" "testing" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/types" + "github.com/stretchr/testify/require" ) func Validator(_ context.Context, votingPower int64) (*types.Validator, types.PrivValidator, error) { @@ -22,11 +21,12 @@ func Validator(_ context.Context, votingPower int64) (*types.Validator, types.Pr } func ValidatorSet(ctx context.Context, t *testing.T, numValidators int, votingPower int64) (*types.ValidatorSet, []types.PrivValidator) { + t.Helper() + var ( valz = make([]*types.Validator, numValidators) privValidators = make([]types.PrivValidator, numValidators) ) - t.Helper() for i := 0; i < numValidators; i++ { val, privValidator, err := Validator(ctx, votingPower) diff --git a/internal/timer/throttle_timer.go b/internal/timer/throttle_timer.go index 8cacc3d830a..4a5c340ad44 100644 --- a/internal/timer/throttle_timer.go +++ b/internal/timer/throttle_timer.go @@ -64,7 +64,7 @@ func (t *ThrottleTimer) Unset() { } // For ease of .Stop()'ing services before .Start()'ing them, -// we ignore .Stop()'s on nil ThrottleTimers +// we ignore .Stop()'s on nil ThrottleTimers. func (t *ThrottleTimer) Stop() bool { if t == nil { return false diff --git a/internal/timer/throttle_timer_test.go b/internal/timer/throttle_timer_test.go index 4f50ae23294..b01d0f1b1ed 100644 --- a/internal/timer/throttle_timer_test.go +++ b/internal/timer/throttle_timer_test.go @@ -4,11 +4,8 @@ import ( "testing" "time" - // make govet noshadow happy... - - asrt "github.com/stretchr/testify/assert" - cmtsync "github.com/cometbft/cometbft/internal/sync" + asrt "github.com/stretchr/testify/assert" ) type thCounter struct { @@ -31,7 +28,7 @@ func (c *thCounter) Count() int { } // Read should run in a go-routine and -// updates count by one every time a packet comes in +// updates count by one every time a packet comes in. func (c *thCounter) Read() { for range c.input { c.Increment() diff --git a/libs/bytes/bytes.go b/libs/bytes/bytes.go index 95b4cc35fca..85ea79b4bd2 100644 --- a/libs/bytes/bytes.go +++ b/libs/bytes/bytes.go @@ -9,12 +9,12 @@ import ( // HexBytes enables HEX-encoding for json/encoding. type HexBytes []byte -// Marshal needed for protobuf compatibility +// Marshal needed for protobuf compatibility. func (bz HexBytes) Marshal() ([]byte, error) { return bz, nil } -// Unmarshal needed for protobuf compatibility +// Unmarshal needed for protobuf compatibility. func (bz *HexBytes) Unmarshal(data []byte) error { *bz = data return nil diff --git a/libs/cli/flags/log_level.go b/libs/cli/flags/log_level.go index 34c00f61922..2abfee5d735 100644 --- a/libs/cli/flags/log_level.go +++ b/libs/cli/flags/log_level.go @@ -73,7 +73,6 @@ func ParseLogLevel(lvl string, logger log.Logger, defaultLogLevelValue string) ( list) } options = append(options, option) - } } diff --git a/libs/cli/flags/log_level_test.go b/libs/cli/flags/log_level_test.go index 17af292e7cd..14be860b177 100644 --- a/libs/cli/flags/log_level_test.go +++ b/libs/cli/flags/log_level_test.go @@ -26,21 +26,24 @@ func TestParseLogLevel(t *testing.T) { ``, `{"_msg":"Mesmero","level":"error","module":"mempool"}`, `{"_msg":"Mind","level":"info","module":"state"}`, // if no default is given, assume info - ``}}, + ``, + }}, {"mempool:error,*:debug", []string{ `{"_msg":"Kingpin","level":"debug","module":"wire"}`, ``, `{"_msg":"Mesmero","level":"error","module":"mempool"}`, `{"_msg":"Mind","level":"info","module":"state"}`, - `{"_msg":"Gideon","level":"debug"}`}}, + `{"_msg":"Gideon","level":"debug"}`, + }}, {"*:debug,wire:none", []string{ ``, `{"_msg":"Kitty Pryde","level":"info","module":"mempool"}`, `{"_msg":"Mesmero","level":"error","module":"mempool"}`, `{"_msg":"Mind","level":"info","module":"state"}`, - `{"_msg":"Gideon","level":"debug"}`}}, + `{"_msg":"Gideon","level":"debug"}`, + }}, } for _, c := range correctLogLevels { diff --git a/libs/cli/helper.go b/libs/cli/helper.go index 37fe34fc9ff..0bd0b4be668 100644 --- a/libs/cli/helper.go +++ b/libs/cli/helper.go @@ -18,11 +18,11 @@ func WriteConfigVals(dir string, vals map[string]string) error { data += fmt.Sprintf("%s = \"%s\"\n", k, v) } cfile := filepath.Join(dir, "config.toml") - return os.WriteFile(cfile, []byte(data), 0600) + return os.WriteFile(cfile, []byte(data), 0o600) } // RunWithArgs executes the given command with the specified command line args -// and environmental variables set. It returns any error returned from cmd.Execute() +// and environmental variables set. It returns any error returned from cmd.Execute(). func RunWithArgs(cmd Executable, args []string, env map[string]string) error { oargs := os.Args oenv := map[string]string{} @@ -52,7 +52,7 @@ func RunWithArgs(cmd Executable, args []string, env map[string]string) error { // RunCaptureWithArgs executes the given command with the specified command // line args and environmental variables set. It returns string fields // representing output written to stdout and stderr, additionally any error -// from cmd.Execute() is also returned +// from cmd.Execute() is also returned. func RunCaptureWithArgs(cmd Executable, args []string, env map[string]string) (stdout, stderr string, err error) { oldout, olderr := os.Stdout, os.Stderr // keep backup of the real stdout rOut, wOut, _ := os.Pipe() diff --git a/libs/cli/setup.go b/libs/cli/setup.go index 9154fa9860c..125bcacbff7 100644 --- a/libs/cli/setup.go +++ b/libs/cli/setup.go @@ -19,12 +19,12 @@ const ( ) // Executable is the minimal interface to *corba.Command, so we can -// wrap if desired before the test +// wrap if desired before the test. type Executable interface { Execute() error } -// PrepareBaseCmd is meant for CometBFT and other servers +// PrepareBaseCmd is meant for CometBFT and other servers. func PrepareBaseCmd(cmd *cobra.Command, envPrefix, defaultHome string) Executor { cobra.OnInitialize(func() { initEnv(envPrefix) }) cmd.PersistentFlags().StringP(HomeFlag, "", defaultHome, "directory for config and data") @@ -55,7 +55,7 @@ func initEnv(prefix string) { } // This copies all variables like TMROOT to TM_ROOT, -// so we can support both formats for the user +// so we can support both formats for the user. func copyEnvVars(prefix string) { prefix = strings.ToUpper(prefix) ps := prefix + "_" @@ -71,7 +71,7 @@ func copyEnvVars(prefix string) { } } -// Executor wraps the cobra Command with a nicer Execute method +// Executor wraps the cobra Command with a nicer Execute method. type Executor struct { *cobra.Command Exit func(int) // this is os.Exit by default, override in tests @@ -110,7 +110,7 @@ func (e Executor) Execute() error { type cobraCmdFunc func(cmd *cobra.Command, args []string) error // Returns a single function that calls each argument function in sequence -// RunE, PreRunE, PersistentPreRunE, etc. all have this same signature +// RunE, PreRunE, PersistentPreRunE, etc. all have this same signature. func concatCobraCmdFuncs(fs ...cobraCmdFunc) cobraCmdFunc { return func(cmd *cobra.Command, args []string) error { for _, f := range fs { @@ -124,7 +124,7 @@ func concatCobraCmdFuncs(fs ...cobraCmdFunc) cobraCmdFunc { } } -// Bind all flags and read the config into viper +// Bind all flags and read the config into viper. func bindFlagsLoadViper(cmd *cobra.Command, _ []string) error { // cmd.Flags() includes flags from this command and all persistent flags from the parent if err := viper.BindPFlags(cmd.Flags()); err != nil { diff --git a/libs/cli/setup_test.go b/libs/cli/setup_test.go index fec49e5c1ed..87539278c6d 100644 --- a/libs/cli/setup_test.go +++ b/libs/cli/setup_test.go @@ -27,8 +27,11 @@ func TestSetupEnv(t *testing.T) { {nil, map[string]string{"DEMO_FOOBAR": "good"}, "good"}, {nil, map[string]string{"DEMOFOOBAR": "silly"}, "silly"}, // and that cli overrides env... - {[]string{"--foobar", "important"}, - map[string]string{"DEMO_FOOBAR": "ignored"}, "important"}, + { + []string{"--foobar", "important"}, + map[string]string{"DEMO_FOOBAR": "ignored"}, + "important", + }, } for idx, tc := range cases { diff --git a/libs/json/decoder.go b/libs/json/decoder.go index 86ff27d3935..562910a0c96 100644 --- a/libs/json/decoder.go +++ b/libs/json/decoder.go @@ -115,7 +115,6 @@ func decodeReflectList(bz []byte, rv reflect.Value) error { return fmt.Errorf("got %v bytes, expected %v", len(buf), rv.Len()) } reflect.Copy(rv, reflect.ValueOf(buf)) - } else if err := decodeStdlib(bz, rv); err != nil { return err } diff --git a/libs/json/decoder_test.go b/libs/json/decoder_test.go index 9a33bf0e2ad..4f2fc016ac9 100644 --- a/libs/json/decoder_test.go +++ b/libs/json/decoder_test.go @@ -5,10 +5,9 @@ import ( "testing" "time" + "github.com/cometbft/cometbft/libs/json" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/libs/json" ) func TestUnmarshal(t *testing.T) { diff --git a/libs/json/doc.go b/libs/json/doc.go index a4fb461db5f..18a4c97cee9 100644 --- a/libs/json/doc.go +++ b/libs/json/doc.go @@ -90,7 +90,7 @@ // // type Struct struct { // Car *Car -// Vehicle Vehicle +// Vehicle // } // // Struct{Car: &Car{Wheels: 4}, Vehicle: &Car{Wheels: 4}} diff --git a/libs/json/encoder_test.go b/libs/json/encoder_test.go index e6eb18a1225..d1effe83044 100644 --- a/libs/json/encoder_test.go +++ b/libs/json/encoder_test.go @@ -4,10 +4,9 @@ import ( "testing" "time" + "github.com/cometbft/cometbft/libs/json" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/cometbft/cometbft/libs/json" ) func TestMarshal(t *testing.T) { diff --git a/libs/log/nop_logger.go b/libs/log/nop_logger.go index 12d75abe6b7..6da16e2a583 100644 --- a/libs/log/nop_logger.go +++ b/libs/log/nop_logger.go @@ -2,7 +2,7 @@ package log type nopLogger struct{} -// Interface assertions +// Interface assertions. var _ Logger = (*nopLogger)(nil) // NewNopLogger returns a logger that doesn't do anything. diff --git a/libs/log/testing_logger.go b/libs/log/testing_logger.go index 7c6f661a745..86fac848994 100644 --- a/libs/log/testing_logger.go +++ b/libs/log/testing_logger.go @@ -8,10 +8,8 @@ import ( "github.com/go-kit/log/term" ) -var ( - // reuse the same logger across all tests - _testingLogger Logger -) +// reuse the same logger across all tests. +var _testingLogger Logger // TestingLogger returns a TMLogger which writes to STDOUT if testing being run // with the verbose (-v) flag, NopLogger otherwise. diff --git a/libs/log/tm_logger.go b/libs/log/tm_logger.go index ac0d08adb00..ddde79432cc 100644 --- a/libs/log/tm_logger.go +++ b/libs/log/tm_logger.go @@ -18,7 +18,7 @@ type tmLogger struct { srcLogger kitlog.Logger } -// Interface assertions +// Interface assertions. var _ Logger = (*tmLogger)(nil) // NewTMLogger returns a logger that encodes msg and keyvals to the Writer diff --git a/libs/log/tmfmt_logger.go b/libs/log/tmfmt_logger.go index 1d8cb80aac9..0082a0682db 100644 --- a/libs/log/tmfmt_logger.go +++ b/libs/log/tmfmt_logger.go @@ -92,7 +92,6 @@ func (l tmfmtLogger) Log(keyvals ...interface{}) error { if s, ok := keyvals[i+1].(fmt.Stringer); ok { keyvals[i+1] = s.String() } - } // Form a custom CometBFT line diff --git a/libs/log/tmfmt_logger_test.go b/libs/log/tmfmt_logger_test.go index d4e8f8bfec2..16bf4a2897e 100644 --- a/libs/log/tmfmt_logger_test.go +++ b/libs/log/tmfmt_logger_test.go @@ -8,10 +8,9 @@ import ( "regexp" "testing" + "github.com/cometbft/cometbft/libs/log" kitlog "github.com/go-kit/log" "github.com/stretchr/testify/assert" - - "github.com/cometbft/cometbft/libs/log" ) func TestTMFmtLogger(t *testing.T) { diff --git a/libs/log/tracing_logger_test.go b/libs/log/tracing_logger_test.go index 9af2fd0ef4d..b81a88c59c6 100644 --- a/libs/log/tracing_logger_test.go +++ b/libs/log/tracing_logger_test.go @@ -7,9 +7,8 @@ import ( "strings" "testing" - "github.com/pkg/errors" - "github.com/cometbft/cometbft/libs/log" + "github.com/pkg/errors" ) func TestTracingLogger(t *testing.T) { diff --git a/libs/math/fraction_test.go b/libs/math/fraction_test.go index 73ca0f6c83f..729e8454fb7 100644 --- a/libs/math/fraction_test.go +++ b/libs/math/fraction_test.go @@ -7,7 +7,6 @@ import ( ) func TestParseFraction(t *testing.T) { - testCases := []struct { f string exp Fraction @@ -82,5 +81,4 @@ func TestParseFraction(t *testing.T) { } assert.Equal(t, tc.exp, output, idx) } - } diff --git a/libs/math/safemath.go b/libs/math/safemath.go index ff7f0908f94..0464c35b254 100644 --- a/libs/math/safemath.go +++ b/libs/math/safemath.go @@ -5,12 +5,14 @@ import ( "math" ) -var ErrOverflowInt32 = errors.New("int32 overflow") -var ErrOverflowUint8 = errors.New("uint8 overflow") -var ErrOverflowInt8 = errors.New("int8 overflow") +var ( + ErrOverflowInt32 = errors.New("int32 overflow") + ErrOverflowUint8 = errors.New("uint8 overflow") + ErrOverflowInt8 = errors.New("int8 overflow") +) // SafeAddInt32 adds two int32 integers -// If there is an overflow this will panic +// If there is an overflow this will panic. func SafeAddInt32(a, b int32) int32 { if b > 0 && (a > math.MaxInt32-b) { panic(ErrOverflowInt32) @@ -21,7 +23,7 @@ func SafeAddInt32(a, b int32) int32 { } // SafeSubInt32 subtracts two int32 integers -// If there is an overflow this will panic +// If there is an overflow this will panic. func SafeSubInt32(a, b int32) int32 { if b > 0 && (a < math.MinInt32+b) { panic(ErrOverflowInt32) @@ -32,7 +34,7 @@ func SafeSubInt32(a, b int32) int32 { } // SafeConvertInt32 takes a int and checks if it overflows -// If there is an overflow this will panic +// If there is an overflow this will panic. func SafeConvertInt32(a int64) int32 { if a > math.MaxInt32 { panic(ErrOverflowInt32) @@ -43,7 +45,7 @@ func SafeConvertInt32(a int64) int32 { } // SafeConvertUint8 takes an int64 and checks if it overflows -// If there is an overflow it returns an error +// If there is an overflow it returns an error. func SafeConvertUint8(a int64) (uint8, error) { if a > math.MaxUint8 { return 0, ErrOverflowUint8 @@ -54,7 +56,7 @@ func SafeConvertUint8(a int64) (uint8, error) { } // SafeConvertInt8 takes an int64 and checks if it overflows -// If there is an overflow it returns an error +// If there is an overflow it returns an error. func SafeConvertInt8(a int64) (int8, error) { if a > math.MaxInt8 { return 0, ErrOverflowInt8 diff --git a/libs/test/mutate.go b/libs/test/mutate.go index 279dce40ed8..4e2e6a1a397 100644 --- a/libs/test/mutate.go +++ b/libs/test/mutate.go @@ -4,7 +4,7 @@ import ( cmtrand "github.com/cometbft/cometbft/internal/rand" ) -// Contract: !bytes.Equal(input, output) && len(input) >= len(output) +// Contract: !bytes.Equal(input, output) && len(input) >= len(output). func MutateByteSlice(bytez []byte) []byte { // If bytez is empty, panic if len(bytez) == 0 { diff --git a/light/client.go b/light/client.go index bf1e6adebc7..7afdcddad1f 100644 --- a/light/client.go +++ b/light/client.go @@ -118,7 +118,7 @@ func MaxClockDrift(d time.Duration) Option { // As an example, say the light client received block B at a time // 12:05 (this is the real time) and the time on the block // was 12:00. Then the lag here is 5 minutes. -// Default: 10s +// Default: 10s. func MaxBlockLag(d time.Duration) Option { return func(c *Client) { c.maxBlockLag = d @@ -129,7 +129,7 @@ func MaxBlockLag(d time.Duration) Option { // light blocks from a primary provider, verifies them either sequentially or by // skipping some and stores them in a trusted store (usually, a local FS). // -// Default verification: SkippingVerification(DefaultTrustLevel) +// Default verification: SkippingVerification(DefaultTrustLevel). type Client struct { chainID string trustingPeriod time.Duration // see TrustOptions.Period @@ -208,7 +208,7 @@ func NewClient( // NewClientFromTrustedStore initializes existing client from the trusted store. // -// See NewClient +// See NewClient. func NewClientFromTrustedStore( chainID string, trustingPeriod time.Duration, @@ -263,7 +263,7 @@ func NewClientFromTrustedStore( return c, nil } -// restoreTrustedLightBlock loads the latest trusted light block from the store +// restoreTrustedLightBlock loads the latest trusted light block from the store. func (c *Client) restoreTrustedLightBlock() error { lastHeight, err := c.trustedStore.LastLightBlockHeight() if err != nil { @@ -470,7 +470,7 @@ func (c *Client) Update(ctx context.Context, now time.Time) (*types.LightBlock, // It returns provider.ErrlightBlockNotFound if light block is not found by // primary. // -// It will replace the primary provider if an error from a request to the provider occurs +// It will replace the primary provider if an error from a request to the provider occurs. func (c *Client) VerifyLightBlockAtHeight(ctx context.Context, height int64, now time.Time) (*types.LightBlock, error) { if height <= 0 { return nil, errors.New("negative or zero height") @@ -609,7 +609,7 @@ func (c *Client) verifyLightBlock(ctx context.Context, newLightBlock *types.Ligh return c.updateTrustedLightBlock(newLightBlock) } -// see VerifyHeader +// see VerifyHeader. func (c *Client) verifySequential( ctx context.Context, trustedBlock *types.LightBlock, @@ -773,7 +773,7 @@ func (c *Client) verifySkipping( } // verifySkippingAgainstPrimary does verifySkipping plus it compares new header with -// witnesses and replaces primary if it sends the light client an invalid header +// witnesses and replaces primary if it sends the light client an invalid header. func (c *Client) verifySkippingAgainstPrimary( ctx context.Context, trustedBlock *types.LightBlock, @@ -1015,7 +1015,7 @@ func (c *Client) lightBlockFromPrimary(ctx context.Context, height int64) (*type } } -// NOTE: requires a providerMutex lock +// NOTE: requires a providerMutex lock. func (c *Client) removeWitnesses(indexes []int) error { // check that we will still have witnesses remaining if len(c.witnesses) <= len(indexes) { @@ -1172,7 +1172,6 @@ and remove witness. Otherwise, use the different primary`, e.WitnessIndex), "wit c.logger.Info("error comparing first header with witness. You may want to consider removing the witness", "err", err) } - } // remove witnesses that have misbehaved diff --git a/light/detector.go b/light/detector.go index 1f49f87da8c..4e95809c3ec 100644 --- a/light/detector.go +++ b/light/detector.go @@ -114,8 +114,8 @@ func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.Lig // // 3: nil -> the hashes of the two headers match func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader, - witness provider.Provider, witnessIndex int) { - + witness provider.Provider, witnessIndex int, +) { lightBlock, err := witness.LightBlock(ctx, h.Height) switch err { // no error means we move on to checking the hash of the two headers @@ -213,7 +213,7 @@ func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEv } // handleConflictingHeaders handles the primary style of attack, which is where a primary and witness have -// two headers of the same height but with different hashes +// two headers of the same height but with different hashes. func (c *Client) handleConflictingHeaders( ctx context.Context, primaryTrace []*types.LightBlock, @@ -293,7 +293,6 @@ func (c *Client) examineConflictingHeaderAgainstTrace( targetBlock *types.LightBlock, source provider.Provider, now time.Time, ) ([]*types.LightBlock, *types.LightBlock, error) { - var ( previouslyVerifiedBlock, sourceBlock *types.LightBlock sourceTrace []*types.LightBlock @@ -370,7 +369,6 @@ func (c *Client) examineConflictingHeaderAgainstTrace( // prerequisites to this function were not met. Namely that either trace[len(trace)-1].Height < targetBlock.Height // or that trace[i].Hash() != targetBlock.Hash() return nil, nil, errNoDivergence - } // getTargetBlockOrLatest gets the latest height, if it is greater than the target height then it queries diff --git a/light/provider/errors.go b/light/provider/errors.go index 398647b3e17..018c2160e2a 100644 --- a/light/provider/errors.go +++ b/light/provider/errors.go @@ -7,14 +7,14 @@ import ( var ( // ErrHeightTooHigh is returned when the height is higher than the last - // block that the provider has. The light client will not remove the provider + // block that the provider has. The light client will not remove the provider. ErrHeightTooHigh = errors.New("height requested is too high") // ErrLightBlockNotFound is returned when a provider can't find the // requested header (i.e. it has been pruned). - // The light client will not remove the provider + // The light client will not remove the provider. ErrLightBlockNotFound = errors.New("light block not found") // ErrNoResponse is returned if the provider doesn't respond to the - // request in a gieven time + // request in a gieven time. ErrNoResponse = errors.New("client failed to respond") ) diff --git a/light/provider/http/http.go b/light/provider/http/http.go index ca3ad52039e..419e98af213 100644 --- a/light/provider/http/http.go +++ b/light/provider/http/http.go @@ -164,7 +164,6 @@ OUTER_LOOP: default: return nil, err } - } } @@ -223,7 +222,7 @@ func validateHeight(height int64) (*int64, error) { } // exponential backoff (with jitter) -// 0.5s -> 2s -> 4.5s -> 8s -> 12.5 with 1s variation +// 0.5s -> 2s -> 4.5s -> 8s -> 12.5 with 1s variation. func backoffTimeout(attempt uint16) time.Duration { //nolint:gosec // G404: Use of weak random number generator return time.Duration(500*attempt*attempt)*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond diff --git a/light/provider/provider.go b/light/provider/provider.go index 333d8c1e891..7a20e26ede5 100644 --- a/light/provider/provider.go +++ b/light/provider/provider.go @@ -25,5 +25,5 @@ type Provider interface { LightBlock(ctx context.Context, height int64) (*types.LightBlock, error) // ReportEvidence reports an evidence of misbehavior. - ReportEvidence(context.Context, types.Evidence) error + ReportEvidence(ctx context.Context, ev types.Evidence) error } diff --git a/light/rpc/client.go b/light/rpc/client.go index e088f85abe0..0011d81abc5 100644 --- a/light/rpc/client.go +++ b/light/rpc/client.go @@ -67,7 +67,7 @@ func KeyPathFn(fn KeyPathFunc) Option { // DefaultMerkleKeyPathFn creates a function used to generate merkle key paths // from a path string and a key. This is the default used by the cosmos SDK. -// This merkle key paths are required when verifying /abci_query calls +// This merkle key paths are required when verifying /abci_query calls. func DefaultMerkleKeyPathFn() KeyPathFunc { // regexp for extracting store name from /abci_query path storeNameRegexp := regexp.MustCompile(`\/store\/(.+)\/key`) @@ -378,7 +378,7 @@ func (c *Client) BlockByHash(ctx context.Context, hash []byte) (*ctypes.ResultBl // BlockResults returns the block results for the given height. If no height is // provided, the results of the block preceding the latest are returned. -// NOTE: Light client only verifies the tx results +// NOTE: Light client only verifies the tx results. func (c *Client) BlockResults(ctx context.Context, height *int64) (*ctypes.ResultBlockResults, error) { var h int64 if height == nil { @@ -422,7 +422,7 @@ func (c *Client) BlockResults(ctx context.Context, height *int64) (*ctypes.Resul return res, nil } -// Header fetches and verifies the header directly via the light client +// Header fetches and verifies the header directly via the light client. func (c *Client) Header(ctx context.Context, height *int64) (*ctypes.ResultHeader, error) { lb, err := c.updateLightClientIfNeededTo(ctx, height) if err != nil { @@ -583,7 +583,7 @@ func (c *Client) RegisterOpDecoder(typ string, dec merkle.OpDecoder) { // SubscribeWS subscribes for events using the given query and remote address as // a subscriber, but does not verify responses (UNSAFE)! -// TODO: verify data +// TODO: verify data. func (c *Client) SubscribeWS(ctx *rpctypes.Context, query string) (*ctypes.ResultSubscribe, error) { out, err := c.next.Subscribe(context.Background(), ctx.RemoteAddr(), query) if err != nil { @@ -630,9 +630,9 @@ func (c *Client) UnsubscribeAllWS(ctx *rpctypes.Context) (*ctypes.ResultUnsubscr return &ctypes.ResultUnsubscribe{}, nil } -// XXX: Copied from rpc/core/env.go +// XXX: Copied from rpc/core/env.go. const ( - // see README + // see README. defaultPerPage = 30 maxPerPage = 100 ) diff --git a/light/setup.go b/light/setup.go index 66ae15d6aa8..7482c850676 100644 --- a/light/setup.go +++ b/light/setup.go @@ -22,8 +22,8 @@ func NewHTTPClient( primaryAddress string, witnessesAddresses []string, trustedStore store.Store, - options ...Option) (*Client, error) { - + options ...Option, +) (*Client, error) { providers, err := providersFromAddresses(append(witnessesAddresses, primaryAddress), chainID) if err != nil { return nil, err @@ -51,8 +51,8 @@ func NewHTTPClientFromTrustedStore( primaryAddress string, witnessesAddresses []string, trustedStore store.Store, - options ...Option) (*Client, error) { - + options ...Option, +) (*Client, error) { providers, err := providersFromAddresses(append(witnessesAddresses, primaryAddress), chainID) if err != nil { return nil, err diff --git a/light/store/db/db.go b/light/store/db/db.go index f70ec7b7dc1..9982ba8f1ff 100644 --- a/light/store/db/db.go +++ b/light/store/db/db.go @@ -7,12 +7,11 @@ import ( "strconv" dbm "github.com/cometbft/cometbft-db" - cmterrors "github.com/cometbft/cometbft/types/errors" - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" cmtsync "github.com/cometbft/cometbft/internal/sync" "github.com/cometbft/cometbft/light/store" "github.com/cometbft/cometbft/types" + cmterrors "github.com/cometbft/cometbft/types/errors" ) var sizeKey = []byte("size") diff --git a/light/store/errors.go b/light/store/errors.go index 099b5964d36..913b5fcc274 100644 --- a/light/store/errors.go +++ b/light/store/errors.go @@ -2,8 +2,6 @@ package store import "errors" -var ( - // ErrLightBlockNotFound is returned when a store does not have the - // requested header. - ErrLightBlockNotFound = errors.New("light block not found") -) +// ErrLightBlockNotFound is returned when a store does not have the +// requested header. +var ErrLightBlockNotFound = errors.New("light block not found") diff --git a/light/verifier.go b/light/verifier.go index 8905db56b05..617a0ebc1f9 100644 --- a/light/verifier.go +++ b/light/verifier.go @@ -10,11 +10,9 @@ import ( "github.com/cometbft/cometbft/types" ) -var ( - // DefaultTrustLevel - new header can be trusted if at least one correct - // validator signed it. - DefaultTrustLevel = cmtmath.Fraction{Numerator: 1, Denominator: 3} -) +// DefaultTrustLevel - new header can be trusted if at least one correct +// validator signed it. +var DefaultTrustLevel = cmtmath.Fraction{Numerator: 1, Denominator: 3} // VerifyNonAdjacent verifies non-adjacent untrustedHeader against // trustedHeader. It ensures that: @@ -37,8 +35,8 @@ func VerifyNonAdjacent( trustingPeriod time.Duration, now time.Time, maxClockDrift time.Duration, - trustLevel cmtmath.Fraction) error { - + trustLevel cmtmath.Fraction, +) error { if untrustedHeader.Height == trustedHeader.Height+1 { return errors.New("headers must be non adjacent in height") } @@ -96,8 +94,8 @@ func VerifyAdjacent( untrustedVals *types.ValidatorSet, // height=X+1 trustingPeriod time.Duration, now time.Time, - maxClockDrift time.Duration) error { - + maxClockDrift time.Duration, +) error { if untrustedHeader.Height != trustedHeader.Height+1 { return errors.New("headers must be adjacent in height") } @@ -140,8 +138,8 @@ func Verify( trustingPeriod time.Duration, now time.Time, maxClockDrift time.Duration, - trustLevel cmtmath.Fraction) error { - + trustLevel cmtmath.Fraction, +) error { if untrustedHeader.Height != trustedHeader.Height+1 { return VerifyNonAdjacent(trustedHeader, trustedVals, untrustedHeader, untrustedVals, trustingPeriod, now, maxClockDrift, trustLevel) @@ -155,8 +153,8 @@ func verifyNewHeaderAndVals( untrustedVals *types.ValidatorSet, trustedHeader *types.SignedHeader, now time.Time, - maxClockDrift time.Duration) error { - + maxClockDrift time.Duration, +) error { if err := untrustedHeader.ValidateBasic(trustedHeader.ChainID); err != nil { return fmt.Errorf("untrustedHeader.ValidateBasic failed: %w", err) } @@ -231,14 +229,16 @@ func VerifyBackwards(untrustedHeader, trustedHeader *types.Header) error { return ErrInvalidHeader{ fmt.Errorf("expected older header time %v to be before new header time %v", untrustedHeader.Time, - trustedHeader.Time)} + trustedHeader.Time), + } } if !bytes.Equal(untrustedHeader.Hash(), trustedHeader.LastBlockID.Hash) { return ErrInvalidHeader{ fmt.Errorf("older header hash %X does not match trusted header's last block %X", untrustedHeader.Hash(), - trustedHeader.LastBlockID.Hash)} + trustedHeader.LastBlockID.Hash), + } } return nil diff --git a/mempool/clist_mempool.go b/mempool/clist_mempool.go index cf3f0c83bf8..d499b3ed90a 100644 --- a/mempool/clist_mempool.go +++ b/mempool/clist_mempool.go @@ -147,7 +147,7 @@ func (mem *CListMempool) removeAllTxs() { }) } -// NOTE: not thread safe - should only be called once, on startup +// NOTE: not thread safe - should only be called once, on startup. func (mem *CListMempool) EnableTxsAvailable() { mem.txsAvailable = make(chan struct{}, 1) } @@ -595,7 +595,7 @@ func (mem *CListMempool) ReapMaxTxs(max int) types.Txs { } // Lock() must be help by the caller during execution. -// TODO: this function always returns nil; remove the return value +// TODO: this function always returns nil; remove the return value. func (mem *CListMempool) Update( height int64, txs types.Txs, diff --git a/mempool/errors.go b/mempool/errors.go index 7eeb8d2be34..714a4529800 100644 --- a/mempool/errors.go +++ b/mempool/errors.go @@ -5,10 +5,10 @@ import ( "fmt" ) -// ErrTxNotFound is returned to the client if tx is not found in mempool +// ErrTxNotFound is returned to the client if tx is not found in mempool. var ErrTxNotFound = errors.New("transaction not found in mempool") -// ErrTxInCache is returned to the client if we saw tx earlier +// ErrTxInCache is returned to the client if we saw tx earlier. var ErrTxInCache = errors.New("tx already exists in cache") // ErrTxTooLarge defines an error when a transaction is too big to be sent in a diff --git a/mempool/mempool.go b/mempool/mempool.go index 772f3407b52..c6a89697ddd 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -12,7 +12,7 @@ import ( const ( MempoolChannel = byte(0x30) - // PeerCatchupSleepIntervalMS defines how much time to sleep if a peer is behind + // PeerCatchupSleepIntervalMS defines how much time to sleep if a peer is behind. PeerCatchupSleepIntervalMS = 100 ) diff --git a/mempool/mempoolTx.go b/mempool/mempoolTx.go index eb5229fd68a..48313461a96 100644 --- a/mempool/mempoolTx.go +++ b/mempool/mempoolTx.go @@ -6,14 +6,14 @@ import ( "github.com/cometbft/cometbft/types" ) -// mempoolTx is an entry in the mempool +// mempoolTx is an entry in the mempool. type mempoolTx struct { height int64 // height that this tx had been validated in gasWanted int64 // amount of gas this tx states it will require tx types.Tx // validated by the application } -// Height returns the height for this transaction +// Height returns the height for this transaction. func (memTx *mempoolTx) Height() int64 { return atomic.LoadInt64(&memTx.height) } diff --git a/mempool/metrics.go b/mempool/metrics.go index 47de43fffbf..e8148c9fb06 100644 --- a/mempool/metrics.go +++ b/mempool/metrics.go @@ -22,7 +22,7 @@ type Metrics struct { SizeBytes metrics.Gauge // Histogram of transaction sizes in bytes. - TxSizeBytes metrics.Histogram `metrics_buckettype:"exp" metrics_bucketsizes:"1,3,7"` + TxSizeBytes metrics.Histogram `metrics_bucketsizes:"1,3,7" metrics_buckettype:"exp"` // Number of failed transactions. FailedTxs metrics.Counter @@ -31,14 +31,14 @@ type Metrics struct { // transactions that passed CheckTx but failed to make it into the mempool // due to resource limits, e.g. mempool is full and no lower priority // transactions exist in the mempool. - //metrics:Number of rejected transactions. + // metrics:Number of rejected transactions. RejectedTxs metrics.Counter // Number of times transactions are rechecked in the mempool. RecheckTimes metrics.Counter // Number of times transactions were received more than once. - //metrics:Number of duplicate transaction reception. + // metrics:Number of duplicate transaction reception. AlreadyReceivedTxs metrics.Counter // Number of connections being actively used for gossiping transactions diff --git a/mempool/reactor.go b/mempool/reactor.go index e71d00e6b8b..912bc89e467 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -163,11 +163,12 @@ func (memR *Reactor) Receive(e p2p.Envelope) { for _, txBytes := range protoTxs { tx := types.Tx(txBytes) reqRes, err := memR.mempool.CheckTx(tx) - if errors.Is(err, ErrTxInCache) { + switch { + case errors.Is(err, ErrTxInCache): memR.Logger.Debug("Tx already exists in cache", "tx", tx.String()) - } else if err != nil { + case err != nil: memR.Logger.Info("Could not check tx", "tx", tx.String(), "err", err) - } else { + default: // Record the sender only when the transaction is valid and, as // a consequence, added to the mempool. Senders are stored until // the transaction is removed from the mempool. Note that it's diff --git a/node/node.go b/node/node.go index f2beb2ac9db..17336d4f6b0 100644 --- a/node/node.go +++ b/node/node.go @@ -7,19 +7,14 @@ import ( "fmt" "net" "net/http" + _ "net/http/pprof" //nolint: gosec "os" "time" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/rs/cors" - cfg "github.com/cometbft/cometbft/config" bc "github.com/cometbft/cometbft/internal/blocksync" cs "github.com/cometbft/cometbft/internal/consensus" "github.com/cometbft/cometbft/internal/evidence" - "github.com/cometbft/cometbft/light" - cmtpubsub "github.com/cometbft/cometbft/internal/pubsub" "github.com/cometbft/cometbft/internal/service" sm "github.com/cometbft/cometbft/internal/state" @@ -29,6 +24,7 @@ import ( "github.com/cometbft/cometbft/internal/statesync" "github.com/cometbft/cometbft/internal/store" "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/light" mempl "github.com/cometbft/cometbft/mempool" "github.com/cometbft/cometbft/p2p" "github.com/cometbft/cometbft/p2p/pex" @@ -40,8 +36,9 @@ import ( "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" "github.com/cometbft/cometbft/version" - - _ "net/http/pprof" //nolint: gosec + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/rs/cors" ) // Node is the highest level interface to a full CometBFT node. @@ -225,16 +222,14 @@ func BootstrapState(ctx context.Context, config *cfg.Config, dbProvider cfg.DBPr } if appHash == nil { logger.Info("warning: cannot verify appHash. Verification will happen when node boots up!") - } else { - if !bytes.Equal(appHash, state.AppHash) { - if err := blockStore.Close(); err != nil { - logger.Error("failed to close blockstore: %w", err) - } - if err := stateStore.Close(); err != nil { - logger.Error("failed to close statestore: %w", err) - } - return fmt.Errorf("the app hash returned by the light client does not match the provided appHash, expected %X, got %X", state.AppHash, appHash) + } else if !bytes.Equal(appHash, state.AppHash) { + if err := blockStore.Close(); err != nil { + logger.Error("failed to close blockstore: %w", err) } + if err := stateStore.Close(); err != nil { + logger.Error("failed to close statestore: %w", err) + } + return fmt.Errorf("the app hash returned by the light client does not match the provided appHash, expected %X, got %X", state.AppHash, appHash) } commit, err := stateProvider.Commit(ctx, height) @@ -731,8 +726,8 @@ func (n *Node) startRPC() ([]net.Listener, error) { } // we may expose the rpc over both a unix and tcp socket - listeners := make([]net.Listener, len(listenAddrs)) - for i, listenAddr := range listenAddrs { + listeners := make([]net.Listener, 0, len(listenAddrs)) + for _, listenAddr := range listenAddrs { mux := http.NewServeMux() rpcLogger := n.Logger.With("module", "rpc-server") wmLogger := rpcLogger.With("protocol", "websocket") @@ -793,7 +788,7 @@ func (n *Node) startRPC() ([]net.Listener, error) { }() } - listeners[i] = listener + listeners = append(listeners, listener) } if n.config.GRPC.ListenAddress != "" { @@ -865,7 +860,7 @@ func (n *Node) startPrometheusServer() *http.Server { return srv } -// starts a ppro +// starts a ppro. func (n *Node) startPprofServer() *http.Server { srv := &http.Server{ Addr: n.config.RPC.PprofListenAddress, diff --git a/node/setup.go b/node/setup.go index 022d385c67b..cf36f60e354 100644 --- a/node/setup.go +++ b/node/setup.go @@ -6,14 +6,12 @@ import ( "encoding/hex" "fmt" "net" + _ "net/http/pprof" //nolint: gosec // securely exposed on separate, optional port "os" "strings" "time" - _ "net/http/pprof" //nolint: gosec // securely exposed on separate, optional port - dbm "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" cfg "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/crypto" @@ -21,12 +19,11 @@ import ( "github.com/cometbft/cometbft/internal/blocksync" cs "github.com/cometbft/cometbft/internal/consensus" "github.com/cometbft/cometbft/internal/evidence" - "github.com/cometbft/cometbft/internal/statesync" - sm "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/state/indexer" "github.com/cometbft/cometbft/internal/state/indexer/block" "github.com/cometbft/cometbft/internal/state/txindex" + "github.com/cometbft/cometbft/internal/statesync" "github.com/cometbft/cometbft/internal/store" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/light" @@ -37,7 +34,6 @@ import ( "github.com/cometbft/cometbft/proxy" "github.com/cometbft/cometbft/types" "github.com/cometbft/cometbft/version" - _ "github.com/lib/pq" // provide the psql db driver ) @@ -119,7 +115,7 @@ func DefaultMetricsProvider(config *cfg.InstrumentationConfig) MetricsProvider { } type blockSyncReactor interface { - SwitchToBlockSync(sm.State) error + SwitchToBlockSync(state sm.State) error } //------------------------------------------------------------------------------ diff --git a/p2p/base_reactor.go b/p2p/base_reactor.go index f3c40f83e6f..c5a00ac1e8f 100644 --- a/p2p/base_reactor.go +++ b/p2p/base_reactor.go @@ -16,7 +16,7 @@ type Reactor interface { service.Service // Start, Stop // SetSwitch allows setting a switch. - SetSwitch(*Switch) + SetSwitch(sw *Switch) // GetChannels returns the list of MConnection.ChannelDescriptor. Make sure // that each ID is unique across all the reactors added to the switch. @@ -40,7 +40,7 @@ type Reactor interface { // Receive is called by the switch when an envelope is received from any connected // peer on any of the channels registered by the reactor - Receive(Envelope) + Receive(e Envelope) } //-------------------------------------- diff --git a/p2p/conn/connection.go b/p2p/conn/connection.go index d779525cbe8..4e9afe0af9f 100644 --- a/p2p/conn/connection.go +++ b/p2p/conn/connection.go @@ -12,8 +12,6 @@ import ( "sync/atomic" "time" - "github.com/cosmos/gogoproto/proto" - tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" "github.com/cometbft/cometbft/config" flow "github.com/cometbft/cometbft/internal/flowrate" @@ -23,6 +21,7 @@ import ( "github.com/cometbft/cometbft/internal/timer" "github.com/cometbft/cometbft/libs/log" cmtmath "github.com/cometbft/cometbft/libs/math" + "github.com/cosmos/gogoproto/proto" ) const ( @@ -35,7 +34,7 @@ const ( // some of these defaults are written in the user config // flushThrottle, sendRate, recvRate - // TODO: remove values present in config + // TODO: remove values present in config. defaultFlushThrottle = 100 * time.Millisecond defaultSendQueueCapacity = 1 @@ -155,7 +154,7 @@ func DefaultMConnConfig() MConnConfig { } } -// NewMConnection wraps net.Conn and creates multiplex connection +// NewMConnection wraps net.Conn and creates multiplex connection. func NewMConnection( conn net.Conn, chDescs []*ChannelDescriptor, @@ -170,7 +169,7 @@ func NewMConnection( DefaultMConnConfig()) } -// NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config +// NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config. func NewMConnectionWithConfig( conn net.Conn, chDescs []*ChannelDescriptor, @@ -223,7 +222,7 @@ func (c *MConnection) SetLogger(l log.Logger) { } } -// OnStart implements BaseService +// OnStart implements BaseService. func (c *MConnection) OnStart() error { if err := c.BaseService.OnStart(); err != nil { return err @@ -309,7 +308,7 @@ func (c *MConnection) FlushStop() { // c.Stop() } -// OnStop implements BaseService +// OnStop implements BaseService. func (c *MConnection) OnStop() { if c.stopServices() { return @@ -664,13 +663,13 @@ FOR_LOOP: // Cleanup close(c.pong) - //nolint:revive + for range c.pong { // Drain } } -// not goroutine-safe +// not goroutine-safe. func (c *MConnection) stopPongTimer() { if c.pongTimer != nil { _ = c.pongTimer.Stop() @@ -678,7 +677,7 @@ func (c *MConnection) stopPongTimer() { } } -// maxPacketMsgSize returns a maximum size of PacketMsg +// maxPacketMsgSize returns a maximum size of PacketMsg. func (c *MConnection) maxPacketMsgSize() int { bz, err := proto.Marshal(mustWrapPacket(&tmp2p.PacketMsg{ ChannelID: 0x01, @@ -786,7 +785,7 @@ func (ch *Channel) SetLogger(l log.Logger) { // Queues message to send to this channel. // Goroutine-safe -// Times out (and returns false) after defaultSendTimeout +// Times out (and returns false) after defaultSendTimeout. func (ch *Channel) sendBytes(bytes []byte) bool { select { case ch.sendQueue <- bytes: @@ -799,7 +798,7 @@ func (ch *Channel) sendBytes(bytes []byte) bool { // Queues message to send to this channel. // Nonblocking, returns true if successful. -// Goroutine-safe +// Goroutine-safe. func (ch *Channel) trySendBytes(bytes []byte) bool { select { case ch.sendQueue <- bytes: @@ -810,7 +809,7 @@ func (ch *Channel) trySendBytes(bytes []byte) bool { } } -// Goroutine-safe +// Goroutine-safe. func (ch *Channel) loadSendQueueSize() (size int) { return int(atomic.LoadInt32(&ch.sendQueueSize)) } @@ -823,7 +822,7 @@ func (ch *Channel) canSend() bool { // Returns true if any PacketMsgs are pending to be sent. // Call before calling nextPacketMsg() -// Goroutine-safe +// Goroutine-safe. func (ch *Channel) isSendPending() bool { if len(ch.sending) == 0 { if len(ch.sendQueue) == 0 { @@ -835,7 +834,7 @@ func (ch *Channel) isSendPending() bool { } // Creates a new PacketMsg to send. -// Not goroutine-safe +// Not goroutine-safe. func (ch *Channel) nextPacketMsg() tmp2p.PacketMsg { packet := tmp2p.PacketMsg{ChannelID: int32(ch.desc.ID)} maxSize := ch.maxPacketMsgPayloadSize @@ -852,7 +851,7 @@ func (ch *Channel) nextPacketMsg() tmp2p.PacketMsg { } // Writes next PacketMsg to w and updates c.recentlySent. -// Not goroutine-safe +// Not goroutine-safe. func (ch *Channel) writePacketMsgTo(w io.Writer) (n int, err error) { packet := ch.nextPacketMsg() n, err = protoio.NewDelimitedWriter(w).WriteMsg(mustWrapPacket(&packet)) @@ -862,7 +861,7 @@ func (ch *Channel) writePacketMsgTo(w io.Writer) (n int, err error) { // Handles incoming PacketMsgs. It returns a message bytes if message is // complete. NOTE message bytes may change on next call to recvPacketMsg. -// Not goroutine-safe +// Not goroutine-safe. func (ch *Channel) recvPacketMsg(packet tmp2p.PacketMsg) ([]byte, error) { ch.Logger.Debug("Read PacketMsg", "conn", ch.conn, "packet", packet) recvCap, recvReceived := ch.desc.RecvMessageCapacity, len(ch.recving)+len(packet.Data) @@ -884,7 +883,7 @@ func (ch *Channel) recvPacketMsg(packet tmp2p.PacketMsg) ([]byte, error) { } // Call this periodically to update stats for throttling purposes. -// Not goroutine-safe +// Not goroutine-safe. func (ch *Channel) updateStats() { // Exponential decay of stats. // TODO: optimize. diff --git a/p2p/conn/connection_test.go b/p2p/conn/connection_test.go index cb3d2d080dc..e9ec70d76df 100644 --- a/p2p/conn/connection_test.go +++ b/p2p/conn/connection_test.go @@ -6,15 +6,14 @@ import ( "testing" "time" - "github.com/cosmos/gogoproto/proto" - "github.com/fortytw2/leaktest" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" pbtypes "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cometbft/cometbft/internal/protoio" "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/gogoproto/proto" + "github.com/fortytw2/leaktest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const maxPingPongPacketSize = 1024 // bytes diff --git a/p2p/conn/evil_secret_connection_test.go b/p2p/conn/evil_secret_connection_test.go index 1d593dd895f..2d25c3686a0 100644 --- a/p2p/conn/evil_secret_connection_test.go +++ b/p2p/conn/evil_secret_connection_test.go @@ -6,16 +6,15 @@ import ( "io" "testing" - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/oasisprotocol/curve25519-voi/primitives/merlin" - "github.com/stretchr/testify/assert" - "golang.org/x/crypto/chacha20poly1305" - tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/ed25519" cryptoenc "github.com/cometbft/cometbft/crypto/encoding" "github.com/cometbft/cometbft/internal/protoio" + gogotypes "github.com/cosmos/gogoproto/types" + "github.com/oasisprotocol/curve25519-voi/primitives/merlin" + "github.com/stretchr/testify/assert" + "golang.org/x/crypto/chacha20poly1305" ) type buffer struct { diff --git a/p2p/conn/secret_connection.go b/p2p/conn/secret_connection.go index 73479cb8ba4..b8d01be27d0 100644 --- a/p2p/conn/secret_connection.go +++ b/p2p/conn/secret_connection.go @@ -13,14 +13,6 @@ import ( "net" "time" - gogotypes "github.com/cosmos/gogoproto/types" - pool "github.com/libp2p/go-buffer-pool" - "github.com/oasisprotocol/curve25519-voi/primitives/merlin" - "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/hkdf" - "golang.org/x/crypto/nacl/box" - tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/ed25519" @@ -28,9 +20,16 @@ import ( "github.com/cometbft/cometbft/internal/async" "github.com/cometbft/cometbft/internal/protoio" cmtsync "github.com/cometbft/cometbft/internal/sync" + gogotypes "github.com/cosmos/gogoproto/types" + pool "github.com/libp2p/go-buffer-pool" + "github.com/oasisprotocol/curve25519-voi/primitives/merlin" + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/hkdf" + "golang.org/x/crypto/nacl/box" ) -// 4 + 1024 == 1028 total frame size +// 4 + 1024 == 1028 total frame size. const ( dataLenSize = 4 dataMaxSize = 1024 @@ -174,7 +173,7 @@ func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (* return sc, nil } -// RemotePubKey returns authenticated remote pubkey +// RemotePubKey returns authenticated remote pubkey. func (sc *SecretConnection) RemotePubKey() crypto.PubKey { return sc.remPubKey } @@ -269,7 +268,7 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { return n, err } -// Implements net.Conn +// Implements net.Conn. func (sc *SecretConnection) Close() error { return sc.conn.Close() } func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() } func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() } diff --git a/p2p/conn/secret_connection_test.go b/p2p/conn/secret_connection_test.go index 26abec0b3c4..e45ec0d8732 100644 --- a/p2p/conn/secret_connection_test.go +++ b/p2p/conn/secret_connection_test.go @@ -14,19 +14,18 @@ import ( "sync" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/crypto/sr25519" "github.com/cometbft/cometbft/internal/async" cmtos "github.com/cometbft/cometbft/internal/os" cmtrand "github.com/cometbft/cometbft/internal/rand" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Run go test -update from within this module -// to update the golden test vector file +// to update the golden test vector file. var update = flag.Bool("update", false, "update .golden files") type kvstoreConn struct { @@ -308,7 +307,7 @@ func readLots(t *testing.T, wg *sync.WaitGroup, conn io.Reader, n int) { // Creates the data for a test vector file. // The file format is: -// Hex(diffie_hellman_secret), loc_is_least, Hex(recvSecret), Hex(sendSecret), Hex(challenge) +// Hex(diffie_hellman_secret), loc_is_least, Hex(recvSecret), Hex(sendSecret), Hex(challenge). func createGoldenTestVectors(*testing.T) string { data := "" for i := 0; i < 32; i++ { @@ -325,7 +324,7 @@ func createGoldenTestVectors(*testing.T) string { return data } -// Each returned ReadWriteCloser is akin to a net.Connection +// Each returned ReadWriteCloser is akin to a net.Connection. func makeKVStoreConnPair() (fooConn, barConn kvstoreConn) { barReader, fooWriter := io.Pipe() fooReader, barWriter := io.Pipe() diff --git a/p2p/conn_set.go b/p2p/conn_set.go index b522b193222..2cdb61ecf11 100644 --- a/p2p/conn_set.go +++ b/p2p/conn_set.go @@ -8,11 +8,11 @@ import ( // ConnSet is a lookup table for connections and all their ips. type ConnSet interface { - Has(net.Conn) bool - HasIP(net.IP) bool - Set(net.Conn, []net.IP) - Remove(net.Conn) - RemoveAddr(net.Addr) + Has(conn net.Conn) bool + HasIP(ip net.IP) bool + Set(conn net.Conn, ip []net.IP) + Remove(conn net.Conn) + RemoveAddr(addr net.Addr) } type connSetItem struct { diff --git a/p2p/errors.go b/p2p/errors.go index 4fc915292fb..bcb0b2211f5 100644 --- a/p2p/errors.go +++ b/p2p/errors.go @@ -75,7 +75,7 @@ func (e ErrRejected) Error() string { return fmt.Sprintf("self ID<%v>", e.id) } - return fmt.Sprintf("%s", e.err) + return e.err.Error() } // IsAuthFailure when Peer authentication was unsuccessful. diff --git a/p2p/fuzz.go b/p2p/fuzz.go index 9e963a1bc2b..6da1d1e82b5 100644 --- a/p2p/fuzz.go +++ b/p2p/fuzz.go @@ -107,7 +107,7 @@ func (fc *FuzzedConnection) randomDuration() time.Duration { } // implements the fuzz (delay, kill conn) -// and returns whether or not the read/write should be ignored +// and returns whether or not the read/write should be ignored. func (fc *FuzzedConnection) fuzz() bool { if !fc.shouldFuzz() { return false diff --git a/p2p/key.go b/p2p/key.go index 8c3e838e6a3..931e4fc4b0d 100644 --- a/p2p/key.go +++ b/p2p/key.go @@ -12,7 +12,7 @@ import ( cmtjson "github.com/cometbft/cometbft/libs/json" ) -// ID is a hex-encoded crypto.Address +// ID is a hex-encoded crypto.Address. type ID string // IDByteLength is the length of a crypto.Address. Currently only 20. @@ -34,7 +34,7 @@ func (nodeKey *NodeKey) ID() ID { return PubKeyToID(nodeKey.PubKey()) } -// PubKey returns the peer's PubKey +// PubKey returns the peer's PubKey. func (nodeKey *NodeKey) PubKey() crypto.PubKey { return nodeKey.PrivKey.PubKey() } diff --git a/p2p/metrics.go b/p2p/metrics.go index 808142e9afc..792a4fe4cf2 100644 --- a/p2p/metrics.go +++ b/p2p/metrics.go @@ -15,12 +15,10 @@ const ( MetricsSubsystem = "p2p" ) -var ( - // valueToLabelRegexp is used to find the golang package name and type name - // so that the name can be turned into a prometheus label where the characters - // in the label do not include prometheus special characters such as '*' and '.'. - valueToLabelRegexp = regexp.MustCompile(`\*?(\w+)\.(.*)`) -) +// valueToLabelRegexp is used to find the golang package name and type name +// so that the name can be turned into a prometheus label where the characters +// in the label do not include prometheus special characters such as '*' and '.'. +var valueToLabelRegexp = regexp.MustCompile(`\*?(\w+)\.(.*)`) //go:generate go run ../scripts/metricsgen -struct=Metrics diff --git a/p2p/mocks/peer.go b/p2p/mocks/peer.go index 590dbfb9961..bce2c24d03f 100644 --- a/p2p/mocks/peer.go +++ b/p2p/mocks/peer.go @@ -41,9 +41,9 @@ func (_m *Peer) FlushStop() { _m.Called() } -// Get provides a mock function with given fields: _a0 -func (_m *Peer) Get(_a0 string) interface{} { - ret := _m.Called(_a0) +// Get provides a mock function with given fields: key +func (_m *Peer) Get(key string) interface{} { + ret := _m.Called(key) if len(ret) == 0 { panic("no return value specified for Get") @@ -51,7 +51,7 @@ func (_m *Peer) Get(_a0 string) interface{} { var r0 interface{} if rf, ok := ret.Get(0).(func(string) interface{}); ok { - r0 = rf(_a0) + r0 = rf(key) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(interface{}) @@ -290,9 +290,9 @@ func (_m *Peer) Reset() error { return r0 } -// Send provides a mock function with given fields: _a0 -func (_m *Peer) Send(_a0 p2p.Envelope) bool { - ret := _m.Called(_a0) +// Send provides a mock function with given fields: e +func (_m *Peer) Send(e p2p.Envelope) bool { + ret := _m.Called(e) if len(ret) == 0 { panic("no return value specified for Send") @@ -300,7 +300,7 @@ func (_m *Peer) Send(_a0 p2p.Envelope) bool { var r0 bool if rf, ok := ret.Get(0).(func(p2p.Envelope) bool); ok { - r0 = rf(_a0) + r0 = rf(e) } else { r0 = ret.Get(0).(bool) } @@ -308,14 +308,14 @@ func (_m *Peer) Send(_a0 p2p.Envelope) bool { return r0 } -// Set provides a mock function with given fields: _a0, _a1 -func (_m *Peer) Set(_a0 string, _a1 interface{}) { - _m.Called(_a0, _a1) +// Set provides a mock function with given fields: key, value +func (_m *Peer) Set(key string, value interface{}) { + _m.Called(key, value) } -// SetLogger provides a mock function with given fields: _a0 -func (_m *Peer) SetLogger(_a0 log.Logger) { - _m.Called(_a0) +// SetLogger provides a mock function with given fields: l +func (_m *Peer) SetLogger(l log.Logger) { + _m.Called(l) } // SetRemovalFailed provides a mock function with given fields: @@ -415,9 +415,9 @@ func (_m *Peer) String() string { return r0 } -// TrySend provides a mock function with given fields: _a0 -func (_m *Peer) TrySend(_a0 p2p.Envelope) bool { - ret := _m.Called(_a0) +// TrySend provides a mock function with given fields: e +func (_m *Peer) TrySend(e p2p.Envelope) bool { + ret := _m.Called(e) if len(ret) == 0 { panic("no return value specified for TrySend") @@ -425,7 +425,7 @@ func (_m *Peer) TrySend(_a0 p2p.Envelope) bool { var r0 bool if rf, ok := ret.Get(0).(func(p2p.Envelope) bool); ok { - r0 = rf(_a0) + r0 = rf(e) } else { r0 = ret.Get(0).(bool) } diff --git a/p2p/netaddress.go b/p2p/netaddress.go index ec8aa011679..a29525fa375 100644 --- a/p2p/netaddress.go +++ b/p2p/netaddress.go @@ -17,7 +17,7 @@ import ( tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" ) -// EmptyNetAddress defines the string representation of an empty NetAddress +// EmptyNetAddress defines the string representation of an empty NetAddress. const EmptyNetAddress = "" // NetAddress defines information about a peer on the network @@ -66,7 +66,7 @@ func NewNetAddress(id ID, addr net.Addr) *NetAddress { // NewNetAddressString returns a new NetAddress using the provided address in // the form of "ID@IP:Port". // Also resolves the host if host is not an IP. -// Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup) +// Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup). func NewNetAddressString(addr string) (*NetAddress, error) { addrWithoutProtocol := removeProtocolIfDefined(addr) spl := strings.Split(addrWithoutProtocol, "@") @@ -208,7 +208,7 @@ func (na *NetAddress) Same(other interface{}) bool { return false } -// String representation: @: +// String representation: @:. func (na *NetAddress) String() string { if na == nil { return EmptyNetAddress @@ -346,7 +346,7 @@ func (na *NetAddress) ReachabilityTo(o *NetAddress) int { // RFC4843: IPv6 ORCHID: (2001:10::/28) // RFC4862: IPv6 Autoconfig (FE80::/64) // RFC6052: IPv6 well known prefix (64:FF9B::/96) -// RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96 +// RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96. var ( rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)} rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)} @@ -368,11 +368,11 @@ var ( // byte number. It then stores the first 6 bytes of the address as // 0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43. // - // This is the same range used by OnionCat, which is part part of the + // This is the same range used by OnionCat, which is part of the // RFC4193 unique local IPv6 range. // // In summary the format is: - // { magic 6 bytes, 10 bytes base32 decode of key hash } + // { magic 6 bytes, 10 bytes base32 decode of key hash }. onionCatNet = ipNet("fd87:d87e:eb43::", 48, 128) ) diff --git a/p2p/node_info.go b/p2p/node_info.go index 907c790a8b9..8bc46ecca48 100644 --- a/p2p/node_info.go +++ b/p2p/node_info.go @@ -17,7 +17,7 @@ const ( maxNumChannels = 16 // plenty of room for upgrades, for now ) -// Max size of the NodeInfo struct +// Max size of the NodeInfo struct. func MaxNodeInfoSize() int { return maxNodeInfoSize } @@ -71,7 +71,7 @@ func NewProtocolVersion(p2p, block, app uint64) ProtocolVersion { //------------------------------------------------------------- -// Assert DefaultNodeInfo satisfies NodeInfo +// Assert DefaultNodeInfo satisfies NodeInfo. var _ NodeInfo = DefaultNodeInfo{} // DefaultNodeInfo is the basic node information exchanged @@ -95,7 +95,7 @@ type DefaultNodeInfo struct { Other DefaultNodeInfoOther `json:"other"` // other application specific data } -// DefaultNodeInfoOther is the misc. application specific data +// DefaultNodeInfoOther is the misc. application specific data. type DefaultNodeInfoOther struct { TxIndex string `json:"tx_index"` RPCAddress string `json:"rpc_address"` @@ -133,7 +133,6 @@ func (info DefaultNodeInfo) Validate() error { // Validate Version if len(info.Version) > 0 && (!cmtstrings.IsASCIIText(info.Version) || cmtstrings.ASCIITrim(info.Version) == "") { - return fmt.Errorf("info.Version must be valid ASCII text without tabs, but got %v", info.Version) } diff --git a/p2p/peer.go b/p2p/peer.go index 3ca77c63da8..ad69f8275f5 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -6,14 +6,12 @@ import ( "reflect" "time" - "github.com/cosmos/gogoproto/proto" - "github.com/cometbft/cometbft/internal/cmap" "github.com/cometbft/cometbft/internal/service" "github.com/cometbft/cometbft/libs/log" - "github.com/cometbft/cometbft/types" - cmtconn "github.com/cometbft/cometbft/p2p/conn" + "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/proto" ) //go:generate ../scripts/mockery_generate.sh Peer @@ -38,11 +36,11 @@ type Peer interface { Status() cmtconn.ConnectionStatus SocketAddr() *NetAddress // actual address of the socket - Send(Envelope) bool - TrySend(Envelope) bool + Send(e Envelope) bool + TrySend(e Envelope) bool - Set(string, interface{}) - Get(string) interface{} + Set(key string, value interface{}) + Get(key string) interface{} SetRemovalFailed() GetRemovalFailed() bool @@ -81,7 +79,7 @@ func (pc peerConn) ID() ID { return PubKeyToID(pc.conn.(*cmtconn.SecretConnection).RemotePubKey()) } -// Return the IP from the connection RemoteAddr +// Return the IP from the connection RemoteAddr. func (pc peerConn) RemoteIP() net.IP { if pc.ip != nil { return pc.ip @@ -341,7 +339,7 @@ func (p *peer) GetRemovalFailed() bool { // methods only used for testing // TODO: can we remove these? -// CloseConn closes the underlying connection +// CloseConn closes the underlying connection. func (pc *peerConn) CloseConn() { pc.conn.Close() } @@ -407,7 +405,7 @@ func createMConnection( msg := proto.Clone(mt) err := proto.Unmarshal(msgBytes, msg) if err != nil { - panic(fmt.Errorf("unmarshaling message: %s into type: %s", err, reflect.TypeOf(mt))) + panic(fmt.Sprintf("unmarshaling message: %v into type: %s", err, reflect.TypeOf(mt))) } labels := []string{ "peer_id", string(p.ID()), @@ -416,7 +414,7 @@ func createMConnection( if w, ok := msg.(types.Unwrapper); ok { msg, err = w.Unwrap() if err != nil { - panic(fmt.Errorf("unwrapping message: %s", err)) + panic(fmt.Sprintf("unwrapping message: %v", err)) } } p.metrics.PeerReceiveBytesTotal.With(labels...).Add(float64(len(msgBytes))) diff --git a/p2p/pex/addrbook.go b/p2p/pex/addrbook.go index 79fd0aed11c..b7e696c416a 100644 --- a/p2p/pex/addrbook.go +++ b/p2p/pex/addrbook.go @@ -14,8 +14,6 @@ import ( "sync" "time" - "github.com/minio/highwayhash" - "github.com/cometbft/cometbft/crypto" cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/internal/service" @@ -23,6 +21,7 @@ import ( "github.com/cometbft/cometbft/libs/log" cmtmath "github.com/cometbft/cometbft/libs/math" "github.com/cometbft/cometbft/p2p" + "github.com/minio/highwayhash" ) const ( @@ -38,18 +37,18 @@ type AddrBook interface { service.Service // Add our own addresses so we don't later add ourselves - AddOurAddress(*p2p.NetAddress) + AddOurAddress(addr *p2p.NetAddress) // Check if it is our address - OurAddress(*p2p.NetAddress) bool + OurAddress(addr *p2p.NetAddress) bool - AddPrivateIDs([]string) + AddPrivateIDs(ids []string) // Add and remove an address AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error - RemoveAddress(*p2p.NetAddress) + RemoveAddress(addr *p2p.NetAddress) // Check if the address is in the book - HasAddress(*p2p.NetAddress) bool + HasAddress(addr *p2p.NetAddress) bool // Do we need more peers? NeedMoreAddrs() bool @@ -61,14 +60,14 @@ type AddrBook interface { PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress // Mark address - MarkGood(p2p.ID) - MarkAttempt(*p2p.NetAddress) - MarkBad(*p2p.NetAddress, time.Duration) // Move peer to bad peers list + MarkGood(id p2p.ID) + MarkAttempt(addr *p2p.NetAddress) + MarkBad(addr *p2p.NetAddress, dur time.Duration) // Move peer to bad peers list // Add bad peers back to addrBook ReinstateBadPeers() - IsGood(*p2p.NetAddress) bool - IsBanned(*p2p.NetAddress) bool + IsGood(addr *p2p.NetAddress) bool + IsBanned(addr *p2p.NetAddress) bool // Send a selection of addresses to peers GetSelection() []*p2p.NetAddress @@ -136,7 +135,7 @@ func NewAddrBook(filePath string, routabilityStrict bool) AddrBook { } // Initialize the buckets. -// When modifying this, don't forget to update loadFromFile() +// When modifying this, don't forget to update loadFromFile(). func (a *addrBook) init() { a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits // New addr buckets @@ -212,7 +211,7 @@ func (a *addrBook) AddPrivateIDs(ids []string) { // AddAddress implements AddrBook // Add address to a "new" bucket. If it's already in one, only add it probabilistically. // Returns error if the addr is non-routable. Does not add self. -// NOTE: addr must not be nil +// NOTE: addr must not be nil. func (a *addrBook) AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error { a.mtx.Lock() defer a.mtx.Unlock() @@ -237,7 +236,7 @@ func (a *addrBook) IsGood(addr *p2p.NetAddress) bool { return a.addrLookup[addr.ID].isOld() } -// IsBanned returns true if the peer is currently banned +// IsBanned returns true if the peer is currently banned. func (a *addrBook) IsBanned(addr *p2p.NetAddress) bool { a.mtx.Lock() _, ok := a.badPeers[addr.ID] @@ -640,7 +639,7 @@ func (a *addrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { } // adds the address to a "new" bucket. if its already in one, -// it only adds it probabilistically +// it only adds it probabilistically. func (a *addrBook) addAddress(addr, src *p2p.NetAddress) error { if addr == nil || src == nil { return ErrAddrBookNilAddr{addr, src} @@ -829,7 +828,7 @@ func (a *addrBook) addBadPeer(addr *p2p.NetAddress, banTime time.Duration) bool //--------------------------------------------------------------------- // calculate bucket placements -// hash(key + sourcegroup + int64(hash(key + group + sourcegroup)) % bucket_per_group) % num_new_buckets +// hash(key + sourcegroup + int64(hash(key + group + sourcegroup)) % bucket_per_group) % num_new_buckets. func (a *addrBook) calcNewBucket(addr, src *p2p.NetAddress) (int, error) { data1 := []byte{} data1 = append(data1, []byte(a.key)...) @@ -856,7 +855,7 @@ func (a *addrBook) calcNewBucket(addr, src *p2p.NetAddress) (int, error) { return result, nil } -// hash(key + group + int64(hash(key + addr)) % buckets_per_group) % num_old_buckets +// hash(key + group + int64(hash(key + addr)) % buckets_per_group) % num_old_buckets. func (a *addrBook) calcOldBucket(addr *p2p.NetAddress) (int, error) { data1 := []byte{} data1 = append(data1, []byte(a.key)...) diff --git a/p2p/pex/errors.go b/p2p/pex/errors.go index f4551292b80..f8c58764047 100644 --- a/p2p/pex/errors.go +++ b/p2p/pex/errors.go @@ -76,7 +76,7 @@ func (err ErrAddrBookInvalidAddr) Error() string { return fmt.Sprintf("Cannot add invalid address %v: %v", err.Addr, err.AddrErr) } -// ErrAddressBanned is thrown when the address has been banned and therefore cannot be used +// ErrAddressBanned is thrown when the address has been banned and therefore cannot be used. type ErrAddressBanned struct { Addr *p2p.NetAddress } diff --git a/p2p/pex/params.go b/p2p/pex/params.go index 29b4d45ab27..ac6c4ba4822 100644 --- a/p2p/pex/params.go +++ b/p2p/pex/params.go @@ -50,6 +50,6 @@ const ( minGetSelection = 32 // max addresses returned by GetSelection - // NOTE: this must match "maxMsgSize" + // NOTE: this must match "maxMsgSize". maxGetSelection = 250 ) diff --git a/p2p/pex/pex_reactor.go b/p2p/pex/pex_reactor.go index 464ba4f6f4a..aa8e7cdba5b 100644 --- a/p2p/pex/pex_reactor.go +++ b/p2p/pex/pex_reactor.go @@ -18,7 +18,7 @@ import ( type Peer = p2p.Peer const ( - // PexChannel is a channel for PEX messages + // PexChannel is a channel for PEX messages. PexChannel = byte(0x00) // over-estimate of max NetAddress size @@ -27,18 +27,18 @@ const ( maxAddressSize = 256 // NOTE: amplificaiton factor! - // small request results in up to maxMsgSize response + // small request results in up to maxMsgSize response. maxMsgSize = maxAddressSize * maxGetSelection - // ensure we have enough peers + // ensure we have enough peers. defaultEnsurePeersPeriod = 30 * time.Second - // Seed/Crawler constants + // Seed/Crawler constants. // minTimeBetweenCrawls is a minimum time between attempts to crawl a peer. minTimeBetweenCrawls = 2 * time.Minute - // check some peers every this + // check some peers every this. crawlPeerPeriod = 30 * time.Second maxAttemptsToDial = 16 // ~ 35h in total (last attempt - 18h) @@ -48,7 +48,7 @@ const ( // untrusted. biasToSelectNewPeers = 30 // 70 to select good peers - // if a peer is marked bad, it will be banned for at least this time period + // if a peer is marked bad, it will be banned for at least this time period. defaultBanTime = 24 * time.Hour ) @@ -140,7 +140,7 @@ func NewReactor(b AddrBook, config *ReactorConfig) *Reactor { return r } -// OnStart implements BaseService +// OnStart implements BaseService. func (r *Reactor) OnStart() error { err := r.book.Start() if err != nil && err != service.ErrAlreadyStarted { @@ -166,14 +166,14 @@ func (r *Reactor) OnStart() error { return nil } -// OnStop implements BaseService +// OnStop implements BaseService. func (r *Reactor) OnStop() { if err := r.book.Stop(); err != nil { r.Logger.Error("Error stopping address book", "err", err) } } -// GetChannels implements Reactor +// GetChannels implements Reactor. func (r *Reactor) GetChannels() []*conn.ChannelDescriptor { return []*conn.ChannelDescriptor{ { @@ -264,7 +264,6 @@ func (r *Reactor) Receive(e p2p.Envelope) { e.Src.FlushStop() r.Switch.StopPeerGracefully(e.Src) }() - } else { // Check we're not receiving requests too frequently. if err := r.receiveRequest(e.Src); err != nil { @@ -297,7 +296,7 @@ func (r *Reactor) Receive(e p2p.Envelope) { } } -// enforces a minimum amount of time between requests +// enforces a minimum amount of time between requests. func (r *Reactor) receiveRequest(src Peer) error { id := string(src.ID()) v := r.lastReceivedRequests.Get(id) @@ -413,7 +412,7 @@ func (r *Reactor) SetEnsurePeersPeriod(d time.Duration) { r.ensurePeersPeriod = d } -// Ensures that sufficient peers are connected. (continuous) +// Ensures that sufficient peers are connected. (continuous). func (r *Reactor) ensurePeersRoutine() { var ( seed = cmtrand.NewRand() @@ -513,7 +512,6 @@ func (r *Reactor) ensurePeers() { } if r.book.NeedMoreAddrs() { - // 1) Pick a random peer and ask for more. peers := r.Switch.Peers().List() peersCount := len(peers) @@ -615,7 +613,7 @@ func (r *Reactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err e return numOnline, netAddrs, nil } -// randomly dial seeds until we connect to one or exhaust them +// randomly dial seeds until we connect to one or exhaust them. func (r *Reactor) dialSeeds() { perm := cmtrand.Perm(len(r.seedAddrs)) // perm := r.Switch.rng.Perm(lSeeds) @@ -740,7 +738,7 @@ func (r *Reactor) cleanupCrawlPeerInfos() { } } -// attemptDisconnects checks if we've been with each peer long enough to disconnect +// attemptDisconnects checks if we've been with each peer long enough to disconnect. func (r *Reactor) attemptDisconnects() { for _, peer := range r.Switch.Peers().List() { if peer.Status().Duration < r.config.SeedDisconnectWaitPeriod { diff --git a/p2p/switch.go b/p2p/switch.go index 27bb0bb2a56..129115c2e5e 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -6,27 +6,26 @@ import ( "sync" "time" - "github.com/cosmos/gogoproto/proto" - "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/internal/cmap" "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/internal/service" "github.com/cometbft/cometbft/p2p/conn" + "github.com/cosmos/gogoproto/proto" ) const ( // wait a random amount of time from this interval - // before dialing peers or reconnecting to help prevent DoS + // before dialing peers or reconnecting to help prevent DoS. dialRandomizerIntervalMilliseconds = 3000 // repeatedly try to reconnect for a few minutes - // ie. 5 * 20 = 100s + // ie. 5 * 20 = 100s. reconnectAttempts = 20 reconnectInterval = 5 * time.Second // then move into exponential backoff mode for ~1day - // ie. 3**10 = 16hrs + // ie. 3**10 = 16hrs. reconnectBackOffAttempts = 10 reconnectBackOffBaseSeconds = 3 ) @@ -50,12 +49,12 @@ func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig { // to store peer addresses. type AddrBook interface { AddAddress(addr *NetAddress, src *NetAddress) error - AddPrivateIDs([]string) - AddOurAddress(*NetAddress) - OurAddress(*NetAddress) bool - MarkGood(ID) - RemoveAddress(*NetAddress) - HasAddress(*NetAddress) bool + AddPrivateIDs(ids []string) + AddOurAddress(addr *NetAddress) + OurAddress(addr *NetAddress) bool + MarkGood(id ID) + RemoveAddress(addr *NetAddress) + HasAddress(addr *NetAddress) bool Save() } @@ -558,7 +557,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error { return sw.addOutboundPeerWithConfig(addr, sw.config) } -// sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds] +// sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]. func (sw *Switch) randomSleep(interval time.Duration) { r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond time.Sleep(r + interval) @@ -681,7 +680,7 @@ func (sw *Switch) acceptRoutine() { // So might as well panic and let process managers restart the node. // There's no point in letting the node run without the acceptRoutine, // since it won't be able to accept new connections. - panic(fmt.Errorf("accept routine exited: %v", err)) + panic(fmt.Sprintf("accept routine exited: %v", err)) } break @@ -702,7 +701,6 @@ func (sw *Switch) acceptRoutine() { continue } - } if err := sw.addPeer(p); err != nil { @@ -841,8 +839,7 @@ func (sw *Switch) addPeer(p Peer) error { // so that if Receive errors, we will find the peer and remove it. // Add should not err since we already checked peers.Has(). if err := sw.peers.Add(p); err != nil { - switch err.(type) { - case ErrPeerRemoval: + if _, ok := err.(ErrPeerRemoval); ok { sw.Logger.Error("Error starting peer ", " err ", "Peer has already errored and removal was attempted.", "peer", p.ID()) diff --git a/p2p/test_util.go b/p2p/test_util.go index f93652ba654..1ece3c45fbb 100644 --- a/p2p/test_util.go +++ b/p2p/test_util.go @@ -5,13 +5,12 @@ import ( "net" "time" + "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/ed25519" cmtnet "github.com/cometbft/cometbft/internal/net" cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/libs/log" - - "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/p2p/conn" ) diff --git a/p2p/transport.go b/p2p/transport.go index 083a4740d9e..8cb56bd7bf7 100644 --- a/p2p/transport.go +++ b/p2p/transport.go @@ -6,14 +6,12 @@ import ( "net" "time" - "golang.org/x/net/netutil" - - "github.com/cosmos/gogoproto/proto" - tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/internal/protoio" "github.com/cometbft/cometbft/p2p/conn" + "github.com/cosmos/gogoproto/proto" + "golang.org/x/net/netutil" ) const ( @@ -24,7 +22,7 @@ const ( // IPResolver is a behavior subset of net.Resolver. type IPResolver interface { - LookupIPAddr(context.Context, string) ([]net.IPAddr, error) + LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error) } // accept is the container to carry the upgraded connection and NodeInfo from an @@ -64,20 +62,20 @@ type Transport interface { NetAddress() NetAddress // Accept returns a newly connected Peer. - Accept(peerConfig) (Peer, error) + Accept(config peerConfig) (Peer, error) // Dial connects to the Peer for the address. - Dial(NetAddress, peerConfig) (Peer, error) + Dial(addr NetAddress, config peerConfig) (Peer, error) // Cleanup any resources associated with Peer. - Cleanup(Peer) + Cleanup(peer Peer) } // transportLifecycle bundles the methods for callers to control start and stop // behavior. type transportLifecycle interface { Close() error - Listen(NetAddress) error + Listen(addr NetAddress) error } // ConnFilterFunc to be implemented by filter hooks after a new connection has @@ -129,7 +127,7 @@ func MultiplexTransportResolver(resolver IPResolver) MultiplexTransportOption { } // MultiplexTransportMaxIncomingConnections sets the maximum number of -// simultaneous connections (incoming). Default: 0 (unlimited) +// simultaneous connections (incoming). Default: 0 (unlimited). func MultiplexTransportMaxIncomingConnections(n int) MultiplexTransportOption { return func(mt *MultiplexTransport) { mt.maxIncomingConnections = n } } @@ -275,7 +273,7 @@ func (mt *MultiplexTransport) Listen(addr NetAddress) error { // AddChannel registers a channel to nodeInfo. // NOTE: NodeInfo must be of type DefaultNodeInfo else channels won't be updated // This is a bit messy at the moment but is cleaned up in the following version -// when NodeInfo changes from an interface to a concrete type +// when NodeInfo changes from an interface to a concrete type. func (mt *MultiplexTransport) AddChannel(chID byte) { if ni, ok := mt.nodeInfo.(DefaultNodeInfo); ok { if !ni.HasChannel(chID) { @@ -423,7 +421,7 @@ func (mt *MultiplexTransport) upgrade( if err != nil { return nil, nil, ErrRejected{ conn: c, - err: fmt.Errorf("secret conn failed: %v", err), + err: fmt.Errorf("secret conn failed: %w", err), isAuthFailure: true, } } @@ -449,7 +447,7 @@ func (mt *MultiplexTransport) upgrade( if err != nil { return nil, nil, ErrRejected{ conn: c, - err: fmt.Errorf("handshake failed: %v", err), + err: fmt.Errorf("handshake failed: %w", err), isAuthFailure: true, } } diff --git a/p2p/types.go b/p2p/types.go index 153c5d7b384..1793aa2d172 100644 --- a/p2p/types.go +++ b/p2p/types.go @@ -1,11 +1,10 @@ package p2p import ( - "github.com/cosmos/gogoproto/proto" - tmp2p "github.com/cometbft/cometbft/api/cometbft/p2p/v1" "github.com/cometbft/cometbft/p2p/conn" "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/proto" ) type ( diff --git a/privval/file.go b/privval/file.go index c3103ea9cc6..4073883118e 100644 --- a/privval/file.go +++ b/privval/file.go @@ -7,8 +7,6 @@ import ( "os" "time" - "github.com/cosmos/gogoproto/proto" - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/crypto/ed25519" @@ -19,6 +17,7 @@ import ( cmtjson "github.com/cometbft/cometbft/libs/json" "github.com/cometbft/cometbft/types" cmttime "github.com/cometbft/cometbft/types/time" + "github.com/cosmos/gogoproto/proto" ) // TODO: type ? @@ -408,7 +407,7 @@ func (pv *FilePV) signProposal(chainID string, proposal *cmtproto.Proposal) erro return nil } -// Persist height/round/step and signature +// Persist height/round/step and signature. func (pv *FilePV) saveSigned(height int64, round int32, step int8, signBytes []byte, sig []byte, ) { @@ -445,7 +444,7 @@ func checkVotesOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.T } // returns the timestamp from the lastSignBytes. -// returns true if the only difference in the proposals is their timestamp +// returns true if the only difference in the proposals is their timestamp. func checkProposalsOnlyDifferByTimestamp(lastSignBytes, newSignBytes []byte) (time.Time, bool) { var lastProposal, newProposal cmtproto.CanonicalProposal if err := protoio.UnmarshalDelimited(lastSignBytes, &lastProposal); err != nil { diff --git a/privval/msgs.go b/privval/msgs.go index 1e383ad5949..de1f0a92715 100644 --- a/privval/msgs.go +++ b/privval/msgs.go @@ -3,9 +3,8 @@ package privval import ( "fmt" - "github.com/cosmos/gogoproto/proto" - pvproto "github.com/cometbft/cometbft/api/cometbft/privval/v1" + "github.com/cosmos/gogoproto/proto" ) // TODO: Add ChainIDRequest diff --git a/privval/signer_client.go b/privval/signer_client.go index 0db86f41a72..63603156e29 100644 --- a/privval/signer_client.go +++ b/privval/signer_client.go @@ -7,14 +7,13 @@ import ( pvproto "github.com/cometbft/cometbft/api/cometbft/privval/v1" cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cometbft/cometbft/crypto" - cmterrors "github.com/cometbft/cometbft/types/errors" - cryptoenc "github.com/cometbft/cometbft/crypto/encoding" "github.com/cometbft/cometbft/types" + cmterrors "github.com/cometbft/cometbft/types/errors" ) // SignerClient implements PrivValidator. -// Handles remote validator connections that provide signing services +// Handles remote validator connections that provide signing services. type SignerClient struct { endpoint *SignerListenerEndpoint chainID string @@ -23,7 +22,7 @@ type SignerClient struct { var _ types.PrivValidator = (*SignerClient)(nil) // NewSignerClient returns an instance of SignerClient. -// it will start the endpoint (if not already started) +// it will start the endpoint (if not already started). func NewSignerClient(endpoint *SignerListenerEndpoint, chainID string) (*SignerClient, error) { if !endpoint.IsRunning() { if err := endpoint.Start(); err != nil { @@ -34,17 +33,17 @@ func NewSignerClient(endpoint *SignerListenerEndpoint, chainID string) (*SignerC return &SignerClient{endpoint: endpoint, chainID: chainID}, nil } -// Close closes the underlying connection +// Close closes the underlying connection. func (sc *SignerClient) Close() error { return sc.endpoint.Close() } -// IsConnected indicates with the signer is connected to a remote signing service +// IsConnected indicates with the signer is connected to a remote signing service. func (sc *SignerClient) IsConnected() bool { return sc.endpoint.IsConnected() } -// WaitForConnection waits maxWait for a connection or returns a timeout error +// WaitForConnection waits maxWait for a connection or returns a timeout error. func (sc *SignerClient) WaitForConnection(maxWait time.Duration) error { return sc.endpoint.WaitForConnection(maxWait) } @@ -52,7 +51,7 @@ func (sc *SignerClient) WaitForConnection(maxWait time.Duration) error { //-------------------------------------------------------- // Implement PrivValidator -// Ping sends a ping request to the remote signer +// Ping sends a ping request to the remote signer. func (sc *SignerClient) Ping() error { response, err := sc.endpoint.SendRequest(mustWrapMsg(&pvproto.PingRequest{})) if err != nil { @@ -69,7 +68,7 @@ func (sc *SignerClient) Ping() error { } // GetPubKey retrieves a public key from a remote signer -// returns an error if client is not able to provide the key +// returns an error if client is not able to provide the key. func (sc *SignerClient) GetPubKey() (crypto.PubKey, error) { response, err := sc.endpoint.SendRequest(mustWrapMsg(&pvproto.PubKeyRequest{ChainId: sc.chainID})) if err != nil { @@ -92,7 +91,7 @@ func (sc *SignerClient) GetPubKey() (crypto.PubKey, error) { return pk, nil } -// SignVote requests a remote signer to sign a vote +// SignVote requests a remote signer to sign a vote. func (sc *SignerClient) SignVote(chainID string, vote *cmtproto.Vote) error { response, err := sc.endpoint.SendRequest(mustWrapMsg(&pvproto.SignVoteRequest{Vote: vote, ChainId: chainID})) if err != nil { @@ -112,7 +111,7 @@ func (sc *SignerClient) SignVote(chainID string, vote *cmtproto.Vote) error { return nil } -// SignProposal requests a remote signer to sign a proposal +// SignProposal requests a remote signer to sign a proposal. func (sc *SignerClient) SignProposal(chainID string, proposal *cmtproto.Proposal) error { response, err := sc.endpoint.SendRequest(mustWrapMsg( &pvproto.SignProposalRequest{Proposal: proposal, ChainId: chainID}, diff --git a/privval/signer_endpoint.go b/privval/signer_endpoint.go index 37b980d9295..b88441deff0 100644 --- a/privval/signer_endpoint.go +++ b/privval/signer_endpoint.go @@ -30,14 +30,14 @@ func (se *signerEndpoint) Close() error { return nil } -// IsConnected indicates if there is an active connection +// IsConnected indicates if there is an active connection. func (se *signerEndpoint) IsConnected() bool { se.connMtx.Lock() defer se.connMtx.Unlock() return se.isConnected() } -// TryGetConnection retrieves a connection if it is already available +// TryGetConnection retrieves a connection if it is already available. func (se *signerEndpoint) GetAvailableConnection(connectionAvailableCh chan net.Conn) bool { se.connMtx.Lock() defer se.connMtx.Unlock() @@ -51,7 +51,7 @@ func (se *signerEndpoint) GetAvailableConnection(connectionAvailableCh chan net. return false } -// TryGetConnection retrieves a connection if it is already available +// TryGetConnection retrieves a connection if it is already available. func (se *signerEndpoint) WaitConnection(connectionAvailableCh chan net.Conn, maxWait time.Duration) error { se.connMtx.Lock() defer se.connMtx.Unlock() @@ -65,21 +65,21 @@ func (se *signerEndpoint) WaitConnection(connectionAvailableCh chan net.Conn, ma return nil } -// SetConnection replaces the current connection object +// SetConnection replaces the current connection object. func (se *signerEndpoint) SetConnection(newConnection net.Conn) { se.connMtx.Lock() defer se.connMtx.Unlock() se.conn = newConnection } -// IsConnected indicates if there is an active connection +// IsConnected indicates if there is an active connection. func (se *signerEndpoint) DropConnection() { se.connMtx.Lock() defer se.connMtx.Unlock() se.dropConnection() } -// ReadMessage reads a message from the endpoint +// ReadMessage reads a message from the endpoint. func (se *signerEndpoint) ReadMessage() (msg privvalproto.Message, err error) { se.connMtx.Lock() defer se.connMtx.Unlock() @@ -111,7 +111,7 @@ func (se *signerEndpoint) ReadMessage() (msg privvalproto.Message, err error) { return } -// WriteMessage writes a message from the endpoint +// WriteMessage writes a message from the endpoint. func (se *signerEndpoint) WriteMessage(msg privvalproto.Message) (err error) { se.connMtx.Lock() defer se.connMtx.Unlock() diff --git a/privval/signer_listener_endpoint.go b/privval/signer_listener_endpoint.go index 62c7b092d04..e48ac8e9b5e 100644 --- a/privval/signer_listener_endpoint.go +++ b/privval/signer_listener_endpoint.go @@ -17,7 +17,7 @@ type SignerListenerEndpointOption func(*SignerListenerEndpoint) // SignerListenerEndpointTimeoutReadWrite sets the read and write timeout for // connections from external signing processes. // -// Default: 5s +// Default: 5s. func SignerListenerEndpointTimeoutReadWrite(timeout time.Duration) SignerListenerEndpointOption { return func(sl *SignerListenerEndpoint) { sl.signerEndpoint.timeoutReadWrite = timeout } } @@ -79,7 +79,7 @@ func (sl *SignerListenerEndpoint) OnStart() error { return nil } -// OnStop implements service.Service +// OnStop implements service.Service. func (sl *SignerListenerEndpoint) OnStop() { sl.instanceMtx.Lock() defer sl.instanceMtx.Unlock() @@ -96,14 +96,14 @@ func (sl *SignerListenerEndpoint) OnStop() { sl.pingTimer.Stop() } -// WaitForConnection waits maxWait for a connection or returns a timeout error +// WaitForConnection waits maxWait for a connection or returns a timeout error. func (sl *SignerListenerEndpoint) WaitForConnection(maxWait time.Duration) error { sl.instanceMtx.Lock() defer sl.instanceMtx.Unlock() return sl.ensureConnection(maxWait) } -// SendRequest ensures there is a connection, sends a request and waits for a response +// SendRequest ensures there is a connection, sends a request and waits for a response. func (sl *SignerListenerEndpoint) SendRequest(request privvalproto.Message) (*privvalproto.Message, error) { sl.instanceMtx.Lock() defer sl.instanceMtx.Unlock() diff --git a/privval/signer_server.go b/privval/signer_server.go index 7a9a82acdf0..3a79184405c 100644 --- a/privval/signer_server.go +++ b/privval/signer_server.go @@ -9,7 +9,7 @@ import ( "github.com/cometbft/cometbft/types" ) -// ValidationRequestHandlerFunc handles different remoteSigner requests +// ValidationRequestHandlerFunc handles different remoteSigner requests. type ValidationRequestHandlerFunc func( privVal types.PrivValidator, requestMessage privvalproto.Message, @@ -51,7 +51,7 @@ func (ss *SignerServer) OnStop() { _ = ss.endpoint.Close() } -// SetRequestHandler override the default function that is used to service requests +// SetRequestHandler override the default function that is used to service requests. func (ss *SignerServer) SetRequestHandler(validationRequestHandler ValidationRequestHandlerFunc) { ss.handlerMtx.Lock() defer ss.handlerMtx.Unlock() diff --git a/privval/utils.go b/privval/utils.go index 13dc5323dde..6754a927537 100644 --- a/privval/utils.go +++ b/privval/utils.go @@ -25,7 +25,7 @@ func IsConnTimeout(err error) bool { } } -// NewSignerListener creates a new SignerListenerEndpoint using the corresponding listen address +// NewSignerListener creates a new SignerListenerEndpoint using the corresponding listen address. func NewSignerListener(listenAddr string, logger log.Logger) (*SignerListenerEndpoint, error) { var listener net.Listener @@ -52,7 +52,7 @@ func NewSignerListener(listenAddr string, logger log.Logger) (*SignerListenerEnd return pve, nil } -// GetFreeLocalhostAddrPort returns a free localhost:port address +// GetFreeLocalhostAddrPort returns a free localhost:port address. func GetFreeLocalhostAddrPort() string { port, err := cmtnet.GetFreePort() if err != nil { diff --git a/proxy/app_conn.go b/proxy/app_conn.go index 78a877fe012..29d059bc7b3 100644 --- a/proxy/app_conn.go +++ b/proxy/app_conn.go @@ -4,10 +4,9 @@ import ( "context" "time" - "github.com/go-kit/kit/metrics" - abcicli "github.com/cometbft/cometbft/abci/client" types "github.com/cometbft/cometbft/abci/types" + "github.com/go-kit/kit/metrics" ) //go:generate ../scripts/mockery_generate.sh AppConnConsensus|AppConnMempool|AppConnQuery|AppConnSnapshot @@ -17,39 +16,39 @@ import ( type AppConnConsensus interface { Error() error - InitChain(context.Context, *types.InitChainRequest) (*types.InitChainResponse, error) - PrepareProposal(context.Context, *types.PrepareProposalRequest) (*types.PrepareProposalResponse, error) - ProcessProposal(context.Context, *types.ProcessProposalRequest) (*types.ProcessProposalResponse, error) - ExtendVote(context.Context, *types.ExtendVoteRequest) (*types.ExtendVoteResponse, error) - VerifyVoteExtension(context.Context, *types.VerifyVoteExtensionRequest) (*types.VerifyVoteExtensionResponse, error) - FinalizeBlock(context.Context, *types.FinalizeBlockRequest) (*types.FinalizeBlockResponse, error) - Commit(context.Context) (*types.CommitResponse, error) + InitChain(ctx context.Context, req *types.InitChainRequest) (*types.InitChainResponse, error) + PrepareProposal(ctx context.Context, req *types.PrepareProposalRequest) (*types.PrepareProposalResponse, error) + ProcessProposal(ctx context.Context, req *types.ProcessProposalRequest) (*types.ProcessProposalResponse, error) + ExtendVote(ctx context.Context, req *types.ExtendVoteRequest) (*types.ExtendVoteResponse, error) + VerifyVoteExtension(ctx context.Context, req *types.VerifyVoteExtensionRequest) (*types.VerifyVoteExtensionResponse, error) + FinalizeBlock(ctx context.Context, req *types.FinalizeBlockRequest) (*types.FinalizeBlockResponse, error) + Commit(ctx context.Context) (*types.CommitResponse, error) } type AppConnMempool interface { - SetResponseCallback(abcicli.Callback) + SetResponseCallback(cb abcicli.Callback) Error() error - CheckTx(context.Context, *types.CheckTxRequest) (*types.CheckTxResponse, error) - CheckTxAsync(context.Context, *types.CheckTxRequest) (*abcicli.ReqRes, error) - Flush(context.Context) error + CheckTx(ctx context.Context, req *types.CheckTxRequest) (*types.CheckTxResponse, error) + CheckTxAsync(ctx context.Context, req *types.CheckTxRequest) (*abcicli.ReqRes, error) + Flush(ctx context.Context) error } type AppConnQuery interface { Error() error - Echo(context.Context, string) (*types.EchoResponse, error) - Info(context.Context, *types.InfoRequest) (*types.InfoResponse, error) - Query(context.Context, *types.QueryRequest) (*types.QueryResponse, error) + Echo(ctx context.Context, echo string) (*types.EchoResponse, error) + Info(ctx context.Context, req *types.InfoRequest) (*types.InfoResponse, error) + Query(ctx context.Context, req *types.QueryRequest) (*types.QueryResponse, error) } type AppConnSnapshot interface { Error() error - ListSnapshots(context.Context, *types.ListSnapshotsRequest) (*types.ListSnapshotsResponse, error) - OfferSnapshot(context.Context, *types.OfferSnapshotRequest) (*types.OfferSnapshotResponse, error) - LoadSnapshotChunk(context.Context, *types.LoadSnapshotChunkRequest) (*types.LoadSnapshotChunkResponse, error) - ApplySnapshotChunk(context.Context, *types.ApplySnapshotChunkRequest) (*types.ApplySnapshotChunkResponse, error) + ListSnapshots(ctx context.Context, req *types.ListSnapshotsRequest) (*types.ListSnapshotsResponse, error) + OfferSnapshot(ctx context.Context, req *types.OfferSnapshotRequest) (*types.OfferSnapshotResponse, error) + LoadSnapshotChunk(ctx context.Context, req *types.LoadSnapshotChunkRequest) (*types.LoadSnapshotChunkResponse, error) + ApplySnapshotChunk(ctx context.Context, req *types.ApplySnapshotChunkRequest) (*types.ApplySnapshotChunkResponse, error) } //----------------------------------------------------------------------------------------- diff --git a/proxy/mocks/app_conn_consensus.go b/proxy/mocks/app_conn_consensus.go index 08739be6086..2ae515c9bab 100644 --- a/proxy/mocks/app_conn_consensus.go +++ b/proxy/mocks/app_conn_consensus.go @@ -15,9 +15,9 @@ type AppConnConsensus struct { mock.Mock } -// Commit provides a mock function with given fields: _a0 -func (_m *AppConnConsensus) Commit(_a0 context.Context) (*v1.CommitResponse, error) { - ret := _m.Called(_a0) +// Commit provides a mock function with given fields: ctx +func (_m *AppConnConsensus) Commit(ctx context.Context) (*v1.CommitResponse, error) { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Commit") @@ -26,10 +26,10 @@ func (_m *AppConnConsensus) Commit(_a0 context.Context) (*v1.CommitResponse, err var r0 *v1.CommitResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context) (*v1.CommitResponse, error)); ok { - return rf(_a0) + return rf(ctx) } if rf, ok := ret.Get(0).(func(context.Context) *v1.CommitResponse); ok { - r0 = rf(_a0) + r0 = rf(ctx) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.CommitResponse) @@ -37,7 +37,7 @@ func (_m *AppConnConsensus) Commit(_a0 context.Context) (*v1.CommitResponse, err } if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(_a0) + r1 = rf(ctx) } else { r1 = ret.Error(1) } @@ -63,9 +63,9 @@ func (_m *AppConnConsensus) Error() error { return r0 } -// ExtendVote provides a mock function with given fields: _a0, _a1 -func (_m *AppConnConsensus) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error) { - ret := _m.Called(_a0, _a1) +// ExtendVote provides a mock function with given fields: ctx, req +func (_m *AppConnConsensus) ExtendVote(ctx context.Context, req *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ExtendVote") @@ -74,10 +74,10 @@ func (_m *AppConnConsensus) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRe var r0 *v1.ExtendVoteResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ExtendVoteRequest) (*v1.ExtendVoteResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ExtendVoteRequest) *v1.ExtendVoteResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ExtendVoteResponse) @@ -85,7 +85,7 @@ func (_m *AppConnConsensus) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRe } if rf, ok := ret.Get(1).(func(context.Context, *v1.ExtendVoteRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -93,9 +93,9 @@ func (_m *AppConnConsensus) ExtendVote(_a0 context.Context, _a1 *v1.ExtendVoteRe return r0, r1 } -// FinalizeBlock provides a mock function with given fields: _a0, _a1 -func (_m *AppConnConsensus) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error) { - ret := _m.Called(_a0, _a1) +// FinalizeBlock provides a mock function with given fields: ctx, req +func (_m *AppConnConsensus) FinalizeBlock(ctx context.Context, req *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for FinalizeBlock") @@ -104,10 +104,10 @@ func (_m *AppConnConsensus) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeB var r0 *v1.FinalizeBlockResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.FinalizeBlockRequest) (*v1.FinalizeBlockResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.FinalizeBlockRequest) *v1.FinalizeBlockResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.FinalizeBlockResponse) @@ -115,7 +115,7 @@ func (_m *AppConnConsensus) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeB } if rf, ok := ret.Get(1).(func(context.Context, *v1.FinalizeBlockRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -123,9 +123,9 @@ func (_m *AppConnConsensus) FinalizeBlock(_a0 context.Context, _a1 *v1.FinalizeB return r0, r1 } -// InitChain provides a mock function with given fields: _a0, _a1 -func (_m *AppConnConsensus) InitChain(_a0 context.Context, _a1 *v1.InitChainRequest) (*v1.InitChainResponse, error) { - ret := _m.Called(_a0, _a1) +// InitChain provides a mock function with given fields: ctx, req +func (_m *AppConnConsensus) InitChain(ctx context.Context, req *v1.InitChainRequest) (*v1.InitChainResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for InitChain") @@ -134,10 +134,10 @@ func (_m *AppConnConsensus) InitChain(_a0 context.Context, _a1 *v1.InitChainRequ var r0 *v1.InitChainResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.InitChainRequest) (*v1.InitChainResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.InitChainRequest) *v1.InitChainResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.InitChainResponse) @@ -145,7 +145,7 @@ func (_m *AppConnConsensus) InitChain(_a0 context.Context, _a1 *v1.InitChainRequ } if rf, ok := ret.Get(1).(func(context.Context, *v1.InitChainRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -153,9 +153,9 @@ func (_m *AppConnConsensus) InitChain(_a0 context.Context, _a1 *v1.InitChainRequ return r0, r1 } -// PrepareProposal provides a mock function with given fields: _a0, _a1 -func (_m *AppConnConsensus) PrepareProposal(_a0 context.Context, _a1 *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error) { - ret := _m.Called(_a0, _a1) +// PrepareProposal provides a mock function with given fields: ctx, req +func (_m *AppConnConsensus) PrepareProposal(ctx context.Context, req *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for PrepareProposal") @@ -164,10 +164,10 @@ func (_m *AppConnConsensus) PrepareProposal(_a0 context.Context, _a1 *v1.Prepare var r0 *v1.PrepareProposalResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.PrepareProposalRequest) (*v1.PrepareProposalResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.PrepareProposalRequest) *v1.PrepareProposalResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.PrepareProposalResponse) @@ -175,7 +175,7 @@ func (_m *AppConnConsensus) PrepareProposal(_a0 context.Context, _a1 *v1.Prepare } if rf, ok := ret.Get(1).(func(context.Context, *v1.PrepareProposalRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -183,9 +183,9 @@ func (_m *AppConnConsensus) PrepareProposal(_a0 context.Context, _a1 *v1.Prepare return r0, r1 } -// ProcessProposal provides a mock function with given fields: _a0, _a1 -func (_m *AppConnConsensus) ProcessProposal(_a0 context.Context, _a1 *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error) { - ret := _m.Called(_a0, _a1) +// ProcessProposal provides a mock function with given fields: ctx, req +func (_m *AppConnConsensus) ProcessProposal(ctx context.Context, req *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ProcessProposal") @@ -194,10 +194,10 @@ func (_m *AppConnConsensus) ProcessProposal(_a0 context.Context, _a1 *v1.Process var r0 *v1.ProcessProposalResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ProcessProposalRequest) (*v1.ProcessProposalResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ProcessProposalRequest) *v1.ProcessProposalResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ProcessProposalResponse) @@ -205,7 +205,7 @@ func (_m *AppConnConsensus) ProcessProposal(_a0 context.Context, _a1 *v1.Process } if rf, ok := ret.Get(1).(func(context.Context, *v1.ProcessProposalRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -213,9 +213,9 @@ func (_m *AppConnConsensus) ProcessProposal(_a0 context.Context, _a1 *v1.Process return r0, r1 } -// VerifyVoteExtension provides a mock function with given fields: _a0, _a1 -func (_m *AppConnConsensus) VerifyVoteExtension(_a0 context.Context, _a1 *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error) { - ret := _m.Called(_a0, _a1) +// VerifyVoteExtension provides a mock function with given fields: ctx, req +func (_m *AppConnConsensus) VerifyVoteExtension(ctx context.Context, req *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for VerifyVoteExtension") @@ -224,10 +224,10 @@ func (_m *AppConnConsensus) VerifyVoteExtension(_a0 context.Context, _a1 *v1.Ver var r0 *v1.VerifyVoteExtensionResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.VerifyVoteExtensionRequest) (*v1.VerifyVoteExtensionResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.VerifyVoteExtensionRequest) *v1.VerifyVoteExtensionResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.VerifyVoteExtensionResponse) @@ -235,7 +235,7 @@ func (_m *AppConnConsensus) VerifyVoteExtension(_a0 context.Context, _a1 *v1.Ver } if rf, ok := ret.Get(1).(func(context.Context, *v1.VerifyVoteExtensionRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } diff --git a/proxy/mocks/app_conn_mempool.go b/proxy/mocks/app_conn_mempool.go index 0e39bd55054..224cfd296bb 100644 --- a/proxy/mocks/app_conn_mempool.go +++ b/proxy/mocks/app_conn_mempool.go @@ -17,9 +17,9 @@ type AppConnMempool struct { mock.Mock } -// CheckTx provides a mock function with given fields: _a0, _a1 -func (_m *AppConnMempool) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) (*v1.CheckTxResponse, error) { - ret := _m.Called(_a0, _a1) +// CheckTx provides a mock function with given fields: ctx, req +func (_m *AppConnMempool) CheckTx(ctx context.Context, req *v1.CheckTxRequest) (*v1.CheckTxResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for CheckTx") @@ -28,10 +28,10 @@ func (_m *AppConnMempool) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) ( var r0 *v1.CheckTxResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) (*v1.CheckTxResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) *v1.CheckTxResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.CheckTxResponse) @@ -39,7 +39,7 @@ func (_m *AppConnMempool) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) ( } if rf, ok := ret.Get(1).(func(context.Context, *v1.CheckTxRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -47,9 +47,9 @@ func (_m *AppConnMempool) CheckTx(_a0 context.Context, _a1 *v1.CheckTxRequest) ( return r0, r1 } -// CheckTxAsync provides a mock function with given fields: _a0, _a1 -func (_m *AppConnMempool) CheckTxAsync(_a0 context.Context, _a1 *v1.CheckTxRequest) (*abcicli.ReqRes, error) { - ret := _m.Called(_a0, _a1) +// CheckTxAsync provides a mock function with given fields: ctx, req +func (_m *AppConnMempool) CheckTxAsync(ctx context.Context, req *v1.CheckTxRequest) (*abcicli.ReqRes, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for CheckTxAsync") @@ -58,10 +58,10 @@ func (_m *AppConnMempool) CheckTxAsync(_a0 context.Context, _a1 *v1.CheckTxReque var r0 *abcicli.ReqRes var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) (*abcicli.ReqRes, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.CheckTxRequest) *abcicli.ReqRes); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*abcicli.ReqRes) @@ -69,7 +69,7 @@ func (_m *AppConnMempool) CheckTxAsync(_a0 context.Context, _a1 *v1.CheckTxReque } if rf, ok := ret.Get(1).(func(context.Context, *v1.CheckTxRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -95,9 +95,9 @@ func (_m *AppConnMempool) Error() error { return r0 } -// Flush provides a mock function with given fields: _a0 -func (_m *AppConnMempool) Flush(_a0 context.Context) error { - ret := _m.Called(_a0) +// Flush provides a mock function with given fields: ctx +func (_m *AppConnMempool) Flush(ctx context.Context) error { + ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for Flush") @@ -105,7 +105,7 @@ func (_m *AppConnMempool) Flush(_a0 context.Context) error { var r0 error if rf, ok := ret.Get(0).(func(context.Context) error); ok { - r0 = rf(_a0) + r0 = rf(ctx) } else { r0 = ret.Error(0) } @@ -113,9 +113,9 @@ func (_m *AppConnMempool) Flush(_a0 context.Context) error { return r0 } -// SetResponseCallback provides a mock function with given fields: _a0 -func (_m *AppConnMempool) SetResponseCallback(_a0 abcicli.Callback) { - _m.Called(_a0) +// SetResponseCallback provides a mock function with given fields: cb +func (_m *AppConnMempool) SetResponseCallback(cb abcicli.Callback) { + _m.Called(cb) } // NewAppConnMempool creates a new instance of AppConnMempool. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. diff --git a/proxy/mocks/app_conn_query.go b/proxy/mocks/app_conn_query.go index cd0a678f0ac..fdc2a50920a 100644 --- a/proxy/mocks/app_conn_query.go +++ b/proxy/mocks/app_conn_query.go @@ -15,9 +15,9 @@ type AppConnQuery struct { mock.Mock } -// Echo provides a mock function with given fields: _a0, _a1 -func (_m *AppConnQuery) Echo(_a0 context.Context, _a1 string) (*v1.EchoResponse, error) { - ret := _m.Called(_a0, _a1) +// Echo provides a mock function with given fields: ctx, echo +func (_m *AppConnQuery) Echo(ctx context.Context, echo string) (*v1.EchoResponse, error) { + ret := _m.Called(ctx, echo) if len(ret) == 0 { panic("no return value specified for Echo") @@ -26,10 +26,10 @@ func (_m *AppConnQuery) Echo(_a0 context.Context, _a1 string) (*v1.EchoResponse, var r0 *v1.EchoResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, string) (*v1.EchoResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, echo) } if rf, ok := ret.Get(0).(func(context.Context, string) *v1.EchoResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, echo) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.EchoResponse) @@ -37,7 +37,7 @@ func (_m *AppConnQuery) Echo(_a0 context.Context, _a1 string) (*v1.EchoResponse, } if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, echo) } else { r1 = ret.Error(1) } @@ -63,9 +63,9 @@ func (_m *AppConnQuery) Error() error { return r0 } -// Info provides a mock function with given fields: _a0, _a1 -func (_m *AppConnQuery) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.InfoResponse, error) { - ret := _m.Called(_a0, _a1) +// Info provides a mock function with given fields: ctx, req +func (_m *AppConnQuery) Info(ctx context.Context, req *v1.InfoRequest) (*v1.InfoResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Info") @@ -74,10 +74,10 @@ func (_m *AppConnQuery) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.Info var r0 *v1.InfoResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.InfoRequest) (*v1.InfoResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.InfoRequest) *v1.InfoResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.InfoResponse) @@ -85,7 +85,7 @@ func (_m *AppConnQuery) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.Info } if rf, ok := ret.Get(1).(func(context.Context, *v1.InfoRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -93,9 +93,9 @@ func (_m *AppConnQuery) Info(_a0 context.Context, _a1 *v1.InfoRequest) (*v1.Info return r0, r1 } -// Query provides a mock function with given fields: _a0, _a1 -func (_m *AppConnQuery) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.QueryResponse, error) { - ret := _m.Called(_a0, _a1) +// Query provides a mock function with given fields: ctx, req +func (_m *AppConnQuery) Query(ctx context.Context, req *v1.QueryRequest) (*v1.QueryResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for Query") @@ -104,10 +104,10 @@ func (_m *AppConnQuery) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.Qu var r0 *v1.QueryResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.QueryRequest) (*v1.QueryResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.QueryRequest) *v1.QueryResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.QueryResponse) @@ -115,7 +115,7 @@ func (_m *AppConnQuery) Query(_a0 context.Context, _a1 *v1.QueryRequest) (*v1.Qu } if rf, ok := ret.Get(1).(func(context.Context, *v1.QueryRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } diff --git a/proxy/mocks/app_conn_snapshot.go b/proxy/mocks/app_conn_snapshot.go index 44891040ec7..75094e34b26 100644 --- a/proxy/mocks/app_conn_snapshot.go +++ b/proxy/mocks/app_conn_snapshot.go @@ -15,9 +15,9 @@ type AppConnSnapshot struct { mock.Mock } -// ApplySnapshotChunk provides a mock function with given fields: _a0, _a1 -func (_m *AppConnSnapshot) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error) { - ret := _m.Called(_a0, _a1) +// ApplySnapshotChunk provides a mock function with given fields: ctx, req +func (_m *AppConnSnapshot) ApplySnapshotChunk(ctx context.Context, req *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ApplySnapshotChunk") @@ -26,10 +26,10 @@ func (_m *AppConnSnapshot) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.Apply var r0 *v1.ApplySnapshotChunkResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ApplySnapshotChunkRequest) (*v1.ApplySnapshotChunkResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ApplySnapshotChunkRequest) *v1.ApplySnapshotChunkResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ApplySnapshotChunkResponse) @@ -37,7 +37,7 @@ func (_m *AppConnSnapshot) ApplySnapshotChunk(_a0 context.Context, _a1 *v1.Apply } if rf, ok := ret.Get(1).(func(context.Context, *v1.ApplySnapshotChunkRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -63,9 +63,9 @@ func (_m *AppConnSnapshot) Error() error { return r0 } -// ListSnapshots provides a mock function with given fields: _a0, _a1 -func (_m *AppConnSnapshot) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error) { - ret := _m.Called(_a0, _a1) +// ListSnapshots provides a mock function with given fields: ctx, req +func (_m *AppConnSnapshot) ListSnapshots(ctx context.Context, req *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for ListSnapshots") @@ -74,10 +74,10 @@ func (_m *AppConnSnapshot) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapsh var r0 *v1.ListSnapshotsResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ListSnapshotsRequest) (*v1.ListSnapshotsResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ListSnapshotsRequest) *v1.ListSnapshotsResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ListSnapshotsResponse) @@ -85,7 +85,7 @@ func (_m *AppConnSnapshot) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapsh } if rf, ok := ret.Get(1).(func(context.Context, *v1.ListSnapshotsRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -93,9 +93,9 @@ func (_m *AppConnSnapshot) ListSnapshots(_a0 context.Context, _a1 *v1.ListSnapsh return r0, r1 } -// LoadSnapshotChunk provides a mock function with given fields: _a0, _a1 -func (_m *AppConnSnapshot) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error) { - ret := _m.Called(_a0, _a1) +// LoadSnapshotChunk provides a mock function with given fields: ctx, req +func (_m *AppConnSnapshot) LoadSnapshotChunk(ctx context.Context, req *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for LoadSnapshotChunk") @@ -104,10 +104,10 @@ func (_m *AppConnSnapshot) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSn var r0 *v1.LoadSnapshotChunkResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.LoadSnapshotChunkRequest) (*v1.LoadSnapshotChunkResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.LoadSnapshotChunkRequest) *v1.LoadSnapshotChunkResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.LoadSnapshotChunkResponse) @@ -115,7 +115,7 @@ func (_m *AppConnSnapshot) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSn } if rf, ok := ret.Get(1).(func(context.Context, *v1.LoadSnapshotChunkRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } @@ -123,9 +123,9 @@ func (_m *AppConnSnapshot) LoadSnapshotChunk(_a0 context.Context, _a1 *v1.LoadSn return r0, r1 } -// OfferSnapshot provides a mock function with given fields: _a0, _a1 -func (_m *AppConnSnapshot) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error) { - ret := _m.Called(_a0, _a1) +// OfferSnapshot provides a mock function with given fields: ctx, req +func (_m *AppConnSnapshot) OfferSnapshot(ctx context.Context, req *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error) { + ret := _m.Called(ctx, req) if len(ret) == 0 { panic("no return value specified for OfferSnapshot") @@ -134,10 +134,10 @@ func (_m *AppConnSnapshot) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnaps var r0 *v1.OfferSnapshotResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.OfferSnapshotRequest) (*v1.OfferSnapshotResponse, error)); ok { - return rf(_a0, _a1) + return rf(ctx, req) } if rf, ok := ret.Get(0).(func(context.Context, *v1.OfferSnapshotRequest) *v1.OfferSnapshotResponse); ok { - r0 = rf(_a0, _a1) + r0 = rf(ctx, req) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.OfferSnapshotResponse) @@ -145,7 +145,7 @@ func (_m *AppConnSnapshot) OfferSnapshot(_a0 context.Context, _a1 *v1.OfferSnaps } if rf, ok := ret.Get(1).(func(context.Context, *v1.OfferSnapshotRequest) error); ok { - r1 = rf(_a0, _a1) + r1 = rf(ctx, req) } else { r1 = ret.Error(1) } diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index 9c4411eb7ef..563fd98ffc6 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -40,7 +40,7 @@ func NewAppConns(clientCreator ClientCreator, metrics *Metrics) AppConns { // // A multiAppConn is made of a few appConns and manages their underlying abci // clients. -// TODO: on app restart, clients must reboot together +// TODO: on app restart, clients must reboot together. type multiAppConn struct { service.BaseService diff --git a/rpc/client/helpers.go b/rpc/client/helpers.go index fe34d0480b1..0fd46179a4a 100644 --- a/rpc/client/helpers.go +++ b/rpc/client/helpers.go @@ -9,11 +9,11 @@ import ( "github.com/cometbft/cometbft/types" ) -// Waiter is informed of current height, decided whether to quit early +// Waiter is informed of current height, decided whether to quit early. type Waiter func(delta int64) (abort error) // DefaultWaitStrategy is the standard backoff algorithm, -// but you can plug in another one +// but you can plug in another one. func DefaultWaitStrategy(delta int64) (abort error) { if delta > 10 { return fmt.Errorf("waiting for %d blocks... aborting", delta) @@ -31,7 +31,7 @@ func DefaultWaitStrategy(delta int64) (abort error) { // the block at the given height is available. // // If waiter is nil, we use DefaultWaitStrategy, but you can also -// provide your own implementation +// provide your own implementation. func WaitForHeight(c StatusClient, h int64, waiter Waiter) error { if waiter == nil { waiter = DefaultWaitStrategy @@ -56,7 +56,7 @@ func WaitForHeight(c StatusClient, h int64, waiter Waiter) error { // event time and returns upon receiving it one time, or // when the timeout duration has expired. // -// This handles subscribing and unsubscribing under the hood +// This handles subscribing and unsubscribing under the hood. func WaitForOneEvent(c EventsClient, evtTyp string, timeout time.Duration) (types.TMEventData, error) { const subscriber = "helpers" ctx, cancel := context.WithTimeout(context.Background(), timeout) diff --git a/rpc/client/http/http.go b/rpc/client/http/http.go index 38a3054bba6..78118cf0726 100644 --- a/rpc/client/http/http.go +++ b/rpc/client/http/http.go @@ -117,7 +117,7 @@ func New(remote string) (*HTTP, error) { return NewWithClient(remote, httpClient) } -// Create timeout enabled http client +// Create timeout enabled http client. func NewWithTimeout(remote string, timeout uint) (*HTTP, error) { httpClient, err := jsonrpcclient.DefaultHTTPClient(remote) if err != nil { diff --git a/rpc/client/interface.go b/rpc/client/interface.go index a814e456560..8229cb91a95 100644 --- a/rpc/client/interface.go +++ b/rpc/client/interface.go @@ -50,15 +50,15 @@ type Client interface { // is easier to mock. type ABCIClient interface { // Reading from abci app - ABCIInfo(context.Context) (*ctypes.ResultABCIInfo, error) + ABCIInfo(ctx context.Context) (*ctypes.ResultABCIInfo, error) ABCIQuery(ctx context.Context, path string, data bytes.HexBytes) (*ctypes.ResultABCIQuery, error) ABCIQueryWithOptions(ctx context.Context, path string, data bytes.HexBytes, opts ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) // Writing to abci app - BroadcastTxCommit(context.Context, types.Tx) (*ctypes.ResultBroadcastTxCommit, error) - BroadcastTxAsync(context.Context, types.Tx) (*ctypes.ResultBroadcastTx, error) - BroadcastTxSync(context.Context, types.Tx) (*ctypes.ResultBroadcastTx, error) + BroadcastTxCommit(ctx context.Context, tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) + BroadcastTxAsync(ctx context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) + BroadcastTxSync(ctx context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) } // SignClient groups together the functionality needed to get valid signatures @@ -95,28 +95,28 @@ type SignClient interface { // HistoryClient provides access to data from genesis to now in large chunks. type HistoryClient interface { - Genesis(context.Context) (*ctypes.ResultGenesis, error) - GenesisChunked(context.Context, uint) (*ctypes.ResultGenesisChunk, error) + Genesis(ctx context.Context) (*ctypes.ResultGenesis, error) + GenesisChunked(ctx context.Context, id uint) (*ctypes.ResultGenesisChunk, error) BlockchainInfo(ctx context.Context, minHeight, maxHeight int64) (*ctypes.ResultBlockchainInfo, error) } // StatusClient provides access to general chain info. type StatusClient interface { - Status(context.Context) (*ctypes.ResultStatus, error) + Status(ctx context.Context) (*ctypes.ResultStatus, error) } // NetworkClient is general info about the network state. May not be needed // usually. type NetworkClient interface { - NetInfo(context.Context) (*ctypes.ResultNetInfo, error) - DumpConsensusState(context.Context) (*ctypes.ResultDumpConsensusState, error) - ConsensusState(context.Context) (*ctypes.ResultConsensusState, error) + NetInfo(ctx context.Context) (*ctypes.ResultNetInfo, error) + DumpConsensusState(ctx context.Context) (*ctypes.ResultDumpConsensusState, error) + ConsensusState(ctx context.Context) (*ctypes.ResultConsensusState, error) ConsensusParams(ctx context.Context, height *int64) (*ctypes.ResultConsensusParams, error) - Health(context.Context) (*ctypes.ResultHealth, error) + Health(ctx context.Context) (*ctypes.ResultHealth, error) } // EventsClient is reactive, you can subscribe to any message, given the proper -// string. see cometbft/types/events.go +// string. see cometbft/types/events.go. type EventsClient interface { // Subscribe subscribes given subscriber to query. Returns a channel with // cap=1 onto which events are published. An error is returned if it fails to @@ -135,14 +135,14 @@ type EventsClient interface { // MempoolClient shows us data about current mempool state. type MempoolClient interface { UnconfirmedTxs(ctx context.Context, limit *int) (*ctypes.ResultUnconfirmedTxs, error) - NumUnconfirmedTxs(context.Context) (*ctypes.ResultUnconfirmedTxs, error) - CheckTx(context.Context, types.Tx) (*ctypes.ResultCheckTx, error) + NumUnconfirmedTxs(ctx context.Context) (*ctypes.ResultUnconfirmedTxs, error) + CheckTx(ctx context.Context, tx types.Tx) (*ctypes.ResultCheckTx, error) } // EvidenceClient is used for submitting an evidence of the malicious // behavior. type EvidenceClient interface { - BroadcastEvidence(context.Context, types.Evidence) (*ctypes.ResultBroadcastEvidence, error) + BroadcastEvidence(ctx context.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) } // RemoteClient is a Client, which can also return the remote network address. diff --git a/rpc/client/mock/status.go b/rpc/client/mock/status.go index 69b60674778..9d57e54ed8a 100644 --- a/rpc/client/mock/status.go +++ b/rpc/client/mock/status.go @@ -7,7 +7,7 @@ import ( ctypes "github.com/cometbft/cometbft/rpc/core/types" ) -// StatusMock returns the result specified by the Call +// StatusMock returns the result specified by the Call. type StatusMock struct { Call } @@ -26,7 +26,7 @@ func (m *StatusMock) Status(context.Context) (*ctypes.ResultStatus, error) { } // StatusRecorder can wrap another type (StatusMock, full client) -// and record the status calls +// and record the status calls. type StatusRecorder struct { Client client.StatusClient Calls []Call diff --git a/rpc/core/env.go b/rpc/core/env.go index a32b3c86b6c..ffa312a5618 100644 --- a/rpc/core/env.go +++ b/rpc/core/env.go @@ -19,16 +19,16 @@ import ( ) const ( - // see README + // see README. defaultPerPage = 30 maxPerPage = 100 // SubscribeTimeout is the maximum time we wait to subscribe for an event. - // must be less than the server's write timeout (see rpcserver.DefaultConfig) + // must be less than the server's write timeout (see rpcserver.DefaultConfig). SubscribeTimeout = 5 * time.Second // genesisChunkSize is the maximum size, in bytes, of each - // chunk in the genesis structure for the chunked API + // chunk in the genesis structure for the chunked API. genesisChunkSize = 16 * 1024 * 1024 // 16 ) @@ -50,10 +50,10 @@ type transport interface { } type peers interface { - AddPersistentPeers([]string) error - AddUnconditionalPeerIDs([]string) error - AddPrivatePeerIDs([]string) error - DialPeersAsync([]string) error + AddPersistentPeers(peers []string) error + AddUnconditionalPeerIDs(peerIDs []string) error + AddPrivatePeerIDs(peerIDs []string) error + DialPeersAsync(peers []string) error Peers() p2p.IPeerSet } diff --git a/rpc/core/events.go b/rpc/core/events.go index 6b67508251a..8909a733250 100644 --- a/rpc/core/events.go +++ b/rpc/core/events.go @@ -23,11 +23,12 @@ const ( func (env *Environment) Subscribe(ctx *rpctypes.Context, query string) (*ctypes.ResultSubscribe, error) { addr := ctx.RemoteAddr() - if env.EventBus.NumClients() >= env.Config.MaxSubscriptionClients { + switch { + case env.EventBus.NumClients() >= env.Config.MaxSubscriptionClients: return nil, fmt.Errorf("max_subscription_clients %d reached", env.Config.MaxSubscriptionClients) - } else if env.EventBus.NumClientSubscriptions(addr) >= env.Config.MaxSubscriptionsPerClient { + case env.EventBus.NumClientSubscriptions(addr) >= env.Config.MaxSubscriptionsPerClient: return nil, fmt.Errorf("max_subscriptions_per_client %d reached", env.Config.MaxSubscriptionsPerClient) - } else if len(query) > maxQueryLength { + case len(query) > maxQueryLength: return nil, errors.New("maximum query length exceeded") } diff --git a/rpc/core/net.go b/rpc/core/net.go index 12ed51a769d..87cd8cde006 100644 --- a/rpc/core/net.go +++ b/rpc/core/net.go @@ -130,13 +130,11 @@ func getIDs(peers []string) ([]string, error) { ids := make([]string, 0, len(peers)) for _, peer := range peers { - spl := strings.Split(peer, "@") if len(spl) != 2 { return nil, p2p.ErrNetAddressNoID{Addr: peer} } ids = append(ids, spl[0]) - } return ids, nil } diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index fba5169f9aa..5139fd672a8 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -12,13 +12,13 @@ import ( "github.com/cometbft/cometbft/types" ) -// List of blocks +// List of blocks. type ResultBlockchainInfo struct { LastHeight int64 `json:"last_height"` BlockMetas []*types.BlockMeta `json:"block_metas"` } -// Genesis file +// Genesis file. type ResultGenesis struct { Genesis *types.GenesisDoc `json:"genesis"` } @@ -33,24 +33,24 @@ type ResultGenesisChunk struct { Data string `json:"data"` } -// Single block (with meta) +// Single block (with meta). type ResultBlock struct { BlockID types.BlockID `json:"block_id"` Block *types.Block `json:"block"` } -// ResultHeader represents the response for a Header RPC Client query +// ResultHeader represents the response for a Header RPC Client query. type ResultHeader struct { Header *types.Header `json:"header"` } -// Commit and Header +// Commit and Header. type ResultCommit struct { types.SignedHeader `json:"signed_header"` CanonicalCommit bool `json:"canonical"` } -// ABCI results from a block +// ABCI results from a block. type ResultBlockResults struct { Height int64 `json:"height"` TxResults []*abci.ExecTxResult `json:"txs_results"` @@ -61,7 +61,7 @@ type ResultBlockResults struct { } // NewResultCommit is a helper to initialize the ResultCommit with -// the embedded struct +// the embedded struct. func NewResultCommit(header *types.Header, commit *types.Commit, canonical bool, ) *ResultCommit { @@ -74,7 +74,7 @@ func NewResultCommit(header *types.Header, commit *types.Commit, } } -// Info about the node's syncing state +// Info about the node's syncing state. type SyncInfo struct { LatestBlockHash bytes.HexBytes `json:"latest_block_hash"` LatestAppHash bytes.HexBytes `json:"latest_app_hash"` @@ -89,21 +89,21 @@ type SyncInfo struct { CatchingUp bool `json:"catching_up"` } -// Info about the node's validator +// Info about the node's validator. type ValidatorInfo struct { Address bytes.HexBytes `json:"address"` PubKey crypto.PubKey `json:"pub_key"` VotingPower int64 `json:"voting_power"` } -// Node Status +// Node Status. type ResultStatus struct { NodeInfo p2p.DefaultNodeInfo `json:"node_info"` SyncInfo SyncInfo `json:"sync_info"` ValidatorInfo ValidatorInfo `json:"validator_info"` } -// Is TxIndexing enabled +// Is TxIndexing enabled. func (s *ResultStatus) TxIndexEnabled() bool { if s == nil { return false @@ -111,7 +111,7 @@ func (s *ResultStatus) TxIndexEnabled() bool { return s.NodeInfo.Other.TxIndex == "on" } -// Info about peer connections +// Info about peer connections. type ResultNetInfo struct { Listening bool `json:"listening"` Listeners []string `json:"listeners"` @@ -119,17 +119,17 @@ type ResultNetInfo struct { Peers []Peer `json:"peers"` } -// Log from dialing seeds +// Log from dialing seeds. type ResultDialSeeds struct { Log string `json:"log"` } -// Log from dialing peers +// Log from dialing peers. type ResultDialPeers struct { Log string `json:"log"` } -// A peer +// A peer. type Peer struct { NodeInfo p2p.DefaultNodeInfo `json:"node_info"` IsOutbound bool `json:"is_outbound"` @@ -147,31 +147,31 @@ type ResultValidators struct { Total int `json:"total"` } -// ConsensusParams for given height +// ConsensusParams for given height. type ResultConsensusParams struct { BlockHeight int64 `json:"block_height"` ConsensusParams types.ConsensusParams `json:"consensus_params"` } // Info about the consensus state. -// UNSTABLE +// UNSTABLE. type ResultDumpConsensusState struct { RoundState json.RawMessage `json:"round_state"` Peers []PeerStateInfo `json:"peers"` } -// UNSTABLE +// UNSTABLE. type PeerStateInfo struct { NodeAddress string `json:"node_address"` PeerState json.RawMessage `json:"peer_state"` } -// UNSTABLE +// UNSTABLE. type ResultConsensusState struct { RoundState json.RawMessage `json:"round_state"` } -// CheckTx result +// CheckTx result. type ResultBroadcastTx struct { Code uint32 `json:"code"` Data bytes.HexBytes `json:"data"` @@ -181,7 +181,7 @@ type ResultBroadcastTx struct { Hash bytes.HexBytes `json:"hash"` } -// CheckTx and ExecTx results +// CheckTx and ExecTx results. type ResultBroadcastTxCommit struct { CheckTx abci.CheckTxResponse `json:"check_tx"` TxResult abci.ExecTxResult `json:"tx_result"` @@ -194,7 +194,7 @@ type ResultCheckTx struct { abci.CheckTxResponse } -// Result of querying for a tx +// Result of querying for a tx. type ResultTx struct { Hash bytes.HexBytes `json:"hash"` Height int64 `json:"height"` @@ -204,7 +204,7 @@ type ResultTx struct { Proof types.TxProof `json:"proof,omitempty"` } -// Result of searching for txs +// Result of searching for txs. type ResultTxSearch struct { Txs []*ResultTx `json:"txs"` TotalCount int `json:"total_count"` @@ -216,7 +216,7 @@ type ResultBlockSearch struct { TotalCount int `json:"total_count"` } -// List of mempool txs +// List of mempool txs. type ResultUnconfirmedTxs struct { Count int `json:"n_txs"` Total int `json:"total"` @@ -224,22 +224,22 @@ type ResultUnconfirmedTxs struct { Txs []types.Tx `json:"txs"` } -// Info abci msg +// Info abci msg. type ResultABCIInfo struct { Response abci.InfoResponse `json:"response"` } -// Query abci msg +// Query abci msg. type ResultABCIQuery struct { Response abci.QueryResponse `json:"response"` } -// Result of broadcasting evidence +// Result of broadcasting evidence. type ResultBroadcastEvidence struct { Hash []byte `json:"hash"` } -// empty results +// empty results. type ( ResultUnsafeFlushMempool struct{} ResultUnsafeProfile struct{} @@ -248,7 +248,7 @@ type ( ResultHealth struct{} ) -// Event data from a subscription +// Event data from a subscription. type ResultEvent struct { Query string `json:"query"` Data types.TMEventData `json:"data"` diff --git a/rpc/grpc/client/block_results_service.go b/rpc/grpc/client/block_results_service.go index c2cd391db4b..85b65db3a9a 100644 --- a/rpc/grpc/client/block_results_service.go +++ b/rpc/grpc/client/block_results_service.go @@ -5,11 +5,9 @@ import ( "fmt" abci "github.com/cometbft/cometbft/abci/types" + brs "github.com/cometbft/cometbft/api/cometbft/services/block_results/v1" cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" - "github.com/cosmos/gogoproto/grpc" - - brs "github.com/cometbft/cometbft/api/cometbft/services/block_results/v1" ) type BlockResults struct { @@ -75,12 +73,12 @@ func newDisabledBlockResultsServiceClient() BlockResultsServiceClient { return &disabledBlockResultsServiceClient{} } -// GetBlockResults implements BlockResultsServiceClient +// GetBlockResults implements BlockResultsServiceClient. func (*disabledBlockResultsServiceClient) GetBlockResults(_ context.Context, _ int64) (*BlockResults, error) { panic("block results service client is disabled") } -// GetLatestBlockResults implements BlockResultsServiceClient +// GetLatestBlockResults implements BlockResultsServiceClient. func (*disabledBlockResultsServiceClient) GetLatestBlockResults(_ context.Context) (*BlockResults, error) { panic("block results service client is disabled") } diff --git a/rpc/grpc/client/block_service.go b/rpc/grpc/client/block_service.go index fada9b25909..9ce54fd3b05 100644 --- a/rpc/grpc/client/block_service.go +++ b/rpc/grpc/client/block_service.go @@ -4,11 +4,10 @@ import ( "context" "fmt" - "github.com/cosmos/gogoproto/grpc" - blocksvc "github.com/cometbft/cometbft/api/cometbft/services/block/v1" cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cometbft/cometbft/types" + "github.com/cosmos/gogoproto/grpc" ) // Block data returned by the CometBFT BlockService gRPC API. @@ -35,7 +34,7 @@ func blockFromProto(pblockID *cmtproto.BlockID, pblock *cmtproto.Block) (*Block, } // LatestHeightResult type used in GetLatestResult and send to the client -// via a channel +// via a channel. type LatestHeightResult struct { Height int64 Error error @@ -55,7 +54,7 @@ func GetLatestHeightChannelSize(sz uint) GetLatestHeightOption { } } -// BlockServiceClient provides block information +// BlockServiceClient provides block information. type BlockServiceClient interface { // GetBlockByHeight attempts to retrieve the block associated with the // given height. @@ -79,7 +78,7 @@ func newBlockServiceClient(conn grpc.ClientConn) BlockServiceClient { } } -// GetBlockByHeight implements BlockServiceClient GetBlockByHeight +// GetBlockByHeight implements BlockServiceClient GetBlockByHeight. func (c *blockServiceClient) GetBlockByHeight(ctx context.Context, height int64) (*Block, error) { res, err := c.client.GetByHeight(ctx, &blocksvc.GetByHeightRequest{ Height: height, @@ -101,7 +100,7 @@ func (c *blockServiceClient) GetLatestBlock(ctx context.Context) (*Block, error) return blockFromProto(res.BlockId, res.Block) } -// GetLatestHeight implements BlockServiceClient GetLatestHeight +// GetLatestHeight implements BlockServiceClient GetLatestHeight. func (c *blockServiceClient) GetLatestHeight(ctx context.Context, opts ...GetLatestHeightOption) (<-chan LatestHeightResult, error) { req := blocksvc.GetLatestHeightRequest{} @@ -137,7 +136,6 @@ func (c *blockServiceClient) GetLatestHeight(ctx context.Context, opts ...GetLat // Skip sending this result because the channel is full - the // client will get the next one once the channel opens up again } - } }(latestHeightClient) @@ -150,7 +148,7 @@ func newDisabledBlockServiceClient() BlockServiceClient { return &disabledBlockServiceClient{} } -// GetBlockByHeight implements BlockServiceClient GetBlockByHeight - disabled client +// GetBlockByHeight implements BlockServiceClient GetBlockByHeight - disabled client. func (*disabledBlockServiceClient) GetBlockByHeight(context.Context, int64) (*Block, error) { panic("block service client is disabled") } @@ -160,7 +158,7 @@ func (*disabledBlockServiceClient) GetLatestBlock(context.Context) (*Block, erro panic("block service client is disabled") } -// GetLatestHeight implements BlockServiceClient GetLatestHeight - disabled client +// GetLatestHeight implements BlockServiceClient GetLatestHeight - disabled client. func (*disabledBlockServiceClient) GetLatestHeight(context.Context, ...GetLatestHeightOption) (<-chan LatestHeightResult, error) { panic("block service client is disabled") } diff --git a/rpc/grpc/client/client.go b/rpc/grpc/client/client.go index da0fc892572..a34570dc27f 100644 --- a/rpc/grpc/client/client.go +++ b/rpc/grpc/client/client.go @@ -9,10 +9,9 @@ import ( "fmt" "net" + cmtnet "github.com/cometbft/cometbft/internal/net" ggrpc "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - - cmtnet "github.com/cometbft/cometbft/internal/net" ) type Option func(*clientBuilder) diff --git a/rpc/grpc/client/privileged/privileged.go b/rpc/grpc/client/privileged/privileged.go index a85de564d82..4e4bd9af447 100644 --- a/rpc/grpc/client/privileged/privileged.go +++ b/rpc/grpc/client/privileged/privileged.go @@ -5,10 +5,9 @@ import ( "fmt" "net" + cmtnet "github.com/cometbft/cometbft/internal/net" ggrpc "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - - cmtnet "github.com/cometbft/cometbft/internal/net" ) type Option func(*clientBuilder) diff --git a/rpc/grpc/client/privileged/pruning_service.go b/rpc/grpc/client/privileged/pruning_service.go index 5e218cd4c99..a4e0176b90c 100644 --- a/rpc/grpc/client/privileged/pruning_service.go +++ b/rpc/grpc/client/privileged/pruning_service.go @@ -3,9 +3,8 @@ package privileged import ( "context" - "github.com/cosmos/gogoproto/grpc" - pbsvc "github.com/cometbft/cometbft/api/cometbft/services/pruning/v1" + "github.com/cosmos/gogoproto/grpc" ) // RetainHeights provides information on which block height limits have been @@ -52,7 +51,7 @@ func (c *pruningServiceClient) GetBlockIndexerRetainHeight(ctx context.Context) return res.Height, nil } -// SetTxIndexerRetainHeight implements PruningServiceClient +// SetTxIndexerRetainHeight implements PruningServiceClient. func (c *pruningServiceClient) SetTxIndexerRetainHeight(ctx context.Context, height uint64) error { _, err := c.inner.SetTxIndexerRetainHeight(ctx, &pbsvc.SetTxIndexerRetainHeightRequest{ Height: height, @@ -60,7 +59,7 @@ func (c *pruningServiceClient) SetTxIndexerRetainHeight(ctx context.Context, hei return err } -// GetTxIndexerRetainHeight implements PruningServiceClient +// GetTxIndexerRetainHeight implements PruningServiceClient. func (c *pruningServiceClient) GetTxIndexerRetainHeight(ctx context.Context) (uint64, error) { res, err := c.inner.GetTxIndexerRetainHeight(ctx, &pbsvc.GetTxIndexerRetainHeightRequest{}) if err != nil { diff --git a/rpc/grpc/client/version_service.go b/rpc/grpc/client/version_service.go index 9745412e0f8..3f117e4dc5d 100644 --- a/rpc/grpc/client/version_service.go +++ b/rpc/grpc/client/version_service.go @@ -3,9 +3,8 @@ package client import ( "context" - "github.com/cosmos/gogoproto/grpc" - pbsvc "github.com/cometbft/cometbft/api/cometbft/services/version/v1" + "github.com/cosmos/gogoproto/grpc" ) // Version provides version information about a particular CometBFT node. @@ -31,7 +30,7 @@ func newVersionServiceClient(conn grpc.ClientConn) VersionServiceClient { } } -// GetVersion implements VersionServiceClient +// GetVersion implements VersionServiceClient. func (c *versionServiceClient) GetVersion(ctx context.Context) (*Version, error) { res, err := c.client.GetVersion(ctx, &pbsvc.GetVersionRequest{}) if err != nil { @@ -51,7 +50,7 @@ func newDisabledVersionServiceClient() VersionServiceClient { return &disabledVersionServiceClient{} } -// GetVersion implements VersionServiceClient +// GetVersion implements VersionServiceClient. func (*disabledVersionServiceClient) GetVersion(context.Context) (*Version, error) { panic("version service client is disabled") } diff --git a/rpc/grpc/server/privileged/privileged.go b/rpc/grpc/server/privileged/privileged.go index bde0ce28a30..6295e99068d 100644 --- a/rpc/grpc/server/privileged/privileged.go +++ b/rpc/grpc/server/privileged/privileged.go @@ -4,12 +4,11 @@ import ( "fmt" "net" - "google.golang.org/grpc" - pbpruningsvc "github.com/cometbft/cometbft/api/cometbft/services/pruning/v1" sm "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/rpc/grpc/server/services/pruningservice" + "google.golang.org/grpc" ) // Option is any function that allows for configuration of the gRPC server diff --git a/rpc/grpc/server/server.go b/rpc/grpc/server/server.go index 5b00829c58a..6acf372a326 100644 --- a/rpc/grpc/server/server.go +++ b/rpc/grpc/server/server.go @@ -5,20 +5,17 @@ import ( "net" "strings" - sm "github.com/cometbft/cometbft/internal/state" - "github.com/cometbft/cometbft/internal/store" - - brs "github.com/cometbft/cometbft/api/cometbft/services/block_results/v1" - "github.com/cometbft/cometbft/rpc/grpc/server/services/blockresultservice" - - "google.golang.org/grpc" - pbblocksvc "github.com/cometbft/cometbft/api/cometbft/services/block/v1" + brs "github.com/cometbft/cometbft/api/cometbft/services/block_results/v1" pbversionsvc "github.com/cometbft/cometbft/api/cometbft/services/version/v1" + sm "github.com/cometbft/cometbft/internal/state" + "github.com/cometbft/cometbft/internal/store" "github.com/cometbft/cometbft/libs/log" + "github.com/cometbft/cometbft/rpc/grpc/server/services/blockresultservice" "github.com/cometbft/cometbft/rpc/grpc/server/services/blockservice" "github.com/cometbft/cometbft/rpc/grpc/server/services/versionservice" "github.com/cometbft/cometbft/types" + "google.golang.org/grpc" ) // Option is any function that allows for configuration of the gRPC server diff --git a/rpc/grpc/server/services/blockresultservice/service.go b/rpc/grpc/server/services/blockresultservice/service.go index 386644bf688..baff554f632 100644 --- a/rpc/grpc/server/services/blockresultservice/service.go +++ b/rpc/grpc/server/services/blockresultservice/service.go @@ -3,14 +3,12 @@ package blockresultservice import ( "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - + brs "github.com/cometbft/cometbft/api/cometbft/services/block_results/v1" sm "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/internal/store" "github.com/cometbft/cometbft/libs/log" - - brs "github.com/cometbft/cometbft/api/cometbft/services/block_results/v1" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) type blockResultsService struct { diff --git a/rpc/grpc/server/services/blockservice/service.go b/rpc/grpc/server/services/blockservice/service.go index e1037cc0c76..a1b1bfd97f7 100644 --- a/rpc/grpc/server/services/blockservice/service.go +++ b/rpc/grpc/server/services/blockservice/service.go @@ -4,9 +4,6 @@ import ( context "context" "fmt" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - blocksvc "github.com/cometbft/cometbft/api/cometbft/services/block/v1" ptypes "github.com/cometbft/cometbft/api/cometbft/types/v1" cmtpubsub "github.com/cometbft/cometbft/internal/pubsub" @@ -14,6 +11,8 @@ import ( "github.com/cometbft/cometbft/internal/store" "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) type blockServiceServer struct { @@ -31,7 +30,7 @@ func New(store *store.BlockStore, eventBus *types.EventBus, logger log.Logger) b } } -// GetByHeight implements v1.BlockServiceServer GetByHeight method +// GetByHeight implements v1.BlockServiceServer GetByHeight method. func (s *blockServiceServer) GetByHeight(_ context.Context, req *blocksvc.GetByHeightRequest) (*blocksvc.GetByHeightResponse, error) { logger := s.logger.With("endpoint", "GetByHeight") if err := validateBlockHeight(req.Height, s.store.Base(), s.store.Height()); err != nil { @@ -95,7 +94,7 @@ func (s *blockServiceServer) getBlock(height int64, logger log.Logger) (*ptypes. return &blockIDProto, bp, nil } -// GetLatestHeight implements v1.BlockServiceServer GetLatestHeight method +// GetLatestHeight implements v1.BlockServiceServer GetLatestHeight method. func (s *blockServiceServer) GetLatestHeight(_ *blocksvc.GetLatestHeightRequest, stream blocksvc.BlockService_GetLatestHeightServer) error { logger := s.logger.With("endpoint", "GetLatestHeight") diff --git a/rpc/grpc/server/services/pruningservice/service.go b/rpc/grpc/server/services/pruningservice/service.go index 88af14fff97..c5ae94594c9 100644 --- a/rpc/grpc/server/services/pruningservice/service.go +++ b/rpc/grpc/server/services/pruningservice/service.go @@ -5,13 +5,12 @@ import ( "fmt" "math" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - pbsvc "github.com/cometbft/cometbft/api/cometbft/services/pruning/v1" "github.com/cometbft/cometbft/internal/rpctrace" sm "github.com/cometbft/cometbft/internal/state" "github.com/cometbft/cometbft/libs/log" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) type pruningServiceServer struct { diff --git a/rpc/grpc/server/services/versionservice/service.go b/rpc/grpc/server/services/versionservice/service.go index 876869802f9..d73bc141fbf 100644 --- a/rpc/grpc/server/services/versionservice/service.go +++ b/rpc/grpc/server/services/versionservice/service.go @@ -14,7 +14,7 @@ func New() pbsvc.VersionServiceServer { return &versionServiceServer{} } -// GetVersion implements v1.VersionServiceServer +// GetVersion implements v1.VersionServiceServer. func (s *versionServiceServer) GetVersion(context.Context, *pbsvc.GetVersionRequest) (*pbsvc.GetVersionResponse, error) { return &pbsvc.GetVersionResponse{ Node: version.CMTSemVer, diff --git a/rpc/jsonrpc/client/decode.go b/rpc/jsonrpc/client/decode.go index 2ae917d97d1..709f8250107 100644 --- a/rpc/jsonrpc/client/decode.go +++ b/rpc/jsonrpc/client/decode.go @@ -14,7 +14,6 @@ func unmarshalResponseBytes( expectedID types.JSONRPCIntID, result interface{}, ) (interface{}, error) { - // Read response. If rpc/core/types is imported, the result will unmarshal // into the correct type. response := &types.RPCResponse{} @@ -43,10 +42,7 @@ func unmarshalResponseBytesArray( expectedIDs []types.JSONRPCIntID, results []interface{}, ) ([]interface{}, error) { - - var ( - responses []types.RPCResponse - ) + var responses []types.RPCResponse if err := json.Unmarshal(responseBytes, &responses); err != nil { return nil, fmt.Errorf("error unmarshalling: %w", err) diff --git a/rpc/jsonrpc/client/http_json_client.go b/rpc/jsonrpc/client/http_json_client.go index 35e77df8049..fabc6016b73 100644 --- a/rpc/jsonrpc/client/http_json_client.go +++ b/rpc/jsonrpc/client/http_json_client.go @@ -26,14 +26,14 @@ const ( //------------------------------------------------------------- -// Parsed URL structure +// Parsed URL structure. type parsedURL struct { url.URL isUnixSocket bool } -// Parse URL and set defaults +// Parse URL and set defaults. func newParsedURL(remoteAddr string) (*parsedURL, error) { u, err := url.Parse(remoteAddr) if err != nil { @@ -57,7 +57,7 @@ func newParsedURL(remoteAddr string) (*parsedURL, error) { return pu, nil } -// Change protocol to HTTP for unknown protocols and TCP protocol - useful for RPC connections +// Change protocol to HTTP for unknown protocols and TCP protocol - useful for RPC connections. func (u *parsedURL) SetDefaultSchemeHTTP() { // protocol to use for http operations, to support both http and https switch u.Scheme { @@ -69,13 +69,13 @@ func (u *parsedURL) SetDefaultSchemeHTTP() { } } -// Get full address without the protocol - useful for Dialer connections +// Get full address without the protocol - useful for Dialer connections. func (u parsedURL) GetHostWithPath() string { // Remove protocol, userinfo and # fragment, assume opaque is empty return u.Host + u.EscapedPath() } -// Get a trimmed address - useful for WS connections +// Get a trimmed address - useful for WS connections. func (u parsedURL) GetTrimmedHostWithPath() string { // if it's not an unix socket we return the normal URL if !u.isUnixSocket { @@ -87,7 +87,7 @@ func (u parsedURL) GetTrimmedHostWithPath() string { return strings.ReplaceAll(u.GetHostWithPath(), "/", ".") } -// GetDialAddress returns the endpoint to dial for the parsed URL +// GetDialAddress returns the endpoint to dial for the parsed URL. func (u parsedURL) GetDialAddress() string { // if it's not a unix socket we return the host, example: localhost:443 if !u.isUnixSocket { @@ -97,7 +97,7 @@ func (u parsedURL) GetDialAddress() string { return u.GetHostWithPath() } -// Get a trimmed address with protocol - useful as address in RPC connections +// Get a trimmed address with protocol - useful as address in RPC connections. func (u parsedURL) GetTrimmedURL() string { return u.Scheme + "://" + u.GetTrimmedHostWithPath() } diff --git a/rpc/jsonrpc/client/http_uri_client.go b/rpc/jsonrpc/client/http_uri_client.go index b8bce3cfc09..03ea5861dcc 100644 --- a/rpc/jsonrpc/client/http_uri_client.go +++ b/rpc/jsonrpc/client/http_uri_client.go @@ -11,7 +11,7 @@ import ( ) const ( - // URIClientRequestID in a request ID used by URIClient + // URIClientRequestID in a request ID used by URIClient. URIClientRequestID = types.JSONRPCIntID(-1) ) @@ -52,8 +52,8 @@ func NewURI(remote string) (*URIClient, error) { // Call issues a POST form HTTP request. func (c *URIClient) Call(ctx context.Context, method string, - params map[string]interface{}, result interface{}) (interface{}, error) { - + params map[string]interface{}, result interface{}, +) (interface{}, error) { values, err := argsToURLValues(params) if err != nil { return nil, fmt.Errorf("failed to encode params: %w", err) diff --git a/rpc/jsonrpc/client/ws_client.go b/rpc/jsonrpc/client/ws_client.go index 5decc3849c2..dfe8f1ab474 100644 --- a/rpc/jsonrpc/client/ws_client.go +++ b/rpc/jsonrpc/client/ws_client.go @@ -9,14 +9,13 @@ import ( "sync" "time" - "github.com/gorilla/websocket" - metrics "github.com/rcrowley/go-metrics" - cmtrand "github.com/cometbft/cometbft/internal/rand" "github.com/cometbft/cometbft/internal/service" cmtsync "github.com/cometbft/cometbft/internal/sync" "github.com/cometbft/cometbft/libs/log" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/gorilla/websocket" + metrics "github.com/rcrowley/go-metrics" ) const ( @@ -30,7 +29,7 @@ const ( // the remote server. // // WSClient is safe for concurrent use by multiple goroutines. -type WSClient struct { //nolint: maligned +type WSClient struct { conn *websocket.Conn Address string // IP:PORT or /path/to/socket diff --git a/rpc/jsonrpc/client/ws_client_test.go b/rpc/jsonrpc/client/ws_client_test.go index f08a47c1d84..4c2360f94bb 100644 --- a/rpc/jsonrpc/client/ws_client_test.go +++ b/rpc/jsonrpc/client/ws_client_test.go @@ -9,12 +9,11 @@ import ( "testing" "time" - "github.com/gorilla/websocket" - "github.com/stretchr/testify/require" - cmtsync "github.com/cometbft/cometbft/internal/sync" "github.com/cometbft/cometbft/libs/log" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" ) var wsCallTimeout = 5 * time.Second diff --git a/rpc/jsonrpc/jsonrpc_test.go b/rpc/jsonrpc/jsonrpc_test.go index 163753473e8..507f69690cd 100644 --- a/rpc/jsonrpc/jsonrpc_test.go +++ b/rpc/jsonrpc/jsonrpc_test.go @@ -14,20 +14,18 @@ import ( "testing" "time" - "github.com/go-kit/log/term" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - cmtrand "github.com/cometbft/cometbft/internal/rand" cmtbytes "github.com/cometbft/cometbft/libs/bytes" "github.com/cometbft/cometbft/libs/log" - client "github.com/cometbft/cometbft/rpc/jsonrpc/client" server "github.com/cometbft/cometbft/rpc/jsonrpc/server" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -// Client and Server should work over tcp or unix sockets +// Client and Server should work over tcp or unix sockets. const ( tcpAddr = "tcp://127.0.0.1:47768" @@ -61,7 +59,7 @@ type ResultEchoWithDefault struct { Value int `json:"value"` } -// Define some routes +// Define some routes. var Routes = map[string]*server.RPCFunc{ "echo": server.NewRPCFunc(EchoResult, "arg"), "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"), @@ -118,7 +116,7 @@ var colorFn = func(keyvals ...interface{}) term.FgBgColor { return term.FgBgColor{} } -// launch unix and tcp servers +// launch unix and tcp servers. func setup() { logger := log.NewTMLoggerWithColorFn(log.NewSyncWriter(os.Stdout), colorFn) diff --git a/rpc/jsonrpc/server/http_json_handler.go b/rpc/jsonrpc/server/http_json_handler.go index 8f56076a79b..b4b7d51c027 100644 --- a/rpc/jsonrpc/server/http_json_handler.go +++ b/rpc/jsonrpc/server/http_json_handler.go @@ -17,7 +17,7 @@ import ( // HTTP + JSON handler -// jsonrpc calls grab the given method's function info and runs reflect.Call +// jsonrpc calls grab the given method's function info and runs reflect.Call. func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { b, err := io.ReadAll(r.Body) @@ -218,7 +218,7 @@ func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte) ([]reflect.Value, error) { return nil, fmt.Errorf("unknown type for JSON params: %v. Expected map or array", err) } -// writes a list of available rpc endpoints as an html page +// writes a list of available rpc endpoints as an html page. func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) { noArgNames := []string{} argNames := []string{} @@ -255,6 +255,6 @@ func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[st } buf.WriteString("") w.Header().Set("Content-Type", "text/html") - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) w.Write(buf.Bytes()) //nolint: errcheck } diff --git a/rpc/jsonrpc/server/http_json_handler_test.go b/rpc/jsonrpc/server/http_json_handler_test.go index 9bb7948b5dd..6c9db6eb721 100644 --- a/rpc/jsonrpc/server/http_json_handler_test.go +++ b/rpc/jsonrpc/server/http_json_handler_test.go @@ -9,11 +9,10 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/libs/log" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testMux() *http.ServeMux { diff --git a/rpc/jsonrpc/server/http_server.go b/rpc/jsonrpc/server/http_server.go index ef831451856..32ffb431a89 100644 --- a/rpc/jsonrpc/server/http_server.go +++ b/rpc/jsonrpc/server/http_server.go @@ -10,13 +10,13 @@ import ( "net/http" "os" "runtime/debug" + "strconv" "strings" "time" - "golang.org/x/net/netutil" - "github.com/cometbft/cometbft/libs/log" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "golang.org/x/net/netutil" ) // Config is a RPC server configuration. @@ -148,7 +148,7 @@ func writeRPCResponseHTTP(w http.ResponseWriter, headers []httpHeader, res ...ty for _, header := range headers { w.Header().Set(header.name, header.value) } - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) _, err = w.Write(jsonBytes) return err } @@ -164,7 +164,7 @@ func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler rww := &responseWriterWrapper{-1, w} begin := time.Now() - rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix())) + rww.Header().Set("X-Server-Time", strconv.FormatInt(begin.Unix(), 10)) defer func() { // Handle any panics in the panic handler below. Does not use the logger, since we want @@ -176,7 +176,7 @@ func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler // https://github.com/golang/go/issues/17790#issuecomment-258481416 if e := recover(); e != nil { fmt.Fprintf(os.Stderr, "Panic during RPC panic recovery: %v\n%v\n", e, string(debug.Stack())) - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) } }() @@ -230,7 +230,7 @@ func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler }) } -// Remember the status for logging +// Remember the status for logging. type responseWriterWrapper struct { Status int http.ResponseWriter @@ -241,7 +241,7 @@ func (w *responseWriterWrapper) WriteHeader(status int) { w.ResponseWriter.WriteHeader(status) } -// implements http.Hijacker +// implements http.Hijacker. func (w *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.ResponseWriter.(http.Hijacker).Hijack() } diff --git a/rpc/jsonrpc/server/http_server_test.go b/rpc/jsonrpc/server/http_server_test.go index 56f6dba2bfe..6b274259866 100644 --- a/rpc/jsonrpc/server/http_server_test.go +++ b/rpc/jsonrpc/server/http_server_test.go @@ -13,11 +13,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/libs/log" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type sampleResult struct { diff --git a/rpc/jsonrpc/server/http_uri_handler.go b/rpc/jsonrpc/server/http_uri_handler.go index 150ebf95c49..452ba34a8f0 100644 --- a/rpc/jsonrpc/server/http_uri_handler.go +++ b/rpc/jsonrpc/server/http_uri_handler.go @@ -17,7 +17,7 @@ import ( var reInt = regexp.MustCompile(`^-?[0-9]+$`) -// convert from a function name to the http handler +// convert from a function name to the http handler. func makeHTTPHandler(rpcFunc *RPCFunc, logger log.Logger) func(http.ResponseWriter, *http.Request) { // Always return -1 as there's no ID here. dummyID := types.JSONRPCIntID(-1) // URIClientRequestID @@ -145,7 +145,7 @@ func nonJSONStringToArg(rt reflect.Type, arg string) (reflect.Value, bool, error // NOTE: rt.Kind() isn't a pointer. func _nonJSONStringToArg(rt reflect.Type, arg string) (reflect.Value, bool, error) { - isIntString := reInt.Match([]byte(arg)) + isIntString := reInt.MatchString(arg) isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`) isHexString := strings.HasPrefix(strings.ToLower(arg), "0x") diff --git a/rpc/jsonrpc/server/parse_test.go b/rpc/jsonrpc/server/parse_test.go index 7c6afc9862e..9fc7041edc1 100644 --- a/rpc/jsonrpc/server/parse_test.go +++ b/rpc/jsonrpc/server/parse_test.go @@ -7,10 +7,9 @@ import ( "strconv" "testing" - "github.com/stretchr/testify/assert" - "github.com/cometbft/cometbft/libs/bytes" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/stretchr/testify/assert" ) func TestParseJSONMap(t *testing.T) { @@ -166,7 +165,6 @@ func TestParseJSONRPC(t *testing.T) { assert.Equal(t, tc.name, vals[1].String(), i) } } - } } @@ -208,6 +206,5 @@ func TestParseURI(t *testing.T) { assert.Equal(t, tc.name, vals[1].String(), i) } } - } } diff --git a/rpc/jsonrpc/server/rpc_func.go b/rpc/jsonrpc/server/rpc_func.go index cd7e5273e14..f7e0da98495 100644 --- a/rpc/jsonrpc/server/rpc_func.go +++ b/rpc/jsonrpc/server/rpc_func.go @@ -12,7 +12,7 @@ import ( // RegisterRPCFuncs adds a route for each function in the funcMap, as well as // general jsonrpc and websocket handlers for all functions. "result" is the // interface on which the result objects are registered, and is popualted with -// every RPCResponse +// every RPCResponse. func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, logger log.Logger) { // HTTP endpoints for funcName, rpcFunc := range funcMap { @@ -51,7 +51,7 @@ func Ws() Option { } } -// RPCFunc contains the introspected type information for a function +// RPCFunc contains the introspected type information for a function. type RPCFunc struct { f reflect.Value // underlying rpc function args []reflect.Type // type of each function arg @@ -63,7 +63,7 @@ type RPCFunc struct { } // NewRPCFunc wraps a function for introspection. -// f is the function, args are comma separated argument names +// f is the function, args are comma separated argument names. func NewRPCFunc(f interface{}, args string, options ...Option) *RPCFunc { return newRPCFunc(f, args, options...) } @@ -118,7 +118,7 @@ func newRPCFunc(f interface{}, args string, options ...Option) *RPCFunc { return r } -// return a function's argument types +// return a function's argument types. func funcArgTypes(f interface{}) []reflect.Type { t := reflect.TypeOf(f) n := t.NumIn() @@ -129,7 +129,7 @@ func funcArgTypes(f interface{}) []reflect.Type { return typez } -// return a function's return types +// return a function's return types. func funcReturnTypes(f interface{}) []reflect.Type { t := reflect.TypeOf(f) n := t.NumOut() @@ -142,7 +142,7 @@ func funcReturnTypes(f interface{}) []reflect.Type { //------------------------------------------------------------- -// NOTE: assume returns is result struct and error. If error is not nil, return it +// NOTE: assume returns is result struct and error. If error is not nil, return it. func unreflectResult(returns []reflect.Value) (interface{}, error) { errV := returns[1] if errV.Interface() != nil { diff --git a/rpc/jsonrpc/server/ws_handler.go b/rpc/jsonrpc/server/ws_handler.go index 955fe2692c6..555954ea940 100644 --- a/rpc/jsonrpc/server/ws_handler.go +++ b/rpc/jsonrpc/server/ws_handler.go @@ -10,11 +10,10 @@ import ( "runtime/debug" "time" - "github.com/gorilla/websocket" - "github.com/cometbft/cometbft/internal/service" "github.com/cometbft/cometbft/libs/log" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/gorilla/websocket" ) // WebSocket handler @@ -28,7 +27,7 @@ const ( // WebsocketManager provides a WS handler for incoming connections and passes a // map of functions along with any additional params to new connections. -// NOTE: The websocket path is defined externally, e.g. in node/node.go +// NOTE: The websocket path is defined externally, e.g. in node/node.go. type WebsocketManager struct { websocket.Upgrader @@ -243,7 +242,7 @@ func (wsc *wsConnection) OnStop() { } // GetRemoteAddr returns the remote address of the underlying connection. -// It implements WSRPCConnection +// It implements WSRPCConnection. func (wsc *wsConnection) GetRemoteAddr() string { return wsc.remoteAddr } @@ -264,7 +263,7 @@ func (wsc *wsConnection) WriteRPCResponse(ctx context.Context, resp types.RPCRes // TryWriteRPCResponse attempts to push a response to the writeChan, but does // not block. -// It implements WSRPCConnection. It is Goroutine-safe +// It implements WSRPCConnection. It is Goroutine-safe. func (wsc *wsConnection) TryWriteRPCResponse(resp types.RPCResponse) bool { select { case <-wsc.Quit(): @@ -286,7 +285,7 @@ func (wsc *wsConnection) Context() context.Context { return wsc.ctx } -// Read from the socket and subscribe to or unsubscribe from events +// Read from the socket and subscribe to or unsubscribe from events. func (wsc *wsConnection) readRoutine() { // readRoutine will block until response is written or WS connection is closed writeCtx := context.Background() @@ -398,7 +397,7 @@ func (wsc *wsConnection) readRoutine() { } } -// receives on a write channel and writes out on the socket +// receives on a write channel and writes out on the socket. func (wsc *wsConnection) writeRoutine() { pingTicker := time.NewTicker(wsc.pingPeriod) defer pingTicker.Stop() diff --git a/rpc/jsonrpc/server/ws_handler_test.go b/rpc/jsonrpc/server/ws_handler_test.go index b403151950c..3790e4b69e0 100644 --- a/rpc/jsonrpc/server/ws_handler_test.go +++ b/rpc/jsonrpc/server/ws_handler_test.go @@ -5,11 +5,10 @@ import ( "net/http/httptest" "testing" - "github.com/gorilla/websocket" - "github.com/stretchr/testify/require" - "github.com/cometbft/cometbft/libs/log" types "github.com/cometbft/cometbft/rpc/jsonrpc/types" + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" ) func TestWebsocketManagerHandler(t *testing.T) { diff --git a/rpc/jsonrpc/types/types.go b/rpc/jsonrpc/types/types.go index 08ee2f2bbd5..792d3773ce2 100644 --- a/rpc/jsonrpc/types/types.go +++ b/rpc/jsonrpc/types/types.go @@ -17,13 +17,13 @@ type jsonrpcid interface { isJSONRPCID() } -// JSONRPCStringID a wrapper for JSON-RPC string IDs +// JSONRPCStringID a wrapper for JSON-RPC string IDs. type JSONRPCStringID string func (JSONRPCStringID) isJSONRPCID() {} func (id JSONRPCStringID) String() string { return string(id) } -// JSONRPCIntID a wrapper for JSON-RPC integer IDs +// JSONRPCIntID a wrapper for JSON-RPC integer IDs. type JSONRPCIntID int func (JSONRPCIntID) isJSONRPCID() {} @@ -55,7 +55,7 @@ type RPCRequest struct { Params json.RawMessage `json:"params"` // must be map[string]interface{} or []interface{} } -// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int +// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int. func (req *RPCRequest) UnmarshalJSON(data []byte) error { unsafeReq := struct { JSONRPC string `json:"jsonrpc"` @@ -99,7 +99,7 @@ func (req RPCRequest) String() string { } func MapToRequest(id jsonrpcid, method string, params map[string]interface{}) (RPCRequest, error) { - var paramsMap = make(map[string]json.RawMessage, len(params)) + paramsMap := make(map[string]json.RawMessage, len(params)) for name, value := range params { valueJSON, err := cmtjson.Marshal(value) if err != nil { @@ -117,7 +117,7 @@ func MapToRequest(id jsonrpcid, method string, params map[string]interface{}) (R } func ArrayToRequest(id jsonrpcid, method string, params []interface{}) (RPCRequest, error) { - var paramsMap = make([]json.RawMessage, len(params)) + paramsMap := make([]json.RawMessage, len(params)) for i, value := range params { valueJSON, err := cmtjson.Marshal(value) if err != nil { @@ -158,7 +158,7 @@ type RPCResponse struct { Error *RPCError `json:"error,omitempty"` } -// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int +// UnmarshalJSON custom JSON unmarshalling due to jsonrpcid being string or int. func (resp *RPCResponse) UnmarshalJSON(data []byte) error { unsafeResp := &struct { JSONRPC string `json:"jsonrpc"` @@ -253,9 +253,9 @@ type WSRPCConnection interface { // GetRemoteAddr returns a remote address of the connection. GetRemoteAddr() string // WriteRPCResponse writes the response onto connection (BLOCKING). - WriteRPCResponse(context.Context, RPCResponse) error + WriteRPCResponse(ctx context.Context, res RPCResponse) error // TryWriteRPCResponse tries to write the response onto connection (NON-BLOCKING). - TryWriteRPCResponse(RPCResponse) bool + TryWriteRPCResponse(res RPCResponse) bool // Context returns the connection's context. Context() context.Context } @@ -317,7 +317,7 @@ func (ctx *Context) Context() context.Context { // Determine if its a unix or tcp socket. // If tcp, must specify the port; `0.0.0.0` will return incorrectly as "unix" since there's no port -// TODO: deprecate +// TODO: deprecate. func SocketType(listenAddr string) string { socketType := "unix" if len(strings.Split(listenAddr, ":")) >= 2 { diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index f143e23bcb2..b50d2e13aa9 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -9,11 +9,10 @@ import ( "time" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/internal/test" - "github.com/cometbft/cometbft/libs/log" - cfg "github.com/cometbft/cometbft/config" cmtnet "github.com/cometbft/cometbft/internal/net" + "github.com/cometbft/cometbft/internal/test" + "github.com/cometbft/cometbft/libs/log" nm "github.com/cometbft/cometbft/node" "github.com/cometbft/cometbft/p2p" "github.com/cometbft/cometbft/privval" @@ -55,7 +54,7 @@ func waitForRPC() { } } -// f**ing long, but unique for each test +// f**ing long, but unique for each test. func makePathname() string { // get path p, err := os.Getwd() @@ -97,7 +96,7 @@ func createConfig() *cfg.Config { return c } -// GetConfig returns a config for the test cases as a singleton +// GetConfig returns a config for the test cases as a singleton. func GetConfig(forceCreate ...bool) *cfg.Config { if globalConfig == nil || (len(forceCreate) > 0 && forceCreate[0]) { globalConfig = createConfig() @@ -105,7 +104,7 @@ func GetConfig(forceCreate ...bool) *cfg.Config { return globalConfig } -// StartCometBFT starts a test CometBFT server in a go routine and returns when it is initialized +// StartCometBFT starts a test CometBFT server in a go routine and returns when it is initialized. func StartCometBFT(app abci.Application, opts ...func(*Options)) *nm.Node { nodeOpts := defaultOptions for _, opt := range opts { @@ -137,7 +136,7 @@ func StopCometBFT(node *nm.Node) { os.RemoveAll(node.Config().RootDir) } -// NewCometBFT creates a new CometBFT server and sleeps forever +// NewCometBFT creates a new CometBFT server and sleeps forever. func NewCometBFT(app abci.Application, opts *Options) *nm.Node { // Create & start node config := GetConfig(opts.recreateConfig) diff --git a/scripts/json2wal/main.go b/scripts/json2wal/main.go index e8359ef5ff9..052380a2576 100644 --- a/scripts/json2wal/main.go +++ b/scripts/json2wal/main.go @@ -31,7 +31,7 @@ func main() { } defer f.Close() - walFile, err := os.OpenFile(os.Args[2], os.O_EXCL|os.O_WRONLY|os.O_CREATE, 0666) + walFile, err := os.OpenFile(os.Args[2], os.O_EXCL|os.O_WRONLY|os.O_CREATE, 0o666) if err != nil { panic(fmt.Errorf("failed to open WAL file: %v", err)) } diff --git a/scripts/metricsgen/metricsdiff/metricsdiff.go b/scripts/metricsgen/metricsdiff/metricsdiff.go index 5ed72ff97cc..2070b175cba 100644 --- a/scripts/metricsgen/metricsdiff/metricsdiff.go +++ b/scripts/metricsgen/metricsdiff/metricsdiff.go @@ -64,16 +64,16 @@ func main() { if err != nil { log.Fatalf("Open: %v", err) } - defer fa.Close() fb, err := os.Open(flag.Arg(1)) if err != nil { log.Fatalf("Open: %v", err) } - defer fb.Close() md, err := DiffFromReaders(fa, fb) if err != nil { log.Fatalf("Generating diff: %v", err) } + fa.Close() + fb.Close() fmt.Print(md) } @@ -126,7 +126,7 @@ func toList(l map[string]*dto.MetricFamily) metricsList { for name, family := range l { r[idx] = parsedMetric{ name: name, - labels: labelsToStringList(family.Metric[0].Label), + labels: labelsToStringList(family.GetMetric()[0].GetLabel()), } idx++ } diff --git a/scripts/metricsgen/metricsdiff/metricsdiff_test.go b/scripts/metricsgen/metricsdiff/metricsdiff_test.go index 122eaf67393..6b63ce69f20 100644 --- a/scripts/metricsgen/metricsdiff/metricsdiff_test.go +++ b/scripts/metricsgen/metricsdiff/metricsdiff_test.go @@ -5,9 +5,8 @@ import ( "io" "testing" - "github.com/stretchr/testify/require" - metricsdiff "github.com/cometbft/cometbft/scripts/metricsgen/metricsdiff" + "github.com/stretchr/testify/require" ) func TestDiff(t *testing.T) { diff --git a/scripts/metricsgen/metricsgen.go b/scripts/metricsgen/metricsgen.go index 00482928e3c..82c851eaed1 100644 --- a/scripts/metricsgen/metricsgen.go +++ b/scripts/metricsgen/metricsgen.go @@ -170,7 +170,7 @@ func ParseMetricsDir(dir string, structName string) (TemplateData, error) { var pkgName string var pkg *ast.Package // TODO(thane): Figure out a more readable way of implementing this. - //nolint:revive + for pkgName, pkg = range d { } td := TemplateData{ diff --git a/scripts/metricsgen/metricsgen_test.go b/scripts/metricsgen/metricsgen_test.go index 8a797dca4e8..45447f09921 100644 --- a/scripts/metricsgen/metricsgen_test.go +++ b/scripts/metricsgen/metricsgen_test.go @@ -11,9 +11,8 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/require" - metricsgen "github.com/cometbft/cometbft/scripts/metricsgen" + "github.com/stretchr/testify/require" ) const testDataDir = "./testdata" @@ -244,16 +243,15 @@ func TestParseAliasedMetric(t *testing.T) { td, err := metricsgen.ParseMetricsDir(dir, "Metrics") require.NoError(t, err) - expected := - metricsgen.TemplateData{ - Package: "mypkg", - ParsedMetrics: []metricsgen.ParsedMetricField{ - { - TypeName: "Gauge", - FieldName: "m", - MetricName: "m", - }, + expected := metricsgen.TemplateData{ + Package: "mypkg", + ParsedMetrics: []metricsgen.ParsedMetricField{ + { + TypeName: "Gauge", + FieldName: "m", + MetricName: "m", }, - } + }, + } require.Equal(t, expected, td) } diff --git a/scripts/wal2json/main.go b/scripts/wal2json/main.go index baedd6e1617..3926143b396 100644 --- a/scripts/wal2json/main.go +++ b/scripts/wal2json/main.go @@ -57,6 +57,5 @@ func main() { fmt.Println("Failed to write message", err) os.Exit(1) //nolint:gocritic } - } } diff --git a/test/e2e/app/app.go b/test/e2e/app/app.go index 66c7dd704c1..4b03d3366ff 100644 --- a/test/e2e/app/app.go +++ b/test/e2e/app/app.go @@ -31,7 +31,6 @@ import ( const ( appVersion = 1 voteExtensionKey string = "extensionSum" - voteExtensionMaxLen int64 = 1024 * 1024 * 128 // TODO: should be smaller. voteExtensionMaxVal int64 = 128 prefixReservedKey string = "reservedTxKey_" suffixChainID string = "ChainID" @@ -202,6 +201,7 @@ func (app *Application) CheckTx(_ context.Context, req *abci.CheckTxRequest) (*a key, _, err := parseTx(req.Tx) if err != nil || key == prefixReservedKey { + //nolint:nilerr return &abci.CheckTxResponse{ Code: kvstore.CodeTypeEncodingError, Log: err.Error(), @@ -556,7 +556,7 @@ func (app *Application) ExtendVote(_ context.Context, req *abci.ExtendVoteReques extLen = binary.PutVarint(ext, num.Int64()) } - app.logger.Info("generated vote extension", "height", appHeight, "vote_extension", fmt.Sprintf("%x", ext[:4]), "len", extLen) + app.logger.Info("generated vote extension", "height", appHeight, "vote_extension", hex.EncodeToString(ext[:4]), "len", extLen) return &abci.ExtendVoteResponse{ VoteExtension: ext[:extLen], }, nil @@ -580,7 +580,7 @@ func (app *Application) VerifyVoteExtension(_ context.Context, req *abci.VerifyV num, err := parseVoteExtension(app.cfg, req.VoteExtension) if err != nil { - app.logger.Error("failed to parse vote extension", "vote_extension", fmt.Sprintf("%x", req.VoteExtension[:4]), "err", err) + app.logger.Error("failed to parse vote extension", "vote_extension", hex.EncodeToString(req.VoteExtension[:4]), "err", err) return &abci.VerifyVoteExtensionResponse{ Status: abci.VERIFY_VOTE_EXTENSION_STATUS_REJECT, }, nil @@ -590,7 +590,7 @@ func (app *Application) VerifyVoteExtension(_ context.Context, req *abci.VerifyV time.Sleep(app.cfg.VoteExtensionDelay) } - app.logger.Info("verified vote extension value", "height", req.Height, "vote_extension", fmt.Sprintf("%x", req.VoteExtension[:4]), "num", num) + app.logger.Info("verified vote extension value", "height", req.Height, "vote_extension", hex.EncodeToString(req.VoteExtension[:4]), "num", num) return &abci.VerifyVoteExtensionResponse{ Status: abci.VERIFY_VOTE_EXTENSION_STATUS_ACCEPT, }, nil @@ -662,14 +662,13 @@ func (app *Application) storeValidator(valUpdate *abci.ValidatorUpdate) error { // validatorUpdates generates a validator set update. func (app *Application) validatorUpdates(height uint64) (abci.ValidatorUpdates, error) { - updates := app.cfg.ValidatorUpdates[fmt.Sprintf("%v", height)] + updates := app.cfg.ValidatorUpdates[strconv.FormatUint(height, 10)] if len(updates) == 0 { return nil, nil } valUpdates := abci.ValidatorUpdates{} for keyString, power := range updates { - keyBytes, err := base64.StdEncoding.DecodeString(keyString) if err != nil { return nil, fmt.Errorf("invalid base64 pubkey value %q: %w", keyString, err) @@ -768,7 +767,7 @@ func (app *Application) verifyAndSum( return 0, fmt.Errorf("error when marshaling signed bytes: %w", err) } - //... and verify + // ... and verify valAddr := crypto.Address(vote.Validator.Address).String() pubKeyHex := app.state.Get(prefixReservedKey + valAddr) if len(pubKeyHex) == 0 { @@ -813,7 +812,7 @@ func (app *Application) verifyAndSum( return sum, nil } -// verifyExtensionTx parses and verifies the payload of a vote extension-generated tx +// verifyExtensionTx parses and verifies the payload of a vote extension-generated tx. func (app *Application) verifyExtensionTx(height int64, payload string) error { parts := strings.Split(payload, "|") if len(parts) != 2 { diff --git a/test/e2e/app/snapshots.go b/test/e2e/app/snapshots.go index 79a223a4694..a5886cf4f53 100644 --- a/test/e2e/app/snapshots.go +++ b/test/e2e/app/snapshots.go @@ -15,7 +15,7 @@ import ( const ( snapshotChunkSize = 1e6 - // Keep only the most recent 10 snapshots. Older snapshots are pruned + // Keep only the most recent 10 snapshots. Older snapshots are pruned. maxSnapshotCount = 10 ) @@ -106,7 +106,7 @@ func (s *SnapshotStore) Create(state *State) (abci.Snapshot, error) { return snapshot, nil } -// Prune removes old snapshots ensuring only the most recent n snapshots remain +// Prune removes old snapshots ensuring only the most recent n snapshots remain. func (s *SnapshotStore) Prune(n int) error { s.Lock() defer s.Unlock() diff --git a/test/e2e/app/state.go b/test/e2e/app/state.go index 732bfbff482..aae021c1535 100644 --- a/test/e2e/app/state.go +++ b/test/e2e/app/state.go @@ -20,9 +20,9 @@ const ( // Intermediate type used exclusively in serialization/deserialization of // State, such that State need not expose any of its internal values publicly. type serializedState struct { - Height uint64 - Values map[string]string - Hash []byte + Height uint64 `json:"height"` + Values map[string]string `json:"values"` + Hash []byte `json:"hash"` } // State is the application state. @@ -182,7 +182,7 @@ func (s *State) Query(key string) (string, uint64) { return value, height } -// Finalize is called after applying a block, updating the height and returning the new app_hash +// Finalize is called after applying a block, updating the height and returning the new app_hash. func (s *State) Finalize() []byte { s.Lock() defer s.Unlock() diff --git a/test/e2e/generator/generate.go b/test/e2e/generator/generate.go index 7fbfc9c6e67..f47d21122d8 100644 --- a/test/e2e/generator/generate.go +++ b/test/e2e/generator/generate.go @@ -10,11 +10,10 @@ import ( "time" "github.com/Masterminds/semver/v3" - "github.com/go-git/go-git/v5" - "github.com/go-git/go-git/v5/plumbing/object" - e2e "github.com/cometbft/cometbft/test/e2e/pkg" "github.com/cometbft/cometbft/version" + "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing/object" ) var ( @@ -197,7 +196,7 @@ func generateTestnet(r *rand.Rand, opt map[string]interface{}, upgradeVersion st if startAt == 0 { (*manifest.Validators)[name] = int64(30 + r.Intn(71)) } else { - manifest.ValidatorUpdates[fmt.Sprint(startAt+5)] = map[string]int64{ + manifest.ValidatorUpdates[strconv.FormatInt(startAt+5, 10)] = map[string]int64{ name: int64(30 + r.Intn(71)), } } @@ -367,11 +366,12 @@ func parseWeightedVersions(s string) (weightedChoice, string, error) { for _, wv := range wvs { parts := strings.Split(strings.TrimSpace(wv), ":") var ver string - if len(parts) == 2 { + switch len(parts) { + case 2: ver = strings.TrimSpace(strings.Join([]string{"cometbft/e2e-node", parts[0]}, ":")) - } else if len(parts) == 3 { + case 3: ver = strings.TrimSpace(strings.Join([]string{parts[0], parts[1]}, ":")) - } else { + default: return nil, "", fmt.Errorf("unexpected weight:version combination: %s", wv) } diff --git a/test/e2e/generator/main.go b/test/e2e/generator/main.go index f4f8140c0c1..29680464365 100644 --- a/test/e2e/generator/main.go +++ b/test/e2e/generator/main.go @@ -7,9 +7,8 @@ import ( "os" "path/filepath" - "github.com/spf13/cobra" - "github.com/cometbft/cometbft/libs/log" + "github.com/spf13/cobra" ) const ( diff --git a/test/e2e/generator/random.go b/test/e2e/generator/random.go index 4312eb30d70..b1c0170f092 100644 --- a/test/e2e/generator/random.go +++ b/test/e2e/generator/random.go @@ -20,7 +20,7 @@ import ( // {"foo": 2, "bar": 6} // {"foo": 3, "bar": 4} // {"foo": 3, "bar": 5} -// {"foo": 3, "bar": 6} +// {"foo": 3, "bar": 6}. func combinations(items map[string][]interface{}) []map[string]interface{} { keys := []string{} for key := range items { diff --git a/test/e2e/node/config.go b/test/e2e/node/config.go index db5b1899b75..0ca24719bf8 100644 --- a/test/e2e/node/config.go +++ b/test/e2e/node/config.go @@ -5,7 +5,6 @@ import ( "time" "github.com/BurntSushi/toml" - "github.com/cometbft/cometbft/test/e2e/app" cmterrors "github.com/cometbft/cometbft/types/errors" ) @@ -37,7 +36,7 @@ type Config struct { ABCIRequestsLoggingEnabled bool `toml:"abci_requests_logging_enabled"` } -// App extracts out the application specific configuration parameters +// App extracts out the application specific configuration parameters. func (cfg *Config) App() *app.Config { return &app.Config{ Dir: cfg.Dir, diff --git a/test/e2e/node/main.go b/test/e2e/node/main.go index ada0ffa13a3..65d7538fe0d 100644 --- a/test/e2e/node/main.go +++ b/test/e2e/node/main.go @@ -7,11 +7,10 @@ import ( "net/http" "os" "path/filepath" + "strconv" "strings" "time" - "github.com/spf13/viper" - "github.com/cometbft/cometbft/abci/server" "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/crypto/ed25519" @@ -29,6 +28,7 @@ import ( rpcserver "github.com/cometbft/cometbft/rpc/jsonrpc/server" "github.com/cometbft/cometbft/test/e2e/app" e2e "github.com/cometbft/cometbft/test/e2e/pkg" + "github.com/spf13/viper" ) var logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) @@ -277,7 +277,7 @@ func setupNode() (*config.Config, log.Logger, *p2p.NodeKey, error) { } // rpcEndpoints takes a list of persistent peers and splits them into a list of rpc endpoints -// using 26657 as the port number +// using 26657 as the port number. func rpcEndpoints(peers string) []string { arr := strings.Split(peers, ",") endpoints := make([]string, len(arr)) @@ -286,7 +286,7 @@ func rpcEndpoints(peers string) []string { hostName := strings.Split(urlString, ":26656")[0] // use RPC port instead port := 26657 - rpcEndpoint := "http://" + hostName + ":" + fmt.Sprint(port) + rpcEndpoint := "http://" + hostName + ":" + strconv.Itoa(port) endpoints[i] = rpcEndpoint } return endpoints diff --git a/test/e2e/pkg/grammar/checker.go b/test/e2e/pkg/grammar/checker.go index 996c4b15b6d..b0c3b49ef61 100644 --- a/test/e2e/pkg/grammar/checker.go +++ b/test/e2e/pkg/grammar/checker.go @@ -5,9 +5,8 @@ import ( "os" "strings" - "github.com/cometbft/cometbft/libs/log" - abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" clean_start_lexer "github.com/cometbft/cometbft/test/e2e/pkg/grammar/clean-start/grammar-auto/lexer" clean_start_parser "github.com/cometbft/cometbft/test/e2e/pkg/grammar/clean-start/grammar-auto/parser" recovery_lexer "github.com/cometbft/cometbft/test/e2e/pkg/grammar/recovery/grammar-auto/lexer" diff --git a/test/e2e/pkg/infra/digitalocean/digitalocean.go b/test/e2e/pkg/infra/digitalocean/digitalocean.go index 5893985bb31..5d393afdd8a 100644 --- a/test/e2e/pkg/infra/digitalocean/digitalocean.go +++ b/test/e2e/pkg/infra/digitalocean/digitalocean.go @@ -171,7 +171,7 @@ func ansibleAddShellTasks(playbook, name string, shells ...string) string { } // file as bytes to be written out to disk. -// ansibleStartBytes generates an Ansible playbook to start the network +// ansibleStartBytes generates an Ansible playbook to start the network. func ansibleSystemdBytes(starting bool) string { return ansibleAddSystemdTask(basePlaybook, starting) } diff --git a/test/e2e/pkg/infra/docker/docker.go b/test/e2e/pkg/infra/docker/docker.go index a1685054a3e..381c545cc9a 100644 --- a/test/e2e/pkg/infra/docker/docker.go +++ b/test/e2e/pkg/infra/docker/docker.go @@ -69,7 +69,7 @@ func (p Provider) CheckUpgraded(ctx context.Context, node *e2e.Node) (string, bo name := node.Name upgraded := false if len(out) == 0 { - name = name + "_u" + name += "_u" upgraded = true } return name, upgraded, nil diff --git a/test/e2e/pkg/infra/provider.go b/test/e2e/pkg/infra/provider.go index 9151a09bc77..1c01bcdef29 100644 --- a/test/e2e/pkg/infra/provider.go +++ b/test/e2e/pkg/infra/provider.go @@ -17,26 +17,26 @@ type Provider interface { // Starts the nodes passed as parameter. A nodes MUST NOT // be started twice before calling StopTestnet // If no nodes are passed, start the whole network - StartNodes(context.Context, ...*e2e.Node) error + StartNodes(ctx context.Context, nodes ...*e2e.Node) error // Set emulated latencies from a node to other nodes. - SetLatency(context.Context, *e2e.Node) error + SetLatency(ctx context.Context, node *e2e.Node) error // Stops the whole network - StopTestnet(context.Context) error + StopTestnet(ctx context.Context) error // Disconnects the node from the network - Disconnect(context.Context, string, string) error + Disconnect(ctx context.Context, name string, ip string) error // Reconnects the node to the network. // This should only be called after Disconnect - Reconnect(context.Context, string, string) error + Reconnect(ctx context.Context, name string, ip string) error - // Returns the the provider's infrastructure data + // Returns the provider's infrastructure data GetInfrastructureData() *e2e.InfrastructureData // Checks whether the node has been upgraded in this run - CheckUpgraded(context.Context, *e2e.Node) (string, bool, error) + CheckUpgraded(ctx context.Context, node *e2e.Node) (string, bool, error) } type ProviderData struct { diff --git a/test/e2e/pkg/infrastructure.go b/test/e2e/pkg/infrastructure.go index e91a5691ed0..0328fbea760 100644 --- a/test/e2e/pkg/infrastructure.go +++ b/test/e2e/pkg/infrastructure.go @@ -18,7 +18,7 @@ const ( // InfrastructureData contains the relevant information for a set of existing // infrastructure that is to be used for running a testnet. type InfrastructureData struct { - Path string + Path string `json:"path"` // Provider is the name of infrastructure provider backing the testnet. // For example, 'docker' if it is running locally in a docker network or @@ -82,7 +82,6 @@ func NewDockerInfrastructureData(m Manifest) (InfrastructureData, error) { GRPCPort: portGen.Next(), PrivilegedGRPCPort: portGen.Next(), } - } return ifd, nil } diff --git a/test/e2e/pkg/testnet.go b/test/e2e/pkg/testnet.go index 62f64c9e79c..08b2f122c42 100644 --- a/test/e2e/pkg/testnet.go +++ b/test/e2e/pkg/testnet.go @@ -3,6 +3,7 @@ package e2e import ( "bytes" "context" + _ "embed" "encoding/csv" "errors" "fmt" @@ -23,8 +24,6 @@ import ( rpchttp "github.com/cometbft/cometbft/rpc/client/http" grpcclient "github.com/cometbft/cometbft/rpc/grpc/client" grpcprivileged "github.com/cometbft/cometbft/rpc/grpc/client/privileged" - - _ "embed" ) const ( @@ -148,7 +147,7 @@ func LoadTestnet(file string, ifd InfrastructureData) (*Testnet, error) { return NewTestnetFromManifest(manifest, file, ifd) } -// NewTestnetFromManifest creates and validates a testnet from a manifest +// NewTestnetFromManifest creates and validates a testnet from a manifest. func NewTestnetFromManifest(manifest Manifest, file string, ifd InfrastructureData) (*Testnet, error) { dir := strings.TrimSuffix(file, filepath.Ext(file)) @@ -389,7 +388,7 @@ func (t Testnet) validateZones(nodes []*Node) error { } // Get list of zone ids in matrix. - zones := make([]ZoneID, len(zoneMatrix)) + zones := make([]ZoneID, 0, len(zoneMatrix)) for zone := range zoneMatrix { zones = append(zones, zone) } @@ -609,6 +608,7 @@ func (n Node) AddressRPC() string { // Client returns an RPC client for the node. func (n Node) Client() (*rpchttp.HTTP, error) { + //nolint:nosprintfhostport return rpchttp.New(fmt.Sprintf("http://%s:%v/v1", n.ExternalIP, n.RPCProxyPort)) } @@ -630,7 +630,7 @@ func (n Node) GRPCPrivilegedClient(ctx context.Context) (grpcprivileged.Client, ) } -// Stateless returns true if the node is either a seed node or a light node +// Stateless returns true if the node is either a seed node or a light node. func (n Node) Stateless() bool { return n.Mode == ModeLight || n.Mode == ModeSeed } diff --git a/test/e2e/runner/benchmark.go b/test/e2e/runner/benchmark.go index bd671fc4f58..05c577d94f7 100644 --- a/test/e2e/runner/benchmark.go +++ b/test/e2e/runner/benchmark.go @@ -20,7 +20,7 @@ import ( // 4. Min block interval (fastest block) // // Metrics are based of the `benchmarkLength`, the amount of consecutive blocks -// sampled from in the testnet +// sampled from in the testnet. func Benchmark(ctx context.Context, testnet *e2e.Testnet, benchmarkLength int64) error { block, _, err := waitForHeight(ctx, testnet, 0) if err != nil { @@ -97,7 +97,6 @@ func (t *testnetStats) OutputJSON(net *e2e.Testnet) string { "txns": t.numtxns, "dur": t.totalTime.Seconds(), }) - if err != nil { return "" } diff --git a/test/e2e/runner/cleanup.go b/test/e2e/runner/cleanup.go index 852612312be..3e80ae13d41 100644 --- a/test/e2e/runner/cleanup.go +++ b/test/e2e/runner/cleanup.go @@ -50,7 +50,7 @@ func cleanupDocker() error { return nil } -// cleanupDir cleans up a testnet directory +// cleanupDir cleans up a testnet directory. func cleanupDir(dir string) error { if dir == "" { return errors.New("no directory set") diff --git a/test/e2e/runner/evidence.go b/test/e2e/runner/evidence.go index 68055d2ca1b..322442e1725 100644 --- a/test/e2e/runner/evidence.go +++ b/test/e2e/runner/evidence.go @@ -21,7 +21,7 @@ import ( "github.com/cometbft/cometbft/version" ) -// 1 in 4 evidence is light client evidence, the rest is duplicate vote evidence +// 1 in 4 evidence is light client evidence, the rest is duplicate vote evidence. const lightClientEvidenceRatio = 4 // InjectEvidence takes a running testnet and generates an amount of valid/invalid @@ -214,7 +214,7 @@ func generateLightClientAttackEvidence( } // generateDuplicateVoteEvidence picks a random validator from the val set and -// returns duplicate vote evidence against the validator +// returns duplicate vote evidence against the validator. func generateDuplicateVoteEvidence( privVals []types.MockPV, height int64, @@ -243,7 +243,7 @@ func generateDuplicateVoteEvidence( } // getRandomValidatorIndex picks a random validator from a slice of mock PrivVals that's -// also part of the validator set, returning the PrivVal and its index in the validator set +// also part of the validator set, returning the PrivVal and its index in the validator set. func getRandomValidatorIndex(privVals []types.MockPV, vals *types.ValidatorSet) (types.MockPV, int32, error) { for _, idx := range rand.Perm(len(privVals)) { pv := privVals[idx] diff --git a/test/e2e/runner/load.go b/test/e2e/runner/load.go index 2dd630f2e7d..ae58dcbf105 100644 --- a/test/e2e/runner/load.go +++ b/test/e2e/runner/load.go @@ -7,13 +7,12 @@ import ( "sync" "time" - "github.com/google/uuid" - "github.com/cometbft/cometbft/libs/log" rpchttp "github.com/cometbft/cometbft/rpc/client/http" e2e "github.com/cometbft/cometbft/test/e2e/pkg" "github.com/cometbft/cometbft/test/loadtime/payload" "github.com/cometbft/cometbft/types" + "github.com/google/uuid" ) const workerPoolSize = 16 @@ -65,7 +64,7 @@ func Load(ctx context.Context, testnet *e2e.Testnet) error { } } -// loadGenerate generates jobs until the context is canceled +// loadGenerate generates jobs until the context is canceled. func loadGenerate(ctx context.Context, txCh chan<- types.Tx, testnet *e2e.Testnet, id []byte) { t := time.NewTimer(0) defer t.Stop() diff --git a/test/e2e/runner/main.go b/test/e2e/runner/main.go index 51a57a8b39a..eb33460b500 100644 --- a/test/e2e/runner/main.go +++ b/test/e2e/runner/main.go @@ -8,13 +8,12 @@ import ( "os" "strconv" - "github.com/spf13/cobra" - "github.com/cometbft/cometbft/libs/log" e2e "github.com/cometbft/cometbft/test/e2e/pkg" "github.com/cometbft/cometbft/test/e2e/pkg/infra" "github.com/cometbft/cometbft/test/e2e/pkg/infra/digitalocean" "github.com/cometbft/cometbft/test/e2e/pkg/infra/docker" + "github.com/spf13/cobra" ) const randomSeed = 2308084734268 diff --git a/test/e2e/runner/rpc.go b/test/e2e/runner/rpc.go index f6f17384230..b1adce51329 100644 --- a/test/e2e/runner/rpc.go +++ b/test/e2e/runner/rpc.go @@ -72,7 +72,6 @@ func waitForHeight(ctx context.Context, testnet *e2e.Testnet, height int64) (*ty } timer.Reset(1 * time.Second) } - } } diff --git a/test/e2e/runner/setup.go b/test/e2e/runner/setup.go index 9eec9fe21bb..1e38673afc5 100644 --- a/test/e2e/runner/setup.go +++ b/test/e2e/runner/setup.go @@ -10,11 +10,11 @@ import ( "path/filepath" "regexp" "sort" + "strconv" "strings" "time" "github.com/BurntSushi/toml" - "github.com/cometbft/cometbft/config" "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/libs/log" @@ -336,7 +336,7 @@ func MakeAppConfig(node *e2e.Node) ([]byte, error) { for node, power := range validators { updateVals[base64.StdEncoding.EncodeToString(node.PrivvalKey.PubKey().Bytes())] = power } - validatorUpdates[fmt.Sprintf("%v", height)] = updateVals + validatorUpdates[strconv.FormatInt(height, 10)] = updateVals } cfg["validator_update"] = validatorUpdates } diff --git a/test/e2e/runner/test.go b/test/e2e/runner/test.go index a42e50d2581..cc72c982daf 100644 --- a/test/e2e/runner/test.go +++ b/test/e2e/runner/test.go @@ -8,7 +8,7 @@ import ( "github.com/cometbft/cometbft/test/e2e/pkg/exec" ) -// Test runs test cases under tests/ +// Test runs test cases under tests. func Test(testnet *e2e.Testnet, ifd *e2e.InfrastructureData) error { logger.Info("Running tests in ./tests/...") diff --git a/test/loadtime/cmd/load/main.go b/test/loadtime/cmd/load/main.go index d6bb798bc1d..fd8a3d9c553 100644 --- a/test/loadtime/cmd/load/main.go +++ b/test/loadtime/cmd/load/main.go @@ -3,10 +3,9 @@ package main import ( "fmt" + "github.com/cometbft/cometbft/test/loadtime/payload" "github.com/google/uuid" "github.com/informalsystems/tm-load-test/pkg/loadtest" - - "github.com/cometbft/cometbft/test/loadtime/payload" ) // Ensure all of the interfaces are correctly satisfied. diff --git a/test/loadtime/cmd/report/main.go b/test/loadtime/cmd/report/main.go index 81f003cf9f8..429ba5da2f0 100644 --- a/test/loadtime/cmd/report/main.go +++ b/test/loadtime/cmd/report/main.go @@ -10,7 +10,6 @@ import ( "strings" dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/internal/store" "github.com/cometbft/cometbft/test/loadtime/report" ) diff --git a/test/loadtime/payload/payload.go b/test/loadtime/payload/payload.go index 778729f8b9d..150456f9761 100644 --- a/test/loadtime/payload/payload.go +++ b/test/loadtime/payload/payload.go @@ -11,32 +11,34 @@ import ( timestamppb "google.golang.org/protobuf/types/known/timestamppb" ) -const keyPrefix = "a=" -const maxPayloadSize = 4 * 1024 * 1024 +const ( + keyPrefix = "a=" + maxPayloadSize = 4 * 1024 * 1024 +) // NewBytes generates a new payload and returns the encoded representation of // the payload as a slice of bytes. NewBytes uses the fields on the Options // to create the payload. func NewBytes(p *Payload) ([]byte, error) { p.Padding = make([]byte, 1) - if p.Time == nil { + if p.GetTime() == nil { p.Time = timestamppb.Now() } us, err := CalculateUnpaddedSize(p) if err != nil { return nil, err } - if p.Size > maxPayloadSize { - return nil, fmt.Errorf("configured size %d is too large (>%d)", p.Size, maxPayloadSize) + if p.GetSize() > maxPayloadSize { + return nil, fmt.Errorf("configured size %d is too large (>%d)", p.GetSize(), maxPayloadSize) } - pSize := int(p.Size) // #nosec -- The "if" above makes this cast safe + pSize := int(p.GetSize()) // #nosec -- The "if" above makes this cast safe if pSize < us { return nil, fmt.Errorf("configured size %d not large enough to fit unpadded transaction of size %d", pSize, us) } // We halve the padding size because we transform the TX to hex p.Padding = make([]byte, (pSize-us)/2) - _, err = rand.Read(p.Padding) + _, err = rand.Read(p.GetPadding()) if err != nil { return nil, err } @@ -89,8 +91,8 @@ func MaxUnpaddedSize() (int, error) { // purpose of determining how much padding to add to add to reach the target size. // CalculateUnpaddedSize returns an error if the payload Padding field is longer than 1. func CalculateUnpaddedSize(p *Payload) (int, error) { - if len(p.Padding) != 1 { - return 0, fmt.Errorf("expected length of padding to be 1, received %d", len(p.Padding)) + if len(p.GetPadding()) != 1 { + return 0, fmt.Errorf("expected length of padding to be 1, received %d", len(p.GetPadding())) } b, err := proto.Marshal(p) if err != nil { diff --git a/test/loadtime/payload/payload_test.go b/test/loadtime/payload/payload_test.go index 62ea3919f79..8c79dd6588d 100644 --- a/test/loadtime/payload/payload_test.go +++ b/test/loadtime/payload/payload_test.go @@ -4,9 +4,8 @@ import ( "bytes" "testing" - "github.com/google/uuid" - "github.com/cometbft/cometbft/test/loadtime/payload" + "github.com/google/uuid" ) const payloadSizeTarget = 1024 // 1kb @@ -43,16 +42,16 @@ func TestRoundTrip(t *testing.T) { if err != nil { t.Fatalf("reading payload %s", err) } - if p.Size != payloadSizeTarget { - t.Fatalf("payload size value %d does not match expected %d", p.Size, payloadSizeTarget) + if p.GetSize() != payloadSizeTarget { + t.Fatalf("payload size value %d does not match expected %d", p.GetSize(), payloadSizeTarget) } - if p.Connections != testConns { - t.Fatalf("payload connections value %d does not match expected %d", p.Connections, testConns) + if p.GetConnections() != testConns { + t.Fatalf("payload connections value %d does not match expected %d", p.GetConnections(), testConns) } - if p.Rate != testRate { - t.Fatalf("payload rate value %d does not match expected %d", p.Rate, testRate) + if p.GetRate() != testRate { + t.Fatalf("payload rate value %d does not match expected %d", p.GetRate(), testRate) } - if !bytes.Equal(p.Id, testID[:]) { - t.Fatalf("payload ID value %d does not match expected %d", p.Id, testID) + if !bytes.Equal(p.GetId(), testID[:]) { + t.Fatalf("payload ID value %d does not match expected %d", p.GetId(), testID) } } diff --git a/test/loadtime/report/report.go b/test/loadtime/report/report.go index 4c40b96ab5d..8171753ff74 100644 --- a/test/loadtime/report/report.go +++ b/test/loadtime/report/report.go @@ -6,11 +6,10 @@ import ( "sync" "time" - "github.com/gofrs/uuid" - "gonum.org/v1/gonum/stat" - "github.com/cometbft/cometbft/test/loadtime/payload" "github.com/cometbft/cometbft/types" + "github.com/gofrs/uuid" + "gonum.org/v1/gonum/stat" ) // BlockStore defines the set of methods needed by the report generator from @@ -20,7 +19,7 @@ import ( type BlockStore interface { Height() int64 Base() int64 - LoadBlock(int64) (*types.Block, *types.BlockMeta) + LoadBlock(height int64) (*types.Block, *types.BlockMeta) } // DataPoint contains the set of data collected for each transaction. @@ -166,16 +165,16 @@ func GenerateFromBlockStore(s BlockStore) (*Reports, error) { continue } - l := b.bt.Sub(p.Time.AsTime()) - idb := (*[16]byte)(p.Id) + l := b.bt.Sub(p.GetTime().AsTime()) + idb := (*[16]byte)(p.GetId()) pdc <- payloadData{ l: l, bt: b.bt, hash: b.tx.Hash(), id: uuid.UUID(*idb), - connections: p.Connections, - rate: p.Rate, - size: p.Size, + connections: p.GetConnections(), + rate: p.GetRate(), + size: p.GetSize(), } } }() diff --git a/types/block.go b/types/block.go index 08e5dc9a8a9..19710819fe4 100644 --- a/types/block.go +++ b/types/block.go @@ -7,9 +7,6 @@ import ( "strings" "time" - "github.com/cosmos/gogoproto/proto" - gogotypes "github.com/cosmos/gogoproto/types" - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" cmtversion "github.com/cometbft/cometbft/api/cometbft/version/v1" "github.com/cometbft/cometbft/crypto" @@ -20,12 +17,14 @@ import ( cmtbytes "github.com/cometbft/cometbft/libs/bytes" cmtmath "github.com/cometbft/cometbft/libs/math" "github.com/cometbft/cometbft/version" + "github.com/cosmos/gogoproto/proto" + gogotypes "github.com/cosmos/gogoproto/types" ) const ( // MaxHeaderBytes is a maximum header size. // NOTE: Because app hash can be of arbitrary size, the header is therefore not - // capped in size and thus this number should be seen as a soft max + // capped in size and thus this number should be seen as a soft max. MaxHeaderBytes int64 = 626 // MaxOverheadForBlock - maximum overhead to encode a block (up to @@ -35,7 +34,7 @@ const ( // Uvarint length of MaxBlockSizeBytes: 4 bytes // 2 fields (2 embedded): 2 bytes // Uvarint length of Data.Txs: 4 bytes - // Data.Txs field: 1 byte + // Data.Txs field: 1 byte. MaxOverheadForBlock int64 = 11 ) @@ -69,7 +68,7 @@ func (b *Block) ValidateBasic() error { return errors.New("nil LastCommit") } if err := b.LastCommit.ValidateBasic(); err != nil { - return fmt.Errorf("wrong LastCommit: %v", err) + return fmt.Errorf("wrong LastCommit: %w", err) } if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) { @@ -91,7 +90,7 @@ func (b *Block) ValidateBasic() error { // NOTE: b.Evidence.Evidence may be nil, but we're just looping. for i, ev := range b.Evidence.Evidence { if err := ev.ValidateBasic(); err != nil { - return fmt.Errorf("invalid evidence (#%d): %v", i, err) + return fmt.Errorf("invalid evidence (#%d): %w", i, err) } } @@ -105,7 +104,7 @@ func (b *Block) ValidateBasic() error { return nil } -// fillHeader fills in any remaining header fields that are a function of the block data +// fillHeader fills in any remaining header fields that are a function of the block data. func (b *Block) fillHeader() { if b.LastCommitHash == nil { b.LastCommitHash = b.LastCommit.Hash() @@ -190,7 +189,7 @@ func (b *Block) String() string { // Data // Evidence // LastCommit -// Hash +// Hash. func (b *Block) StringIndented(indent string) string { if b == nil { return "nil-Block" @@ -216,7 +215,7 @@ func (b *Block) StringShort() string { return fmt.Sprintf("Block#%X", b.Hash()) } -// ToProto converts Block to protobuf +// ToProto converts Block to protobuf. func (b *Block) ToProto() (*cmtproto.Block, error) { if b == nil { return nil, errors.New("nil Block") @@ -393,15 +392,15 @@ func (h Header) ValidateBasic() error { } if err := ValidateHash(h.LastCommitHash); err != nil { - return fmt.Errorf("wrong LastCommitHash: %v", err) + return fmt.Errorf("wrong LastCommitHash: %w", err) } if err := ValidateHash(h.DataHash); err != nil { - return fmt.Errorf("wrong DataHash: %v", err) + return fmt.Errorf("wrong DataHash: %w", err) } if err := ValidateHash(h.EvidenceHash); err != nil { - return fmt.Errorf("wrong EvidenceHash: %v", err) + return fmt.Errorf("wrong EvidenceHash: %w", err) } if len(h.ProposerAddress) != crypto.AddressSize { @@ -414,17 +413,17 @@ func (h Header) ValidateBasic() error { // Basic validation of hashes related to application data. // Will validate fully against state in state#ValidateBlock. if err := ValidateHash(h.ValidatorsHash); err != nil { - return fmt.Errorf("wrong ValidatorsHash: %v", err) + return fmt.Errorf("wrong ValidatorsHash: %w", err) } if err := ValidateHash(h.NextValidatorsHash); err != nil { - return fmt.Errorf("wrong NextValidatorsHash: %v", err) + return fmt.Errorf("wrong NextValidatorsHash: %w", err) } if err := ValidateHash(h.ConsensusHash); err != nil { - return fmt.Errorf("wrong ConsensusHash: %v", err) + return fmt.Errorf("wrong ConsensusHash: %w", err) } // NOTE: AppHash is arbitrary length if err := ValidateHash(h.LastResultsHash); err != nil { - return fmt.Errorf("wrong LastResultsHash: %v", err) + return fmt.Errorf("wrong LastResultsHash: %w", err) } return nil @@ -512,7 +511,7 @@ func (h *Header) StringIndented(indent string) string { ) } -// ToProto converts Header to protobuf +// ToProto converts Header to protobuf. func (h *Header) ToProto() *cmtproto.Header { if h == nil { return nil @@ -587,7 +586,7 @@ const ( // Max size of commit without any commitSigs -> 82 for BlockID, 8 for Height, 4 for Round. MaxCommitOverheadBytes int64 = 94 // Commit sig size is made up of 64 bytes for the signature, 20 bytes for the address, - // 1 byte for the flag and 14 bytes for the timestamp + // 1 byte for the flag and 14 bytes for the timestamp. MaxCommitSigBytes int64 = 109 ) @@ -618,7 +617,7 @@ func NewCommitSigAbsent() CommitSig { // 1. first 6 bytes of signature // 2. first 6 bytes of validator address // 3. block ID flag -// 4. timestamp +// 4. timestamp. func (cs CommitSig) String() string { return fmt.Sprintf("CommitSig{%X by %X on %v @ %s}", cmtbytes.Fingerprint(cs.Signature), @@ -684,7 +683,7 @@ func (cs CommitSig) ValidateBasic() error { return nil } -// ToProto converts CommitSig to protobuf +// ToProto converts CommitSig to protobuf. func (cs *CommitSig) ToProto() *cmtproto.CommitSig { if cs == nil { return nil @@ -729,7 +728,7 @@ func NewExtendedCommitSigAbsent() ExtendedCommitSig { // // 1. commit sig // 2. first 6 bytes of vote extension -// 3. first 6 bytes of vote extension signature +// 3. first 6 bytes of vote extension signature. func (ecs ExtendedCommitSig) String() string { return fmt.Sprintf("ExtendedCommitSig{%s with %X %X}", ecs.CommitSig, @@ -876,7 +875,7 @@ func (commit *Commit) GetVote(valIdx int32) *Vote { // // Panics if valIdx >= commit.Size(). // -// See VoteSignBytes +// See VoteSignBytes. func (commit *Commit) VoteSignBytes(chainID string, valIdx int32) []byte { v := commit.GetVote(valIdx).ToProto() return VoteSignBytes(chainID, v) @@ -910,14 +909,14 @@ func (commit *Commit) ValidateBasic() error { } for i, commitSig := range commit.Signatures { if err := commitSig.ValidateBasic(); err != nil { - return fmt.Errorf("wrong CommitSig #%d: %v", i, err) + return fmt.Errorf("wrong CommitSig #%d: %w", i, err) } } } return nil } -// Hash returns the hash of the commit +// Hash returns the hash of the commit. func (commit *Commit) Hash() cmtbytes.HexBytes { if commit == nil { return nil @@ -982,7 +981,7 @@ func (commit *Commit) StringIndented(indent string) string { indent, commit.hash) } -// ToProto converts Commit to protobuf +// ToProto converts Commit to protobuf. func (commit *Commit) ToProto() *cmtproto.Commit { if commit == nil { return nil @@ -1216,14 +1215,14 @@ func (ec *ExtendedCommit) ValidateBasic() error { } for i, extCommitSig := range ec.ExtendedSignatures { if err := extCommitSig.ValidateBasic(); err != nil { - return fmt.Errorf("wrong ExtendedCommitSig #%d: %v", i, err) + return fmt.Errorf("wrong ExtendedCommitSig #%d: %w", i, err) } } } return nil } -// ToProto converts ExtendedCommit to protobuf +// ToProto converts ExtendedCommit to protobuf. func (ec *ExtendedCommit) ToProto() *cmtproto.ExtendedCommit { if ec == nil { return nil @@ -1273,7 +1272,7 @@ func ExtendedCommitFromProto(ecp *cmtproto.ExtendedCommit) (*ExtendedCommit, err //------------------------------------- -// Data contains the set of transactions included in the block +// Data contains the set of transactions included in the block. type Data struct { // Txs that will be applied by state @ block.Height+1. // NOTE: not all txs here are valid. We're just agreeing on the order first. @@ -1284,7 +1283,7 @@ type Data struct { hash cmtbytes.HexBytes } -// Hash returns the hash of the data +// Hash returns the hash of the data. func (data *Data) Hash() cmtbytes.HexBytes { if data == nil { return (Txs{}).Hash() @@ -1315,7 +1314,7 @@ func (data *Data) StringIndented(indent string) string { indent, data.hash) } -// ToProto converts Data to protobuf +// ToProto converts Data to protobuf. func (data *Data) ToProto() cmtproto.Data { tp := new(cmtproto.Data) @@ -1353,7 +1352,7 @@ func DataFromProto(dp *cmtproto.Data) (Data, error) { //----------------------------------------------------------------------------- -// EvidenceData contains any evidence of malicious wrong-doing by validators +// EvidenceData contains any evidence of malicious wrong-doing by validators. type EvidenceData struct { Evidence EvidenceList `json:"evidence"` @@ -1370,7 +1369,7 @@ func (data *EvidenceData) Hash() cmtbytes.HexBytes { return data.hash } -// ByteSize returns the total byte size of all the evidence +// ByteSize returns the total byte size of all the evidence. func (data *EvidenceData) ByteSize() int64 { if data.byteSize == 0 && len(data.Evidence) != 0 { pb, err := data.ToProto() @@ -1402,7 +1401,7 @@ func (data *EvidenceData) StringIndented(indent string) string { indent, data.hash) } -// ToProto converts EvidenceData to protobuf +// ToProto converts EvidenceData to protobuf. func (data *EvidenceData) ToProto() (*cmtproto.EvidenceList, error) { if data == nil { return nil, errors.New("nil evidence data") @@ -1444,19 +1443,19 @@ func (data *EvidenceData) FromProto(eviData *cmtproto.EvidenceList) error { //-------------------------------------------------------------------------------- -// BlockID +// BlockID. type BlockID struct { Hash cmtbytes.HexBytes `json:"hash"` PartSetHeader PartSetHeader `json:"parts"` } -// Equals returns true if the BlockID matches the given BlockID +// Equals returns true if the BlockID matches the given BlockID. func (blockID BlockID) Equals(other BlockID) bool { return bytes.Equal(blockID.Hash, other.Hash) && blockID.PartSetHeader.Equals(other.PartSetHeader) } -// Key returns a machine-readable string representation of the BlockID +// Key returns a machine-readable string representation of the BlockID. func (blockID BlockID) Key() string { pbph := blockID.PartSetHeader.ToProto() bz, err := pbph.Marshal() @@ -1474,7 +1473,7 @@ func (blockID BlockID) ValidateBasic() error { return fmt.Errorf("wrong Hash") } if err := blockID.PartSetHeader.ValidateBasic(); err != nil { - return fmt.Errorf("wrong PartSetHeader: %v", err) + return fmt.Errorf("wrong PartSetHeader: %w", err) } return nil } @@ -1497,12 +1496,12 @@ func (blockID BlockID) IsComplete() bool { // 1. hash // 2. part set header // -// See PartSetHeader#String +// See PartSetHeader#String. func (blockID BlockID) String() string { return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader) } -// ToProto converts BlockID to protobuf +// ToProto converts BlockID to protobuf. func (blockID *BlockID) ToProto() cmtproto.BlockID { if blockID == nil { return cmtproto.BlockID{} diff --git a/types/canonical.go b/types/canonical.go index da719a32dc5..3805f642ab8 100644 --- a/types/canonical.go +++ b/types/canonical.go @@ -9,7 +9,7 @@ import ( // Canonical* wraps the structs in types for amino encoding them for use in SignBytes / the Signable interface. -// TimeFormat is used for generating the sigs +// TimeFormat is used for generating the sigs. const TimeFormat = time.RFC3339Nano //----------------------------------- diff --git a/types/encoding_helper.go b/types/encoding_helper.go index 3590ac9a252..0efabedb80a 100644 --- a/types/encoding_helper.go +++ b/types/encoding_helper.go @@ -1,13 +1,12 @@ package types import ( - gogotypes "github.com/cosmos/gogoproto/types" - "github.com/cometbft/cometbft/libs/bytes" + gogotypes "github.com/cosmos/gogoproto/types" ) // cdcEncode returns nil if the input is nil, otherwise returns -// proto.Marshal(Value{Value: item}) +// proto.Marshal(Value{Value: item}). func cdcEncode(item interface{}) []byte { if item != nil && !isTypedNil(item) && !isEmpty(item) { switch item := item.(type) { diff --git a/types/errors/sanity.go b/types/errors/sanity.go index e8a5cff5a87..e064281e2e3 100644 --- a/types/errors/sanity.go +++ b/types/errors/sanity.go @@ -3,23 +3,23 @@ package errors import "fmt" type ( - // ErrNegativeField is returned every time some field which should be non-negative turns out negative + // ErrNegativeField is returned every time some field which should be non-negative turns out negative. ErrNegativeField struct { Field string } - // ErrRequiredField is returned every time a required field is not provided + // ErrRequiredField is returned every time a required field is not provided. ErrRequiredField struct { Field string } - // ErrInvalidField is returned every time a value does not pass a validity check + // ErrInvalidField is returned every time a value does not pass a validity check. ErrInvalidField struct { Field string Reason string } - // ErrWrongField is returned every time a value does not pass a validaty check, accompanied with error + // ErrWrongField is returned every time a value does not pass a validaty check, accompanied with error. ErrWrongField struct { Field string Err error diff --git a/types/event_bus.go b/types/event_bus.go index 78c1845c10c..d92d20e00c1 100644 --- a/types/event_bus.go +++ b/types/event_bus.go @@ -3,6 +3,7 @@ package types import ( "context" "fmt" + "strconv" "github.com/cometbft/cometbft/abci/types" cmtpubsub "github.com/cometbft/cometbft/internal/pubsub" @@ -82,7 +83,7 @@ func (b *EventBus) Subscribe( } // SubscribeUnbuffered can be used for a local consensus explorer and synchronous -// testing. Do not use for for public facing / untrusted subscriptions! +// testing. Do not use for public facing / untrusted subscriptions! func (b *EventBus) SubscribeUnbuffered( ctx context.Context, subscriber string, @@ -183,7 +184,7 @@ func (b *EventBus) PublishEventTx(data EventDataTx) error { // add predefined compositeKeys events[EventTypeKey] = append(events[EventTypeKey], EventTx) events[TxHashKey] = append(events[TxHashKey], fmt.Sprintf("%X", Tx(data.Tx).Hash())) - events[TxHeightKey] = append(events[TxHeightKey], fmt.Sprintf("%d", data.Height)) + events[TxHeightKey] = append(events[TxHeightKey], strconv.FormatInt(data.Height, 10)) return b.pubsub.PublishWithEvents(ctx, data, events) } @@ -224,7 +225,7 @@ func (b *EventBus) PublishEventValidatorSetUpdates(data EventDataValidatorSetUpd return b.Publish(EventValidatorSetUpdates, data) } -// ----------------------------------------------------------------------------- +// -----------------------------------------------------------------------------. type NopEventBus struct{} func (NopEventBus) Subscribe( diff --git a/types/events.go b/types/events.go index 2135b9eee07..6326b8d6f36 100644 --- a/types/events.go +++ b/types/events.go @@ -84,12 +84,12 @@ type EventDataNewEvidence struct { Evidence Evidence `json:"evidence"` } -// All txs fire EventDataTx +// All txs fire EventDataTx. type EventDataTx struct { abci.TxResult } -// NOTE: This goes into the replay WAL +// NOTE: This goes into the replay WAL. type EventDataRoundState struct { Height int64 `json:"height"` Round int32 `json:"round"` @@ -134,11 +134,11 @@ const ( EventTypeKey = "tm.event" // TxHashKey is a reserved key, used to specify transaction's hash. - // see EventBus#PublishEventTx + // see EventBus#PublishEventTx. TxHashKey = "tx.hash" // TxHeightKey is a reserved key, used to specify transaction block's height. - // see EventBus#PublishEventTx + // see EventBus#PublishEventTx. TxHeightKey = "tx.height" // BlockHeightKey is a reserved key used for indexing FinalizeBlock events. @@ -172,16 +172,16 @@ func QueryForEvent(eventType string) cmtpubsub.Query { return cmtquery.MustCompile(fmt.Sprintf("%s='%s'", EventTypeKey, eventType)) } -// BlockEventPublisher publishes all block related events +// BlockEventPublisher publishes all block related events. type BlockEventPublisher interface { PublishEventNewBlock(block EventDataNewBlock) error PublishEventNewBlockHeader(header EventDataNewBlockHeader) error PublishEventNewBlockEvents(events EventDataNewBlockEvents) error PublishEventNewEvidence(evidence EventDataNewEvidence) error - PublishEventTx(EventDataTx) error - PublishEventValidatorSetUpdates(EventDataValidatorSetUpdates) error + PublishEventTx(tx EventDataTx) error + PublishEventValidatorSetUpdates(updates EventDataValidatorSetUpdates) error } type TxEventPublisher interface { - PublishEventTx(EventDataTx) error + PublishEventTx(tx EventDataTx) error } diff --git a/types/evidence.go b/types/evidence.go index c22eb5c19b8..799e2f996ca 100644 --- a/types/evidence.go +++ b/types/evidence.go @@ -47,7 +47,7 @@ var _ Evidence = &DuplicateVoteEvidence{} // NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given // two conflicting votes. If either of the votes is nil, the val set is nil or the voter is -// not in the val set, an error is returned +// not in the val set, an error is returned. func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *ValidatorSet, ) (*DuplicateVoteEvidence, error) { var voteA, voteB *Vote @@ -78,7 +78,7 @@ func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *V }, nil } -// ABCI returns the application relevant representation of the evidence +// ABCI returns the application relevant representation of the evidence. func (dve *DuplicateVoteEvidence) ABCI() []abci.Misbehavior { return []abci.Misbehavior{{ Type: abci.MISBEHAVIOR_TYPE_DUPLICATE_VOTE, @@ -108,7 +108,7 @@ func (dve *DuplicateVoteEvidence) Hash() []byte { return tmhash.Sum(dve.Bytes()) } -// Height returns the height of the infraction +// Height returns the height of the infraction. func (dve *DuplicateVoteEvidence) Height() int64 { return dve.VoteA.Height } @@ -118,7 +118,7 @@ func (dve *DuplicateVoteEvidence) String() string { return fmt.Sprintf("DuplicateVoteEvidence{VoteA: %v, VoteB: %v}", dve.VoteA, dve.VoteB) } -// Time returns the time of the infraction +// Time returns the time of the infraction. func (dve *DuplicateVoteEvidence) Time() time.Time { return dve.Timestamp } @@ -145,7 +145,7 @@ func (dve *DuplicateVoteEvidence) ValidateBasic() error { return nil } -// ToProto encodes DuplicateVoteEvidence to protobuf +// ToProto encodes DuplicateVoteEvidence to protobuf. func (dve *DuplicateVoteEvidence) ToProto() *cmtproto.DuplicateVoteEvidence { voteB := dve.VoteB.ToProto() voteA := dve.VoteA.ToProto() @@ -159,7 +159,7 @@ func (dve *DuplicateVoteEvidence) ToProto() *cmtproto.DuplicateVoteEvidence { return &tp } -// DuplicateVoteEvidenceFromProto decodes protobuf into DuplicateVoteEvidence +// DuplicateVoteEvidenceFromProto decodes protobuf into DuplicateVoteEvidence. func DuplicateVoteEvidenceFromProto(pb *cmtproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error) { if pb == nil { return nil, errors.New("nil duplicate vote evidence") @@ -206,7 +206,7 @@ func DuplicateVoteEvidenceFromProto(pb *cmtproto.DuplicateVoteEvidence) (*Duplic // a light client such that a full node can verify, propose and commit the evidence on-chain for // punishment of the malicious validators. There are three forms of attacks: Lunatic, Equivocation // and Amnesia. These attacks are exhaustive. You can find a more detailed overview of this at -// cometbft/docs/architecture/tendermint-core/adr-047-handling-evidence-from-light-client.md +// cometbft/docs/architecture/tendermint-core/adr-047-handling-evidence-from-light-client.md. type LightClientAttackEvidence struct { ConflictingBlock *LightBlock CommonHeight int64 @@ -219,7 +219,7 @@ type LightClientAttackEvidence struct { var _ Evidence = &LightClientAttackEvidence{} -// ABCI forms an array of abci.Misbehavior for each byzantine validator +// ABCI forms an array of abci.Misbehavior for each byzantine validator. func (l *LightClientAttackEvidence) ABCI() []abci.Misbehavior { abciEv := make([]abci.Misbehavior, len(l.ByzantineValidators)) for idx, val := range l.ByzantineValidators { @@ -234,7 +234,7 @@ func (l *LightClientAttackEvidence) ABCI() []abci.Misbehavior { return abciEv } -// Bytes returns the proto-encoded evidence as a byte array +// Bytes returns the proto-encoded evidence as a byte array. func (l *LightClientAttackEvidence) Bytes() []byte { pbe, err := l.ToProto() if err != nil { @@ -249,7 +249,7 @@ func (l *LightClientAttackEvidence) Bytes() []byte { // GetByzantineValidators finds out what style of attack LightClientAttackEvidence was and then works out who // the malicious validators were and returns them. This is used both for forming the ByzantineValidators -// field and for validating that it is correct. Validators are ordered based on validator power +// field and for validating that it is correct. Validators are ordered based on validator power. func (l *LightClientAttackEvidence) GetByzantineValidators(commonVals *ValidatorSet, trusted *SignedHeader, ) []*Validator { @@ -318,7 +318,7 @@ func (l *LightClientAttackEvidence) ConflictingHeaderIsInvalid(trustedHeader *He // most commit signatures (captures the most byzantine validators) but anything greater than 1/3 is // sufficient. // TODO: We should change the hash to include the commit, header, total voting power, byzantine -// validators and timestamp +// validators and timestamp. func (l *LightClientAttackEvidence) Hash() []byte { buf := make([]byte, binary.MaxVarintLen64) n := binary.PutVarint(buf, l.CommonHeight) @@ -330,12 +330,12 @@ func (l *LightClientAttackEvidence) Hash() []byte { // Height returns the last height at which the primary provider and witness provider had the same header. // We use this as the height of the infraction rather than the actual conflicting header because we know -// that the malicious validators were bonded at this height which is important for evidence expiry +// that the malicious validators were bonded at this height which is important for evidence expiry. func (l *LightClientAttackEvidence) Height() int64 { return l.CommonHeight } -// String returns a string representation of LightClientAttackEvidence +// String returns a string representation of LightClientAttackEvidence. func (l *LightClientAttackEvidence) String() string { return fmt.Sprintf(`LightClientAttackEvidence{ ConflictingBlock: %v, @@ -386,7 +386,7 @@ func (l *LightClientAttackEvidence) ValidateBasic() error { return nil } -// ToProto encodes LightClientAttackEvidence to protobuf +// ToProto encodes LightClientAttackEvidence to protobuf. func (l *LightClientAttackEvidence) ToProto() (*cmtproto.LightClientAttackEvidence, error) { conflictingBlock, err := l.ConflictingBlock.ToProto() if err != nil { @@ -411,7 +411,7 @@ func (l *LightClientAttackEvidence) ToProto() (*cmtproto.LightClientAttackEviden }, nil } -// LightClientAttackEvidenceFromProto decodes protobuf +// LightClientAttackEvidenceFromProto decodes protobuf. func LightClientAttackEvidenceFromProto(lpb *cmtproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error) { if lpb == nil { return nil, cmterrors.ErrRequiredField{Field: "light_client_attack_evidence"} @@ -492,7 +492,7 @@ func (evl EvidenceList) ToABCI() []abci.Misbehavior { //------------------------------------------ PROTO -------------------------------------- // EvidenceToProto is a generalized function for encoding evidence that conforms to the -// evidence interface to protobuf +// evidence interface to protobuf. func EvidenceToProto(evidence Evidence) (*cmtproto.Evidence, error) { if evidence == nil { return nil, errors.New("nil evidence") @@ -524,7 +524,7 @@ func EvidenceToProto(evidence Evidence) (*cmtproto.Evidence, error) { } // EvidenceFromProto is a generalized function for decoding protobuf into the -// evidence interface +// evidence interface. func EvidenceFromProto(evidence *cmtproto.Evidence) (Evidence, error) { if evidence == nil { return nil, errors.New("nil evidence") @@ -584,14 +584,14 @@ func (err *ErrEvidenceOverflow) Error() string { // unstable - use only for testing // NewMockDuplicateVoteEvidence assumes the round to be 0 and the validator -// index to be 0 +// index to be 0. func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) (*DuplicateVoteEvidence, error) { val := NewMockPV() return NewMockDuplicateVoteEvidenceWithValidator(height, time, val, chainID) } // NewMockDuplicateVoteEvidenceWithValidator assumes voting power to be 10 -// and validator to be the only one in the set +// and validator to be the only one in the set. func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time, pv PrivValidator, chainID string, ) (*DuplicateVoteEvidence, error) { diff --git a/types/genesis.go b/types/genesis.go index 42eb56c6051..4f0f18ce40e 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -51,10 +51,10 @@ func (genDoc *GenesisDoc) SaveAs(file string) error { if err != nil { return err } - return cmtos.WriteFile(file, genDocBytes, 0644) + return cmtos.WriteFile(file, genDocBytes, 0o644) } -// ValidatorHash returns the hash of the validator set contained in the GenesisDoc +// ValidatorHash returns the hash of the validator set contained in the GenesisDoc. func (genDoc *GenesisDoc) ValidatorHash() []byte { vals := make([]*Validator, len(genDoc.Validators)) for i, v := range genDoc.Validators { @@ -65,7 +65,7 @@ func (genDoc *GenesisDoc) ValidatorHash() []byte { } // ValidateAndComplete checks that all necessary fields are present -// and fills in defaults for optional fields left empty +// and fills in defaults for optional fields left empty. func (genDoc *GenesisDoc) ValidateAndComplete() error { if genDoc.ChainID == "" { return errors.New("genesis doc must include non-empty chain_id") diff --git a/types/keys.go b/types/keys.go index 941e82b65b0..cb1161bf579 100644 --- a/types/keys.go +++ b/types/keys.go @@ -1,6 +1,6 @@ package types -// UNSTABLE +// UNSTABLE. var ( PeerStateKey = "ConsensusReactor.peerState" ) diff --git a/types/light.go b/types/light.go index 52d35f92ca9..d8f9169bf9b 100644 --- a/types/light.go +++ b/types/light.go @@ -9,7 +9,7 @@ import ( ) // LightBlock is a SignedHeader and a ValidatorSet. -// It is the basis of the light client +// It is the basis of the light client. type LightBlock struct { *SignedHeader `json:"signed_header"` ValidatorSet *ValidatorSet `json:"validator_set"` @@ -17,7 +17,7 @@ type LightBlock struct { // ValidateBasic checks that the data is correct and consistent // -// This does no verification of the signatures +// This does no verification of the signatures. func (lb LightBlock) ValidateBasic(chainID string) error { if lb.SignedHeader == nil { return errors.New("missing signed header") @@ -43,7 +43,7 @@ func (lb LightBlock) ValidateBasic(chainID string) error { return nil } -// String returns a string representation of the LightBlock +// String returns a string representation of the LightBlock. func (lb LightBlock) String() string { return lb.StringIndented("") } @@ -51,7 +51,7 @@ func (lb LightBlock) String() string { // StringIndented returns an indented string representation of the LightBlock // // SignedHeader -// ValidatorSet +// ValidatorSet. func (lb LightBlock) StringIndented(indent string) string { return fmt.Sprintf(`LightBlock{ %s %v @@ -62,7 +62,7 @@ func (lb LightBlock) StringIndented(indent string) string { indent) } -// ToProto converts the LightBlock to protobuf +// ToProto converts the LightBlock to protobuf. func (lb *LightBlock) ToProto() (*cmtproto.LightBlock, error) { if lb == nil { return nil, nil @@ -84,7 +84,7 @@ func (lb *LightBlock) ToProto() (*cmtproto.LightBlock, error) { } // LightBlockFromProto converts from protobuf back into the Lightblock. -// An error is returned if either the validator set or signed header are invalid +// An error is returned if either the validator set or signed header are invalid. func LightBlockFromProto(pb *cmtproto.LightBlock) (*LightBlock, error) { if pb == nil { return nil, errors.New("nil light block") @@ -169,7 +169,7 @@ func (sh SignedHeader) String() string { // StringIndented returns an indented string representation of SignedHeader. // // Header -// Commit +// Commit. func (sh SignedHeader) StringIndented(indent string) string { return fmt.Sprintf(`SignedHeader{ %s %v @@ -180,7 +180,7 @@ func (sh SignedHeader) StringIndented(indent string) string { indent) } -// ToProto converts SignedHeader to protobuf +// ToProto converts SignedHeader to protobuf. func (sh *SignedHeader) ToProto() *cmtproto.SignedHeader { if sh == nil { return nil diff --git a/types/params.go b/types/params.go index 124c59920b2..3bbef17b09e 100644 --- a/types/params.go +++ b/types/params.go @@ -254,7 +254,7 @@ func (params ConsensusParams) Hash() []byte { } // Update returns a copy of the params with updates from the non-zero fields of p2. -// NOTE: note: must not modify the original +// NOTE: note: must not modify the original. func (params ConsensusParams) Update(params2 *cmtproto.ConsensusParams) ConsensusParams { res := params // explicit copy diff --git a/types/part_set.go b/types/part_set.go index c6c61379589..96067e2a1ff 100644 --- a/types/part_set.go +++ b/types/part_set.go @@ -46,7 +46,7 @@ func (part *Part) String() string { // StringIndented returns an indented Part. // -// See merkle.Proof#StringIndented +// See merkle.Proof#StringIndented. func (part *Part) StringIndented(indent string) string { return fmt.Sprintf(`Part{#%v %s Bytes: %X... @@ -99,7 +99,7 @@ type PartSetHeader struct { // String returns a string representation of PartSetHeader. // // 1. total number of parts -// 2. first 6 bytes of the hash +// 2. first 6 bytes of the hash. func (psh PartSetHeader) String() string { return fmt.Sprintf("%v:%X", psh.Total, cmtbytes.Fingerprint(psh.Hash)) } @@ -121,7 +121,7 @@ func (psh PartSetHeader) ValidateBasic() error { return nil } -// ToProto converts PartSetHeader to protobuf +// ToProto converts PartSetHeader to protobuf. func (psh *PartSetHeader) ToProto() cmtproto.PartSetHeader { if psh == nil { return cmtproto.PartSetHeader{} @@ -133,7 +133,7 @@ func (psh *PartSetHeader) ToProto() cmtproto.PartSetHeader { } } -// PartSetHeaderFromProto sets a protobuf PartSetHeader to the given pointer +// PartSetHeaderFromProto sets a protobuf PartSetHeader to the given pointer. func PartSetHeaderFromProto(ppsh *cmtproto.PartSetHeader) (*PartSetHeader, error) { if ppsh == nil { return nil, errors.New("nil PartSetHeader") @@ -356,7 +356,7 @@ func (psr *PartSetReader) Read(p []byte) (n int, err error) { // StringShort returns a short version of String. // -// (Count of Total) +// (Count of Total). func (ps *PartSet) StringShort() string { if ps == nil { return "nil-PartSet" diff --git a/types/proposal.go b/types/proposal.go index d57dbb6d14f..1bb3c7e64db 100644 --- a/types/proposal.go +++ b/types/proposal.go @@ -60,7 +60,7 @@ func (p *Proposal) ValidateBasic() error { return errors.New("negative POLRound (exception: -1)") } if err := p.BlockID.ValidateBasic(); err != nil { - return fmt.Errorf("wrong BlockID: %v", err) + return fmt.Errorf("wrong BlockID: %w", err) } // ValidateBasic above would pass even if the BlockID was empty: if !p.BlockID.IsComplete() { @@ -106,7 +106,7 @@ func (p *Proposal) String() string { // for backwards-compatibility with the Amino encoding, due to e.g. hardware // devices that rely on this encoding. // -// See CanonicalizeProposal +// See CanonicalizeProposal. func ProposalSignBytes(chainID string, p *cmtproto.Proposal) []byte { pb := CanonicalizeProposal(chainID, p) bz, err := protoio.MarshalDelimited(&pb) @@ -117,7 +117,7 @@ func ProposalSignBytes(chainID string, p *cmtproto.Proposal) []byte { return bz } -// ToProto converts Proposal to protobuf +// ToProto converts Proposal to protobuf. func (p *Proposal) ToProto() *cmtproto.Proposal { if p == nil { return &cmtproto.Proposal{} diff --git a/types/protobuf.go b/types/protobuf.go index 7fda6dad2f1..f7685d93b33 100644 --- a/types/protobuf.go +++ b/types/protobuf.go @@ -10,7 +10,7 @@ import ( //------------------------------------------------------- // TM2PB is used for converting CometBFT ABCI to protobuf ABCI. -// UNSTABLE +// UNSTABLE. var TM2PB = tm2pb{} type tm2pb struct{} @@ -59,7 +59,7 @@ func (tm2pb) PartSetHeader(header PartSetHeader) cmtproto.PartSetHeader { } } -// XXX: panics on unknown pubkey type +// XXX: panics on unknown pubkey type. func (tm2pb) ValidatorUpdate(val *Validator) abci.ValidatorUpdate { pk, err := cryptoenc.PubKeyToProto(val.PubKey) if err != nil { @@ -71,7 +71,7 @@ func (tm2pb) ValidatorUpdate(val *Validator) abci.ValidatorUpdate { } } -// XXX: panics on nil or unknown pubkey type +// XXX: panics on nil or unknown pubkey type. func (tm2pb) ValidatorUpdates(vals *ValidatorSet) []abci.ValidatorUpdate { validators := make([]abci.ValidatorUpdate, vals.Size()) for i, val := range vals.Validators { @@ -80,7 +80,7 @@ func (tm2pb) ValidatorUpdates(vals *ValidatorSet) []abci.ValidatorUpdate { return validators } -// XXX: panics on nil or unknown pubkey type +// XXX: panics on nil or unknown pubkey type. func (tm2pb) NewValidatorUpdate(pubkey crypto.PubKey, power int64) abci.ValidatorUpdate { pubkeyABCI, err := cryptoenc.PubKeyToProto(pubkey) if err != nil { @@ -95,7 +95,7 @@ func (tm2pb) NewValidatorUpdate(pubkey crypto.PubKey, power int64) abci.Validato //---------------------------------------------------------------------------- // PB2TM is used for converting protobuf ABCI to CometBFT ABCI. -// UNSTABLE +// UNSTABLE. var PB2TM = pb2tm{} type pb2tm struct{} diff --git a/types/results.go b/types/results.go index 214fca90f98..abf42f6f760 100644 --- a/types/results.go +++ b/types/results.go @@ -23,7 +23,7 @@ func (a ABCIResults) Hash() []byte { return merkle.HashFromByteSlices(a.toByteSlices()) } -// ProveResult returns a merkle proof of one result from the set +// ProveResult returns a merkle proof of one result from the set. func (a ABCIResults) ProveResult(i int) merkle.Proof { _, proofs := merkle.ProofsFromByteSlices(a.toByteSlices()) return *proofs[i] diff --git a/types/signable.go b/types/signable.go index 8ba2e6599a1..743ec03a279 100644 --- a/types/signable.go +++ b/types/signable.go @@ -5,12 +5,10 @@ import ( cmtmath "github.com/cometbft/cometbft/libs/math" ) -var ( - // MaxSignatureSize is a maximum allowed signature size for the Proposal - // and Vote. - // XXX: secp256k1 does not have Size nor MaxSize defined. - MaxSignatureSize = cmtmath.MaxInt(ed25519.SignatureSize, 64) -) +// MaxSignatureSize is a maximum allowed signature size for the Proposal +// and Vote. +// XXX: secp256k1 does not have Size nor MaxSize defined. +var MaxSignatureSize = cmtmath.MaxInt(ed25519.SignatureSize, 64) // Signable is an interface for all signable things. // It typically removes signatures before serializing. diff --git a/types/test_util.go b/types/test_util.go index 105fbf5b467..0ab9bf2bf57 100644 --- a/types/test_util.go +++ b/types/test_util.go @@ -5,10 +5,9 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - cmtversion "github.com/cometbft/cometbft/api/cometbft/version/v1" "github.com/cometbft/cometbft/version" + "github.com/stretchr/testify/require" ) func MakeExtCommit(blockID BlockID, height int64, round int32, @@ -98,6 +97,8 @@ func MakeVoteNoError( blockID BlockID, time time.Time, ) *Vote { + t.Helper() + vote, err := MakeVote(val, chainID, valIndex, height, round, step, blockID, time) require.NoError(t, err) return vote diff --git a/types/tx.go b/types/tx.go index f4bb9b21562..fa6930a56e6 100644 --- a/types/tx.go +++ b/types/tx.go @@ -12,7 +12,7 @@ import ( cmtbytes "github.com/cometbft/cometbft/libs/bytes" ) -// TxKeySize is the size of the transaction key index +// TxKeySize is the size of the transaction key index. const TxKeySize = sha256.Size type ( @@ -49,7 +49,7 @@ func (txs Txs) Hash() []byte { return merkle.HashFromByteSlices(hl) } -// Index returns the index of this transaction in the list, or -1 if not found +// Index returns the index of this transaction in the list, or -1 if not found. func (txs Txs) Index(tx Tx) int { for i := range txs { if bytes.Equal(txs[i], tx) { @@ -59,7 +59,7 @@ func (txs Txs) Index(tx Tx) int { return -1 } -// IndexByHash returns the index of this transaction hash in the list, or -1 if not found +// IndexByHash returns the index of this transaction hash in the list, or -1 if not found. func (txs Txs) IndexByHash(hash []byte) int { for i := range txs { if bytes.Equal(txs[i].Hash(), hash) { diff --git a/types/validation.go b/types/validation.go index e8ce5b0003f..7bf7c55e401 100644 --- a/types/validation.go +++ b/types/validation.go @@ -24,7 +24,8 @@ func shouldBatchVerify(vals *ValidatorSet, commit *Commit) bool { // includes which validators signed. For instance, Gaia incentivizes proposers // with a bonus for including more than +2/3 of the signatures. func VerifyCommit(chainID string, vals *ValidatorSet, blockID BlockID, - height int64, commit *Commit) error { + height int64, commit *Commit, +) error { // run a basic validation of the arguments if err := verifyBasicValsAndCommit(vals, commit, height, blockID); err != nil { return err @@ -322,7 +323,7 @@ func verifyCommitBatch( // If a key does not support batch verification, or batch verification fails this will be used // This method is used to check all the signatures included in a commit. // It is used in consensus for validating a block LastCommit. -// CONTRACT: both commit and validator set should have passed validate basic +// CONTRACT: both commit and validator set should have passed validate basic. func verifyCommitSingle( chainID string, vals *ValidatorSet, diff --git a/types/validator.go b/types/validator.go index 56dd3f81ae1..4522119d11b 100644 --- a/types/validator.go +++ b/types/validator.go @@ -14,7 +14,7 @@ import ( // Volatile state for each Validator // NOTE: The ProposerPriority is not included in Validator.Hash(); -// make sure to update that method if changes are made here +// make sure to update that method if changes are made here. type Validator struct { Address Address `json:"address"` PubKey crypto.PubKey `json:"pub_key"` @@ -89,7 +89,7 @@ func (v *Validator) CompareProposerPriority(other *Validator) *Validator { // 1. address // 2. public key // 3. voting power -// 4. proposer priority +// 4. proposer priority. func (v *Validator) String() string { if v == nil { return "nil-Validator" @@ -133,7 +133,7 @@ func (v *Validator) Bytes() []byte { return bz } -// ToProto converts Validator to protobuf +// ToProto converts Validator to protobuf. func (v *Validator) ToProto() (*cmtproto.Validator, error) { if v == nil { return nil, errors.New("nil validator") @@ -178,7 +178,7 @@ func ValidatorFromProto(vp *cmtproto.Validator) (*Validator, error) { // RandValidator // RandValidator returns a randomized validator, useful for testing. -// UNSTABLE +// UNSTABLE. func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator) { privVal := NewMockPV() votePower := minPower diff --git a/types/validator_set.go b/types/validator_set.go index 921c6d1089b..7658d7a12ed 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -425,7 +425,7 @@ func processChanges(origChanges []*Validator) (updates, removals []*Validator, e // Note that this will be < 2 * MaxTotalVotingPower in case high power validators are removed and // validators are added/ updated with high power values. // -// err - non-nil if the maximum allowed total voting power would be exceeded +// err - non-nil if the maximum allowed total voting power would be exceeded. func verifyUpdates( updates []*Validator, vals *ValidatorSet, @@ -661,7 +661,7 @@ func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error { } // VerifyCommit verifies +2/3 of the set had signed the given commit and all -// other signatures are valid +// other signatures are valid. func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height int64, commit *Commit, ) error { @@ -810,7 +810,7 @@ func (valz ValidatorsByAddress) Swap(i, j int) { valz[i], valz[j] = valz[j], valz[i] } -// ToProto converts ValidatorSet to protobuf +// ToProto converts ValidatorSet to protobuf. func (vals *ValidatorSet) ToProto() (*cmtproto.ValidatorSet, error) { if vals.IsNilOrEmpty() { return &cmtproto.ValidatorSet{}, nil // validator set should never be nil @@ -842,7 +842,7 @@ func (vals *ValidatorSet) ToProto() (*cmtproto.ValidatorSet, error) { // ValidatorSetFromProto sets a protobuf ValidatorSet to the given pointer. // It returns an error if any of the validators from the set or the proposer -// is invalid +// is invalid. func ValidatorSetFromProto(vp *cmtproto.ValidatorSet) (*ValidatorSet, error) { if vp == nil { return nil, errors.New("nil validator set") // validator set should never be nil, bigger issues are at play if empty diff --git a/types/vote.go b/types/vote.go index 8fb8c3014ba..b12ff13636d 100644 --- a/types/vote.go +++ b/types/vote.go @@ -7,7 +7,6 @@ import ( "time" cmtcons "github.com/cometbft/cometbft/api/cometbft/consensus/v1" - cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1" "github.com/cometbft/cometbft/crypto" "github.com/cometbft/cometbft/internal/protoio" @@ -137,7 +136,7 @@ func (vote *Vote) ExtendedCommitSig() ExtendedCommitSig { // for backwards-compatibility with the Amino encoding, due to e.g. hardware // devices that rely on this encoding. // -// See CanonicalizeVote +// See CanonicalizeVote. func VoteSignBytes(chainID string, vote *cmtproto.Vote) []byte { pb := CanonicalizeVote(chainID, vote) bz, err := protoio.MarshalDelimited(&pb) @@ -179,7 +178,7 @@ func (vote *Vote) Copy() *Vote { // 7. first 6 bytes of block hash // 8. first 6 bytes of signature // 9. first 6 bytes of vote extension -// 10. timestamp +// 10. timestamp. func (vote *Vote) String() string { if vote == nil { return nilVoteStr @@ -284,7 +283,7 @@ func (vote *Vote) ValidateBasic() error { // NOTE: Timestamp validation is subtle and handled elsewhere. if err := vote.BlockID.ValidateBasic(); err != nil { - return fmt.Errorf("wrong BlockID: %v", err) + return fmt.Errorf("wrong BlockID: %w", err) } // BlockID.ValidateBasic would not err if we for instance have an empty hash but a @@ -334,7 +333,7 @@ func (vote *Vote) ValidateBasic() error { } // NOTE: extended votes should have a signature regardless of - // of whether there is any data in the extension or not however + // whether there is any data in the extension or not however // we don't know if extensions are enabled so we can only // enforce the signature when extension size is not nil if len(vote.ExtensionSignature) == 0 && len(vote.Extension) != 0 { @@ -362,7 +361,7 @@ func (vote *Vote) EnsureExtension() error { } // ToProto converts the handwritten type to proto generated type -// return type, nil if everything converts safely, otherwise nil, error +// return type, nil if everything converts safely, otherwise nil, error. func (vote *Vote) ToProto() *cmtproto.Vote { if vote == nil { return nil diff --git a/types/vote_set.go b/types/vote_set.go index 9834725cd8d..0f8fa48c719 100644 --- a/types/vote_set.go +++ b/types/vote_set.go @@ -154,7 +154,7 @@ func (voteSet *VoteSet) Size() int { // Conflicting votes return added=*, err=ErrVoteConflictingVotes. // NOTE: vote should not be mutated after adding. // NOTE: VoteSet must not be nil -// NOTE: Vote must not be nil +// NOTE: Vote must not be nil. func (voteSet *VoteSet) AddVote(vote *Vote) (added bool, err error) { if voteSet == nil { panic("AddVote() on nil VoteSet") @@ -331,7 +331,7 @@ func (voteSet *VoteSet) addVerifiedVote( // NOTE: if there are too many peers, or too much peer churn, // this can cause memory issues. // TODO: implement ability to remove peers too -// NOTE: VoteSet must not be nil +// NOTE: VoteSet must not be nil. func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error { if voteSet == nil { panic("SetPeerMaj23() on nil VoteSet") @@ -544,7 +544,7 @@ func (voteSet *VoteSet) MarshalJSON() ([]byte, error) { // More human readable JSON of the vote set // NOTE: insufficient for unmarshalling from (compressed votes) -// TODO: make the peerMaj23s nicer to read (eg just the block hash) +// TODO: make the peerMaj23s nicer to read (eg just the block hash). type VoteSetJSON struct { Votes []string `json:"votes"` VotesBitArray string `json:"votes_bit_array"` @@ -553,7 +553,7 @@ type VoteSetJSON struct { // BitArrayString returns the bit-array of votes including // the fraction of power that has voted like: -// "BA{29:xx__x__x_x___x__x_______xxx__} 856/1304 = 0.66" +// "BA{29:xx__x__x_x___x__x_______xxx__} 856/1304 = 0.66". func (voteSet *VoteSet) BitArrayString() string { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() @@ -593,7 +593,7 @@ func (voteSet *VoteSet) voteStrings() []string { // 4. first 2/3+ majority // 5. fraction of voted power // 6. votes bit array -// 7. 2/3+ majority for each peer +// 7. 2/3+ majority for each peer. func (voteSet *VoteSet) StringShort() string { if voteSet == nil { return nilVoteSetString @@ -618,7 +618,7 @@ func (voteSet *VoteSet) LogString() string { return fmt.Sprintf("Votes:%d/%d(%.3f)", voted, total, frac) } -// sumTotalFrac returns the power voted, the total, and the fraction +// sumTotalFrac returns the power voted, the total, and the fraction. func (voteSet *VoteSet) sumTotalFrac() (int64, int64, float64) { voted, total := voteSet.sum, voteSet.valSet.TotalVotingPower() fracVoted := float64(voted) / float64(total) @@ -677,7 +677,7 @@ func (voteSet *VoteSet) MakeExtendedCommit(ap ABCIParams) *ExtendedCommit { Votes for a particular block There are two ways a *blockVotes gets created for a blockKey. 1. first (non-conflicting) vote of a validator w/ blockKey (peerMaj23=false) -2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true) +2. A peer claims to have a 2/3 majority w/ blockKey (peerMaj23=true). */ type blockVotes struct { peerMaj23 bool // peer claims to have maj23 @@ -713,13 +713,13 @@ func (vs *blockVotes) getByIndex(index int32) *Vote { //-------------------------------------------------------------------------------- -// Common interface between *consensus.VoteSet and types.Commit +// Common interface between *consensus.VoteSet and types.Commit. type VoteSetReader interface { GetHeight() int64 GetRound() int32 Type() byte Size() int BitArray() *bits.BitArray - GetByIndex(int32) *Vote + GetByIndex(idx int32) *Vote IsCommit() bool } diff --git a/version/version.go b/version/version.go index 91cc9f55154..b2b79888e63 100644 --- a/version/version.go +++ b/version/version.go @@ -4,7 +4,7 @@ const ( // CMTSemVer is the used as the fallback version of CometBFT // when not using git describe. It is formatted with semantic versioning. CMTSemVer = "0.39.0-dev" - // ABCISemVer is the semantic version of the ABCI protocol + // ABCISemVer is the semantic version of the ABCI protocol. ABCISemVer = "2.0.0" ABCIVersion = ABCISemVer // P2PProtocol versions all p2p behavior and msgs. @@ -17,5 +17,5 @@ const ( ) // CMTGitCommitHash uses git rev-parse HEAD to find commit hash which is helpful -// for the engineering team when working with the cometbft binary. See Makefile +// for the engineering team when working with the cometbft binary. See Makefile. var CMTGitCommitHash = ""