From cceea4de2221b0f2b490247fa5619edf6b1048ee Mon Sep 17 00:00:00 2001 From: Thane Thomson Date: Tue, 30 Aug 2022 12:28:46 -0400 Subject: [PATCH] chore: Format and fix lints (#9336) * make format Signed-off-by: Thane Thomson * Fix linting directives Signed-off-by: Thane Thomson * make mockery Signed-off-by: Thane Thomson * Appease CI linter Signed-off-by: Thane Thomson * Appease CI linter Signed-off-by: Thane Thomson Signed-off-by: Thane Thomson --- abci/example/kvstore/kvstore_test.go | 2 +- abci/server/server.go | 5 +- abci/types/messages.go | 1 + blocksync/msgs_test.go | 2 +- blocksync/pool.go | 1 + blocksync/reactor.go | 2 +- cmd/tendermint/commands/debug/kill.go | 2 +- cmd/tendermint/commands/debug/util.go | 2 +- config/config_test.go | 2 +- consensus/metrics.go | 1 + consensus/msgs_test.go | 2 +- consensus/reactor_test.go | 8 +-- consensus/replay_test.go | 2 +- consensus/state.go | 2 +- crypto/armor/armor.go | 2 +- crypto/merkle/doc.go | 25 ++++---- crypto/merkle/proof_value.go | 4 +- crypto/merkle/tree.go | 8 +-- crypto/secp256k1/secp256k1.go | 8 +-- evidence/pool.go | 10 +-- evidence/reactor_test.go | 2 +- evidence/verify.go | 19 +++--- internal/test/factory_test.go | 1 + libs/cli/flags/log_level.go | 3 +- libs/clist/clist.go | 2 - libs/clist/clist_test.go | 2 + libs/flowrate/flowrate.go | 8 +-- libs/json/doc.go | 15 +++-- libs/log/filter.go | 21 ++++--- libs/log/logger.go | 6 +- libs/log/tmfmt_logger.go | 2 +- libs/log/tmfmt_logger_test.go | 5 +- libs/pubsub/pubsub.go | 36 +++++------ libs/pubsub/query/query.go | 2 +- libs/pubsub/subscription.go | 6 +- libs/rand/random.go | 2 +- light/detector.go | 20 +++--- light/provider/http/http.go | 2 +- light/proxy/routes.go | 6 +- light/rpc/client.go | 1 + light/verifier.go | 36 +++++------ mempool/v0/clist_mempool.go | 10 +-- node/doc.go | 45 +++++++------- node/node.go | 56 ++++++++--------- p2p/conn/connection.go | 1 + p2p/conn/connection_test.go | 32 +++++----- p2p/fuzz.go | 2 +- p2p/node_info_test.go | 2 +- p2p/pex/known_address.go | 16 ++--- p2p/pex/pex_reactor_test.go | 30 ++++----- p2p/switch.go | 4 +- p2p/trust/metric_test.go | 1 + p2p/upnp/upnp.go | 2 +- privval/doc.go | 10 ++- privval/msgs_test.go | 2 +- proxy/app_conn.go | 1 + proxy/multi_app_conn_test.go | 2 +- rpc/client/http/http.go | 30 ++++----- rpc/client/mock/client.go | 1 - rpc/core/env.go | 2 +- rpc/jsonrpc/client/ws_client.go | 4 +- rpc/jsonrpc/client/ws_client_test.go | 8 +-- rpc/jsonrpc/server/http_json_handler.go | 7 ++- rpc/jsonrpc/types/types.go | 23 ++++--- .../metricsdiff/metricsdiff_test.go | 1 + scripts/metricsgen/metricsgen_test.go | 1 + statesync/snapshots.go | 2 +- store/store.go | 13 ++-- test/e2e/app/snapshots.go | 7 +-- test/e2e/app/state.go | 9 +-- test/e2e/generator/main.go | 5 +- test/e2e/node/config.go | 3 +- test/e2e/pkg/testnet.go | 13 ++-- test/e2e/runner/evidence.go | 4 +- test/e2e/runner/exec.go | 5 +- test/e2e/runner/main.go | 4 +- test/e2e/runner/setup.go | 9 ++- test/fuzz/p2p/addrbook/fuzz.go | 3 +- test/fuzz/p2p/addrbook/init-corpus/main.go | 6 +- test/fuzz/p2p/pex/init-corpus/main.go | 6 +- .../p2p/secret_connection/init-corpus/main.go | 6 +- types/block_test.go | 2 +- types/event_bus.go | 4 +- types/utils.go | 6 +- types/validator_set.go | 31 ++++++---- types/validator_set_test.go | 5 +- types/vote_set.go | 62 ++++++++++--------- 87 files changed, 402 insertions(+), 384 deletions(-) diff --git a/abci/example/kvstore/kvstore_test.go b/abci/example/kvstore/kvstore_test.go index 0a7802aab..5d91f3699 100644 --- a/abci/example/kvstore/kvstore_test.go +++ b/abci/example/kvstore/kvstore_test.go @@ -162,7 +162,7 @@ func TestValUpdates(t *testing.T) { makeApplyBlock(t, kvstore, 2, diff, tx1, tx2, tx3) - vals1 = append(vals[:nInit-2], vals[nInit+1]) // nolint: gocritic + vals1 = append(vals[:nInit-2], vals[nInit+1]) //nolint: gocritic vals2 = kvstore.Validators() valsEqual(t, vals1, vals2) diff --git a/abci/server/server.go b/abci/server/server.go index 6dd13ad02..4b70545b2 100644 --- a/abci/server/server.go +++ b/abci/server/server.go @@ -2,9 +2,8 @@ Package server is used to start a new ABCI server. It contains two server implementation: - * gRPC server - * socket server - + - gRPC server + - socket server */ package server diff --git a/abci/types/messages.go b/abci/types/messages.go index 3f2060575..702fdac0b 100644 --- a/abci/types/messages.go +++ b/abci/types/messages.go @@ -4,6 +4,7 @@ import ( "io" "github.com/gogo/protobuf/proto" + "github.com/tendermint/tendermint/libs/protoio" ) diff --git a/blocksync/msgs_test.go b/blocksync/msgs_test.go index b27376b14..ca2502a0f 100644 --- a/blocksync/msgs_test.go +++ b/blocksync/msgs_test.go @@ -79,7 +79,7 @@ func TestBcStatusResponseMessageValidateBasic(t *testing.T) { } } -// nolint:lll // ignore line length in tests +//nolint:lll // ignore line length in tests func TestBlockchainMessageVectors(t *testing.T) { block := types.MakeBlock(int64(3), []types.Tx{types.Tx("Hello World")}, nil, nil) block.Version.Block = 11 // overwrite updated protocol version diff --git a/blocksync/pool.go b/blocksync/pool.go index 99dcb79e2..1a89cbe7d 100644 --- a/blocksync/pool.go +++ b/blocksync/pool.go @@ -410,6 +410,7 @@ func (pool *BlockPool) sendError(err error, peerID p2p.ID) { } // for debugging purposes +// //nolint:unused func (pool *BlockPool) debug() string { pool.mtx.Lock() diff --git a/blocksync/reactor.go b/blocksync/reactor.go index 1eccd5efb..51e17630e 100644 --- a/blocksync/reactor.go +++ b/blocksync/reactor.go @@ -303,7 +303,7 @@ func (bcR *Reactor) poolRoutine(stateSynced bool) { case <-statusUpdateTicker.C: // ask for status updates - go bcR.BroadcastStatusRequest() // nolint: errcheck + go bcR.BroadcastStatusRequest() //nolint: errcheck } } diff --git a/cmd/tendermint/commands/debug/kill.go b/cmd/tendermint/commands/debug/kill.go index 6801746b9..f1670b150 100644 --- a/cmd/tendermint/commands/debug/kill.go +++ b/cmd/tendermint/commands/debug/kill.go @@ -104,7 +104,7 @@ func killProc(pid uint64, dir string) error { // pipe STDERR output from tailing the Tendermint process to a file // // NOTE: This will only work on UNIX systems. - cmd := exec.Command("tail", "-f", fmt.Sprintf("/proc/%d/fd/2", pid)) // nolint: gosec + cmd := exec.Command("tail", "-f", fmt.Sprintf("/proc/%d/fd/2", pid)) //nolint: gosec outFile, err := os.Create(filepath.Join(dir, "stacktrace.out")) if err != nil { diff --git a/cmd/tendermint/commands/debug/util.go b/cmd/tendermint/commands/debug/util.go index 4c1fa2e75..089817f2f 100644 --- a/cmd/tendermint/commands/debug/util.go +++ b/cmd/tendermint/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) - resp, err := http.Get(endpoint) // nolint: gosec + resp, err := http.Get(endpoint) //nolint: gosec if err != nil { return fmt.Errorf("failed to query for %s profile: %w", profile, err) } diff --git a/config/config_test.go b/config/config_test.go index 2446f08e6..86b32c768 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -141,7 +141,7 @@ func TestBlockSyncConfigValidateBasic(t *testing.T) { } func TestConsensusConfig_ValidateBasic(t *testing.T) { - // nolint: lll + //nolint: lll testcases := map[string]struct { modify func(*ConsensusConfig) expectErr bool diff --git a/consensus/metrics.go b/consensus/metrics.go index ce6de0a3c..a2ee039d1 100644 --- a/consensus/metrics.go +++ b/consensus/metrics.go @@ -5,6 +5,7 @@ import ( "time" "github.com/go-kit/kit/metrics" + cstypes "github.com/tendermint/tendermint/consensus/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/tendermint/tendermint/types" diff --git a/consensus/msgs_test.go b/consensus/msgs_test.go index b1f32e67d..296f6b12a 100644 --- a/consensus/msgs_test.go +++ b/consensus/msgs_test.go @@ -314,7 +314,7 @@ func TestWALMsgProto(t *testing.T) { } } -// nolint:lll //ignore line length for tests +//nolint:lll //ignore line length for tests func TestConsMsgsVectors(t *testing.T) { date := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC) psh := types.PartSetHeader{ diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index 8235b2bf8..ce8353810 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -692,7 +692,7 @@ func capture() { // Ensure basic validation of structs is functioning func TestNewRoundStepMessageValidateBasic(t *testing.T) { - testCases := []struct { // nolint: maligned + testCases := []struct { //nolint: maligned expectErr bool messageRound int32 messageLastCommitRound int32 @@ -731,7 +731,7 @@ func TestNewRoundStepMessageValidateBasic(t *testing.T) { func TestNewRoundStepMessageValidateHeight(t *testing.T) { initialHeight := int64(10) - testCases := []struct { // nolint: maligned + testCases := []struct { //nolint: maligned expectErr bool messageLastCommitRound int32 messageHeight int64 @@ -881,7 +881,7 @@ func TestHasVoteMessageValidateBasic(t *testing.T) { invalidSignedMsgType tmproto.SignedMsgType = 0x03 ) - testCases := []struct { // nolint: maligned + testCases := []struct { //nolint: maligned expectErr bool messageRound int32 messageIndex int32 @@ -926,7 +926,7 @@ func TestVoteSetMaj23MessageValidateBasic(t *testing.T) { }, } - testCases := []struct { // nolint: maligned + testCases := []struct { //nolint: maligned expectErr bool messageRound int32 messageHeight int64 diff --git a/consensus/replay_test.go b/consensus/replay_test.go index e4ecf785d..cfc23898e 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -292,7 +292,7 @@ func (w *crashingWAL) Start() error { return w.next.Start() } func (w *crashingWAL) Stop() error { return w.next.Stop() } func (w *crashingWAL) Wait() { w.next.Wait() } -//------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------ type testSim struct { GenesisState sm.State Config *cfg.Config diff --git a/consensus/state.go b/consensus/state.go index 949742d12..9375abc40 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -2006,7 +2006,7 @@ func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) { // If the vote height is off, we'll just ignore it, // But if it's a conflicting sig, add it to the cs.evpool. // If it's otherwise invalid, punish peer. - // nolint: gocritic + //nolint: gocritic if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok { if cs.privValidatorPubKey == nil { return false, errPubKeyIsNotSet diff --git a/crypto/armor/armor.go b/crypto/armor/armor.go index 3f346ff75..99e2c3b3a 100644 --- a/crypto/armor/armor.go +++ b/crypto/armor/armor.go @@ -5,7 +5,7 @@ import ( "fmt" "io" - "golang.org/x/crypto/openpgp/armor" // nolint: staticcheck + "golang.org/x/crypto/openpgp/armor" //nolint: staticcheck ) func EncodeArmor(blockType string, headers map[string]string, data []byte) string { diff --git a/crypto/merkle/doc.go b/crypto/merkle/doc.go index 865c30217..fe50b3463 100644 --- a/crypto/merkle/doc.go +++ b/crypto/merkle/doc.go @@ -12,20 +12,19 @@ second pre-image attacks. Hence, use this library with caution. Otherwise you might run into similar issues as, e.g., in early Bitcoin: https://bitcointalk.org/?topic=102395 - * - / \ - / \ - / \ - / \ - * * - / \ / \ - / \ / \ - / \ / \ - * * * h6 - / \ / \ / \ - h0 h1 h2 h3 h4 h5 + * + / \ + / \ + / \ + / \ + * * + / \ / \ + / \ / \ + / \ / \ + * * * h6 + / \ / \ / \ + h0 h1 h2 h3 h4 h5 TODO(ismail): add 2nd pre-image protection or clarify further on how we use this and why this secure. - */ package merkle diff --git a/crypto/merkle/proof_value.go b/crypto/merkle/proof_value.go index ab776216b..842dc8201 100644 --- a/crypto/merkle/proof_value.go +++ b/crypto/merkle/proof_value.go @@ -85,8 +85,8 @@ func (op ValueOp) Run(args [][]byte) ([][]byte, error) { bz := new(bytes.Buffer) // Wrap to hash the KVPair. - encodeByteSlice(bz, op.key) // nolint: errcheck // does not error - encodeByteSlice(bz, vhash) // nolint: errcheck // does not error + encodeByteSlice(bz, op.key) //nolint: errcheck // does not error + encodeByteSlice(bz, vhash) //nolint: errcheck // does not error kvhash := leafHash(bz.Bytes()) if !bytes.Equal(kvhash, op.Proof.LeafHash) { diff --git a/crypto/merkle/tree.go b/crypto/merkle/tree.go index 466c43482..089c2f82e 100644 --- a/crypto/merkle/tree.go +++ b/crypto/merkle/tree.go @@ -47,10 +47,10 @@ func HashFromByteSlices(items [][]byte) []byte { // // These preliminary results suggest: // -// 1. The performance of the HashFromByteSlice is pretty good -// 2. Go has low overhead for recursive functions -// 3. The performance of the HashFromByteSlice routine is dominated -// by the actual hashing of data +// 1. The performance of the HashFromByteSlice is pretty good +// 2. Go has low overhead for recursive functions +// 3. The performance of the HashFromByteSlice routine is dominated +// by the actual hashing of data // // Although this work is in no way exhaustive, point #3 suggests that // optimization of this routine would need to take an alternative diff --git a/crypto/secp256k1/secp256k1.go b/crypto/secp256k1/secp256k1.go index 0fbd9ad2d..21073bea1 100644 --- a/crypto/secp256k1/secp256k1.go +++ b/crypto/secp256k1/secp256k1.go @@ -9,13 +9,13 @@ import ( "math/big" secp256k1 "github.com/btcsuite/btcd/btcec" - "golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format + "golang.org/x/crypto/ripemd160" //nolint: staticcheck // necessary for Bitcoin address format "github.com/tendermint/tendermint/crypto" tmjson "github.com/tendermint/tendermint/libs/json" ) -//------------------------------------- +// ------------------------------------- const ( PrivKeyName = "tendermint/PrivKeySecp256k1" PubKeyName = "tendermint/PubKeySecp256k1" @@ -124,8 +124,8 @@ func GenPrivKeySecp256k1(secret []byte) PrivKey { // used to reject malleable signatures // see: -// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93 -// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39 +// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93 +// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39 var secp256k1halfN = new(big.Int).Rsh(secp256k1.S256().N, 1) // Sign creates an ECDSA signature on curve Secp256k1, using SHA256 on the msg. diff --git a/evidence/pool.go b/evidence/pool.go index 4d82de971..7a5e4f3d5 100644 --- a/evidence/pool.go +++ b/evidence/pool.go @@ -97,11 +97,11 @@ func (evpool *Pool) PendingEvidence(maxBytes int64) ([]types.Evidence, int64) { // Update takes both the new state and the evidence committed at that height and performs // the following operations: -// 1. Take any conflicting votes from consensus and use the state's LastBlockTime to form -// DuplicateVoteEvidence and add it to the pool. -// 2. Update the pool's state which contains evidence params relating to expiry. -// 3. Moves pending evidence that has now been committed into the committed pool. -// 4. Removes any expired evidence based on both height and time. +// 1. Take any conflicting votes from consensus and use the state's LastBlockTime to form +// DuplicateVoteEvidence and add it to the pool. +// 2. Update the pool's state which contains evidence params relating to expiry. +// 3. Moves pending evidence that has now been committed into the committed pool. +// 4. Removes any expired evidence based on both height and time. func (evpool *Pool) Update(state sm.State, ev types.EvidenceList) { // sanity check if state.LastBlockHeight <= evpool.state.LastBlockHeight { diff --git a/evidence/reactor_test.go b/evidence/reactor_test.go index 4f8e73261..a2d82bf71 100644 --- a/evidence/reactor_test.go +++ b/evidence/reactor_test.go @@ -369,7 +369,7 @@ func exampleVote(t byte) *types.Vote { } } -// nolint:lll //ignore line length for tests +//nolint:lll //ignore line length for tests func TestEvidenceVectors(t *testing.T) { val := &types.Validator{ diff --git a/evidence/verify.go b/evidence/verify.go index f3eba5358..c20cb0a2d 100644 --- a/evidence/verify.go +++ b/evidence/verify.go @@ -102,13 +102,14 @@ func (evpool *Pool) verify(evidence types.Evidence) error { // VerifyLightClientAttack verifies LightClientAttackEvidence against the state of the full node. This involves // the following checks: -// - the common header from the full node has at least 1/3 voting power which is also present in -// the conflicting header's commit -// - 2/3+ of the conflicting validator set correctly signed the conflicting block -// - the nodes trusted header at the same height as the conflicting header has a different hash +// - the common header from the full node has at least 1/3 voting power which is also present in +// the conflicting header's commit +// - 2/3+ of the conflicting validator set correctly signed the conflicting block +// - the nodes trusted header at the same height as the conflicting header has a different hash // // CONTRACT: must run ValidateBasic() on the evidence before verifying -// must check that the evidence has not expired (i.e. is outside the maximum age threshold) +// +// must check that the evidence has not expired (i.e. is outside the maximum age threshold) func VerifyLightClientAttack(e *types.LightClientAttackEvidence, commonHeader, trustedHeader *types.SignedHeader, commonVals *types.ValidatorSet, now time.Time, trustPeriod time.Duration) error { // In the case of lunatic attack there will be a different commonHeader height. Therefore the node perform a single @@ -154,10 +155,10 @@ func VerifyLightClientAttack(e *types.LightClientAttackEvidence, commonHeader, t // VerifyDuplicateVote verifies DuplicateVoteEvidence against the state of full node. This involves the // following checks: -// - the validator is in the validator set at the height of the evidence -// - the height, round, type and validator address of the votes must be the same -// - the block ID's must be different -// - The signatures must both be valid +// - the validator is in the validator set at the height of the evidence +// - the height, round, type and validator address of the votes must be the same +// - the block ID's must be different +// - The signatures must both be valid func VerifyDuplicateVote(e *types.DuplicateVoteEvidence, chainID string, valSet *types.ValidatorSet) error { _, val := valSet.GetByAddress(e.VoteA.ValidatorAddress) if val == nil { diff --git a/internal/test/factory_test.go b/internal/test/factory_test.go index 6231cc7cc..221e4d130 100644 --- a/internal/test/factory_test.go +++ b/internal/test/factory_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/types" ) diff --git a/libs/cli/flags/log_level.go b/libs/cli/flags/log_level.go index d96ad3f47..706305300 100644 --- a/libs/cli/flags/log_level.go +++ b/libs/cli/flags/log_level.go @@ -17,7 +17,8 @@ const ( // all other modules). // // Example: -// ParseLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout), "info") +// +// ParseLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout), "info") func ParseLogLevel(lvl string, logger log.Logger, defaultLogLevelValue string) (log.Logger, error) { if lvl == "" { return nil, errors.New("empty log level") diff --git a/libs/clist/clist.go b/libs/clist/clist.go index 5579b1d0f..2e4171b1c 100644 --- a/libs/clist/clist.go +++ b/libs/clist/clist.go @@ -24,7 +24,6 @@ import ( const MaxLength = int(^uint(0) >> 1) /* - CElement is an element of a linked-list Traversal from a CElement is goroutine-safe. @@ -41,7 +40,6 @@ the for-loop. Use sync.Cond when you need serial access to the "condition". In our case our condition is if `next != nil || removed`, and there's no reason to serialize that condition for goroutines waiting on NextWait() (since it's just a read operation). - */ type CElement struct { mtx tmsync.RWMutex diff --git a/libs/clist/clist_test.go b/libs/clist/clist_test.go index d10a1e5ae..ccb50ca83 100644 --- a/libs/clist/clist_test.go +++ b/libs/clist/clist_test.go @@ -68,6 +68,7 @@ func TestSmall(t *testing.T) { // This test is quite hacky because it relies on SetFinalizer // which isn't guaranteed to run at all. +// //nolint:unused,deadcode func _TestGCFifo(t *testing.T) { if runtime.GOARCH != "amd64" { @@ -117,6 +118,7 @@ func _TestGCFifo(t *testing.T) { // This test is quite hacky because it relies on SetFinalizer // which isn't guaranteed to run at all. +// //nolint:unused,deadcode func _TestGCRandom(t *testing.T) { if runtime.GOARCH != "amd64" { diff --git a/libs/flowrate/flowrate.go b/libs/flowrate/flowrate.go index c7ba93282..fdc168d18 100644 --- a/libs/flowrate/flowrate.go +++ b/libs/flowrate/flowrate.go @@ -39,10 +39,10 @@ type Monitor struct { // weight of each sample in the exponential moving average (EMA) calculation. // The exact formulas are: // -// sampleTime = currentTime - prevSampleTime -// sampleRate = byteCount / sampleTime -// weight = 1 - exp(-sampleTime/windowSize) -// newRate = weight*sampleRate + (1-weight)*oldRate +// sampleTime = currentTime - prevSampleTime +// sampleRate = byteCount / sampleTime +// weight = 1 - exp(-sampleTime/windowSize) +// newRate = weight*sampleRate + (1-weight)*oldRate // // The default values for sampleRate and windowSize (if <= 0) are 100ms and 1s, // respectively. diff --git a/libs/json/doc.go b/libs/json/doc.go index d5ef4047f..1b92c0db6 100644 --- a/libs/json/doc.go +++ b/libs/json/doc.go @@ -13,12 +13,12 @@ // compatibility with e.g. Javascript (which uses 64-bit floats for numbers, having 53-bit // precision): // -// int32(32) // Output: 32 -// uint32(32) // Output: 32 -// int64(64) // Output: "64" -// uint64(64) // Output: "64" -// int(64) // Output: "64" -// uint(64) // Output: "64" +// int32(32) // Output: 32 +// uint32(32) // Output: 32 +// int64(64) // Output: "64" +// uint64(64) // Output: "64" +// int(64) // Output: "64" +// uint(64) // Output: "64" // // Encoding of other scalars follows encoding/json: // @@ -50,7 +50,7 @@ // Times are encoded as encoding/json, in RFC3339Nano format, but requiring UTC time zone (with zero // times emitted as "0001-01-01T00:00:00Z" as with encoding/json): // -// time.Date(2020, 6, 8, 16, 21, 28, 123, time.FixedZone("UTC+2", 2*60*60)) +// time.Date(2020, 6, 8, 16, 21, 28, 123, time.FixedZone("UTC+2", 2*60*60)) // // Output: "2020-06-08T14:21:28.000000123Z" // time.Time{} // Output: "0001-01-01T00:00:00Z" // (*time.Time)(nil) // Output: null @@ -95,5 +95,4 @@ // // Struct{Car: &Car{Wheels: 4}, Vehicle: &Car{Wheels: 4}} // // Output: {"Car": {"Wheels: 4"}, "Vehicle": {"type":"vehicle/car","value":{"Wheels":4}}} -// package json diff --git a/libs/log/filter.go b/libs/log/filter.go index e39a85dcb..4b7ed981c 100644 --- a/libs/log/filter.go +++ b/libs/log/filter.go @@ -69,18 +69,19 @@ func (l *filter) Error(msg string, keyvals ...interface{}) { // Allow*With methods, it is used as the logger's level. // // Examples: -// logger = log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("module", "crypto")) -// logger.With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto" // -// logger = log.NewFilter(logger, log.AllowError(), -// log.AllowInfoWith("module", "crypto"), -// log.AllowNoneWith("user", "Sam")) -// logger.With("module", "crypto", "user", "Sam").Info("Hello") # returns nil +// logger = log.NewFilter(logger, log.AllowError(), log.AllowInfoWith("module", "crypto")) +// logger.With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto" // -// logger = log.NewFilter(logger, -// log.AllowError(), -// log.AllowInfoWith("module", "crypto"), log.AllowNoneWith("user", "Sam")) -// logger.With("user", "Sam").With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto user=Sam" +// logger = log.NewFilter(logger, log.AllowError(), +// log.AllowInfoWith("module", "crypto"), +// log.AllowNoneWith("user", "Sam")) +// logger.With("module", "crypto", "user", "Sam").Info("Hello") # returns nil +// +// logger = log.NewFilter(logger, +// log.AllowError(), +// log.AllowInfoWith("module", "crypto"), log.AllowNoneWith("user", "Sam")) +// logger.With("user", "Sam").With("module", "crypto").Info("Hello") # produces "I... Hello module=crypto user=Sam" func (l *filter) With(keyvals ...interface{}) Logger { keyInAllowedKeyvals := false diff --git a/libs/log/logger.go b/libs/log/logger.go index 9b1a65d42..34aca8af5 100644 --- a/libs/log/logger.go +++ b/libs/log/logger.go @@ -22,9 +22,9 @@ type Logger interface { // // If w implements the following interface, so does the returned writer. // -// interface { -// Fd() uintptr -// } +// interface { +// Fd() uintptr +// } func NewSyncWriter(w io.Writer) io.Writer { return kitlog.NewSyncWriter(w) } diff --git a/libs/log/tmfmt_logger.go b/libs/log/tmfmt_logger.go index 391ae478a..492c1c12e 100644 --- a/libs/log/tmfmt_logger.go +++ b/libs/log/tmfmt_logger.go @@ -65,7 +65,7 @@ func (l tmfmtLogger) Log(keyvals ...interface{}) error { switch keyvals[i] { case kitlevel.Key(): excludeIndexes = append(excludeIndexes, i) - switch keyvals[i+1].(type) { // nolint:gocritic + switch keyvals[i+1].(type) { //nolint:gocritic case string: lvl = keyvals[i+1].(string) case kitlevel.Value: diff --git a/libs/log/tmfmt_logger_test.go b/libs/log/tmfmt_logger_test.go index 12c2fbbc4..7e64197cf 100644 --- a/libs/log/tmfmt_logger_test.go +++ b/libs/log/tmfmt_logger_test.go @@ -83,10 +83,9 @@ func benchmarkRunnerKitlog(b *testing.B, logger kitlog.Logger, f func(kitlog.Log } } -//nolint: errcheck // ignore errors var ( - baseMessage = func(logger kitlog.Logger) { logger.Log("foo_key", "foo_value") } - withMessage = func(logger kitlog.Logger) { kitlog.With(logger, "a", "b").Log("d", "f") } + baseMessage = func(logger kitlog.Logger) { logger.Log("foo_key", "foo_value") } //nolint:errcheck + withMessage = func(logger kitlog.Logger) { kitlog.With(logger, "a", "b").Log("d", "f") } //nolint:errcheck ) // These test are designed to be run with the race detector. diff --git a/libs/pubsub/pubsub.go b/libs/pubsub/pubsub.go index 5f9226c90..321e775c8 100644 --- a/libs/pubsub/pubsub.go +++ b/libs/pubsub/pubsub.go @@ -12,25 +12,25 @@ // // Example: // -// q, err := query.New("account.name='John'") -// if err != nil { -// return err -// } -// ctx, cancel := context.WithTimeout(context.Background(), 1 * time.Second) -// defer cancel() -// subscription, err := pubsub.Subscribe(ctx, "johns-transactions", q) -// if err != nil { -// return err -// } +// q, err := query.New("account.name='John'") +// if err != nil { +// return err +// } +// ctx, cancel := context.WithTimeout(context.Background(), 1 * time.Second) +// defer cancel() +// subscription, err := pubsub.Subscribe(ctx, "johns-transactions", q) +// if err != nil { +// return err +// } // -// for { -// select { -// case msg <- subscription.Out(): -// // handle msg.Data() and msg.Events() -// case <-subscription.Cancelled(): -// return subscription.Err() -// } -// } +// for { +// select { +// case msg <- subscription.Out(): +// // handle msg.Data() and msg.Events() +// case <-subscription.Cancelled(): +// return subscription.Err() +// } +// } package pubsub import ( diff --git a/libs/pubsub/query/query.go b/libs/pubsub/query/query.go index 0643bc3cb..7495b11ac 100644 --- a/libs/pubsub/query/query.go +++ b/libs/pubsub/query/query.go @@ -1,6 +1,6 @@ // Package query provides a parser for a custom query format: // -// abci.invoice.number=22 AND abci.invoice.owner=Ivan +// abci.invoice.number=22 AND abci.invoice.owner=Ivan // // See query.peg for the grammar, which is a https://en.wikipedia.org/wiki/Parsing_expression_grammar. // More: https://github.com/PhilippeSigaud/Pegged/wiki/PEG-Basics diff --git a/libs/pubsub/subscription.go b/libs/pubsub/subscription.go index 8f90e177a..141569310 100644 --- a/libs/pubsub/subscription.go +++ b/libs/pubsub/subscription.go @@ -43,9 +43,10 @@ func (s *Subscription) Out() <-chan Message { return s.out } -// nolint: misspell // Cancelled returns a channel that's closed when the subscription is // terminated and supposed to be used in a select statement. +// +//nolint:misspell func (s *Subscription) Cancelled() <-chan struct{} { return s.canceled } @@ -54,7 +55,8 @@ func (s *Subscription) Cancelled() <-chan struct{} { // If the channel is closed, Err returns a non-nil error explaining why: // - ErrUnsubscribed if the subscriber choose to unsubscribe, // - ErrOutOfCapacity if the subscriber is not pulling messages fast enough -// and the channel returned by Out became full, +// and the channel returned by Out became full, +// // After Err returns a non-nil error, successive calls to Err return the same // error. func (s *Subscription) Err() error { diff --git a/libs/rand/random.go b/libs/rand/random.go index 41d04a440..05af30f1a 100644 --- a/libs/rand/random.go +++ b/libs/rand/random.go @@ -48,7 +48,7 @@ func (r *Rand) init() { } func (r *Rand) reset(seed int64) { - r.rand = mrand.New(mrand.NewSource(seed)) // nolint:gosec // G404: Use of weak random number generator + r.rand = mrand.New(mrand.NewSource(seed)) //nolint:gosec } //---------------------------------------- diff --git a/light/detector.go b/light/detector.go index 881242135..1fd21f41e 100644 --- a/light/detector.go +++ b/light/detector.go @@ -109,7 +109,9 @@ func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.Lig // // 1: errConflictingHeaders -> there may have been an attack on this light client // 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one -// Note: In the case of an invalid header we remove the witness +// +// Note: In the case of an invalid header we remove the witness +// // 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) { @@ -275,16 +277,16 @@ func (c *Client) handleConflictingHeaders( // it has received from another and preforms verifySkipping at the heights of each of the intermediate // headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen. // -// 1. The light client verifies a header that is different to the intermediate header in the trace. This -// is the bifurcation point and the light client can create evidence from it -// 2. The source stops responding, doesn't have the block or sends an invalid header in which case we -// return the error and remove the witness +// 1. The light client verifies a header that is different to the intermediate header in the trace. This +// is the bifurcation point and the light client can create evidence from it +// 2. The source stops responding, doesn't have the block or sends an invalid header in which case we +// return the error and remove the witness // // CONTRACT: -// 1. Trace can not be empty len(trace) > 0 -// 2. The last block in the trace can not be of a lower height than the target block -// trace[len(trace)-1].Height >= targetBlock.Height -// 3. The +// 1. Trace can not be empty len(trace) > 0 +// 2. The last block in the trace can not be of a lower height than the target block +// trace[len(trace)-1].Height >= targetBlock.Height +// 3. The func (c *Client) examineConflictingHeaderAgainstTrace( ctx context.Context, trace []*types.LightBlock, diff --git a/light/provider/http/http.go b/light/provider/http/http.go index dcf1b0d10..7e6292430 100644 --- a/light/provider/http/http.go +++ b/light/provider/http/http.go @@ -216,6 +216,6 @@ func validateHeight(height int64) (*int64, error) { // exponential backoff (with jitter) // 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 + //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/proxy/routes.go b/light/proxy/routes.go index 2f53c8808..a641268eb 100644 --- a/light/proxy/routes.go +++ b/light/proxy/routes.go @@ -62,7 +62,6 @@ func makeHealthFunc(c *lrpc.Client) rpcHealthFunc { type rpcStatusFunc func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) -// nolint: interfacer func makeStatusFunc(c *lrpc.Client) rpcStatusFunc { return func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) { return c.Status(ctx.Context()) @@ -259,8 +258,8 @@ type rpcABCIQueryFunc func(ctx *rpctypes.Context, path string, func makeABCIQueryFunc(c *lrpc.Client) rpcABCIQueryFunc { return func(ctx *rpctypes.Context, path string, data bytes.HexBytes, - height int64, prove bool) (*ctypes.ResultABCIQuery, error) { - + height int64, prove bool, + ) (*ctypes.ResultABCIQuery, error) { return c.ABCIQueryWithOptions(ctx.Context(), path, data, rpcclient.ABCIQueryOptions{ Height: height, Prove: prove, @@ -278,7 +277,6 @@ func makeABCIInfoFunc(c *lrpc.Client) rpcABCIInfoFunc { type rpcBroadcastEvidenceFunc func(ctx *rpctypes.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) -// nolint: interfacer func makeBroadcastEvidenceFunc(c *lrpc.Client) rpcBroadcastEvidenceFunc { return func(ctx *rpctypes.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) { return c.BroadcastEvidence(ctx.Context(), ev) diff --git a/light/rpc/client.go b/light/rpc/client.go index bc83eb336..0639d20eb 100644 --- a/light/rpc/client.go +++ b/light/rpc/client.go @@ -27,6 +27,7 @@ var errNegOrZeroHeight = errors.New("negative or zero height") type KeyPathFunc func(path string, key []byte) (merkle.KeyPath, error) // LightClient is an interface that contains functionality needed by Client from the light client. +// //go:generate ../../scripts/mockery_generate.sh LightClient type LightClient interface { ChainID() string diff --git a/light/verifier.go b/light/verifier.go index 0b0a4926b..2ec02e877 100644 --- a/light/verifier.go +++ b/light/verifier.go @@ -19,13 +19,13 @@ var ( // VerifyNonAdjacent verifies non-adjacent untrustedHeader against // trustedHeader. It ensures that: // -// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned) -// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned) -// c) trustLevel ([1/3, 1]) of trustedHeaderVals (or trustedHeaderNextVals) -// signed correctly (if not, ErrNewValSetCantBeTrusted is returned) -// d) more than 2/3 of untrustedVals have signed h2 -// (otherwise, ErrInvalidHeader is returned) -// e) headers are non-adjacent. +// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned) +// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned) +// c) trustLevel ([1/3, 1]) of trustedHeaderVals (or trustedHeaderNextVals) +// signed correctly (if not, ErrNewValSetCantBeTrusted is returned) +// d) more than 2/3 of untrustedVals have signed h2 +// (otherwise, ErrInvalidHeader is returned) +// e) headers are non-adjacent. // // maxClockDrift defines how much untrustedHeader.Time can drift into the // future. @@ -81,12 +81,12 @@ func VerifyNonAdjacent( // VerifyAdjacent verifies directly adjacent untrustedHeader against // trustedHeader. It ensures that: // -// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned) -// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned) -// c) untrustedHeader.ValidatorsHash equals trustedHeader.NextValidatorsHash -// d) more than 2/3 of new validators (untrustedVals) have signed h2 -// (otherwise, ErrInvalidHeader is returned) -// e) headers are adjacent. +// a) trustedHeader can still be trusted (if not, ErrOldHeaderExpired is returned) +// b) untrustedHeader is valid (if not, ErrInvalidHeader is returned) +// c) untrustedHeader.ValidatorsHash equals trustedHeader.NextValidatorsHash +// d) more than 2/3 of new validators (untrustedVals) have signed h2 +// (otherwise, ErrInvalidHeader is returned) +// e) headers are adjacent. // // maxClockDrift defines how much untrustedHeader.Time can drift into the // future. @@ -212,12 +212,12 @@ func HeaderExpired(h *types.SignedHeader, trustingPeriod time.Duration, now time // VerifyBackwards verifies an untrusted header with a height one less than // that of an adjacent trusted header. It ensures that: // -// a) untrusted header is valid -// b) untrusted header has a time before the trusted header -// c) that the LastBlockID hash of the trusted header is the same as the hash -// of the trusted header +// a) untrusted header is valid +// b) untrusted header has a time before the trusted header +// c) that the LastBlockID hash of the trusted header is the same as the hash +// of the trusted header // -// For any of these cases ErrInvalidHeader is returned. +// For any of these cases ErrInvalidHeader is returned. func VerifyBackwards(untrustedHeader, trustedHeader *types.Header) error { if err := untrustedHeader.ValidateBasic(); err != nil { return ErrInvalidHeader{err} diff --git a/mempool/v0/clist_mempool.go b/mempool/v0/clist_mempool.go index 4695eed17..516a57f22 100644 --- a/mempool/v0/clist_mempool.go +++ b/mempool/v0/clist_mempool.go @@ -194,7 +194,9 @@ func (mem *CListMempool) TxsWaitChan() <-chan struct{} { // It blocks if we're waiting on Update() or Reap(). // cb: A callback from the CheckTx command. -// It gets called from another goroutine. +// +// It gets called from another goroutine. +// // CONTRACT: Either cb will get called, or err returned. // // Safe for concurrent use by multiple goroutines. @@ -310,7 +312,7 @@ func (mem *CListMempool) reqResCb( } // Called from: -// - resCbFirstTime (lock not held) if tx is valid +// - resCbFirstTime (lock not held) if tx is valid func (mem *CListMempool) addTx(memTx *mempoolTx) { e := mem.txs.PushBack(memTx) mem.txsMap.Store(memTx.tx.Key(), e) @@ -319,8 +321,8 @@ func (mem *CListMempool) addTx(memTx *mempoolTx) { } // Called from: -// - Update (lock held) if tx was committed -// - resCbRecheck (lock not held) if tx was invalidated +// - Update (lock held) if tx was committed +// - resCbRecheck (lock not held) if tx was invalidated func (mem *CListMempool) removeTx(tx types.Tx, elem *clist.CElement, removeFromCache bool) { mem.txs.Remove(elem) elem.DetachPrev() diff --git a/node/doc.go b/node/doc.go index 08f3fa258..3a145c573 100644 --- a/node/doc.go +++ b/node/doc.go @@ -6,35 +6,34 @@ Adding new p2p.Reactor(s) To add a new p2p.Reactor, use the CustomReactors option: - node, err := NewNode( - config, - privVal, - nodeKey, - clientCreator, - genesisDocProvider, - dbProvider, - metricsProvider, - logger, - CustomReactors(map[string]p2p.Reactor{"CUSTOM": customReactor}), - ) + node, err := NewNode( + config, + privVal, + nodeKey, + clientCreator, + genesisDocProvider, + dbProvider, + metricsProvider, + logger, + CustomReactors(map[string]p2p.Reactor{"CUSTOM": customReactor}), + ) Replacing existing p2p.Reactor(s) To replace the built-in p2p.Reactor, use the CustomReactors option: - node, err := NewNode( - config, - privVal, - nodeKey, - clientCreator, - genesisDocProvider, - dbProvider, - metricsProvider, - logger, - CustomReactors(map[string]p2p.Reactor{"BLOCKCHAIN": customBlockchainReactor}), - ) + node, err := NewNode( + config, + privVal, + nodeKey, + clientCreator, + genesisDocProvider, + dbProvider, + metricsProvider, + logger, + CustomReactors(map[string]p2p.Reactor{"BLOCKCHAIN": customBlockchainReactor}), + ) The list of existing reactors can be found in CustomReactors documentation. - */ package node diff --git a/node/node.go b/node/node.go index 304bed154..e40b72e99 100644 --- a/node/node.go +++ b/node/node.go @@ -51,7 +51,7 @@ import ( tmtime "github.com/tendermint/tendermint/types/time" "github.com/tendermint/tendermint/version" - _ "net/http/pprof" // nolint: gosec // securely exposed on separate, optional port + _ "net/http/pprof" //nolint: gosec // securely exposed on separate, optional port _ "github.com/lib/pq" // provide the psql db driver ) @@ -145,12 +145,12 @@ type blockSyncReactor interface { // WARNING: using any name from the below list of the existing reactors will // result in replacing it with the custom one. // -// - MEMPOOL -// - BLOCKCHAIN -// - CONSENSUS -// - EVIDENCE -// - PEX -// - STATESYNC +// - MEMPOOL +// - BLOCKCHAIN +// - CONSENSUS +// - EVIDENCE +// - PEX +// - STATESYNC func CustomReactors(reactors map[string]p2p.Reactor) Option { return func(n *Node) { for name, reactor := range reactors { @@ -272,7 +272,6 @@ func createAndStartIndexerService( eventBus *types.EventBus, logger log.Logger, ) (*txindex.IndexerService, txindex.TxIndexer, indexer.BlockIndexer, error) { - var ( txIndexer txindex.TxIndexer blockIndexer indexer.BlockIndexer @@ -321,8 +320,8 @@ func doHandshake( genDoc *types.GenesisDoc, eventBus types.BlockEventPublisher, proxyApp proxy.AppConns, - consensusLogger log.Logger) error { - + consensusLogger log.Logger, +) error { handshaker := cs.NewHandshaker(stateStore, state, blockStore, genDoc) handshaker.SetLogger(consensusLogger) handshaker.SetEventBus(eventBus) @@ -372,7 +371,6 @@ func createMempoolAndMempoolReactor( memplMetrics *mempl.Metrics, logger log.Logger, ) (mempl.Mempool, p2p.Reactor) { - switch config.Mempool.Version { case cfg.MempoolV1: mp := mempoolv1.NewTxMempool( @@ -423,8 +421,8 @@ func createMempoolAndMempoolReactor( } func createEvidenceReactor(config *cfg.Config, dbProvider DBProvider, - stateDB dbm.DB, blockStore *store.BlockStore, logger log.Logger) (*evidence.Reactor, *evidence.Pool, error) { - + stateDB dbm.DB, blockStore *store.BlockStore, logger log.Logger, +) (*evidence.Reactor, *evidence.Pool, error) { evidenceDB, err := dbProvider(&DBContext{"evidence", config}) if err != nil { return nil, nil, err @@ -446,8 +444,8 @@ func createBlockchainReactor(config *cfg.Config, blockExec *sm.BlockExecutor, blockStore *store.BlockStore, blockSync bool, - logger log.Logger) (bcReactor p2p.Reactor, err error) { - + logger log.Logger, +) (bcReactor p2p.Reactor, err error) { switch config.BlockSync.Version { case "v0": bcReactor = bc.NewReactor(state.Copy(), blockExec, blockStore, blockSync) @@ -471,8 +469,8 @@ func createConsensusReactor(config *cfg.Config, csMetrics *cs.Metrics, waitSync bool, eventBus *types.EventBus, - consensusLogger log.Logger) (*cs.Reactor, *cs.State) { - + consensusLogger log.Logger, +) (*cs.Reactor, *cs.State) { consensusState := cs.NewState( config.Consensus, state.Copy(), @@ -574,8 +572,8 @@ func createSwitch(config *cfg.Config, evidenceReactor *evidence.Reactor, nodeInfo p2p.NodeInfo, nodeKey *p2p.NodeKey, - p2pLogger log.Logger) *p2p.Switch { - + p2pLogger log.Logger, +) *p2p.Switch { sw := p2p.NewSwitch( config.P2P, transport, @@ -597,8 +595,8 @@ func createSwitch(config *cfg.Config, } func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch, - p2pLogger log.Logger, nodeKey *p2p.NodeKey) (pex.AddrBook, error) { - + p2pLogger log.Logger, nodeKey *p2p.NodeKey, +) (pex.AddrBook, error) { addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict) addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile())) @@ -624,8 +622,8 @@ func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch, } func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config, - sw *p2p.Switch, logger log.Logger) *pex.Reactor { - + sw *p2p.Switch, logger log.Logger, +) *pex.Reactor { // TODO persistent peers ? so we can have their DNS addrs saved pexReactor := pex.NewReactor(addrBook, &pex.ReactorConfig{ @@ -647,7 +645,8 @@ func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config, // startStateSync starts an asynchronous state sync process, then switches to block sync mode. func startStateSync(ssR *statesync.Reactor, bcR blockSyncReactor, conR *cs.Reactor, stateProvider statesync.StateProvider, config *cfg.StateSyncConfig, blockSync bool, - stateStore sm.Store, blockStore *store.BlockStore, state sm.State) error { + stateStore sm.Store, blockStore *store.BlockStore, state sm.State, +) error { ssR.Logger.Info("Starting state sync") if stateProvider == nil { @@ -709,8 +708,8 @@ func NewNode(config *cfg.Config, dbProvider DBProvider, metricsProvider MetricsProvider, logger log.Logger, - options ...Option) (*Node, error) { - + options ...Option, +) (*Node, error) { blockStore, stateDB, err := initDBs(config, dbProvider) if err != nil { return nil, err @@ -1209,7 +1208,6 @@ func (n *Node) startRPC() ([]net.Listener, error) { } return listeners, nil - } // startPrometheusServer starts a Prometheus HTTP server, listening for metrics @@ -1370,9 +1368,7 @@ func makeNodeInfo( //------------------------------------------------------------------------------ -var ( - genesisDocKey = []byte("genesisDoc") -) +var genesisDocKey = []byte("genesisDoc") // LoadStateFromDBOrGenesisDocProvider attempts to load the state from the // database, or creates one using the given genesisDocProvider. On success this also diff --git a/p2p/conn/connection.go b/p2p/conn/connection.go index 44ff83893..318297a67 100644 --- a/p2p/conn/connection.go +++ b/p2p/conn/connection.go @@ -62,6 +62,7 @@ The byte id and the relative priorities of each `Channel` are configured upon initialization of the connection. There are two methods for sending messages: + func (m MConnection) Send(chID byte, msgBytes []byte) bool {} func (m MConnection) TrySend(chID byte, msgBytes []byte}) bool {} diff --git a/p2p/conn/connection_test.go b/p2p/conn/connection_test.go index c41a46c48..f59df3dc8 100644 --- a/p2p/conn/connection_test.go +++ b/p2p/conn/connection_test.go @@ -51,7 +51,7 @@ func TestMConnectionSendFlushStop(t *testing.T) { clientConn := createTestMConnection(client) err := clientConn.Start() require.Nil(t, err) - defer clientConn.Stop() // nolint:errcheck // ignore for tests + defer clientConn.Stop() //nolint:errcheck // ignore for tests msg := []byte("abc") assert.True(t, clientConn.Send(0x01, msg)) @@ -89,7 +89,7 @@ func TestMConnectionSend(t *testing.T) { mconn := createTestMConnection(client) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests msg := []byte("Ant-Man") assert.True(t, mconn.Send(0x01, msg)) @@ -128,12 +128,12 @@ func TestMConnectionReceive(t *testing.T) { mconn1 := createMConnectionWithCallbacks(client, onReceive, onError) err := mconn1.Start() require.Nil(t, err) - defer mconn1.Stop() // nolint:errcheck // ignore for tests + defer mconn1.Stop() //nolint:errcheck // ignore for tests mconn2 := createTestMConnection(server) err = mconn2.Start() require.Nil(t, err) - defer mconn2.Stop() // nolint:errcheck // ignore for tests + defer mconn2.Stop() //nolint:errcheck // ignore for tests msg := []byte("Cyclops") assert.True(t, mconn2.Send(0x01, msg)) @@ -156,7 +156,7 @@ func TestMConnectionStatus(t *testing.T) { mconn := createTestMConnection(client) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests status := mconn.Status() assert.NotNil(t, status) @@ -179,7 +179,7 @@ func TestMConnectionPongTimeoutResultsInError(t *testing.T) { mconn := createMConnectionWithCallbacks(client, onReceive, onError) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests serverGotPing := make(chan struct{}) go func() { @@ -218,7 +218,7 @@ func TestMConnectionMultiplePongsInTheBeginning(t *testing.T) { mconn := createMConnectionWithCallbacks(client, onReceive, onError) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests // sending 3 pongs in a row (abuse) protoWriter := protoio.NewDelimitedWriter(server) @@ -273,7 +273,7 @@ func TestMConnectionMultiplePings(t *testing.T) { mconn := createMConnectionWithCallbacks(client, onReceive, onError) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests // sending 3 pings in a row (abuse) // see https://github.com/tendermint/tendermint/issues/1190 @@ -322,7 +322,7 @@ func TestMConnectionPingPongs(t *testing.T) { mconn := createMConnectionWithCallbacks(client, onReceive, onError) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests serverGotPing := make(chan struct{}) go func() { @@ -380,7 +380,7 @@ func TestMConnectionStopsAndReturnsError(t *testing.T) { mconn := createMConnectionWithCallbacks(client, onReceive, onError) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests if err := client.Close(); err != nil { t.Error(err) @@ -492,8 +492,8 @@ func TestMConnectionReadErrorLongMessage(t *testing.T) { chOnRcv := make(chan struct{}) mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr) - defer mconnClient.Stop() // nolint:errcheck // ignore for tests - defer mconnServer.Stop() // nolint:errcheck // ignore for tests + defer mconnClient.Stop() //nolint:errcheck // ignore for tests + defer mconnServer.Stop() //nolint:errcheck // ignore for tests mconnServer.onReceive = func(chID byte, msgBytes []byte) { chOnRcv <- struct{}{} @@ -528,8 +528,8 @@ func TestMConnectionReadErrorLongMessage(t *testing.T) { func TestMConnectionReadErrorUnknownMsgType(t *testing.T) { chOnErr := make(chan struct{}) mconnClient, mconnServer := newClientAndServerConnsForReadErrors(t, chOnErr) - defer mconnClient.Stop() // nolint:errcheck // ignore for tests - defer mconnServer.Stop() // nolint:errcheck // ignore for tests + defer mconnClient.Stop() //nolint:errcheck // ignore for tests + defer mconnServer.Stop() //nolint:errcheck // ignore for tests // send msg with unknown msg type _, err := protoio.NewDelimitedWriter(mconnClient.conn).WriteMsg(&types.Header{ChainID: "x"}) @@ -545,7 +545,7 @@ func TestMConnectionTrySend(t *testing.T) { mconn := createTestMConnection(client) err := mconn.Start() require.Nil(t, err) - defer mconn.Stop() // nolint:errcheck // ignore for tests + defer mconn.Stop() //nolint:errcheck // ignore for tests msg := []byte("Semicolon-Woman") resultCh := make(chan string, 2) @@ -564,7 +564,7 @@ func TestMConnectionTrySend(t *testing.T) { assert.Equal(t, "TrySend", <-resultCh) } -// nolint:lll //ignore line length for tests +//nolint:lll //ignore line length for tests func TestConnVectors(t *testing.T) { testCases := []struct { diff --git a/p2p/fuzz.go b/p2p/fuzz.go index 0ada85ecc..e41e989bb 100644 --- a/p2p/fuzz.go +++ b/p2p/fuzz.go @@ -103,7 +103,7 @@ func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error { func (fc *FuzzedConnection) randomDuration() time.Duration { maxDelayMillis := int(fc.config.MaxDelay.Nanoseconds() / 1000) - return time.Millisecond * time.Duration(tmrand.Int()%maxDelayMillis) // nolint: gas + return time.Millisecond * time.Duration(tmrand.Int()%maxDelayMillis) //nolint: gas } // implements the fuzz (delay, kill conn) diff --git a/p2p/node_info_test.go b/p2p/node_info_test.go index 1bceb4a10..9c317f8a1 100644 --- a/p2p/node_info_test.go +++ b/p2p/node_info_test.go @@ -33,7 +33,7 @@ func TestNodeInfoValidate(t *testing.T) { }{ { "Too Many Channels", - func(ni *DefaultNodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, // nolint: gocritic + func(ni *DefaultNodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, //nolint: gocritic true, }, {"Duplicate Channel", func(ni *DefaultNodeInfo) { ni.Channels = dupChannels }, true}, diff --git a/p2p/pex/known_address.go b/p2p/pex/known_address.go index ee3df4255..33763c084 100644 --- a/p2p/pex/known_address.go +++ b/p2p/pex/known_address.go @@ -94,16 +94,16 @@ func (ka *knownAddress) removeBucketRef(bucketIdx int) int { } /* - An address is bad if the address in question is a New address, has not been tried in the last - minute, and meets one of the following criteria: +An address is bad if the address in question is a New address, has not been tried in the last +minute, and meets one of the following criteria: - 1) It claims to be from the future - 2) It hasn't been seen in over a week - 3) It has failed at least three times and never succeeded - 4) It has failed ten times in the last week +1) It claims to be from the future +2) It hasn't been seen in over a week +3) It has failed at least three times and never succeeded +4) It has failed ten times in the last week - All addresses that meet these criteria are assumed to be worthless and not - worth keeping hold of. +All addresses that meet these criteria are assumed to be worthless and not +worth keeping hold of. */ func (ka *knownAddress) isBad() bool { // Is Old --> good diff --git a/p2p/pex/pex_reactor_test.go b/p2p/pex/pex_reactor_test.go index 1ffd01342..a552bc098 100644 --- a/p2p/pex/pex_reactor_test.go +++ b/p2p/pex/pex_reactor_test.go @@ -58,6 +58,7 @@ func TestPEXReactorAddRemovePeer(t *testing.T) { } // --- FAIL: TestPEXReactorRunning (11.10s) +// // pex_reactor_test.go:411: expected all switches to be connected to at // least one peer (switches: 0 => {outbound: 1, inbound: 0}, 1 => // {outbound: 0, inbound: 1}, 2 => {outbound: 0, inbound: 0}, ) @@ -66,7 +67,6 @@ func TestPEXReactorAddRemovePeer(t *testing.T) { // if any peer (who we already connected to) has the same IP. Even though local // peers have different IP addresses, they all have the same underlying remote // IP: 127.0.0.1. -// func TestPEXReactorRunning(t *testing.T) { N := 3 switches := make([]*p2p.Switch, N) @@ -214,7 +214,7 @@ func TestCheckSeeds(t *testing.T) { // 1. test creating peer with no seeds works peerSwitch := testCreateDefaultPeer(dir, 0) require.Nil(t, peerSwitch.Start()) - peerSwitch.Stop() // nolint:errcheck // ignore for tests + peerSwitch.Stop() //nolint:errcheck // ignore for tests // 2. create seed seed := testCreateSeed(dir, 1, []*p2p.NetAddress{}, []*p2p.NetAddress{}) @@ -222,7 +222,7 @@ func TestCheckSeeds(t *testing.T) { // 3. test create peer with online seed works peerSwitch = testCreatePeerWithSeed(dir, 2, seed) require.Nil(t, peerSwitch.Start()) - peerSwitch.Stop() // nolint:errcheck // ignore for tests + peerSwitch.Stop() //nolint:errcheck // ignore for tests // 4. test create peer with all seeds having unresolvable DNS fails badPeerConfig := &ReactorConfig{ @@ -231,7 +231,7 @@ func TestCheckSeeds(t *testing.T) { } peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig) require.Error(t, peerSwitch.Start()) - peerSwitch.Stop() // nolint:errcheck // ignore for tests + peerSwitch.Stop() //nolint:errcheck // ignore for tests // 5. test create peer with one good seed address succeeds badPeerConfig = &ReactorConfig{ @@ -241,7 +241,7 @@ func TestCheckSeeds(t *testing.T) { } peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig) require.Nil(t, peerSwitch.Start()) - peerSwitch.Stop() // nolint:errcheck // ignore for tests + peerSwitch.Stop() //nolint:errcheck // ignore for tests } func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) { @@ -253,12 +253,12 @@ func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) { // 1. create seed seed := testCreateSeed(dir, 0, []*p2p.NetAddress{}, []*p2p.NetAddress{}) require.Nil(t, seed.Start()) - defer seed.Stop() // nolint:errcheck // ignore for tests + defer seed.Stop() //nolint:errcheck // ignore for tests // 2. create usual peer with only seed configured. peer := testCreatePeerWithSeed(dir, 1, seed) require.Nil(t, peer.Start()) - defer peer.Stop() // nolint:errcheck // ignore for tests + defer peer.Stop() //nolint:errcheck // ignore for tests // 3. check that the peer connects to seed immediately assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1) @@ -273,18 +273,18 @@ func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) { // 1. create peer peerSwitch := testCreateDefaultPeer(dir, 1) require.Nil(t, peerSwitch.Start()) - defer peerSwitch.Stop() // nolint:errcheck // ignore for tests + defer peerSwitch.Stop() //nolint:errcheck // ignore for tests // 2. Create seed which knows about the peer peerAddr := peerSwitch.NetAddress() seed := testCreateSeed(dir, 2, []*p2p.NetAddress{peerAddr}, []*p2p.NetAddress{peerAddr}) require.Nil(t, seed.Start()) - defer seed.Stop() // nolint:errcheck // ignore for tests + defer seed.Stop() //nolint:errcheck // ignore for tests // 3. create another peer with only seed configured. secondPeer := testCreatePeerWithSeed(dir, 3, seed) require.Nil(t, secondPeer.Start()) - defer secondPeer.Stop() // nolint:errcheck // ignore for tests + defer secondPeer.Stop() //nolint:errcheck // ignore for tests // 4. check that the second peer connects to seed immediately assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 3*time.Second, 1) @@ -307,13 +307,13 @@ func TestPEXReactorSeedMode(t *testing.T) { sw.SetAddrBook(book) err = sw.Start() require.NoError(t, err) - defer sw.Stop() // nolint:errcheck // ignore for tests + defer sw.Stop() //nolint:errcheck // ignore for tests assert.Zero(t, sw.Peers().Size()) peerSwitch := testCreateDefaultPeer(dir, 1) require.NoError(t, peerSwitch.Start()) - defer peerSwitch.Stop() // nolint:errcheck // ignore for tests + defer peerSwitch.Stop() //nolint:errcheck // ignore for tests // 1. Test crawlPeers dials the peer pexR.crawlPeers([]*p2p.NetAddress{peerSwitch.NetAddress()}) @@ -346,13 +346,13 @@ func TestPEXReactorDoesNotDisconnectFromPersistentPeerInSeedMode(t *testing.T) { sw.SetAddrBook(book) err = sw.Start() require.NoError(t, err) - defer sw.Stop() // nolint:errcheck // ignore for tests + defer sw.Stop() //nolint:errcheck // ignore for tests assert.Zero(t, sw.Peers().Size()) peerSwitch := testCreateDefaultPeer(dir, 1) require.NoError(t, peerSwitch.Start()) - defer peerSwitch.Stop() // nolint:errcheck // ignore for tests + defer peerSwitch.Stop() //nolint:errcheck // ignore for tests err = sw.AddPersistentPeers([]string{peerSwitch.NetAddress().String()}) require.NoError(t, err) @@ -618,7 +618,7 @@ func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*p2p.NetAddress) book := NewAddrBook(filepath.Join(dir, "addrbookSeed.json"), false) book.SetLogger(log.TestingLogger()) for j := 0; j < len(knownAddrs); j++ { - book.AddAddress(knownAddrs[j], srcAddrs[j]) // nolint:errcheck // ignore for tests + book.AddAddress(knownAddrs[j], srcAddrs[j]) //nolint:errcheck // ignore for tests book.MarkGood(knownAddrs[j].ID) } sw.SetAddrBook(book) diff --git a/p2p/switch.go b/p2p/switch.go index fa87cbccd..3214de223 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -379,8 +379,8 @@ func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) { // to the PEX/Addrbook to find the peer with the addr again // NOTE: this will keep trying even if the handshake or auth fails. // TODO: be more explicit with error types so we only retry on certain failures -// - ie. if we're getting ErrDuplicatePeer we can stop -// because the addrbook got us the peer back already +// - ie. if we're getting ErrDuplicatePeer we can stop +// because the addrbook got us the peer back already func (sw *Switch) reconnectToPeer(addr *NetAddress) { if sw.reconnecting.Has(string(addr.ID)) { return diff --git a/p2p/trust/metric_test.go b/p2p/trust/metric_test.go index 65caf38a2..c3adfd5d1 100644 --- a/p2p/trust/metric_test.go +++ b/p2p/trust/metric_test.go @@ -72,6 +72,7 @@ func TestTrustMetricCopyNilPointer(t *testing.T) { } // XXX: This test fails non-deterministically +// //nolint:unused,deadcode func _TestTrustMetricStopPause(t *testing.T) { // The TestTicker will provide manual control over diff --git a/p2p/upnp/upnp.go b/p2p/upnp/upnp.go index e2c8f3fcf..45da9d33c 100644 --- a/p2p/upnp/upnp.go +++ b/p2p/upnp/upnp.go @@ -202,7 +202,7 @@ func localIPv4() (net.IP, error) { } func getServiceURL(rootURL string) (url, urnDomain string, err error) { - r, err := http.Get(rootURL) // nolint: gosec + r, err := http.Get(rootURL) //nolint: gosec if err != nil { return } diff --git a/privval/doc.go b/privval/doc.go index 7695ffe9d..63e1d071d 100644 --- a/privval/doc.go +++ b/privval/doc.go @@ -1,13 +1,12 @@ /* - Package privval provides different implementations of the types.PrivValidator. -FilePV +# FilePV FilePV is the simplest implementation and developer default. It uses one file for the private key and another to store state. -SignerListenerEndpoint +# SignerListenerEndpoint SignerListenerEndpoint establishes a connection to an external process, like a Key Management Server (KMS), using a socket. @@ -15,15 +14,14 @@ SignerListenerEndpoint listens for the external KMS process to dial in. SignerListenerEndpoint takes a listener, which determines the type of connection (ie. encrypted over tcp, or unencrypted over unix). -SignerDialerEndpoint +# SignerDialerEndpoint SignerDialerEndpoint is a simple wrapper around a net.Conn. It's used by both IPCVal and TCPVal. -SignerClient +# SignerClient SignerClient handles remote validator connections that provide signing services. In production, it's recommended to wrap it with RetrySignerClient to avoid termination in case of temporary errors. - */ package privval diff --git a/privval/msgs_test.go b/privval/msgs_test.go index bf532bd7b..afefa0e77 100644 --- a/privval/msgs_test.go +++ b/privval/msgs_test.go @@ -57,7 +57,7 @@ func exampleProposal() *types.Proposal { } } -// nolint:lll // ignore line length for tests +//nolint:lll // ignore line length for tests func TestPrivvalVectors(t *testing.T) { pk := ed25519.GenPrivKeyFromSecret([]byte("it's a secret")).PubKey() ppk, err := cryptoenc.PubKeyToProto(pk) diff --git a/proxy/app_conn.go b/proxy/app_conn.go index f3ac18f18..912085fa0 100644 --- a/proxy/app_conn.go +++ b/proxy/app_conn.go @@ -4,6 +4,7 @@ import ( "time" "github.com/go-kit/kit/metrics" + abcicli "github.com/tendermint/tendermint/abci/client" "github.com/tendermint/tendermint/abci/types" ) diff --git a/proxy/multi_app_conn_test.go b/proxy/multi_app_conn_test.go index 82ff19281..4fd62ad77 100644 --- a/proxy/multi_app_conn_test.go +++ b/proxy/multi_app_conn_test.go @@ -53,7 +53,7 @@ func TestAppConns_Failure(t *testing.T) { }() quitCh := make(chan struct{}) - var recvQuitCh <-chan struct{} // nolint:gosimple + var recvQuitCh <-chan struct{} //nolint:gosimple recvQuitCh = quitCh clientCreatorMock := &mocks.ClientCreator{} diff --git a/rpc/client/http/http.go b/rpc/client/http/http.go index 64c3cf727..4fec87f2f 100644 --- a/rpc/client/http/http.go +++ b/rpc/client/http/http.go @@ -39,24 +39,24 @@ the example for more details. Example: - c, err := New("http://192.168.1.10:26657", "/websocket") - if err != nil { - // handle error - } + c, err := New("http://192.168.1.10:26657", "/websocket") + if err != nil { + // handle error + } - // call Start/Stop if you're subscribing to events - err = c.Start() - if err != nil { - // handle error - } - defer c.Stop() + // call Start/Stop if you're subscribing to events + err = c.Start() + if err != nil { + // handle error + } + defer c.Stop() - res, err := c.Status() - if err != nil { - // handle error - } + res, err := c.Status() + if err != nil { + // handle error + } - // handle result + // handle result */ type HTTP struct { remote string diff --git a/rpc/client/mock/client.go b/rpc/client/mock/client.go index ed911ec20..ec3a358cd 100644 --- a/rpc/client/mock/client.go +++ b/rpc/client/mock/client.go @@ -47,7 +47,6 @@ var _ client.Client = Client{} // Call is used by recorders to save a call and response. // It can also be used to configure mock responses. -// type Call struct { Name string Args interface{} diff --git a/rpc/core/env.go b/rpc/core/env.go index 11a51bfe7..e92319937 100644 --- a/rpc/core/env.go +++ b/rpc/core/env.go @@ -69,7 +69,7 @@ type peers interface { Peers() p2p.IPeerSet } -//---------------------------------------------- +// ---------------------------------------------- // Environment contains objects and interfaces used by the RPC. It is expected // to be setup once during startup. type Environment struct { diff --git a/rpc/jsonrpc/client/ws_client.go b/rpc/jsonrpc/client/ws_client.go index 44bf5f098..09b41888f 100644 --- a/rpc/jsonrpc/client/ws_client.go +++ b/rpc/jsonrpc/client/ws_client.go @@ -30,7 +30,7 @@ const ( // the remote server. // // WSClient is safe for concurrent use by multiple goroutines. -type WSClient struct { // nolint: maligned +type WSClient struct { //nolint: maligned conn *websocket.Conn Address string // IP:PORT or /path/to/socket @@ -265,7 +265,7 @@ func (c *WSClient) dial() error { Proxy: http.ProxyFromEnvironment, } rHeader := http.Header{} - conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader) // nolint:bodyclose + conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader) //nolint:bodyclose if err != nil { return err } diff --git a/rpc/jsonrpc/client/ws_client_test.go b/rpc/jsonrpc/client/ws_client_test.go index 2e6403806..b4ac8f83b 100644 --- a/rpc/jsonrpc/client/ws_client_test.go +++ b/rpc/jsonrpc/client/ws_client_test.go @@ -72,7 +72,7 @@ func TestWSClientReconnectsAfterReadFailure(t *testing.T) { defer s.Close() c := startClient(t, "//"+s.Listener.Addr().String()) - defer c.Stop() // nolint:errcheck // ignore for tests + defer c.Stop() //nolint:errcheck // ignore for tests wg.Add(1) go callWgDoneOnResult(t, c, &wg) @@ -104,7 +104,7 @@ func TestWSClientReconnectsAfterWriteFailure(t *testing.T) { s := httptest.NewServer(h) c := startClient(t, "//"+s.Listener.Addr().String()) - defer c.Stop() // nolint:errcheck // ignore for tests + defer c.Stop() //nolint:errcheck // ignore for tests wg.Add(2) go callWgDoneOnResult(t, c, &wg) @@ -132,7 +132,7 @@ func TestWSClientReconnectFailure(t *testing.T) { s := httptest.NewServer(h) c := startClient(t, "//"+s.Listener.Addr().String()) - defer c.Stop() // nolint:errcheck // ignore for tests + defer c.Stop() //nolint:errcheck // ignore for tests go func() { for { @@ -181,7 +181,7 @@ func TestNotBlockingOnStop(t *testing.T) { timeout := 2 * time.Second s := httptest.NewServer(&myHandler{}) c := startClient(t, "//"+s.Listener.Addr().String()) - c.Call(context.Background(), "a", make(map[string]interface{})) // nolint:errcheck // ignore for tests + c.Call(context.Background(), "a", make(map[string]interface{})) //nolint:errcheck // ignore for tests // Let the readRoutine get around to blocking time.Sleep(time.Second) passCh := make(chan struct{}) diff --git a/rpc/jsonrpc/server/http_json_handler.go b/rpc/jsonrpc/server/http_json_handler.go index 13b4eefe5..c73694d6e 100644 --- a/rpc/jsonrpc/server/http_json_handler.go +++ b/rpc/jsonrpc/server/http_json_handler.go @@ -176,8 +176,9 @@ func arrayParamsToArgs( // array. // // Example: -// rpcFunc.args = [rpctypes.Context string] -// rpcFunc.argNames = ["arg"] +// +// rpcFunc.args = [rpctypes.Context string] +// rpcFunc.argNames = ["arg"] func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte) ([]reflect.Value, error) { const argsOffset = 1 @@ -237,5 +238,5 @@ func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[st buf.WriteString("") w.Header().Set("Content-Type", "text/html") w.WriteHeader(200) - w.Write(buf.Bytes()) // nolint: errcheck + w.Write(buf.Bytes()) //nolint: errcheck } diff --git a/rpc/jsonrpc/types/types.go b/rpc/jsonrpc/types/types.go index ca7dd3de9..33eb0a6c9 100644 --- a/rpc/jsonrpc/types/types.go +++ b/rpc/jsonrpc/types/types.go @@ -215,15 +215,17 @@ func (resp RPCResponse) String() string { } // From the JSON-RPC 2.0 spec: +// // If there was an error in detecting the id in the Request object (e.g. Parse -// error/Invalid Request), it MUST be Null. +// error/Invalid Request), it MUST be Null. func RPCParseError(err error) RPCResponse { return NewRPCErrorResponse(nil, -32700, "Parse error. Invalid JSON", err.Error()) } // From the JSON-RPC 2.0 spec: +// // If there was an error in detecting the id in the Request object (e.g. Parse -// error/Invalid Request), it MUST be Null. +// error/Invalid Request), it MUST be Null. func RPCInvalidRequestError(id jsonrpcid, err error) RPCResponse { return NewRPCErrorResponse(id, -32600, "Invalid Request", err.Error()) } @@ -276,9 +278,12 @@ type Context struct { // RemoteAddr returns the remote address (usually a string "IP:port"). // If neither HTTPReq nor WSConn is set, an empty string is returned. // HTTP: -// http.Request#RemoteAddr +// +// http.Request#RemoteAddr +// // WS: -// result of GetRemoteAddr +// +// result of GetRemoteAddr func (ctx *Context) RemoteAddr() string { if ctx.HTTPReq != nil { return ctx.HTTPReq.RemoteAddr @@ -291,10 +296,13 @@ func (ctx *Context) RemoteAddr() string { // Context returns the request's context. // The returned context is always non-nil; it defaults to the background context. // HTTP: -// The context is canceled when the client's connection closes, the request -// is canceled (with HTTP/2), or when the ServeHTTP method returns. +// +// The context is canceled when the client's connection closes, the request +// is canceled (with HTTP/2), or when the ServeHTTP method returns. +// // WS: -// The context is canceled when the client's connections closes. +// +// The context is canceled when the client's connections closes. func (ctx *Context) Context() context.Context { if ctx.HTTPReq != nil { return ctx.HTTPReq.Context() @@ -307,7 +315,6 @@ func (ctx *Context) Context() context.Context { //---------------------------------------- // SOCKETS -// // 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 diff --git a/scripts/metricsgen/metricsdiff/metricsdiff_test.go b/scripts/metricsgen/metricsdiff/metricsdiff_test.go index ec27ef1e9..8a392c141 100644 --- a/scripts/metricsgen/metricsdiff/metricsdiff_test.go +++ b/scripts/metricsgen/metricsdiff/metricsdiff_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/require" + metricsdiff "github.com/tendermint/tendermint/scripts/metricsgen/metricsdiff" ) diff --git a/scripts/metricsgen/metricsgen_test.go b/scripts/metricsgen/metricsgen_test.go index d543623e9..f3c97854d 100644 --- a/scripts/metricsgen/metricsgen_test.go +++ b/scripts/metricsgen/metricsgen_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/stretchr/testify/require" + metricsgen "github.com/tendermint/tendermint/scripts/metricsgen" ) diff --git a/statesync/snapshots.go b/statesync/snapshots.go index e4936c91a..917c04947 100644 --- a/statesync/snapshots.go +++ b/statesync/snapshots.go @@ -132,7 +132,7 @@ func (p *snapshotPool) GetPeer(snapshot *snapshot) p2p.Peer { if len(peers) == 0 { return nil } - return peers[rand.Intn(len(peers))] // nolint:gosec // G404: Use of weak random number generator + return peers[rand.Intn(len(peers))] //nolint:gosec // G404: Use of weak random number generator } // GetPeers returns the peers for a snapshot. diff --git a/store/store.go b/store/store.go index 6f27d27d1..48fd1c97e 100644 --- a/store/store.go +++ b/store/store.go @@ -17,9 +17,9 @@ import ( BlockStore is a simple low level store for blocks. There are three types of information stored: - - BlockMeta: Meta information about each block - - Block part: Parts of each block, aggregated w/ PartSet - - Commit: The commit part of each block, for gossiping precommit votes + - BlockMeta: Meta information about each block + - Block part: Parts of each block, aggregated w/ PartSet + - Commit: The commit part of each block, for gossiping precommit votes Currently the precommit signatures are duplicated in the Block parts as well as the Commit. In the future this may change, perhaps by moving @@ -325,9 +325,10 @@ func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) { // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db. // blockParts: Must be parts of the block // seenCommit: The +2/3 precommits that were seen which committed at height. -// If all the nodes restart after committing a block, -// we need this to reload the precommits to catch-up nodes to the -// most recent height. Otherwise they'd stall at H-1. +// +// If all the nodes restart after committing a block, +// we need this to reload the precommits to catch-up nodes to the +// most recent height. Otherwise they'd stall at H-1. func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) { if block == nil { panic("BlockStore can only save a non-nil block") diff --git a/test/e2e/app/snapshots.go b/test/e2e/app/snapshots.go index 38ecd9237..bd6c8686a 100644 --- a/test/e2e/app/snapshots.go +++ b/test/e2e/app/snapshots.go @@ -1,4 +1,3 @@ -// nolint: gosec package app import ( @@ -29,7 +28,7 @@ type SnapshotStore struct { // NewSnapshotStore creates a new snapshot store. func NewSnapshotStore(dir string) (*SnapshotStore, error) { store := &SnapshotStore{dir: dir} - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return nil, err } if err := store.loadMetadata(); err != nil { @@ -71,7 +70,7 @@ func (s *SnapshotStore) saveMetadata() error { // save the file to a new file and move it to make saving atomic. newFile := filepath.Join(s.dir, "metadata.json.new") file := filepath.Join(s.dir, "metadata.json") - err = os.WriteFile(newFile, bz, 0644) // nolint: gosec + err = os.WriteFile(newFile, bz, 0o644) //nolint: gosec if err != nil { return err } @@ -92,7 +91,7 @@ func (s *SnapshotStore) Create(state *State) (abci.Snapshot, error) { Hash: hashItems(state.Values), Chunks: byteChunks(bz), } - err = os.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0644) + err = os.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0o644) //nolint:gosec if err != nil { return abci.Snapshot{}, err } diff --git a/test/e2e/app/state.go b/test/e2e/app/state.go index e82a22539..b07a6b9fc 100644 --- a/test/e2e/app/state.go +++ b/test/e2e/app/state.go @@ -1,4 +1,3 @@ -//nolint: gosec package app import ( @@ -12,8 +11,10 @@ import ( "sync" ) -const stateFileName = "app_state.json" -const prevStateFileName = "prev_app_state.json" +const ( + stateFileName = "app_state.json" + prevStateFileName = "prev_app_state.json" +) // State is the application state. type State struct { @@ -81,7 +82,7 @@ func (s *State) save() error { // We write the state to a separate file and move it to the destination, to // make it atomic. newFile := fmt.Sprintf("%v.new", s.currentFile) - err = os.WriteFile(newFile, bz, 0644) + err = os.WriteFile(newFile, bz, 0o644) //nolint:gosec if err != nil { return fmt.Errorf("failed to write state to %q: %w", s.currentFile, err) } diff --git a/test/e2e/generator/main.go b/test/e2e/generator/main.go index f17b4f3f4..d5b6ab639 100644 --- a/test/e2e/generator/main.go +++ b/test/e2e/generator/main.go @@ -1,4 +1,3 @@ -//nolint: gosec package main import ( @@ -58,12 +57,12 @@ func NewCLI() *CLI { // generate generates manifests in a directory. func (cli *CLI) generate(dir string, groups int) error { - err := os.MkdirAll(dir, 0755) + err := os.MkdirAll(dir, 0o755) if err != nil { return err } - manifests, err := Generate(rand.New(rand.NewSource(randomSeed))) + manifests, err := Generate(rand.New(rand.NewSource(randomSeed))) //nolint:gosec if err != nil { return err } diff --git a/test/e2e/node/config.go b/test/e2e/node/config.go index 7efb4e822..6941d0a1c 100644 --- a/test/e2e/node/config.go +++ b/test/e2e/node/config.go @@ -1,4 +1,3 @@ -//nolint: goconst package main import ( @@ -56,6 +55,8 @@ func LoadConfig(file string) (*Config, error) { // Validate validates the configuration. We don't do exhaustive config // validation here, instead relying on Testnet.Validate() to handle it. +// +//nolint:goconst func (cfg Config) Validate() error { switch { case cfg.ChainID == "": diff --git a/test/e2e/pkg/testnet.go b/test/e2e/pkg/testnet.go index 47f1b0b26..2ee4a44c3 100644 --- a/test/e2e/pkg/testnet.go +++ b/test/e2e/pkg/testnet.go @@ -1,4 +1,3 @@ -//nolint: gosec package e2e import ( @@ -26,9 +25,11 @@ const ( networkIPv6 = "fd80:b10c::/48" ) -type Mode string -type Protocol string -type Perturbation string +type ( + Mode string + Protocol string + Perturbation string +) const ( ModeValidator Mode = "validator" @@ -396,7 +397,7 @@ func (t Testnet) ArchiveNodes() []*Node { // RandomNode returns a random non-seed node. func (t Testnet) RandomNode() *Node { for { - node := t.Nodes[rand.Intn(len(t.Nodes))] + node := t.Nodes[rand.Intn(len(t.Nodes))] //nolint:gosec if node.Mode != ModeSeed { return node } @@ -459,7 +460,7 @@ type keyGenerator struct { func newKeyGenerator(seed int64) *keyGenerator { return &keyGenerator{ - random: rand.New(rand.NewSource(seed)), + random: rand.New(rand.NewSource(seed)), //nolint:gosec } } diff --git a/test/e2e/runner/evidence.go b/test/e2e/runner/evidence.go index 0cd56016f..8edfaa4ba 100644 --- a/test/e2e/runner/evidence.go +++ b/test/e2e/runner/evidence.go @@ -5,8 +5,8 @@ import ( "context" "errors" "fmt" - "io/ioutil" "math/rand" + "os" "path/filepath" "time" @@ -234,7 +234,7 @@ func getRandomValidatorIndex(privVals []types.MockPV, vals *types.ValidatorSet) } func readPrivKey(keyFilePath string) (crypto.PrivKey, error) { - keyJSONBytes, err := ioutil.ReadFile(keyFilePath) + keyJSONBytes, err := os.ReadFile(keyFilePath) if err != nil { return nil, err } diff --git a/test/e2e/runner/exec.go b/test/e2e/runner/exec.go index f790f7fc1..e6e47ca0a 100644 --- a/test/e2e/runner/exec.go +++ b/test/e2e/runner/exec.go @@ -1,4 +1,3 @@ -//nolint: gosec package main import ( @@ -10,7 +9,7 @@ import ( // execute executes a shell command. func exec(args ...string) error { - cmd := osexec.Command(args[0], args[1:]...) + cmd := osexec.Command(args[0], args[1:]...) //nolint:gosec out, err := cmd.CombinedOutput() switch err := err.(type) { case nil: @@ -24,7 +23,7 @@ func exec(args ...string) error { // execVerbose executes a shell command while displaying its output. func execVerbose(args ...string) error { - cmd := osexec.Command(args[0], args[1:]...) + cmd := osexec.Command(args[0], args[1:]...) //nolint:gosec cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() diff --git a/test/e2e/runner/main.go b/test/e2e/runner/main.go index 798bf12e4..048d2cabc 100644 --- a/test/e2e/runner/main.go +++ b/test/e2e/runner/main.go @@ -57,7 +57,7 @@ func NewCLI() *CLI { return err } - r := rand.New(rand.NewSource(randomSeed)) // nolint: gosec + r := rand.New(rand.NewSource(randomSeed)) //nolint: gosec chLoadResult := make(chan error) ctx, loadCancel := context.WithCancel(context.Background()) @@ -203,7 +203,7 @@ func NewCLI() *CLI { return InjectEvidence( cmd.Context(), - rand.New(rand.NewSource(randomSeed)), // nolint: gosec + rand.New(rand.NewSource(randomSeed)), //nolint: gosec cli.testnet, amount, ) diff --git a/test/e2e/runner/setup.go b/test/e2e/runner/setup.go index db180b382..202f3f79e 100644 --- a/test/e2e/runner/setup.go +++ b/test/e2e/runner/setup.go @@ -1,4 +1,3 @@ -// nolint: gosec package main import ( @@ -52,7 +51,7 @@ func Setup(testnet *e2e.Testnet) error { if err != nil { return err } - err = os.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0644) + err = os.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0o644) //nolint:gosec if err != nil { return err } @@ -75,7 +74,7 @@ func Setup(testnet *e2e.Testnet) error { if node.Mode == e2e.ModeLight && strings.Contains(dir, "app") { continue } - err := os.MkdirAll(dir, 0755) + err := os.MkdirAll(dir, 0o755) if err != nil { return err } @@ -91,7 +90,7 @@ func Setup(testnet *e2e.Testnet) error { if err != nil { return err } - err = os.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0644) + err = os.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0o644) //nolint:gosec if err != nil { return err } @@ -400,5 +399,5 @@ func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error { } bz = regexp.MustCompile(`(?m)^trust_height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_height = %v`, height))) bz = regexp.MustCompile(`(?m)^trust_hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_hash = "%X"`, hash))) - return os.WriteFile(cfgPath, bz, 0644) + return os.WriteFile(cfgPath, bz, 0o644) //nolint:gosec } diff --git a/test/fuzz/p2p/addrbook/fuzz.go b/test/fuzz/p2p/addrbook/fuzz.go index f2799ef04..81aa2d474 100644 --- a/test/fuzz/p2p/addrbook/fuzz.go +++ b/test/fuzz/p2p/addrbook/fuzz.go @@ -1,4 +1,3 @@ -// nolint: gosec package addr import ( @@ -25,7 +24,7 @@ func Fuzz(data []byte) int { } // Also, make sure PickAddress always returns a non-nil address. - bias := rand.Intn(100) + bias := rand.Intn(100) //nolint:gosec if p := addrBook.PickAddress(bias); p == nil { panic(fmt.Sprintf("picked a nil address (bias: %d, addrBook size: %v)", bias, addrBook.Size())) diff --git a/test/fuzz/p2p/addrbook/init-corpus/main.go b/test/fuzz/p2p/addrbook/init-corpus/main.go index 2185eab4b..999d2a082 100644 --- a/test/fuzz/p2p/addrbook/init-corpus/main.go +++ b/test/fuzz/p2p/addrbook/init-corpus/main.go @@ -1,4 +1,3 @@ -// nolint: gosec package main import ( @@ -26,7 +25,7 @@ func initCorpus(baseDir string) { // create "corpus" directory corpusDir := filepath.Join(baseDir, "corpus") - if err := os.MkdirAll(corpusDir, 0755); err != nil { + if err := os.MkdirAll(corpusDir, 0o755); err != nil { log.Fatalf("Creating %q err: %v", corpusDir, err) } @@ -48,7 +47,8 @@ func initCorpus(baseDir string) { log.Fatalf("can't marshal %v: %v", addr, err) } - if err := os.WriteFile(filename, bz, 0644); err != nil { + //nolint:gosec + if err := os.WriteFile(filename, bz, 0o644); err != nil { log.Fatalf("can't write %v to %q: %v", addr, filename, err) } diff --git a/test/fuzz/p2p/pex/init-corpus/main.go b/test/fuzz/p2p/pex/init-corpus/main.go index d96740306..dfa18363e 100644 --- a/test/fuzz/p2p/pex/init-corpus/main.go +++ b/test/fuzz/p2p/pex/init-corpus/main.go @@ -1,4 +1,3 @@ -// nolint: gosec package main import ( @@ -21,11 +20,12 @@ func main() { initCorpus(*baseDir) } +//nolint:gosec func initCorpus(rootDir string) { log.SetFlags(0) corpusDir := filepath.Join(rootDir, "corpus") - if err := os.MkdirAll(corpusDir, 0755); err != nil { + if err := os.MkdirAll(corpusDir, 0o755); err != nil { log.Fatalf("Creating %q err: %v", corpusDir, err) } sizes := []int{0, 1, 2, 17, 5, 31} @@ -72,7 +72,7 @@ func initCorpus(rootDir string) { filename := filepath.Join(rootDir, "corpus", fmt.Sprintf("%d", n)) - if err := os.WriteFile(filename, bz, 0644); err != nil { + if err := os.WriteFile(filename, bz, 0o644); err != nil { log.Fatalf("can't write %X to %q: %v", bz, filename, err) } diff --git a/test/fuzz/p2p/secret_connection/init-corpus/main.go b/test/fuzz/p2p/secret_connection/init-corpus/main.go index 3a2537ff7..155ce4d67 100644 --- a/test/fuzz/p2p/secret_connection/init-corpus/main.go +++ b/test/fuzz/p2p/secret_connection/init-corpus/main.go @@ -1,4 +1,3 @@ -// nolint: gosec package main import ( @@ -20,7 +19,7 @@ func initCorpus(baseDir string) { log.SetFlags(0) corpusDir := filepath.Join(baseDir, "corpus") - if err := os.MkdirAll(corpusDir, 0755); err != nil { + if err := os.MkdirAll(corpusDir, 0o755); err != nil { log.Fatal(err) } @@ -38,7 +37,8 @@ func initCorpus(baseDir string) { for i, datum := range data { filename := filepath.Join(corpusDir, fmt.Sprintf("%d", i)) - if err := os.WriteFile(filename, []byte(datum), 0644); err != nil { + //nolint:gosec + if err := os.WriteFile(filename, []byte(datum), 0o644); err != nil { log.Fatalf("can't write %v to %q: %v", datum, filename, err) } diff --git a/types/block_test.go b/types/block_test.go index 10a81d5d7..ee8ce9c77 100644 --- a/types/block_test.go +++ b/types/block_test.go @@ -211,7 +211,7 @@ func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) BlockID { var nilBytes []byte -// This follows RFC-6962, i.e. `echo -n '' | sha256sum` +// This follows RFC-6962, i.e. `echo -n ” | sha256sum` var emptyBytes = []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55} diff --git a/types/event_bus.go b/types/event_bus.go index 126bf27c6..d51ae8e67 100644 --- a/types/event_bus.go +++ b/types/event_bus.go @@ -23,7 +23,7 @@ type EventBusSubscriber interface { type Subscription interface { Out() <-chan tmpubsub.Message - Cancelled() <-chan struct{} // nolint: misspell + Cancelled() <-chan struct{} //nolint: misspell Err() error } @@ -227,7 +227,7 @@ func (b *EventBus) PublishEventValidatorSetUpdates(data EventDataValidatorSetUpd return b.Publish(EventValidatorSetUpdates, data) } -//----------------------------------------------------------------------------- +// ----------------------------------------------------------------------------- type NopEventBus struct{} func (NopEventBus) Subscribe( diff --git a/types/utils.go b/types/utils.go index cec47e202..60e82fe3f 100644 --- a/types/utils.go +++ b/types/utils.go @@ -4,9 +4,9 @@ import "reflect" // Go lacks a simple and safe way to see if something is a typed nil. // See: -// - https://dave.cheney.net/2017/08/09/typed-nils-in-go-2 -// - https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I/discussion -// - https://github.com/golang/go/issues/21538 +// - https://dave.cheney.net/2017/08/09/typed-nils-in-go-2 +// - https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I/discussion +// - https://github.com/golang/go/issues/21538 func isTypedNil(o interface{}) bool { rv := reflect.ValueOf(o) switch rv.Kind() { diff --git a/types/validator_set.go b/types/validator_set.go index 5b2ec85a5..39a004b0b 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -411,14 +411,17 @@ func processChanges(origChanges []*Validator) (updates, removals []*Validator, e // // Inputs: // updates - a list of proper validator changes, i.e. they have been verified by processChanges for duplicates -// and invalid values. +// +// and invalid values. +// // vals - the original validator set. Note that vals is NOT modified by this function. // removedPower - the total voting power that will be removed after the updates are verified and applied. // // Returns: // tvpAfterUpdatesBeforeRemovals - the new total voting power if these updates would be applied without the removals. -// Note that this will be < 2 * MaxTotalVotingPower in case high power validators are removed and -// validators are added/ updated with high power values. +// +// 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 func verifyUpdates( @@ -467,8 +470,9 @@ func numNewValidators(updates []*Validator, vals *ValidatorSet) int { // 'updates' parameter must be a list of unique validators to be added or updated. // // 'updatedTotalVotingPower' is the total voting power of a set where all updates would be applied but -// not the removals. It must be < 2*MaxTotalVotingPower and may be close to this limit if close to -// MaxTotalVotingPower will be removed. This is still safe from overflow since MaxTotalVotingPower is maxInt64/8. +// +// not the removals. It must be < 2*MaxTotalVotingPower and may be close to this limit if close to +// MaxTotalVotingPower will be removed. This is still safe from overflow since MaxTotalVotingPower is maxInt64/8. // // No changes are made to the validator set 'vals'. func computeNewPriorities(updates []*Validator, vals *ValidatorSet, updatedTotalVotingPower int64) { @@ -638,14 +642,15 @@ func (vals *ValidatorSet) updateWithChangeSet(changes []*Validator, allowDeletes // UpdateWithChangeSet attempts to update the validator set with 'changes'. // It performs the following steps: -// - validates the changes making sure there are no duplicates and splits them in updates and deletes -// - verifies that applying the changes will not result in errors -// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities -// across old and newly added validators are fair -// - computes the priorities of new validators against the final set -// - applies the updates against the validator set -// - applies the removals against the validator set -// - performs scaling and centering of priority values +// - validates the changes making sure there are no duplicates and splits them in updates and deletes +// - verifies that applying the changes will not result in errors +// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities +// across old and newly added validators are fair +// - computes the priorities of new validators against the final set +// - applies the updates against the validator set +// - applies the removals against the validator set +// - performs scaling and centering of priority values +// // If an error is detected during verification steps, it is returned and the validator set // is not changed. func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error { diff --git a/types/validator_set_test.go b/types/validator_set_test.go index 67a9a96ea..6fbbb0885 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -1641,7 +1641,7 @@ func TestValidatorSetProtoBuf(t *testing.T) { } } -//--------------------- +// --------------------- // Sort validators by priority and address type validatorsByPriority []*Validator @@ -1682,9 +1682,8 @@ func (tvals testValsByVotingPower) Swap(i, j int) { tvals[i], tvals[j] = tvals[j], tvals[i] } -//------------------------------------- +// ------------------------------------- // Benchmark tests -// func BenchmarkUpdates(b *testing.B) { const ( n = 100 diff --git a/types/vote_set.go b/types/vote_set.go index 829b54b53..2fec82348 100644 --- a/types/vote_set.go +++ b/types/vote_set.go @@ -25,38 +25,38 @@ const ( type P2PID string /* - VoteSet helps collect signatures from validators at each height+round for a - predefined vote type. +VoteSet helps collect signatures from validators at each height+round for a +predefined vote type. - We need VoteSet to be able to keep track of conflicting votes when validators - double-sign. Yet, we can't keep track of *all* the votes seen, as that could - be a DoS attack vector. +We need VoteSet to be able to keep track of conflicting votes when validators +double-sign. Yet, we can't keep track of *all* the votes seen, as that could +be a DoS attack vector. - There are two storage areas for votes. - 1. voteSet.votes - 2. voteSet.votesByBlock +There are two storage areas for votes. +1. voteSet.votes +2. voteSet.votesByBlock - `.votes` is the "canonical" list of votes. It always has at least one vote, - if a vote from a validator had been seen at all. Usually it keeps track of - the first vote seen, but when a 2/3 majority is found, votes for that get - priority and are copied over from `.votesByBlock`. +`.votes` is the "canonical" list of votes. It always has at least one vote, +if a vote from a validator had been seen at all. Usually it keeps track of +the first vote seen, but when a 2/3 majority is found, votes for that get +priority and are copied over from `.votesByBlock`. - `.votesByBlock` keeps track of a list of votes for a particular block. There - are two ways a &blockVotes{} gets created in `.votesByBlock`. - 1. the first vote seen by a validator was for the particular block. - 2. a peer claims to have seen 2/3 majority for the particular block. +`.votesByBlock` keeps track of a list of votes for a particular block. There +are two ways a &blockVotes{} gets created in `.votesByBlock`. +1. the first vote seen by a validator was for the particular block. +2. a peer claims to have seen 2/3 majority for the particular block. - Since the first vote from a validator will always get added in `.votesByBlock` - , all votes in `.votes` will have a corresponding entry in `.votesByBlock`. +Since the first vote from a validator will always get added in `.votesByBlock` +, all votes in `.votes` will have a corresponding entry in `.votesByBlock`. - When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its - votes are copied into `.votes`. +When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its +votes are copied into `.votes`. - All this is memory bounded because conflicting votes only get added if a peer - told us to track that block, each peer only gets to tell us 1 such block, and, - there's only a limited number of peers. +All this is memory bounded because conflicting votes only get added if a peer +told us to track that block, each peer only gets to tell us 1 such block, and, +there's only a limited number of peers. - NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64. +NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64. */ type VoteSet struct { chainID string @@ -133,8 +133,10 @@ func (voteSet *VoteSet) Size() int { // Returns added=true if vote is valid and new. // Otherwise returns err=ErrVote[ -// UnexpectedStep | InvalidIndex | InvalidAddress | -// InvalidSignature | InvalidBlockHash | ConflictingVotes ] +// +// UnexpectedStep | InvalidIndex | InvalidAddress | +// InvalidSignature | InvalidBlockHash | ConflictingVotes ] +// // Duplicate votes return added=false, err=nil. // Conflicting votes return added=*, err=ErrVoteConflictingVotes. // NOTE: vote should not be mutated after adding. @@ -644,10 +646,10 @@ func (voteSet *VoteSet) MakeCommit() *Commit { //-------------------------------------------------------------------------------- /* - 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) +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) */ type blockVotes struct { peerMaj23 bool // peer claims to have maj23