From 102ec83eb11880913d02729585bee8cdcee74f67 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 28 Jun 2023 17:37:39 +0800 Subject: [PATCH 1/5] fix tests for NewClistMempool by sending a nil blockreadynotifier --- .github/workflows/lint.yml | 55 ++++ .golangci.yml | 181 +++++++++---- abci/client/grpc_client.go | 11 +- abci/client/local_client.go | 6 +- abci/client/socket_client.go | 8 +- abci/client/socket_client_test.go | 8 +- abci/cmd/abci-cli/abci-cli.go | 14 +- abci/example/counter/counter.go | 12 +- abci/example/example_test.go | 14 +- abci/example/kvstore/kvstore.go | 3 +- abci/example/kvstore/kvstore_test.go | 14 +- abci/example/kvstore/persistent_kvstore.go | 30 ++- abci/server/grpc_server.go | 4 +- abci/server/socket_server.go | 8 +- abci/tests/benchmarks/parallel/parallel.go | 7 +- abci/tests/benchmarks/simple/simple.go | 7 +- abci/tests/client_server_test.go | 3 +- abci/types/application.go | 15 +- abci/types/messages_test.go | 3 +- abci/types/result.go | 12 +- behaviour/doc.go | 31 ++- behaviour/reporter_test.go | 81 +++--- blockchain/msgs.go | 3 +- blockchain/msgs_test.go | 59 +++-- blockchain/v0/pool.go | 6 +- blockchain/v0/pool_test.go | 5 +- blockchain/v0/reactor.go | 12 +- blockchain/v0/reactor_test.go | 14 +- blockchain/v1/peer.go | 6 +- blockchain/v1/peer_test.go | 6 +- blockchain/v1/pool.go | 4 +- blockchain/v1/pool_test.go | 50 ++-- blockchain/v1/reactor.go | 15 +- blockchain/v1/reactor_fsm.go | 1 - blockchain/v1/reactor_fsm_test.go | 37 +-- blockchain/v1/reactor_test.go | 26 +- blockchain/v2/io.go | 2 +- blockchain/v2/processor.go | 3 +- blockchain/v2/processor_context.go | 4 +- blockchain/v2/processor_test.go | 18 +- blockchain/v2/reactor.go | 10 +- blockchain/v2/reactor_test.go | 20 +- blockchain/v2/routine.go | 1 - blockchain/v2/scheduler.go | 12 +- blockchain/v2/scheduler_test.go | 200 ++++++++------ blockchain/v2/types.go | 8 +- cmd/priv_val_server/main.go | 1 - cmd/tendermint/commands/debug/debug.go | 3 +- cmd/tendermint/commands/debug/dump.go | 5 +- cmd/tendermint/commands/debug/io.go | 1 - cmd/tendermint/commands/debug/kill.go | 5 +- cmd/tendermint/commands/gen_node_key.go | 3 +- cmd/tendermint/commands/gen_validator.go | 3 +- cmd/tendermint/commands/init.go | 3 +- cmd/tendermint/commands/light.go | 6 +- cmd/tendermint/commands/probe_upnp.go | 3 +- cmd/tendermint/commands/replay.go | 3 +- cmd/tendermint/commands/reset.go | 7 +- cmd/tendermint/commands/reset_test.go | 3 +- cmd/tendermint/commands/rollback.go | 6 +- cmd/tendermint/commands/root.go | 5 +- cmd/tendermint/commands/root_test.go | 17 +- cmd/tendermint/commands/run_node.go | 7 +- cmd/tendermint/commands/show_node_id.go | 3 +- cmd/tendermint/commands/show_validator.go | 3 +- cmd/tendermint/commands/testnet.go | 7 +- cmd/tendermint/commands/version.go | 3 +- config/config_test.go | 1 - config/toml.go | 12 +- config/toml_test.go | 2 +- consensus/byzantine_test.go | 2 +- consensus/common_test.go | 2 +- consensus/reactor_test.go | 2 +- consensus/types/height_vote_set.go | 9 +- consensus/types/height_vote_set_test.go | 1 - crypto/crypto.go | 6 +- crypto/ed25519/ed25519.go | 5 +- crypto/ed25519/ed25519_test.go | 6 +- crypto/internal/benchmarking/bench.go | 1 - crypto/merkle/doc.go | 25 +- crypto/merkle/hash.go | 2 +- crypto/merkle/proof.go | 2 +- crypto/merkle/proof_test.go | 23 +- crypto/merkle/tree.go | 8 +- crypto/merkle/tree_test.go | 7 +- crypto/merkle/types.go | 10 +- crypto/random_test.go | 3 +- crypto/secp256k1/btcec/btcec.go | 16 +- crypto/secp256k1/btcec/btcec_test.go | 8 +- crypto/secp256k1/btcec/ciphering_test.go | 9 +- crypto/secp256k1/btcec/field.go | 63 ++--- crypto/secp256k1/btcec/privkey.go | 3 +- crypto/secp256k1/btcec/pubkey_test.go | 51 ++-- crypto/secp256k1/btcec/signature.go | 11 +- crypto/secp256k1/btcec/signature_test.go | 63 +++-- crypto/secp256k1/secp256k1.go | 7 +- crypto/secp256k1/secp256k1_internal_test.go | 4 +- crypto/secp256k1/secp256k1_test.go | 6 +- crypto/sr25519/encoding.go | 1 - crypto/sr25519/privkey.go | 3 +- crypto/sr25519/pubkey.go | 6 +- crypto/sr25519/sr25519_test.go | 6 +- crypto/tmhash/hash.go | 1 + crypto/tmhash/hash_test.go | 3 +- crypto/xsalsa20symmetric/symmetric.go | 13 +- crypto/xsalsa20symmetric/symmetric_test.go | 6 +- evidence/doc.go | 7 +- evidence/pool.go | 12 +- evidence/pool_test.go | 20 +- evidence/reactor.go | 1 - evidence/reactor_test.go | 22 +- evidence/verify.go | 4 +- evidence/verify_test.go | 16 +- libs/async/async.go | 14 +- libs/async/async_test.go | 28 +- libs/autofile/autofile.go | 2 +- libs/autofile/autofile_test.go | 3 +- libs/autofile/cmd/logjack.go | 10 +- libs/autofile/group.go | 2 +- libs/autofile/group_test.go | 7 +- libs/bits/bit_array_test.go | 6 +- libs/cli/flags/log_level_test.go | 9 +- libs/cli/helper.go | 2 +- libs/cli/setup_test.go | 7 +- libs/clist/clist_test.go | 5 +- libs/events/events.go | 4 +- libs/events/events_test.go | 6 +- libs/flowrate/io_test.go | 12 +- libs/json/decoder_test.go | 3 +- libs/json/doc.go | 15 +- libs/json/encoder_test.go | 3 +- libs/json/helpers_test.go | 6 +- libs/json/structs.go | 6 +- libs/json/types.go | 6 +- libs/log/filter.go | 29 +- libs/log/logger.go | 6 +- libs/log/testing_logger.go | 6 +- libs/log/tmfmt_logger_test.go | 3 +- libs/log/tracing_logger_test.go | 3 +- libs/math/fraction_test.go | 2 - libs/math/safemath.go | 8 +- libs/net/net_test.go | 1 - libs/os/os_test.go | 14 +- libs/protoio/io_test.go | 3 +- libs/pubsub/example_test.go | 4 +- libs/pubsub/pubsub.go | 5 +- libs/pubsub/pubsub_test.go | 12 +- libs/pubsub/query/empty.go | 3 +- libs/pubsub/query/empty_test.go | 3 +- libs/pubsub/query/parser_test.go | 3 +- libs/pubsub/query/query.go | 6 +- libs/pubsub/query/query_test.go | 33 ++- libs/rand/random_test.go | 6 +- libs/strings/string_test.go | 3 +- libs/tempfile/tempfile_test.go | 15 +- libs/timer/throttle_timer.go | 6 +- libs/timer/throttle_timer_test.go | 5 +- light/client.go | 26 +- light/client_benchmark_test.go | 3 +- light/client_test.go | 12 +- light/detector.go | 6 +- light/detector_test.go | 9 +- light/doc.go | 50 ++-- light/example_test.go | 3 +- light/helpers_test.go | 23 +- light/provider/http/http_test.go | 5 +- light/proxy/routes.go | 4 +- light/rpc/client.go | 14 +- light/setup.go | 8 +- light/store/db/db.go | 10 +- light/store/db/db_test.go | 9 +- light/store/errors.go | 8 +- light/verifier.go | 30 +-- light/verifier_test.go | 4 +- mempool/clist_mempool_test.go | 2 +- node/node_test.go | 2 + p2p/conn/connection.go | 15 +- p2p/conn/connection_test.go | 15 +- p2p/conn/evil_secret_connection_test.go | 9 +- p2p/conn/secret_connection.go | 43 ++- p2p/conn/secret_connection_test.go | 33 ++- p2p/key.go | 2 +- p2p/key_test.go | 6 +- p2p/mock/peer.go | 1 + p2p/netaddress.go | 55 ++-- p2p/netaddress_test.go | 3 +- p2p/node_info.go | 2 - p2p/node_info_test.go | 6 +- p2p/peer.go | 3 - p2p/peer_set_test.go | 3 +- p2p/peer_test.go | 9 +- p2p/pex/addrbook.go | 7 +- p2p/pex/addrbook_test.go | 5 +- p2p/pex/file.go | 2 +- p2p/pex/known_address.go | 2 +- p2p/pex/pex_reactor.go | 6 +- p2p/pex/pex_reactor_test.go | 24 +- p2p/switch.go | 2 +- p2p/switch_test.go | 16 +- p2p/test_util.go | 7 +- p2p/transport.go | 11 +- p2p/transport_test.go | 18 +- p2p/trust/metric.go | 1 - p2p/trust/metric_test.go | 1 + p2p/trust/store.go | 3 +- p2p/trust/store_test.go | 3 +- p2p/types.go | 6 +- p2p/upnp/probe.go | 2 +- p2p/upnp/upnp.go | 5 +- privval/doc.go | 10 +- privval/file.go | 12 +- privval/file_test.go | 32 ++- privval/msgs.go | 3 +- privval/msgs_test.go | 6 +- privval/signer_client_test.go | 8 +- privval/signer_dialer_endpoint.go | 1 - privval/signer_listener_endpoint_test.go | 6 +- privval/signer_requestHandler.go | 21 +- privval/socket_dialers_test.go | 3 +- proxy/app_conn.go | 6 +- proxy/multi_app_conn_test.go | 5 +- rpc/client/event_test.go | 7 +- rpc/client/evidence_test.go | 11 +- rpc/client/helpers_test.go | 5 +- rpc/client/http/http.go | 17 +- rpc/client/local/local.go | 9 +- rpc/client/mock/abci.go | 9 +- rpc/client/mock/abci_test.go | 5 +- rpc/client/mock/client.go | 3 +- rpc/client/mock/status_test.go | 8 +- rpc/client/rpc_test.go | 9 +- rpc/core/blocks.go | 4 +- rpc/core/blocks_test.go | 9 +- rpc/core/consensus.go | 9 +- rpc/core/env.go | 6 +- rpc/core/mempool.go | 7 +- rpc/core/net.go | 3 +- rpc/core/net_test.go | 5 +- rpc/core/tx.go | 1 - rpc/core/types/responses.go | 4 +- rpc/core/types/responses_test.go | 3 +- rpc/grpc/api.go | 3 +- rpc/grpc/client_server.go | 3 +- rpc/grpc/grpc_test.go | 3 +- rpc/jsonrpc/client/decode.go | 6 +- rpc/jsonrpc/client/http_json_client.go | 6 +- rpc/jsonrpc/client/http_uri_client.go | 4 +- rpc/jsonrpc/client/ws_client.go | 5 +- rpc/jsonrpc/client/ws_client_test.go | 5 +- rpc/jsonrpc/jsonrpc_test.go | 14 +- rpc/jsonrpc/server/http_json_handler.go | 2 - rpc/jsonrpc/server/http_json_handler_test.go | 5 +- rpc/jsonrpc/server/http_server.go | 4 +- rpc/jsonrpc/server/http_server_test.go | 5 +- rpc/jsonrpc/server/parse_test.go | 3 +- rpc/jsonrpc/server/ws_handler.go | 3 +- rpc/jsonrpc/server/ws_handler_test.go | 5 +- rpc/jsonrpc/types/types.go | 6 +- rpc/test/helpers.go | 15 +- scripts/json2wal/main.go | 2 +- state/execution.go | 11 +- state/execution_test.go | 7 +- state/export_test.go | 3 +- state/helpers_test.go | 23 +- state/indexer/block/kv/kv.go | 7 +- state/indexer/block/kv/kv_test.go | 5 +- state/indexer/block/kv/util.go | 3 +- state/indexer/sink/psql/psql.go | 4 +- state/indexer/sink/psql/psql_test.go | 10 +- state/rollback_test.go | 5 +- state/state.go | 5 +- state/state_test.go | 17 +- state/store.go | 8 +- state/store_test.go | 24 +- state/tx_filter_test.go | 8 +- state/txindex/indexer_service.go | 1 - state/txindex/indexer_service_test.go | 5 +- state/txindex/kv/kv.go | 5 +- state/txindex/kv/kv_bench_test.go | 3 +- state/txindex/kv/kv_test.go | 10 +- state/validation_test.go | 7 +- statesync/chunks.go | 2 +- statesync/chunks_test.go | 3 +- statesync/messages.go | 3 +- statesync/messages_test.go | 48 ++-- statesync/reactor.go | 1 - statesync/reactor_test.go | 13 +- statesync/snapshots.go | 2 +- statesync/snapshots_test.go | 5 +- statesync/stateprovider.go | 3 +- statesync/syncer.go | 1 - statesync/syncer_test.go | 10 +- store/store.go | 17 +- store/store_test.go | 31 ++- test/app/grpc_client.go | 3 +- test/e2e/app/snapshots.go | 8 +- test/e2e/app/state.go | 10 +- test/e2e/generator/generate.go | 2 +- test/e2e/generator/main.go | 5 +- test/e2e/node/config.go | 1 - test/e2e/node/main.go | 3 +- test/e2e/pkg/testnet.go | 8 +- test/e2e/runner/exec.go | 2 +- test/e2e/runner/main.go | 7 +- test/e2e/runner/setup.go | 9 +- test/e2e/tests/app_test.go | 6 +- test/e2e/tests/block_test.go | 3 +- test/e2e/tests/e2e_test.go | 3 +- test/e2e/tests/evidence_test.go | 3 +- test/e2e/tests/net_test.go | 3 +- test/e2e/tests/validator_test.go | 3 +- test/fuzz/mempool/checktx.go | 2 +- test/fuzz/p2p/addrbook/init-corpus/main.go | 4 +- test/fuzz/p2p/pex/init-corpus/main.go | 4 +- test/fuzz/p2p/pex/reactor_receive.go | 27 +- .../p2p/secret_connection/init-corpus/main.go | 4 +- test/fuzz/p2p/secret_connection/read_write.go | 2 +- test/maverick/consensus/misbehavior.go | 2 - test/maverick/consensus/reactor.go | 14 +- test/maverick/consensus/replay.go | 12 +- test/maverick/consensus/replay_file.go | 8 +- test/maverick/consensus/state.go | 17 +- test/maverick/consensus/ticker.go | 5 +- test/maverick/consensus/wal.go | 13 +- test/maverick/consensus/wal_generator.go | 6 +- test/maverick/main.go | 5 +- test/maverick/node/node.go | 57 ++-- test/maverick/node/privval.go | 10 +- .../internal/test_harness.go | 8 +- .../internal/test_harness_test.go | 5 +- tools/tm-signer-harness/main.go | 2 +- types/block.go | 11 +- types/block_meta_test.go | 15 +- types/block_test.go | 15 +- types/canonical_test.go | 24 +- types/encoding_helper.go | 3 +- types/event_bus_test.go | 13 +- types/evidence.go | 10 +- types/evidence_test.go | 9 +- types/genesis.go | 2 +- types/genesis_test.go | 5 +- types/light_test.go | 5 +- types/params_test.go | 3 +- types/part_set_test.go | 18 +- types/proposal.go | 2 +- types/proposal_test.go | 16 +- types/protobuf_test.go | 17 +- types/results_test.go | 3 +- types/signable.go | 10 +- types/test_util.go | 4 +- types/tx.go | 3 +- types/tx_test.go | 8 +- types/utils.go | 6 +- types/validator_set.go | 11 +- types/validator_set_test.go | 248 ++++++++++++------ types/vote_set.go | 3 +- types/vote_set_test.go | 5 +- types/vote_test.go | 22 +- version/version.go | 4 +- vm/block.go | 4 +- vm/block_utils.go | 9 +- vm/cmd/main.go | 6 +- vm/database.go | 14 +- vm/service.go | 4 +- vm/vm.go | 15 +- vm/vm_test.go | 8 +- 366 files changed, 2072 insertions(+), 1951 deletions(-) create mode 100644 .github/workflows/lint.yml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 000000000..bd8a9b828 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,55 @@ +name: golangci-lint +on: + push: + branches: + - master + - main + pull_request: + +permissions: + contents: read + # Optional: allow read access to pull request. Use with `only-new-issues` option. + # pull-requests: read + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: '1.20' + cache: false + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + # Require: The version of golangci-lint to use. + # When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version. + # When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit. + version: latest + + # Optional: working directory, useful for monorepos + # working-directory: somedir + + # Optional: golangci-lint command line arguments. + # + # Note: By default, the `.golangci.yml` file should be at the root of the repository. + # The location of the configuration file can be changed by using `--config=` + # args: --timeout=30m --config=/my/path/.golangci.yml --issues-exit-code=0 + + # Optional: show only new issues if it's a pull request. The default value is `false`. + # only-new-issues: true + + # Optional: if set to true, then all caching functionality will be completely disabled, + # takes precedence over all other caching options. + # skip-cache: true + + # Optional: if set to true, then the action won't cache or restore ~/go/pkg. + # skip-pkg-cache: true + + # Optional: if set to true, then the action won't cache or restore ~/.cache/go-build. + # skip-build-cache: true + + # Optional: The mode to install golangci-lint. It can be 'binary' or 'goinstall'. + # install-mode: "goinstall" diff --git a/.golangci.yml b/.golangci.yml index 9d846393d..d555d3eaf 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,70 +1,139 @@ +run: + tests: true + timeout: 10m + sort-results: true + allow-parallel-runners: true + exclude-dir: testutil/testdata + skip-files: + - server/grpc/gogoreflection/fix_registration.go + linters: + disable-all: true enable: - - asciicheck - - bodyclose - - deadcode - - depguard - - dogsled - - dupl - - errcheck - - exportloopref - # - funlen - # - gochecknoglobals - # - gochecknoinits - # - gocognit - - goconst - # - gocritic - # - gocyclo - # - godox - - gofmt - - goimports - - revive - - gosec - - gosimple - - govet - - ineffassign - # - interfacer - - lll - # - maligned - # - misspell + # - dogsled + # - exportloopref + # - goconst + # - gocritic + - gci + - gofumpt + # - gosec + # - gosimple + # - govet + # - ineffassign + # - misspell - nakedret - - nolintlint - - prealloc - - staticcheck - - structcheck - - stylecheck - # - typecheck - - unconvert - # - unparam - - unused - - varcheck - # - whitespace - # - wsl +# - nolintlint +# - staticcheck +# - revive +# - stylecheck +# - typecheck +# - unconvert +# - unused issues: exclude-rules: - - path: _test\.go + - text: 'Use of weak random number generator' linters: - gosec - - linters: - - lll - source: "https://" - max-same-issues: 50 + - text: 'ST1003:' + linters: + - stylecheck + # FIXME: Disabled until golangci-lint updates stylecheck with this fix: + # https://github.com/dominikh/go-tools/issues/389 + - text: 'ST1016:' + linters: + - stylecheck + - path: 'migrations' + text: 'SA1019:' + linters: + - staticcheck + - text: 'SA1019: codec.NewAminoCodec is deprecated' # TODO remove once migration path is set out + linters: + - staticcheck + - text: 'SA1019: legacybech32.MustMarshalPubKey' # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: 'SA1019: legacybech32.MarshalPubKey' # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: 'SA1019: legacybech32.UnmarshalPubKey' # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: 'leading space' + linters: + - nolintlint + + max-issues-per-linter: 10000 + max-same-issues: 10000 linters-settings: - dogsled: - max-blank-identifiers: 3 - maligned: - suggest-new: true - # govet: - # check-shadowing: true + gci: + custom-order: true + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(cosmossdk.io) + - prefix(github.com/cosmos/cosmos-sdk) revive: - min-confidence: 0 - maligned: - suggest-new: true + rules: + - name: redefines-builtin-id + disabled: true + + gosec: + # To select a subset of rules to run. + # Available rules: https://github.com/securego/gosec#available-rules + # Default: [] - means include all rules + includes: + # - G101 # Look for hard coded credentials + - G102 # Bind to all interfaces + - G103 # Audit the use of unsafe block + - G104 # Audit errors not checked + - G106 # Audit the use of ssh.InsecureIgnoreHostKey + - G107 # Url provided to HTTP request as taint input + - G108 # Profiling endpoint automatically exposed on /debug/pprof + - G109 # Potential Integer overflow made by strconv.Atoi result conversion to int16/32 + - G110 # Potential DoS vulnerability via decompression bomb + - G111 # Potential directory traversal + - G112 # Potential slowloris attack + - G113 # Usage of Rat.SetString in math/big with an overflow (CVE-2022-23772) + - G114 # Use of net/http serve function that has no support for setting timeouts + - G201 # SQL query construction using format string + - G202 # SQL query construction using string concatenation + - G203 # Use of unescaped data in HTML templates + - G204 # Audit use of command execution + - G301 # Poor file permissions used when creating a directory + - G302 # Poor file permissions used with chmod + - G303 # Creating tempfile using a predictable path + - G304 # File path provided as taint input + - G305 # File traversal when extracting zip/tar archive + - G306 # Poor file permissions used when writing to a new file + - G307 # Deferring a method which returns an error + - G401 # Detect the usage of DES, RC4, MD5 or SHA1 + - G402 # Look for bad TLS connection settings + - G403 # Ensure minimum RSA key length of 2048 bits + - G404 # Insecure random number source (rand) + - G501 # Import blocklist: crypto/md5 + - G502 # Import blocklist: crypto/des + - G503 # Import blocklist: crypto/rc4 + - G504 # Import blocklist: net/http/cgi + - G505 # Import blocklist: crypto/sha1 + - G601 # Implicit memory aliasing of items from a range statement misspell: locale: US - ignore-words: - - behaviour - + gofumpt: + extra-rules: true + dogsled: + max-blank-identifiers: 5 + nolintlint: + allow-unused: false + allow-leading-space: true + require-explanation: true + require-specific: false + gosimple: + checks: ['all'] + gocritic: + disabled-checks: + - regexpMust + - appendAssign + - ifElseChain diff --git a/abci/client/grpc_client.go b/abci/client/grpc_client.go index add267790..f95c0055d 100644 --- a/abci/client/grpc_client.go +++ b/abci/client/grpc_client.go @@ -6,13 +6,12 @@ import ( "sync" "time" - "golang.org/x/net/context" - "google.golang.org/grpc" - "github.com/consideritdone/landslidecore/abci/types" tmnet "github.com/consideritdone/landslidecore/libs/net" "github.com/consideritdone/landslidecore/libs/service" tmsync "github.com/consideritdone/landslidecore/libs/sync" + "golang.org/x/net/context" + "google.golang.org/grpc" ) var _ Client = (*grpcClient)(nil) @@ -408,13 +407,15 @@ func (cli *grpcClient) OfferSnapshotSync(params types.RequestOfferSnapshot) (*ty } func (cli *grpcClient) LoadSnapshotChunkSync( - params types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + params types.RequestLoadSnapshotChunk, +) (*types.ResponseLoadSnapshotChunk, error) { reqres := cli.LoadSnapshotChunkAsync(params) return cli.finishSyncCall(reqres).GetLoadSnapshotChunk(), cli.Error() } func (cli *grpcClient) ApplySnapshotChunkSync( - params types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + params types.RequestApplySnapshotChunk, +) (*types.ResponseApplySnapshotChunk, error) { reqres := cli.ApplySnapshotChunkAsync(params) return cli.finishSyncCall(reqres).GetApplySnapshotChunk(), cli.Error() } diff --git a/abci/client/local_client.go b/abci/client/local_client.go index bbedc7588..81136fe96 100644 --- a/abci/client/local_client.go +++ b/abci/client/local_client.go @@ -306,7 +306,8 @@ func (app *localClient) OfferSnapshotSync(req types.RequestOfferSnapshot) (*type } func (app *localClient) LoadSnapshotChunkSync( - req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + req types.RequestLoadSnapshotChunk, +) (*types.ResponseLoadSnapshotChunk, error) { app.mtx.Lock() defer app.mtx.Unlock() @@ -315,7 +316,8 @@ func (app *localClient) LoadSnapshotChunkSync( } func (app *localClient) ApplySnapshotChunkSync( - req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + req types.RequestApplySnapshotChunk, +) (*types.ResponseApplySnapshotChunk, error) { app.mtx.Lock() defer app.mtx.Unlock() diff --git a/abci/client/socket_client.go b/abci/client/socket_client.go index 72fa04d83..3694adbb4 100644 --- a/abci/client/socket_client.go +++ b/abci/client/socket_client.go @@ -153,7 +153,7 @@ func (cli *socketClient) sendRequestsRoutine(conn io.Writer) { func (cli *socketClient) recvResponseRoutine(conn io.Reader) { r := bufio.NewReader(conn) for { - var res = &types.Response{} + res := &types.Response{} err := types.ReadMessage(r, res) if err != nil { cli.stopForError(fmt.Errorf("read message: %w", err)) @@ -399,7 +399,8 @@ func (cli *socketClient) OfferSnapshotSync(req types.RequestOfferSnapshot) (*typ } func (cli *socketClient) LoadSnapshotChunkSync( - req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + req types.RequestLoadSnapshotChunk, +) (*types.ResponseLoadSnapshotChunk, error) { reqres := cli.queueRequest(types.ToRequestLoadSnapshotChunk(req)) if err := cli.FlushSync(); err != nil { return nil, err @@ -409,7 +410,8 @@ func (cli *socketClient) LoadSnapshotChunkSync( } func (cli *socketClient) ApplySnapshotChunkSync( - req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + req types.RequestApplySnapshotChunk, +) (*types.ResponseApplySnapshotChunk, error) { reqres := cli.queueRequest(types.ToRequestApplySnapshotChunk(req)) if err := cli.FlushSync(); err != nil { return nil, err diff --git a/abci/client/socket_client_test.go b/abci/client/socket_client_test.go index a40346b64..76dcefc7c 100644 --- a/abci/client/socket_client_test.go +++ b/abci/client/socket_client_test.go @@ -5,14 +5,13 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abcicli "github.com/consideritdone/landslidecore/abci/client" "github.com/consideritdone/landslidecore/abci/server" "github.com/consideritdone/landslidecore/abci/types" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/libs/service" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestProperSyncCalls(t *testing.T) { @@ -93,7 +92,8 @@ func TestHangingSyncCalls(t *testing.T) { } func setupClientServer(t *testing.T, app types.Application) ( - service.Service, abcicli.Client) { + service.Service, abcicli.Client, +) { // some port between 20k and 30k port := 20000 + tmrand.Int32()%10000 addr := fmt.Sprintf("localhost:%d", port) diff --git a/abci/cmd/abci-cli/abci-cli.go b/abci/cmd/abci-cli/abci-cli.go index f080fae20..7bbe809f9 100644 --- a/abci/cmd/abci-cli/abci-cli.go +++ b/abci/cmd/abci-cli/abci-cli.go @@ -9,11 +9,6 @@ import ( "os" "strings" - "github.com/spf13/cobra" - - "github.com/consideritdone/landslidecore/libs/log" - tmos "github.com/consideritdone/landslidecore/libs/os" - abcicli "github.com/consideritdone/landslidecore/abci/client" "github.com/consideritdone/landslidecore/abci/example/code" "github.com/consideritdone/landslidecore/abci/example/counter" @@ -22,7 +17,10 @@ import ( servertest "github.com/consideritdone/landslidecore/abci/tests/server" "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/abci/version" + "github.com/consideritdone/landslidecore/libs/log" + tmos "github.com/consideritdone/landslidecore/libs/os" "github.com/consideritdone/landslidecore/proto/tendermint/crypto" + "github.com/spf13/cobra" ) // client is a global variable so it can be reused by the console @@ -56,7 +54,6 @@ var RootCmd = &cobra.Command{ Short: "the ABCI CLI tool wraps an ABCI client", Long: "the ABCI CLI tool wraps an ABCI client and is used for testing ABCI servers", PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - switch cmd.Use { case "counter", "kvstore": // for the examples apps, don't pre-run return nil @@ -209,6 +206,7 @@ var echoCmd = &cobra.Command{ Args: cobra.ExactArgs(1), RunE: cmdEcho, } + var infoCmd = &cobra.Command{ Use: "info", Short: "get some info about the application", @@ -216,6 +214,7 @@ var infoCmd = &cobra.Command{ Args: cobra.ExactArgs(0), RunE: cmdInfo, } + var setOptionCmd = &cobra.Command{ Use: "set_option", Short: "set an option on the application", @@ -293,7 +292,6 @@ var testCmd = &cobra.Command{ // Generates new Args array based off of previous call args to maintain flag persistence func persistentArgs(line []byte) []string { - // generate the arguments to run from original os.Args // to maintain flag arguments args := os.Args @@ -688,7 +686,6 @@ func cmdKVStore(cmd *cobra.Command, args []string) error { //-------------------------------------------------------------------------------- func printResponse(cmd *cobra.Command, args []string, rsp response) { - if flagVerbose { fmt.Println(">", cmd.Use, strings.Join(args, " ")) } @@ -698,7 +695,6 @@ func printResponse(cmd *cobra.Command, args []string, rsp response) { fmt.Printf("-> code: OK\n") } else { fmt.Printf("-> code: %d\n", rsp.Code) - } if len(rsp.Data) != 0 { diff --git a/abci/example/counter/counter.go b/abci/example/counter/counter.go index 4ee666270..a1fcedeaf 100644 --- a/abci/example/counter/counter.go +++ b/abci/example/counter/counter.go @@ -47,7 +47,8 @@ func (app *Application) DeliverTx(req types.RequestDeliverTx) types.ResponseDeli if len(req.Tx) > 8 { return types.ResponseDeliverTx{ Code: code.CodeTypeEncodingError, - Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(req.Tx))} + Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(req.Tx)), + } } tx8 := make([]byte, 8) copy(tx8[len(tx8)-len(req.Tx):], req.Tx) @@ -55,7 +56,8 @@ func (app *Application) DeliverTx(req types.RequestDeliverTx) types.ResponseDeli if txValue != uint64(app.txCount) { return types.ResponseDeliverTx{ Code: code.CodeTypeBadNonce, - Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)} + Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue), + } } } app.txCount++ @@ -67,7 +69,8 @@ func (app *Application) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx if len(req.Tx) > 8 { return types.ResponseCheckTx{ Code: code.CodeTypeEncodingError, - Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(req.Tx))} + Log: fmt.Sprintf("Max tx size is 8 bytes, got %d", len(req.Tx)), + } } tx8 := make([]byte, 8) copy(tx8[len(tx8)-len(req.Tx):], req.Tx) @@ -75,7 +78,8 @@ func (app *Application) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx if txValue < uint64(app.txCount) { return types.ResponseCheckTx{ Code: code.CodeTypeBadNonce, - Log: fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue)} + Log: fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue), + } } } return types.ResponseCheckTx{Code: code.CodeTypeOK} diff --git a/abci/example/example_test.go b/abci/example/example_test.go index f11707dde..a33c95cfe 100644 --- a/abci/example/example_test.go +++ b/abci/example/example_test.go @@ -9,20 +9,16 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - - "google.golang.org/grpc" - - "golang.org/x/net/context" - - "github.com/consideritdone/landslidecore/libs/log" - tmnet "github.com/consideritdone/landslidecore/libs/net" - abcicli "github.com/consideritdone/landslidecore/abci/client" "github.com/consideritdone/landslidecore/abci/example/code" "github.com/consideritdone/landslidecore/abci/example/kvstore" abciserver "github.com/consideritdone/landslidecore/abci/server" "github.com/consideritdone/landslidecore/abci/types" + "github.com/consideritdone/landslidecore/libs/log" + tmnet "github.com/consideritdone/landslidecore/libs/net" + "github.com/stretchr/testify/require" + "golang.org/x/net/context" + "google.golang.org/grpc" ) func init() { diff --git a/abci/example/kvstore/kvstore.go b/abci/example/kvstore/kvstore.go index 7a4da6484..a7d79da1a 100644 --- a/abci/example/kvstore/kvstore.go +++ b/abci/example/kvstore/kvstore.go @@ -6,11 +6,10 @@ import ( "encoding/json" "fmt" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/code" "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/version" + dbm "github.com/tendermint/tm-db" ) var ( diff --git a/abci/example/kvstore/kvstore_test.go b/abci/example/kvstore/kvstore_test.go index 4ec3b3ff3..6f9d51a38 100644 --- a/abci/example/kvstore/kvstore_test.go +++ b/abci/example/kvstore/kvstore_test.go @@ -6,16 +6,14 @@ import ( "sort" "testing" - "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/libs/log" - "github.com/consideritdone/landslidecore/libs/service" - abcicli "github.com/consideritdone/landslidecore/abci/client" "github.com/consideritdone/landslidecore/abci/example/code" abciserver "github.com/consideritdone/landslidecore/abci/server" "github.com/consideritdone/landslidecore/abci/types" + "github.com/consideritdone/landslidecore/libs/log" + "github.com/consideritdone/landslidecore/libs/service" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/stretchr/testify/require" ) const ( @@ -114,7 +112,6 @@ func TestPersistentKVStoreInfo(t *testing.T) { if resInfo.LastBlockHeight != height { t.Fatalf("expected height of %d, got %d", height, resInfo.LastBlockHeight) } - } // add a validator, remove a validator, update a validator @@ -181,7 +178,6 @@ func TestValUpdates(t *testing.T) { vals1 = append([]types.ValidatorUpdate{v1}, vals1[1:]...) vals2 = kvstore.Validators() valsEqual(t, vals1, vals2) - } func makeApplyBlock( @@ -189,7 +185,8 @@ func makeApplyBlock( kvstore types.Application, heightInt int, diff []types.ValidatorUpdate, - txs ...[]byte) { + txs ...[]byte, +) { // make and apply block height := int64(heightInt) hash := []byte("foo") @@ -207,7 +204,6 @@ func makeApplyBlock( kvstore.Commit() valsEqual(t, diff, resEndBlock.ValidatorUpdates) - } // order doesn't matter diff --git a/abci/example/kvstore/persistent_kvstore.go b/abci/example/kvstore/persistent_kvstore.go index fdfc71784..9a60b3072 100644 --- a/abci/example/kvstore/persistent_kvstore.go +++ b/abci/example/kvstore/persistent_kvstore.go @@ -7,13 +7,12 @@ import ( "strconv" "strings" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/code" "github.com/consideritdone/landslidecore/abci/types" cryptoenc "github.com/consideritdone/landslidecore/crypto/encoding" "github.com/consideritdone/landslidecore/libs/log" pc "github.com/consideritdone/landslidecore/proto/tendermint/crypto" + dbm "github.com/tendermint/tm-db" ) const ( @@ -151,22 +150,26 @@ func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) typ } func (app *PersistentKVStoreApplication) ListSnapshots( - req types.RequestListSnapshots) types.ResponseListSnapshots { + req types.RequestListSnapshots, +) types.ResponseListSnapshots { return types.ResponseListSnapshots{} } func (app *PersistentKVStoreApplication) LoadSnapshotChunk( - req types.RequestLoadSnapshotChunk) types.ResponseLoadSnapshotChunk { + req types.RequestLoadSnapshotChunk, +) types.ResponseLoadSnapshotChunk { return types.ResponseLoadSnapshotChunk{} } func (app *PersistentKVStoreApplication) OfferSnapshot( - req types.RequestOfferSnapshot) types.ResponseOfferSnapshot { + req types.RequestOfferSnapshot, +) types.ResponseOfferSnapshot { return types.ResponseOfferSnapshot{Result: types.ResponseOfferSnapshot_ABORT} } func (app *PersistentKVStoreApplication) ApplySnapshotChunk( - req types.RequestApplySnapshotChunk) types.ResponseApplySnapshotChunk { + req types.RequestApplySnapshotChunk, +) types.ResponseApplySnapshotChunk { return types.ResponseApplySnapshotChunk{Result: types.ResponseApplySnapshotChunk_ABORT} } @@ -217,7 +220,8 @@ func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.Respon if len(pubKeyAndPower) != 2 { return types.ResponseDeliverTx{ Code: code.CodeTypeEncodingError, - Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)} + Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower), + } } pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1] @@ -226,7 +230,8 @@ func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.Respon if err != nil { return types.ResponseDeliverTx{ Code: code.CodeTypeEncodingError, - Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)} + Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS), + } } // decode the power @@ -234,7 +239,8 @@ func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.Respon if err != nil { return types.ResponseDeliverTx{ Code: code.CodeTypeEncodingError, - Log: fmt.Sprintf("Power (%s) is not an int", powerS)} + Log: fmt.Sprintf("Power (%s) is not an int", powerS), + } } // update @@ -259,7 +265,8 @@ func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate pubStr := base64.StdEncoding.EncodeToString(pubkey.Bytes()) return types.ResponseDeliverTx{ Code: code.CodeTypeUnauthorized, - Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)} + Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr), + } } if err = app.app.state.db.Delete(key); err != nil { panic(err) @@ -271,7 +278,8 @@ func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate if err := types.WriteMessage(&v, value); err != nil { return types.ResponseDeliverTx{ Code: code.CodeTypeEncodingError, - Log: fmt.Sprintf("Error encoding validator: %v", err)} + Log: fmt.Sprintf("Error encoding validator: %v", err), + } } if err = app.app.state.db.Set(key, value.Bytes()); err != nil { panic(err) diff --git a/abci/server/grpc_server.go b/abci/server/grpc_server.go index 812ab572b..f37e3f111 100644 --- a/abci/server/grpc_server.go +++ b/abci/server/grpc_server.go @@ -3,11 +3,10 @@ package server import ( "net" - "google.golang.org/grpc" - "github.com/consideritdone/landslidecore/abci/types" tmnet "github.com/consideritdone/landslidecore/libs/net" "github.com/consideritdone/landslidecore/libs/service" + "google.golang.org/grpc" ) type GRPCServer struct { @@ -36,7 +35,6 @@ func NewGRPCServer(protoAddr string, app types.ABCIApplicationServer) service.Se // OnStart starts the gRPC service. func (s *GRPCServer) OnStart() error { - ln, err := net.Listen(s.proto, s.addr) if err != nil { return err diff --git a/abci/server/socket_server.go b/abci/server/socket_server.go index df45edac1..1132b8225 100644 --- a/abci/server/socket_server.go +++ b/abci/server/socket_server.go @@ -154,7 +154,7 @@ func (s *SocketServer) waitForClose(closeConn chan error, connID int) { // Read requests from conn and deal with them func (s *SocketServer) handleRequests(closeConn chan error, conn io.Reader, responses chan<- *types.Response) { var count int - var bufReader = bufio.NewReader(conn) + bufReader := bufio.NewReader(conn) defer func() { // make sure to recover from any app-related panics to allow proper socket cleanup @@ -174,7 +174,7 @@ func (s *SocketServer) handleRequests(closeConn chan error, conn io.Reader, resp for { - var req = &types.Request{} + req := &types.Request{} err := types.ReadMessage(bufReader, req) if err != nil { if err == io.EOF { @@ -244,9 +244,9 @@ func (s *SocketServer) handleRequest(req *types.Request, responses chan<- *types // Pull responses from 'responses' and write them to conn. func (s *SocketServer) handleResponses(closeConn chan error, conn io.Writer, responses <-chan *types.Response) { var count int - var bufWriter = bufio.NewWriter(conn) + bufWriter := bufio.NewWriter(conn) for { - var res = <-responses + res := <-responses err := types.WriteMessage(res, bufWriter) if err != nil { closeConn <- fmt.Errorf("error writing message: %w", err) diff --git a/abci/tests/benchmarks/parallel/parallel.go b/abci/tests/benchmarks/parallel/parallel.go index 40521657e..680c83b9b 100644 --- a/abci/tests/benchmarks/parallel/parallel.go +++ b/abci/tests/benchmarks/parallel/parallel.go @@ -10,7 +10,6 @@ import ( ) func main() { - conn, err := tmnet.Connect("unix://test.sock") if err != nil { log.Fatal(err.Error()) @@ -20,7 +19,7 @@ func main() { go func() { counter := 0 for { - var res = &types.Response{} + res := &types.Response{} err := types.ReadMessage(conn, res) if err != nil { log.Fatal(err.Error()) @@ -35,8 +34,8 @@ func main() { // Write a bunch of requests counter := 0 for i := 0; ; i++ { - var bufWriter = bufio.NewWriter(conn) - var req = types.ToRequestEcho("foobar") + bufWriter := bufio.NewWriter(conn) + req := types.ToRequestEcho("foobar") err := types.WriteMessage(req, bufWriter) if err != nil { diff --git a/abci/tests/benchmarks/simple/simple.go b/abci/tests/benchmarks/simple/simple.go index 1240d4ba2..6e401666b 100644 --- a/abci/tests/benchmarks/simple/simple.go +++ b/abci/tests/benchmarks/simple/simple.go @@ -12,7 +12,6 @@ import ( ) func main() { - conn, err := tmnet.Connect("unix://test.sock") if err != nil { log.Fatal(err.Error()) @@ -34,7 +33,7 @@ func main() { } func makeRequest(conn io.ReadWriter, req *types.Request) (*types.Response, error) { - var bufWriter = bufio.NewWriter(conn) + bufWriter := bufio.NewWriter(conn) // Write desired request err := types.WriteMessage(req, bufWriter) @@ -51,12 +50,12 @@ func makeRequest(conn io.ReadWriter, req *types.Request) (*types.Response, error } // Read desired response - var res = &types.Response{} + res := &types.Response{} err = types.ReadMessage(conn, res) if err != nil { return nil, err } - var resFlush = &types.Response{} + resFlush := &types.Response{} err = types.ReadMessage(conn, resFlush) if err != nil { return nil, err diff --git a/abci/tests/client_server_test.go b/abci/tests/client_server_test.go index 074432f6a..1c63896b4 100644 --- a/abci/tests/client_server_test.go +++ b/abci/tests/client_server_test.go @@ -3,11 +3,10 @@ package tests import ( "testing" - "github.com/stretchr/testify/assert" - abciclient "github.com/consideritdone/landslidecore/abci/client" "github.com/consideritdone/landslidecore/abci/example/kvstore" abciserver "github.com/consideritdone/landslidecore/abci/server" + "github.com/stretchr/testify/assert" ) func TestClientServerNoAddrPrefix(t *testing.T) { diff --git a/abci/types/application.go b/abci/types/application.go index 65cc78b8c..4fb22fde0 100644 --- a/abci/types/application.go +++ b/abci/types/application.go @@ -36,8 +36,7 @@ type Application interface { var _ Application = (*BaseApplication)(nil) -type BaseApplication struct { -} +type BaseApplication struct{} func NewBaseApplication() *BaseApplication { return &BaseApplication{} @@ -160,25 +159,29 @@ func (app *GRPCApplication) EndBlock(ctx context.Context, req *RequestEndBlock) } func (app *GRPCApplication) ListSnapshots( - ctx context.Context, req *RequestListSnapshots) (*ResponseListSnapshots, error) { + ctx context.Context, req *RequestListSnapshots, +) (*ResponseListSnapshots, error) { res := app.app.ListSnapshots(*req) return &res, nil } func (app *GRPCApplication) OfferSnapshot( - ctx context.Context, req *RequestOfferSnapshot) (*ResponseOfferSnapshot, error) { + ctx context.Context, req *RequestOfferSnapshot, +) (*ResponseOfferSnapshot, error) { res := app.app.OfferSnapshot(*req) return &res, nil } func (app *GRPCApplication) LoadSnapshotChunk( - ctx context.Context, req *RequestLoadSnapshotChunk) (*ResponseLoadSnapshotChunk, error) { + ctx context.Context, req *RequestLoadSnapshotChunk, +) (*ResponseLoadSnapshotChunk, error) { res := app.app.LoadSnapshotChunk(*req) return &res, nil } func (app *GRPCApplication) ApplySnapshotChunk( - ctx context.Context, req *RequestApplySnapshotChunk) (*ResponseApplySnapshotChunk, error) { + ctx context.Context, req *RequestApplySnapshotChunk, +) (*ResponseApplySnapshotChunk, error) { res := app.app.ApplySnapshotChunk(*req) return &res, nil } diff --git a/abci/types/messages_test.go b/abci/types/messages_test.go index de252a491..472628bdf 100644 --- a/abci/types/messages_test.go +++ b/abci/types/messages_test.go @@ -6,10 +6,9 @@ import ( "strings" "testing" + tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/assert" - - tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" ) func TestMarshalJSON(t *testing.T) { diff --git a/abci/types/result.go b/abci/types/result.go index 53acdb906..e2d7316e7 100644 --- a/abci/types/result.go +++ b/abci/types/result.go @@ -122,10 +122,12 @@ type jsonRoundTripper interface { json.Unmarshaler } -var _ jsonRoundTripper = (*ResponseCommit)(nil) -var _ jsonRoundTripper = (*ResponseQuery)(nil) -var _ jsonRoundTripper = (*ResponseDeliverTx)(nil) -var _ jsonRoundTripper = (*ResponseCheckTx)(nil) -var _ jsonRoundTripper = (*ResponseSetOption)(nil) +var ( + _ jsonRoundTripper = (*ResponseCommit)(nil) + _ jsonRoundTripper = (*ResponseQuery)(nil) + _ jsonRoundTripper = (*ResponseDeliverTx)(nil) + _ jsonRoundTripper = (*ResponseCheckTx)(nil) + _ jsonRoundTripper = (*ResponseSetOption)(nil) +) var _ jsonRoundTripper = (*EventAttribute)(nil) diff --git a/behaviour/doc.go b/behaviour/doc.go index 40061e095..7b00ae1eb 100644 --- a/behaviour/doc.go +++ b/behaviour/doc.go @@ -8,35 +8,34 @@ There are four different behaviours a reactor can report. 1. bad message -type badMessage struct { - explanation string -} + type badMessage struct { + explanation string + } -This message will request the peer be stopped for an error +# This message will request the peer be stopped for an error 2. message out of order -type messageOutOfOrder struct { - explanation string -} + type messageOutOfOrder struct { + explanation string + } -This message will request the peer be stopped for an error +# This message will request the peer be stopped for an error 3. consesnsus Vote -type consensusVote struct { - explanation string -} + type consensusVote struct { + explanation string + } -This message will request the peer be marked as good +# This message will request the peer be marked as good 4. block part -type blockPart struct { - explanation string -} + type blockPart struct { + explanation string + } This message will request the peer be marked as good - */ package behaviour diff --git a/behaviour/reporter_test.go b/behaviour/reporter_test.go index f496ae0f2..315860c6c 100644 --- a/behaviour/reporter_test.go +++ b/behaviour/reporter_test.go @@ -40,7 +40,7 @@ type scriptItem struct { // equalBehaviours returns true if a and b contain the same PeerBehaviours with // the same freequencies and otherwise false. -func equalBehaviours(a []bh.PeerBehaviour, b []bh.PeerBehaviour) bool { +func equalBehaviours(a, b []bh.PeerBehaviour) bool { aHistogram := map[bh.PeerBehaviour]int{} bHistogram := map[bh.PeerBehaviour]int{} @@ -88,11 +88,15 @@ func TestEqualPeerBehaviours(t *testing.T) { // Single behaviours {[]bh.PeerBehaviour{consensusVote}, []bh.PeerBehaviour{consensusVote}}, // Equal Frequencies - {[]bh.PeerBehaviour{consensusVote, consensusVote}, - []bh.PeerBehaviour{consensusVote, consensusVote}}, + { + []bh.PeerBehaviour{consensusVote, consensusVote}, + []bh.PeerBehaviour{consensusVote, consensusVote}, + }, // Equal frequencies different orders - {[]bh.PeerBehaviour{consensusVote, blockPart}, - []bh.PeerBehaviour{blockPart, consensusVote}}, + { + []bh.PeerBehaviour{consensusVote, blockPart}, + []bh.PeerBehaviour{blockPart, consensusVote}, + }, } unequals = []struct { left []bh.PeerBehaviour @@ -103,8 +107,10 @@ func TestEqualPeerBehaviours(t *testing.T) { // Different behaviours {[]bh.PeerBehaviour{consensusVote}, []bh.PeerBehaviour{blockPart}}, // Same behaviour with different frequencies - {[]bh.PeerBehaviour{consensusVote}, - []bh.PeerBehaviour{consensusVote, consensusVote}}, + { + []bh.PeerBehaviour{consensusVote}, + []bh.PeerBehaviour{consensusVote, consensusVote}, + }, } ) @@ -126,33 +132,40 @@ func TestEqualPeerBehaviours(t *testing.T) { // This test reproduces the conditions in which MockReporter will // be used within a Reactor `Receive` method tests to ensure thread safety. func TestMockPeerBehaviourReporterConcurrency(t *testing.T) { - var ( - behaviourScript = []struct { - peerID p2p.ID - behaviours []bh.PeerBehaviour - }{ - {"1", []bh.PeerBehaviour{bh.ConsensusVote("1", "")}}, - {"2", []bh.PeerBehaviour{bh.ConsensusVote("2", ""), bh.ConsensusVote("2", ""), bh.ConsensusVote("2", "")}}, - { - "3", - []bh.PeerBehaviour{bh.BlockPart("3", ""), - bh.ConsensusVote("3", ""), - bh.BlockPart("3", ""), - bh.ConsensusVote("3", "")}}, - { - "4", - []bh.PeerBehaviour{bh.ConsensusVote("4", ""), - bh.ConsensusVote("4", ""), - bh.ConsensusVote("4", ""), - bh.ConsensusVote("4", "")}}, - { - "5", - []bh.PeerBehaviour{bh.BlockPart("5", ""), - bh.ConsensusVote("5", ""), - bh.BlockPart("5", ""), - bh.ConsensusVote("5", "")}}, - } - ) + behaviourScript := []struct { + peerID p2p.ID + behaviours []bh.PeerBehaviour + }{ + {"1", []bh.PeerBehaviour{bh.ConsensusVote("1", "")}}, + {"2", []bh.PeerBehaviour{bh.ConsensusVote("2", ""), bh.ConsensusVote("2", ""), bh.ConsensusVote("2", "")}}, + { + "3", + []bh.PeerBehaviour{ + bh.BlockPart("3", ""), + bh.ConsensusVote("3", ""), + bh.BlockPart("3", ""), + bh.ConsensusVote("3", ""), + }, + }, + { + "4", + []bh.PeerBehaviour{ + bh.ConsensusVote("4", ""), + bh.ConsensusVote("4", ""), + bh.ConsensusVote("4", ""), + bh.ConsensusVote("4", ""), + }, + }, + { + "5", + []bh.PeerBehaviour{ + bh.BlockPart("5", ""), + bh.ConsensusVote("5", ""), + bh.BlockPart("5", ""), + bh.ConsensusVote("5", ""), + }, + }, + } var receiveWg sync.WaitGroup pr := bh.NewMockReporter() diff --git a/blockchain/msgs.go b/blockchain/msgs.go index 18ac42329..afabfb9bf 100644 --- a/blockchain/msgs.go +++ b/blockchain/msgs.go @@ -4,10 +4,9 @@ import ( "errors" "fmt" - "github.com/gogo/protobuf/proto" - bcproto "github.com/consideritdone/landslidecore/proto/tendermint/blockchain" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" ) const ( diff --git a/blockchain/msgs_test.go b/blockchain/msgs_test.go index 8b56ff2cc..e42e075d9 100644 --- a/blockchain/msgs_test.go +++ b/blockchain/msgs_test.go @@ -5,12 +5,11 @@ import ( "math" "testing" + bcproto "github.com/consideritdone/landslidecore/proto/tendermint/blockchain" + "github.com/consideritdone/landslidecore/types" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - bcproto "github.com/consideritdone/landslidecore/proto/tendermint/blockchain" - "github.com/consideritdone/landslidecore/types" ) func TestBcBlockRequestMessageValidateBasic(t *testing.T) { @@ -92,26 +91,44 @@ func TestBlockchainMessageVectors(t *testing.T) { expBytes string }{ {"BlockRequestMessage", &bcproto.Message{Sum: &bcproto.Message_BlockRequest{ - BlockRequest: &bcproto.BlockRequest{Height: 1}}}, "0a020801"}, - {"BlockRequestMessage", &bcproto.Message{Sum: &bcproto.Message_BlockRequest{ - BlockRequest: &bcproto.BlockRequest{Height: math.MaxInt64}}}, - "0a0a08ffffffffffffffff7f"}, + BlockRequest: &bcproto.BlockRequest{Height: 1}, + }}, "0a020801"}, + { + "BlockRequestMessage", &bcproto.Message{Sum: &bcproto.Message_BlockRequest{ + BlockRequest: &bcproto.BlockRequest{Height: math.MaxInt64}, + }}, + "0a0a08ffffffffffffffff7f", + }, {"BlockResponseMessage", &bcproto.Message{Sum: &bcproto.Message_BlockResponse{ - BlockResponse: &bcproto.BlockResponse{Block: bpb}}}, "1a700a6e0a5b0a02080b1803220b088092b8c398feffffff012a0212003a20c4da88e876062aa1543400d50d0eaa0dac88096057949cfb7bca7f3a48c04bf96a20e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855120d0a0b48656c6c6f20576f726c641a00"}, - {"NoBlockResponseMessage", &bcproto.Message{Sum: &bcproto.Message_NoBlockResponse{ - NoBlockResponse: &bcproto.NoBlockResponse{Height: 1}}}, "12020801"}, + BlockResponse: &bcproto.BlockResponse{Block: bpb}, + }}, "1a700a6e0a5b0a02080b1803220b088092b8c398feffffff012a0212003a20c4da88e876062aa1543400d50d0eaa0dac88096057949cfb7bca7f3a48c04bf96a20e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855120d0a0b48656c6c6f20576f726c641a00"}, {"NoBlockResponseMessage", &bcproto.Message{Sum: &bcproto.Message_NoBlockResponse{ - NoBlockResponse: &bcproto.NoBlockResponse{Height: math.MaxInt64}}}, - "120a08ffffffffffffffff7f"}, - {"StatusRequestMessage", &bcproto.Message{Sum: &bcproto.Message_StatusRequest{ - StatusRequest: &bcproto.StatusRequest{}}}, - "2200"}, - {"StatusResponseMessage", &bcproto.Message{Sum: &bcproto.Message_StatusResponse{ - StatusResponse: &bcproto.StatusResponse{Height: 1, Base: 2}}}, - "2a0408011002"}, - {"StatusResponseMessage", &bcproto.Message{Sum: &bcproto.Message_StatusResponse{ - StatusResponse: &bcproto.StatusResponse{Height: math.MaxInt64, Base: math.MaxInt64}}}, - "2a1408ffffffffffffffff7f10ffffffffffffffff7f"}, + NoBlockResponse: &bcproto.NoBlockResponse{Height: 1}, + }}, "12020801"}, + { + "NoBlockResponseMessage", &bcproto.Message{Sum: &bcproto.Message_NoBlockResponse{ + NoBlockResponse: &bcproto.NoBlockResponse{Height: math.MaxInt64}, + }}, + "120a08ffffffffffffffff7f", + }, + { + "StatusRequestMessage", &bcproto.Message{Sum: &bcproto.Message_StatusRequest{ + StatusRequest: &bcproto.StatusRequest{}, + }}, + "2200", + }, + { + "StatusResponseMessage", &bcproto.Message{Sum: &bcproto.Message_StatusResponse{ + StatusResponse: &bcproto.StatusResponse{Height: 1, Base: 2}, + }}, + "2a0408011002", + }, + { + "StatusResponseMessage", &bcproto.Message{Sum: &bcproto.Message_StatusResponse{ + StatusResponse: &bcproto.StatusResponse{Height: math.MaxInt64, Base: math.MaxInt64}, + }}, + "2a1408ffffffffffffffff7f10ffffffffffffffff7f", + }, } for _, tc := range testCases { diff --git a/blockchain/v0/pool.go b/blockchain/v0/pool.go index 72b89f60e..1eb0fdd5c 100644 --- a/blockchain/v0/pool.go +++ b/blockchain/v0/pool.go @@ -189,7 +189,7 @@ func (pool *BlockPool) IsCaughtUp() bool { // We need to see the second block's Commit to validate the first block. // So we peek two blocks at a time. // The caller will verify the commit. -func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) { +func (pool *BlockPool) PeekTwoBlocks() (first, second *types.Block) { pool.mtx.Lock() defer pool.mtx.Unlock() @@ -286,7 +286,7 @@ func (pool *BlockPool) MaxPeerHeight() int64 { } // SetPeerRange sets the peer's alleged blockchain base and height. -func (pool *BlockPool) SetPeerRange(peerID p2p.ID, base int64, height int64) { +func (pool *BlockPool) SetPeerRange(peerID p2p.ID, base, height int64) { pool.mtx.Lock() defer pool.mtx.Unlock() @@ -445,7 +445,7 @@ type bpPeer struct { logger log.Logger } -func newBPPeer(pool *BlockPool, peerID p2p.ID, base int64, height int64) *bpPeer { +func newBPPeer(pool *BlockPool, peerID p2p.ID, base, height int64) *bpPeer { peer := &bpPeer{ pool: pool, id: peerID, diff --git a/blockchain/v0/pool_test.go b/blockchain/v0/pool_test.go index 8caad8f5e..39c16ded4 100644 --- a/blockchain/v0/pool_test.go +++ b/blockchain/v0/pool_test.go @@ -5,13 +5,12 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/p2p" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func init() { diff --git a/blockchain/v0/reactor.go b/blockchain/v0/reactor.go index 52ea7e80d..7b144c522 100644 --- a/blockchain/v0/reactor.go +++ b/blockchain/v0/reactor.go @@ -63,8 +63,8 @@ type BlockchainReactor struct { // NewBlockchainReactor returns new reactor instance. func NewBlockchainReactor(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore, - fastSync bool) *BlockchainReactor { - + fastSync bool, +) *BlockchainReactor { if state.LastBlockHeight != store.Height() { panic(fmt.Sprintf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())) @@ -152,7 +152,8 @@ func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor { func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) { msgBytes, err := bc.EncodeMsg(&bcproto.StatusResponse{ Base: bcR.store.Base(), - Height: bcR.store.Height()}) + Height: bcR.store.Height(), + }) if err != nil { bcR.Logger.Error("could not convert msg to protobuf", "err", err) return @@ -173,8 +174,8 @@ func (bcR *BlockchainReactor) RemovePeer(peer p2p.Peer, reason interface{}) { // respondToPeer loads a block and sends it to the requesting peer, // if we have it. Otherwise, we'll respond saying we don't have it. func (bcR *BlockchainReactor) respondToPeer(msg *bcproto.BlockRequest, - src p2p.Peer) (queued bool) { - + src p2p.Peer, +) (queued bool) { block := bcR.store.LoadBlock(msg.Height) if block != nil { bl, err := block.ToProto() @@ -254,7 +255,6 @@ func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) // Handle messages from the poolReactor telling the reactor what to do. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down! func (bcR *BlockchainReactor) poolRoutine(stateSynced bool) { - trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond) defer trySyncTicker.Stop() diff --git a/blockchain/v0/reactor_test.go b/blockchain/v0/reactor_test.go index ad7f1602b..9cbf55faf 100644 --- a/blockchain/v0/reactor_test.go +++ b/blockchain/v0/reactor_test.go @@ -7,11 +7,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/log" @@ -22,6 +17,9 @@ import ( "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) var config *cfg.Config @@ -55,7 +53,8 @@ func newBlockchainReactor( logger log.Logger, genDoc *types.GenesisDoc, privVals []types.PrivValidator, - maxBlockHeight int64) BlockchainReactorPair { + maxBlockHeight int64, +) BlockchainReactorPair { if len(privVals) != 1 { panic("only support one validator") } @@ -146,7 +145,6 @@ func TestNoBlockResponse(t *testing.T) { p2p.MakeConnectedSwitches(config.P2P, 2, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("BLOCKCHAIN", reactorPairs[i].reactor) return s - }, p2p.Connect2Switches) defer func() { @@ -221,7 +219,6 @@ func TestBadBlockStopsPeer(t *testing.T) { switches := p2p.MakeConnectedSwitches(config.P2P, 4, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("BLOCKCHAIN", reactorPairs[i].reactor) return s - }, p2p.Connect2Switches) defer func() { @@ -260,7 +257,6 @@ func TestBadBlockStopsPeer(t *testing.T) { switches = append(switches, p2p.MakeConnectedSwitches(config.P2P, 1, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("BLOCKCHAIN", reactorPairs[len(reactorPairs)-1].reactor) return s - }, p2p.Connect2Switches)...) for i := 0; i < len(reactorPairs)-1; i++ { diff --git a/blockchain/v1/peer.go b/blockchain/v1/peer.go index 2ebf63650..2839dc77c 100644 --- a/blockchain/v1/peer.go +++ b/blockchain/v1/peer.go @@ -39,9 +39,9 @@ type BpPeer struct { } // NewBpPeer creates a new peer. -func NewBpPeer(peerID p2p.ID, base int64, height int64, - onErr func(err error, peerID p2p.ID), params *BpPeerParams) *BpPeer { - +func NewBpPeer(peerID p2p.ID, base, height int64, + onErr func(err error, peerID p2p.ID), params *BpPeerParams, +) *BpPeer { if params == nil { params = BpPeerDefaultParams() } diff --git a/blockchain/v1/peer_test.go b/blockchain/v1/peer_test.go index ace4288e3..85e8902e1 100644 --- a/blockchain/v1/peer_test.go +++ b/blockchain/v1/peer_test.go @@ -5,13 +5,12 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/p2p" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPeerMonitor(t *testing.T) { @@ -180,7 +179,6 @@ func TestPeerAddBlock(t *testing.T) { } func TestPeerOnErrFuncCalledDueToExpiration(t *testing.T) { - params := &BpPeerParams{timeout: 10 * time.Millisecond} var ( numErrFuncCalls int // number of calls to the onErr function diff --git a/blockchain/v1/pool.go b/blockchain/v1/pool.go index 3e3d9ab8f..de202f0e4 100644 --- a/blockchain/v1/pool.go +++ b/blockchain/v1/pool.go @@ -68,8 +68,7 @@ func (pool *BlockPool) updateMaxPeerHeight() { // UpdatePeer adds a new peer or updates an existing peer with a new base and height. // If a peer is short it is not added. -func (pool *BlockPool) UpdatePeer(peerID p2p.ID, base int64, height int64) error { - +func (pool *BlockPool) UpdatePeer(peerID p2p.ID, base, height int64) error { peer := pool.peers[peerID] if peer == nil { @@ -280,7 +279,6 @@ func (pool *BlockPool) BlockAndPeerAtHeight(height int64) (bData *BlockData, err } return &BlockData{peer: peer, block: block}, nil - } // FirstTwoBlocksAndPeers returns the blocks and the delivery peers at pool's height H and H+1. diff --git a/blockchain/v1/pool_test.go b/blockchain/v1/pool_test.go index aefa2af0e..0dbf14316 100644 --- a/blockchain/v1/pool_test.go +++ b/blockchain/v1/pool_test.go @@ -4,11 +4,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/p2p" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" ) type testPeer struct { @@ -46,7 +45,6 @@ func (testR *testBcR) resetStateTimer(name string, timer **time.Timer, timeout t } func (testR *testBcR) switchToConsensus() { - } func newTestBcR() *testBcR { @@ -87,7 +85,7 @@ func makeBlockPool(bcr *testBcR, height int64, peers []BpPeer, blocks map[int64] return bPool } -func assertPeerSetsEquivalent(t *testing.T, set1 map[p2p.ID]*BpPeer, set2 map[p2p.ID]*BpPeer) { +func assertPeerSetsEquivalent(t *testing.T, set1, set2 map[p2p.ID]*BpPeer) { assert.Equal(t, len(set1), len(set2)) for peerID, peer1 := range set1 { peer2 := set2[peerID] @@ -109,7 +107,6 @@ func assertBlockPoolEquivalent(t *testing.T, poolWanted, pool *BlockPool) { assertPeerSetsEquivalent(t, poolWanted.peers, pool.peers) assert.Equal(t, poolWanted.MaxPeerHeight, pool.MaxPeerHeight) assert.Equal(t, poolWanted.Height, pool.Height) - } func TestBlockPoolUpdatePeer(t *testing.T) { @@ -158,7 +155,8 @@ func TestBlockPoolUpdatePeer(t *testing.T) { name: "decrease the height of P1 from 105 to 102 with blocks", pool: makeBlockPool(testBcR, 100, []BpPeer{{ID: "P1", Height: 105}}, map[int64]tPBlocks{ - 100: {"P1", true}, 101: {"P1", true}, 102: {"P1", true}}), + 100: {"P1", true}, 101: {"P1", true}, 102: {"P1", true}, + }), args: testPeer{"P1", 0, 102}, errWanted: errPeerLowersItsHeight, poolWanted: makeBlockPool(testBcR, 100, []BpPeer{}, @@ -349,7 +347,8 @@ func TestBlockPoolSendRequestBatch(t *testing.T) { expRequestsSent: 4, expPeerResults: []testPeerResult{ {id: "P1", numPendingBlockRequests: 2}, - {id: "P2", numPendingBlockRequests: 2}}, + {id: "P2", numPendingBlockRequests: 2}, + }, }, } @@ -358,13 +357,13 @@ func TestBlockPoolSendRequestBatch(t *testing.T) { t.Run(tt.name, func(t *testing.T) { resetPoolTestResults() - var pool = tt.pool + pool := tt.pool maxRequestsPerPeer = tt.maxRequestsPerPeer pool.MakeNextRequests(10) assert.Equal(t, tt.expRequestsSent, testResults.numRequestsSent) for _, tPeer := range tt.expPeerResults { - var peer = pool.peers[tPeer.id] + peer := pool.peers[tPeer.id] assert.NotNil(t, peer) assert.Equal(t, tPeer.numPendingBlockRequests, peer.NumPendingBlockRequests) } @@ -388,7 +387,8 @@ func TestBlockPoolAddBlock(t *testing.T) { poolWanted *BlockPool errWanted error }{ - {name: "block from unknown peer", + { + name: "block from unknown peer", pool: makeBlockPool(testBcR, 10, []BpPeer{{ID: "P1", Height: 100}}, map[int64]tPBlocks{}), args: args{ peerID: "P2", @@ -398,7 +398,8 @@ func TestBlockPoolAddBlock(t *testing.T) { poolWanted: makeBlockPool(testBcR, 10, []BpPeer{{ID: "P1", Height: 100}}, map[int64]tPBlocks{}), errWanted: errBadDataFromPeer, }, - {name: "unexpected block 11 from known peer - waiting for 10", + { + name: "unexpected block 11 from known peer - waiting for 10", pool: makeBlockPool(testBcR, 10, []BpPeer{{ID: "P1", Height: 100}}, map[int64]tPBlocks{10: {"P1", false}}), @@ -412,7 +413,8 @@ func TestBlockPoolAddBlock(t *testing.T) { map[int64]tPBlocks{10: {"P1", false}}), errWanted: errMissingBlock, }, - {name: "unexpected block 10 from known peer - already have 10", + { + name: "unexpected block 10 from known peer - already have 10", pool: makeBlockPool(testBcR, 10, []BpPeer{{ID: "P1", Height: 100}}, map[int64]tPBlocks{10: {"P1", true}, 11: {"P1", false}}), @@ -426,7 +428,8 @@ func TestBlockPoolAddBlock(t *testing.T) { map[int64]tPBlocks{10: {"P1", true}, 11: {"P1", false}}), errWanted: errDuplicateBlock, }, - {name: "unexpected block 10 from known peer P2 - expected 10 to come from P1", + { + name: "unexpected block 10 from known peer P2 - expected 10 to come from P1", pool: makeBlockPool(testBcR, 10, []BpPeer{{ID: "P1", Height: 100}, {ID: "P2", Height: 100}}, map[int64]tPBlocks{10: {"P1", false}}), @@ -440,7 +443,8 @@ func TestBlockPoolAddBlock(t *testing.T) { map[int64]tPBlocks{10: {"P1", false}}), errWanted: errBadDataFromPeer, }, - {name: "expected block from known peer", + { + name: "expected block from known peer", pool: makeBlockPool(testBcR, 10, []BpPeer{{ID: "P1", Height: 100}}, map[int64]tPBlocks{10: {"P1", false}}), @@ -612,13 +616,15 @@ func TestProcessedCurrentHeightBlock(t *testing.T) { map[int64]tPBlocks{ 100: {"P1", true}, 104: {"P1", true}, 105: {"P1", false}, 101: {"P2", true}, 103: {"P2", false}, - 102: {"P3", true}, 106: {"P3", true}}), + 102: {"P3", true}, 106: {"P3", true}, + }), poolWanted: makeBlockPool(testBcR, 101, []BpPeer{{ID: "P1", Height: 120}, {ID: "P2", Height: 120}, {ID: "P3", Height: 130}}, map[int64]tPBlocks{ 104: {"P1", true}, 105: {"P1", false}, 101: {"P2", true}, 103: {"P2", false}, - 102: {"P3", true}, 106: {"P3", true}}), + 102: {"P3", true}, 106: {"P3", true}, + }), }, } @@ -658,12 +664,14 @@ func TestRemovePeerAtCurrentHeight(t *testing.T) { map[int64]tPBlocks{ 100: {"P1", false}, 104: {"P1", true}, 105: {"P1", false}, 101: {"P2", true}, 103: {"P2", false}, - 102: {"P3", true}, 106: {"P3", true}}), + 102: {"P3", true}, 106: {"P3", true}, + }), poolWanted: makeBlockPool(testBcR, 100, []BpPeer{{ID: "P2", Height: 120}, {ID: "P3", Height: 130}}, map[int64]tPBlocks{ 101: {"P2", true}, 103: {"P2", false}, - 102: {"P3", true}, 106: {"P3", true}}), + 102: {"P3", true}, 106: {"P3", true}, + }), }, { name: "multiple peers, remove peer for block at H+1", @@ -672,12 +680,14 @@ func TestRemovePeerAtCurrentHeight(t *testing.T) { map[int64]tPBlocks{ 100: {"P1", true}, 104: {"P1", true}, 105: {"P1", false}, 101: {"P2", false}, 103: {"P2", false}, - 102: {"P3", true}, 106: {"P3", true}}), + 102: {"P3", true}, 106: {"P3", true}, + }), poolWanted: makeBlockPool(testBcR, 100, []BpPeer{{ID: "P1", Height: 120}, {ID: "P3", Height: 130}}, map[int64]tPBlocks{ 100: {"P1", true}, 104: {"P1", true}, 105: {"P1", false}, - 102: {"P3", true}, 106: {"P3", true}}), + 102: {"P3", true}, 106: {"P3", true}, + }), }, } diff --git a/blockchain/v1/reactor.go b/blockchain/v1/reactor.go index 6edb9157c..21ba82cdb 100644 --- a/blockchain/v1/reactor.go +++ b/blockchain/v1/reactor.go @@ -71,8 +71,8 @@ type BlockchainReactor struct { // NewBlockchainReactor returns new reactor instance. func NewBlockchainReactor(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore, - fastSync bool) *BlockchainReactor { - + fastSync bool, +) *BlockchainReactor { if state.LastBlockHeight != store.Height() { panic(fmt.Sprintf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())) @@ -197,8 +197,8 @@ func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) { // If the block doesn't exist a bcNoBlockResponseMessage is sent. // If all nodes are honest, no node should be requesting for a block that doesn't exist. func (bcR *BlockchainReactor) sendBlockToPeer(msg *bcproto.BlockRequest, - src p2p.Peer) (queued bool) { - + src p2p.Peer, +) (queued bool) { block := bcR.store.LoadBlock(msg.Height) if block != nil { pbbi, err := block.ToProto() @@ -327,7 +327,6 @@ func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) // processBlocksRoutine processes blocks until signlaed to stop over the stopProcessing channel func (bcR *BlockchainReactor) processBlocksRoutine(stopProcessing chan struct{}) { - processReceivedBlockTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond) doProcessBlockCh := make(chan struct{}, 1) @@ -379,7 +378,6 @@ ForLoop: // poolRoutine receives and handles messages from the Receive() routine and from the FSM. func (bcR *BlockchainReactor) poolRoutine() { - bcR.fsm.Start() sendBlockRequestTicker := time.NewTicker(trySendIntervalMS * time.Millisecond) @@ -399,7 +397,9 @@ ForLoop: _ = bcR.fsm.Handle(&bcReactorMessage{ event: makeRequestsEv, data: bReactorEventData{ - maxNumRequests: maxNumRequests}}) + maxNumRequests: maxNumRequests, + }, + }) case <-statusUpdateTicker.C: // Ask for status updates. @@ -456,7 +456,6 @@ func (bcR *BlockchainReactor) reportPeerErrorToSwitch(err error, peerID p2p.ID) } func (bcR *BlockchainReactor) processBlock() error { - first, second, err := bcR.fsm.FirstTwoBlocks() if err != nil { // We need both to sync the first block. diff --git a/blockchain/v1/reactor_fsm.go b/blockchain/v1/reactor_fsm.go index 59b4c0f12..bf73afefb 100644 --- a/blockchain/v1/reactor_fsm.go +++ b/blockchain/v1/reactor_fsm.go @@ -138,7 +138,6 @@ func (ev bReactorEvent) String() string { default: return "event unknown" } - } // states diff --git a/blockchain/v1/reactor_fsm_test.go b/blockchain/v1/reactor_fsm_test.go index 32d174f87..a453d7f0d 100644 --- a/blockchain/v1/reactor_fsm_test.go +++ b/blockchain/v1/reactor_fsm_test.go @@ -5,13 +5,12 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/libs/log" tmmath "github.com/consideritdone/landslidecore/libs/math" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/p2p" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" ) type lastBlockRequestT struct { @@ -59,7 +58,8 @@ func sStopFSMEv(current, expected string) fsmStepTestValues { currentState: current, event: stopFSMEv, wantState: expected, - wantErr: errNoErrorFinished} + wantErr: errNoErrorFinished, + } } func sUnknownFSMEv(current string) fsmStepTestValues { @@ -67,7 +67,8 @@ func sUnknownFSMEv(current string) fsmStepTestValues { currentState: current, event: 1234, wantState: current, - wantErr: errInvalidEvent} + wantErr: errInvalidEvent, + } } func sStartFSMEv() fsmStepTestValues { @@ -75,10 +76,11 @@ func sStartFSMEv() fsmStepTestValues { currentState: "unknown", event: startFSMEv, wantState: "waitForPeer", - wantStatusReqSent: true} + wantStatusReqSent: true, + } } -func sStateTimeoutEv(current, expected string, timedoutState string, wantErr error) fsmStepTestValues { +func sStateTimeoutEv(current, expected, timedoutState string, wantErr error) fsmStepTestValues { return fsmStepTestValues{ currentState: current, event: stateTimeoutEv, @@ -108,7 +110,8 @@ func sStatusEv(current, expected string, peerID p2p.ID, height int64, err error) event: statusResponseEv, data: bReactorEventData{peerID: peerID, height: height}, wantState: expected, - wantErr: err} + wantErr: err, + } } func sMakeRequestsEv(current, expected string, maxPendingRequests int) fsmStepTestValues { @@ -122,7 +125,8 @@ func sMakeRequestsEv(current, expected string, maxPendingRequests int) fsmStepTe } func sMakeRequestsEvErrored(current, expected string, - maxPendingRequests int, err error, peersRemoved []p2p.ID) fsmStepTestValues { + maxPendingRequests int, err error, peersRemoved []p2p.ID, +) fsmStepTestValues { return fsmStepTestValues{ currentState: current, event: makeRequestsEv, @@ -143,14 +147,16 @@ func sBlockRespEv(current, expected string, peerID p2p.ID, height int64, prevBlo peerID: peerID, height: height, block: types.MakeBlock(height, txs, nil, nil), - length: 100}, + length: 100, + }, wantState: expected, wantNewBlocks: append(prevBlocks, height), } } func sBlockRespEvErrored(current, expected string, - peerID p2p.ID, height int64, prevBlocks []int64, wantErr error, peersRemoved []p2p.ID) fsmStepTestValues { + peerID p2p.ID, height int64, prevBlocks []int64, wantErr error, peersRemoved []p2p.ID, +) fsmStepTestValues { txs := []types.Tx{types.Tx("foo"), types.Tx("bar")} return fsmStepTestValues{ @@ -160,7 +166,8 @@ func sBlockRespEvErrored(current, expected string, peerID: peerID, height: height, block: types.MakeBlock(height, txs, nil, nil), - length: 100}, + length: 100, + }, wantState: expected, wantErr: wantErr, wantRemovedPeers: peersRemoved, @@ -726,9 +733,9 @@ func TestFSMPeerStateTimeoutEvent(t *testing.T) { executeFSMTests(t, tests, false) } -func makeCorrectTransitionSequence(startingHeight int64, numBlocks int64, numPeers int, randomPeerHeights bool, - maxRequestsPerPeer int, maxPendingRequests int) testFields { - +func makeCorrectTransitionSequence(startingHeight, numBlocks int64, numPeers int, randomPeerHeights bool, + maxRequestsPerPeer, maxPendingRequests int, +) testFields { // Generate numPeers peers with random or numBlocks heights according to the randomPeerHeights flag. peerHeights := make([]int64, numPeers) for i := 0; i < numPeers; i++ { @@ -859,7 +866,6 @@ func shouldApplyProcessedBlockEvStep(step *fsmStepTestValues, testBcR *testReact } func TestFSMCorrectTransitionSequences(t *testing.T) { - tests := []testFields{ makeCorrectTransitionSequence(1, 100, 10, true, 10, 40), makeCorrectTransitionSequenceWithRandomParameters(), @@ -899,7 +905,6 @@ func TestFSMCorrectTransitionSequences(t *testing.T) { assert.True(t, testBcR.fsm.isCaughtUp()) } } - }) } } diff --git a/blockchain/v1/reactor_test.go b/blockchain/v1/reactor_test.go index ccba8f003..65d4c1a48 100644 --- a/blockchain/v1/reactor_test.go +++ b/blockchain/v1/reactor_test.go @@ -8,11 +8,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/log" @@ -24,6 +19,9 @@ import ( "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) var config *cfg.Config @@ -53,8 +51,8 @@ func makeVote( header *types.Header, blockID types.BlockID, valset *types.ValidatorSet, - privVal types.PrivValidator) *types.Vote { - + privVal types.PrivValidator, +) *types.Vote { pubKey, err := privVal.GetPubKey() require.NoError(t, err) @@ -87,7 +85,8 @@ func newBlockchainReactor( logger log.Logger, genDoc *types.GenesisDoc, privVals []types.PrivValidator, - maxBlockHeight int64) *BlockchainReactor { + maxBlockHeight int64, +) *BlockchainReactor { if len(privVals) != 1 { panic("only support one validator") } @@ -157,14 +156,15 @@ func newBlockchainReactorPair( logger log.Logger, genDoc *types.GenesisDoc, privVals []types.PrivValidator, - maxBlockHeight int64) BlockchainReactorPair { - + maxBlockHeight int64, +) BlockchainReactorPair { consensusReactor := &consensusReactorTest{} consensusReactor.BaseReactor = *p2p.NewBaseReactor("Consensus reactor", consensusReactor) return BlockchainReactorPair{ newBlockchainReactor(t, logger, genDoc, privVals, maxBlockHeight), - consensusReactor} + consensusReactor, + } } type consensusReactorTest struct { @@ -180,7 +180,6 @@ func (conR *consensusReactorTest) SwitchToConsensus(state sm.State, blocksSynced } func TestFastSyncNoBlockResponse(t *testing.T) { - config = cfg.ResetTestRoot("blockchain_new_reactor_test") defer os.RemoveAll(config.RootDir) genDoc, privVals := randGenesisDoc(1, false, 30) @@ -200,7 +199,6 @@ func TestFastSyncNoBlockResponse(t *testing.T) { reactorPairs[i].bcR.SetLogger(logger.With("module", moduleName)) return s - }, p2p.Connect2Switches) defer func() { @@ -281,7 +279,6 @@ func TestFastSyncBadBlockStopsPeer(t *testing.T) { reactorPairs[i].bcR.SetLogger(logger[i].With("module", moduleName)) reactorPairs[i].conR.mtx.Unlock() return s - }, p2p.Connect2Switches) defer func() { @@ -321,7 +318,6 @@ outerFor: moduleName := fmt.Sprintf("blockchain-%v", len(reactorPairs)-1) reactorPairs[len(reactorPairs)-1].bcR.SetLogger(lastLogger.With("module", moduleName)) return s - }, p2p.Connect2Switches)...) for i := 0; i < len(reactorPairs)-1; i++ { diff --git a/blockchain/v2/io.go b/blockchain/v2/io.go index c83b424a7..c8bf06679 100644 --- a/blockchain/v2/io.go +++ b/blockchain/v2/io.go @@ -59,7 +59,7 @@ func (sio *switchIO) sendBlockRequest(peerID p2p.ID, height int64) error { return nil } -func (sio *switchIO) sendStatusResponse(base int64, height int64, peerID p2p.ID) error { +func (sio *switchIO) sendStatusResponse(base, height int64, peerID p2p.ID) error { peer := sio.sw.Peers().Get(peerID) if peer == nil { return fmt.Errorf("peer not found") diff --git a/blockchain/v2/processor.go b/blockchain/v2/processor.go index fcf7bcd23..71838a76d 100644 --- a/blockchain/v2/processor.go +++ b/blockchain/v2/processor.go @@ -172,7 +172,8 @@ func (state *pcState) handle(event Event) (Event, error) { state.purgePeer(secondItem.peerID) } return pcBlockVerificationFailure{ - height: first.Height, firstPeerID: firstItem.peerID, secondPeerID: secondItem.peerID}, + height: first.Height, firstPeerID: firstItem.peerID, secondPeerID: secondItem.peerID, + }, nil } diff --git a/blockchain/v2/processor_context.go b/blockchain/v2/processor_context.go index 26c666c01..24fe0b0bd 100644 --- a/blockchain/v2/processor_context.go +++ b/blockchain/v2/processor_context.go @@ -60,7 +60,8 @@ type mockPContext struct { func newMockProcessorContext( state state.State, verificationBlackList []int64, - applicationBlackList []int64) *mockPContext { + applicationBlackList []int64, +) *mockPContext { return &mockPContext{ applicationBL: applicationBlackList, verificationBL: verificationBlackList, @@ -88,7 +89,6 @@ func (mpc *mockPContext) verifyCommit(chainID string, blockID types.BlockID, hei } func (mpc *mockPContext) saveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) { - } func (mpc *mockPContext) setState(state state.State) { diff --git a/blockchain/v2/processor_test.go b/blockchain/v2/processor_test.go index ac4607bfe..dab2ff316 100644 --- a/blockchain/v2/processor_test.go +++ b/blockchain/v2/processor_test.go @@ -3,11 +3,10 @@ package v2 import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/p2p" tmState "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" ) // pcBlock is a test helper structure with simple types. Its purpose is to help with test readability. @@ -242,8 +241,10 @@ func TestRProcessBlockFailures(t *testing.T) { name: "blocks H+1 and H+2 present from same peers - H+1 verification fails ", steps: []pcFsmMakeStateValues{ { - currentState: ¶ms{height: 0, items: []pcBlock{{"P1", 1}, {"P1", 2}, {"P2", 3}}, - verBL: []int64{1}}, event: rProcessBlock{}, + currentState: ¶ms{ + height: 0, items: []pcBlock{{"P1", 1}, {"P1", 2}, {"P2", 3}}, + verBL: []int64{1}, + }, event: rProcessBlock{}, wantState: ¶ms{height: 0, items: []pcBlock{{"P2", 3}}, verBL: []int64{1}}, wantNextEvent: pcBlockVerificationFailure{height: 1, firstPeerID: "P1", secondPeerID: "P1"}, }, @@ -281,7 +282,8 @@ func TestScFinishedEv(t *testing.T) { steps: []pcFsmMakeStateValues{ { currentState: ¶ms{height: 100, items: []pcBlock{ - {"P1", 101}}, blocksSynced: 100}, event: scFinishedEv{}, + {"P1", 101}, + }, blocksSynced: 100}, event: scFinishedEv{}, wantState: ¶ms{height: 100, items: []pcBlock{{"P1", 101}}, blocksSynced: 100}, wantNextEvent: pcFinished{tmState: tmState.State{LastBlockHeight: 100}, blocksSynced: 100}, }, @@ -292,9 +294,11 @@ func TestScFinishedEv(t *testing.T) { steps: []pcFsmMakeStateValues{ { currentState: ¶ms{height: 100, items: []pcBlock{ - {"P1", 101}, {"P1", 102}}, blocksSynced: 100}, event: scFinishedEv{}, + {"P1", 101}, {"P1", 102}, + }, blocksSynced: 100}, event: scFinishedEv{}, wantState: ¶ms{height: 100, items: []pcBlock{ - {"P1", 101}, {"P1", 102}}, blocksSynced: 100, draining: true}, + {"P1", 101}, {"P1", 102}, + }, blocksSynced: 100, draining: true}, wantNextEvent: noOp, wantErr: nil, }, diff --git a/blockchain/v2/reactor.go b/blockchain/v2/reactor.go index 08c45a44c..a1ca3f2dc 100644 --- a/blockchain/v2/reactor.go +++ b/blockchain/v2/reactor.go @@ -58,7 +58,8 @@ type blockApplier interface { // XXX: unify naming in this package around tmState func newReactor(state state.State, store blockStore, reporter behaviour.Reporter, - blockApplier blockApplier, fastSync bool) *BlockchainReactor { + blockApplier blockApplier, fastSync bool, +) *BlockchainReactor { initHeight := state.LastBlockHeight + 1 if initHeight == 1 { initHeight = state.InitialHeight @@ -84,7 +85,8 @@ func NewBlockchainReactor( state state.State, blockApplier blockApplier, store blockStore, - fastSync bool) *BlockchainReactor { + fastSync bool, +) *BlockchainReactor { reporter := behaviour.NewMockReporter() return newReactor(state, store, reporter, blockApplier, fastSync) } @@ -284,8 +286,8 @@ func (e bcResetState) String() string { // Takes the channel as a parameter to avoid race conditions on r.events. func (r *BlockchainReactor) demux(events <-chan Event) { - var lastRate = 0.0 - var lastHundred = time.Now() + lastRate := 0.0 + lastHundred := time.Now() var ( processBlockFreq = 20 * time.Millisecond diff --git a/blockchain/v2/reactor_test.go b/blockchain/v2/reactor_test.go index 5218e71e5..9746453c4 100644 --- a/blockchain/v2/reactor_test.go +++ b/blockchain/v2/reactor_test.go @@ -9,10 +9,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/behaviour" bc "github.com/consideritdone/landslidecore/blockchain" @@ -28,6 +24,9 @@ import ( "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) type mockPeer struct { @@ -79,8 +78,7 @@ func (ml *mockBlockStore) SaveBlock(block *types.Block, part *types.PartSet, com ml.blocks[block.Height] = block } -type mockBlockApplier struct { -} +type mockBlockApplier struct{} // XXX: Add whitelist/blacklist? func (mba *mockBlockApplier) ApplyBlock( @@ -350,9 +348,7 @@ func newTestReactor(p testReactorParams) *BlockchainReactor { // } func TestReactorHelperMode(t *testing.T) { - var ( - channelID = byte(0x40) - ) + channelID := byte(0x40) config := cfg.ResetTestRoot("blockchain_reactor_v2_test") defer os.RemoveAll(config.RootDir) @@ -465,7 +461,8 @@ type testApp struct { } func randGenesisDoc(chainID string, numValidators int, randPower bool, minPower int64) ( - *types.GenesisDoc, []types.PrivValidator) { + *types.GenesisDoc, []types.PrivValidator, +) { validators := make([]types.GenesisValidator, numValidators) privValidators := make([]types.PrivValidator, numValidators) for i := 0; i < numValidators; i++ { @@ -490,7 +487,8 @@ func randGenesisDoc(chainID string, numValidators int, randPower bool, minPower func newReactorStore( genDoc *types.GenesisDoc, privVals []types.PrivValidator, - maxBlockHeight int64) (*store.BlockStore, sm.State, *sm.BlockExecutor) { + maxBlockHeight int64, +) (*store.BlockStore, sm.State, *sm.BlockExecutor) { if len(privVals) != 1 { panic("only support one validator") } diff --git a/blockchain/v2/routine.go b/blockchain/v2/routine.go index a3b6023fc..b25519a61 100644 --- a/blockchain/v2/routine.go +++ b/blockchain/v2/routine.go @@ -6,7 +6,6 @@ import ( "sync/atomic" "github.com/Workiva/go-datastructures/queue" - "github.com/consideritdone/landslidecore/libs/log" ) diff --git a/blockchain/v2/scheduler.go b/blockchain/v2/scheduler.go index d7bac770f..272449799 100644 --- a/blockchain/v2/scheduler.go +++ b/blockchain/v2/scheduler.go @@ -298,7 +298,7 @@ func (sc *scheduler) addNewBlocks() { } } -func (sc *scheduler) setPeerRange(peerID p2p.ID, base int64, height int64) error { +func (sc *scheduler) setPeerRange(peerID p2p.ID, base, height int64) error { peer := sc.ensurePeer(peerID) if peer.state == peerStateRemoved { @@ -366,7 +366,7 @@ func (sc *scheduler) setStateAtHeight(height int64, state blockState) { } // CONTRACT: peer exists and in Ready state. -func (sc *scheduler) markReceived(peerID p2p.ID, height int64, size int64, now time.Time) error { +func (sc *scheduler) markReceived(peerID p2p.ID, height, size int64, now time.Time) error { peer := sc.peers[peerID] if state := sc.getStateAtHeight(height); state != blockStatePending || sc.pendingBlocks[height] != peerID { @@ -514,6 +514,7 @@ type PeerByID []p2p.ID func (peers PeerByID) Len() int { return len(peers) } + func (peers PeerByID) Less(i, j int) bool { return bytes.Compare([]byte(peers[i]), []byte(peers[j])) == -1 } @@ -551,9 +552,11 @@ func (sc *scheduler) handleNoBlockResponse(event bcNoBlockResponse) (Event, erro // The peer may have been just removed due to errors, low speed or timeouts. sc.removePeer(event.peerID) - return scPeerError{peerID: event.peerID, + return scPeerError{ + peerID: event.peerID, reason: fmt.Errorf("peer %v with base %d height %d claims no block for %d", - event.peerID, peer.base, peer.height, event.height)}, nil + event.peerID, peer.base, peer.height, event.height), + }, nil } func (sc *scheduler) handleBlockProcessed(event pcBlockProcessed) (Event, error) { @@ -663,7 +666,6 @@ func (sc *scheduler) handleTrySchedule(event rTrySchedule) (Event, error) { return scSchedulerFail{reason: err}, nil // XXX: peerError might be more appropriate } return scBlockRequest{peerID: bestPeerID, height: nextHeight}, nil - } func (sc *scheduler) handleStatusResponse(event bcStatusResponse) (Event, error) { diff --git a/blockchain/v2/scheduler_test.go b/blockchain/v2/scheduler_test.go index 0e8f8313f..937c48266 100644 --- a/blockchain/v2/scheduler_test.go +++ b/blockchain/v2/scheduler_test.go @@ -7,12 +7,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/p2p" "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type scTestParams struct { @@ -107,7 +106,6 @@ func TestScInit(t *testing.T) { } func TestScMaxHeights(t *testing.T) { - tests := []struct { name string sc scheduler @@ -132,7 +130,8 @@ func TestScMaxHeights(t *testing.T) { height: 1, peers: map[p2p.ID]*scPeer{ "P1": {height: 4, state: peerStateReady}, - "P2": {height: 10, state: peerStateRemoved}}, + "P2": {height: 10, state: peerStateRemoved}, + }, }, wantMax: 4, }, @@ -142,7 +141,8 @@ func TestScMaxHeights(t *testing.T) { height: 1, peers: map[p2p.ID]*scPeer{ "P1": {height: 4, state: peerStateRemoved}, - "P2": {height: 10, state: peerStateRemoved}}, + "P2": {height: 10, state: peerStateRemoved}, + }, }, wantMax: 0, }, @@ -152,7 +152,8 @@ func TestScMaxHeights(t *testing.T) { height: 1, peers: map[p2p.ID]*scPeer{ "P1": {base: -1, height: -1, state: peerStateNew}, - "P2": {base: -1, height: -1, state: peerStateNew}}, + "P2": {base: -1, height: -1, state: peerStateNew}, + }, }, wantMax: 0, }, @@ -185,7 +186,6 @@ func TestScMaxHeights(t *testing.T) { } func TestScEnsurePeer(t *testing.T) { - type args struct { peerID p2p.ID } @@ -207,7 +207,8 @@ func TestScEnsurePeer(t *testing.T) { args: args{peerID: "P2"}, wantFields: scTestParams{peers: map[string]*scPeer{ "P1": {base: -1, height: -1, state: peerStateNew}, - "P2": {base: -1, height: -1, state: peerStateNew}}}, + "P2": {base: -1, height: -1, state: peerStateNew}, + }}, }, { name: "add duplicate peer is fine", @@ -262,8 +263,9 @@ func TestScTouchPeer(t *testing.T) { allB: []int64{1, 2, 3, 4, 5}, }, args: args{peerID: "P2", time: now}, - wantFields: scTestParams{peers: map[string]*scPeer{"P1": {state: peerStateReady, height: 5}}, - allB: []int64{1, 2, 3, 4, 5}, + wantFields: scTestParams{ + peers: map[string]*scPeer{"P1": {state: peerStateReady, height: 5}}, + allB: []int64{1, 2, 3, 4, 5}, }, wantErr: true, }, @@ -286,7 +288,8 @@ func TestScTouchPeer(t *testing.T) { fields: scTestParams{peers: map[string]*scPeer{"P1": {state: peerStateReady, lastTouched: now}}}, args: args{peerID: "P1", time: now.Add(3 * time.Second)}, wantFields: scTestParams{peers: map[string]*scPeer{ - "P1": {state: peerStateReady, lastTouched: now.Add(3 * time.Second)}}}, + "P1": {state: peerStateReady, lastTouched: now.Add(3 * time.Second)}, + }}, }, } @@ -359,7 +362,6 @@ func TestScPrunablePeers(t *testing.T) { } func TestScRemovePeer(t *testing.T) { - type args struct { peerID p2p.ID } @@ -393,13 +395,16 @@ func TestScRemovePeer(t *testing.T) { fields: scTestParams{ peers: map[string]*scPeer{ "P1": {height: 10, state: peerStateRemoved}, - "P2": {height: 5, state: peerStateReady}}, + "P2": {height: 5, state: peerStateReady}, + }, allB: []int64{1, 2, 3, 4, 5}, }, args: args{peerID: "P2"}, - wantFields: scTestParams{peers: map[string]*scPeer{ - "P1": {height: 10, state: peerStateRemoved}, - "P2": {height: 5, state: peerStateRemoved}}, + wantFields: scTestParams{ + peers: map[string]*scPeer{ + "P1": {height: 10, state: peerStateRemoved}, + "P2": {height: 5, state: peerStateRemoved}, + }, }, }, { @@ -408,7 +413,8 @@ func TestScRemovePeer(t *testing.T) { height: 8, peers: map[string]*scPeer{ "P1": {height: 10, state: peerStateRemoved}, - "P2": {height: 11, state: peerStateReady}}, + "P2": {height: 11, state: peerStateReady}, + }, allB: []int64{8, 9, 10, 11}, }, args: args{peerID: "P1"}, @@ -416,8 +422,10 @@ func TestScRemovePeer(t *testing.T) { height: 8, peers: map[string]*scPeer{ "P1": {height: 10, state: peerStateRemoved}, - "P2": {height: 11, state: peerStateReady}}, - allB: []int64{8, 9, 10, 11}}, + "P2": {height: 11, state: peerStateReady}, + }, + allB: []int64{8, 9, 10, 11}, + }, }, { name: "remove Ready peer with blocks requested", @@ -499,7 +507,6 @@ func TestScRemovePeer(t *testing.T) { } func TestScSetPeerRange(t *testing.T) { - type args struct { peerID p2p.ID base int64 @@ -516,19 +523,22 @@ func TestScSetPeerRange(t *testing.T) { name: "change height of non existing peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, args: args{peerID: "P2", height: 4}, wantFields: scTestParams{ peers: map[string]*scPeer{ "P1": {height: 2, state: peerStateReady}, "P2": {height: 4, state: peerStateReady}, }, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, }, { name: "increase height of removed peer", fields: scTestParams{ - peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}}, + peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}, + }, args: args{peerID: "P1", height: 4}, wantFields: scTestParams{peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}}, }, @@ -536,32 +546,38 @@ func TestScSetPeerRange(t *testing.T) { name: "decrease height of single peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, args: args{peerID: "P1", height: 2}, wantFields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 4, state: peerStateRemoved}}, - allB: []int64{}}, + allB: []int64{}, + }, wantErr: true, }, { name: "increase height of single peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, args: args{peerID: "P1", height: 4}, wantFields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, }, { name: "noop height change of single peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, args: args{peerID: "P1", height: 4}, wantFields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, }, { name: "add peer with huge height 10**10 ", @@ -573,16 +589,19 @@ func TestScSetPeerRange(t *testing.T) { wantFields: scTestParams{ targetPending: 4, peers: map[string]*scPeer{"P2": {height: 10000000000, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, }, { name: "add peer with base > height should error", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, args: args{peerID: "P1", base: 6, height: 5}, wantFields: scTestParams{ - peers: map[string]*scPeer{"P1": {height: 4, state: peerStateRemoved}}}, + peers: map[string]*scPeer{"P1": {height: 4, state: peerStateRemoved}}, + }, wantErr: true, }, { @@ -595,7 +614,8 @@ func TestScSetPeerRange(t *testing.T) { wantFields: scTestParams{ targetPending: 4, peers: map[string]*scPeer{"P1": {base: 6, height: 6, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, }, } @@ -614,7 +634,6 @@ func TestScSetPeerRange(t *testing.T) { } func TestScGetPeersWithHeight(t *testing.T) { - type args struct { height int64 } @@ -699,7 +718,8 @@ func TestScGetPeersWithHeight(t *testing.T) { "P2": {height: 10, state: peerStateReady}, "P3": {height: 5, state: peerStateReady}, "P4": {height: 20, state: peerStateRemoved}, - "P5": {height: 11, state: peerStateReady}}, + "P5": {height: 11, state: peerStateReady}, + }, allB: []int64{8, 9, 10, 11}, }, args: args{height: 8}, @@ -740,42 +760,50 @@ func TestScMarkPending(t *testing.T) { name: "attempt mark pending an unknown block above height", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, args: args{peerID: "P1", height: 3, tm: now}, wantFields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, wantErr: true, }, { name: "attempt mark pending an unknown block below base", fields: scTestParams{ peers: map[string]*scPeer{"P1": {base: 4, height: 6, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4, 5, 6}}, + allB: []int64{1, 2, 3, 4, 5, 6}, + }, args: args{peerID: "P1", height: 3, tm: now}, wantFields: scTestParams{ peers: map[string]*scPeer{"P1": {base: 4, height: 6, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4, 5, 6}}, + allB: []int64{1, 2, 3, 4, 5, 6}, + }, wantErr: true, }, { name: "attempt mark pending from non existing peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, args: args{peerID: "P2", height: 1, tm: now}, wantFields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, wantErr: true, }, { name: "mark pending from Removed peer", fields: scTestParams{ - peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}}, + peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}, + }, args: args{peerID: "P1", height: 1, tm: now}, wantFields: scTestParams{ - peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}}, + peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}, + }, wantErr: true, }, { @@ -867,20 +895,24 @@ func TestScMarkReceived(t *testing.T) { name: "received from non existing peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, args: args{peerID: "P2", height: 1, size: 1000, tm: now}, wantFields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, wantErr: true, }, { name: "received from removed peer", fields: scTestParams{ - peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}}, + peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}, + }, args: args{peerID: "P1", height: 1, size: 1000, tm: now}, wantFields: scTestParams{ - peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}}, + peers: map[string]*scPeer{"P1": {height: 2, state: peerStateRemoved}}, + }, wantErr: true, }, { @@ -1011,14 +1043,16 @@ func TestScMarkProcessed(t *testing.T) { allB: []int64{1, 2}, pending: map[int64]p2p.ID{2: "P1"}, pendingTime: map[int64]time.Time{2: now}, - received: map[int64]p2p.ID{1: "P1"}}, + received: map[int64]p2p.ID{1: "P1"}, + }, args: args{height: 1}, wantFields: scTestParams{ height: 2, peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, allB: []int64{2}, pending: map[int64]p2p.ID{2: "P1"}, - pendingTime: map[int64]time.Time{2: now}}, + pendingTime: map[int64]time.Time{2: now}, + }, }, } @@ -1120,7 +1154,8 @@ func TestScAllBlocksProcessed(t *testing.T) { fields: scTestParams{ height: 4, peers: map[string]*scPeer{ - "P1": {height: 4, state: peerStateReady}}, + "P1": {height: 4, state: peerStateReady}, + }, allB: []int64{4}, received: map[int64]p2p.ID{4: "P1"}, }, @@ -1231,7 +1266,6 @@ func TestScNextHeightToSchedule(t *testing.T) { } func TestScSelectPeer(t *testing.T) { - type args struct { height int64 } @@ -1275,16 +1309,18 @@ func TestScSelectPeer(t *testing.T) { }, { name: "one Ready equal peer", - fields: scTestParams{peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}, + fields: scTestParams{ + peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, + allB: []int64{1, 2, 3, 4}, }, args: args{height: 4}, wantResult: "P1", }, { name: "one Ready higher peer", - fields: scTestParams{peers: map[string]*scPeer{"P1": {height: 6, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4, 5, 6}, + fields: scTestParams{ + peers: map[string]*scPeer{"P1": {height: 6, state: peerStateReady}}, + allB: []int64{1, 2, 3, 4, 5, 6}, }, args: args{height: 4}, wantResult: "P1", @@ -1305,7 +1341,8 @@ func TestScSelectPeer(t *testing.T) { height: 4, peers: map[string]*scPeer{ "P1": {height: 8, state: peerStateReady}, - "P2": {height: 9, state: peerStateReady}}, + "P2": {height: 9, state: peerStateReady}, + }, allB: []int64{4, 5, 6, 7, 8, 9}, pending: map[int64]p2p.ID{ 4: "P1", 6: "P1", @@ -1321,7 +1358,8 @@ func TestScSelectPeer(t *testing.T) { peers: map[string]*scPeer{ "P2": {height: 20, state: peerStateReady}, "P1": {height: 15, state: peerStateReady}, - "P3": {height: 15, state: peerStateReady}}, + "P3": {height: 15, state: peerStateReady}, + }, allB: []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, pending: map[int64]p2p.ID{ 1: "P1", 2: "P1", @@ -1355,7 +1393,7 @@ func makeScBlock(height int64) *types.Block { // used in place of assert.Equal(t, want, actual) to avoid failures due to // scheduler.lastAdvanced timestamp inequalities. -func checkSameScheduler(t *testing.T, want *scheduler, actual *scheduler) { +func checkSameScheduler(t *testing.T, want, actual *scheduler) { assert.Equal(t, want.initHeight, actual.initHeight) assert.Equal(t, want.height, actual.height) assert.Equal(t, want.peers, actual.peers) @@ -1368,7 +1406,7 @@ func checkSameScheduler(t *testing.T, want *scheduler, actual *scheduler) { } // checkScResults checks scheduler handler test results -func checkScResults(t *testing.T, wantErr bool, err error, wantEvent Event, event Event) { +func checkScResults(t *testing.T, wantErr bool, err error, wantEvent, event Event) { if (err != nil) != wantErr { t.Errorf("error = %v, wantErr %v", err, wantErr) return @@ -1421,7 +1459,8 @@ func TestScHandleBlockResponse(t *testing.T) { name: "block we haven't asked for", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 8, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4, 5, 6, 7, 8}}, + allB: []int64{1, 2, 3, 4, 5, 6, 7, 8}, + }, args: args{event: block6FromP1}, wantEvent: scPeerError{peerID: "P1", reason: fmt.Errorf("some error")}, }, @@ -1501,7 +1540,8 @@ func TestScHandleNoBlockResponse(t *testing.T) { name: "for block we haven't asked for", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 8, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4, 5, 6, 7, 8}}, + allB: []int64{1, 2, 3, 4, 5, 6, 7, 8}, + }, wantEvent: scPeerError{peerID: "P1", reason: fmt.Errorf("some error")}, wantFields: scTestParams{peers: map[string]*scPeer{"P1": {height: 8, state: peerStateRemoved}}}, }, @@ -1798,7 +1838,8 @@ func TestScHandleTryPrunePeer(t *testing.T) { // X - ready, active, fast "P2": {state: peerStateReady, lastTouched: now.Add(time.Second), lastRate: 101}, // X - removed, active, equal - "P3": {state: peerStateRemoved, lastTouched: now.Add(time.Second), lastRate: 100}}, + "P3": {state: peerStateRemoved, lastTouched: now.Add(time.Second), lastRate: 100}, + }, peerTimeout: time.Second, }, args: args{event: pruneEv}, @@ -1823,7 +1864,8 @@ func TestScHandleTryPrunePeer(t *testing.T) { "P6": {state: peerStateReady, lastTouched: now.Add(time.Second), lastRate: 90, height: 7}, }, allB: []int64{1, 2, 3, 4, 5, 6, 7}, - peerTimeout: time.Second}, + peerTimeout: time.Second, + }, args: args{event: pruneEv}, wantEvent: scPeersPruned{peers: []p2p.ID{"P4", "P5", "P6"}}, }, @@ -1847,7 +1889,8 @@ func TestScHandleTryPrunePeer(t *testing.T) { "P6": {state: peerStateReady, lastTouched: now.Add(time.Second), lastRate: 90, height: 7}, }, allB: []int64{6, 7}, - peerTimeout: time.Second}, + peerTimeout: time.Second, + }, args: args{event: pruneEv}, wantEvent: scFinishedEv{}, }, @@ -1902,7 +1945,8 @@ func TestScHandleTrySchedule(t *testing.T) { fields: scTestParams{ startTime: now, height: 6, - peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}}, + peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, + }, args: args{event: tryEv}, wantEvent: noOpEvent{}, }, @@ -1911,7 +1955,8 @@ func TestScHandleTrySchedule(t *testing.T) { fields: scTestParams{ startTime: now, peers: map[string]*scPeer{"P1": {height: 4, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4}}, + allB: []int64{1, 2, 3, 4}, + }, args: args{event: tryEv}, wantEvent: scBlockRequest{peerID: "P1", height: 1}, }, @@ -1921,7 +1966,8 @@ func TestScHandleTrySchedule(t *testing.T) { startTime: now, peers: map[string]*scPeer{ "P1": {height: 4, state: peerStateReady}, - "P2": {height: 5, state: peerStateReady}}, + "P2": {height: 5, state: peerStateReady}, + }, allB: []int64{1, 2, 3, 4, 5}, pending: map[int64]p2p.ID{ 1: "P1", 2: "P1", @@ -1939,7 +1985,8 @@ func TestScHandleTrySchedule(t *testing.T) { peers: map[string]*scPeer{ "P2": {height: 8, state: peerStateReady}, "P1": {height: 8, state: peerStateReady}, - "P3": {height: 8, state: peerStateReady}}, + "P3": {height: 8, state: peerStateReady}, + }, allB: []int64{1, 2, 3, 4, 5, 6, 7, 8}, pending: map[int64]p2p.ID{ 1: "P1", 2: "P1", @@ -2012,7 +2059,8 @@ func TestScHandleStatusResponse(t *testing.T) { name: "increase height of single peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 2, state: peerStateReady}}, - allB: []int64{1, 2}}, + allB: []int64{1, 2}, + }, args: args{event: statusRespP1Ev}, wantEvent: noOpEvent{}, }, @@ -2020,7 +2068,8 @@ func TestScHandleStatusResponse(t *testing.T) { name: "noop height change of single peer", fields: scTestParams{ peers: map[string]*scPeer{"P1": {height: 6, state: peerStateReady}}, - allB: []int64{1, 2, 3, 4, 5, 6}}, + allB: []int64{1, 2, 3, 4, 5, 6}, + }, args: args{event: statusRespP1Ev}, wantEvent: noOpEvent{}, }, @@ -2082,7 +2131,8 @@ func TestScHandle(t *testing.T) { args: args{event: bcAddNewPeer{peerID: "P1"}}, wantEvent: noOpEvent{}, wantSc: &scTestParams{startTime: now, peers: map[string]*scPeer{ - "P1": {base: -1, height: -1, state: peerStateNew}}, height: 1}, + "P1": {base: -1, height: -1, state: peerStateNew}, + }, height: 1}, }, { // set height of P1 args: args{event: bcStatusResponse{peerID: "P1", time: tick[0], height: 3}}, @@ -2199,7 +2249,8 @@ func TestScHandle(t *testing.T) { startTime: now, peers: map[string]*scPeer{ "P1": {height: 4, state: peerStateReady, lastTouched: tick[6]}, - "P2": {height: 3, state: peerStateReady, lastTouched: tick[6]}}, + "P2": {height: 3, state: peerStateReady, lastTouched: tick[6]}, + }, allB: []int64{1, 2, 3, 4}, received: map[int64]p2p.ID{1: "P1", 2: "P1", 3: "P1"}, height: 1, @@ -2210,7 +2261,8 @@ func TestScHandle(t *testing.T) { startTime: now, peers: map[string]*scPeer{ "P1": {height: 4, state: peerStateRemoved, lastTouched: tick[6]}, - "P2": {height: 3, state: peerStateReady, lastTouched: tick[6]}}, + "P2": {height: 3, state: peerStateReady, lastTouched: tick[6]}, + }, allB: []int64{1, 2, 3}, received: map[int64]p2p.ID{}, height: 1, diff --git a/blockchain/v2/types.go b/blockchain/v2/types.go index 7a73728e4..02d025826 100644 --- a/blockchain/v2/types.go +++ b/blockchain/v2/types.go @@ -12,9 +12,11 @@ type priority interface { Priority() int } -type priorityLow struct{} -type priorityNormal struct{} -type priorityHigh struct{} +type ( + priorityLow struct{} + priorityNormal struct{} + priorityHigh struct{} +) func (p priorityLow) Priority() int { return 1 diff --git a/cmd/priv_val_server/main.go b/cmd/priv_val_server/main.go index 59476ac2c..198df5787 100644 --- a/cmd/priv_val_server/main.go +++ b/cmd/priv_val_server/main.go @@ -9,7 +9,6 @@ import ( "github.com/consideritdone/landslidecore/libs/log" tmnet "github.com/consideritdone/landslidecore/libs/net" tmos "github.com/consideritdone/landslidecore/libs/os" - "github.com/consideritdone/landslidecore/privval" ) diff --git a/cmd/tendermint/commands/debug/debug.go b/cmd/tendermint/commands/debug/debug.go index bde4520bb..50b080df0 100644 --- a/cmd/tendermint/commands/debug/debug.go +++ b/cmd/tendermint/commands/debug/debug.go @@ -3,9 +3,8 @@ package debug import ( "os" - "github.com/spf13/cobra" - "github.com/consideritdone/landslidecore/libs/log" + "github.com/spf13/cobra" ) var ( diff --git a/cmd/tendermint/commands/debug/dump.go b/cmd/tendermint/commands/debug/dump.go index 0cdef93fe..aaa40b8e1 100644 --- a/cmd/tendermint/commands/debug/dump.go +++ b/cmd/tendermint/commands/debug/dump.go @@ -8,12 +8,11 @@ import ( "path/filepath" "time" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/cli" rpchttp "github.com/consideritdone/landslidecore/rpc/client/http" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var dumpCmd = &cobra.Command{ diff --git a/cmd/tendermint/commands/debug/io.go b/cmd/tendermint/commands/debug/io.go index dcfff50c8..8a3fe2aa7 100644 --- a/cmd/tendermint/commands/debug/io.go +++ b/cmd/tendermint/commands/debug/io.go @@ -68,7 +68,6 @@ func zipDir(src, dest string) error { _, err = io.Copy(headerWriter, file) return err }) - } // copyFile copies a file from src to dest and returns an error upon failure. The diff --git a/cmd/tendermint/commands/debug/kill.go b/cmd/tendermint/commands/debug/kill.go index a7263ff48..f64fa31b8 100644 --- a/cmd/tendermint/commands/debug/kill.go +++ b/cmd/tendermint/commands/debug/kill.go @@ -11,12 +11,11 @@ import ( "syscall" "time" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/cli" rpchttp "github.com/consideritdone/landslidecore/rpc/client/http" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var killCmd = &cobra.Command{ diff --git a/cmd/tendermint/commands/gen_node_key.go b/cmd/tendermint/commands/gen_node_key.go index baf0afb4a..004a578a6 100644 --- a/cmd/tendermint/commands/gen_node_key.go +++ b/cmd/tendermint/commands/gen_node_key.go @@ -3,10 +3,9 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - tmos "github.com/consideritdone/landslidecore/libs/os" "github.com/consideritdone/landslidecore/p2p" + "github.com/spf13/cobra" ) // GenNodeKeyCmd allows the generation of a node key. It prints node's ID to diff --git a/cmd/tendermint/commands/gen_validator.go b/cmd/tendermint/commands/gen_validator.go index 4c2840f46..ebf23f77d 100644 --- a/cmd/tendermint/commands/gen_validator.go +++ b/cmd/tendermint/commands/gen_validator.go @@ -3,10 +3,9 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - tmjson "github.com/consideritdone/landslidecore/libs/json" "github.com/consideritdone/landslidecore/privval" + "github.com/spf13/cobra" ) // GenValidatorCmd allows the generation of a keypair for a diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index c7f3ea512..5f9a62776 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -3,8 +3,6 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - cfg "github.com/consideritdone/landslidecore/config" tmos "github.com/consideritdone/landslidecore/libs/os" tmrand "github.com/consideritdone/landslidecore/libs/rand" @@ -12,6 +10,7 @@ import ( "github.com/consideritdone/landslidecore/privval" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/spf13/cobra" ) // InitFilesCmd initialises a fresh Tendermint Core instance. diff --git a/cmd/tendermint/commands/light.go b/cmd/tendermint/commands/light.go index f3221dbae..fff3540c7 100644 --- a/cmd/tendermint/commands/light.go +++ b/cmd/tendermint/commands/light.go @@ -11,10 +11,6 @@ import ( "strings" "time" - "github.com/spf13/cobra" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/libs/log" tmmath "github.com/consideritdone/landslidecore/libs/math" tmos "github.com/consideritdone/landslidecore/libs/os" @@ -23,6 +19,8 @@ import ( lrpc "github.com/consideritdone/landslidecore/light/rpc" dbs "github.com/consideritdone/landslidecore/light/store/db" rpcserver "github.com/consideritdone/landslidecore/rpc/jsonrpc/server" + "github.com/spf13/cobra" + dbm "github.com/tendermint/tm-db" ) // LightCmd represents the base command when called without any subcommands diff --git a/cmd/tendermint/commands/probe_upnp.go b/cmd/tendermint/commands/probe_upnp.go index 613f1dbff..25873b656 100644 --- a/cmd/tendermint/commands/probe_upnp.go +++ b/cmd/tendermint/commands/probe_upnp.go @@ -3,10 +3,9 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - tmjson "github.com/consideritdone/landslidecore/libs/json" "github.com/consideritdone/landslidecore/p2p/upnp" + "github.com/spf13/cobra" ) // ProbeUpnpCmd adds capabilities to test the UPnP functionality. diff --git a/cmd/tendermint/commands/replay.go b/cmd/tendermint/commands/replay.go index 8dc88a3e4..6e44ed6f3 100644 --- a/cmd/tendermint/commands/replay.go +++ b/cmd/tendermint/commands/replay.go @@ -1,9 +1,8 @@ package commands import ( - "github.com/spf13/cobra" - "github.com/consideritdone/landslidecore/consensus" + "github.com/spf13/cobra" ) // ReplayCmd allows replaying of messages from the WAL. diff --git a/cmd/tendermint/commands/reset.go b/cmd/tendermint/commands/reset.go index 37e869c65..7f7b0ac9d 100644 --- a/cmd/tendermint/commands/reset.go +++ b/cmd/tendermint/commands/reset.go @@ -4,11 +4,10 @@ import ( "os" "path/filepath" - "github.com/spf13/cobra" - "github.com/consideritdone/landslidecore/libs/log" tmos "github.com/consideritdone/landslidecore/libs/os" "github.com/consideritdone/landslidecore/privval" + "github.com/spf13/cobra" ) // ResetAllCmd removes the database of this Tendermint core @@ -94,7 +93,7 @@ func resetAll(dbDir, addrBookFile, privValKeyFile, privValStateFile string, logg logger.Error("Error removing all blockchain history", "dir", dbDir, "err", err) } - if err := tmos.EnsureDir(dbDir, 0700); err != nil { + if err := tmos.EnsureDir(dbDir, 0o700); err != nil { logger.Error("unable to recreate dbDir", "err", err) } @@ -151,7 +150,7 @@ func resetState(dbDir string, logger log.Logger) error { } } - if err := tmos.EnsureDir(dbDir, 0700); err != nil { + if err := tmos.EnsureDir(dbDir, 0o700); err != nil { logger.Error("unable to recreate dbDir", "err", err) } return nil diff --git a/cmd/tendermint/commands/reset_test.go b/cmd/tendermint/commands/reset_test.go index 45b60a05e..268bbde0d 100644 --- a/cmd/tendermint/commands/reset_test.go +++ b/cmd/tendermint/commands/reset_test.go @@ -4,10 +4,9 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/require" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/privval" + "github.com/stretchr/testify/require" ) func Test_ResetAll(t *testing.T) { diff --git a/cmd/tendermint/commands/rollback.go b/cmd/tendermint/commands/rollback.go index cf371e927..0fd3617a5 100644 --- a/cmd/tendermint/commands/rollback.go +++ b/cmd/tendermint/commands/rollback.go @@ -3,13 +3,11 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - - dbm "github.com/tendermint/tm-db" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/store" + "github.com/spf13/cobra" + dbm "github.com/tendermint/tm-db" ) var RollbackStateCmd = &cobra.Command{ diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 9189e1c45..db9f0b936 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -5,13 +5,12 @@ import ( "os" "strings" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/cli" tmflags "github.com/consideritdone/landslidecore/libs/cli/flags" "github.com/consideritdone/landslidecore/libs/log" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var ( diff --git a/cmd/tendermint/commands/root_test.go b/cmd/tendermint/commands/root_test.go index 412927bd6..6a07fd12a 100644 --- a/cmd/tendermint/commands/root_test.go +++ b/cmd/tendermint/commands/root_test.go @@ -8,19 +8,16 @@ import ( "strconv" "testing" + cfg "github.com/consideritdone/landslidecore/config" + "github.com/consideritdone/landslidecore/libs/cli" + tmos "github.com/consideritdone/landslidecore/libs/os" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - cfg "github.com/consideritdone/landslidecore/config" - "github.com/consideritdone/landslidecore/libs/cli" - tmos "github.com/consideritdone/landslidecore/libs/os" ) -var ( - defaultRoot = os.ExpandEnv("$HOME/.some/test/dir") -) +var defaultRoot = os.ExpandEnv("$HOME/.some/test/dir") // clearConfig clears env vars, the given root dir, and resets viper. func clearConfig(dir string) { @@ -88,7 +85,6 @@ func TestRootHome(t *testing.T) { } func TestRootFlagsEnv(t *testing.T) { - // defaults defaults := cfg.DefaultConfig() defaultLogLvl := defaults.LogLevel @@ -116,7 +112,6 @@ func TestRootFlagsEnv(t *testing.T) { } func TestRootConfig(t *testing.T) { - // write non-default config nonDefaultLogLvl := "abc:debug" cvals := map[string]string{ @@ -140,7 +135,7 @@ func TestRootConfig(t *testing.T) { // XXX: path must match cfg.defaultConfigPath configFilePath := filepath.Join(defaultRoot, "config") - err := tmos.EnsureDir(configFilePath, 0700) + err := tmos.EnsureDir(configFilePath, 0o700) require.Nil(t, err) // write the non-defaults to a different path @@ -168,5 +163,5 @@ func WriteConfigVals(dir string, vals map[string]string) error { data += fmt.Sprintf("%s = \"%s\"\n", k, v) } cfile := filepath.Join(dir, "config.toml") - return ioutil.WriteFile(cfile, []byte(data), 0600) + return ioutil.WriteFile(cfile, []byte(data), 0o600) } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index f9a77f366..918245217 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -7,16 +7,13 @@ import ( "io" "os" - "github.com/spf13/cobra" - cfg "github.com/consideritdone/landslidecore/config" tmos "github.com/consideritdone/landslidecore/libs/os" nm "github.com/consideritdone/landslidecore/node" + "github.com/spf13/cobra" ) -var ( - genesisHash []byte -) +var genesisHash []byte // AddNodeFlags exposes some common configuration options on the command-line // These are exposed for convenience of commands embedding a tendermint node diff --git a/cmd/tendermint/commands/show_node_id.go b/cmd/tendermint/commands/show_node_id.go index 855b7187e..130378f23 100644 --- a/cmd/tendermint/commands/show_node_id.go +++ b/cmd/tendermint/commands/show_node_id.go @@ -3,9 +3,8 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - "github.com/consideritdone/landslidecore/p2p" + "github.com/spf13/cobra" ) // ShowNodeIDCmd dumps node's ID to the standard output. diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 92f2334aa..9183b068f 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -3,11 +3,10 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - tmjson "github.com/consideritdone/landslidecore/libs/json" tmos "github.com/consideritdone/landslidecore/libs/os" "github.com/consideritdone/landslidecore/privval" + "github.com/spf13/cobra" ) // ShowValidatorCmd adds capabilities for showing the validator info. diff --git a/cmd/tendermint/commands/testnet.go b/cmd/tendermint/commands/testnet.go index 8a2eaab9b..8d5045543 100644 --- a/cmd/tendermint/commands/testnet.go +++ b/cmd/tendermint/commands/testnet.go @@ -7,9 +7,6 @@ import ( "path/filepath" "strings" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/bytes" tmrand "github.com/consideritdone/landslidecore/libs/rand" @@ -17,6 +14,8 @@ import ( "github.com/consideritdone/landslidecore/privval" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var ( @@ -37,7 +36,7 @@ var ( ) const ( - nodeDirPerm = 0755 + nodeDirPerm = 0o755 ) func init() { diff --git a/cmd/tendermint/commands/version.go b/cmd/tendermint/commands/version.go index 809de3b74..9447cc0e8 100644 --- a/cmd/tendermint/commands/version.go +++ b/cmd/tendermint/commands/version.go @@ -3,9 +3,8 @@ package commands import ( "fmt" - "github.com/spf13/cobra" - "github.com/consideritdone/landslidecore/version" + "github.com/spf13/cobra" ) // VersionCmd ... diff --git a/config/config_test.go b/config/config_test.go index 6a46933bc..584201949 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -27,7 +27,6 @@ func TestDefaultConfig(t *testing.T) { assert.Equal("/foo/bar", cfg.GenesisFile()) assert.Equal("/opt/data", cfg.DBDir()) assert.Equal("/foo/wal/mem", cfg.Mempool.WalDir()) - } func TestConfigValidateBasic(t *testing.T) { diff --git a/config/toml.go b/config/toml.go index e45665dd1..fbed5c046 100644 --- a/config/toml.go +++ b/config/toml.go @@ -12,7 +12,7 @@ import ( ) // DefaultDirPerm is the default permissions used when creating directories. -const DefaultDirPerm = 0700 +const DefaultDirPerm = 0o700 var configTemplate *template.Template @@ -63,7 +63,7 @@ func WriteConfigFile(configFilePath string, config *Config) { panic(err) } - tmos.MustWriteFile(configFilePath, buffer.Bytes(), 0644) + tmos.MustWriteFile(configFilePath, buffer.Bytes(), 0o644) } // Note: any changes to the comments/variables/mapstructure @@ -504,7 +504,7 @@ func ResetTestRoot(testName string) *Config { return ResetTestRootWithChainID(testName, "") } -func ResetTestRootWithChainID(testName string, chainID string) *Config { +func ResetTestRootWithChainID(testName, chainID string) *Config { // create a unique, concurrency-safe test directory under os.TempDir() rootDir, err := ioutil.TempDir("", fmt.Sprintf("%s-%s_", chainID, testName)) if err != nil { @@ -533,11 +533,11 @@ func ResetTestRootWithChainID(testName string, chainID string) *Config { chainID = "tendermint_test" } testGenesis := fmt.Sprintf(testGenesisFmt, chainID) - tmos.MustWriteFile(genesisFilePath, []byte(testGenesis), 0644) + tmos.MustWriteFile(genesisFilePath, []byte(testGenesis), 0o644) } // we always overwrite the priv val - tmos.MustWriteFile(privKeyFilePath, []byte(testPrivValidatorKey), 0644) - tmos.MustWriteFile(privStateFilePath, []byte(testPrivValidatorState), 0644) + tmos.MustWriteFile(privKeyFilePath, []byte(testPrivValidatorKey), 0o644) + tmos.MustWriteFile(privStateFilePath, []byte(testPrivValidatorState), 0o644) config := TestConfig().SetRoot(rootDir) return config diff --git a/config/toml_test.go b/config/toml_test.go index f19710687..1c50ade34 100644 --- a/config/toml_test.go +++ b/config/toml_test.go @@ -68,7 +68,7 @@ func checkConfig(configFile string) bool { var valid bool // list of words we expect in the config - var elems = []string{ + elems := []string{ "moniker", "seeds", "proxy_app", diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index 6003f7770..3b8ab2652 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -64,7 +64,7 @@ func TestByzantinePrevoteEquivocation(t *testing.T) { proxyAppConnCon := abcicli.NewLocalClient(mtx, app) // Make Mempool - mempool := mempl.NewCListMempool(thisConfig.Mempool, proxyAppConnMem, 0) + mempool := mempl.NewCListMempool(thisConfig.Mempool, proxyAppConnMem, 0, nil) mempool.SetLogger(log.TestingLogger().With("module", "mempool")) if thisConfig.Consensus.WaitForTxs() { mempool.EnableTxsAvailable() diff --git a/consensus/common_test.go b/consensus/common_test.go index 2eb53c9eb..96ccbfc62 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -394,7 +394,7 @@ func newStateWithConfigAndBlockStore( proxyAppConnCon := abcicli.NewLocalClient(mtx, app) // Make Mempool - mempool := mempl.NewCListMempool(thisConfig.Mempool, proxyAppConnMem, 0) + mempool := mempl.NewCListMempool(thisConfig.Mempool, proxyAppConnMem, 0, nil) mempool.SetLogger(log.TestingLogger().With("module", "mempool")) if thisConfig.Consensus.WaitForTxs() { mempool.EnableTxsAvailable() diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index dc4b7139c..99cdbd75e 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -158,7 +158,7 @@ func TestReactorWithEvidence(t *testing.T) { proxyAppConnCon := abcicli.NewLocalClient(mtx, app) // Make Mempool - mempool := mempl.NewCListMempool(thisConfig.Mempool, proxyAppConnMem, 0) + mempool := mempl.NewCListMempool(thisConfig.Mempool, proxyAppConnMem, 0, nil) mempool.SetLogger(log.TestingLogger().With("module", "mempool")) if thisConfig.Consensus.WaitForTxs() { mempool.EnableTxsAvailable() diff --git a/consensus/types/height_vote_set.go b/consensus/types/height_vote_set.go index fba912c6e..83290ea6c 100644 --- a/consensus/types/height_vote_set.go +++ b/consensus/types/height_vote_set.go @@ -18,10 +18,8 @@ type RoundVoteSet struct { Precommits *types.VoteSet } -var ( - ErrGotVoteFromUnwantedRound = errors.New( - "peer has sent a vote that does not match our round for more than one round", - ) +var ErrGotVoteFromUnwantedRound = errors.New( + "peer has sent a vote that does not match our round for more than one round", ) /* @@ -186,7 +184,8 @@ func (hvs *HeightVoteSet) SetPeerMaj23( round int32, voteType tmproto.SignedMsgType, peerID p2p.ID, - blockID types.BlockID) error { + blockID types.BlockID, +) error { hvs.mtx.Lock() defer hvs.mtx.Unlock() if !types.IsVoteTypeValid(voteType) { diff --git a/consensus/types/height_vote_set_test.go b/consensus/types/height_vote_set_test.go index 1a73269e5..7e2646398 100644 --- a/consensus/types/height_vote_set_test.go +++ b/consensus/types/height_vote_set_test.go @@ -52,7 +52,6 @@ func TestPeerCatchupRounds(t *testing.T) { if !added || err != nil { t.Error("Expected to successfully add vote from another peer") } - } func makeVoteHR(t *testing.T, height int64, valIndex, round int32, privVals []types.PrivValidator) *types.Vote { diff --git a/crypto/crypto.go b/crypto/crypto.go index 9c3dfdced..2c7561235 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -22,7 +22,7 @@ func AddressHash(bz []byte) Address { type PubKey interface { Address() Address Bytes() []byte - VerifySignature(msg []byte, sig []byte) bool + VerifySignature(msg, sig []byte) bool Equals(PubKey) bool Type() string } @@ -37,6 +37,6 @@ type PrivKey interface { type Symmetric interface { Keygen() []byte - Encrypt(plaintext []byte, secret []byte) (ciphertext []byte) - Decrypt(ciphertext []byte, secret []byte) (plaintext []byte, err error) + Encrypt(plaintext, secret []byte) (ciphertext []byte) + Decrypt(ciphertext, secret []byte) (plaintext []byte, err error) } diff --git a/crypto/ed25519/ed25519.go b/crypto/ed25519/ed25519.go index 0b8fddcc8..09a2f0600 100644 --- a/crypto/ed25519/ed25519.go +++ b/crypto/ed25519/ed25519.go @@ -6,11 +6,10 @@ import ( "fmt" "io" - "golang.org/x/crypto/ed25519" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" tmjson "github.com/consideritdone/landslidecore/libs/json" + "golang.org/x/crypto/ed25519" ) //------------------------------------- @@ -145,7 +144,7 @@ func (pubKey PubKey) Bytes() []byte { return []byte(pubKey) } -func (pubKey PubKey) VerifySignature(msg []byte, sig []byte) bool { +func (pubKey PubKey) VerifySignature(msg, sig []byte) bool { // make sure we use the same algorithm to sign if len(sig) != SignatureSize { return false diff --git a/crypto/ed25519/ed25519_test.go b/crypto/ed25519/ed25519_test.go index 95dd675b3..fd127e9c3 100644 --- a/crypto/ed25519/ed25519_test.go +++ b/crypto/ed25519/ed25519_test.go @@ -3,15 +3,13 @@ package ed25519_test import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSignAndValidateEd25519(t *testing.T) { - privKey := ed25519.GenPrivKey() pubKey := privKey.PubKey() diff --git a/crypto/internal/benchmarking/bench.go b/crypto/internal/benchmarking/bench.go index 28184f947..d36506af4 100644 --- a/crypto/internal/benchmarking/bench.go +++ b/crypto/internal/benchmarking/bench.go @@ -38,7 +38,6 @@ func BenchmarkSigning(b *testing.B, priv crypto.PrivKey) { b.ResetTimer() for i := 0; i < b.N; i++ { _, err := priv.Sign(message) - if err != nil { b.FailNow() } diff --git a/crypto/merkle/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/hash.go b/crypto/merkle/hash.go index 5d82142da..014705ba0 100644 --- a/crypto/merkle/hash.go +++ b/crypto/merkle/hash.go @@ -21,6 +21,6 @@ func leafHash(leaf []byte) []byte { } // returns tmhash(0x01 || left || right) -func innerHash(left []byte, right []byte) []byte { +func innerHash(left, right []byte) []byte { return tmhash.Sum(append(innerPrefix, append(left, right...)...)) } diff --git a/crypto/merkle/proof.go b/crypto/merkle/proof.go index 5ab81bbb9..ef88a3d7d 100644 --- a/crypto/merkle/proof.go +++ b/crypto/merkle/proof.go @@ -49,7 +49,7 @@ func ProofsFromByteSlices(items [][]byte) (rootHash []byte, proofs []*Proof) { // Verify that the Proof proves the root hash. // Check sp.Index/sp.Total manually if needed -func (sp *Proof) Verify(rootHash []byte, leaf []byte) error { +func (sp *Proof) Verify(rootHash, leaf []byte) error { leafHash := leafHash(leaf) if sp.Total < 0 { return errors.New("proof total must be positive") diff --git a/crypto/merkle/proof_test.go b/crypto/merkle/proof_test.go index df449b9f7..fe6aca9ad 100644 --- a/crypto/merkle/proof_test.go +++ b/crypto/merkle/proof_test.go @@ -5,10 +5,9 @@ import ( "fmt" "testing" + tmcrypto "github.com/consideritdone/landslidecore/proto/tendermint/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - tmcrypto "github.com/consideritdone/landslidecore/proto/tendermint/crypto" ) const ProofOpDomino = "test:domino" @@ -146,12 +145,18 @@ func TestProofValidateBasic(t *testing.T) { {"Good", func(sp *Proof) {}, ""}, {"Negative Total", func(sp *Proof) { sp.Total = -1 }, "negative Total"}, {"Negative Index", func(sp *Proof) { sp.Index = -1 }, "negative Index"}, - {"Invalid LeafHash", func(sp *Proof) { sp.LeafHash = make([]byte, 10) }, - "expected LeafHash size to be 32, got 10"}, - {"Too many Aunts", func(sp *Proof) { sp.Aunts = make([][]byte, MaxAunts+1) }, - "expected no more than 100 aunts, got 101"}, - {"Invalid Aunt", func(sp *Proof) { sp.Aunts[0] = make([]byte, 10) }, - "expected Aunts#0 size to be 32, got 10"}, + { + "Invalid LeafHash", func(sp *Proof) { sp.LeafHash = make([]byte, 10) }, + "expected LeafHash size to be 32, got 10", + }, + { + "Too many Aunts", func(sp *Proof) { sp.Aunts = make([][]byte, MaxAunts+1) }, + "expected no more than 100 aunts, got 101", + }, + { + "Invalid Aunt", func(sp *Proof) { sp.Aunts[0] = make([]byte, 10) }, + "expected Aunts#0 size to be 32, got 10", + }, } for _, tc := range testCases { @@ -170,8 +175,8 @@ func TestProofValidateBasic(t *testing.T) { }) } } -func TestVoteProtobuf(t *testing.T) { +func TestVoteProtobuf(t *testing.T) { _, proofs := ProofsFromByteSlices([][]byte{ []byte("apple"), []byte("watermelon"), 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/merkle/tree_test.go b/crypto/merkle/tree_test.go index 0fa844c08..117ab4fe0 100644 --- a/crypto/merkle/tree_test.go +++ b/crypto/merkle/tree_test.go @@ -4,12 +4,11 @@ import ( "encoding/hex" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/tmhash" tmrand "github.com/consideritdone/landslidecore/libs/rand" ctest "github.com/consideritdone/landslidecore/libs/test" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testItem []byte @@ -43,7 +42,6 @@ func TestHashFromByteSlices(t *testing.T) { } func TestProof(t *testing.T) { - // Try an empty proof first rootHash, proofs := ProofsFromByteSlices([][]byte{}) require.Equal(t, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", hex.EncodeToString(rootHash)) @@ -101,7 +99,6 @@ func TestProof(t *testing.T) { } func TestHashAlternatives(t *testing.T) { - total := 100 items := make([][]byte, total) diff --git a/crypto/merkle/types.go b/crypto/merkle/types.go index 6a5c7e6a3..6f478cf65 100644 --- a/crypto/merkle/types.go +++ b/crypto/merkle/types.go @@ -10,18 +10,18 @@ type Tree interface { Size() (size int) Height() (height int8) Has(key []byte) (has bool) - Proof(key []byte) (value []byte, proof []byte, exists bool) // TODO make it return an index + Proof(key []byte) (value, proof []byte, exists bool) // TODO make it return an index Get(key []byte) (index int, value []byte, exists bool) - GetByIndex(index int) (key []byte, value []byte) - Set(key []byte, value []byte) (updated bool) + GetByIndex(index int) (key, value []byte) + Set(key, value []byte) (updated bool) Remove(key []byte) (value []byte, removed bool) HashWithCount() (hash []byte, count int) Hash() (hash []byte) Save() (hash []byte) Load(hash []byte) Copy() Tree - Iterate(func(key []byte, value []byte) (stop bool)) (stopped bool) - IterateRange(start []byte, end []byte, ascending bool, fx func(key []byte, value []byte) (stop bool)) (stopped bool) + Iterate(func(key, value []byte) (stop bool)) (stopped bool) + IterateRange(start, end []byte, ascending bool, fx func(key, value []byte) (stop bool)) (stopped bool) } //----------------------------------------------------------------------- diff --git a/crypto/random_test.go b/crypto/random_test.go index 50db9ea57..4a3d08e03 100644 --- a/crypto/random_test.go +++ b/crypto/random_test.go @@ -3,9 +3,8 @@ package crypto_test import ( "testing" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" + "github.com/stretchr/testify/require" ) // the purpose of this test is primarily to ensure that the randomness diff --git a/crypto/secp256k1/btcec/btcec.go b/crypto/secp256k1/btcec/btcec.go index a2e20f4b3..fb568ce9e 100644 --- a/crypto/secp256k1/btcec/btcec.go +++ b/crypto/secp256k1/btcec/btcec.go @@ -25,12 +25,10 @@ import ( "sync" ) -var ( - // fieldOne is simply the integer 1 in field representation. It is - // used to avoid needing to create it multiple times during the internal - // arithmetic. - fieldOne = new(fieldVal).SetInt(1) -) +// fieldOne is simply the integer 1 in field representation. It is +// used to avoid needing to create it multiple times during the internal +// arithmetic. +var fieldOne = new(fieldVal).SetInt(1) // KoblitzCurve supports a koblitz curve implementation that fits the ECC Curve // interface from crypto/elliptic. @@ -902,8 +900,10 @@ func (curve *KoblitzCurve) Q() *big.Int { return curve.q } -var initonce sync.Once -var secp256k1 KoblitzCurve +var ( + initonce sync.Once + secp256k1 KoblitzCurve +) func initAll() { initS256() diff --git a/crypto/secp256k1/btcec/btcec_test.go b/crypto/secp256k1/btcec/btcec_test.go index 42a69037b..623613483 100644 --- a/crypto/secp256k1/btcec/btcec_test.go +++ b/crypto/secp256k1/btcec/btcec_test.go @@ -352,7 +352,7 @@ func TestAddAffine(t *testing.T) { rx, ry := S256().Add(x1, y1, x2, y2) // Ensure result matches expected. - if rx.Cmp(x3) != 00 || ry.Cmp(y3) != 0 { + if rx.Cmp(x3) != 0o0 || ry.Cmp(y3) != 0 { t.Errorf("#%d wrong result\ngot: (%x, %x)\n"+ "want: (%x, %x)", i, rx, ry, x3, y3) continue @@ -507,7 +507,7 @@ func TestDoubleAffine(t *testing.T) { rx, ry := S256().Double(x1, y1) // Ensure result matches expected. - if rx.Cmp(x3) != 00 || ry.Cmp(y3) != 0 { + if rx.Cmp(x3) != 0o0 || ry.Cmp(y3) != 0 { t.Errorf("#%d wrong result\ngot: (%x, %x)\n"+ "want: (%x, %x)", i, rx, ry, x3, y3) continue @@ -527,7 +527,7 @@ type baseMultTest struct { x, y string } -//TODO: add more test vectors +// TODO: add more test vectors var s256BaseMultTests = []baseMultTest{ { "AA5E28D6A97A2479A65527F7290311A3624D4CC0FA1578598EE3C2613BF99522", @@ -556,7 +556,7 @@ var s256BaseMultTests = []baseMultTest{ }, } -//TODO: test different curves as well? +// TODO: test different curves as well? func TestBaseMult(t *testing.T) { s256 := S256() for i, e := range s256BaseMultTests { diff --git a/crypto/secp256k1/btcec/ciphering_test.go b/crypto/secp256k1/btcec/ciphering_test.go index 819f18846..3a269421c 100644 --- a/crypto/secp256k1/btcec/ciphering_test.go +++ b/crypto/secp256k1/btcec/ciphering_test.go @@ -91,7 +91,8 @@ func TestCipheringErrors(t *testing.T) { {bytes.Repeat([]byte{0x00}, 134)}, // errUnsupportedCurve {bytes.Repeat([]byte{0x02, 0xCA}, 134)}, // errInvalidXLength {bytes.Repeat([]byte{0x02, 0xCA, 0x00, 0x20}, 134)}, // errInvalidYLength - {[]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // IV + {[]byte{ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // IV 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xCA, 0x00, 0x20, // curve and X length 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // X @@ -110,7 +111,8 @@ func TestCipheringErrors(t *testing.T) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }}, // invalid pubkey - {[]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // IV + {[]byte{ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // IV 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xCA, 0x00, 0x20, // curve and X length 0x11, 0x5C, 0x42, 0xE7, 0x57, 0xB2, 0xEF, 0xB7, // X @@ -130,7 +132,8 @@ func TestCipheringErrors(t *testing.T) { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }}, // errInvalidPadding - {[]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // IV + {[]byte{ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // IV 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xCA, 0x00, 0x20, // curve and X length 0x11, 0x5C, 0x42, 0xE7, 0x57, 0xB2, 0xEF, 0xB7, // X diff --git a/crypto/secp256k1/btcec/field.go b/crypto/secp256k1/btcec/field.go index 98105ed8e..606d7b530 100644 --- a/crypto/secp256k1/btcec/field.go +++ b/crypto/secp256k1/btcec/field.go @@ -102,19 +102,17 @@ const ( fieldPrimeWordOne = 0x3ffffbf ) -var ( - // fieldQBytes is the value Q = (P+1)/4 for the secp256k1 prime P. This - // value is used to efficiently compute the square root of values in the - // field via exponentiation. The value of Q in hex is: - // - // Q = 3fffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffff0c - fieldQBytes = []byte{ - 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xbf, 0xff, 0xff, 0x0c, - } -) +// fieldQBytes is the value Q = (P+1)/4 for the secp256k1 prime P. This +// value is used to efficiently compute the square root of values in the +// field via exponentiation. The value of Q in hex is: +// +// Q = 3fffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffff0c +var fieldQBytes = []byte{ + 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xbf, 0xff, 0xff, 0x0c, +} // fieldVal implements optimized fixed-precision arithmetic over the // secp256k1 finite field. This means all arithmetic is performed modulo @@ -125,27 +123,30 @@ var ( // the arithmetic needed for elliptic curve operations. // // The following depicts the internal representation: -// ----------------------------------------------------------------- -// | n[9] | n[8] | ... | n[0] | -// | 32 bits available | 32 bits available | ... | 32 bits available | -// | 22 bits for value | 26 bits for value | ... | 26 bits for value | -// | 10 bits overflow | 6 bits overflow | ... | 6 bits overflow | -// | Mult: 2^(26*9) | Mult: 2^(26*8) | ... | Mult: 2^(26*0) | -// ----------------------------------------------------------------- +// +// ----------------------------------------------------------------- +// | n[9] | n[8] | ... | n[0] | +// | 32 bits available | 32 bits available | ... | 32 bits available | +// | 22 bits for value | 26 bits for value | ... | 26 bits for value | +// | 10 bits overflow | 6 bits overflow | ... | 6 bits overflow | +// | Mult: 2^(26*9) | Mult: 2^(26*8) | ... | Mult: 2^(26*0) | +// ----------------------------------------------------------------- // // For example, consider the number 2^49 + 1. It would be represented as: -// n[0] = 1 -// n[1] = 2^23 -// n[2..9] = 0 +// +// n[0] = 1 +// n[1] = 2^23 +// n[2..9] = 0 // // The full 256-bit value is then calculated by looping i from 9..0 and // doing sum(n[i] * 2^(26i)) like so: -// n[9] * 2^(26*9) = 0 * 2^234 = 0 -// n[8] * 2^(26*8) = 0 * 2^208 = 0 -// ... -// n[1] * 2^(26*1) = 2^23 * 2^26 = 2^49 -// n[0] * 2^(26*0) = 1 * 2^0 = 1 -// Sum: 0 + 0 + ... + 2^49 + 1 = 2^49 + 1 +// +// n[9] * 2^(26*9) = 0 * 2^234 = 0 +// n[8] * 2^(26*8) = 0 * 2^208 = 0 +// ... +// n[1] * 2^(26*1) = 2^23 * 2^26 = 2^49 +// n[0] * 2^(26*0) = 1 * 2^0 = 1 +// Sum: 0 + 0 + ... + 2^49 + 1 = 2^49 + 1 type fieldVal struct { n [10]uint32 } @@ -568,7 +569,7 @@ func (f *fieldVal) Add(val *fieldVal) *fieldVal { // // The field value is returned to support chaining. This enables syntax like: // f3.Add2(f, f2).AddInt(1) so that f3 = f + f2 + 1. -func (f *fieldVal) Add2(val *fieldVal, val2 *fieldVal) *fieldVal { +func (f *fieldVal) Add2(val, val2 *fieldVal) *fieldVal { // Since the field representation intentionally provides overflow bits, // it's ok to use carryless addition as the carry bit is safely part of // each word and will be normalized out. This could obviously be done @@ -636,7 +637,7 @@ func (f *fieldVal) Mul(val *fieldVal) *fieldVal { // // The field value is returned to support chaining. This enables syntax like: // f3.Mul2(f, f2).AddInt(1) so that f3 = (f * f2) + 1. -func (f *fieldVal) Mul2(val *fieldVal, val2 *fieldVal) *fieldVal { +func (f *fieldVal) Mul2(val, val2 *fieldVal) *fieldVal { // This could be done with a couple of for loops and an array to store // the intermediate terms, but this unrolled version is significantly // faster. diff --git a/crypto/secp256k1/btcec/privkey.go b/crypto/secp256k1/btcec/privkey.go index 676a8c3fb..218fd037b 100644 --- a/crypto/secp256k1/btcec/privkey.go +++ b/crypto/secp256k1/btcec/privkey.go @@ -19,7 +19,8 @@ type PrivateKey ecdsa.PrivateKey // PrivKeyFromBytes returns a private and public key for `curve' based on the // private key passed as an argument as a byte slice. func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey, - *PublicKey) { + *PublicKey, +) { x, y := curve.ScalarBaseMult(pk) priv := &ecdsa.PrivateKey{ diff --git a/crypto/secp256k1/btcec/pubkey_test.go b/crypto/secp256k1/btcec/pubkey_test.go index 68b61de10..cd3e86102 100644 --- a/crypto/secp256k1/btcec/pubkey_test.go +++ b/crypto/secp256k1/btcec/pubkey_test.go @@ -23,7 +23,8 @@ var pubKeyTests = []pubKeyTest{ // 0437cd7f8525ceed2324359c2d0ba26006d92d85 { name: "uncompressed ok", - key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -37,7 +38,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed x changed", - key: []byte{0x04, 0x15, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x04, 0x15, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -50,7 +52,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed y changed", - key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -63,7 +66,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed claims compressed", - key: []byte{0x03, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x03, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -76,7 +80,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed as hybrid ok", - key: []byte{0x07, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x07, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -90,7 +95,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed as hybrid wrong", - key: []byte{0x06, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x06, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -104,7 +110,8 @@ var pubKeyTests = []pubKeyTest{ // from tx 0b09c51c51ff762f00fb26217269d2a18e77a4fa87d69b3c363ab4df16543f20 { name: "compressed ok (ybit = 0)", - key: []byte{0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, + key: []byte{ + 0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, 0xa5, 0x49, 0xfd, 0xd6, 0x75, 0xc9, 0x80, 0x75, 0xf1, 0x2e, 0x9c, 0x51, 0x0f, 0x8e, 0xf5, 0x2b, 0xd0, 0x21, 0xa9, 0xa1, 0xf4, 0x80, 0x9d, 0x3b, 0x4d, @@ -115,7 +122,8 @@ var pubKeyTests = []pubKeyTest{ // from tx fdeb8e72524e8dab0da507ddbaf5f88fe4a933eb10a66bc4745bb0aa11ea393c { name: "compressed ok (ybit = 1)", - key: []byte{0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, + key: []byte{ + 0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, 0x09, 0xfb, 0x14, 0x3e, 0x0e, 0x8f, 0xe3, 0x96, 0x34, 0x25, 0x21, 0x88, 0x7e, 0x97, 0x66, 0x90, 0xb6, 0xb4, 0x7f, 0x5b, 0x2a, 0x4b, 0x7d, 0x44, 0x8e, @@ -125,7 +133,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "compressed claims uncompressed (ybit = 0)", - key: []byte{0x04, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, + key: []byte{ + 0x04, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, 0xa5, 0x49, 0xfd, 0xd6, 0x75, 0xc9, 0x80, 0x75, 0xf1, 0x2e, 0x9c, 0x51, 0x0f, 0x8e, 0xf5, 0x2b, 0xd0, 0x21, 0xa9, 0xa1, 0xf4, 0x80, 0x9d, 0x3b, 0x4d, @@ -134,7 +143,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "compressed claims uncompressed (ybit = 1)", - key: []byte{0x05, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, + key: []byte{ + 0x05, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, 0x09, 0xfb, 0x14, 0x3e, 0x0e, 0x8f, 0xe3, 0x96, 0x34, 0x25, 0x21, 0x88, 0x7e, 0x97, 0x66, 0x90, 0xb6, 0xb4, 0x7f, 0x5b, 0x2a, 0x4b, 0x7d, 0x44, 0x8e, @@ -148,7 +158,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "X == P", - key: []byte{0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + key: []byte{ + 0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F, 0xb2, 0xe0, @@ -161,7 +172,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "X > P", - key: []byte{0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + key: []byte{ + 0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFD, 0x2F, 0xb2, 0xe0, @@ -174,7 +186,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "Y == P", - key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xFF, 0xFF, @@ -187,7 +200,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "Y > P", - key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{ + 0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xFF, 0xFF, @@ -200,7 +214,8 @@ var pubKeyTests = []pubKeyTest{ }, { name: "hybrid", - key: []byte{0x06, 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, + key: []byte{ + 0x06, 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xce, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98, 0x48, 0x3a, @@ -249,7 +264,8 @@ func TestPubKeys(t *testing.T) { func TestPublicKeyIsEqual(t *testing.T) { pubKey1, err := ParsePubKey( - []byte{0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, + []byte{ + 0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, 0x09, 0xfb, 0x14, 0x3e, 0x0e, 0x8f, 0xe3, 0x96, 0x34, 0x25, 0x21, 0x88, 0x7e, 0x97, 0x66, 0x90, 0xb6, 0xb4, 0x7f, 0x5b, 0x2a, 0x4b, 0x7d, 0x44, 0x8e, @@ -261,7 +277,8 @@ func TestPublicKeyIsEqual(t *testing.T) { } pubKey2, err := ParsePubKey( - []byte{0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, + []byte{ + 0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, 0xa5, 0x49, 0xfd, 0xd6, 0x75, 0xc9, 0x80, 0x75, 0xf1, 0x2e, 0x9c, 0x51, 0x0f, 0x8e, 0xf5, 0x2b, 0xd0, 0x21, 0xa9, 0xa1, 0xf4, 0x80, 0x9d, 0x3b, 0x4d, diff --git a/crypto/secp256k1/btcec/signature.go b/crypto/secp256k1/btcec/signature.go index cdd7cedfb..565ef0e5c 100644 --- a/crypto/secp256k1/btcec/signature.go +++ b/crypto/secp256k1/btcec/signature.go @@ -283,7 +283,8 @@ func hashToInt(hash []byte, c elliptic.Curve) *big.Int { // case in step 1.6. This counter is used in the bitcoin compressed signature // format and thus we match bitcoind's behaviour here. func recoverKeyFromSignature(curve *KoblitzCurve, sig *Signature, msg []byte, - iter int, doChecks bool) (*PublicKey, error) { + iter int, doChecks bool, +) (*PublicKey, error) { // Parse and validate the R and S signature components. // // Fail if r and s are not in [1, N-1]. @@ -368,7 +369,8 @@ func recoverKeyFromSignature(curve *KoblitzCurve, sig *Signature, msg []byte, // <(byte of 27+public key solution)+4 if compressed >< padded bytes for signature R> // where the R and S parameters are padde up to the bitlengh of the curve. func SignCompact(curve *KoblitzCurve, key *PrivateKey, - hash []byte, isCompressedKey bool) ([]byte, error) { + hash []byte, isCompressedKey bool, +) ([]byte, error) { sig, err := key.Sign(hash) if err != nil { return nil, err @@ -415,7 +417,8 @@ func SignCompact(curve *KoblitzCurve, key *PrivateKey, // key will be returned as well as a boolean if the original key was compressed // or not, else an error will be returned. func RecoverCompact(curve *KoblitzCurve, signature, - hash []byte) (*PublicKey, bool, error) { + hash []byte, +) (*PublicKey, bool, error) { bitlen := (curve.BitSize + 7) / 8 if len(signature) != 1+bitlen*2 { return nil, false, errors.New("invalid compact signature size") @@ -439,7 +442,6 @@ func RecoverCompact(curve *KoblitzCurve, signature, // signRFC6979 generates a deterministic ECDSA signature according to RFC 6979 and BIP 62. func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) { - privkey := privateKey.ToECDSA() N := S256().N halfOrder := S256().halfOrder @@ -470,7 +472,6 @@ func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) { // nonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to RFC 6979. // It takes a 32-byte hash as an input and returns 32-byte nonce to be used in ECDSA algorithm. func nonceRFC6979(privkey *big.Int, hash []byte) *big.Int { - curve := S256() q := curve.Params().N x := privkey diff --git a/crypto/secp256k1/btcec/signature_test.go b/crypto/secp256k1/btcec/signature_test.go index ba02a03f7..40d3a1337 100644 --- a/crypto/secp256k1/btcec/signature_test.go +++ b/crypto/secp256k1/btcec/signature_test.go @@ -40,7 +40,8 @@ var signatureTests = []signatureTest{ // 0437cd7f8525ceed2324359c2d0ba26006d92d85 { name: "valid signature.", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -59,7 +60,8 @@ var signatureTests = []signatureTest{ }, { name: "bad magic.", - sig: []byte{0x31, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x31, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -73,7 +75,8 @@ var signatureTests = []signatureTest{ }, { name: "bad 1st int marker magic.", - sig: []byte{0x30, 0x44, 0x03, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x03, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -87,7 +90,8 @@ var signatureTests = []signatureTest{ }, { name: "bad 2nd int marker.", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -101,7 +105,8 @@ var signatureTests = []signatureTest{ }, { name: "short len", - sig: []byte{0x30, 0x43, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x43, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -121,7 +126,8 @@ var signatureTests = []signatureTest{ }, { name: "long len", - sig: []byte{0x30, 0x45, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x45, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -135,7 +141,8 @@ var signatureTests = []signatureTest{ }, { name: "long X", - sig: []byte{0x30, 0x44, 0x02, 0x42, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x42, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -149,7 +156,8 @@ var signatureTests = []signatureTest{ }, { name: "long Y", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -163,7 +171,8 @@ var signatureTests = []signatureTest{ }, { name: "short Y", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -177,7 +186,8 @@ var signatureTests = []signatureTest{ }, { name: "trailing crap.", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -197,7 +207,8 @@ var signatureTests = []signatureTest{ }, { name: "X == N ", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, @@ -211,7 +222,8 @@ var signatureTests = []signatureTest{ }, { name: "X == N ", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, @@ -225,7 +237,8 @@ var signatureTests = []signatureTest{ }, { name: "Y == N", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -239,7 +252,8 @@ var signatureTests = []signatureTest{ }, { name: "Y > N", - sig: []byte{0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x44, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -253,7 +267,8 @@ var signatureTests = []signatureTest{ }, { name: "0 len X.", - sig: []byte{0x30, 0x24, 0x02, 0x00, 0x02, 0x20, 0x18, 0x15, + sig: []byte{ + 0x30, 0x24, 0x02, 0x00, 0x02, 0x20, 0x18, 0x15, 0x22, 0xec, 0x8e, 0xca, 0x07, 0xde, 0x48, 0x60, 0xa4, 0xac, 0xdd, 0x12, 0x90, 0x9d, 0x83, 0x1c, 0xc5, 0x6c, 0xbb, 0xac, 0x46, 0x22, 0x08, 0x22, 0x21, 0xa8, 0x76, @@ -264,7 +279,8 @@ var signatureTests = []signatureTest{ }, { name: "0 len Y.", - sig: []byte{0x30, 0x24, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x24, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -275,7 +291,8 @@ var signatureTests = []signatureTest{ }, { name: "extra R padding.", - sig: []byte{0x30, 0x45, 0x02, 0x21, 0x00, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x45, 0x02, 0x21, 0x00, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -289,7 +306,8 @@ var signatureTests = []signatureTest{ }, { name: "extra S padding.", - sig: []byte{0x30, 0x45, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x45, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -311,7 +329,8 @@ var signatureTests = []signatureTest{ // for the coordinates being zero. { name: "X == 0", - sig: []byte{0x30, 0x25, 0x02, 0x01, 0x00, 0x02, 0x20, 0x18, + sig: []byte{ + 0x30, 0x25, 0x02, 0x01, 0x00, 0x02, 0x20, 0x18, 0x15, 0x22, 0xec, 0x8e, 0xca, 0x07, 0xde, 0x48, 0x60, 0xa4, 0xac, 0xdd, 0x12, 0x90, 0x9d, 0x83, 0x1c, 0xc5, 0x6c, 0xbb, 0xac, 0x46, 0x22, 0x08, 0x22, 0x21, 0xa8, @@ -322,7 +341,8 @@ var signatureTests = []signatureTest{ }, { name: "Y == 0.", - sig: []byte{0x30, 0x25, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, + sig: []byte{ + 0x30, 0x25, 0x02, 0x20, 0x4e, 0x45, 0xe1, 0x69, 0x32, 0xb8, 0xaf, 0x51, 0x49, 0x61, 0xa1, 0xd3, 0xa1, 0xa2, 0x5f, 0xdf, 0x3f, 0x4f, 0x77, 0x32, 0xe9, 0xd6, 0x24, 0xc6, 0xc6, 0x15, 0x48, 0xab, 0x5f, 0xb8, 0xcd, @@ -463,7 +483,8 @@ func TestSignatureSerialize(t *testing.T) { } func testSignCompact(t *testing.T, tag string, curve *KoblitzCurve, - data []byte, isCompressed bool) { + data []byte, isCompressed bool, +) { priv, _ := NewPrivateKey(curve) hashed := []byte("testing") diff --git a/crypto/secp256k1/secp256k1.go b/crypto/secp256k1/secp256k1.go index 8dc0ad413..7d0070593 100644 --- a/crypto/secp256k1/secp256k1.go +++ b/crypto/secp256k1/secp256k1.go @@ -8,11 +8,10 @@ import ( "io" "math/big" - secp256k1 "github.com/consideritdone/landslidecore/crypto/secp256k1/btcec" - "golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format - "github.com/consideritdone/landslidecore/crypto" + secp256k1 "github.com/consideritdone/landslidecore/crypto/secp256k1/btcec" tmjson "github.com/consideritdone/landslidecore/libs/json" + "golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format ) // ------------------------------------- @@ -194,7 +193,7 @@ func (pubKey PubKey) Type() string { // VerifySignature verifies a signature of the form R || S. // It rejects signatures which are not in lower-S form. -func (pubKey PubKey) VerifySignature(msg []byte, sigStr []byte) bool { +func (pubKey PubKey) VerifySignature(msg, sigStr []byte) bool { if len(sigStr) != 64 { return false } diff --git a/crypto/secp256k1/secp256k1_internal_test.go b/crypto/secp256k1/secp256k1_internal_test.go index c68ea62e3..661903d82 100644 --- a/crypto/secp256k1/secp256k1_internal_test.go +++ b/crypto/secp256k1/secp256k1_internal_test.go @@ -5,13 +5,11 @@ import ( "math/big" "testing" - "github.com/stretchr/testify/require" - secp256k1 "github.com/consideritdone/landslidecore/crypto/secp256k1/btcec" + "github.com/stretchr/testify/require" ) func Test_genPrivKey(t *testing.T) { - empty := make([]byte, 32) oneB := big.NewInt(1).Bytes() onePadded := make([]byte, 32) diff --git a/crypto/secp256k1/secp256k1_test.go b/crypto/secp256k1/secp256k1_test.go index bdfe94a08..9c2c1a515 100644 --- a/crypto/secp256k1/secp256k1_test.go +++ b/crypto/secp256k1/secp256k1_test.go @@ -6,13 +6,11 @@ import ( "testing" "github.com/btcsuite/btcutil/base58" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/secp256k1" - underlyingSecp256k1 "github.com/consideritdone/landslidecore/crypto/secp256k1/btcec" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type keyData struct { diff --git a/crypto/sr25519/encoding.go b/crypto/sr25519/encoding.go index 096a3e7f9..954fb28c4 100644 --- a/crypto/sr25519/encoding.go +++ b/crypto/sr25519/encoding.go @@ -17,7 +17,6 @@ const ( ) func init() { - tmjson.RegisterType(PubKey{}, PubKeyName) tmjson.RegisterType(PrivKey{}, PrivKeyName) } diff --git a/crypto/sr25519/privkey.go b/crypto/sr25519/privkey.go index 2699c4113..a335c8072 100644 --- a/crypto/sr25519/privkey.go +++ b/crypto/sr25519/privkey.go @@ -5,9 +5,8 @@ import ( "fmt" "io" - "github.com/consideritdone/landslidecore/crypto" - schnorrkel "github.com/ChainSafe/go-schnorrkel" + "github.com/consideritdone/landslidecore/crypto" ) // PrivKeySize is the number of bytes in an Sr25519 private key. diff --git a/crypto/sr25519/pubkey.go b/crypto/sr25519/pubkey.go index 87e14a16f..1fa1ea2a9 100644 --- a/crypto/sr25519/pubkey.go +++ b/crypto/sr25519/pubkey.go @@ -4,10 +4,9 @@ import ( "bytes" "fmt" + schnorrkel "github.com/ChainSafe/go-schnorrkel" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" - - schnorrkel "github.com/ChainSafe/go-schnorrkel" ) var _ crypto.PubKey = PubKey{} @@ -31,7 +30,7 @@ func (pubKey PubKey) Bytes() []byte { return []byte(pubKey) } -func (pubKey PubKey) VerifySignature(msg []byte, sig []byte) bool { +func (pubKey PubKey) VerifySignature(msg, sig []byte) bool { // make sure we use the same algorithm to sign if len(sig) != SignatureSize { return false @@ -73,5 +72,4 @@ func (pubKey PubKey) Equals(other crypto.PubKey) bool { func (pubKey PubKey) Type() string { return keyType - } diff --git a/crypto/sr25519/sr25519_test.go b/crypto/sr25519/sr25519_test.go index 743c65445..3d8b3a271 100644 --- a/crypto/sr25519/sr25519_test.go +++ b/crypto/sr25519/sr25519_test.go @@ -3,15 +3,13 @@ package sr25519_test import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/sr25519" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSignAndValidateSr25519(t *testing.T) { - privKey := sr25519.GenPrivKey() pubKey := privKey.PubKey() diff --git a/crypto/tmhash/hash.go b/crypto/tmhash/hash.go index f9b958242..f714c405e 100644 --- a/crypto/tmhash/hash.go +++ b/crypto/tmhash/hash.go @@ -34,6 +34,7 @@ type sha256trunc struct { func (h sha256trunc) Write(p []byte) (n int, err error) { return h.sha256.Write(p) } + func (h sha256trunc) Sum(b []byte) []byte { shasum := h.sha256.Sum(b) return shasum[:TruncatedSize] diff --git a/crypto/tmhash/hash_test.go b/crypto/tmhash/hash_test.go index c01714816..703ac5fc0 100644 --- a/crypto/tmhash/hash_test.go +++ b/crypto/tmhash/hash_test.go @@ -4,10 +4,9 @@ import ( "crypto/sha256" "testing" + "github.com/consideritdone/landslidecore/crypto/tmhash" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/crypto/tmhash" ) func TestHash(t *testing.T) { diff --git a/crypto/xsalsa20symmetric/symmetric.go b/crypto/xsalsa20symmetric/symmetric.go index 68aee5014..41a98f997 100644 --- a/crypto/xsalsa20symmetric/symmetric.go +++ b/crypto/xsalsa20symmetric/symmetric.go @@ -4,19 +4,20 @@ import ( "errors" "fmt" - "golang.org/x/crypto/nacl/secretbox" - "github.com/consideritdone/landslidecore/crypto" + "golang.org/x/crypto/nacl/secretbox" ) // TODO, make this into a struct that implements crypto.Symmetric. -const nonceLen = 24 -const secretLen = 32 +const ( + nonceLen = 24 + secretLen = 32 +) // secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase)) // The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. -func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) { +func EncryptSymmetric(plaintext, secret []byte) (ciphertext []byte) { if len(secret) != secretLen { panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) } @@ -33,7 +34,7 @@ func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) { // secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase)) // The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. -func DecryptSymmetric(ciphertext []byte, secret []byte) (plaintext []byte, err error) { +func DecryptSymmetric(ciphertext, secret []byte) (plaintext []byte, err error) { if len(secret) != secretLen { panic(fmt.Sprintf("Secret must be 32 bytes long, got len %v", len(secret))) } diff --git a/crypto/xsalsa20symmetric/symmetric_test.go b/crypto/xsalsa20symmetric/symmetric_test.go index 576894f62..823be8814 100644 --- a/crypto/xsalsa20symmetric/symmetric_test.go +++ b/crypto/xsalsa20symmetric/symmetric_test.go @@ -3,16 +3,13 @@ package xsalsa20symmetric import ( "testing" + "github.com/consideritdone/landslidecore/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "golang.org/x/crypto/bcrypt" - - "github.com/consideritdone/landslidecore/crypto" ) func TestSimple(t *testing.T) { - plaintext := []byte("sometext") secret := []byte("somesecretoflengththirtytwo===32") ciphertext := EncryptSymmetric(plaintext, secret) @@ -23,7 +20,6 @@ func TestSimple(t *testing.T) { } func TestSimpleWithKDF(t *testing.T) { - plaintext := []byte("sometext") secretPass := []byte("somesecret") secret, err := bcrypt.GenerateFromPassword(secretPass, 12) diff --git a/evidence/doc.go b/evidence/doc.go index d521debd3..42ea1d6bb 100644 --- a/evidence/doc.go +++ b/evidence/doc.go @@ -3,7 +3,7 @@ Package evidence handles all evidence storage and gossiping from detection to bl For the different types of evidence refer to the `evidence.go` file in the types package or https://github.com/tendermint/spec/blob/master/spec/consensus/light-client/accountability.md. -Gossiping +# Gossiping The core functionality begins with the evidence reactor (see reactor. go) which operates both the sending and receiving of evidence. @@ -29,7 +29,7 @@ There are two buckets that evidence can be stored in: Pending & Committed. All evidence is proto encoded to disk. -Proposing +# Proposing When a new block is being proposed (in state/execution.go#CreateProposalBlock), `PendingEvidence(maxBytes)` is called to send up to the maxBytes of uncommitted evidence, from the evidence store, @@ -42,12 +42,11 @@ Once the proposed evidence is submitted, the evidence is marked as committed and is moved from the broadcasted set to the committed set. As a result it is also removed from the concurrent list so that it is no longer gossiped. -Minor Functionality +# Minor Functionality As all evidence (including POLC's) are bounded by an expiration date, those that exceed this are no longer needed and hence pruned. Currently, only committed evidence in which a marker to the height that the evidence was committed and hence very small is saved. All updates are made from the `Update(block, state)` function which should be called when a new block is committed. - */ package evidence diff --git a/evidence/pool.go b/evidence/pool.go index 02acef99c..d81cedfdf 100644 --- a/evidence/pool.go +++ b/evidence/pool.go @@ -8,15 +8,14 @@ import ( "sync/atomic" "time" - "github.com/gogo/protobuf/proto" - gogotypes "github.com/gogo/protobuf/types" - dbm "github.com/tendermint/tm-db" - clist "github.com/consideritdone/landslidecore/libs/clist" "github.com/consideritdone/landslidecore/libs/log" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + gogotypes "github.com/gogo/protobuf/types" + dbm "github.com/tendermint/tm-db" ) const ( @@ -52,7 +51,6 @@ type Pool struct { // NewPool creates an evidence pool. If using an existing evidence store, // it will add all pending evidence to the concurrent list. func NewPool(evidenceDB dbm.DB, stateDB sm.Store, blockStore BlockStore) (*Pool, error) { - state, err := stateDB.Load() if err != nil { return nil, fmt.Errorf("cannot load state: %w", err) @@ -434,8 +432,8 @@ func (evpool *Pool) removeExpiredPendingEvidence() (int64, time.Time) { } func (evpool *Pool) removeEvidenceFromList( - blockEvidenceMap map[string]struct{}) { - + blockEvidenceMap map[string]struct{}, +) { for e := evpool.evidenceList.Front(); e != nil; e = e.Next() { // Remove from clist ev := e.Value.(types.Evidence) diff --git a/evidence/pool_test.go b/evidence/pool_test.go index 634b578c5..9b5c9c4bb 100644 --- a/evidence/pool_test.go +++ b/evidence/pool_test.go @@ -5,12 +5,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/evidence" "github.com/consideritdone/landslidecore/evidence/mocks" "github.com/consideritdone/landslidecore/libs/log" @@ -21,10 +15,13 @@ import ( "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestMain(m *testing.M) { - code := m.Run() os.Exit(code) } @@ -91,7 +88,6 @@ func TestEvidencePoolBasic(t *testing.T) { assert.NoError(t, pool.AddEvidence(ev)) evs, _ = pool.PendingEvidence(defaultEvidenceMaxBytes) assert.Equal(t, 1, len(evs)) - } // Tests inbound evidence for the right time and height @@ -125,8 +121,10 @@ func TestAddExpiredEvidence(t *testing.T) { {height, defaultEvidenceTime, false, "valid evidence"}, {expiredHeight, defaultEvidenceTime, false, "valid evidence (despite old height)"}, {height - 1, expiredEvidenceTime, false, "valid evidence (despite old time)"}, - {expiredHeight - 1, expiredEvidenceTime, true, - "evidence from height 1 (created at: 2019-01-01 00:00:00 +0000 UTC) is too old"}, + { + expiredHeight - 1, expiredEvidenceTime, true, + "evidence from height 1 (created at: 2019-01-01 00:00:00 +0000 UTC) is too old", + }, {height, defaultEvidenceTime.Add(1 * time.Minute), true, "evidence time and block time is different"}, } @@ -343,7 +341,6 @@ func TestRecoverPendingEvidence(t *testing.T) { assert.Equal(t, 1, len(evList)) next := newPool.EvidenceFront() assert.Equal(t, goodEvidence, next.Value.(types.Evidence)) - } func initializeStateFromValidatorSet(valSet *types.ValidatorSet, height int64) sm.Store { @@ -383,7 +380,6 @@ func initializeStateFromValidatorSet(valSet *types.ValidatorSet, height int64) s } func initializeValidatorState(privVal types.PrivValidator, height int64) sm.Store { - pubKey, _ := privVal.GetPubKey() validator := &types.Validator{Address: pubKey.Address(), VotingPower: 10, PubKey: pubKey} diff --git a/evidence/reactor.go b/evidence/reactor.go index 86dc15e5a..1eda69e93 100644 --- a/evidence/reactor.go +++ b/evidence/reactor.go @@ -160,7 +160,6 @@ func (evR Reactor) prepareEvidenceMessage( peer p2p.Peer, ev types.Evidence, ) (evis []types.Evidence) { - // make sure the peer is up to date evHeight := ev.Height() peerState, ok := peer.Get(types.PeerStateKey).(PeerState) diff --git a/evidence/reactor_test.go b/evidence/reactor_test.go index f90ed2ea1..d10bc6edb 100644 --- a/evidence/reactor_test.go +++ b/evidence/reactor_test.go @@ -7,14 +7,6 @@ import ( "testing" "time" - "github.com/fortytw2/leaktest" - "github.com/go-kit/log/term" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" @@ -26,6 +18,12 @@ import ( tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/fortytw2/leaktest" + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) var ( @@ -237,7 +235,8 @@ func evidenceLogger() log.Logger { // connect N evidence reactors through N switches func makeAndConnectReactorsAndPools(config *cfg.Config, stateStores []sm.Store) ([]*evidence.Reactor, - []*evidence.Pool) { + []*evidence.Pool, +) { N := len(stateStores) reactors := make([]*evidence.Reactor, N) @@ -263,7 +262,6 @@ func makeAndConnectReactorsAndPools(config *cfg.Config, stateStores []sm.Store) p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("EVIDENCE", reactors[i]) return s - }, p2p.Connect2Switches) return reactors, pools @@ -345,7 +343,7 @@ func (ps peerState) GetHeight() int64 { } func exampleVote(t byte) *types.Vote { - var stamp, err = time.Parse(types.TimeFormat, "2017-12-25T03:00:01.234Z") + stamp, err := time.Parse(types.TimeFormat, "2017-12-25T03:00:01.234Z") if err != nil { panic(err) } @@ -369,7 +367,6 @@ func exampleVote(t byte) *types.Vote { // nolint:lll //ignore line length for tests func TestEvidenceVectors(t *testing.T) { - val := &types.Validator{ Address: crypto.AddressHash([]byte("validator_address")), VotingPower: 10, @@ -412,5 +409,4 @@ func TestEvidenceVectors(t *testing.T) { require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName) } - } diff --git a/evidence/verify.go b/evidence/verify.go index 2a70445bf..0c98eb4b9 100644 --- a/evidence/verify.go +++ b/evidence/verify.go @@ -97,7 +97,6 @@ func (evpool *Pool) verify(evidence types.Evidence) error { default: return fmt.Errorf("unrecognized evidence type: %T", evidence) } - } // VerifyLightClientAttack verifies LightClientAttackEvidence against the state of the full node. This involves @@ -111,7 +110,8 @@ func (evpool *Pool) verify(evidence types.Evidence) error { // // 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 { + 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 // verification jump between the common header and the conflicting one if commonHeader.Height != e.ConflictingBlock.Height { diff --git a/evidence/verify_test.go b/evidence/verify_test.go index 28fe20f65..bbd97e456 100644 --- a/evidence/verify_test.go +++ b/evidence/verify_test.go @@ -5,11 +5,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" "github.com/consideritdone/landslidecore/evidence" @@ -21,6 +16,9 @@ import ( smmocks "github.com/consideritdone/landslidecore/state/mocks" "github.com/consideritdone/landslidecore/types" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) const ( @@ -454,7 +452,7 @@ func makeLunaticEvidence( height, commonHeight int64, totalVals, byzVals, phantomVals int, commonTime, attackTime time.Time, -) (ev *types.LightClientAttackEvidence, trusted *types.LightBlock, common *types.LightBlock) { +) (ev *types.LightClientAttackEvidence, trusted, common *types.LightBlock) { commonValSet, commonPrivVals := types.RandValidatorSet(totalVals, defaultVotingPower) require.Greater(t, totalVals, byzVals) @@ -529,7 +527,8 @@ func makeLunaticEvidence( func makeVote( t *testing.T, val types.PrivValidator, chainID string, valIndex int32, height int64, - round int32, step int, blockID types.BlockID, time time.Time) *types.Vote { + round int32, step int, blockID types.BlockID, time time.Time, +) *types.Vote { pubKey, err := val.GetPubKey() require.NoError(t, err) v := &types.Vote{ @@ -587,7 +586,8 @@ func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.Bloc } func orderPrivValsByValSet( - t *testing.T, vals *types.ValidatorSet, privVals []types.PrivValidator) []types.PrivValidator { + t *testing.T, vals *types.ValidatorSet, privVals []types.PrivValidator, +) []types.PrivValidator { output := make([]types.PrivValidator, len(privVals)) for idx, v := range vals.Validators { for _, p := range privVals { diff --git a/libs/async/async.go b/libs/async/async.go index e716821b6..2fb6173e3 100644 --- a/libs/async/async.go +++ b/libs/async/async.go @@ -54,7 +54,7 @@ func (trs *TaskResultSet) LatestResult(index int) (TaskResult, bool) { // Writes results to trs.results without waiting for all tasks to complete. func (trs *TaskResultSet) Reap() *TaskResultSet { for i := 0; i < len(trs.results); i++ { - var trch = trs.chz[i] + trch := trs.chz[i] select { case result, ok := <-trch: if ok { @@ -78,7 +78,7 @@ func (trs *TaskResultSet) Reap() *TaskResultSet { // Like Reap() but waits until all tasks have returned or panic'd. func (trs *TaskResultSet) Wait() *TaskResultSet { for i := 0; i < len(trs.results); i++ { - var trch = trs.chz[i] + trch := trs.chz[i] result, ok := <-trch if ok { // Write result. @@ -125,9 +125,9 @@ func (trs *TaskResultSet) FirstError() error { // concurrent quit-like primitives, passed implicitly via Task closures. (e.g. // it's not Parallel's concern how you quit/abort your tasks). func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) { - var taskResultChz = make([]TaskResultCh, len(tasks)) // To return. - var taskDoneCh = make(chan bool, len(tasks)) // A "wait group" channel, early abort if any true received. - var numPanics = new(int32) // Keep track of panics to set ok=false later. + taskResultChz := make([]TaskResultCh, len(tasks)) // To return. + taskDoneCh := make(chan bool, len(tasks)) // A "wait group" channel, early abort if any true received. + numPanics := new(int32) // Keep track of panics to set ok=false later. // We will set it to false iff any tasks panic'd or returned abort. ok = true @@ -136,7 +136,7 @@ func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) { // When the task is complete, it will appear in the // respective taskResultCh (associated by task index). for i, task := range tasks { - var taskResultCh = make(chan TaskResult, 1) // Capacity for 1 result. + taskResultCh := make(chan TaskResult, 1) // Capacity for 1 result. taskResultChz[i] = taskResultCh go func(i int, task Task, taskResultCh chan TaskResult) { // Recovery @@ -155,7 +155,7 @@ func Parallel(tasks ...Task) (trs *TaskResultSet, ok bool) { } }() // Run the task. - var val, abort, err = task(i) + val, abort, err := task(i) // Send val/err to taskResultCh. // NOTE: Below this line, nothing must panic/ taskResultCh <- TaskResult{val, err} diff --git a/libs/async/async_test.go b/libs/async/async_test.go index 4faead444..59e836785 100644 --- a/libs/async/async_test.go +++ b/libs/async/async_test.go @@ -11,10 +11,9 @@ import ( ) func TestParallel(t *testing.T) { - // Create tasks. - var counter = new(int32) - var tasks = make([]Task, 100*1000) + counter := new(int32) + tasks := make([]Task, 100*1000) for i := 0; i < len(tasks); i++ { tasks[i] = func(i int) (res interface{}, abort bool, err error) { atomic.AddInt32(counter, 1) @@ -23,7 +22,7 @@ func TestParallel(t *testing.T) { } // Run in parallel. - var trs, ok = Parallel(tasks...) + trs, ok := Parallel(tasks...) assert.True(t, ok) // Verify. @@ -52,14 +51,13 @@ func TestParallel(t *testing.T) { } func TestParallelAbort(t *testing.T) { - - var flow1 = make(chan struct{}, 1) - var flow2 = make(chan struct{}, 1) - var flow3 = make(chan struct{}, 1) // Cap must be > 0 to prevent blocking. - var flow4 = make(chan struct{}, 1) + flow1 := make(chan struct{}, 1) + flow2 := make(chan struct{}, 1) + flow3 := make(chan struct{}, 1) // Cap must be > 0 to prevent blocking. + flow4 := make(chan struct{}, 1) // Create tasks. - var tasks = []Task{ + tasks := []Task{ func(i int) (res interface{}, abort bool, err error) { assert.Equal(t, i, 0) flow1 <- struct{}{} @@ -83,7 +81,7 @@ func TestParallelAbort(t *testing.T) { } // Run in parallel. - var taskResultSet, ok = Parallel(tasks...) + taskResultSet, ok := Parallel(tasks...) assert.False(t, ok, "ok should be false since we aborted task #2.") // Verify task #3. @@ -104,9 +102,8 @@ func TestParallelAbort(t *testing.T) { } func TestParallelRecover(t *testing.T) { - // Create tasks. - var tasks = []Task{ + tasks := []Task{ func(i int) (res interface{}, abort bool, err error) { return 0, false, nil }, @@ -119,7 +116,7 @@ func TestParallelRecover(t *testing.T) { } // Run in parallel. - var taskResultSet, ok = Parallel(tasks...) + taskResultSet, ok := Parallel(tasks...) assert.False(t, ok, "ok should be false since we panic'd in task #2.") // Verify task #0, #1, #2. @@ -130,7 +127,8 @@ func TestParallelRecover(t *testing.T) { // Wait for result func checkResult(t *testing.T, taskResultSet *TaskResultSet, index int, - val interface{}, err error, pnk interface{}) { + val interface{}, err error, pnk interface{}, +) { taskResult, ok := taskResultSet.LatestResult(index) taskName := fmt.Sprintf("Task #%v", index) assert.True(t, ok, "TaskResultCh unexpectedly closed for %v", taskName) diff --git a/libs/autofile/autofile.go b/libs/autofile/autofile.go index 4b3d5db34..ddbb6bcb8 100644 --- a/libs/autofile/autofile.go +++ b/libs/autofile/autofile.go @@ -35,7 +35,7 @@ if err != nil { const ( autoFileClosePeriod = 1000 * time.Millisecond - autoFilePerms = os.FileMode(0600) + autoFilePerms = os.FileMode(0o600) ) // AutoFile automatically closes and re-opens file for writing. The file is diff --git a/libs/autofile/autofile_test.go b/libs/autofile/autofile_test.go index 4ca60460c..fa83cc42e 100644 --- a/libs/autofile/autofile_test.go +++ b/libs/autofile/autofile_test.go @@ -8,10 +8,9 @@ import ( "testing" "time" + tmos "github.com/consideritdone/landslidecore/libs/os" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - tmos "github.com/consideritdone/landslidecore/libs/os" ) func TestSIGHUP(t *testing.T) { diff --git a/libs/autofile/cmd/logjack.go b/libs/autofile/cmd/logjack.go index ea4f82956..64172177b 100644 --- a/libs/autofile/cmd/logjack.go +++ b/libs/autofile/cmd/logjack.go @@ -12,12 +12,14 @@ import ( tmos "github.com/consideritdone/landslidecore/libs/os" ) -const Version = "0.0.1" -const readBufferSize = 1024 // 1KB at a time +const ( + Version = "0.0.1" + readBufferSize = 1024 // 1KB at a time +) // Parse command-line options -func parseFlags() (headPath string, chopSize int64, limitSize int64, version bool) { - var flagSet = flag.NewFlagSet(os.Args[0], flag.ExitOnError) +func parseFlags() (headPath string, chopSize, limitSize int64, version bool) { + flagSet := flag.NewFlagSet(os.Args[0], flag.ExitOnError) var chopSizeStr, limitSizeStr string flagSet.StringVar(&headPath, "head", "logjack.out", "Destination (head) file.") flagSet.StringVar(&chopSizeStr, "chop", "100M", "Move file if greater than this") diff --git a/libs/autofile/group.go b/libs/autofile/group.go index 7859d56a9..e0a244e21 100644 --- a/libs/autofile/group.go +++ b/libs/autofile/group.go @@ -410,7 +410,7 @@ func (g *Group) readGroupInfo() GroupInfo { return GroupInfo{minIndex, maxIndex, totalSize, headSize} } -func filePathForIndex(headPath string, index int, maxIndex int) string { +func filePathForIndex(headPath string, index, maxIndex int) string { if index == maxIndex { return headPath } diff --git a/libs/autofile/group_test.go b/libs/autofile/group_test.go index d566d3e5b..5ab03e7a9 100644 --- a/libs/autofile/group_test.go +++ b/libs/autofile/group_test.go @@ -7,17 +7,16 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - tmos "github.com/consideritdone/landslidecore/libs/os" tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createTestGroupWithHeadSizeLimit(t *testing.T, headSizeLimit int64) *Group { testID := tmrand.Str(12) testDir := "_test_" + testID - err := tmos.EnsureDir(testDir, 0700) + err := tmos.EnsureDir(testDir, 0o700) require.NoError(t, err, "Error creating dir") headPath := testDir + "/myfile" diff --git a/libs/bits/bit_array_test.go b/libs/bits/bit_array_test.go index 21ccfe4f4..f984edc49 100644 --- a/libs/bits/bit_array_test.go +++ b/libs/bits/bit_array_test.go @@ -6,10 +6,9 @@ import ( "fmt" "testing" + tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - tmrand "github.com/consideritdone/landslidecore/libs/rand" ) func randBitArray(bits int) (*BitArray, []byte) { @@ -28,7 +27,6 @@ func randBitArray(bits int) (*BitArray, []byte) { } func TestAnd(t *testing.T) { - bA1, _ := randBitArray(51) bA2, _ := randBitArray(31) bA3 := bA1.And(bA2) @@ -53,7 +51,6 @@ func TestAnd(t *testing.T) { } func TestOr(t *testing.T) { - bA1, _ := randBitArray(51) bA2, _ := randBitArray(31) bA3 := bA1.Or(bA2) @@ -218,7 +215,6 @@ func TestNewBitArrayNeverCrashesOnNegatives(t *testing.T) { } func TestJSONMarshalUnmarshal(t *testing.T) { - bA1 := NewBitArray(0) bA2 := NewBitArray(1) diff --git a/libs/cli/flags/log_level_test.go b/libs/cli/flags/log_level_test.go index 665281bf5..53a824f97 100644 --- a/libs/cli/flags/log_level_test.go +++ b/libs/cli/flags/log_level_test.go @@ -26,21 +26,24 @@ func TestParseLogLevel(t *testing.T) { ``, `{"_msg":"Mesmero","level":"error","module":"mempool"}`, `{"_msg":"Mind","level":"info","module":"state"}`, // if no default is given, assume info - ``}}, + ``, + }}, {"mempool:error,*:debug", []string{ `{"_msg":"Kingpin","level":"debug","module":"wire"}`, ``, `{"_msg":"Mesmero","level":"error","module":"mempool"}`, `{"_msg":"Mind","level":"info","module":"state"}`, - `{"_msg":"Gideon","level":"debug"}`}}, + `{"_msg":"Gideon","level":"debug"}`, + }}, {"*:debug,wire:none", []string{ ``, `{"_msg":"Kitty Pryde","level":"info","module":"mempool"}`, `{"_msg":"Mesmero","level":"error","module":"mempool"}`, `{"_msg":"Mind","level":"info","module":"state"}`, - `{"_msg":"Gideon","level":"debug"}`}}, + `{"_msg":"Gideon","level":"debug"}`, + }}, } for _, c := range correctLogLevels { diff --git a/libs/cli/helper.go b/libs/cli/helper.go index 4b87bd60b..0e767182d 100644 --- a/libs/cli/helper.go +++ b/libs/cli/helper.go @@ -19,7 +19,7 @@ func WriteConfigVals(dir string, vals map[string]string) error { data += fmt.Sprintf("%s = \"%s\"\n", k, v) } cfile := filepath.Join(dir, "config.toml") - return ioutil.WriteFile(cfile, []byte(data), 0600) + return ioutil.WriteFile(cfile, []byte(data), 0o600) } // RunWithArgs executes the given command with the specified command line args diff --git a/libs/cli/setup_test.go b/libs/cli/setup_test.go index 0cb322344..2ff9127a9 100644 --- a/libs/cli/setup_test.go +++ b/libs/cli/setup_test.go @@ -27,8 +27,11 @@ func TestSetupEnv(t *testing.T) { {nil, map[string]string{"DEMO_FOOBAR": "good"}, "good"}, {nil, map[string]string{"DEMOFOOBAR": "silly"}, "silly"}, // and that cli overrides env... - {[]string{"--foobar", "important"}, - map[string]string{"DEMO_FOOBAR": "ignored"}, "important"}, + { + []string{"--foobar", "important"}, + map[string]string{"DEMO_FOOBAR": "ignored"}, + "important", + }, } for idx, tc := range cases { diff --git a/libs/clist/clist_test.go b/libs/clist/clist_test.go index 20c310ed6..6c0155797 100644 --- a/libs/clist/clist_test.go +++ b/libs/clist/clist_test.go @@ -7,9 +7,8 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/assert" ) func TestPanicOnMaxLength(t *testing.T) { @@ -63,7 +62,6 @@ func TestSmall(t *testing.T) { if l.Len() != 0 { t.Error("Expected len 0, got ", l.Len()) } - } // This test is quite hacky because it relies on SetFinalizer @@ -166,7 +164,6 @@ func _TestGCRandom(t *testing.T) { } func TestScanRightDeleteRandom(t *testing.T) { - const numElements = 1000 const numTimes = 100 const numScanners = 10 diff --git a/libs/events/events.go b/libs/events/events.go index 36e1c7765..f115e9294 100644 --- a/libs/events/events.go +++ b/libs/events/events.go @@ -47,7 +47,7 @@ type EventSwitch interface { Fireable AddListenerForEvent(listenerID, event string, cb EventCallback) error - RemoveListenerForEvent(event string, listenerID string) + RemoveListenerForEvent(event, listenerID string) RemoveListener(listenerID string) } @@ -118,7 +118,7 @@ func (evsw *eventSwitch) RemoveListener(listenerID string) { } } -func (evsw *eventSwitch) RemoveListenerForEvent(event string, listenerID string) { +func (evsw *eventSwitch) RemoveListenerForEvent(event, listenerID string) { // Get eventCell evsw.mtx.Lock() eventCell := evsw.eventCells[event] diff --git a/libs/events/events_test.go b/libs/events/events_test.go index 4f7ff382c..3fe64cb52 100644 --- a/libs/events/events_test.go +++ b/libs/events/events_test.go @@ -5,10 +5,9 @@ import ( "testing" "time" + "github.com/consideritdone/landslidecore/libs/rand" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/libs/rand" ) // TestAddListenerForEventFireOnce sets up an EventSwitch, subscribes a single @@ -476,7 +475,8 @@ func sumReceivedNumbers(numbers, doneSum chan uint64) { // sent on `doneChan` for assertion that all events have been sent, and enabling // the test to assert all events have also been received. func fireEvents(evsw Fireable, event string, doneChan chan uint64, - offset uint64) { + offset uint64, +) { var sentSum uint64 for i := offset; i <= offset+uint64(999); i++ { sentSum += i diff --git a/libs/flowrate/io_test.go b/libs/flowrate/io_test.go index 4d7de417e..76bfa0cd4 100644 --- a/libs/flowrate/io_test.go +++ b/libs/flowrate/io_test.go @@ -155,14 +155,16 @@ func TestWriter(t *testing.T) { } } -const maxDeviationForDuration = 50 * time.Millisecond -const maxDeviationForRate int64 = 50 +const ( + maxDeviationForDuration = 50 * time.Millisecond + maxDeviationForRate int64 = 50 +) // statusesAreEqual returns true if s1 is equal to s2. Equality here means // general equality of fields except for the duration and rates, which can // drift due to unpredictable delays (e.g. thread wakes up 25ms after // `time.Sleep` has ended). -func statusesAreEqual(s1 *Status, s2 *Status) bool { +func statusesAreEqual(s1, s2 *Status) bool { if s1.Active == s2.Active && s1.Start == s2.Start && durationsAreEqual(s1.Duration, s2.Duration, maxDeviationForDuration) && @@ -181,11 +183,11 @@ func statusesAreEqual(s1 *Status, s2 *Status) bool { return false } -func durationsAreEqual(d1 time.Duration, d2 time.Duration, maxDeviation time.Duration) bool { +func durationsAreEqual(d1, d2, maxDeviation time.Duration) bool { return d2-d1 <= maxDeviation } -func ratesAreEqual(r1 int64, r2 int64, maxDeviation int64) bool { +func ratesAreEqual(r1, r2, maxDeviation int64) bool { sub := r1 - r2 if sub < 0 { sub = -sub diff --git a/libs/json/decoder_test.go b/libs/json/decoder_test.go index 0692207b8..c1c2f5b6c 100644 --- a/libs/json/decoder_test.go +++ b/libs/json/decoder_test.go @@ -5,10 +5,9 @@ import ( "testing" "time" + "github.com/consideritdone/landslidecore/libs/json" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/libs/json" ) func TestUnmarshal(t *testing.T) { 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/json/encoder_test.go b/libs/json/encoder_test.go index 1e0887e0a..4033afab5 100644 --- a/libs/json/encoder_test.go +++ b/libs/json/encoder_test.go @@ -4,10 +4,9 @@ import ( "testing" "time" + "github.com/consideritdone/landslidecore/libs/json" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/libs/json" ) func TestMarshal(t *testing.T) { diff --git a/libs/json/helpers_test.go b/libs/json/helpers_test.go index f9d6f8473..3905814d8 100644 --- a/libs/json/helpers_test.go +++ b/libs/json/helpers_test.go @@ -33,8 +33,10 @@ type Boat struct { func (b Boat) Drive() error { return nil } // These are public and private encryption keys. -type PublicKey [8]byte -type PrivateKey [8]byte +type ( + PublicKey [8]byte + PrivateKey [8]byte +) // Custom has custom marshalers and unmarshalers, taking pointer receivers. type CustomPtr struct { diff --git a/libs/json/structs.go b/libs/json/structs.go index c07c59c5e..4fa12fa36 100644 --- a/libs/json/structs.go +++ b/libs/json/structs.go @@ -9,10 +9,8 @@ import ( tmsync "github.com/consideritdone/landslidecore/libs/sync" ) -var ( - // cache caches struct info. - cache = newStructInfoCache() -) +// cache caches struct info. +var cache = newStructInfoCache() // structCache is a cache of struct info. type structInfoCache struct { diff --git a/libs/json/types.go b/libs/json/types.go index 4881c2494..b4da1256b 100644 --- a/libs/json/types.go +++ b/libs/json/types.go @@ -8,10 +8,8 @@ import ( tmsync "github.com/consideritdone/landslidecore/libs/sync" ) -var ( - // typeRegistry contains globally registered types for JSON encoding/decoding. - typeRegistry = newTypes() -) +// typeRegistry contains globally registered types for JSON encoding/decoding. +var typeRegistry = newTypes() // RegisterType registers a type for Amino-compatible interface encoding in the global type // registry. These types will be encoded with a type wrapper `{"type":"","value":}` diff --git a/libs/log/filter.go b/libs/log/filter.go index e39a85dcb..97214ec38 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 @@ -175,21 +176,21 @@ func allowed(allowed level) Option { } // AllowDebugWith allows error, info and debug level log events to pass for a specific key value pair. -func AllowDebugWith(key interface{}, value interface{}) Option { +func AllowDebugWith(key, value interface{}) Option { return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = levelError | levelInfo | levelDebug } } // AllowInfoWith allows error and info level log events to pass for a specific key value pair. -func AllowInfoWith(key interface{}, value interface{}) Option { +func AllowInfoWith(key, value interface{}) Option { return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = levelError | levelInfo } } // AllowErrorWith allows only error level log events to pass for a specific key value pair. -func AllowErrorWith(key interface{}, value interface{}) Option { +func AllowErrorWith(key, value interface{}) Option { return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = levelError } } // AllowNoneWith allows no leveled log events to pass for a specific key value pair. -func AllowNoneWith(key interface{}, value interface{}) Option { +func AllowNoneWith(key, value interface{}) Option { return func(l *filter) { l.allowedKeyvals[keyval{key, value}] = 0 } } 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/testing_logger.go b/libs/log/testing_logger.go index 7c6f661a7..a481aa030 100644 --- a/libs/log/testing_logger.go +++ b/libs/log/testing_logger.go @@ -8,10 +8,8 @@ import ( "github.com/go-kit/log/term" ) -var ( - // reuse the same logger across all tests - _testingLogger Logger -) +// reuse the same logger across all tests +var _testingLogger Logger // TestingLogger returns a TMLogger which writes to STDOUT if testing being run // with the verbose (-v) flag, NopLogger otherwise. diff --git a/libs/log/tmfmt_logger_test.go b/libs/log/tmfmt_logger_test.go index b36334377..121e98ac8 100644 --- a/libs/log/tmfmt_logger_test.go +++ b/libs/log/tmfmt_logger_test.go @@ -8,10 +8,9 @@ import ( "regexp" "testing" + "github.com/consideritdone/landslidecore/libs/log" kitlog "github.com/go-kit/log" "github.com/stretchr/testify/assert" - - "github.com/consideritdone/landslidecore/libs/log" ) func TestTMFmtLogger(t *testing.T) { diff --git a/libs/log/tracing_logger_test.go b/libs/log/tracing_logger_test.go index e225acd6b..301efd502 100644 --- a/libs/log/tracing_logger_test.go +++ b/libs/log/tracing_logger_test.go @@ -7,9 +7,8 @@ import ( "strings" "testing" - "github.com/pkg/errors" - "github.com/consideritdone/landslidecore/libs/log" + "github.com/pkg/errors" ) func TestTracingLogger(t *testing.T) { diff --git a/libs/math/fraction_test.go b/libs/math/fraction_test.go index 73ca0f6c8..729e8454f 100644 --- a/libs/math/fraction_test.go +++ b/libs/math/fraction_test.go @@ -7,7 +7,6 @@ import ( ) func TestParseFraction(t *testing.T) { - testCases := []struct { f string exp Fraction @@ -82,5 +81,4 @@ func TestParseFraction(t *testing.T) { } assert.Equal(t, tc.exp, output, idx) } - } diff --git a/libs/math/safemath.go b/libs/math/safemath.go index ff7f0908f..470ba9250 100644 --- a/libs/math/safemath.go +++ b/libs/math/safemath.go @@ -5,9 +5,11 @@ import ( "math" ) -var ErrOverflowInt32 = errors.New("int32 overflow") -var ErrOverflowUint8 = errors.New("uint8 overflow") -var ErrOverflowInt8 = errors.New("int8 overflow") +var ( + ErrOverflowInt32 = errors.New("int32 overflow") + ErrOverflowUint8 = errors.New("uint8 overflow") + ErrOverflowInt8 = errors.New("int8 overflow") +) // SafeAddInt32 adds two int32 integers // If there is an overflow this will panic diff --git a/libs/net/net_test.go b/libs/net/net_test.go index 38cd58f6a..975e4f6d0 100644 --- a/libs/net/net_test.go +++ b/libs/net/net_test.go @@ -7,7 +7,6 @@ import ( ) func TestProtocolAndAddress(t *testing.T) { - cases := []struct { fullAddr string proto string diff --git a/libs/os/os_test.go b/libs/os/os_test.go index 09bf6738a..56688298a 100644 --- a/libs/os/os_test.go +++ b/libs/os/os_test.go @@ -45,30 +45,30 @@ func TestEnsureDir(t *testing.T) { defer os.RemoveAll(tmp) // Should be possible to create a new directory. - err = EnsureDir(filepath.Join(tmp, "dir"), 0755) + err = EnsureDir(filepath.Join(tmp, "dir"), 0o755) require.NoError(t, err) require.DirExists(t, filepath.Join(tmp, "dir")) // Should succeed on existing directory. - err = EnsureDir(filepath.Join(tmp, "dir"), 0755) + err = EnsureDir(filepath.Join(tmp, "dir"), 0o755) require.NoError(t, err) // Should fail on file. - err = ioutil.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0644) + err = ioutil.WriteFile(filepath.Join(tmp, "file"), []byte{}, 0o644) require.NoError(t, err) - err = EnsureDir(filepath.Join(tmp, "file"), 0755) + err = EnsureDir(filepath.Join(tmp, "file"), 0o755) require.Error(t, err) // Should allow symlink to dir. err = os.Symlink(filepath.Join(tmp, "dir"), filepath.Join(tmp, "linkdir")) require.NoError(t, err) - err = EnsureDir(filepath.Join(tmp, "linkdir"), 0755) + err = EnsureDir(filepath.Join(tmp, "linkdir"), 0o755) require.NoError(t, err) // Should error on symlink to file. err = os.Symlink(filepath.Join(tmp, "file"), filepath.Join(tmp, "linkfile")) require.NoError(t, err) - err = EnsureDir(filepath.Join(tmp, "linkfile"), 0755) + err = EnsureDir(filepath.Join(tmp, "linkfile"), 0o755) require.Error(t, err) } @@ -84,7 +84,7 @@ func TestTrickedTruncation(t *testing.T) { originalWALPath := filepath.Join(tmpDir, "wal") originalWALContent := []byte("I AM BECOME DEATH, DESTROYER OF ALL WORLDS!") - if err := ioutil.WriteFile(originalWALPath, originalWALContent, 0755); err != nil { + if err := ioutil.WriteFile(originalWALPath, originalWALContent, 0o755); err != nil { t.Fatal(err) } diff --git a/libs/protoio/io_test.go b/libs/protoio/io_test.go index ea63c6580..ce875ee05 100644 --- a/libs/protoio/io_test.go +++ b/libs/protoio/io_test.go @@ -37,11 +37,10 @@ import ( "testing" "time" + "github.com/consideritdone/landslidecore/libs/protoio" "github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/test" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/libs/protoio" ) func iotest(writer protoio.WriteCloser, reader protoio.ReadCloser) error { diff --git a/libs/pubsub/example_test.go b/libs/pubsub/example_test.go index daaa8ed35..7d68ee798 100644 --- a/libs/pubsub/example_test.go +++ b/libs/pubsub/example_test.go @@ -4,12 +4,10 @@ import ( "context" "testing" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" - "github.com/consideritdone/landslidecore/libs/pubsub" "github.com/consideritdone/landslidecore/libs/pubsub/query" + "github.com/stretchr/testify/require" ) func TestExample(t *testing.T) { diff --git a/libs/pubsub/pubsub.go b/libs/pubsub/pubsub.go index fb027b784..c0a93bb62 100644 --- a/libs/pubsub/pubsub.go +++ b/libs/pubsub/pubsub.go @@ -150,7 +150,8 @@ func (s *Server) Subscribe( ctx context.Context, clientID string, query Query, - outCapacity ...int) (*Subscription, error) { + outCapacity ...int, +) (*Subscription, error) { outCap := 1 if len(outCapacity) > 0 { if outCapacity[0] <= 0 { @@ -359,7 +360,7 @@ func (state *state) add(clientID string, q Query, subscription *Subscription) { state.queries[qStr].refCount++ } -func (state *state) remove(clientID string, qStr string, reason error) { +func (state *state) remove(clientID, qStr string, reason error) { clientSubscriptions, ok := state.subscriptions[qStr] if !ok { return diff --git a/libs/pubsub/pubsub_test.go b/libs/pubsub/pubsub_test.go index a8d998da7..4d4418c30 100644 --- a/libs/pubsub/pubsub_test.go +++ b/libs/pubsub/pubsub_test.go @@ -7,13 +7,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" - "github.com/consideritdone/landslidecore/libs/pubsub" "github.com/consideritdone/landslidecore/libs/pubsub/query" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -482,8 +480,10 @@ func benchmarkNClientsOneQuery(n int, b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - err = s.PublishWithEvents(ctx, "Gamora", map[string][]string{"abci.Account.Owner": {"Ivan"}, - "abci.Invoices.Number": {"1"}}) + err = s.PublishWithEvents(ctx, "Gamora", map[string][]string{ + "abci.Account.Owner": {"Ivan"}, + "abci.Invoices.Number": {"1"}, + }) require.NoError(b, err) } } diff --git a/libs/pubsub/query/empty.go b/libs/pubsub/query/empty.go index b86b8d4e8..5696ccec1 100644 --- a/libs/pubsub/query/empty.go +++ b/libs/pubsub/query/empty.go @@ -1,8 +1,7 @@ package query // Empty query matches any set of events. -type Empty struct { -} +type Empty struct{} // Matches always returns true. func (Empty) Matches(tags map[string][]string) (bool, error) { diff --git a/libs/pubsub/query/empty_test.go b/libs/pubsub/query/empty_test.go index d7cdedd9d..48ac8c8df 100644 --- a/libs/pubsub/query/empty_test.go +++ b/libs/pubsub/query/empty_test.go @@ -3,9 +3,8 @@ package query_test import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/libs/pubsub/query" + "github.com/stretchr/testify/assert" ) func TestEmptyQueryMatchesAnything(t *testing.T) { diff --git a/libs/pubsub/query/parser_test.go b/libs/pubsub/query/parser_test.go index ebd59f04c..e942337ae 100644 --- a/libs/pubsub/query/parser_test.go +++ b/libs/pubsub/query/parser_test.go @@ -3,9 +3,8 @@ package query_test import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/libs/pubsub/query" + "github.com/stretchr/testify/assert" ) // TODO: fuzzy testing? diff --git a/libs/pubsub/query/query.go b/libs/pubsub/query/query.go index cf6903ccf..94c3c6ec4 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 @@ -17,9 +17,7 @@ import ( "time" ) -var ( - numRegex = regexp.MustCompile(`([0-9\.]+)`) -) +var numRegex = regexp.MustCompile(`([0-9\.]+)`) // Query holds the query string and the query parser. type Query struct { diff --git a/libs/pubsub/query/query_test.go b/libs/pubsub/query/query_test.go index 62f88a608..53818e510 100644 --- a/libs/pubsub/query/query_test.go +++ b/libs/pubsub/query/query_test.go @@ -5,10 +5,9 @@ import ( "testing" "time" + "github.com/consideritdone/landslidecore/libs/pubsub/query" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/libs/pubsub/query" ) func TestMatches(t *testing.T) { @@ -112,40 +111,50 @@ func TestMatches(t *testing.T) { false, false, }, - {"slash EXISTS", + { + "slash EXISTS", map[string][]string{"slash.reason": {"missing_signature"}, "slash.power": {"6000"}}, false, true, false, }, - {"sl EXISTS", + { + "sl EXISTS", map[string][]string{"slash.reason": {"missing_signature"}, "slash.power": {"6000"}}, false, true, false, }, - {"slash EXISTS", - map[string][]string{"transfer.recipient": {"cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz"}, - "transfer.sender": {"cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5"}}, + { + "slash EXISTS", + map[string][]string{ + "transfer.recipient": {"cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz"}, + "transfer.sender": {"cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5"}, + }, false, false, false, }, - {"slash.reason EXISTS AND slash.power > 1000", + { + "slash.reason EXISTS AND slash.power > 1000", map[string][]string{"slash.reason": {"missing_signature"}, "slash.power": {"6000"}}, false, true, false, }, - {"slash.reason EXISTS AND slash.power > 1000", + { + "slash.reason EXISTS AND slash.power > 1000", map[string][]string{"slash.reason": {"missing_signature"}, "slash.power": {"500"}}, false, false, false, }, - {"slash.reason EXISTS", - map[string][]string{"transfer.recipient": {"cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz"}, - "transfer.sender": {"cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5"}}, + { + "slash.reason EXISTS", + map[string][]string{ + "transfer.recipient": {"cosmos1gu6y2a0ffteesyeyeesk23082c6998xyzmt9mz"}, + "transfer.sender": {"cosmos1crje20aj4gxdtyct7z3knxqry2jqt2fuaey6u5"}, + }, false, false, false, diff --git a/libs/rand/random_test.go b/libs/rand/random_test.go index e669f250f..1b8504aa3 100644 --- a/libs/rand/random_test.go +++ b/libs/rand/random_test.go @@ -53,7 +53,6 @@ func TestDeterminism(t *testing.T) { } func testThemAll() string { - // Such determinism. grand.reset(1) @@ -92,18 +91,23 @@ func TestRngConcurrencySafety(t *testing.T) { func BenchmarkRandBytes10B(b *testing.B) { benchmarkRandBytes(b, 10) } + func BenchmarkRandBytes100B(b *testing.B) { benchmarkRandBytes(b, 100) } + func BenchmarkRandBytes1KiB(b *testing.B) { benchmarkRandBytes(b, 1024) } + func BenchmarkRandBytes10KiB(b *testing.B) { benchmarkRandBytes(b, 10*1024) } + func BenchmarkRandBytes100KiB(b *testing.B) { benchmarkRandBytes(b, 100*1024) } + func BenchmarkRandBytes1MiB(b *testing.B) { benchmarkRandBytes(b, 1024*1024) } diff --git a/libs/strings/string_test.go b/libs/strings/string_test.go index 1ec7b0d56..56c4d789d 100644 --- a/libs/strings/string_test.go +++ b/libs/strings/string_test.go @@ -3,9 +3,8 @@ package strings import ( "testing" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStringInSlice(t *testing.T) { diff --git a/libs/tempfile/tempfile_test.go b/libs/tempfile/tempfile_test.go index fd395ff70..a2184a56e 100644 --- a/libs/tempfile/tempfile_test.go +++ b/libs/tempfile/tempfile_test.go @@ -9,16 +9,15 @@ import ( "os" testing "testing" - "github.com/stretchr/testify/require" - tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/require" ) func TestWriteFileAtomic(t *testing.T) { var ( data = []byte(tmrand.Str(tmrand.Intn(2048))) old = tmrand.Bytes(tmrand.Intn(2048)) - perm os.FileMode = 0600 + perm os.FileMode = 0o600 ) f, err := ioutil.TempFile("/tmp", "write-atomic-test-") @@ -27,7 +26,7 @@ func TestWriteFileAtomic(t *testing.T) { } defer os.Remove(f.Name()) - if err = ioutil.WriteFile(f.Name(), old, 0600); err != nil { + if err = ioutil.WriteFile(f.Name(), old, 0o600); err != nil { t.Fatal(err) } @@ -69,7 +68,7 @@ func TestWriteFileAtomicDuplicateFile(t *testing.T) { firstFileRand := randWriteFileSuffix() atomicWriteFileRand = defaultSeed fname := "/tmp/" + atomicWriteFilePrefix + firstFileRand - f, err := os.OpenFile(fname, atomicWriteFileFlag, 0777) + f, err := os.OpenFile(fname, atomicWriteFileFlag, 0o777) defer os.Remove(fname) // Defer here, in case there is a panic in WriteFileAtomic. defer os.Remove(fileToWrite) @@ -77,7 +76,7 @@ func TestWriteFileAtomicDuplicateFile(t *testing.T) { require.NoError(t, err) _, err = f.WriteString(testString) require.NoError(t, err) - err = WriteFileAtomic(fileToWrite, []byte(expectedString), 0777) + err = WriteFileAtomic(fileToWrite, []byte(expectedString), 0o777) require.NoError(t, err) // Check that the first atomic file was untouched firstAtomicFileBytes, err := ioutil.ReadFile(fname) @@ -113,7 +112,7 @@ func TestWriteFileAtomicManyDuplicates(t *testing.T) { for i := 0; i < atomicWriteFileMaxNumConflicts+2; i++ { fileRand := randWriteFileSuffix() fname := "/tmp/" + atomicWriteFilePrefix + fileRand - f, err := os.OpenFile(fname, atomicWriteFileFlag, 0777) + f, err := os.OpenFile(fname, atomicWriteFileFlag, 0o777) require.Nil(t, err) _, err = f.WriteString(fmt.Sprintf(testString, i)) require.NoError(t, err) @@ -124,7 +123,7 @@ func TestWriteFileAtomicManyDuplicates(t *testing.T) { // Defer here, in case there is a panic in WriteFileAtomic. defer os.Remove(fileToWrite) - err := WriteFileAtomic(fileToWrite, []byte(expectedString), 0777) + err := WriteFileAtomic(fileToWrite, []byte(expectedString), 0o777) require.NoError(t, err) // Check that all intermittent atomic file were untouched atomicWriteFileRand = defaultSeed diff --git a/libs/timer/throttle_timer.go b/libs/timer/throttle_timer.go index cfe189948..a3d520414 100644 --- a/libs/timer/throttle_timer.go +++ b/libs/timer/throttle_timer.go @@ -24,9 +24,9 @@ type ThrottleTimer struct { } func NewThrottleTimer(name string, dur time.Duration) *ThrottleTimer { - var ch = make(chan struct{}) - var quit = make(chan struct{}) - var t = &ThrottleTimer{Name: name, Ch: ch, dur: dur, quit: quit} + ch := make(chan struct{}) + quit := make(chan struct{}) + t := &ThrottleTimer{Name: name, Ch: ch, dur: dur, quit: quit} t.mtx.Lock() t.timer = time.AfterFunc(dur, t.fireRoutine) t.mtx.Unlock() diff --git a/libs/timer/throttle_timer_test.go b/libs/timer/throttle_timer_test.go index de237cf34..5de7751f1 100644 --- a/libs/timer/throttle_timer_test.go +++ b/libs/timer/throttle_timer_test.go @@ -4,11 +4,8 @@ import ( "testing" "time" - // make govet noshadow happy... - - asrt "github.com/stretchr/testify/assert" - tmsync "github.com/consideritdone/landslidecore/libs/sync" + asrt "github.com/stretchr/testify/assert" ) type thCounter struct { diff --git a/light/client.go b/light/client.go index 891cd568a..a76d7625f 100644 --- a/light/client.go +++ b/light/client.go @@ -178,8 +178,8 @@ func NewClient( primary provider.Provider, witnesses []provider.Provider, trustedStore store.Store, - options ...Option) (*Client, error) { - + options ...Option, +) (*Client, error) { if err := trustOptions.ValidateBasic(); err != nil { return nil, fmt.Errorf("invalid TrustOptions: %w", err) } @@ -215,8 +215,8 @@ func NewClientFromTrustedStore( primary provider.Provider, witnesses []provider.Provider, trustedStore store.Store, - options ...Option) (*Client, error) { - + options ...Option, +) (*Client, error) { c := &Client{ chainID: chainID, trustingPeriod: trustingPeriod, @@ -559,7 +559,7 @@ func (c *Client) verifyLightBlock(ctx context.Context, newLightBlock *types.Ligh c.logger.Info("VerifyHeader", "height", newLightBlock.Height, "hash", newLightBlock.Hash()) var ( - verifyFunc func(ctx context.Context, trusted *types.LightBlock, new *types.LightBlock, now time.Time) error + verifyFunc func(ctx context.Context, trusted, new *types.LightBlock, now time.Time) error err error ) @@ -614,8 +614,8 @@ func (c *Client) verifySequential( ctx context.Context, trustedBlock *types.LightBlock, newLightBlock *types.LightBlock, - now time.Time) error { - + now time.Time, +) error { var ( verifiedBlock = trustedBlock interimBlock *types.LightBlock @@ -708,8 +708,8 @@ func (c *Client) verifySkipping( source provider.Provider, trustedBlock *types.LightBlock, newLightBlock *types.LightBlock, - now time.Time) ([]*types.LightBlock, error) { - + now time.Time, +) ([]*types.LightBlock, error) { var ( blockCache = []*types.LightBlock{newLightBlock} depth = 0 @@ -778,8 +778,8 @@ func (c *Client) verifySkippingAgainstPrimary( ctx context.Context, trustedBlock *types.LightBlock, newLightBlock *types.LightBlock, - now time.Time) error { - + now time.Time, +) error { trace, err := c.verifySkipping(ctx, c.primary, trustedBlock, newLightBlock, now) switch errors.Unwrap(err).(type) { @@ -933,8 +933,8 @@ func (c *Client) updateTrustedLightBlock(l *types.LightBlock) error { func (c *Client) backwards( ctx context.Context, trustedHeader *types.Header, - newHeader *types.Header) error { - + newHeader *types.Header, +) error { var ( verifiedHeader = trustedHeader interimHeader *types.Header diff --git a/light/client_benchmark_test.go b/light/client_benchmark_test.go index be42389a3..1e1167d34 100644 --- a/light/client_benchmark_test.go +++ b/light/client_benchmark_test.go @@ -5,13 +5,12 @@ import ( "testing" "time" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/light" "github.com/consideritdone/landslidecore/light/provider" mockp "github.com/consideritdone/landslidecore/light/provider/mock" dbs "github.com/consideritdone/landslidecore/light/store/db" + dbm "github.com/tendermint/tm-db" ) // NOTE: block is produced every minute. Make sure the verification time diff --git a/light/client_test.go b/light/client_test.go index fc45b5d30..30f67de17 100644 --- a/light/client_test.go +++ b/light/client_test.go @@ -7,17 +7,15 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/light" "github.com/consideritdone/landslidecore/light/provider" mockp "github.com/consideritdone/landslidecore/light/provider/mock" dbs "github.com/consideritdone/landslidecore/light/store/db" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) const ( @@ -110,7 +108,6 @@ func TestValidateTrustOptions(t *testing.T) { assert.NoError(t, err) } } - } func TestMock(t *testing.T) { @@ -376,7 +373,6 @@ func TestClient_SkippingVerification(t *testing.T) { } }) } - } // start from a large light block to make sure that the pivot height doesn't select a height outside @@ -1098,7 +1094,6 @@ func TestClientEnsureValidHeadersAndValSets(t *testing.T) { assert.NoError(t, err) } } - } func TestClientHandlesContexts(t *testing.T) { @@ -1156,5 +1151,4 @@ func TestClientHandlesContexts(t *testing.T) { require.Error(t, ctxCancel.Err()) require.Error(t, err) require.True(t, errors.Is(err, context.Canceled)) - } diff --git a/light/detector.go b/light/detector.go index 1d145ddbd..372289220 100644 --- a/light/detector.go +++ b/light/detector.go @@ -114,8 +114,8 @@ func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.Lig // // 3: nil -> the hashes of the two headers match func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader, - witness provider.Provider, witnessIndex int) { - + witness provider.Provider, witnessIndex int, +) { lightBlock, err := witness.LightBlock(ctx, h.Height) switch err { // no error means we move on to checking the hash of the two headers @@ -293,7 +293,6 @@ func (c *Client) examineConflictingHeaderAgainstTrace( targetBlock *types.LightBlock, source provider.Provider, now time.Time, ) ([]*types.LightBlock, *types.LightBlock, error) { - var ( previouslyVerifiedBlock, sourceBlock *types.LightBlock sourceTrace []*types.LightBlock @@ -370,7 +369,6 @@ func (c *Client) examineConflictingHeaderAgainstTrace( // prerequisites to this function were not met. Namely that either trace[len(trace)-1].Height < targetBlock.Height // or that trace[i].Hash() != targetBlock.Hash() return nil, nil, errNoDivergence - } // getTargetBlockOrLatest gets the latest height, if it is greater than the target height then it queries diff --git a/light/detector_test.go b/light/detector_test.go index dc0a23f09..79e0f2671 100644 --- a/light/detector_test.go +++ b/light/detector_test.go @@ -4,17 +4,15 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/light" "github.com/consideritdone/landslidecore/light/provider" mockp "github.com/consideritdone/landslidecore/light/provider/mock" dbs "github.com/consideritdone/landslidecore/light/store/db" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestLightClientAttackEvidence_Lunatic(t *testing.T) { @@ -302,7 +300,6 @@ func TestLightClientAttackEvidence_ForwardLunatic(t *testing.T) { _, err = c.Update(ctx, bTime.Add(time.Duration(forgedHeight)*time.Minute)) assert.NoError(t, err) - } // 1. Different nodes therefore a divergent header is produced. diff --git a/light/doc.go b/light/doc.go index 700bbeb6c..fc50df2fa 100644 --- a/light/doc.go +++ b/light/doc.go @@ -63,31 +63,31 @@ This package provides three major things: Example usage: - db, err := dbm.NewGoLevelDB("light-client-db", dbDir) - if err != nil { - // handle error - } - - c, err := NewHTTPClient( - chainID, - TrustOptions{ - Period: 504 * time.Hour, // 21 days - Height: 100, - Hash: header.Hash(), - }, - "http://localhost:26657", - []string{"http://witness1:26657"}, - dbs.New(db, ""), - ) - if err != nil { - // handle error - } - - h, err := c.TrustedHeader(100) - if err != nil { - // handle error - } - fmt.Println("header", h) + db, err := dbm.NewGoLevelDB("light-client-db", dbDir) + if err != nil { + // handle error + } + + c, err := NewHTTPClient( + chainID, + TrustOptions{ + Period: 504 * time.Hour, // 21 days + Height: 100, + Hash: header.Hash(), + }, + "http://localhost:26657", + []string{"http://witness1:26657"}, + dbs.New(db, ""), + ) + if err != nil { + // handle error + } + + h, err := c.TrustedHeader(100) + if err != nil { + // handle error + } + fmt.Println("header", h) Check out other examples in example_test.go diff --git a/light/example_test.go b/light/example_test.go index debff1d83..8fd180826 100644 --- a/light/example_test.go +++ b/light/example_test.go @@ -9,8 +9,6 @@ import ( "testing" "time" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/kvstore" "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/light" @@ -18,6 +16,7 @@ import ( httpp "github.com/consideritdone/landslidecore/light/provider/http" dbs "github.com/consideritdone/landslidecore/light/store/db" rpctest "github.com/consideritdone/landslidecore/rpc/test" + dbm "github.com/tendermint/tm-db" ) // Automatically getting new headers and verifying them. diff --git a/light/helpers_test.go b/light/helpers_test.go index 5237fb802..fb2ba49ec 100644 --- a/light/helpers_test.go +++ b/light/helpers_test.go @@ -94,8 +94,8 @@ func (pkz privKeys) signHeader(header *types.Header, valSet *types.ValidatorSet, } func makeVote(header *types.Header, valset *types.ValidatorSet, - key crypto.PrivKey, blockID types.BlockID) *types.Vote { - + key crypto.PrivKey, blockID types.BlockID, +) *types.Vote { addr := key.PubKey().Address() idx, _ := valset.GetByAddress(addr) vote := &types.Vote{ @@ -122,8 +122,8 @@ func makeVote(header *types.Header, valset *types.ValidatorSet, } func genHeader(chainID string, height int64, bTime time.Time, txs types.Txs, - valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte) *types.Header { - + valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte, +) *types.Header { return &types.Header{ Version: tmversion.Consensus{Block: version.BlockProtocol, App: 0}, ChainID: chainID, @@ -143,8 +143,8 @@ func genHeader(chainID string, height int64, bTime time.Time, txs types.Txs, // GenSignedHeader calls genHeader and signHeader and combines them into a SignedHeader. func (pkz privKeys) GenSignedHeader(chainID string, height int64, bTime time.Time, txs types.Txs, - valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte, first, last int) *types.SignedHeader { - + valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte, first, last int, +) *types.SignedHeader { header := genHeader(chainID, height, bTime, txs, valset, nextValset, appHash, consHash, resHash) return &types.SignedHeader{ Header: header, @@ -155,8 +155,8 @@ func (pkz privKeys) GenSignedHeader(chainID string, height int64, bTime time.Tim // GenSignedHeaderLastBlockID calls genHeader and signHeader and combines them into a SignedHeader. func (pkz privKeys) GenSignedHeaderLastBlockID(chainID string, height int64, bTime time.Time, txs types.Txs, valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte, first, last int, - lastBlockID types.BlockID) *types.SignedHeader { - + lastBlockID types.BlockID, +) *types.SignedHeader { header := genHeader(chainID, height, bTime, txs, valset, nextValset, appHash, consHash, resHash) header.LastBlockID = lastBlockID return &types.SignedHeader{ @@ -181,8 +181,8 @@ func genMockNodeWithKeys( bTime time.Time) ( map[int64]*types.SignedHeader, map[int64]*types.ValidatorSet, - map[int64]privKeys) { - + map[int64]privKeys, +) { var ( headers = make(map[int64]*types.SignedHeader, blockSize) valset = make(map[int64]*types.ValidatorSet, blockSize+1) @@ -235,7 +235,8 @@ func genMockNode( bTime time.Time) ( string, map[int64]*types.SignedHeader, - map[int64]*types.ValidatorSet) { + map[int64]*types.ValidatorSet, +) { headers, valset, _ := genMockNodeWithKeys(chainID, blockSize, valSize, valVariation, bTime) return chainID, headers, valset } diff --git a/light/provider/http/http_test.go b/light/provider/http/http_test.go index e84899ca0..643b8e100 100644 --- a/light/provider/http/http_test.go +++ b/light/provider/http/http_test.go @@ -7,9 +7,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/kvstore" "github.com/consideritdone/landslidecore/light/provider" lighthttp "github.com/consideritdone/landslidecore/light/provider/http" @@ -17,6 +14,8 @@ import ( rpchttp "github.com/consideritdone/landslidecore/rpc/client/http" rpctest "github.com/consideritdone/landslidecore/rpc/test" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewProvider(t *testing.T) { diff --git a/light/proxy/routes.go b/light/proxy/routes.go index af578c103..92eb90747 100644 --- a/light/proxy/routes.go +++ b/light/proxy/routes.go @@ -259,8 +259,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, diff --git a/light/rpc/client.go b/light/rpc/client.go index 9ee4184fb..0f45769d9 100644 --- a/light/rpc/client.go +++ b/light/rpc/client.go @@ -8,8 +8,6 @@ import ( "regexp" "time" - "github.com/gogo/protobuf/proto" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/crypto/merkle" tmbytes "github.com/consideritdone/landslidecore/libs/bytes" @@ -19,6 +17,7 @@ import ( ctypes "github.com/consideritdone/landslidecore/rpc/core/types" rpctypes "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" ) var errNegOrZeroHeight = errors.New("negative or zero height") @@ -131,8 +130,8 @@ func (c *Client) ABCIQuery(ctx context.Context, path string, data tmbytes.HexByt // ABCIQueryWithOptions returns an error if opts.Prove is false. func (c *Client) ABCIQueryWithOptions(ctx context.Context, path string, data tmbytes.HexBytes, - opts rpcclient.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { - + opts rpcclient.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { // always request the proof opts.Prove = true @@ -503,7 +502,6 @@ func (c *Client) Validators( height *int64, pagePtr, perPagePtr *int, ) (*ctypes.ResultValidators, error) { - // Update the light client if we're behind and retrieve the light block at the // requested height or at the latest height if no height is provided. l, err := c.updateLightClientIfNeededTo(ctx, height) @@ -525,7 +523,8 @@ func (c *Client) Validators( BlockHeight: l.Height, Validators: v, Count: len(v), - Total: totalCount}, nil + Total: totalCount, + }, nil } func (c *Client) BroadcastEvidence(ctx context.Context, ev types.Evidence) (*ctypes.ResultBroadcastEvidence, error) { @@ -533,7 +532,8 @@ func (c *Client) BroadcastEvidence(ctx context.Context, ev types.Evidence) (*cty } func (c *Client) Subscribe(ctx context.Context, subscriber, query string, - outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) { + outCapacity ...int, +) (out <-chan ctypes.ResultEvent, err error) { return c.next.Subscribe(ctx, subscriber, query, outCapacity...) } diff --git a/light/setup.go b/light/setup.go index 01c57ec6c..67780fcec 100644 --- a/light/setup.go +++ b/light/setup.go @@ -22,8 +22,8 @@ func NewHTTPClient( primaryAddress string, witnessesAddresses []string, trustedStore store.Store, - options ...Option) (*Client, error) { - + options ...Option, +) (*Client, error) { providers, err := providersFromAddresses(append(witnessesAddresses, primaryAddress), chainID) if err != nil { return nil, err @@ -51,8 +51,8 @@ func NewHTTPClientFromTrustedStore( primaryAddress string, witnessesAddresses []string, trustedStore store.Store, - options ...Option) (*Client, error) { - + options ...Option, +) (*Client, error) { providers, err := providersFromAddresses(append(witnessesAddresses, primaryAddress), chainID) if err != nil { return nil, err diff --git a/light/store/db/db.go b/light/store/db/db.go index 8810f2f8d..98a60a2ff 100644 --- a/light/store/db/db.go +++ b/light/store/db/db.go @@ -6,17 +6,14 @@ import ( "regexp" "strconv" - dbm "github.com/tendermint/tm-db" - tmsync "github.com/consideritdone/landslidecore/libs/sync" "github.com/consideritdone/landslidecore/light/store" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + dbm "github.com/tendermint/tm-db" ) -var ( - sizeKey = []byte("size") -) +var sizeKey = []byte("size") type dbs struct { db dbm.DB @@ -29,7 +26,6 @@ type dbs struct { // New returns a Store that wraps any DB (with an optional prefix in case you // want to use one DB with many light clients). func New(db dbm.DB, prefix string) store.Store { - size := uint16(0) bz, err := db.Get(sizeKey) if err == nil && len(bz) > 0 { @@ -295,7 +291,7 @@ func (s *dbs) lbKey(height int64) []byte { var keyPattern = regexp.MustCompile(`^(lb)/([^/]*)/([0-9]+)$`) -func parseKey(key []byte) (part string, prefix string, height int64, ok bool) { +func parseKey(key []byte) (part, prefix string, height int64, ok bool) { submatch := keyPattern.FindSubmatch(key) if submatch == nil { return "", "", 0, false diff --git a/light/store/db/db_test.go b/light/store/db/db_test.go index d1da41de0..0391fa724 100644 --- a/light/store/db/db_test.go +++ b/light/store/db/db_test.go @@ -5,17 +5,15 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" tmrand "github.com/consideritdone/landslidecore/libs/rand" tmversion "github.com/consideritdone/landslidecore/proto/tendermint/version" "github.com/consideritdone/landslidecore/types" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestLast_FirstLightBlockHeight(t *testing.T) { @@ -70,7 +68,6 @@ func Test_SaveLightBlock(t *testing.T) { h, err = dbStore.LightBlock(1) require.Error(t, err) assert.Nil(t, h) - } func Test_LightBlockBefore(t *testing.T) { diff --git a/light/store/errors.go b/light/store/errors.go index 099b5964d..913b5fcc2 100644 --- a/light/store/errors.go +++ b/light/store/errors.go @@ -2,8 +2,6 @@ package store import "errors" -var ( - // ErrLightBlockNotFound is returned when a store does not have the - // requested header. - ErrLightBlockNotFound = errors.New("light block not found") -) +// ErrLightBlockNotFound is returned when a store does not have the +// requested header. +var ErrLightBlockNotFound = errors.New("light block not found") diff --git a/light/verifier.go b/light/verifier.go index d086ee755..9cac8673e 100644 --- a/light/verifier.go +++ b/light/verifier.go @@ -10,11 +10,9 @@ import ( "github.com/consideritdone/landslidecore/types" ) -var ( - // DefaultTrustLevel - new header can be trusted if at least one correct - // validator signed it. - DefaultTrustLevel = tmmath.Fraction{Numerator: 1, Denominator: 3} -) +// DefaultTrustLevel - new header can be trusted if at least one correct +// validator signed it. +var DefaultTrustLevel = tmmath.Fraction{Numerator: 1, Denominator: 3} // VerifyNonAdjacent verifies non-adjacent untrustedHeader against // trustedHeader. It ensures that: @@ -37,8 +35,8 @@ func VerifyNonAdjacent( trustingPeriod time.Duration, now time.Time, maxClockDrift time.Duration, - trustLevel tmmath.Fraction) error { - + trustLevel tmmath.Fraction, +) error { if untrustedHeader.Height == trustedHeader.Height+1 { return errors.New("headers must be non adjacent in height") } @@ -96,8 +94,8 @@ func VerifyAdjacent( untrustedVals *types.ValidatorSet, // height=X+1 trustingPeriod time.Duration, now time.Time, - maxClockDrift time.Duration) error { - + maxClockDrift time.Duration, +) error { if untrustedHeader.Height != trustedHeader.Height+1 { return errors.New("headers must be adjacent in height") } @@ -140,8 +138,8 @@ func Verify( trustingPeriod time.Duration, now time.Time, maxClockDrift time.Duration, - trustLevel tmmath.Fraction) error { - + trustLevel tmmath.Fraction, +) error { if untrustedHeader.Height != trustedHeader.Height+1 { return VerifyNonAdjacent(trustedHeader, trustedVals, untrustedHeader, untrustedVals, trustingPeriod, now, maxClockDrift, trustLevel) @@ -155,8 +153,8 @@ func verifyNewHeaderAndVals( untrustedVals *types.ValidatorSet, trustedHeader *types.SignedHeader, now time.Time, - maxClockDrift time.Duration) error { - + maxClockDrift time.Duration, +) error { if err := untrustedHeader.ValidateBasic(trustedHeader.ChainID); err != nil { return fmt.Errorf("untrustedHeader.ValidateBasic failed: %w", err) } @@ -231,14 +229,16 @@ func VerifyBackwards(untrustedHeader, trustedHeader *types.Header) error { return ErrInvalidHeader{ fmt.Errorf("expected older header time %v to be before new header time %v", untrustedHeader.Time, - trustedHeader.Time)} + trustedHeader.Time), + } } if !bytes.Equal(untrustedHeader.Hash(), trustedHeader.LastBlockID.Hash) { return ErrInvalidHeader{ fmt.Errorf("older header hash %X does not match trusted header's last block %X", untrustedHeader.Hash(), - trustedHeader.LastBlockID.Hash)} + trustedHeader.LastBlockID.Hash), + } } return nil diff --git a/light/verifier_test.go b/light/verifier_test.go index e9f12ed4f..3b3d963a2 100644 --- a/light/verifier_test.go +++ b/light/verifier_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - tmmath "github.com/consideritdone/landslidecore/libs/math" "github.com/consideritdone/landslidecore/light" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" ) const ( @@ -166,7 +165,6 @@ func TestVerifyAdjacentHeaders(t *testing.T) { } }) } - } func TestVerifyNonAdjacentHeaders(t *testing.T) { diff --git a/mempool/clist_mempool_test.go b/mempool/clist_mempool_test.go index 8107b650f..1be594ed1 100644 --- a/mempool/clist_mempool_test.go +++ b/mempool/clist_mempool_test.go @@ -44,7 +44,7 @@ func newMempoolWithAppAndConfig(cc proxy.ClientCreator, config *cfg.Config) (*CL if err != nil { panic(err) } - mempool := NewCListMempool(config.Mempool, appConnMem, 0) + mempool := NewCListMempool(config.Mempool, appConnMem, 0, nil) mempool.SetLogger(log.TestingLogger()) return mempool, func() { os.RemoveAll(config.RootDir) } } diff --git a/node/node_test.go b/node/node_test.go index 69f1358ff..34af6b615 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -247,6 +247,7 @@ func TestCreateProposalBlock(t *testing.T) { config.Mempool, proxyApp.Mempool(), state.LastBlockHeight, + nil, mempl.WithMetrics(memplMetrics), mempl.WithPreCheck(sm.TxPreCheck(state)), mempl.WithPostCheck(sm.TxPostCheck(state)), @@ -339,6 +340,7 @@ func TestMaxProposalBlockSize(t *testing.T) { config.Mempool, proxyApp.Mempool(), state.LastBlockHeight, + nil, mempl.WithMetrics(memplMetrics), mempl.WithPreCheck(sm.TxPreCheck(state)), mempl.WithPostCheck(sm.TxPostCheck(state)), diff --git a/p2p/conn/connection.go b/p2p/conn/connection.go index f8cd4c509..4c500ed9e 100644 --- a/p2p/conn/connection.go +++ b/p2p/conn/connection.go @@ -12,8 +12,6 @@ import ( "sync/atomic" "time" - "github.com/gogo/protobuf/proto" - flow "github.com/consideritdone/landslidecore/libs/flowrate" "github.com/consideritdone/landslidecore/libs/log" tmmath "github.com/consideritdone/landslidecore/libs/math" @@ -22,6 +20,7 @@ import ( tmsync "github.com/consideritdone/landslidecore/libs/sync" "github.com/consideritdone/landslidecore/libs/timer" tmp2p "github.com/consideritdone/landslidecore/proto/tendermint/p2p" + "github.com/gogo/protobuf/proto" ) const ( @@ -47,8 +46,10 @@ const ( defaultPongTimeout = 45 * time.Second ) -type receiveCbFunc func(chID byte, msgBytes []byte) -type errorCbFunc func(interface{}) +type ( + receiveCbFunc func(chID byte, msgBytes []byte) + errorCbFunc func(interface{}) +) /* Each peer has one `MConnection` (multiplex connection) instance. @@ -190,8 +191,8 @@ func NewMConnectionWithConfig( } // Create channels - var channelsIdx = map[byte]*Channel{} - var channels = []*Channel{} + channelsIdx := map[byte]*Channel{} + channels := []*Channel{} for _, desc := range chDescs { channel := newChannel(mconn, *desc) @@ -855,7 +856,7 @@ func (ch *Channel) writePacketMsgTo(w io.Writer) (n int, err error) { // Not goroutine-safe func (ch *Channel) recvPacketMsg(packet tmp2p.PacketMsg) ([]byte, error) { ch.Logger.Debug("Read PacketMsg", "conn", ch.conn, "packet", packet) - var recvCap, recvReceived = ch.desc.RecvMessageCapacity, len(ch.recving) + len(packet.Data) + recvCap, recvReceived := ch.desc.RecvMessageCapacity, len(ch.recving)+len(packet.Data) if recvCap < recvReceived { return nil, fmt.Errorf("received message exceeds available capacity: %v < %v", recvCap, recvReceived) } diff --git a/p2p/conn/connection_test.go b/p2p/conn/connection_test.go index 5f3d2da56..afc7e6cb1 100644 --- a/p2p/conn/connection_test.go +++ b/p2p/conn/connection_test.go @@ -6,15 +6,14 @@ import ( "testing" "time" - "github.com/fortytw2/leaktest" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/libs/protoio" tmp2p "github.com/consideritdone/landslidecore/proto/tendermint/p2p" "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/fortytw2/leaktest" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const maxPingPongPacketSize = 1024 // bytes @@ -503,7 +502,7 @@ func TestMConnectionReadErrorLongMessage(t *testing.T) { protoWriter := protoio.NewDelimitedWriter(client) // send msg thats just right - var packet = tmp2p.PacketMsg{ + packet := tmp2p.PacketMsg{ ChannelID: 0x01, EOF: true, Data: make([]byte, mconnClient.config.MaxPacketMsgPayloadSize), @@ -566,7 +565,6 @@ func TestMConnectionTrySend(t *testing.T) { // nolint:lll //ignore line length for tests func TestConnVectors(t *testing.T) { - testCases := []struct { testName string msg proto.Message @@ -602,7 +600,7 @@ func TestMConnectionChannelOverflow(t *testing.T) { client := mconnClient.conn protoWriter := protoio.NewDelimitedWriter(client) - var packet = tmp2p.PacketMsg{ + packet := tmp2p.PacketMsg{ ChannelID: 0x01, EOF: true, Data: []byte(`42`), @@ -615,7 +613,6 @@ func TestMConnectionChannelOverflow(t *testing.T) { _, err = protoWriter.WriteMsg(mustWrapPacket(&packet)) require.NoError(t, err) assert.False(t, expectSend(chOnRcv)) - } type stopper interface { diff --git a/p2p/conn/evil_secret_connection_test.go b/p2p/conn/evil_secret_connection_test.go index f7ebcfa89..0854902f9 100644 --- a/p2p/conn/evil_secret_connection_test.go +++ b/p2p/conn/evil_secret_connection_test.go @@ -6,16 +6,15 @@ import ( "io" "testing" - gogotypes "github.com/gogo/protobuf/types" - "github.com/gtank/merlin" - "github.com/stretchr/testify/assert" - "golang.org/x/crypto/chacha20poly1305" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" cryptoenc "github.com/consideritdone/landslidecore/crypto/encoding" "github.com/consideritdone/landslidecore/libs/protoio" tmp2p "github.com/consideritdone/landslidecore/proto/tendermint/p2p" + gogotypes "github.com/gogo/protobuf/types" + "github.com/gtank/merlin" + "github.com/stretchr/testify/assert" + "golang.org/x/crypto/chacha20poly1305" ) type buffer struct { diff --git a/p2p/conn/secret_connection.go b/p2p/conn/secret_connection.go index 72ffd1bda..95134f98c 100644 --- a/p2p/conn/secret_connection.go +++ b/p2p/conn/secret_connection.go @@ -13,14 +13,6 @@ import ( "net" "time" - gogotypes "github.com/gogo/protobuf/types" - "github.com/gtank/merlin" - pool "github.com/libp2p/go-buffer-pool" - "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/hkdf" - "golang.org/x/crypto/nacl/box" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" cryptoenc "github.com/consideritdone/landslidecore/crypto/encoding" @@ -28,6 +20,13 @@ import ( "github.com/consideritdone/landslidecore/libs/protoio" tmsync "github.com/consideritdone/landslidecore/libs/sync" tmp2p "github.com/consideritdone/landslidecore/proto/tendermint/p2p" + gogotypes "github.com/gogo/protobuf/types" + "github.com/gtank/merlin" + pool "github.com/libp2p/go-buffer-pool" + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/hkdf" + "golang.org/x/crypto/nacl/box" ) // 4 + 1024 == 1028 total frame size @@ -61,7 +60,6 @@ var ( // Otherwise they are vulnerable to MITM. // (TODO(ismail): see also https://github.com/consideritdone/landslidecore/issues/3010) type SecretConnection struct { - // immutable recvAead cipher.AEAD sendAead cipher.AEAD @@ -90,9 +88,7 @@ type SecretConnection struct { // Caller should call conn.Close() // See docs/sts-final.pdf for more information. func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*SecretConnection, error) { - var ( - locPubKey = locPrivKey.PubKey() - ) + locPubKey := locPrivKey.PubKey() // Generate ephemeral keys for perfect forward secrecy. locEphPub, locEphPriv := genEphKeys() @@ -192,8 +188,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) { for 0 < len(data) { if err := func() error { - var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize) - var frame = pool.Get(totalFrameSize) + sealedFrame := pool.Get(aeadSizeOverhead + totalFrameSize) + frame := pool.Get(totalFrameSize) defer func() { pool.Put(sealedFrame) pool.Put(frame) @@ -241,7 +237,7 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { } // read off the conn - var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize) + sealedFrame := pool.Get(aeadSizeOverhead + totalFrameSize) defer pool.Put(sealedFrame) _, err = io.ReadFull(sc.conn, sealedFrame) if err != nil { @@ -250,7 +246,7 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { // decrypt the frame. // reads and updates the sc.recvNonce - var frame = pool.Get(totalFrameSize) + frame := pool.Get(totalFrameSize) defer pool.Put(frame) _, err = sc.recvAead.Open(frame[:0], sc.recvNonce[:], sealedFrame, nil) if err != nil { @@ -261,11 +257,11 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { // copy checkLength worth into data, // set recvBuffer to the rest. - var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes + chunkLength := binary.LittleEndian.Uint32(frame) // read the first four bytes if chunkLength > dataMaxSize { return 0, errors.New("chunkLength is greater than dataMaxSize") } - var chunk = frame[dataLenSize : dataLenSize+chunkLength] + chunk := frame[dataLenSize : dataLenSize+chunkLength] n = copy(data, chunk) if n < len(chunk) { sc.recvBuffer = make([]byte, len(chunk)-n) @@ -282,6 +278,7 @@ func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net func (sc *SecretConnection) SetReadDeadline(t time.Time) error { return sc.conn.(net.Conn).SetReadDeadline(t) } + func (sc *SecretConnection) SetWriteDeadline(t time.Time) error { return sc.conn.(net.Conn).SetWriteDeadline(t) } @@ -299,9 +296,8 @@ func genEphKeys() (ephPub, ephPriv *[32]byte) { } func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byte, err error) { - // Send our pubkey and receive theirs in tandem. - var trs, _ = async.Parallel( + trs, _ := async.Parallel( func(_ int) (val interface{}, abort bool, err error) { lc := *locEphPub _, err = protoio.NewDelimitedWriter(conn).WriteMsg(&gogotypes.BytesValue{Value: lc[:]}) @@ -330,7 +326,7 @@ func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byt } // Otherwise: - var _remEphPub = trs.FirstValue().([32]byte) + _remEphPub := trs.FirstValue().([32]byte) return &_remEphPub, nil } @@ -402,9 +398,8 @@ type authSigMessage struct { } func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) { - // Send our info and receive theirs in tandem. - var trs, _ = async.Parallel( + trs, _ := async.Parallel( func(_ int) (val interface{}, abort bool, err error) { pbpk, err := cryptoenc.PubKeyToProto(pubKey) if err != nil { @@ -442,7 +437,7 @@ func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte return } - var _recvMsg = trs.FirstValue().(authSigMessage) + _recvMsg := trs.FirstValue().(authSigMessage) return _recvMsg, nil } diff --git a/p2p/conn/secret_connection_test.go b/p2p/conn/secret_connection_test.go index 3433c9688..87dd52100 100644 --- a/p2p/conn/secret_connection_test.go +++ b/p2p/conn/secret_connection_test.go @@ -14,15 +14,14 @@ import ( "sync" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/crypto/sr25519" "github.com/consideritdone/landslidecore/libs/async" tmos "github.com/consideritdone/landslidecore/libs/os" tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Run go test -update from within this module @@ -129,7 +128,7 @@ func TestSecretConnectionReadWrite(t *testing.T) { return nil, true, err } // In parallel, handle some reads and writes. - var trs, ok = async.Parallel( + trs, ok := async.Parallel( func(_ int) (interface{}, bool, error) { // Node writes: for _, nodeWrite := range nodeWrites { @@ -182,7 +181,7 @@ func TestSecretConnectionReadWrite(t *testing.T) { } // Run foo & bar in parallel - var trs, ok = async.Parallel( + trs, ok := async.Parallel( genNodeRunner("foo", fooConn, fooWrites, &fooReads), genNodeRunner("bar", barConn, barWrites, &barReads), ) @@ -191,12 +190,12 @@ func TestSecretConnectionReadWrite(t *testing.T) { // A helper to ensure that the writes and reads match. // Additionally, small writes (<= dataMaxSize) must be atomically read. - compareWritesReads := func(writes []string, reads []string) { + compareWritesReads := func(writes, reads []string) { for { // Pop next write & corresponding reads - var read = "" - var write = writes[0] - var readCount = 0 + read := "" + write := writes[0] + readCount := 0 for _, readChunk := range reads { read += readChunk readCount++ @@ -229,7 +228,7 @@ func TestDeriveSecretsAndChallengeGolden(t *testing.T) { if *update { t.Logf("Updating golden test vector file %s", goldenFilepath) data := createGoldenTestVectors(t) - err := tmos.WriteFile(goldenFilepath, []byte(data), 0644) + err := tmos.WriteFile(goldenFilepath, []byte(data), 0o644) require.NoError(t, err) } f, err := os.Open(goldenFilepath) @@ -259,11 +258,11 @@ func TestDeriveSecretsAndChallengeGolden(t *testing.T) { } func TestNilPubkey(t *testing.T) { - var fooConn, barConn = makeKVStoreConnPair() + fooConn, barConn := makeKVStoreConnPair() defer fooConn.Close() defer barConn.Close() - var fooPrvKey = ed25519.GenPrivKey() - var barPrvKey = privKeyWithNilPubKey{ed25519.GenPrivKey()} + fooPrvKey := ed25519.GenPrivKey() + barPrvKey := privKeyWithNilPubKey{ed25519.GenPrivKey()} go MakeSecretConnection(fooConn, fooPrvKey) //nolint:errcheck // ignore for tests @@ -273,11 +272,11 @@ func TestNilPubkey(t *testing.T) { } func TestNonEd25519Pubkey(t *testing.T) { - var fooConn, barConn = makeKVStoreConnPair() + fooConn, barConn := makeKVStoreConnPair() defer fooConn.Close() defer barConn.Close() - var fooPrvKey = ed25519.GenPrivKey() - var barPrvKey = sr25519.GenPrivKey() + fooPrvKey := ed25519.GenPrivKey() + barPrvKey := sr25519.GenPrivKey() go MakeSecretConnection(fooConn, fooPrvKey) //nolint:errcheck // ignore for tests @@ -342,7 +341,7 @@ func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection ) // Make connections from both sides in parallel. - var trs, ok = async.Parallel( + trs, ok := async.Parallel( func(_ int) (val interface{}, abort bool, err error) { fooSecConn, err = MakeSecretConnection(fooConn, fooPrvKey) if err != nil { diff --git a/p2p/key.go b/p2p/key.go index 9816179b7..bdee92d3e 100644 --- a/p2p/key.go +++ b/p2p/key.go @@ -88,7 +88,7 @@ func (nodeKey *NodeKey) SaveAs(filePath string) error { if err != nil { return err } - err = ioutil.WriteFile(filePath, jsonBytes, 0600) + err = ioutil.WriteFile(filePath, jsonBytes, 0o600) if err != nil { return err } diff --git a/p2p/key_test.go b/p2p/key_test.go index 27158b491..6c8cb4015 100644 --- a/p2p/key_test.go +++ b/p2p/key_test.go @@ -6,11 +6,10 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/ed25519" tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLoadOrGenNodeKey(t *testing.T) { @@ -60,7 +59,6 @@ func padBytes(bz []byte, targetBytes int) []byte { } func TestPoWTarget(t *testing.T) { - targetBytes := 20 cases := []struct { difficulty uint diff --git a/p2p/mock/peer.go b/p2p/mock/peer.go index 22a0e6781..5800a6b86 100644 --- a/p2p/mock/peer.go +++ b/p2p/mock/peer.go @@ -61,6 +61,7 @@ func (mp *Peer) Get(key string) interface{} { } return nil } + func (mp *Peer) Set(key string, value interface{}) { mp.kv[key] = value } diff --git a/p2p/netaddress.go b/p2p/netaddress.go index 7b69b9a27..b89e55a22 100644 --- a/p2p/netaddress.go +++ b/p2p/netaddress.go @@ -89,7 +89,8 @@ func NewNetAddressString(addr string) (*NetAddress, error) { if len(host) == 0 { return nil, ErrNetAddressInvalid{ addrWithoutProtocol, - errors.New("host is empty")} + errors.New("host is empty"), + } } ip := net.ParseIP(host) @@ -346,34 +347,35 @@ func (na *NetAddress) ReachabilityTo(o *NetAddress) int { // RFC4862: IPv6 Autoconfig (FE80::/64) // RFC6052: IPv6 well known prefix (64:FF9B::/96) // RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96 -var rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)} -var rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)} -var rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)} -var rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)} -var rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)} -var rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)} -var rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)} -var rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)} -var rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)} -var rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)} -var rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)} -var rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)} -var zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)} var ( - // onionCatNet defines the IPv6 address block used to support Tor. - // bitcoind encodes a .onion address as a 16 byte number by decoding the - // address prior to the .onion (i.e. the key hash) base32 into a ten - // byte number. It then stores the first 6 bytes of the address as - // 0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43. - // - // This is the same range used by OnionCat, which is part part of the - // RFC4193 unique local IPv6 range. - // - // In summary the format is: - // { magic 6 bytes, 10 bytes base32 decode of key hash } - onionCatNet = ipNet("fd87:d87e:eb43::", 48, 128) + rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)} + rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)} + rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)} + rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)} + rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)} + rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)} + rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)} + rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)} + rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)} + rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)} + rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)} + rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)} + zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)} ) +// onionCatNet defines the IPv6 address block used to support Tor. +// bitcoind encodes a .onion address as a 16 byte number by decoding the +// address prior to the .onion (i.e. the key hash) base32 into a ten +// byte number. It then stores the first 6 bytes of the address as +// 0xfd, 0x87, 0xd8, 0x7e, 0xeb, 0x43. +// +// This is the same range used by OnionCat, which is part part of the +// RFC4193 unique local IPv6 range. +// +// In summary the format is: +// { magic 6 bytes, 10 bytes base32 decode of key hash } +var onionCatNet = ipNet("fd87:d87e:eb43::", 48, 128) + // ipNet returns a net.IPNet struct given the passed IP address string, number // of one bits to include at the start of the mask, and the total number of bits // for the mask. @@ -402,7 +404,6 @@ func removeProtocolIfDefined(addr string) string { return strings.Split(addr, "://")[1] } return addr - } func validateID(id ID) error { diff --git a/p2p/netaddress_test.go b/p2p/netaddress_test.go index 65f9fb834..468b169a0 100644 --- a/p2p/netaddress_test.go +++ b/p2p/netaddress_test.go @@ -128,7 +128,8 @@ func TestNewNetAddressStrings(t *testing.T) { addrs, errs := NewNetAddressStrings([]string{ "127.0.0.1:8080", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef@127.0.0.1:8080", - "deadbeefdeadbeefdeadbeefdeadbeefdeadbeed@127.0.0.2:8080"}) + "deadbeefdeadbeefdeadbeefdeadbeefdeadbeed@127.0.0.2:8080", + }) assert.Len(t, errs, 1) assert.Equal(t, 2, len(addrs)) } diff --git a/p2p/node_info.go b/p2p/node_info.go index 5edb72719..448448ee5 100644 --- a/p2p/node_info.go +++ b/p2p/node_info.go @@ -120,7 +120,6 @@ func (info DefaultNodeInfo) ID() ID { // url-encoding), and we just need to be careful with how we handle that in our // clients. (e.g. off by default). func (info DefaultNodeInfo) Validate() error { - // ID is already validated. // Validate ListenAddr. @@ -228,7 +227,6 @@ func (info DefaultNodeInfo) HasChannel(chID byte) bool { } func (info DefaultNodeInfo) ToProto() *tmp2p.DefaultNodeInfo { - dni := new(tmp2p.DefaultNodeInfo) dni.ProtocolVersion = tmp2p.ProtocolVersion{ P2P: info.ProtocolVersion.P2P, diff --git a/p2p/node_info_test.go b/p2p/node_info_test.go index d91c576a1..ad8ed7b11 100644 --- a/p2p/node_info_test.go +++ b/p2p/node_info_test.go @@ -3,13 +3,11 @@ package p2p import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/crypto/ed25519" + "github.com/stretchr/testify/assert" ) func TestNodeInfoValidate(t *testing.T) { - // empty fails ni := DefaultNodeInfo{} assert.Error(t, ni.Validate()) @@ -85,11 +83,9 @@ func TestNodeInfoValidate(t *testing.T) { assert.NoError(t, err, tc.testName) } } - } func TestNodeInfoCompatible(t *testing.T) { - nodeKey1 := NodeKey{PrivKey: ed25519.GenPrivKey()} nodeKey2 := NodeKey{PrivKey: ed25519.GenPrivKey()} name := "testing" diff --git a/p2p/peer.go b/p2p/peer.go index 6102e2be6..4a4b0deea 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -8,7 +8,6 @@ import ( "github.com/consideritdone/landslidecore/libs/cmap" "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/libs/service" - tmconn "github.com/consideritdone/landslidecore/p2p/conn" ) @@ -60,7 +59,6 @@ func newPeerConn( conn net.Conn, socketAddr *NetAddress, ) peerConn { - return peerConn{ outbound: outbound, persistent: persistent, @@ -374,7 +372,6 @@ func createMConnection( onPeerError func(Peer, interface{}), config tmconn.MConnConfig, ) *tmconn.MConnection { - onReceive := func(chID byte, msgBytes []byte) { reactor := reactorsByCh[chID] if reactor == nil { diff --git a/p2p/peer_set_test.go b/p2p/peer_set_test.go index 064b5b48f..aca0af734 100644 --- a/p2p/peer_set_test.go +++ b/p2p/peer_set_test.go @@ -5,10 +5,9 @@ import ( "sync" "testing" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/libs/service" + "github.com/stretchr/testify/assert" ) // mockPeer for testing the PeerSet diff --git a/p2p/peer_test.go b/p2p/peer_test.go index fbf5b394f..ced6bcf0c 100644 --- a/p2p/peer_test.go +++ b/p2p/peer_test.go @@ -7,16 +7,14 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - + "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/libs/bytes" "github.com/consideritdone/landslidecore/libs/log" - - "github.com/consideritdone/landslidecore/config" tmconn "github.com/consideritdone/landslidecore/p2p/conn" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPeerBasic(t *testing.T) { @@ -117,7 +115,6 @@ func testOutboundPeerConn( persistent bool, ourNodePrivKey crypto.PrivKey, ) (peerConn, error) { - var pc peerConn conn, err := testDial(addr, config) if err != nil { diff --git a/p2p/pex/addrbook.go b/p2p/pex/addrbook.go index d0c0253d4..9cb7bf5fa 100644 --- a/p2p/pex/addrbook.go +++ b/p2p/pex/addrbook.go @@ -14,14 +14,13 @@ import ( "sync" "time" - "github.com/minio/highwayhash" - "github.com/consideritdone/landslidecore/crypto" tmmath "github.com/consideritdone/landslidecore/libs/math" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/libs/service" tmsync "github.com/consideritdone/landslidecore/libs/sync" "github.com/consideritdone/landslidecore/p2p" + "github.com/minio/highwayhash" ) const ( @@ -44,7 +43,7 @@ type AddrBook interface { AddPrivateIDs([]string) // Add and remove an address - AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error + AddAddress(addr, src *p2p.NetAddress) error RemoveAddress(*p2p.NetAddress) // Check if the address is in the book @@ -209,7 +208,7 @@ func (a *addrBook) AddPrivateIDs(ids []string) { // Add address to a "new" bucket. If it's already in one, only add it probabilistically. // Returns error if the addr is non-routable. Does not add self. // NOTE: addr must not be nil -func (a *addrBook) AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error { +func (a *addrBook) AddAddress(addr, src *p2p.NetAddress) error { a.mtx.Lock() defer a.mtx.Unlock() diff --git a/p2p/pex/addrbook_test.go b/p2p/pex/addrbook_test.go index 3925d4d08..56ac7dd91 100644 --- a/p2p/pex/addrbook_test.go +++ b/p2p/pex/addrbook_test.go @@ -10,13 +10,12 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" tmmath "github.com/consideritdone/landslidecore/libs/math" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/p2p" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // FIXME These tests should not rely on .(*addrBook) assertions diff --git a/p2p/pex/file.go b/p2p/pex/file.go index defb5860f..58c8ee83a 100644 --- a/p2p/pex/file.go +++ b/p2p/pex/file.go @@ -35,7 +35,7 @@ func (a *addrBook) saveToFile(filePath string) { a.Logger.Error("Failed to save AddrBook to file", "err", err) return } - err = tempfile.WriteFileAtomic(filePath, jsonBytes, 0644) + err = tempfile.WriteFileAtomic(filePath, jsonBytes, 0o644) if err != nil { a.Logger.Error("Failed to save AddrBook to file", "file", filePath, "err", err) } diff --git a/p2p/pex/known_address.go b/p2p/pex/known_address.go index 1339b7aa4..eea25bd94 100644 --- a/p2p/pex/known_address.go +++ b/p2p/pex/known_address.go @@ -19,7 +19,7 @@ type knownAddress struct { LastBanTime time.Time `json:"last_ban_time"` } -func newKnownAddress(addr *p2p.NetAddress, src *p2p.NetAddress) *knownAddress { +func newKnownAddress(addr, src *p2p.NetAddress) *knownAddress { return &knownAddress{ Addr: addr, Src: src, diff --git a/p2p/pex/pex_reactor.go b/p2p/pex/pex_reactor.go index fa173dfe6..d5b4cd3fa 100644 --- a/p2p/pex/pex_reactor.go +++ b/p2p/pex/pex_reactor.go @@ -6,8 +6,6 @@ import ( "sync" "time" - "github.com/gogo/protobuf/proto" - "github.com/consideritdone/landslidecore/libs/cmap" tmmath "github.com/consideritdone/landslidecore/libs/math" tmrand "github.com/consideritdone/landslidecore/libs/rand" @@ -15,6 +13,7 @@ import ( "github.com/consideritdone/landslidecore/p2p" "github.com/consideritdone/landslidecore/p2p/conn" tmp2p "github.com/consideritdone/landslidecore/proto/tendermint/p2p" + "github.com/gogo/protobuf/proto" ) type Peer = p2p.Peer @@ -54,8 +53,7 @@ const ( defaultBanTime = 24 * time.Hour ) -type errMaxAttemptsToDial struct { -} +type errMaxAttemptsToDial struct{} func (e errMaxAttemptsToDial) Error() string { return fmt.Sprintf("reached max attempts %d to dial", maxAttemptsToDial) diff --git a/p2p/pex/pex_reactor_test.go b/p2p/pex/pex_reactor_test.go index f014256a3..ccb99138a 100644 --- a/p2p/pex/pex_reactor_test.go +++ b/p2p/pex/pex_reactor_test.go @@ -9,20 +9,17 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/p2p" "github.com/consideritdone/landslidecore/p2p/mock" tmp2p "github.com/consideritdone/landslidecore/proto/tendermint/p2p" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -var ( - cfg *config.P2PConfig -) +var cfg *config.P2PConfig func init() { cfg = config.DefaultP2PConfig() @@ -227,8 +224,10 @@ func TestCheckSeeds(t *testing.T) { // 4. test create peer with all seeds having unresolvable DNS fails badPeerConfig := &ReactorConfig{ - Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657", - "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657"}, + Seeds: []string{ + "ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657", + "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657", + }, } peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig) require.Error(t, peerSwitch.Start()) @@ -236,9 +235,11 @@ func TestCheckSeeds(t *testing.T) { // 5. test create peer with one good seed address succeeds badPeerConfig = &ReactorConfig{ - Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657", + Seeds: []string{ + "ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657", "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657", - seed.NetAddress().String()}, + seed.NetAddress().String(), + }, } peerSwitch = testCreatePeerWithConfig(dir, 2, badPeerConfig) require.Nil(t, peerSwitch.Start()) @@ -677,7 +678,6 @@ func createSwitchAndAddReactors(reactors ...p2p.Reactor) *p2p.Switch { } func TestPexVectors(t *testing.T) { - addr := tmp2p.NetAddress{ ID: "1", IP: "127.0.0.1", diff --git a/p2p/switch.go b/p2p/switch.go index e3841e0a0..0c04a067f 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -45,7 +45,7 @@ func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig { // An AddrBook represents an address book from the pex package, which is used // to store peer addresses. type AddrBook interface { - AddAddress(addr *NetAddress, src *NetAddress) error + AddAddress(addr, src *NetAddress) error AddPrivateIDs([]string) AddOurAddress(*NetAddress) OurAddress(*NetAddress) bool diff --git a/p2p/switch_test.go b/p2p/switch_test.go index 41a27dc37..8b0d758f0 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -14,20 +14,17 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/libs/log" tmsync "github.com/consideritdone/landslidecore/libs/sync" "github.com/consideritdone/landslidecore/p2p/conn" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -var ( - cfg *config.P2PConfig -) +var cfg *config.P2PConfig func init() { cfg = config.DefaultP2PConfig() @@ -99,7 +96,8 @@ func MakeSwitchPair(t testing.TB, initSwitch func(int, *Switch) *Switch) (*Switc func initSwitchFunc(i int, sw *Switch) *Switch { sw.SetAddrBook(&AddrBookMock{ Addrs: make(map[string]struct{}), - OurAddrs: make(map[string]struct{})}) + OurAddrs: make(map[string]struct{}), + }) // Make two reactors of two channels each sw.AddReactor("foo", NewTestReactor([]*conn.ChannelDescriptor{ @@ -681,9 +679,11 @@ func (et errorTransport) NetAddress() NetAddress { func (et errorTransport) Accept(c peerConfig) (Peer, error) { return nil, et.acceptErr } + func (errorTransport) Dial(NetAddress, peerConfig) (Peer, error) { panic("not implemented") } + func (errorTransport) Cleanup(Peer) { panic("not implemented") } diff --git a/p2p/test_util.go b/p2p/test_util.go index e0bedc486..bf3c26a5b 100644 --- a/p2p/test_util.go +++ b/p2p/test_util.go @@ -5,13 +5,12 @@ import ( "net" "time" + "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/libs/log" tmnet "github.com/consideritdone/landslidecore/libs/net" tmrand "github.com/consideritdone/landslidecore/libs/rand" - - "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/p2p/conn" ) @@ -180,7 +179,6 @@ func MakeSwitch( initSwitch func(int, *Switch) *Switch, opts ...SwitchOption, ) *Switch { - nodeKey := NodeKey{ PrivKey: ed25519.GenPrivKey(), } @@ -289,7 +287,7 @@ type AddrBookMock struct { var _ AddrBook = (*AddrBookMock)(nil) -func (book *AddrBookMock) AddAddress(addr *NetAddress, src *NetAddress) error { +func (book *AddrBookMock) AddAddress(addr, src *NetAddress) error { book.Addrs[addr.String()] = struct{}{} return nil } @@ -303,6 +301,7 @@ func (book *AddrBookMock) HasAddress(addr *NetAddress) bool { _, ok := book.Addrs[addr.String()] return ok } + func (book *AddrBookMock) RemoveAddress(addr *NetAddress) { delete(book.Addrs, addr.String()) } diff --git a/p2p/transport.go b/p2p/transport.go index 1070be8ce..a307ca66a 100644 --- a/p2p/transport.go +++ b/p2p/transport.go @@ -6,12 +6,11 @@ import ( "net" "time" - "golang.org/x/net/netutil" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/libs/protoio" "github.com/consideritdone/landslidecore/p2p/conn" tmp2p "github.com/consideritdone/landslidecore/proto/tendermint/p2p" + "golang.org/x/net/netutil" ) const ( @@ -158,8 +157,10 @@ type MultiplexTransport struct { } // Test multiplexTransport for interface completeness. -var _ Transport = (*MultiplexTransport)(nil) -var _ transportLifecycle = (*MultiplexTransport)(nil) +var ( + _ Transport = (*MultiplexTransport)(nil) + _ transportLifecycle = (*MultiplexTransport)(nil) +) // NewMultiplexTransport returns a tcp connected multiplexed peer. func NewMultiplexTransport( @@ -391,7 +392,6 @@ func (mt *MultiplexTransport) filterConn(c net.Conn) (err error) { case <-time.After(mt.filterTimeout): return ErrFilterTimeout{} } - } mt.conns.Set(c, ips) @@ -494,7 +494,6 @@ func (mt *MultiplexTransport) wrapPeer( cfg peerConfig, socketAddr *NetAddress, ) Peer { - persistent := false if cfg.isPersistent != nil { if cfg.outbound { diff --git a/p2p/transport_test.go b/p2p/transport_test.go index 875c743e9..6c35d3234 100644 --- a/p2p/transport_test.go +++ b/p2p/transport_test.go @@ -319,13 +319,11 @@ func TestTransportMultiplexAcceptNonBlocking(t *testing.T) { go func() { <-slowc - var ( - dialer = newMultiplexTransport( - fastNodeInfo, - NodeKey{ - PrivKey: fastNodePV, - }, - ) + dialer := newMultiplexTransport( + fastNodeInfo, + NodeKey{ + PrivKey: fastNodePV, + }, ) addr := NewNetAddress(mt.nodeKey.ID(), mt.listener.Addr()) @@ -588,10 +586,8 @@ func TestTransportHandshake(t *testing.T) { } }(c) go func(c net.Conn) { - var ( - // ni DefaultNodeInfo - pbni tmp2p.DefaultNodeInfo - ) + // ni DefaultNodeInfo + var pbni tmp2p.DefaultNodeInfo protoReader := protoio.NewDelimitedReader(c, MaxNodeInfoSize()) _, err := protoReader.ReadMsg(&pbni) diff --git a/p2p/trust/metric.go b/p2p/trust/metric.go index c6ba1dd8a..ebc95fd91 100644 --- a/p2p/trust/metric.go +++ b/p2p/trust/metric.go @@ -279,7 +279,6 @@ func (tm *Metric) Copy() *Metric { bad: tm.bad, paused: tm.paused, } - } /* Private methods */ 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/trust/store.go b/p2p/trust/store.go index 3516c5398..c1071b0be 100644 --- a/p2p/trust/store.go +++ b/p2p/trust/store.go @@ -8,10 +8,9 @@ import ( "fmt" "time" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/libs/service" tmsync "github.com/consideritdone/landslidecore/libs/sync" + dbm "github.com/tendermint/tm-db" ) const defaultStorePeriodicSaveInterval = 1 * time.Minute diff --git a/p2p/trust/store_test.go b/p2p/trust/store_test.go index 25b66874b..b3926563b 100644 --- a/p2p/trust/store_test.go +++ b/p2p/trust/store_test.go @@ -9,11 +9,10 @@ import ( "os" "testing" + "github.com/consideritdone/landslidecore/libs/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" dbm "github.com/tendermint/tm-db" - - "github.com/consideritdone/landslidecore/libs/log" ) func TestTrustMetricStoreSaveLoad(t *testing.T) { diff --git a/p2p/types.go b/p2p/types.go index bcb3fd785..cfa5f62c6 100644 --- a/p2p/types.go +++ b/p2p/types.go @@ -4,5 +4,7 @@ import ( "github.com/consideritdone/landslidecore/p2p/conn" ) -type ChannelDescriptor = conn.ChannelDescriptor -type ConnectionStatus = conn.ConnectionStatus +type ( + ChannelDescriptor = conn.ChannelDescriptor + ConnectionStatus = conn.ConnectionStatus +) diff --git a/p2p/upnp/probe.go b/p2p/upnp/probe.go index 43c9a4a0a..e6f42a102 100644 --- a/p2p/upnp/probe.go +++ b/p2p/upnp/probe.go @@ -13,7 +13,7 @@ type Capabilities struct { Hairpin bool } -func makeUPNPListener(intPort int, extPort int, logger log.Logger) (NAT, net.Listener, net.IP, error) { +func makeUPNPListener(intPort, extPort int, logger log.Logger) (NAT, net.Listener, net.IP, error) { nat, err := Discover() if err != nil { return nil, nil, nil, fmt.Errorf("nat upnp could not be discovered: %v", err) diff --git a/p2p/upnp/upnp.go b/p2p/upnp/upnp.go index c00530aca..3777f4a1d 100644 --- a/p2p/upnp/upnp.go +++ b/p2p/upnp/upnp.go @@ -299,7 +299,6 @@ type statusInfo struct { } func (n *upnpNAT) getExternalIPAddress() (info statusInfo, err error) { - message := "\r\n" + "" @@ -350,7 +349,8 @@ func (n *upnpNAT) AddPortMapping( externalPort, internalPort int, description string, - timeout int) (mappedExternalPort int, err error) { + timeout int, +) (mappedExternalPort int, err error) { // A single concatenation would break ARM compilation. message := "\r\n" + "" + strconv.Itoa(externalPort) @@ -382,7 +382,6 @@ func (n *upnpNAT) AddPortMapping( } func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) { - message := "\r\n" + "" + strconv.Itoa(externalPort) + "" + protocol + "" + 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/file.go b/privval/file.go index 80c4d3797..30a7de122 100644 --- a/privval/file.go +++ b/privval/file.go @@ -7,8 +7,6 @@ import ( "io/ioutil" "time" - "github.com/gogo/protobuf/proto" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" tmbytes "github.com/consideritdone/landslidecore/libs/bytes" @@ -19,6 +17,7 @@ import ( tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/gogo/protobuf/proto" ) // TODO: type ? @@ -64,7 +63,7 @@ func (pvKey FilePVKey) Save() { panic(err) } - if err := tempfile.WriteFileAtomic(outFile, jsonBytes, 0600); err != nil { + if err := tempfile.WriteFileAtomic(outFile, jsonBytes, 0o600); err != nil { panic(err) } } @@ -90,7 +89,6 @@ type FilePVLastSignState struct { // we have already signed for this HRS, and can reuse the existing signature). // It panics if the HRS matches the arguments, there's a SignBytes, but no Signature. func (lss *FilePVLastSignState) CheckHRS(height int64, round int32, step int8) (bool, error) { - if lss.Height > height { return false, fmt.Errorf("height regression. Got %v, last height %v", height, lss.Height) } @@ -133,7 +131,7 @@ func (lss *FilePVLastSignState) Save() { if err != nil { panic(err) } - err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600) + err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0o600) if err != nil { panic(err) } @@ -384,8 +382,8 @@ func (pv *FilePV) signProposal(chainID string, proposal *tmproto.Proposal) error // Persist height/round/step and signature func (pv *FilePV) saveSigned(height int64, round int32, step int8, - signBytes []byte, sig []byte) { - + signBytes, sig []byte, +) { pv.LastSignState.Height = height pv.LastSignState.Round = round pv.LastSignState.Step = step diff --git a/privval/file_test.go b/privval/file_test.go index f722f6677..024c08e0a 100644 --- a/privval/file_test.go +++ b/privval/file_test.go @@ -8,9 +8,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/crypto/tmhash" tmjson "github.com/consideritdone/landslidecore/libs/json" @@ -18,6 +15,8 @@ import ( tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGenLoadValidator(t *testing.T) { @@ -169,10 +168,14 @@ func TestSignVote(t *testing.T) { randbytes := tmrand.Bytes(tmhash.Size) randbytes2 := tmrand.Bytes(tmhash.Size) - block1 := types.BlockID{Hash: randbytes, - PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}} - block2 := types.BlockID{Hash: randbytes2, - PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}} + block1 := types.BlockID{ + Hash: randbytes, + PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}, + } + block2 := types.BlockID{ + Hash: randbytes2, + PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}, + } height, round := int64(10), int32(1) voteType := tmproto.PrevoteType @@ -222,10 +225,14 @@ func TestSignProposal(t *testing.T) { randbytes := tmrand.Bytes(tmhash.Size) randbytes2 := tmrand.Bytes(tmhash.Size) - block1 := types.BlockID{Hash: randbytes, - PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}} - block2 := types.BlockID{Hash: randbytes2, - PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}} + block1 := types.BlockID{ + Hash: randbytes, + PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}, + } + block2 := types.BlockID{ + Hash: randbytes2, + PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}, + } height, round := int64(10), int32(1) // sign a proposal for first time @@ -321,7 +328,8 @@ func TestDifferByTimestamp(t *testing.T) { } func newVote(addr types.Address, idx int32, height int64, round int32, - typ tmproto.SignedMsgType, blockID types.BlockID) *types.Vote { + typ tmproto.SignedMsgType, blockID types.BlockID, +) *types.Vote { return &types.Vote{ ValidatorAddress: addr, ValidatorIndex: idx, diff --git a/privval/msgs.go b/privval/msgs.go index 35901798c..54d28804a 100644 --- a/privval/msgs.go +++ b/privval/msgs.go @@ -3,9 +3,8 @@ package privval import ( "fmt" - "github.com/gogo/protobuf/proto" - privvalproto "github.com/consideritdone/landslidecore/proto/tendermint/privval" + "github.com/gogo/protobuf/proto" ) // TODO: Add ChainIDRequest diff --git a/privval/msgs_test.go b/privval/msgs_test.go index 53a36d668..71def39d4 100644 --- a/privval/msgs_test.go +++ b/privval/msgs_test.go @@ -5,9 +5,6 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" cryptoenc "github.com/consideritdone/landslidecore/crypto/encoding" @@ -16,6 +13,8 @@ import ( privproto "github.com/consideritdone/landslidecore/proto/tendermint/privval" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/require" ) var stamp = time.Date(2019, 10, 13, 16, 14, 44, 0, time.UTC) @@ -39,7 +38,6 @@ func exampleVote() *types.Vote { } func exampleProposal() *types.Proposal { - return &types.Proposal{ Type: tmproto.SignedMsgType(1), Height: 3, diff --git a/privval/signer_client_test.go b/privval/signer_client_test.go index 1cf11c2e4..375bd13a7 100644 --- a/privval/signer_client_test.go +++ b/privval/signer_client_test.go @@ -5,9 +5,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" tmrand "github.com/consideritdone/landslidecore/libs/rand" @@ -15,6 +12,8 @@ import ( privvalproto "github.com/consideritdone/landslidecore/proto/tendermint/privval" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type signerTestCase struct { @@ -390,7 +389,8 @@ func TestSignerSignVoteErrors(t *testing.T) { } func brokenHandler(privVal types.PrivValidator, request privvalproto.Message, - chainID string) (privvalproto.Message, error) { + chainID string, +) (privvalproto.Message, error) { var res privvalproto.Message var err error diff --git a/privval/signer_dialer_endpoint.go b/privval/signer_dialer_endpoint.go index 6b23a3666..a10c5af95 100644 --- a/privval/signer_dialer_endpoint.go +++ b/privval/signer_dialer_endpoint.go @@ -52,7 +52,6 @@ func NewSignerDialerEndpoint( dialer SocketDialer, options ...SignerServiceEndpointOption, ) *SignerDialerEndpoint { - sd := &SignerDialerEndpoint{ dialer: dialer, retryWait: defaultRetryWaitMilliseconds * time.Millisecond, diff --git a/privval/signer_listener_endpoint_test.go b/privval/signer_listener_endpoint_test.go index 916c9858a..efdb9ff1b 100644 --- a/privval/signer_listener_endpoint_test.go +++ b/privval/signer_listener_endpoint_test.go @@ -5,14 +5,13 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/libs/log" tmnet "github.com/consideritdone/landslidecore/libs/net" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -188,7 +187,6 @@ func getMockEndpoints( addr string, socketDialer SocketDialer, ) (*SignerListenerEndpoint, *SignerDialerEndpoint) { - var ( logger = log.TestingLogger() endpointIsOpenCh = make(chan struct{}) diff --git a/privval/signer_requestHandler.go b/privval/signer_requestHandler.go index 52b2aacdc..1eebed48b 100644 --- a/privval/signer_requestHandler.go +++ b/privval/signer_requestHandler.go @@ -26,7 +26,9 @@ func DefaultValidationRequestHandler( if r.PubKeyRequest.GetChainId() != chainID { res = mustWrapMsg(&privvalproto.PubKeyResponse{ PubKey: cryptoproto.PublicKey{}, Error: &privvalproto.RemoteSignerError{ - Code: 0, Description: "unable to provide pubkey"}}) + Code: 0, Description: "unable to provide pubkey", + }, + }) return res, fmt.Errorf("want chainID: %s, got chainID: %s", r.PubKeyRequest.GetChainId(), chainID) } @@ -42,7 +44,8 @@ func DefaultValidationRequestHandler( if err != nil { res = mustWrapMsg(&privvalproto.PubKeyResponse{ - PubKey: cryptoproto.PublicKey{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}}) + PubKey: cryptoproto.PublicKey{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}, + }) } else { res = mustWrapMsg(&privvalproto.PubKeyResponse{PubKey: pk, Error: nil}) } @@ -51,7 +54,9 @@ func DefaultValidationRequestHandler( if r.SignVoteRequest.ChainId != chainID { res = mustWrapMsg(&privvalproto.SignedVoteResponse{ Vote: tmproto.Vote{}, Error: &privvalproto.RemoteSignerError{ - Code: 0, Description: "unable to sign vote"}}) + Code: 0, Description: "unable to sign vote", + }, + }) return res, fmt.Errorf("want chainID: %s, got chainID: %s", r.SignVoteRequest.GetChainId(), chainID) } @@ -60,7 +65,8 @@ func DefaultValidationRequestHandler( err = privVal.SignVote(chainID, vote) if err != nil { res = mustWrapMsg(&privvalproto.SignedVoteResponse{ - Vote: tmproto.Vote{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}}) + Vote: tmproto.Vote{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}, + }) } else { res = mustWrapMsg(&privvalproto.SignedVoteResponse{Vote: *vote, Error: nil}) } @@ -70,7 +76,9 @@ func DefaultValidationRequestHandler( res = mustWrapMsg(&privvalproto.SignedProposalResponse{ Proposal: tmproto.Proposal{}, Error: &privvalproto.RemoteSignerError{ Code: 0, - Description: "unable to sign proposal"}}) + Description: "unable to sign proposal", + }, + }) return res, fmt.Errorf("want chainID: %s, got chainID: %s", r.SignProposalRequest.GetChainId(), chainID) } @@ -79,7 +87,8 @@ func DefaultValidationRequestHandler( err = privVal.SignProposal(chainID, proposal) if err != nil { res = mustWrapMsg(&privvalproto.SignedProposalResponse{ - Proposal: tmproto.Proposal{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}}) + Proposal: tmproto.Proposal{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}, + }) } else { res = mustWrapMsg(&privvalproto.SignedProposalResponse{Proposal: *proposal, Error: nil}) } diff --git a/privval/socket_dialers_test.go b/privval/socket_dialers_test.go index 0ca747cf7..29bab7c21 100644 --- a/privval/socket_dialers_test.go +++ b/privval/socket_dialers_test.go @@ -5,10 +5,9 @@ import ( "testing" "time" + "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/crypto/ed25519" ) func getDialerTestCases(t *testing.T) []dialerTestCase { diff --git a/proxy/app_conn.go b/proxy/app_conn.go index a11f22518..1687625d7 100644 --- a/proxy/app_conn.go +++ b/proxy/app_conn.go @@ -185,11 +185,13 @@ func (app *appConnSnapshot) OfferSnapshotSync(req types.RequestOfferSnapshot) (* } func (app *appConnSnapshot) LoadSnapshotChunkSync( - req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) { + req types.RequestLoadSnapshotChunk, +) (*types.ResponseLoadSnapshotChunk, error) { return app.appConn.LoadSnapshotChunkSync(req) } func (app *appConnSnapshot) ApplySnapshotChunkSync( - req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) { + req types.RequestApplySnapshotChunk, +) (*types.ResponseApplySnapshotChunk, error) { return app.appConn.ApplySnapshotChunkSync(req) } diff --git a/proxy/multi_app_conn_test.go b/proxy/multi_app_conn_test.go index b38bbca1d..b48bd1426 100644 --- a/proxy/multi_app_conn_test.go +++ b/proxy/multi_app_conn_test.go @@ -8,11 +8,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - abcimocks "github.com/consideritdone/landslidecore/abci/client/mocks" "github.com/consideritdone/landslidecore/proxy/mocks" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" ) func TestAppConns_Start_Stop(t *testing.T) { diff --git a/rpc/client/event_test.go b/rpc/client/event_test.go index 8a3dbe866..932864898 100644 --- a/rpc/client/event_test.go +++ b/rpc/client/event_test.go @@ -7,14 +7,13 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/rpc/client" ctypes "github.com/consideritdone/landslidecore/rpc/core/types" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var waitForEventTimeout = 8 * time.Second @@ -57,7 +56,6 @@ func TestBlockEvents(t *testing.T) { for _, c := range GetClients() { c := c t.Run(reflect.TypeOf(c).String(), func(t *testing.T) { - // start for this test it if it wasn't already running if !c.IsRunning() { // if so, then we start it, listen, and stop it. @@ -105,7 +103,6 @@ func testTxEventsSent(t *testing.T, broadcastMethod string) { for _, c := range GetClients() { c := c t.Run(reflect.TypeOf(c).String(), func(t *testing.T) { - // start for this test it if it wasn't already running if !c.IsRunning() { // if so, then we start it, listen, and stop it. diff --git a/rpc/client/evidence_test.go b/rpc/client/evidence_test.go index 458270fa2..4395ab6de 100644 --- a/rpc/client/evidence_test.go +++ b/rpc/client/evidence_test.go @@ -6,9 +6,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/crypto/ed25519" cryptoenc "github.com/consideritdone/landslidecore/crypto/encoding" @@ -19,6 +16,8 @@ import ( "github.com/consideritdone/landslidecore/rpc/client" rpctest "github.com/consideritdone/landslidecore/rpc/test" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // For some reason the empty node used in tests has a time of @@ -28,9 +27,9 @@ import ( var defaultTestTime = time.Date(2018, 10, 10, 8, 20, 13, 695936996, time.UTC) func newEvidence(t *testing.T, val *privval.FilePV, - vote *types.Vote, vote2 *types.Vote, - chainID string) *types.DuplicateVoteEvidence { - + vote, vote2 *types.Vote, + chainID string, +) *types.DuplicateVoteEvidence { var err error v := vote.ToProto() diff --git a/rpc/client/helpers_test.go b/rpc/client/helpers_test.go index 2fe2d6e3d..41a16bee3 100644 --- a/rpc/client/helpers_test.go +++ b/rpc/client/helpers_test.go @@ -5,12 +5,11 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/rpc/client" "github.com/consideritdone/landslidecore/rpc/client/mock" ctypes "github.com/consideritdone/landslidecore/rpc/core/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestWaitForHeight(t *testing.T) { diff --git a/rpc/client/http/http.go b/rpc/client/http/http.go index 8f3a82bc1..e485f8b78 100644 --- a/rpc/client/http/http.go +++ b/rpc/client/http/http.go @@ -98,9 +98,11 @@ type baseRPCClient struct { caller jsonrpcclient.Caller } -var _ rpcClient = (*HTTP)(nil) -var _ rpcClient = (*BatchHTTP)(nil) -var _ rpcClient = (*baseRPCClient)(nil) +var ( + _ rpcClient = (*HTTP)(nil) + _ rpcClient = (*BatchHTTP)(nil) + _ rpcClient = (*baseRPCClient)(nil) +) //----------------------------------------------------------------------------- // HTTP @@ -233,7 +235,8 @@ func (c *baseRPCClient) ABCIQueryWithOptions( ctx context.Context, path string, data bytes.HexBytes, - opts rpcclient.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { + opts rpcclient.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { result := new(ctypes.ResultABCIQuery) _, err := c.caller.Call(ctx, "abci_query", map[string]interface{}{"path": path, "data": data, "height": opts.Height, "prove": opts.Prove}, @@ -478,7 +481,6 @@ func (c *baseRPCClient) TxSearch( perPage *int, orderBy string, ) (*ctypes.ResultTxSearch, error) { - result := new(ctypes.ResultTxSearch) params := map[string]interface{}{ "query": query, @@ -507,7 +509,6 @@ func (c *baseRPCClient) BlockSearch( page, perPage *int, orderBy string, ) (*ctypes.ResultBlockSearch, error) { - result := new(ctypes.ResultBlockSearch) params := map[string]interface{}{ "query": query, @@ -628,8 +629,8 @@ func (w *WSEvents) OnStop() { // // It returns an error if WSEvents is not running. func (w *WSEvents) Subscribe(ctx context.Context, subscriber, query string, - outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) { - + outCapacity ...int, +) (out <-chan ctypes.ResultEvent, err error) { if !w.IsRunning() { return nil, errNotRunning } diff --git a/rpc/client/local/local.go b/rpc/client/local/local.go index 05a4e944f..3a4b12b21 100644 --- a/rpc/client/local/local.go +++ b/rpc/client/local/local.go @@ -83,7 +83,8 @@ func (c *Local) ABCIQueryWithOptions( ctx context.Context, path string, data bytes.HexBytes, - opts rpcclient.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { + opts rpcclient.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { return core.ABCIQuery(c.ctx, path, data, opts.Height, opts.Prove) } @@ -209,7 +210,8 @@ func (c *Local) Subscribe( ctx context.Context, subscriber, query string, - outCapacity ...int) (out <-chan ctypes.ResultEvent, err error) { + outCapacity ...int, +) (out <-chan ctypes.ResultEvent, err error) { q, err := tmquery.New(query) if err != nil { return nil, fmt.Errorf("failed to parse query: %w", err) @@ -240,7 +242,8 @@ func (c *Local) eventsRoutine( sub types.Subscription, subscriber string, q tmpubsub.Query, - outc chan<- ctypes.ResultEvent) { + outc chan<- ctypes.ResultEvent, +) { for { select { case msg := <-sub.Out(): diff --git a/rpc/client/mock/abci.go b/rpc/client/mock/abci.go index d8ecba5f0..ae4e81ee3 100644 --- a/rpc/client/mock/abci.go +++ b/rpc/client/mock/abci.go @@ -36,7 +36,8 @@ func (a ABCIApp) ABCIQueryWithOptions( ctx context.Context, path string, data bytes.HexBytes, - opts client.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { + opts client.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { q := a.App.Query(abci.RequestQuery{ Data: data, Path: path, @@ -116,7 +117,8 @@ func (m ABCIMock) ABCIQueryWithOptions( ctx context.Context, path string, data bytes.HexBytes, - opts client.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { + opts client.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { res, err := m.Query.GetResponse(QueryArgs{path, data, opts.Height, opts.Prove}) if err != nil { return nil, err @@ -196,7 +198,8 @@ func (r *ABCIRecorder) ABCIQueryWithOptions( ctx context.Context, path string, data bytes.HexBytes, - opts client.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { + opts client.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { res, err := r.Client.ABCIQueryWithOptions(ctx, path, data, opts) r.addCall(Call{ Name: "abci_query", diff --git a/rpc/client/mock/abci_test.go b/rpc/client/mock/abci_test.go index 658af6398..0d84acc6f 100644 --- a/rpc/client/mock/abci_test.go +++ b/rpc/client/mock/abci_test.go @@ -6,9 +6,6 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/kvstore" abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/bytes" @@ -16,6 +13,8 @@ import ( "github.com/consideritdone/landslidecore/rpc/client/mock" ctypes "github.com/consideritdone/landslidecore/rpc/core/types" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestABCIMock(t *testing.T) { diff --git a/rpc/client/mock/client.go b/rpc/client/mock/client.go index ab03fd0e6..f3c2ffa7d 100644 --- a/rpc/client/mock/client.go +++ b/rpc/client/mock/client.go @@ -95,7 +95,8 @@ func (c Client) ABCIQueryWithOptions( ctx context.Context, path string, data bytes.HexBytes, - opts client.ABCIQueryOptions) (*ctypes.ResultABCIQuery, error) { + opts client.ABCIQueryOptions, +) (*ctypes.ResultABCIQuery, error) { return core.ABCIQuery(&rpctypes.Context{}, path, data, opts.Height, opts.Prove) } diff --git a/rpc/client/mock/status_test.go b/rpc/client/mock/status_test.go index 800570abe..fda500793 100644 --- a/rpc/client/mock/status_test.go +++ b/rpc/client/mock/status_test.go @@ -4,12 +4,11 @@ import ( "context" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/bytes" "github.com/consideritdone/landslidecore/rpc/client/mock" ctypes "github.com/consideritdone/landslidecore/rpc/core/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStatus(t *testing.T) { @@ -23,7 +22,8 @@ func TestStatus(t *testing.T) { LatestAppHash: bytes.HexBytes("app"), LatestBlockHeight: 10, }, - }}, + }, + }, } r := mock.NewStatusRecorder(m) diff --git a/rpc/client/rpc_test.go b/rpc/client/rpc_test.go index e422e7362..1ceb27ae8 100644 --- a/rpc/client/rpc_test.go +++ b/rpc/client/rpc_test.go @@ -11,9 +11,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" tmjson "github.com/consideritdone/landslidecore/libs/json" "github.com/consideritdone/landslidecore/libs/log" @@ -26,11 +23,11 @@ import ( rpcclient "github.com/consideritdone/landslidecore/rpc/jsonrpc/client" rpctest "github.com/consideritdone/landslidecore/rpc/test" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -var ( - ctx = context.Background() -) +var ctx = context.Background() func getHTTPClient() *rpchttp.HTTP { rpcAddr := rpctest.GetConfig().RPC.ListenAddress diff --git a/rpc/core/blocks.go b/rpc/core/blocks.go index 25de55202..d3c537d67 100644 --- a/rpc/core/blocks.go +++ b/rpc/core/blocks.go @@ -39,7 +39,8 @@ func BlockchainInfo(ctx *rpctypes.Context, minHeight, maxHeight int64) (*ctypes. return &ctypes.ResultBlockchainInfo{ LastHeight: env.BlockStore.Height(), - BlockMetas: blockMetas}, nil + BlockMetas: blockMetas, + }, nil } // error if either min or max are negative or min > max @@ -167,7 +168,6 @@ func BlockSearch( pagePtr, perPagePtr *int, orderBy string, ) (*ctypes.ResultBlockSearch, error) { - // skip if block indexing is disabled if _, ok := env.BlockIndexer.(*blockidxnull.BlockerIndexer); ok { return nil, errors.New("block indexing is disabled") diff --git a/rpc/core/blocks_test.go b/rpc/core/blocks_test.go index cf9513907..b22f3d0f3 100644 --- a/rpc/core/blocks_test.go +++ b/rpc/core/blocks_test.go @@ -4,17 +4,15 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" tmstate "github.com/consideritdone/landslidecore/proto/tendermint/state" ctypes "github.com/consideritdone/landslidecore/rpc/core/types" rpctypes "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestBlockchainInfo(t *testing.T) { @@ -25,7 +23,6 @@ func TestBlockchainInfo(t *testing.T) { resultLength int64 wantErr bool }{ - // min > max {0, 0, 0, 0, 10, 0, true}, // min set to 1 {0, 1, 0, 0, 10, 0, true}, // max set to height (0) diff --git a/rpc/core/consensus.go b/rpc/core/consensus.go index 54ca7eafe..876c00239 100644 --- a/rpc/core/consensus.go +++ b/rpc/core/consensus.go @@ -42,7 +42,8 @@ func Validators(ctx *rpctypes.Context, heightPtr *int64, pagePtr, perPagePtr *in BlockHeight: height, Validators: v, Count: len(v), - Total: totalCount}, nil + Total: totalCount, + }, nil } // DumpConsensusState dumps consensus state. @@ -75,7 +76,8 @@ func DumpConsensusState(ctx *rpctypes.Context) (*ctypes.ResultDumpConsensusState } return &ctypes.ResultDumpConsensusState{ RoundState: roundState, - Peers: peerStates}, nil + Peers: peerStates, + }, nil } // ConsensusState returns a concise summary of the consensus state. @@ -104,5 +106,6 @@ func ConsensusParams(ctx *rpctypes.Context, heightPtr *int64) (*ctypes.ResultCon } return &ctypes.ResultConsensusParams{ BlockHeight: height, - ConsensusParams: consensusParams}, nil + ConsensusParams: consensusParams, + }, nil } diff --git a/rpc/core/env.go b/rpc/core/env.go index de27bae1e..fc2fe582b 100644 --- a/rpc/core/env.go +++ b/rpc/core/env.go @@ -33,10 +33,8 @@ const ( genesisChunkSize = 16 * 1024 * 1024 // 16 ) -var ( - // set by Node - env *Environment -) +// set by Node +var env *Environment // SetEnvironment sets up the given Environment. // It will race if multiple Node call SetEnvironment. diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go index ca9e6774a..5a53f2078 100644 --- a/rpc/core/mempool.go +++ b/rpc/core/mempool.go @@ -21,7 +21,6 @@ import ( // More: https://docs.tendermint.com/master/rpc/#/Tx/broadcast_tx_async func BroadcastTxAsync(ctx *rpctypes.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { err := env.Mempool.CheckTx(tx, nil, mempl.TxInfo{}) - if err != nil { return nil, err } @@ -143,7 +142,8 @@ func UnconfirmedTxs(ctx *rpctypes.Context, limitPtr *int) (*ctypes.ResultUnconfi Count: len(txs), Total: env.Mempool.Size(), TotalBytes: env.Mempool.TxsBytes(), - Txs: txs}, nil + Txs: txs, + }, nil } // NumUnconfirmedTxs gets number of unconfirmed transactions. @@ -152,7 +152,8 @@ func NumUnconfirmedTxs(ctx *rpctypes.Context) (*ctypes.ResultUnconfirmedTxs, err return &ctypes.ResultUnconfirmedTxs{ Count: env.Mempool.Size(), Total: env.Mempool.Size(), - TotalBytes: env.Mempool.TxsBytes()}, nil + TotalBytes: env.Mempool.TxsBytes(), + }, nil } // CheckTx checks the transaction without executing it. The transaction won't diff --git a/rpc/core/net.go b/rpc/core/net.go index 391afc8d2..33bb3edd1 100644 --- a/rpc/core/net.go +++ b/rpc/core/net.go @@ -53,7 +53,8 @@ func UnsafeDialSeeds(ctx *rpctypes.Context, seeds []string) (*ctypes.ResultDialS // UnsafeDialPeers dials the given peers (comma-separated id@IP:PORT), // optionally making them persistent. func UnsafeDialPeers(ctx *rpctypes.Context, peers []string, persistent, unconditional, private bool) ( - *ctypes.ResultDialPeers, error) { + *ctypes.ResultDialPeers, error, +) { if len(peers) == 0 { return &ctypes.ResultDialPeers{}, errors.New("no peers provided") } diff --git a/rpc/core/net_test.go b/rpc/core/net_test.go index 5a4c94347..a994d8c23 100644 --- a/rpc/core/net_test.go +++ b/rpc/core/net_test.go @@ -3,13 +3,12 @@ package core import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/p2p" rpctypes "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUnsafeDialSeeds(t *testing.T) { diff --git a/rpc/core/tx.go b/rpc/core/tx.go index 62fdf7976..19757b7cd 100644 --- a/rpc/core/tx.go +++ b/rpc/core/tx.go @@ -61,7 +61,6 @@ func TxSearch( pagePtr, perPagePtr *int, orderBy string, ) (*ctypes.ResultTxSearch, error) { - // if index is disabled, return error if _, ok := env.TxIndexer.(*null.TxIndex); ok { return nil, errors.New("transaction indexing is disabled") diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 90850406f..b7117ba42 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -58,8 +58,8 @@ type ResultBlockResults struct { // NewResultCommit is a helper to initialize the ResultCommit with // the embedded struct func NewResultCommit(header *types.Header, commit *types.Commit, - canonical bool) *ResultCommit { - + canonical bool, +) *ResultCommit { return &ResultCommit{ SignedHeader: types.SignedHeader{ Header: header, diff --git a/rpc/core/types/responses_test.go b/rpc/core/types/responses_test.go index afb378a74..3e68b7f94 100644 --- a/rpc/core/types/responses_test.go +++ b/rpc/core/types/responses_test.go @@ -3,9 +3,8 @@ package coretypes import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/p2p" + "github.com/stretchr/testify/assert" ) func TestStatusIndexer(t *testing.T) { diff --git a/rpc/grpc/api.go b/rpc/grpc/api.go index 616631604..06cbdb7f9 100644 --- a/rpc/grpc/api.go +++ b/rpc/grpc/api.go @@ -8,8 +8,7 @@ import ( rpctypes "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" ) -type broadcastAPI struct { -} +type broadcastAPI struct{} func (bapi *broadcastAPI) Ping(ctx context.Context, req *RequestPing) (*ResponsePing, error) { // kvstore so we can check if the server is up diff --git a/rpc/grpc/client_server.go b/rpc/grpc/client_server.go index e13614b00..b1bc0c738 100644 --- a/rpc/grpc/client_server.go +++ b/rpc/grpc/client_server.go @@ -3,10 +3,9 @@ package coregrpc import ( "net" + tmnet "github.com/consideritdone/landslidecore/libs/net" "golang.org/x/net/context" "google.golang.org/grpc" - - tmnet "github.com/consideritdone/landslidecore/libs/net" ) // Config is an gRPC server configuration. diff --git a/rpc/grpc/grpc_test.go b/rpc/grpc/grpc_test.go index 270bef3d9..8bc45268f 100644 --- a/rpc/grpc/grpc_test.go +++ b/rpc/grpc/grpc_test.go @@ -5,11 +5,10 @@ import ( "os" "testing" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/kvstore" core_grpc "github.com/consideritdone/landslidecore/rpc/grpc" rpctest "github.com/consideritdone/landslidecore/rpc/test" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { diff --git a/rpc/jsonrpc/client/decode.go b/rpc/jsonrpc/client/decode.go index 2969c463e..49342daad 100644 --- a/rpc/jsonrpc/client/decode.go +++ b/rpc/jsonrpc/client/decode.go @@ -14,7 +14,6 @@ func unmarshalResponseBytes( expectedID types.JSONRPCIntID, result interface{}, ) (interface{}, error) { - // Read response. If rpc/core/types is imported, the result will unmarshal // into the correct type. response := &types.RPCResponse{} @@ -43,10 +42,7 @@ func unmarshalResponseBytesArray( expectedIDs []types.JSONRPCIntID, results []interface{}, ) ([]interface{}, error) { - - var ( - responses []types.RPCResponse - ) + var responses []types.RPCResponse if err := json.Unmarshal(responseBytes, &responses); err != nil { return nil, fmt.Errorf("error unmarshalling: %w", err) diff --git a/rpc/jsonrpc/client/http_json_client.go b/rpc/jsonrpc/client/http_json_client.go index 67baf561e..650b2e678 100644 --- a/rpc/jsonrpc/client/http_json_client.go +++ b/rpc/jsonrpc/client/http_json_client.go @@ -136,8 +136,10 @@ var _ HTTPClient = (*Client)(nil) // Both Client and RequestBatch can facilitate calls to the JSON // RPC endpoint. -var _ Caller = (*Client)(nil) -var _ Caller = (*RequestBatch)(nil) +var ( + _ Caller = (*Client)(nil) + _ Caller = (*RequestBatch)(nil) +) // New returns a Client pointed at the given address. // An error is returned on invalid remote. The function panics when remote is nil. diff --git a/rpc/jsonrpc/client/http_uri_client.go b/rpc/jsonrpc/client/http_uri_client.go index 669dcf550..8227234b4 100644 --- a/rpc/jsonrpc/client/http_uri_client.go +++ b/rpc/jsonrpc/client/http_uri_client.go @@ -52,8 +52,8 @@ func NewURI(remote string) (*URIClient, error) { // Call issues a POST form HTTP request. func (c *URIClient) Call(ctx context.Context, method string, - params map[string]interface{}, result interface{}) (interface{}, error) { - + params map[string]interface{}, result interface{}, +) (interface{}, error) { values, err := argsToURLValues(params) if err != nil { return nil, fmt.Errorf("failed to encode params: %w", err) diff --git a/rpc/jsonrpc/client/ws_client.go b/rpc/jsonrpc/client/ws_client.go index 74094356f..4bf51c410 100644 --- a/rpc/jsonrpc/client/ws_client.go +++ b/rpc/jsonrpc/client/ws_client.go @@ -9,13 +9,12 @@ import ( "sync" "time" - "github.com/gorilla/websocket" - metrics "github.com/rcrowley/go-metrics" - tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/libs/service" tmsync "github.com/consideritdone/landslidecore/libs/sync" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/gorilla/websocket" + metrics "github.com/rcrowley/go-metrics" ) const ( diff --git a/rpc/jsonrpc/client/ws_client_test.go b/rpc/jsonrpc/client/ws_client_test.go index 50c89af75..b6da65995 100644 --- a/rpc/jsonrpc/client/ws_client_test.go +++ b/rpc/jsonrpc/client/ws_client_test.go @@ -9,12 +9,11 @@ import ( "testing" "time" - "github.com/gorilla/websocket" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" tmsync "github.com/consideritdone/landslidecore/libs/sync" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" ) var wsCallTimeout = 5 * time.Second diff --git a/rpc/jsonrpc/jsonrpc_test.go b/rpc/jsonrpc/jsonrpc_test.go index 08a7384aa..8aee3840d 100644 --- a/rpc/jsonrpc/jsonrpc_test.go +++ b/rpc/jsonrpc/jsonrpc_test.go @@ -12,17 +12,15 @@ import ( "testing" "time" - "github.com/go-kit/log/term" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - tmbytes "github.com/consideritdone/landslidecore/libs/bytes" "github.com/consideritdone/landslidecore/libs/log" tmrand "github.com/consideritdone/landslidecore/libs/rand" - client "github.com/consideritdone/landslidecore/rpc/jsonrpc/client" server "github.com/consideritdone/landslidecore/rpc/jsonrpc/server" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Client and Server should work over tcp or unix sockets @@ -37,9 +35,7 @@ const ( testVal = "acbd" ) -var ( - ctx = context.Background() -) +var ctx = context.Background() type ResultEcho struct { Value string `json:"value"` @@ -233,7 +229,6 @@ func echoViaWS(cl *client.WSClient, val string) (string, error) { msg := <-cl.ResponsesCh if msg.Error != nil { return "", err - } result := new(ResultEcho) err = json.Unmarshal(msg.Result, result) @@ -255,7 +250,6 @@ func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) { msg := <-cl.ResponsesCh if msg.Error != nil { return []byte{}, msg.Error - } result := new(ResultEchoBytes) err = json.Unmarshal(msg.Result, result) diff --git a/rpc/jsonrpc/server/http_json_handler.go b/rpc/jsonrpc/server/http_json_handler.go index b51f1f231..18c2cbfc6 100644 --- a/rpc/jsonrpc/server/http_json_handler.go +++ b/rpc/jsonrpc/server/http_json_handler.go @@ -128,7 +128,6 @@ func mapParamsToArgs( params map[string]json.RawMessage, argsOffset int, ) ([]reflect.Value, error) { - values := make([]reflect.Value, len(rpcFunc.argNames)) for i, argName := range rpcFunc.argNames { argType := rpcFunc.args[i+argsOffset] @@ -153,7 +152,6 @@ func arrayParamsToArgs( params []json.RawMessage, argsOffset int, ) ([]reflect.Value, error) { - if len(rpcFunc.argNames) != len(params) { return nil, fmt.Errorf("expected %v parameters (%v), got %v (%v)", len(rpcFunc.argNames), rpcFunc.argNames, len(params), params) diff --git a/rpc/jsonrpc/server/http_json_handler_test.go b/rpc/jsonrpc/server/http_json_handler_test.go index 4bb942de0..41eab015a 100644 --- a/rpc/jsonrpc/server/http_json_handler_test.go +++ b/rpc/jsonrpc/server/http_json_handler_test.go @@ -9,11 +9,10 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testMux() *http.ServeMux { diff --git a/rpc/jsonrpc/server/http_server.go b/rpc/jsonrpc/server/http_server.go index 6ea215817..9f63fe92b 100644 --- a/rpc/jsonrpc/server/http_server.go +++ b/rpc/jsonrpc/server/http_server.go @@ -13,10 +13,9 @@ import ( "strings" "time" - "golang.org/x/net/netutil" - "github.com/consideritdone/landslidecore/libs/log" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "golang.org/x/net/netutil" ) // Config is a RPC server configuration. @@ -164,7 +163,6 @@ func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler // Without this, Chrome & Firefox were retrying aborted ajax requests, // at least to my localhost. if e := recover(); e != nil { - // If RPCResponse if res, ok := e.(types.RPCResponse); ok { if wErr := WriteRPCResponseHTTP(rww, res); wErr != nil { diff --git a/rpc/jsonrpc/server/http_server_test.go b/rpc/jsonrpc/server/http_server_test.go index a0e1c5079..368696b42 100644 --- a/rpc/jsonrpc/server/http_server_test.go +++ b/rpc/jsonrpc/server/http_server_test.go @@ -13,11 +13,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type sampleResult struct { diff --git a/rpc/jsonrpc/server/parse_test.go b/rpc/jsonrpc/server/parse_test.go index fbc13277a..c03655a01 100644 --- a/rpc/jsonrpc/server/parse_test.go +++ b/rpc/jsonrpc/server/parse_test.go @@ -7,10 +7,9 @@ import ( "strconv" "testing" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/libs/bytes" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/stretchr/testify/assert" ) func TestParseJSONMap(t *testing.T) { diff --git a/rpc/jsonrpc/server/ws_handler.go b/rpc/jsonrpc/server/ws_handler.go index 49bec69ea..6ad030b2b 100644 --- a/rpc/jsonrpc/server/ws_handler.go +++ b/rpc/jsonrpc/server/ws_handler.go @@ -10,11 +10,10 @@ import ( "runtime/debug" "time" - "github.com/gorilla/websocket" - "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/libs/service" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/gorilla/websocket" ) // WebSocket handler diff --git a/rpc/jsonrpc/server/ws_handler_test.go b/rpc/jsonrpc/server/ws_handler_test.go index 0a83480b5..2eb704847 100644 --- a/rpc/jsonrpc/server/ws_handler_test.go +++ b/rpc/jsonrpc/server/ws_handler_test.go @@ -5,11 +5,10 @@ import ( "net/http/httptest" "testing" - "github.com/gorilla/websocket" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/libs/log" types "github.com/consideritdone/landslidecore/rpc/jsonrpc/types" + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" ) func TestWebsocketManagerHandler(t *testing.T) { diff --git a/rpc/jsonrpc/types/types.go b/rpc/jsonrpc/types/types.go index 96e8fe189..14ec3406d 100644 --- a/rpc/jsonrpc/types/types.go +++ b/rpc/jsonrpc/types/types.go @@ -99,7 +99,7 @@ func (req RPCRequest) String() string { } func MapToRequest(id jsonrpcid, method string, params map[string]interface{}) (RPCRequest, error) { - var paramsMap = make(map[string]json.RawMessage, len(params)) + paramsMap := make(map[string]json.RawMessage, len(params)) for name, value := range params { valueJSON, err := tmjson.Marshal(value) if err != nil { @@ -117,7 +117,7 @@ func MapToRequest(id jsonrpcid, method string, params map[string]interface{}) (R } func ArrayToRequest(id jsonrpcid, method string, params []interface{}) (RPCRequest, error) { - var paramsMap = make([]json.RawMessage, len(params)) + paramsMap := make([]json.RawMessage, len(params)) for i, value := range params { valueJSON, err := tmjson.Marshal(value) if err != nil { @@ -199,7 +199,7 @@ func NewRPCSuccessResponse(id jsonrpcid, res interface{}) RPCResponse { return RPCResponse{JSONRPC: "2.0", ID: id, Result: rawMsg} } -func NewRPCErrorResponse(id jsonrpcid, code int, msg string, data string) RPCResponse { +func NewRPCErrorResponse(id jsonrpcid, code int, msg, data string) RPCResponse { return RPCResponse{ JSONRPC: "2.0", ID: id, diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 8689a20b7..1d86677cb 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -9,9 +9,8 @@ import ( "time" abci "github.com/consideritdone/landslidecore/abci/types" - "github.com/consideritdone/landslidecore/libs/log" - cfg "github.com/consideritdone/landslidecore/config" + "github.com/consideritdone/landslidecore/libs/log" tmnet "github.com/consideritdone/landslidecore/libs/net" nm "github.com/consideritdone/landslidecore/node" "github.com/consideritdone/landslidecore/p2p" @@ -29,11 +28,13 @@ type Options struct { recreateConfig bool } -var globalConfig *cfg.Config -var defaultOptions = Options{ - suppressStdout: false, - recreateConfig: false, -} +var ( + globalConfig *cfg.Config + defaultOptions = Options{ + suppressStdout: false, + recreateConfig: false, + } +) func waitForRPC() { laddr := GetConfig().RPC.ListenAddress diff --git a/scripts/json2wal/main.go b/scripts/json2wal/main.go index a118126a8..f3c3023b8 100644 --- a/scripts/json2wal/main.go +++ b/scripts/json2wal/main.go @@ -31,7 +31,7 @@ func main() { } defer f.Close() - walFile, err := os.OpenFile(os.Args[2], os.O_EXCL|os.O_WRONLY|os.O_CREATE, 0666) + walFile, err := os.OpenFile(os.Args[2], os.O_EXCL|os.O_WRONLY|os.O_CREATE, 0o666) if err != nil { panic(fmt.Errorf("failed to open WAL file: %v", err)) } diff --git a/state/execution.go b/state/execution.go index 66c5fa6c3..fac907425 100644 --- a/state/execution.go +++ b/state/execution.go @@ -96,7 +96,6 @@ func (blockExec *BlockExecutor) CreateProposalBlock( state State, commit *types.Commit, proposerAddr []byte, ) (*types.Block, *types.PartSet) { - maxBytes := state.ConsensusParams.Block.MaxBytes maxGas := state.ConsensusParams.Block.MaxGas @@ -131,7 +130,6 @@ func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) e func (blockExec *BlockExecutor) ApplyBlock( state State, blockID types.BlockID, block *types.Block, ) (State, int64, error) { - if err := validateBlock(state, block); err != nil { return state, 0, ErrInvalidBlock(err) } @@ -263,7 +261,7 @@ func execBlockOnProxyApp( store Store, initialHeight int64, ) (*tmstate.ABCIResponses, error) { - var validTxs, invalidTxs = 0, 0 + validTxs, invalidTxs := 0, 0 txIndex := 0 abciResponses := new(tmstate.ABCIResponses) @@ -335,7 +333,8 @@ func execBlockOnProxyApp( } func getBeginBlockValidatorInfo(block *types.Block, store Store, - initialHeight int64) abci.LastCommitInfo { + initialHeight int64, +) abci.LastCommitInfo { voteInfos := make([]abci.VoteInfo, block.LastCommit.Size()) // Initial block -> LastCommitInfo.Votes are empty. // Remember that the first LastCommit is intentionally empty, so it makes @@ -375,7 +374,8 @@ func getBeginBlockValidatorInfo(block *types.Block, store Store, } func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate, - params tmproto.ValidatorParams) error { + params tmproto.ValidatorParams, +) error { for _, valUpdate := range abciUpdates { if valUpdate.GetPower() < 0 { return fmt.Errorf("voting power can't be negative %v", valUpdate) @@ -407,7 +407,6 @@ func updateState( abciResponses *tmstate.ABCIResponses, validatorUpdates []*types.Validator, ) (State, error) { - // Copy the valset so we can apply changes from EndBlock // and update s.LastValidators and s.Validators. nValSet := state.NextValidators.Copy() diff --git a/state/execution_test.go b/state/execution_test.go index 94a111330..41f180e29 100644 --- a/state/execution_test.go +++ b/state/execution_test.go @@ -5,10 +5,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" @@ -24,6 +20,9 @@ import ( "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" ) var ( diff --git a/state/export_test.go b/state/export_test.go index a5344e64b..1f354597e 100644 --- a/state/export_test.go +++ b/state/export_test.go @@ -1,12 +1,11 @@ package state import ( - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" tmstate "github.com/consideritdone/landslidecore/proto/tendermint/state" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + dbm "github.com/tendermint/tm-db" ) // diff --git a/state/helpers_test.go b/state/helpers_test.go index 33154ad75..6820c22c0 100644 --- a/state/helpers_test.go +++ b/state/helpers_test.go @@ -5,8 +5,6 @@ import ( "fmt" "time" - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" @@ -17,6 +15,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + dbm "github.com/tendermint/tm-db" ) type paramsChangeTestCase struct { @@ -37,7 +36,8 @@ func makeAndCommitGoodBlock( proposerAddr []byte, blockExec *sm.BlockExecutor, privVals map[string]types.PrivValidator, - evidence []types.Evidence) (sm.State, types.BlockID, *types.Commit, error) { + evidence []types.Evidence, +) (sm.State, types.BlockID, *types.Commit, error) { // A good block passes state, blockID, err := makeAndApplyGoodBlock(state, height, lastCommit, proposerAddr, blockExec, evidence) if err != nil { @@ -53,13 +53,16 @@ func makeAndCommitGoodBlock( } func makeAndApplyGoodBlock(state sm.State, height int64, lastCommit *types.Commit, proposerAddr []byte, - blockExec *sm.BlockExecutor, evidence []types.Evidence) (sm.State, types.BlockID, error) { + blockExec *sm.BlockExecutor, evidence []types.Evidence, +) (sm.State, types.BlockID, error) { block, _ := state.MakeBlock(height, makeTxs(height), lastCommit, evidence, proposerAddr) if err := blockExec.ValidateBlock(state, block); err != nil { return state, types.BlockID{}, err } - blockID := types.BlockID{Hash: block.Hash(), - PartSetHeader: types.PartSetHeader{Total: 3, Hash: tmrand.Bytes(32)}} + blockID := types.BlockID{ + Hash: block.Hash(), + PartSetHeader: types.PartSetHeader{Total: 3, Hash: tmrand.Bytes(32)}, + } state, _, err := blockExec.ApplyBlock(state, blockID, block) if err != nil { return state, types.BlockID{}, err @@ -154,7 +157,6 @@ func makeHeaderPartsResponsesValPubKeyChange( state sm.State, pubkey crypto.PubKey, ) (types.Header, types.BlockID, *tmstate.ABCIResponses) { - block := makeBlock(state, state.LastBlockHeight+1) abciResponses := &tmstate.ABCIResponses{ BeginBlock: &abci.ResponseBeginBlock{}, @@ -178,7 +180,6 @@ func makeHeaderPartsResponsesValPowerChange( state sm.State, power int64, ) (types.Header, types.BlockID, *tmstate.ABCIResponses) { - block := makeBlock(state, state.LastBlockHeight+1) abciResponses := &tmstate.ABCIResponses{ BeginBlock: &abci.ResponseBeginBlock{}, @@ -202,7 +203,6 @@ func makeHeaderPartsResponsesParams( state sm.State, params tmproto.ConsensusParams, ) (types.Header, types.BlockID, *tmstate.ABCIResponses) { - block := makeBlock(state, state.LastBlockHeight+1) abciResponses := &tmstate.ABCIResponses{ BeginBlock: &abci.ResponseBeginBlock{}, @@ -255,7 +255,10 @@ func (app *testApp) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock { ValidatorUpdates: app.ValidatorUpdates, ConsensusParamUpdates: &abci.ConsensusParams{ Version: &tmproto.VersionParams{ - AppVersion: 1}}} + AppVersion: 1, + }, + }, + } } func (app *testApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx { diff --git a/state/indexer/block/kv/kv.go b/state/indexer/block/kv/kv.go index f77391306..e8d064f7b 100644 --- a/state/indexer/block/kv/kv.go +++ b/state/indexer/block/kv/kv.go @@ -8,13 +8,12 @@ import ( "strconv" "strings" - "github.com/google/orderedcode" - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/pubsub/query" "github.com/consideritdone/landslidecore/state/indexer" "github.com/consideritdone/landslidecore/types" + "github.com/google/orderedcode" + dbm "github.com/tendermint/tm-db" ) var _ indexer.BlockIndexer = (*BlockerIndexer)(nil) @@ -223,7 +222,6 @@ func (idx *BlockerIndexer) matchRange( filteredHeights map[string][]byte, firstRun bool, ) (map[string][]byte, error) { - // A previous match was attempted but resulted in no matches, so we return // no matches (assuming AND operand). if !firstRun && len(filteredHeights) == 0 { @@ -331,7 +329,6 @@ func (idx *BlockerIndexer) match( filteredHeights map[string][]byte, firstRun bool, ) (map[string][]byte, error) { - // A previous match was attempted but resulted in no matches, so we return // no matches (assuming AND operand). if !firstRun && len(filteredHeights) == 0 { diff --git a/state/indexer/block/kv/kv_test.go b/state/indexer/block/kv/kv_test.go index b9b2bb8f6..cf9570579 100644 --- a/state/indexer/block/kv/kv_test.go +++ b/state/indexer/block/kv/kv_test.go @@ -5,13 +5,12 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/require" - db "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/pubsub/query" blockidxkv "github.com/consideritdone/landslidecore/state/indexer/block/kv" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/require" + db "github.com/tendermint/tm-db" ) func TestBlockIndexer(t *testing.T) { diff --git a/state/indexer/block/kv/util.go b/state/indexer/block/kv/util.go index 7c87aefe4..d6e8c17a2 100644 --- a/state/indexer/block/kv/util.go +++ b/state/indexer/block/kv/util.go @@ -5,10 +5,9 @@ import ( "fmt" "strconv" - "github.com/google/orderedcode" - "github.com/consideritdone/landslidecore/libs/pubsub/query" "github.com/consideritdone/landslidecore/types" + "github.com/google/orderedcode" ) func intInSlice(a int, list []int) bool { diff --git a/state/indexer/sink/psql/psql.go b/state/indexer/sink/psql/psql.go index 7cba9fe94..34ef35bc7 100644 --- a/state/indexer/sink/psql/psql.go +++ b/state/indexer/sink/psql/psql.go @@ -9,11 +9,10 @@ import ( "strings" "time" - "github.com/gogo/protobuf/proto" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/pubsub/query" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" ) const ( @@ -222,7 +221,6 @@ INSERT INTO `+tableTxResults+` (block_id, index, created_at, tx_hash, tx_result) return fmt.Errorf("indexing transaction events: %w", err) } return nil - }); err != nil { return err } diff --git a/state/indexer/sink/psql/psql_test.go b/state/indexer/sink/psql/psql_test.go index e9995b1fc..d8205ec65 100644 --- a/state/indexer/sink/psql/psql_test.go +++ b/state/indexer/sink/psql/psql_test.go @@ -13,17 +13,15 @@ import ( "time" "github.com/adlio/schema" + abci "github.com/consideritdone/landslidecore/abci/types" + "github.com/consideritdone/landslidecore/types" "github.com/gogo/protobuf/proto" + // Register the Postgres database driver. + _ "github.com/lib/pq" "github.com/ory/dockertest" "github.com/ory/dockertest/docker" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - abci "github.com/consideritdone/landslidecore/abci/types" - "github.com/consideritdone/landslidecore/types" - - // Register the Postgres database driver. - _ "github.com/lib/pq" ) var ( diff --git a/state/rollback_test.go b/state/rollback_test.go index f3df8d69d..9d83f2b62 100644 --- a/state/rollback_test.go +++ b/state/rollback_test.go @@ -4,9 +4,6 @@ import ( "crypto/rand" "testing" - "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" tmstate "github.com/consideritdone/landslidecore/proto/tendermint/state" @@ -15,6 +12,8 @@ import ( "github.com/consideritdone/landslidecore/state/mocks" "github.com/consideritdone/landslidecore/types" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestRollback(t *testing.T) { diff --git a/state/state.go b/state/state.go index 97cac484a..225643e76 100644 --- a/state/state.go +++ b/state/state.go @@ -7,14 +7,13 @@ import ( "io/ioutil" "time" - "github.com/gogo/protobuf/proto" - tmstate "github.com/consideritdone/landslidecore/proto/tendermint/state" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" tmversion "github.com/consideritdone/landslidecore/proto/tendermint/version" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" "github.com/consideritdone/landslidecore/version" + "github.com/gogo/protobuf/proto" ) // database keys @@ -82,7 +81,6 @@ type State struct { // Copy makes a copy of the State for mutating. func (state State) Copy() State { - return State{ Version: state.Version, ChainID: state.ChainID, @@ -239,7 +237,6 @@ func (state State) MakeBlock( evidence []types.Evidence, proposerAddress []byte, ) (*types.Block, *types.PartSet) { - // Build base block with block data. block := types.MakeBlock(height, txs, commit, evidence) diff --git a/state/state_test.go b/state/state_test.go index 8d8a33b84..f5c283a06 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -8,11 +8,6 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto/ed25519" @@ -22,6 +17,9 @@ import ( tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) // setupTestCase does setup common to all test cases. @@ -146,7 +144,8 @@ func TestABCIResponsesSaveLoad2(t *testing.T) { }, []*abci.ResponseDeliverTx{ {Code: 32, Data: []byte("Hello")}, - }}, + }, + }, 2: { []*abci.ResponseDeliverTx{ {Code: 383}, @@ -164,7 +163,8 @@ func TestABCIResponsesSaveLoad2(t *testing.T) { {Type: "type1", Attributes: []abci.EventAttribute{{Key: []byte("a"), Value: []byte("1")}}}, {Type: "type2", Attributes: []abci.EventAttribute{{Key: []byte("build"), Value: []byte("stuff")}}}, }}, - }}, + }, + }, 3: { nil, nil, @@ -304,7 +304,6 @@ func TestOneValidatorChangesSaveLoad(t *testing.T) { } func TestProposerFrequency(t *testing.T) { - // some explicit test cases testCases := []struct { powers []int64 @@ -934,7 +933,7 @@ func TestManyValidatorChangesSaveLoad(t *testing.T) { require.NoError(t, err) _, valOld := state.Validators.GetByIndex(0) - var pubkeyOld = valOld.PubKey + pubkeyOld := valOld.PubKey pubkey := ed25519.GenPrivKey().PubKey() // Swap the first validator with a new one (validator set size stays the same). diff --git a/state/store.go b/state/store.go index 4ab41eba1..b9f4b5996 100644 --- a/state/store.go +++ b/state/store.go @@ -4,15 +4,14 @@ import ( "errors" "fmt" - "github.com/gogo/protobuf/proto" - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" tmmath "github.com/consideritdone/landslidecore/libs/math" tmos "github.com/consideritdone/landslidecore/libs/os" tmstate "github.com/consideritdone/landslidecore/proto/tendermint/state" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + dbm "github.com/tendermint/tm-db" ) const ( @@ -223,7 +222,7 @@ func (store dbStore) Bootstrap(state State) error { // encoding not preserving ordering: https://github.com/consideritdone/landslidecore/issues/4567 // This will cause some old states to be left behind when doing incremental partial prunes, // specifically older checkpoints and LastHeightChanged targets. -func (store dbStore) PruneStates(from int64, to int64) error { +func (store dbStore) PruneStates(from, to int64) error { if from <= 0 || to <= 0 { return fmt.Errorf("from height %v and to height %v must be greater than 0", from, to) } @@ -369,7 +368,6 @@ func (store dbStore) LoadABCIResponses(height int64) (*tmstate.ABCIResponses, er return nil, err } if len(buf) == 0 { - return nil, ErrNoABCIResponsesForHeight{height} } diff --git a/state/store_test.go b/state/store_test.go index 45a4e56c1..77d55344e 100644 --- a/state/store_test.go +++ b/state/store_test.go @@ -5,11 +5,6 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto" @@ -19,6 +14,9 @@ import ( tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestStoreLoadValidators(t *testing.T) { @@ -98,10 +96,18 @@ func TestPruneStates(t *testing.T) { "error when from == to": {100, 3, 3, true, nil, nil, nil}, "error when to does not exist": {100, 1, 101, true, nil, nil, nil}, "prune all": {100, 1, 100, false, []int64{93, 100}, []int64{95, 100}, []int64{100}}, - "prune some": {10, 2, 8, false, []int64{1, 3, 8, 9, 10}, - []int64{1, 5, 8, 9, 10}, []int64{1, 8, 9, 10}}, - "prune across checkpoint": {100001, 1, 100001, false, []int64{99993, 100000, 100001}, - []int64{99995, 100001}, []int64{100001}}, + "prune some": { + 10, 2, 8, false, + []int64{1, 3, 8, 9, 10}, + []int64{1, 5, 8, 9, 10}, + []int64{1, 8, 9, 10}, + }, + "prune across checkpoint": { + 100001, 1, 100001, false, + []int64{99993, 100000, 100001}, + []int64{99995, 100001}, + []int64{100001}, + }, } for name, tc := range testcases { tc := tc diff --git a/state/tx_filter_test.go b/state/tx_filter_test.go index 9d58e98c5..beb247070 100644 --- a/state/tx_filter_test.go +++ b/state/tx_filter_test.go @@ -4,14 +4,12 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - tmrand "github.com/consideritdone/landslidecore/libs/rand" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestTxFilter(t *testing.T) { diff --git a/state/txindex/indexer_service.go b/state/txindex/indexer_service.go index 569991601..1859d7452 100644 --- a/state/txindex/indexer_service.go +++ b/state/txindex/indexer_service.go @@ -30,7 +30,6 @@ func NewIndexerService( blockIdxr indexer.BlockIndexer, eventBus *types.EventBus, ) *IndexerService { - is := &IndexerService{txIdxr: txIdxr, blockIdxr: blockIdxr, eventBus: eventBus} is.BaseService = *service.NewBaseService(nil, "IndexerService", is) return is diff --git a/state/txindex/indexer_service_test.go b/state/txindex/indexer_service_test.go index 412602ef0..30fa4e188 100644 --- a/state/txindex/indexer_service_test.go +++ b/state/txindex/indexer_service_test.go @@ -4,15 +4,14 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - db "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/log" blockidxkv "github.com/consideritdone/landslidecore/state/indexer/block/kv" "github.com/consideritdone/landslidecore/state/txindex" "github.com/consideritdone/landslidecore/state/txindex/kv" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/require" + db "github.com/tendermint/tm-db" ) func TestIndexerServiceIndexesBlocks(t *testing.T) { diff --git a/state/txindex/kv/kv.go b/state/txindex/kv/kv.go index 23884065a..1ca657a0f 100644 --- a/state/txindex/kv/kv.go +++ b/state/txindex/kv/kv.go @@ -8,14 +8,13 @@ import ( "strconv" "strings" - "github.com/gogo/protobuf/proto" - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/pubsub/query" "github.com/consideritdone/landslidecore/state/indexer" "github.com/consideritdone/landslidecore/state/txindex" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + dbm "github.com/tendermint/tm-db" ) const ( diff --git a/state/txindex/kv/kv_bench_test.go b/state/txindex/kv/kv_bench_test.go index b1c8a3c79..429ad463e 100644 --- a/state/txindex/kv/kv_bench_test.go +++ b/state/txindex/kv/kv_bench_test.go @@ -7,11 +7,10 @@ import ( "io/ioutil" "testing" - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/pubsub/query" "github.com/consideritdone/landslidecore/types" + dbm "github.com/tendermint/tm-db" ) func BenchmarkTxSearch(b *testing.B) { diff --git a/state/txindex/kv/kv_test.go b/state/txindex/kv/kv_test.go index 63a5c25f1..e83c686d1 100644 --- a/state/txindex/kv/kv_test.go +++ b/state/txindex/kv/kv_test.go @@ -7,17 +7,15 @@ import ( "os" "testing" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - db "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/libs/pubsub/query" tmrand "github.com/consideritdone/landslidecore/libs/rand" "github.com/consideritdone/landslidecore/state/txindex" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + db "github.com/tendermint/tm-db" ) func TestTxIndex(t *testing.T) { diff --git a/state/validation_test.go b/state/validation_test.go index 8b61b4332..c653aa244 100644 --- a/state/validation_test.go +++ b/state/validation_test.go @@ -4,10 +4,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/crypto/tmhash" @@ -18,6 +14,9 @@ import ( "github.com/consideritdone/landslidecore/state/mocks" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" ) const validationTestsStopHeight int64 = 10 diff --git a/statesync/chunks.go b/statesync/chunks.go index 58d13006c..627c3aa35 100644 --- a/statesync/chunks.go +++ b/statesync/chunks.go @@ -84,7 +84,7 @@ func (q *chunkQueue) Add(chunk *chunk) (bool, error) { } path := filepath.Join(q.dir, strconv.FormatUint(uint64(chunk.Index), 10)) - err := ioutil.WriteFile(path, chunk.Chunk, 0600) + err := ioutil.WriteFile(path, chunk.Chunk, 0o600) if err != nil { return false, fmt.Errorf("failed to save chunk %v to file %v: %w", chunk.Index, path, err) } diff --git a/statesync/chunks_test.go b/statesync/chunks_test.go index 306346f38..352cadede 100644 --- a/statesync/chunks_test.go +++ b/statesync/chunks_test.go @@ -5,10 +5,9 @@ import ( "os" "testing" + "github.com/consideritdone/landslidecore/p2p" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/consideritdone/landslidecore/p2p" ) func setupChunkQueue(t *testing.T) (*chunkQueue, func()) { diff --git a/statesync/messages.go b/statesync/messages.go index f605c13dd..a2be4a563 100644 --- a/statesync/messages.go +++ b/statesync/messages.go @@ -4,9 +4,8 @@ import ( "errors" "fmt" - "github.com/gogo/protobuf/proto" - ssproto "github.com/consideritdone/landslidecore/proto/tendermint/statesync" + "github.com/gogo/protobuf/proto" ) const ( diff --git a/statesync/messages_test.go b/statesync/messages_test.go index 69d1f0593..15055b5a7 100644 --- a/statesync/messages_test.go +++ b/statesync/messages_test.go @@ -4,11 +4,10 @@ import ( "encoding/hex" "testing" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/require" - ssproto "github.com/consideritdone/landslidecore/proto/tendermint/statesync" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/require" ) func TestValidateMsg(t *testing.T) { @@ -26,49 +25,63 @@ func TestValidateMsg(t *testing.T) { "ChunkResponse valid": { &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{1}}, - true}, + true, + }, "ChunkResponse 0 height": { &ssproto.ChunkResponse{Height: 0, Format: 1, Index: 1, Chunk: []byte{1}}, - false}, + false, + }, "ChunkResponse 0 format": { &ssproto.ChunkResponse{Height: 1, Format: 0, Index: 1, Chunk: []byte{1}}, - true}, + true, + }, "ChunkResponse 0 chunk": { &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 0, Chunk: []byte{1}}, - true}, + true, + }, "ChunkResponse empty body": { &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{}}, - true}, + true, + }, "ChunkResponse nil body": { &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: nil}, - false}, + false, + }, "ChunkResponse missing": { &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true}, - true}, + true, + }, "ChunkResponse missing with empty": { &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true, Chunk: []byte{}}, - true}, + true, + }, "ChunkResponse missing with body": { &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true, Chunk: []byte{1}}, - false}, + false, + }, "SnapshotsRequest valid": {&ssproto.SnapshotsRequest{}, true}, "SnapshotsResponse valid": { &ssproto.SnapshotsResponse{Height: 1, Format: 1, Chunks: 2, Hash: []byte{1}}, - true}, + true, + }, "SnapshotsResponse 0 height": { &ssproto.SnapshotsResponse{Height: 0, Format: 1, Chunks: 2, Hash: []byte{1}}, - false}, + false, + }, "SnapshotsResponse 0 format": { &ssproto.SnapshotsResponse{Height: 1, Format: 0, Chunks: 2, Hash: []byte{1}}, - true}, + true, + }, "SnapshotsResponse 0 chunks": { &ssproto.SnapshotsResponse{Height: 1, Format: 1, Hash: []byte{1}}, - false}, + false, + }, "SnapshotsResponse no hash": { &ssproto.SnapshotsResponse{Height: 1, Format: 1, Chunks: 2, Hash: []byte{}}, - false}, + false, + }, } for name, tc := range testcases { tc := tc @@ -85,7 +98,6 @@ func TestValidateMsg(t *testing.T) { //nolint:lll // ignore line length func TestStateSyncVectors(t *testing.T) { - testCases := []struct { testName string msg proto.Message diff --git a/statesync/reactor.go b/statesync/reactor.go index 58ef3697f..4a4affbf8 100644 --- a/statesync/reactor.go +++ b/statesync/reactor.go @@ -47,7 +47,6 @@ func NewReactor( connQuery proxy.AppConnQuery, tempDir string, ) *Reactor { - r := &Reactor{ cfg: cfg, conn: conn, diff --git a/statesync/reactor_test.go b/statesync/reactor_test.go index f39978ff7..d86243cb6 100644 --- a/statesync/reactor_test.go +++ b/statesync/reactor_test.go @@ -4,16 +4,15 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/p2p" p2pmocks "github.com/consideritdone/landslidecore/p2p/mocks" ssproto "github.com/consideritdone/landslidecore/proto/tendermint/statesync" proxymocks "github.com/consideritdone/landslidecore/proxy/mocks" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" ) func TestReactor_Receive_ChunkRequest(t *testing.T) { @@ -25,11 +24,13 @@ func TestReactor_Receive_ChunkRequest(t *testing.T) { "chunk is returned": { &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1}, []byte{1, 2, 3}, - &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{1, 2, 3}}}, + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{1, 2, 3}}, + }, "empty chunk is returned, as nil": { &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1}, []byte{}, - &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: nil}}, + &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: nil}, + }, "nil (missing) chunk is returned as missing": { &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1}, nil, diff --git a/statesync/snapshots.go b/statesync/snapshots.go index 268e0e7b2..25a46e03c 100644 --- a/statesync/snapshots.go +++ b/statesync/snapshots.go @@ -146,7 +146,7 @@ func (p *snapshotPool) GetPeers(snapshot *snapshot) []p2p.Peer { peers = append(peers, peer) } // sort results, for testability (otherwise order is random, so tests randomly fail) - sort.Slice(peers, func(a int, b int) bool { + sort.Slice(peers, func(a, b int) bool { return peers[a].ID() < peers[b].ID() }) return peers diff --git a/statesync/snapshots_test.go b/statesync/snapshots_test.go index 424665a98..2596ee4b9 100644 --- a/statesync/snapshots_test.go +++ b/statesync/snapshots_test.go @@ -3,11 +3,10 @@ package statesync import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/p2p" p2pmocks "github.com/consideritdone/landslidecore/p2p/mocks" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSnapshot_Key(t *testing.T) { diff --git a/statesync/stateprovider.go b/statesync/stateprovider.go index 41ad19878..2e5c418db 100644 --- a/statesync/stateprovider.go +++ b/statesync/stateprovider.go @@ -6,8 +6,6 @@ import ( "strings" "time" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/libs/log" tmsync "github.com/consideritdone/landslidecore/libs/sync" "github.com/consideritdone/landslidecore/light" @@ -20,6 +18,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" "github.com/consideritdone/landslidecore/version" + dbm "github.com/tendermint/tm-db" ) //go:generate mockery --case underscore --name StateProvider diff --git a/statesync/syncer.go b/statesync/syncer.go index af2a152ba..45028ff4b 100644 --- a/statesync/syncer.go +++ b/statesync/syncer.go @@ -73,7 +73,6 @@ func newSyncer( stateProvider StateProvider, tempDir string, ) *syncer { - return &syncer{ logger: logger, stateProvider: stateProvider, diff --git a/statesync/syncer_test.go b/statesync/syncer_test.go index 184793590..7d6ccfc89 100644 --- a/statesync/syncer_test.go +++ b/statesync/syncer_test.go @@ -5,10 +5,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/log" @@ -24,6 +20,9 @@ import ( "github.com/consideritdone/landslidecore/statesync/mocks" "github.com/consideritdone/landslidecore/types" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" ) const testAppVersion = 9 @@ -427,7 +426,8 @@ func TestSyncer_applyChunks_Results(t *testing.T) { connSnapshot.On("ApplySnapshotChunkSync", abci.RequestApplySnapshotChunk{ Index: 0, Chunk: body, }).Once().Return(&abci.ResponseApplySnapshotChunk{ - Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil) + Result: abci.ResponseApplySnapshotChunk_ACCEPT, + }, nil) } err = syncer.applyChunks(chunks) diff --git a/store/store.go b/store/store.go index c83226ccc..6fd6b61b3 100644 --- a/store/store.go +++ b/store/store.go @@ -4,13 +4,12 @@ import ( "fmt" "strconv" - "github.com/gogo/protobuf/proto" - dbm "github.com/tendermint/tm-db" - tmsync "github.com/consideritdone/landslidecore/libs/sync" tmstore "github.com/consideritdone/landslidecore/proto/tendermint/store" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + dbm "github.com/tendermint/tm-db" ) /* @@ -91,7 +90,7 @@ func (bs *BlockStore) LoadBaseMeta() *types.BlockMeta { // LoadBlock returns the block with the given height. // If no block is found for that height, it returns nil. func (bs *BlockStore) LoadBlock(height int64) *types.Block { - var blockMeta = bs.LoadBlockMeta(height) + blockMeta := bs.LoadBlockMeta(height) if blockMeta == nil { return nil } @@ -136,7 +135,6 @@ func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block { s := string(bz) height, err := strconv.ParseInt(s, 10, 64) - if err != nil { panic(fmt.Sprintf("failed to extract height from %s: %v", s, err)) } @@ -147,7 +145,7 @@ func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block { // from the block at the given height. // If no part is found for the given height and index, it returns nil. func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part { - var pbpart = new(tmproto.Part) + pbpart := new(tmproto.Part) bz, err := bs.db.Get(calcBlockPartKey(height, index)) if err != nil { @@ -172,9 +170,8 @@ func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part { // LoadBlockMeta returns the BlockMeta for the given height. // If no block is found for the given height, it returns nil. func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta { - var pbbm = new(tmproto.BlockMeta) + pbbm := new(tmproto.BlockMeta) bz, err := bs.db.Get(calcBlockMetaKey(height)) - if err != nil { panic(err) } @@ -201,7 +198,7 @@ func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta { // and it comes from the block.LastCommit for `height+1`. // If no commit is found for the given height, it returns nil. func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit { - var pbc = new(tmproto.Commit) + pbc := new(tmproto.Commit) bz, err := bs.db.Get(calcBlockCommitKey(height)) if err != nil { panic(err) @@ -224,7 +221,7 @@ func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit { // This is useful when we've seen a commit, but there has not yet been // a new block at `height + 1` that includes this commit in its block.LastCommit. func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit { - var pbc = new(tmproto.Commit) + pbc := new(tmproto.Commit) bz, err := bs.db.Get(calcSeenCommitKey(height)) if err != nil { panic(err) diff --git a/store/store_test.go b/store/store_test.go index 8da35b4e7..97e80c876 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -9,11 +9,6 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/libs/log" @@ -24,6 +19,10 @@ import ( "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" "github.com/consideritdone/landslidecore/version" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) // A cleanupFunc cleans up any config / test files created for a particular @@ -69,7 +68,6 @@ func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFu } func TestLoadBlockStoreState(t *testing.T) { - type blockStoreTest struct { testName string bss *tmstore.BlockStoreState @@ -77,8 +75,10 @@ func TestLoadBlockStoreState(t *testing.T) { } testCases := []blockStoreTest{ - {"success", &tmstore.BlockStoreState{Base: 100, Height: 1000}, - tmstore.BlockStoreState{Base: 100, Height: 1000}}, + { + "success", &tmstore.BlockStoreState{Base: 100, Height: 1000}, + tmstore.BlockStoreState{Base: 100, Height: 1000}, + }, {"empty", &tmstore.BlockStoreState{}, tmstore.BlockStoreState{}}, {"no base", &tmstore.BlockStoreState{Height: 1000}, tmstore.BlockStoreState{Base: 1, Height: 1000}}, } @@ -226,7 +226,8 @@ func TestBlockStoreSaveLoadBlock(t *testing.T) { Height: 5, ChainID: "block_test", Time: tmtime.Now(), - ProposerAddress: tmrand.Bytes(crypto.AddressSize)}, + ProposerAddress: tmrand.Bytes(crypto.AddressSize), + }, makeTestCommit(5, tmtime.Now()), ), parts: validPartSet, @@ -328,8 +329,10 @@ func TestBlockStoreSaveLoadBlock(t *testing.T) { require.NoError(t, err) } bCommit := bs.LoadBlockCommit(commitHeight) - return &quad{block: bBlock, seenCommit: bSeenCommit, commit: bCommit, - meta: bBlockMeta}, nil + return &quad{ + block: bBlock, seenCommit: bSeenCommit, commit: bCommit, + meta: bBlockMeta, + }, nil }) if subStr := tuple.wantPanic; subStr != "" { @@ -533,7 +536,9 @@ func TestLoadBlockMeta(t *testing.T) { // 3. A good blockMeta serialized and saved to the DB should be retrievable meta := &types.BlockMeta{Header: types.Header{ Version: tmversion.Consensus{ - Block: version.BlockProtocol, App: 0}, Height: 1, ProposerAddress: tmrand.Bytes(crypto.AddressSize)}} + Block: version.BlockProtocol, App: 0, + }, Height: 1, ProposerAddress: tmrand.Bytes(crypto.AddressSize), + }} pbm := meta.ToProto() err = db.Set(calcBlockMetaKey(height), mustEncode(pbm)) require.NoError(t, err) @@ -576,7 +581,7 @@ func TestBlockFetchAtHeight(t *testing.T) { require.Nil(t, blockAtHeightPlus2, "expecting an unsuccessful load of Height()+2") } -func doFn(fn func() (interface{}, error)) (res interface{}, err error, panicErr error) { +func doFn(fn func() (interface{}, error)) (res interface{}, err, panicErr error) { defer func() { if r := recover(); r != nil { switch e := r.(type) { diff --git a/test/app/grpc_client.go b/test/app/grpc_client.go index 739f938d3..bba3e5abe 100644 --- a/test/app/grpc_client.go +++ b/test/app/grpc_client.go @@ -1,12 +1,11 @@ package main import ( + "context" "encoding/hex" "fmt" "os" - "context" - tmjson "github.com/consideritdone/landslidecore/libs/json" coregrpc "github.com/consideritdone/landslidecore/rpc/grpc" ) diff --git a/test/e2e/app/snapshots.go b/test/e2e/app/snapshots.go index 6dfbbc052..cfd7770c2 100644 --- a/test/e2e/app/snapshots.go +++ b/test/e2e/app/snapshots.go @@ -30,7 +30,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 { @@ -72,7 +72,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 = ioutil.WriteFile(newFile, bz, 0644) // nolint: gosec + err = ioutil.WriteFile(newFile, bz, 0o644) // nolint: gosec if err != nil { return err } @@ -93,7 +93,7 @@ func (s *SnapshotStore) Create(state *State) (abci.Snapshot, error) { Hash: hashItems(state.Values), Chunks: byteChunks(bz), } - err = ioutil.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0644) + err = ioutil.WriteFile(filepath.Join(s.dir, fmt.Sprintf("%v.json", state.Height)), bz, 0o644) if err != nil { return abci.Snapshot{}, err } @@ -117,7 +117,7 @@ func (s *SnapshotStore) List() ([]*abci.Snapshot, error) { } // LoadChunk loads a snapshot chunk. -func (s *SnapshotStore) LoadChunk(height uint64, format uint32, chunk uint32) ([]byte, error) { +func (s *SnapshotStore) LoadChunk(height uint64, format, chunk uint32) ([]byte, error) { s.RLock() defer s.RUnlock() for _, snapshot := range s.metadata { diff --git a/test/e2e/app/state.go b/test/e2e/app/state.go index 1ede6fb4c..429465c6e 100644 --- a/test/e2e/app/state.go +++ b/test/e2e/app/state.go @@ -1,4 +1,4 @@ -//nolint: gosec +// nolint: gosec package app import ( @@ -13,8 +13,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 { @@ -82,7 +84,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 = ioutil.WriteFile(newFile, bz, 0644) + err = ioutil.WriteFile(newFile, bz, 0o644) if err != nil { return fmt.Errorf("failed to write state to %q: %w", s.currentFile, err) } diff --git a/test/e2e/generator/generate.go b/test/e2e/generator/generate.go index ccc4a3e48..fb1aabe98 100644 --- a/test/e2e/generator/generate.go +++ b/test/e2e/generator/generate.go @@ -202,7 +202,7 @@ func generateTestnet(r *rand.Rand, opt map[string]interface{}) (e2e.Manifest, er // here, since we need to know the overall network topology and startup // sequencing. func generateNode( - r *rand.Rand, mode e2e.Mode, startAt int64, initialHeight int64, forceArchive bool, + r *rand.Rand, mode e2e.Mode, startAt, initialHeight int64, forceArchive bool, ) *e2e.ManifestNode { node := e2e.ManifestNode{ Mode: string(mode), diff --git a/test/e2e/generator/main.go b/test/e2e/generator/main.go index a769daa72..e763b52d4 100644 --- a/test/e2e/generator/main.go +++ b/test/e2e/generator/main.go @@ -8,9 +8,8 @@ import ( "os" "path/filepath" - "github.com/spf13/cobra" - "github.com/consideritdone/landslidecore/libs/log" + "github.com/spf13/cobra" ) const ( @@ -58,7 +57,7 @@ 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 } diff --git a/test/e2e/node/config.go b/test/e2e/node/config.go index d13e9c9dc..946820179 100644 --- a/test/e2e/node/config.go +++ b/test/e2e/node/config.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/BurntSushi/toml" - "github.com/consideritdone/landslidecore/test/e2e/app" ) diff --git a/test/e2e/node/main.go b/test/e2e/node/main.go index c7193852c..6c262d76b 100644 --- a/test/e2e/node/main.go +++ b/test/e2e/node/main.go @@ -11,8 +11,6 @@ import ( "strings" "time" - "github.com/spf13/viper" - "github.com/consideritdone/landslidecore/abci/server" "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto/ed25519" @@ -32,6 +30,7 @@ import ( e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" mcs "github.com/consideritdone/landslidecore/test/maverick/consensus" maverick "github.com/consideritdone/landslidecore/test/maverick/node" + "github.com/spf13/viper" ) var logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) diff --git a/test/e2e/pkg/testnet.go b/test/e2e/pkg/testnet.go index d7b13a982..9413d10f9 100644 --- a/test/e2e/pkg/testnet.go +++ b/test/e2e/pkg/testnet.go @@ -26,9 +26,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" diff --git a/test/e2e/runner/exec.go b/test/e2e/runner/exec.go index f790f7fc1..15204c73d 100644 --- a/test/e2e/runner/exec.go +++ b/test/e2e/runner/exec.go @@ -1,4 +1,4 @@ -//nolint: gosec +// nolint: gosec package main import ( diff --git a/test/e2e/runner/main.go b/test/e2e/runner/main.go index af11c2b6c..e5aa616b0 100644 --- a/test/e2e/runner/main.go +++ b/test/e2e/runner/main.go @@ -6,15 +6,12 @@ import ( "os" "strconv" - "github.com/spf13/cobra" - "github.com/consideritdone/landslidecore/libs/log" e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" + "github.com/spf13/cobra" ) -var ( - logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) -) +var logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) func main() { NewCLI().Run() diff --git a/test/e2e/runner/setup.go b/test/e2e/runner/setup.go index 1b9b09e77..6ff369642 100644 --- a/test/e2e/runner/setup.go +++ b/test/e2e/runner/setup.go @@ -18,7 +18,6 @@ import ( "time" "github.com/BurntSushi/toml" - "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/p2p" @@ -52,7 +51,7 @@ func Setup(testnet *e2e.Testnet) error { if err != nil { return err } - err = ioutil.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0644) + err = ioutil.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0o644) 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 = ioutil.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0644) + err = ioutil.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0o644) if err != nil { return err } @@ -403,5 +402,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 ioutil.WriteFile(cfgPath, bz, 0644) + return ioutil.WriteFile(cfgPath, bz, 0o644) } diff --git a/test/e2e/tests/app_test.go b/test/e2e/tests/app_test.go index a39a617aa..9ba3df86b 100644 --- a/test/e2e/tests/app_test.go +++ b/test/e2e/tests/app_test.go @@ -7,11 +7,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Tests that any initial state given in genesis has made it into the app. @@ -92,6 +91,5 @@ func TestApp_Tx(t *testing.T) { require.NoError(t, err) assert.Equal(t, key, string(abciResp.Response.Key)) assert.Equal(t, value, string(abciResp.Response.Value)) - }) } diff --git a/test/e2e/tests/block_test.go b/test/e2e/tests/block_test.go index 14e3d31e4..825f1d6cf 100644 --- a/test/e2e/tests/block_test.go +++ b/test/e2e/tests/block_test.go @@ -3,10 +3,9 @@ package e2e_test import ( "testing" + e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" ) // Tests that block headers are identical across nodes where present. diff --git a/test/e2e/tests/e2e_test.go b/test/e2e/tests/e2e_test.go index c8f4b03c9..2923965b0 100644 --- a/test/e2e/tests/e2e_test.go +++ b/test/e2e/tests/e2e_test.go @@ -7,12 +7,11 @@ import ( "sync" "testing" - "github.com/stretchr/testify/require" - rpchttp "github.com/consideritdone/landslidecore/rpc/client/http" rpctypes "github.com/consideritdone/landslidecore/rpc/core/types" e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/require" ) func init() { diff --git a/test/e2e/tests/evidence_test.go b/test/e2e/tests/evidence_test.go index 52adb6676..12a1935a0 100644 --- a/test/e2e/tests/evidence_test.go +++ b/test/e2e/tests/evidence_test.go @@ -4,10 +4,9 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/require" - e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/require" ) // assert that all nodes that have blocks at the height of a misbehavior has evidence diff --git a/test/e2e/tests/net_test.go b/test/e2e/tests/net_test.go index 9138e4044..372b96e83 100644 --- a/test/e2e/tests/net_test.go +++ b/test/e2e/tests/net_test.go @@ -3,9 +3,8 @@ package e2e_test import ( "testing" - "github.com/stretchr/testify/require" - e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" + "github.com/stretchr/testify/require" ) // Tests that all nodes have peered with each other, regardless of discovery method. diff --git a/test/e2e/tests/validator_test.go b/test/e2e/tests/validator_test.go index 34c99f254..2283619cb 100644 --- a/test/e2e/tests/validator_test.go +++ b/test/e2e/tests/validator_test.go @@ -4,10 +4,9 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/require" - e2e "github.com/consideritdone/landslidecore/test/e2e/pkg" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/require" ) // Tests that validator sets are available and correct according to diff --git a/test/fuzz/mempool/checktx.go b/test/fuzz/mempool/checktx.go index e028cac61..67790ad87 100644 --- a/test/fuzz/mempool/checktx.go +++ b/test/fuzz/mempool/checktx.go @@ -21,7 +21,7 @@ func init() { cfg := config.DefaultMempoolConfig() cfg.Broadcast = false - mempool = mempl.NewCListMempool(cfg, appConnMem, 0) + mempool = mempl.NewCListMempool(cfg, appConnMem, 0, nil) } func Fuzz(data []byte) int { diff --git a/test/fuzz/p2p/addrbook/init-corpus/main.go b/test/fuzz/p2p/addrbook/init-corpus/main.go index 9601de509..cc0d2ea98 100644 --- a/test/fuzz/p2p/addrbook/init-corpus/main.go +++ b/test/fuzz/p2p/addrbook/init-corpus/main.go @@ -27,7 +27,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) } @@ -49,7 +49,7 @@ func initCorpus(baseDir string) { log.Fatalf("can't marshal %v: %v", addr, err) } - if err := ioutil.WriteFile(filename, bz, 0644); err != nil { + if err := ioutil.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 3d5927ffc..4758b3052 100644 --- a/test/fuzz/p2p/pex/init-corpus/main.go +++ b/test/fuzz/p2p/pex/init-corpus/main.go @@ -26,7 +26,7 @@ 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} @@ -73,7 +73,7 @@ func initCorpus(rootDir string) { filename := filepath.Join(rootDir, "corpus", fmt.Sprintf("%d", n)) - if err := ioutil.WriteFile(filename, bz, 0644); err != nil { + if err := ioutil.WriteFile(filename, bz, 0o644); err != nil { log.Fatalf("can't write %X to %q: %v", bz, filename, err) } diff --git a/test/fuzz/p2p/pex/reactor_receive.go b/test/fuzz/p2p/pex/reactor_receive.go index 9520e07ba..8a33875ea 100644 --- a/test/fuzz/p2p/pex/reactor_receive.go +++ b/test/fuzz/p2p/pex/reactor_receive.go @@ -26,7 +26,6 @@ func init() { pexR.SetLogger(log.NewNopLogger()) peer := newFuzzPeer() pexR.AddPeer(peer) - } func Fuzz(data []byte) int { @@ -55,18 +54,20 @@ func newFuzzPeer() *fuzzPeer { return fp } -var privKey = ed25519.GenPrivKey() -var nodeID = p2p.PubKeyToID(privKey.PubKey()) -var defaultNodeInfo = p2p.DefaultNodeInfo{ - ProtocolVersion: p2p.NewProtocolVersion( - version.P2PProtocol, - version.BlockProtocol, - 0, - ), - DefaultNodeID: nodeID, - ListenAddr: "0.0.0.0:98992", - Moniker: "foo1", -} +var ( + privKey = ed25519.GenPrivKey() + nodeID = p2p.PubKeyToID(privKey.PubKey()) + defaultNodeInfo = p2p.DefaultNodeInfo{ + ProtocolVersion: p2p.NewProtocolVersion( + version.P2PProtocol, + version.BlockProtocol, + 0, + ), + DefaultNodeID: nodeID, + ListenAddr: "0.0.0.0:98992", + Moniker: "foo1", + } +) func (fp *fuzzPeer) FlushStop() {} func (fp *fuzzPeer) ID() p2p.ID { return nodeID } diff --git a/test/fuzz/p2p/secret_connection/init-corpus/main.go b/test/fuzz/p2p/secret_connection/init-corpus/main.go index 635f2d99f..70a5d5c35 100644 --- a/test/fuzz/p2p/secret_connection/init-corpus/main.go +++ b/test/fuzz/p2p/secret_connection/init-corpus/main.go @@ -21,7 +21,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) } @@ -39,7 +39,7 @@ func initCorpus(baseDir string) { for i, datum := range data { filename := filepath.Join(corpusDir, fmt.Sprintf("%d", i)) - if err := ioutil.WriteFile(filename, []byte(datum), 0644); err != nil { + if err := ioutil.WriteFile(filename, []byte(datum), 0o644); err != nil { log.Fatalf("can't write %v to %q: %v", datum, filename, err) } diff --git a/test/fuzz/p2p/secret_connection/read_write.go b/test/fuzz/p2p/secret_connection/read_write.go index c6ea991c8..28ee25480 100644 --- a/test/fuzz/p2p/secret_connection/read_write.go +++ b/test/fuzz/p2p/secret_connection/read_write.go @@ -63,7 +63,7 @@ func makeSecretConnPair() (fooSecConn, barSecConn *sc.SecretConnection) { ) // Make connections from both sides in parallel. - var trs, ok = async.Parallel( + trs, ok := async.Parallel( func(_ int) (val interface{}, abort bool, err error) { fooSecConn, err = sc.MakeSecretConnection(fooConn, fooPrvKey) if err != nil { diff --git a/test/maverick/consensus/misbehavior.go b/test/maverick/consensus/misbehavior.go index 5d9ed9378..41569dca9 100644 --- a/test/maverick/consensus/misbehavior.go +++ b/test/maverick/consensus/misbehavior.go @@ -50,7 +50,6 @@ func DoublePrevoteMisbehavior() Misbehavior { b := DefaultMisbehavior() b.Name = "double-prevote" b.EnterPrevote = func(cs *State, height int64, round int32) { - // If a block is locked, prevote that. if cs.LockedBlock != nil { cs.Logger.Debug("enterPrevote: already locked on a block, prevoting locked block") @@ -333,7 +332,6 @@ func defaultReceivePrevote(cs *State, vote *types.Vote) { cs.enterPrevote(height, cs.Round) } } - } func defaultReceivePrecommit(cs *State, vote *types.Vote) { diff --git a/test/maverick/consensus/reactor.go b/test/maverick/consensus/reactor.go index 12f254480..727d4f058 100644 --- a/test/maverick/consensus/reactor.go +++ b/test/maverick/consensus/reactor.go @@ -7,8 +7,6 @@ import ( "sync" "time" - "github.com/gogo/protobuf/proto" - tmcon "github.com/consideritdone/landslidecore/consensus" cstypes "github.com/consideritdone/landslidecore/consensus/types" "github.com/consideritdone/landslidecore/libs/bits" @@ -22,6 +20,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/gogo/protobuf/proto" ) const ( @@ -420,7 +419,6 @@ func (conR *Reactor) subscribeToBroadcastEvents() { }); err != nil { conR.Logger.Error("Error adding listener for events", "err", err) } - } func (conR *Reactor) unsubscribeFromBroadcastEvents() { @@ -586,8 +584,8 @@ OUTER_LOOP: } func (conR *Reactor) gossipDataForCatchup(logger log.Logger, rs *cstypes.RoundState, - prs *cstypes.PeerRoundState, ps *PeerState, peer p2p.Peer) { - + prs *cstypes.PeerRoundState, ps *PeerState, peer p2p.Peer, +) { if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok { // Ensure that the peer's PartSetHeader is correct blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height) @@ -631,7 +629,7 @@ func (conR *Reactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) { logger := conR.Logger.With("peer", peer) // Simple hack to throttle logs upon sleep. - var sleeping = 0 + sleeping := 0 OUTER_LOOP: for { @@ -702,7 +700,6 @@ func (conR *Reactor) gossipVotesForHeight( prs *cstypes.PeerRoundState, ps *PeerState, ) bool { - // If there are lastCommits to send... if prs.Step == cstypes.RoundStepNewHeight { if ps.PickSendVote(rs.LastCommit) { @@ -1069,8 +1066,7 @@ func (ps *PeerState) PickVoteToSend(votes types.VoteSetReader) (vote *types.Vote return nil, false } - height, round, votesType, size := - votes.GetHeight(), votes.GetRound(), tmproto.SignedMsgType(votes.Type()), votes.Size() + height, round, votesType, size := votes.GetHeight(), votes.GetRound(), tmproto.SignedMsgType(votes.Type()), votes.Size() // Lazily set data using 'votes'. if votes.IsCommit() { diff --git a/test/maverick/consensus/replay.go b/test/maverick/consensus/replay.go index 26e3cab0c..13db590d5 100644 --- a/test/maverick/consensus/replay.go +++ b/test/maverick/consensus/replay.go @@ -92,7 +92,6 @@ func (cs *State) readReplayMessage(msg *tmcon.TimedWALMessage, newStepSub types. // Replay only those messages since the last block. `timeoutRoutine` should // run concurrently to read off tickChan. func (cs *State) catchupReplay(csHeight int64) error { - // Set replayMode to true so we don't log signing errors. cs.replayMode = true defer func() { cs.replayMode = false }() @@ -210,8 +209,8 @@ type Handshaker struct { } func NewHandshaker(stateStore sm.Store, state sm.State, - store sm.BlockStore, genDoc *types.GenesisDoc) *Handshaker { - + store sm.BlockStore, genDoc *types.GenesisDoc, +) *Handshaker { return &Handshaker{ stateStore: stateStore, initialState: state, @@ -240,7 +239,6 @@ func (h *Handshaker) NBlocks() int { // TODO: retry the handshake/replay if it fails ? func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { - // Handshake is done via ABCI Info on the query conn. res, err := proxyApp.Query().InfoSync(proxy.RequestInfo) if err != nil { @@ -392,13 +390,11 @@ func (h *Handshaker) ReplayBlocks( if appBlockHeight < storeBlockHeight { // the app is behind, so replay blocks, but no need to go through WAL (state is already synced to store) return h.replayBlocks(state, proxyApp, appBlockHeight, storeBlockHeight, false) - } else if appBlockHeight == storeBlockHeight { // We're good! assertAppHashEqualsOneFromState(appHash, state) return appHash, nil } - } else if storeBlockHeight == stateBlockHeight+1 { // We saved the block in the store but haven't updated the state, // so we'll need to replay a block using the WAL. @@ -428,7 +424,6 @@ func (h *Handshaker) ReplayBlocks( state, err = h.replayBlock(state, storeBlockHeight, mockApp) return state.AppHash, err } - } panic(fmt.Sprintf("uncovered case! appHeight: %d, storeHeight: %d, stateHeight: %d", @@ -440,7 +435,8 @@ func (h *Handshaker) replayBlocks( proxyApp proxy.AppConns, appBlockHeight, storeBlockHeight int64, - mutateState bool) ([]byte, error) { + mutateState bool, +) ([]byte, error) { // App is further behind than it should be, so we need to replay blocks. // We replay all blocks from appBlockHeight+1. // diff --git a/test/maverick/consensus/replay_file.go b/test/maverick/consensus/replay_file.go index e99c02cda..c774291e7 100644 --- a/test/maverick/consensus/replay_file.go +++ b/test/maverick/consensus/replay_file.go @@ -10,8 +10,6 @@ import ( "strconv" "strings" - dbm "github.com/tendermint/tm-db" - cfg "github.com/consideritdone/landslidecore/config" tmcon "github.com/consideritdone/landslidecore/consensus" "github.com/consideritdone/landslidecore/libs/log" @@ -20,6 +18,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" + dbm "github.com/tendermint/tm-db" ) const ( @@ -41,7 +40,6 @@ func RunReplayFile(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console // Replay msgs in file or start the console func (cs *State) ReplayFile(file string, console bool) error { - if cs.IsRunning() { return errors.New("cs is already running, cannot replay") } @@ -65,7 +63,7 @@ func (cs *State) ReplayFile(file string, console bool) error { }() // just open the file for reading, no need to use wal - fp, err := os.OpenFile(file, os.O_RDONLY, 0600) + fp, err := os.OpenFile(file, os.O_RDONLY, 0o600) if err != nil { return err } @@ -138,7 +136,7 @@ func (pb *playback) replayReset(count int, newStepSub types.Subscription) error if err := pb.fp.Close(); err != nil { return err } - fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0600) + fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0o600) if err != nil { return err } diff --git a/test/maverick/consensus/state.go b/test/maverick/consensus/state.go index b7c22a1a7..f4f491ecc 100644 --- a/test/maverick/consensus/state.go +++ b/test/maverick/consensus/state.go @@ -11,8 +11,6 @@ import ( "sync" "time" - "github.com/gogo/protobuf/proto" - cfg "github.com/consideritdone/landslidecore/config" tmcon "github.com/consideritdone/landslidecore/consensus" cstypes "github.com/consideritdone/landslidecore/consensus/types" @@ -29,6 +27,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/gogo/protobuf/proto" ) // State handles execution of the consensus algorithm. @@ -343,12 +342,12 @@ func (cs *State) enterPrecommit(height int64, round int32) { } else { defaultEnterPrecommit(cs, height, round) } - } func (cs *State) addVote( vote *types.Vote, - peerID p2p.ID) (added bool, err error) { + peerID p2p.ID, +) (added bool, err error) { cs.Logger.Debug( "addVote", "voteHeight", @@ -439,9 +438,7 @@ var ( //----------------------------------------------------------------------------- -var ( - msgQueueSize = 1000 -) +var msgQueueSize = 1000 // msgs from the reactor which may update the state type msgInfo struct { @@ -723,7 +720,6 @@ func (cs *State) AddVote(vote *types.Vote, peerID p2p.ID) (added bool, err error // SetProposal inputs a proposal. func (cs *State) SetProposal(proposal *types.Proposal, peerID p2p.ID) error { - if peerID == "" { cs.internalMsgQueue <- msgInfo{&tmcon.ProposalMessage{Proposal: proposal}, ""} } else { @@ -736,7 +732,6 @@ func (cs *State) SetProposal(proposal *types.Proposal, peerID p2p.ID) error { // AddProposalBlockPart inputs a part of the proposal block. func (cs *State) AddProposalBlockPart(height int64, round int32, part *types.Part, peerID p2p.ID) error { - if peerID == "" { cs.internalMsgQueue <- msgInfo{&tmcon.BlockPartMessage{Height: height, Round: round, Part: part}, ""} } else { @@ -1064,7 +1059,6 @@ func (cs *State) handleTimeout(ti timeoutInfo, rs cstypes.RoundState) { default: panic(fmt.Sprintf("Invalid timeout step: %v", ti.Step)) } - } func (cs *State) handleTxsAvailable() { @@ -1240,7 +1234,6 @@ func (cs *State) isProposalComplete() bool { } // if this is false the proposer is lying or we haven't received the POL yet return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority() - } // Create the next block to propose and return it. Returns nil block upon error. @@ -1697,7 +1690,7 @@ func (cs *State) addProposalBlockPart(msg *tmcon.BlockPartMessage, peerID p2p.ID return added, err } - var pbb = new(tmproto.Block) + pbb := new(tmproto.Block) err = proto.Unmarshal(bz, pbb) if err != nil { return added, err diff --git a/test/maverick/consensus/ticker.go b/test/maverick/consensus/ticker.go index 489e9b046..be9295b01 100644 --- a/test/maverick/consensus/ticker.go +++ b/test/maverick/consensus/ticker.go @@ -7,9 +7,7 @@ import ( "github.com/consideritdone/landslidecore/libs/service" ) -var ( - tickTockBufferSize = 10 -) +var tickTockBufferSize = 10 // TimeoutTicker is a timer that schedules timeouts // conditional on the height/round/step in the timeoutInfo. @@ -50,7 +48,6 @@ func NewTimeoutTicker() TimeoutTicker { // OnStart implements service.Service. It starts the timeout routine. func (t *timeoutTicker) OnStart() error { - go t.timeoutRoutine() return nil diff --git a/test/maverick/consensus/wal.go b/test/maverick/consensus/wal.go index db89a6ca7..04a5530bf 100644 --- a/test/maverick/consensus/wal.go +++ b/test/maverick/consensus/wal.go @@ -9,8 +9,6 @@ import ( "path/filepath" "time" - "github.com/gogo/protobuf/proto" - // tmjson "github.com/consideritdone/landslidecore/libs/json" tmcon "github.com/consideritdone/landslidecore/consensus" auto "github.com/consideritdone/landslidecore/libs/autofile" @@ -19,6 +17,7 @@ import ( "github.com/consideritdone/landslidecore/libs/service" tmcons "github.com/consideritdone/landslidecore/proto/tendermint/consensus" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/gogo/protobuf/proto" ) const ( @@ -58,7 +57,7 @@ var _ tmcon.WAL = &BaseWAL{} // NewWAL returns a new write-ahead logger based on `baseWAL`, which implements // WAL. It's flushed and synced to disk every 2s and once when stopped. func NewWAL(walFile string, groupOptions ...func(*auto.Group)) (*BaseWAL, error) { - err := tmos.EnsureDir(filepath.Dir(walFile), 0700) + err := tmos.EnsureDir(filepath.Dir(walFile), 0o700) if err != nil { return nil, fmt.Errorf("failed to ensure WAL directory is in place: %w", err) } @@ -199,7 +198,8 @@ type WALSearchOptions struct { // CONTRACT: caller must close group reader. func (wal *BaseWAL) SearchForEndHeight( height int64, - options *tmcon.WALSearchOptions) (rd io.ReadCloser, found bool, err error) { + options *tmcon.WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { var ( msg *tmcon.TimedWALMessage gr *auto.GroupReader @@ -373,7 +373,7 @@ func (dec *WALDecoder) Decode() (*tmcon.TimedWALMessage, error) { return nil, DataCorruptionError{fmt.Errorf("checksums do not match: read: %v, actual: %v", crc, actualCRC)} } - var res = new(tmcons.TimedWALMessage) + res := new(tmcons.TimedWALMessage) err = proto.Unmarshal(data, res) if err != nil { return nil, DataCorruptionError{fmt.Errorf("failed to decode data: %v", err)} @@ -399,7 +399,8 @@ func (nilWAL) Write(m tmcon.WALMessage) error { return nil } func (nilWAL) WriteSync(m tmcon.WALMessage) error { return nil } func (nilWAL) FlushAndSync() error { return nil } func (nilWAL) SearchForEndHeight(height int64, - options *tmcon.WALSearchOptions) (rd io.ReadCloser, found bool, err error) { + options *tmcon.WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { return nil, false, nil } func (nilWAL) Start() error { return nil } diff --git a/test/maverick/consensus/wal_generator.go b/test/maverick/consensus/wal_generator.go index 4506c2679..c71cf6429 100644 --- a/test/maverick/consensus/wal_generator.go +++ b/test/maverick/consensus/wal_generator.go @@ -9,8 +9,6 @@ import ( "testing" "time" - db "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/kvstore" cfg "github.com/consideritdone/landslidecore/config" tmcon "github.com/consideritdone/landslidecore/consensus" @@ -21,6 +19,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" + db "github.com/tendermint/tm-db" ) // WALGenerateNBlocks generates a consensus WAL. It does this by spinning up a @@ -221,7 +220,8 @@ func (w *byteBufferWAL) FlushAndSync() error { return nil } func (w *byteBufferWAL) SearchForEndHeight( height int64, - options *tmcon.WALSearchOptions) (rd io.ReadCloser, found bool, err error) { + options *tmcon.WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { return nil, false, nil } diff --git a/test/maverick/main.go b/test/maverick/main.go index 973553705..362182114 100644 --- a/test/maverick/main.go +++ b/test/maverick/main.go @@ -5,9 +5,6 @@ import ( "os" "path/filepath" - "github.com/spf13/cobra" - "github.com/spf13/viper" - cmd "github.com/consideritdone/landslidecore/cmd/tendermint/commands" "github.com/consideritdone/landslidecore/cmd/tendermint/commands/debug" cfg "github.com/consideritdone/landslidecore/config" @@ -21,6 +18,8 @@ import ( nd "github.com/consideritdone/landslidecore/test/maverick/node" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) var ( diff --git a/test/maverick/node/node.go b/test/maverick/node/node.go index 018d55ff6..e74eed940 100644 --- a/test/maverick/node/node.go +++ b/test/maverick/node/node.go @@ -12,12 +12,6 @@ import ( "strings" "time" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/rs/cors" - - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" bcv0 "github.com/consideritdone/landslidecore/blockchain/v0" bcv1 "github.com/consideritdone/landslidecore/blockchain/v1" @@ -52,6 +46,10 @@ import ( "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" "github.com/consideritdone/landslidecore/version" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/rs/cors" + dbm "github.com/tendermint/tm-db" ) //------------------------------------------------------------------------------ @@ -60,7 +58,7 @@ import ( // a map of misbehaviors to be executed by the maverick node func ParseMisbehaviors(str string) (map[int64]cs.Misbehavior, error) { // check if string is empty in which case we run a normal node - var misbehaviors = make(map[int64]cs.Misbehavior) + misbehaviors := make(map[int64]cs.Misbehavior) if str == "" { return misbehaviors, nil } @@ -137,7 +135,6 @@ func DefaultNewNode(config *cfg.Config, logger log.Logger, misbehaviors map[int6 logger, misbehaviors, ) - } // MetricsProvider returns a consensus, p2p and mempool Metrics. @@ -296,7 +293,6 @@ func createAndStartIndexerService( eventBus *types.EventBus, logger log.Logger, ) (*txindex.IndexerService, txindex.TxIndexer, indexer.BlockIndexer, error) { - var ( txIndexer txindex.TxIndexer blockIndexer indexer.BlockIndexer @@ -333,8 +329,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) @@ -378,8 +374,8 @@ func onlyValidatorIsUs(state sm.State, pubKey crypto.PubKey) bool { } func createMempoolAndMempoolReactor(config *cfg.Config, proxyApp proxy.AppConns, - state sm.State, memplMetrics *mempl.Metrics, logger log.Logger) (*mempl.Reactor, *mempl.CListMempool) { - + state sm.State, memplMetrics *mempl.Metrics, logger log.Logger, +) (*mempl.Reactor, *mempl.CListMempool) { mempool := mempl.NewCListMempool( config.Mempool, proxyApp.Mempool(), @@ -400,8 +396,8 @@ func createMempoolAndMempoolReactor(config *cfg.Config, proxyApp proxy.AppConns, } 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 @@ -421,8 +417,8 @@ func createBlockchainReactor(config *cfg.Config, blockExec *sm.BlockExecutor, blockStore *store.BlockStore, fastSync bool, - logger log.Logger) (bcReactor p2p.Reactor, err error) { - + logger log.Logger, +) (bcReactor p2p.Reactor, err error) { switch config.FastSync.Version { case "v0": bcReactor = bcv0.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync) @@ -449,8 +445,8 @@ func createConsensusReactor(config *cfg.Config, waitSync bool, eventBus *types.EventBus, consensusLogger log.Logger, - misbehaviors map[int64]cs.Misbehavior) (*cs.Reactor, *cs.State) { - + misbehaviors map[int64]cs.Misbehavior, +) (*cs.Reactor, *cs.State) { consensusState := cs.NewState( config.Consensus, state.Copy(), @@ -553,8 +549,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, @@ -576,8 +572,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())) @@ -603,8 +599,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{ @@ -626,7 +622,8 @@ func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config, // startStateSync starts an asynchronous state sync process, then switches to fast sync mode. func startStateSync(ssR *statesync.Reactor, bcR fastSyncReactor, conR *cs.Reactor, stateProvider statesync.StateProvider, config *cfg.StateSyncConfig, fastSync 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 { @@ -689,8 +686,8 @@ func NewNode(config *cfg.Config, metricsProvider MetricsProvider, logger log.Logger, misbehaviors map[int64]cs.Misbehavior, - options ...Option) (*Node, error) { - + options ...Option, +) (*Node, error) { blockStore, stateDB, err := initDBs(config, dbProvider) if err != nil { return nil, err @@ -1352,9 +1349,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 and persists the diff --git a/test/maverick/node/privval.go b/test/maverick/node/privval.go index 80d971f3d..8c812859d 100644 --- a/test/maverick/node/privval.go +++ b/test/maverick/node/privval.go @@ -62,11 +62,10 @@ func (pvKey FilePVKey) Save() { if err != nil { panic(err) } - err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600) + err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0o600) if err != nil { panic(err) } - } //------------------------------------------------------------------------------- @@ -90,7 +89,6 @@ type FilePVLastSignState struct { // we have already signed for this HRS, and can reuse the existing signature). // It panics if the HRS matches the arguments, there's a SignBytes, but no Signature. func (lss *FilePVLastSignState) CheckHRS(height int64, round int32, step int8) (bool, error) { - if lss.Height > height { return false, fmt.Errorf("height regression. Got %v, last height %v", height, lss.Height) } @@ -133,7 +131,7 @@ func (lss *FilePVLastSignState) Save() { if err != nil { panic(err) } - err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0600) + err = tempfile.WriteFileAtomic(outFile, jsonBytes, 0o600) if err != nil { panic(err) } @@ -347,8 +345,8 @@ func (pv *FilePV) signProposal(chainID string, proposal *tmproto.Proposal) error // Persist height/round/step and signature func (pv *FilePV) saveSigned(height int64, round int32, step int8, - signBytes []byte, sig []byte) { - + signBytes, sig []byte, +) { pv.LastSignState.Height = height pv.LastSignState.Round = round pv.LastSignState.Step = step diff --git a/tools/tm-signer-harness/internal/test_harness.go b/tools/tm-signer-harness/internal/test_harness.go index 8de764d09..4d5513dd4 100644 --- a/tools/tm-signer-harness/internal/test_harness.go +++ b/tools/tm-signer-harness/internal/test_harness.go @@ -8,16 +8,14 @@ import ( "os/signal" "time" - "github.com/consideritdone/landslidecore/crypto/tmhash" - "github.com/consideritdone/landslidecore/crypto/ed25519" - "github.com/consideritdone/landslidecore/privval" - "github.com/consideritdone/landslidecore/state" - + "github.com/consideritdone/landslidecore/crypto/tmhash" "github.com/consideritdone/landslidecore/libs/log" tmnet "github.com/consideritdone/landslidecore/libs/net" tmos "github.com/consideritdone/landslidecore/libs/os" + "github.com/consideritdone/landslidecore/privval" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" ) diff --git a/tools/tm-signer-harness/internal/test_harness_test.go b/tools/tm-signer-harness/internal/test_harness_test.go index ca4a485b4..b7fab323f 100644 --- a/tools/tm-signer-harness/internal/test_harness_test.go +++ b/tools/tm-signer-harness/internal/test_harness_test.go @@ -7,14 +7,13 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/libs/log" "github.com/consideritdone/landslidecore/privval" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( diff --git a/tools/tm-signer-harness/main.go b/tools/tm-signer-harness/main.go index db8c097a9..3a359b86a 100644 --- a/tools/tm-signer-harness/main.go +++ b/tools/tm-signer-harness/main.go @@ -136,7 +136,7 @@ func extractKey(tmhome, outputPath string) { stateFile := filepath.Join(internal.ExpandPath(tmhome), "data", "priv_validator_state.json") fpv := privval.LoadFilePV(keyFile, stateFile) pkb := []byte(fpv.Key.PrivKey.(ed25519.PrivKey)) - if err := ioutil.WriteFile(internal.ExpandPath(outputPath), pkb[:32], 0600); err != nil { + if err := ioutil.WriteFile(internal.ExpandPath(outputPath), pkb[:32], 0o600); err != nil { logger.Info("Failed to write private key", "output", outputPath, "err", err) os.Exit(1) } diff --git a/types/block.go b/types/block.go index 19f3a4ee6..db49ff128 100644 --- a/types/block.go +++ b/types/block.go @@ -7,9 +7,6 @@ import ( "strings" "time" - "github.com/gogo/protobuf/proto" - gogotypes "github.com/gogo/protobuf/types" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/merkle" "github.com/consideritdone/landslidecore/crypto/tmhash" @@ -20,6 +17,8 @@ import ( tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" tmversion "github.com/consideritdone/landslidecore/proto/tendermint/version" "github.com/consideritdone/landslidecore/version" + "github.com/gogo/protobuf/proto" + gogotypes "github.com/gogo/protobuf/types" ) const ( @@ -721,7 +720,6 @@ func (cs *CommitSig) ToProto() *tmproto.CommitSig { // FromProto sets a protobuf CommitSig to the given pointer. // It returns an error if the CommitSig is invalid. func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error { - cs.BlockIDFlag = BlockIDFlag(csp.BlockIdFlag) cs.ValidatorAddress = csp.ValidatorAddress cs.Timestamp = csp.Timestamp @@ -962,9 +960,7 @@ func CommitFromProto(cp *tmproto.Commit) (*Commit, error) { return nil, errors.New("nil Commit") } - var ( - commit = new(Commit) - ) + commit := new(Commit) bi, err := BlockIDFromProto(&cp.BlockID) if err != nil { @@ -990,7 +986,6 @@ func CommitFromProto(cp *tmproto.Commit) (*Commit, error) { // Data contains the set of transactions included in the block type Data struct { - // Txs that will be applied by state @ block.Height+1. // NOTE: not all txs here are valid. We're just agreeing on the order first. // This means that block.AppHash does not include these txs. diff --git a/types/block_meta_test.go b/types/block_meta_test.go index 7ca5780a4..848dc2804 100644 --- a/types/block_meta_test.go +++ b/types/block_meta_test.go @@ -3,10 +3,9 @@ package types import ( "testing" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/tmhash" tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/require" ) func TestBlockMeta_ToProto(t *testing.T) { @@ -49,10 +48,14 @@ func TestBlockMeta_ToProto(t *testing.T) { func TestBlockMeta_ValidateBasic(t *testing.T) { h := makeRandHeader() bi := BlockID{Hash: h.Hash(), PartSetHeader: PartSetHeader{Total: 123, Hash: tmrand.Bytes(tmhash.Size)}} - bi2 := BlockID{Hash: tmrand.Bytes(tmhash.Size), - PartSetHeader: PartSetHeader{Total: 123, Hash: tmrand.Bytes(tmhash.Size)}} - bi3 := BlockID{Hash: []byte("incorrect hash"), - PartSetHeader: PartSetHeader{Total: 123, Hash: []byte("incorrect hash")}} + bi2 := BlockID{ + Hash: tmrand.Bytes(tmhash.Size), + PartSetHeader: PartSetHeader{Total: 123, Hash: tmrand.Bytes(tmhash.Size)}, + } + bi3 := BlockID{ + Hash: []byte("incorrect hash"), + PartSetHeader: PartSetHeader{Total: 123, Hash: []byte("incorrect hash")}, + } bm := &BlockMeta{ BlockID: bi, diff --git a/types/block_test.go b/types/block_test.go index 75058b4be..6b1f7383e 100644 --- a/types/block_test.go +++ b/types/block_test.go @@ -11,10 +11,6 @@ import ( "testing" "time" - gogotypes "github.com/gogo/protobuf/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/merkle" "github.com/consideritdone/landslidecore/crypto/tmhash" @@ -25,6 +21,9 @@ import ( tmversion "github.com/consideritdone/landslidecore/proto/tendermint/version" tmtime "github.com/consideritdone/landslidecore/types/time" "github.com/consideritdone/landslidecore/version" + gogotypes "github.com/gogo/protobuf/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -201,9 +200,11 @@ func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) BlockID { var nilBytes []byte // This follows RFC-6962, i.e. `echo -n ” | sha256sum` -var emptyBytes = []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, +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} + 0x78, 0x52, 0xb8, 0x55, +} func TestNilHeaderHashDoesntCrash(t *testing.T) { assert.Equal(t, nilBytes, []byte((*Header)(nil).Hash())) @@ -299,7 +300,6 @@ func TestMaxCommitBytes(t *testing.T) { pb = commit.ToProto() assert.EqualValues(t, MaxCommitBytes(MaxVotesCount), int64(pb.Size())) - } func TestHeaderHash(t *testing.T) { @@ -782,7 +782,6 @@ func TestHeaderProto(t *testing.T) { } else { require.Error(t, err, tt.msg) } - }) } } diff --git a/types/canonical_test.go b/types/canonical_test.go index 667642ae8..5ccd1d4ab 100644 --- a/types/canonical_test.go +++ b/types/canonical_test.go @@ -11,14 +11,22 @@ import ( func TestCanonicalizeBlockID(t *testing.T) { randhash := tmrand.Bytes(tmhash.Size) - block1 := tmproto.BlockID{Hash: randhash, - PartSetHeader: tmproto.PartSetHeader{Total: 5, Hash: randhash}} - block2 := tmproto.BlockID{Hash: randhash, - PartSetHeader: tmproto.PartSetHeader{Total: 10, Hash: randhash}} - cblock1 := tmproto.CanonicalBlockID{Hash: randhash, - PartSetHeader: tmproto.CanonicalPartSetHeader{Total: 5, Hash: randhash}} - cblock2 := tmproto.CanonicalBlockID{Hash: randhash, - PartSetHeader: tmproto.CanonicalPartSetHeader{Total: 10, Hash: randhash}} + block1 := tmproto.BlockID{ + Hash: randhash, + PartSetHeader: tmproto.PartSetHeader{Total: 5, Hash: randhash}, + } + block2 := tmproto.BlockID{ + Hash: randhash, + PartSetHeader: tmproto.PartSetHeader{Total: 10, Hash: randhash}, + } + cblock1 := tmproto.CanonicalBlockID{ + Hash: randhash, + PartSetHeader: tmproto.CanonicalPartSetHeader{Total: 5, Hash: randhash}, + } + cblock2 := tmproto.CanonicalBlockID{ + Hash: randhash, + PartSetHeader: tmproto.CanonicalPartSetHeader{Total: 10, Hash: randhash}, + } tests := []struct { name string diff --git a/types/encoding_helper.go b/types/encoding_helper.go index 744c78a4c..5e5e320ff 100644 --- a/types/encoding_helper.go +++ b/types/encoding_helper.go @@ -1,9 +1,8 @@ package types import ( - gogotypes "github.com/gogo/protobuf/types" - "github.com/consideritdone/landslidecore/libs/bytes" + gogotypes "github.com/gogo/protobuf/types" ) // cdcEncode returns nil if the input is nil, otherwise returns diff --git a/types/event_bus_test.go b/types/event_bus_test.go index a99a81756..84de4d423 100644 --- a/types/event_bus_test.go +++ b/types/event_bus_test.go @@ -7,13 +7,12 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" tmpubsub "github.com/consideritdone/landslidecore/libs/pubsub" tmquery "github.com/consideritdone/landslidecore/libs/pubsub/query" tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEventBusPublishEventTx(t *testing.T) { @@ -408,7 +407,7 @@ func BenchmarkEventBus(b *testing.B) { } } -func benchmarkEventBus(numClients int, randQueries bool, randEvents bool, b *testing.B) { +func benchmarkEventBus(numClients int, randQueries, randEvents bool, b *testing.B) { // for random* functions rand.Seed(time.Now().Unix()) @@ -473,7 +472,8 @@ var events = []string{ EventLock, EventRelock, EventTimeoutWait, - EventVote} + EventVote, +} func randEvent() string { return events[tmrand.Intn(len(events))] @@ -491,7 +491,8 @@ var queries = []tmpubsub.Query{ EventQueryLock, EventQueryRelock, EventQueryTimeoutWait, - EventQueryVote} + EventQueryVote, +} func randQuery() tmpubsub.Query { return queries[tmrand.Intn(len(queries))] diff --git a/types/evidence.go b/types/evidence.go index d8b1139d4..be2280c72 100644 --- a/types/evidence.go +++ b/types/evidence.go @@ -231,7 +231,8 @@ func (l *LightClientAttackEvidence) Bytes() []byte { // the malicious validators were and returns them. This is used both for forming the ByzantineValidators // field and for validating that it is correct. Validators are ordered based on validator power func (l *LightClientAttackEvidence) GetByzantineValidators(commonVals *ValidatorSet, - trusted *SignedHeader) []*Validator { + trusted *SignedHeader, +) []*Validator { var validators []*Validator // First check if the header is invalid. This means that it is a lunatic attack and therefore we take the // validators who are in the commonVals and voted for the lunatic header @@ -288,7 +289,6 @@ func (l *LightClientAttackEvidence) ConflictingHeaderIsInvalid(trustedHeader *He !bytes.Equal(trustedHeader.ConsensusHash, l.ConflictingBlock.ConsensusHash) || !bytes.Equal(trustedHeader.AppHash, l.ConflictingBlock.AppHash) || !bytes.Equal(trustedHeader.LastResultsHash, l.ConflictingBlock.LastResultsHash) - } // Hash returns the hash of the header and the commonHeight. This is designed to cause hash collisions @@ -561,7 +561,8 @@ func NewMockDuplicateVoteEvidence(height int64, time time.Time, chainID string) // assumes voting power to be 10 and validator to be the only one in the set func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time, - pv PrivValidator, chainID string) *DuplicateVoteEvidence { + pv PrivValidator, chainID string, +) *DuplicateVoteEvidence { pubKey, _ := pv.GetPubKey() val := NewValidator(pubKey, 10) voteA := makeMockVote(height, 0, 0, pubKey.Address(), randBlockID(), time) @@ -576,7 +577,8 @@ func NewMockDuplicateVoteEvidenceWithValidator(height int64, time time.Time, } func makeMockVote(height int64, round, index int32, addr Address, - blockID BlockID, time time.Time) *Vote { + blockID BlockID, time time.Time, +) *Vote { return &Vote{ Type: tmproto.SignedMsgType(2), Height: height, diff --git a/types/evidence_test.go b/types/evidence_test.go index 9320030d5..ca68f16ac 100644 --- a/types/evidence_test.go +++ b/types/evidence_test.go @@ -5,15 +5,14 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/tmhash" tmrand "github.com/consideritdone/landslidecore/libs/rand" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" tmversion "github.com/consideritdone/landslidecore/proto/tendermint/version" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var defaultVoteTime = time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC) @@ -220,7 +219,6 @@ func TestLightClientAttackEvidenceValidation(t *testing.T) { } }) } - } func TestMockEvidenceValidateBasic(t *testing.T) { @@ -230,7 +228,8 @@ func TestMockEvidenceValidateBasic(t *testing.T) { func makeVote( t *testing.T, val PrivValidator, chainID string, valIndex int32, height int64, round int32, step int, blockID BlockID, - time time.Time) *Vote { + time time.Time, +) *Vote { pubKey, err := val.GetPubKey() require.NoError(t, err) v := &Vote{ diff --git a/types/genesis.go b/types/genesis.go index e3f50fa6e..3314057d4 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -52,7 +52,7 @@ func (genDoc *GenesisDoc) SaveAs(file string) error { if err != nil { return err } - return tmos.WriteFile(file, genDocBytes, 0644) + return tmos.WriteFile(file, genDocBytes, 0o644) } // ValidatorHash returns the hash of the validator set contained in the GenesisDoc diff --git a/types/genesis_test.go b/types/genesis_test.go index 31d6c1ee9..163b5e832 100644 --- a/types/genesis_test.go +++ b/types/genesis_test.go @@ -5,12 +5,11 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/ed25519" tmjson "github.com/consideritdone/landslidecore/libs/json" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGenesisBad(t *testing.T) { diff --git a/types/light_test.go b/types/light_test.go index c7a1d5e96..5242cf0d7 100644 --- a/types/light_test.go +++ b/types/light_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/consideritdone/landslidecore/crypto" tmversion "github.com/consideritdone/landslidecore/proto/tendermint/version" "github.com/consideritdone/landslidecore/version" + "github.com/stretchr/testify/assert" ) func TestLightBlockValidateBasic(t *testing.T) { @@ -54,7 +53,6 @@ func TestLightBlockValidateBasic(t *testing.T) { assert.NoError(t, err, tc.name) } } - } func TestLightBlockProtobuf(t *testing.T) { @@ -107,7 +105,6 @@ func TestLightBlockProtobuf(t *testing.T) { assert.Equal(t, lightBlock, lb) } } - } func TestSignedHeaderValidateBasic(t *testing.T) { diff --git a/types/params_test.go b/types/params_test.go index 7d70759e1..ee46f700b 100644 --- a/types/params_test.go +++ b/types/params_test.go @@ -6,10 +6,9 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - abci "github.com/consideritdone/landslidecore/abci/types" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/stretchr/testify/assert" ) var ( diff --git a/types/part_set_test.go b/types/part_set_test.go index 895594e31..65ecf3600 100644 --- a/types/part_set_test.go +++ b/types/part_set_test.go @@ -4,11 +4,10 @@ import ( "io/ioutil" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/merkle" tmrand "github.com/consideritdone/landslidecore/libs/rand" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -145,8 +144,10 @@ func TestParSetHeaderProtoBuf(t *testing.T) { expPass bool }{ {"success empty", &PartSetHeader{}, true}, - {"success", - &PartSetHeader{Total: 1, Hash: []byte("hash")}, true}, + { + "success", + &PartSetHeader{Total: 1, Hash: []byte("hash")}, true, + }, } for _, tc := range testCases { @@ -162,7 +163,6 @@ func TestParSetHeaderProtoBuf(t *testing.T) { } func TestPartProtoBuf(t *testing.T) { - proof := merkle.Proof{ Total: 1, Index: 1, @@ -175,8 +175,10 @@ func TestPartProtoBuf(t *testing.T) { }{ {"failure empty", &Part{}, false}, {"failure nil", nil, false}, - {"success", - &Part{Index: 1, Bytes: tmrand.Bytes(32), Proof: proof}, true}, + { + "success", + &Part{Index: 1, Bytes: tmrand.Bytes(32), Proof: proof}, true, + }, } for _, tc := range testCases { diff --git a/types/proposal.go b/types/proposal.go index 727f830c0..9586dd6fd 100644 --- a/types/proposal.go +++ b/types/proposal.go @@ -34,7 +34,7 @@ type Proposal struct { // NewProposal returns a new Proposal. // If there is no POLRound, polRound should be -1. -func NewProposal(height int64, round int32, polRound int32, blockID BlockID) *Proposal { +func NewProposal(height int64, round, polRound int32, blockID BlockID) *Proposal { return &Proposal{ Type: tmproto.ProposalType, Height: height, diff --git a/types/proposal_test.go b/types/proposal_test.go index 32fce5968..e6740774d 100644 --- a/types/proposal_test.go +++ b/types/proposal_test.go @@ -5,14 +5,13 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/tmhash" "github.com/consideritdone/landslidecore/libs/protoio" tmrand "github.com/consideritdone/landslidecore/libs/rand" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -21,15 +20,17 @@ var ( ) func init() { - var stamp, err = time.Parse(TimeFormat, "2018-02-11T07:09:22.765Z") + stamp, err := time.Parse(TimeFormat, "2018-02-11T07:09:22.765Z") if err != nil { panic(err) } testProposal = &Proposal{ Height: 12345, Round: 23456, - BlockID: BlockID{Hash: []byte("--June_15_2020_amino_was_removed"), - PartSetHeader: PartSetHeader{Total: 111, Hash: []byte("--June_15_2020_amino_was_removed")}}, + BlockID: BlockID{ + Hash: []byte("--June_15_2020_amino_was_removed"), + PartSetHeader: PartSetHeader{Total: 111, Hash: []byte("--June_15_2020_amino_was_removed")}, + }, POLRound: -1, Timestamp: stamp, } @@ -123,7 +124,6 @@ func BenchmarkProposalVerifySignature(b *testing.B) { } func TestProposalValidateBasic(t *testing.T) { - privVal := NewMockPV() testCases := []struct { testName string diff --git a/types/protobuf_test.go b/types/protobuf_test.go index c7c3e45dd..2e4f6228f 100644 --- a/types/protobuf_test.go +++ b/types/protobuf_test.go @@ -3,13 +3,12 @@ package types import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" cryptoenc "github.com/consideritdone/landslidecore/crypto/encoding" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestABCIPubKey(t *testing.T) { @@ -62,12 +61,12 @@ func TestABCIConsensusParams(t *testing.T) { type pubKeyEddie struct{} -func (pubKeyEddie) Address() Address { return []byte{} } -func (pubKeyEddie) Bytes() []byte { return []byte{} } -func (pubKeyEddie) VerifySignature(msg []byte, sig []byte) bool { return false } -func (pubKeyEddie) Equals(crypto.PubKey) bool { return false } -func (pubKeyEddie) String() string { return "" } -func (pubKeyEddie) Type() string { return "pubKeyEddie" } +func (pubKeyEddie) Address() Address { return []byte{} } +func (pubKeyEddie) Bytes() []byte { return []byte{} } +func (pubKeyEddie) VerifySignature(msg, sig []byte) bool { return false } +func (pubKeyEddie) Equals(crypto.PubKey) bool { return false } +func (pubKeyEddie) String() string { return "" } +func (pubKeyEddie) Type() string { return "pubKeyEddie" } func TestABCIValidatorFromPubKeyAndPower(t *testing.T) { pubkey := ed25519.GenPrivKey().PubKey() diff --git a/types/results_test.go b/types/results_test.go index f9278041d..39c17be90 100644 --- a/types/results_test.go +++ b/types/results_test.go @@ -3,10 +3,9 @@ package types import ( "testing" + abci "github.com/consideritdone/landslidecore/abci/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - abci "github.com/consideritdone/landslidecore/abci/types" ) func TestABCIResults(t *testing.T) { diff --git a/types/signable.go b/types/signable.go index 6303a918a..29154e682 100644 --- a/types/signable.go +++ b/types/signable.go @@ -5,12 +5,10 @@ import ( tmmath "github.com/consideritdone/landslidecore/libs/math" ) -var ( - // MaxSignatureSize is a maximum allowed signature size for the Proposal - // and Vote. - // XXX: secp256k1 does not have Size nor MaxSize defined. - MaxSignatureSize = tmmath.MaxInt(ed25519.SignatureSize, 64) -) +// MaxSignatureSize is a maximum allowed signature size for the Proposal +// and Vote. +// XXX: secp256k1 does not have Size nor MaxSize defined. +var MaxSignatureSize = tmmath.MaxInt(ed25519.SignatureSize, 64) // Signable is an interface for all signable things. // It typically removes signatures before serializing. diff --git a/types/test_util.go b/types/test_util.go index ace10ce0d..d51ac3228 100644 --- a/types/test_util.go +++ b/types/test_util.go @@ -10,8 +10,8 @@ import ( ) func MakeCommit(blockID BlockID, height int64, round int32, - voteSet *VoteSet, validators []PrivValidator, now time.Time) (*Commit, error) { - + voteSet *VoteSet, validators []PrivValidator, now time.Time, +) (*Commit, error) { // all sign for i := 0; i < len(validators); i++ { pubKey, err := validators[i].GetPubKey() diff --git a/types/tx.go b/types/tx.go index fef82c2ea..0b43b698d 100644 --- a/types/tx.go +++ b/types/tx.go @@ -111,7 +111,6 @@ func (tp TxProof) Validate(dataHash []byte) error { } func (tp TxProof) ToProto() tmproto.TxProof { - pbProof := tp.Proof.ToProto() pbtp := tmproto.TxProof{ @@ -122,8 +121,8 @@ func (tp TxProof) ToProto() tmproto.TxProof { return pbtp } -func TxProofFromProto(pb tmproto.TxProof) (TxProof, error) { +func TxProofFromProto(pb tmproto.TxProof) (TxProof, error) { pbProof, err := merkle.ProofFromProto(pb.Proof) if err != nil { return TxProof{}, err diff --git a/types/tx_test.go b/types/tx_test.go index 1ef97a224..96f200f12 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -4,12 +4,11 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - tmrand "github.com/consideritdone/landslidecore/libs/rand" ctest "github.com/consideritdone/landslidecore/libs/test" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func makeTxs(cnt, size int) Txs { @@ -128,8 +127,7 @@ func testTxProofUnchangable(t *testing.T) { } // This makes sure that the proof doesn't deserialize into something valid. -func assertBadProof(t *testing.T, root []byte, bad []byte, good TxProof) { - +func assertBadProof(t *testing.T, root, bad []byte, good TxProof) { var ( proof TxProof pbProof tmproto.TxProof 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 7ddad84e8..a281835ad 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -431,7 +431,6 @@ func verifyUpdates( vals *ValidatorSet, removedPower int64, ) (tvpAfterUpdatesBeforeRemovals int64, err error) { - delta := func(update *Validator, vals *ValidatorSet) int64 { _, val := vals.GetByAddress(update.Address) if val != nil { @@ -495,7 +494,6 @@ func computeNewPriorities(updates []*Validator, vals *ValidatorSet, updatedTotal valUpdate.ProposerPriority = val.ProposerPriority } } - } // Merges the vals' validator list with the updates list. @@ -667,8 +665,8 @@ func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error { // includes which validators signed. For instance, Gaia incentivizes proposers // with a bonus for including more than +2/3 of the signatures. func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, - height int64, commit *Commit) error { - + height int64, commit *Commit, +) error { if vals.Size() != len(commit.Signatures) { return NewErrInvalidCommitSignatures(vals.Size(), len(commit.Signatures)) } @@ -722,8 +720,8 @@ func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, // This method is primarily used by the light client and does not check all the // signatures. func (vals *ValidatorSet) VerifyCommitLight(chainID string, blockID BlockID, - height int64, commit *Commit) error { - + height int64, commit *Commit, +) error { if vals.Size() != len(commit.Signatures) { return NewErrInvalidCommitSignatures(vals.Size(), len(commit.Signatures)) } @@ -894,7 +892,6 @@ func (vals *ValidatorSet) StringIndented(indent string) string { indent, indent, strings.Join(valStrings, "\n"+indent+" "), indent) - } //------------------------------------- diff --git a/types/validator_set_test.go b/types/validator_set_test.go index 18a63ac2e..0ecd49dd8 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -10,14 +10,13 @@ import ( "testing/quick" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" tmmath "github.com/consideritdone/landslidecore/libs/math" tmrand "github.com/consideritdone/landslidecore/libs/rand" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidatorSetBasic(t *testing.T) { @@ -46,9 +45,11 @@ func TestValidatorSetBasic(t *testing.T) { assert.Zero(t, vset.Size()) assert.Equal(t, int64(0), vset.TotalVotingPower()) assert.Nil(t, vset.GetProposer()) - assert.Equal(t, []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, + assert.Equal(t, []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}, vset.Hash()) + 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, + }, vset.Hash()) // add val = randValidator(vset.TotalVotingPower()) assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val})) @@ -75,7 +76,6 @@ func TestValidatorSetBasic(t *testing.T) { assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val})) _, val = vset.GetByAddress(val.Address) assert.Equal(t, proposerPriority, val.ProposerPriority) - } func TestValidatorSetValidateBasic(t *testing.T) { @@ -133,7 +133,6 @@ func TestValidatorSetValidateBasic(t *testing.T) { assert.NoError(t, err) } } - } func TestCopy(t *testing.T) { @@ -479,28 +478,39 @@ func TestAveragingInIncrementProposerPriority(t *testing.T) { times int32 avg int64 }{ - 0: {ValidatorSet{ - Validators: []*Validator{ - {Address: []byte("a"), ProposerPriority: 1}, - {Address: []byte("b"), ProposerPriority: 2}, - {Address: []byte("c"), ProposerPriority: 3}}}, - 1, 2}, - 1: {ValidatorSet{ - Validators: []*Validator{ - {Address: []byte("a"), ProposerPriority: 10}, - {Address: []byte("b"), ProposerPriority: -10}, - {Address: []byte("c"), ProposerPriority: 1}}}, + 0: { + ValidatorSet{ + Validators: []*Validator{ + {Address: []byte("a"), ProposerPriority: 1}, + {Address: []byte("b"), ProposerPriority: 2}, + {Address: []byte("c"), ProposerPriority: 3}, + }, + }, + 1, 2, + }, + 1: { + ValidatorSet{ + Validators: []*Validator{ + {Address: []byte("a"), ProposerPriority: 10}, + {Address: []byte("b"), ProposerPriority: -10}, + {Address: []byte("c"), ProposerPriority: 1}, + }, + }, // this should average twice but the average should be 0 after the first iteration // (voting power is 0 -> no changes) 11, 0, // 1 / 3 }, - 2: {ValidatorSet{ - Validators: []*Validator{ - {Address: []byte("a"), ProposerPriority: 100}, - {Address: []byte("b"), ProposerPriority: -10}, - {Address: []byte("c"), ProposerPriority: 1}}}, - 1, 91 / 3}, + 2: { + ValidatorSet{ + Validators: []*Validator{ + {Address: []byte("a"), ProposerPriority: 100}, + {Address: []byte("b"), ProposerPriority: -10}, + {Address: []byte("c"), ProposerPriority: 1}, + }, + }, + 1, 91 / 3, + }, } for i, tc := range tcs { // work on copy to have the old ProposerPriorities: @@ -524,103 +534,125 @@ func TestAveragingInIncrementProposerPriorityWithVotingPower(t *testing.T) { vals := ValidatorSet{Validators: []*Validator{ {Address: []byte{0}, ProposerPriority: 0, VotingPower: vp0}, {Address: []byte{1}, ProposerPriority: 0, VotingPower: vp1}, - {Address: []byte{2}, ProposerPriority: 0, VotingPower: vp2}}} + {Address: []byte{2}, ProposerPriority: 0, VotingPower: vp2}, + }} tcs := []struct { vals *ValidatorSet wantProposerPrioritys []int64 times int32 wantProposer *Validator }{ - 0: { vals.Copy(), []int64{ // Acumm+VotingPower-Avg: 0 + vp0 - total - avg, // mostest will be subtracted by total voting power (12) 0 + vp1, - 0 + vp2}, + 0 + vp2, + }, 1, - vals.Validators[0]}, + vals.Validators[0], + }, 1: { vals.Copy(), []int64{ (0 + vp0 - total) + vp0 - total - avg, // this will be mostest on 2nd iter, too (0 + vp1) + vp1, - (0 + vp2) + vp2}, + (0 + vp2) + vp2, + }, 2, - vals.Validators[0]}, // increment twice -> expect average to be subtracted twice + vals.Validators[0], + }, // increment twice -> expect average to be subtracted twice 2: { vals.Copy(), []int64{ 0 + 3*(vp0-total) - avg, // still mostest 0 + 3*vp1, - 0 + 3*vp2}, + 0 + 3*vp2, + }, 3, - vals.Validators[0]}, + vals.Validators[0], + }, 3: { vals.Copy(), []int64{ 0 + 4*(vp0-total), // still mostest 0 + 4*vp1, - 0 + 4*vp2}, + 0 + 4*vp2, + }, 4, - vals.Validators[0]}, + vals.Validators[0], + }, 4: { vals.Copy(), []int64{ 0 + 4*(vp0-total) + vp0, // 4 iters was mostest 0 + 5*vp1 - total, // now this val is mostest for the 1st time (hence -12==totalVotingPower) - 0 + 5*vp2}, + 0 + 5*vp2, + }, 5, - vals.Validators[1]}, + vals.Validators[1], + }, 5: { vals.Copy(), []int64{ 0 + 6*vp0 - 5*total, // mostest again 0 + 6*vp1 - total, // mostest once up to here - 0 + 6*vp2}, + 0 + 6*vp2, + }, 6, - vals.Validators[0]}, + vals.Validators[0], + }, 6: { vals.Copy(), []int64{ 0 + 7*vp0 - 6*total, // in 7 iters this val is mostest 6 times 0 + 7*vp1 - total, // in 7 iters this val is mostest 1 time - 0 + 7*vp2}, + 0 + 7*vp2, + }, 7, - vals.Validators[0]}, + vals.Validators[0], + }, 7: { vals.Copy(), []int64{ 0 + 8*vp0 - 7*total, // mostest again 0 + 8*vp1 - total, - 0 + 8*vp2}, + 0 + 8*vp2, + }, 8, - vals.Validators[0]}, + vals.Validators[0], + }, 8: { vals.Copy(), []int64{ 0 + 9*vp0 - 7*total, 0 + 9*vp1 - total, - 0 + 9*vp2 - total}, // mostest + 0 + 9*vp2 - total, + }, // mostest 9, - vals.Validators[2]}, + vals.Validators[2], + }, 9: { vals.Copy(), []int64{ 0 + 10*vp0 - 8*total, // after 10 iters this is mostest again 0 + 10*vp1 - total, // after 6 iters this val is "mostest" once and not in between - 0 + 10*vp2 - total}, // in between 10 iters this val is "mostest" once + 0 + 10*vp2 - total, + }, // in between 10 iters this val is "mostest" once 10, - vals.Validators[0]}, + vals.Validators[0], + }, 10: { vals.Copy(), []int64{ 0 + 11*vp0 - 9*total, - 0 + 11*vp1 - total, // after 6 iters this val is "mostest" once and not in between - 0 + 11*vp2 - total}, // after 10 iters this val is "mostest" once + 0 + 11*vp1 - total, // after 6 iters this val is "mostest" once and not in between + 0 + 11*vp2 - total, + }, // after 10 iters this val is "mostest" once 11, - vals.Validators[0]}, + vals.Validators[0], + }, } for i, tc := range tcs { tc.vals.IncrementProposerPriority(tc.times) @@ -705,18 +737,26 @@ func TestValidatorSet_VerifyCommit_All(t *testing.T) { {"wrong block ID", chainID, makeBlockIDRandom(), vote.Height, commit, true}, {"wrong height", chainID, vote.BlockID, vote.Height - 1, commit, true}, - {"wrong set size: 1 vs 0", chainID, vote.BlockID, vote.Height, - NewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{}), true}, + { + "wrong set size: 1 vs 0", chainID, vote.BlockID, vote.Height, + NewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{}), true, + }, - {"wrong set size: 1 vs 2", chainID, vote.BlockID, vote.Height, + { + "wrong set size: 1 vs 2", chainID, vote.BlockID, vote.Height, NewCommit(vote.Height, vote.Round, vote.BlockID, - []CommitSig{vote.CommitSig(), {BlockIDFlag: BlockIDFlagAbsent}}), true}, + []CommitSig{vote.CommitSig(), {BlockIDFlag: BlockIDFlagAbsent}}), true, + }, - {"insufficient voting power: got 0, needed more than 666", chainID, vote.BlockID, vote.Height, - NewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{{BlockIDFlag: BlockIDFlagAbsent}}), true}, + { + "insufficient voting power: got 0, needed more than 666", chainID, vote.BlockID, vote.Height, + NewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{{BlockIDFlag: BlockIDFlagAbsent}}), true, + }, - {"wrong signature (#0)", chainID, vote.BlockID, vote.Height, - NewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{vote2.CommitSig()}), true}, + { + "wrong signature (#0)", chainID, vote.BlockID, vote.Height, + NewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{vote2.CommitSig()}), true, + }, } for _, tc := range testCases { @@ -815,7 +855,6 @@ func TestValidatorSet_VerifyCommitLightTrusting_ReturnsAsSoonAsTrustLevelOfVotin } func TestEmptySet(t *testing.T) { - var valList []*Validator valSet := NewValidatorSet(valList) assert.Panics(t, func() { valSet.IncrementProposerPriority(1) }) @@ -839,11 +878,9 @@ func TestEmptySet(t *testing.T) { // Attempt delete from empty set assert.Error(t, valSet.UpdateWithChangeSet(delList)) - } func TestUpdatesForNewValidatorSet(t *testing.T) { - v1 := newValidator([]byte("v1"), 100) v2 := newValidator([]byte("v2"), 100) valList := []*Validator{v1, v2} @@ -870,7 +907,6 @@ func TestUpdatesForNewValidatorSet(t *testing.T) { v3 = newValidator([]byte("v3"), 30) valList = []*Validator{v1, v2, v3} assert.Panics(t, func() { NewValidatorSet(valList) }) - } type testVal struct { @@ -1160,19 +1196,23 @@ func TestValSetUpdatesOrderIndependenceTestsExecute(t *testing.T) { }{ 0: { // order of changes should not matter, the final validator sets should be the same []testVal{{"v4", 40}, {"v3", 30}, {"v2", 10}, {"v1", 10}}, - []testVal{{"v4", 44}, {"v3", 33}, {"v2", 22}, {"v1", 11}}}, + []testVal{{"v4", 44}, {"v3", 33}, {"v2", 22}, {"v1", 11}}, + }, 1: { // order of additions should not matter []testVal{{"v2", 20}, {"v1", 10}}, - []testVal{{"v3", 30}, {"v4", 40}, {"v5", 50}, {"v6", 60}}}, + []testVal{{"v3", 30}, {"v4", 40}, {"v5", 50}, {"v6", 60}}, + }, 2: { // order of removals should not matter []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}}, - []testVal{{"v1", 0}, {"v3", 0}, {"v4", 0}}}, + []testVal{{"v1", 0}, {"v3", 0}, {"v4", 0}}, + }, 3: { // order of mixed operations should not matter []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}}, - []testVal{{"v1", 0}, {"v3", 0}, {"v2", 22}, {"v5", 50}, {"v4", 44}}}, + []testVal{{"v1", 0}, {"v3", 0}, {"v2", 22}, {"v5", 50}, {"v4", 44}}, + }, } for i, tt := range valSetUpdatesOrderTests { @@ -1217,41 +1257,50 @@ func TestValSetApplyUpdatesTestsExecute(t *testing.T) { 0: { // prepend []testVal{{"v4", 44}, {"v5", 55}}, []testVal{{"v1", 11}}, - []testVal{{"v1", 11}, {"v4", 44}, {"v5", 55}}}, + []testVal{{"v1", 11}, {"v4", 44}, {"v5", 55}}, + }, 1: { // append []testVal{{"v4", 44}, {"v5", 55}}, []testVal{{"v6", 66}}, - []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}}, + []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}, + }, 2: { // insert []testVal{{"v4", 44}, {"v6", 66}}, []testVal{{"v5", 55}}, - []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}}, + []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}, + }, 3: { // insert multi []testVal{{"v4", 44}, {"v6", 66}, {"v9", 99}}, []testVal{{"v5", 55}, {"v7", 77}, {"v8", 88}}, - []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}, {"v7", 77}, {"v8", 88}, {"v9", 99}}}, + []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}, {"v7", 77}, {"v8", 88}, {"v9", 99}}, + }, // changes 4: { // head []testVal{{"v1", 111}, {"v2", 22}}, []testVal{{"v1", 11}}, - []testVal{{"v1", 11}, {"v2", 22}}}, + []testVal{{"v1", 11}, {"v2", 22}}, + }, 5: { // tail []testVal{{"v1", 11}, {"v2", 222}}, []testVal{{"v2", 22}}, - []testVal{{"v1", 11}, {"v2", 22}}}, + []testVal{{"v1", 11}, {"v2", 22}}, + }, 6: { // middle []testVal{{"v1", 11}, {"v2", 222}, {"v3", 33}}, []testVal{{"v2", 22}}, - []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}}, + []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}, + }, 7: { // multi []testVal{{"v1", 111}, {"v2", 222}, {"v3", 333}}, []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}, - []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}}, + []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}, + }, // additions and changes 8: { []testVal{{"v1", 111}, {"v2", 22}}, []testVal{{"v1", 11}, {"v3", 33}, {"v4", 44}}, - []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}, {"v4", 44}}}, + []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}, {"v4", 44}}, + }, } for i, tt := range valSetUpdatesBasicTests { @@ -1329,7 +1378,6 @@ func randTestVSetCfg(t *testing.T, nBase, nAddMax int) testVSetCfg { sort.Sort(testValsByVotingPower(cfg.expectedVals)) return cfg - } func applyChangesToValSet(t *testing.T, expErr error, valSet *ValidatorSet, valsLists ...[]testVal) { @@ -1475,28 +1523,56 @@ func TestValSetUpdateOverflowRelated(t *testing.T) { { name: "4 no false overflow error messages for adds, updates and deletes", startVals: []testVal{ - {"v1", MaxTotalVotingPower / 4}, {"v2", MaxTotalVotingPower / 4}, - {"v3", MaxTotalVotingPower / 4}, {"v4", MaxTotalVotingPower / 4}}, + {"v1", MaxTotalVotingPower / 4}, + {"v2", MaxTotalVotingPower / 4}, + {"v3", MaxTotalVotingPower / 4}, + {"v4", MaxTotalVotingPower / 4}, + }, deletedVals: []testVal{{"v2", 0}}, updatedVals: []testVal{ - {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v4", 2}}, + {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v4", 2}, + }, addedVals: []testVal{{"v5", 3}}, expectedVals: []testVal{ - {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v5", 3}, {"v4", 2}}, + {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v5", 3}, {"v4", 2}, + }, expErr: nil, }, { name: "5 check panic on overflow is prevented: update 8 validators with power int64(math.MaxInt64)/8", startVals: []testVal{ - {"v1", 1}, {"v2", 1}, {"v3", 1}, {"v4", 1}, {"v5", 1}, - {"v6", 1}, {"v7", 1}, {"v8", 1}, {"v9", 1}}, + {"v1", 1}, + {"v2", 1}, + {"v3", 1}, + {"v4", 1}, + {"v5", 1}, + {"v6", 1}, + {"v7", 1}, + {"v8", 1}, + {"v9", 1}, + }, updatedVals: []testVal{ - {"v1", MaxTotalVotingPower}, {"v2", MaxTotalVotingPower}, {"v3", MaxTotalVotingPower}, - {"v4", MaxTotalVotingPower}, {"v5", MaxTotalVotingPower}, {"v6", MaxTotalVotingPower}, - {"v7", MaxTotalVotingPower}, {"v8", MaxTotalVotingPower}, {"v9", 8}}, + {"v1", MaxTotalVotingPower}, + {"v2", MaxTotalVotingPower}, + {"v3", MaxTotalVotingPower}, + {"v4", MaxTotalVotingPower}, + {"v5", MaxTotalVotingPower}, + {"v6", MaxTotalVotingPower}, + {"v7", MaxTotalVotingPower}, + {"v8", MaxTotalVotingPower}, + {"v9", 8}, + }, expectedVals: []testVal{ - {"v1", 1}, {"v2", 1}, {"v3", 1}, {"v4", 1}, {"v5", 1}, - {"v6", 1}, {"v7", 1}, {"v8", 1}, {"v9", 1}}, + {"v1", 1}, + {"v2", 1}, + {"v3", 1}, + {"v4", 1}, + {"v5", 1}, + {"v6", 1}, + {"v7", 1}, + {"v8", 1}, + {"v9", 1}, + }, expErr: ErrTotalVotingPowerOverflow, }, } diff --git a/types/vote_set.go b/types/vote_set.go index ca693c8c9..b9192dc25 100644 --- a/types/vote_set.go +++ b/types/vote_set.go @@ -76,7 +76,8 @@ type VoteSet struct { // Constructs a new VoteSet struct used to accumulate votes for given height/round. func NewVoteSet(chainID string, height int64, round int32, - signedMsgType tmproto.SignedMsgType, valSet *ValidatorSet) *VoteSet { + signedMsgType tmproto.SignedMsgType, valSet *ValidatorSet, +) *VoteSet { if height == 0 { panic("Cannot make VoteSet for height == 0, doesn't make sense.") } diff --git a/types/vote_set_test.go b/types/vote_set_test.go index 9519a944e..2fabdaf6c 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -4,13 +4,12 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" tmrand "github.com/consideritdone/landslidecore/libs/rand" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestVoteSet_AddVote_Good(t *testing.T) { diff --git a/types/vote_test.go b/types/vote_test.go index eb181eade..b8e0397be 100644 --- a/types/vote_test.go +++ b/types/vote_test.go @@ -4,15 +4,14 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/crypto/ed25519" "github.com/consideritdone/landslidecore/crypto/tmhash" "github.com/consideritdone/landslidecore/libs/protoio" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func examplePrevote() *Vote { @@ -24,7 +23,7 @@ func examplePrecommit() *Vote { } func exampleVote(t byte) *Vote { - var stamp, err = time.Parse(TimeFormat, "2017-12-25T03:00:01.234Z") + stamp, err := time.Parse(TimeFormat, "2017-12-25T03:00:01.234Z") if err != nil { panic(err) } @@ -58,7 +57,6 @@ func TestVoteSignable(t *testing.T) { } func TestVoteSignBytesTestVectors(t *testing.T) { - tests := []struct { chainID string vote *Vote @@ -82,7 +80,8 @@ func TestVoteSignBytesTestVectors(t *testing.T) { 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round 0x2a, // (field_number << 3) | wire_type // remaining fields (timestamp): - 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1}, + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, + }, }, // with proper (fixed size) height and round (PreVote): 2: { @@ -97,7 +96,8 @@ func TestVoteSignBytesTestVectors(t *testing.T) { 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round 0x2a, // (field_number << 3) | wire_type // remaining fields (timestamp): - 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1}, + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, + }, }, 3: { "", &Vote{Height: 1, Round: 1}, @@ -109,7 +109,8 @@ func TestVoteSignBytesTestVectors(t *testing.T) { 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // round // remaining fields (timestamp): 0x2a, - 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1}, + 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, + }, }, // containing non-empty chain_id: 4: { @@ -125,7 +126,8 @@ func TestVoteSignBytesTestVectors(t *testing.T) { 0xb, 0x8, 0x80, 0x92, 0xb8, 0xc3, 0x98, 0xfe, 0xff, 0xff, 0xff, 0x1, // timestamp // (field_number << 3) | wire_type 0x32, - 0xd, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64}, // chainID + 0xd, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, + }, // chainID }, } for i, tc := range tests { diff --git a/version/version.go b/version/version.go index 4b4c3cb9f..13e060934 100644 --- a/version/version.go +++ b/version/version.go @@ -1,8 +1,6 @@ package version -var ( - TMCoreSemVer = TMVersionDefault -) +var TMCoreSemVer = TMVersionDefault const ( // TMVersionDefault is the used as the fallback version of Tendermint Core diff --git a/vm/block.go b/vm/block.go index 771687cb2..c637b53f3 100644 --- a/vm/block.go +++ b/vm/block.go @@ -10,9 +10,7 @@ import ( "github.com/consideritdone/landslidecore/types" ) -var ( - _ snowman.Block = &Block{} -) +var _ snowman.Block = &Block{} // Block implements the snowman.Block interface type Block struct { diff --git a/vm/block_utils.go b/vm/block_utils.go index 49723682a..c9b1dda69 100644 --- a/vm/block_utils.go +++ b/vm/block_utils.go @@ -5,15 +5,14 @@ import ( "fmt" "time" - "github.com/consideritdone/landslidecore/crypto" - "github.com/consideritdone/landslidecore/state" - "github.com/consideritdone/landslidecore/types" - abci "github.com/consideritdone/landslidecore/abci/types" + "github.com/consideritdone/landslidecore/crypto" "github.com/consideritdone/landslidecore/libs/log" mempl "github.com/consideritdone/landslidecore/mempool" tmstate "github.com/consideritdone/landslidecore/proto/tendermint/state" "github.com/consideritdone/landslidecore/proxy" + "github.com/consideritdone/landslidecore/state" + "github.com/consideritdone/landslidecore/types" ) func makeCommitMock(height int64, timestamp time.Time) *types.Commit { @@ -107,7 +106,7 @@ func execBlockOnProxyApp( store state.Store, initialHeight int64, ) (*tmstate.ABCIResponses, error) { - var validTxs, invalidTxs = 0, 0 + validTxs, invalidTxs := 0, 0 txIndex := 0 abciResponses := new(tmstate.ABCIResponses) diff --git a/vm/cmd/main.go b/vm/cmd/main.go index e0f8b9743..913c5b253 100644 --- a/vm/cmd/main.go +++ b/vm/cmd/main.go @@ -3,17 +3,15 @@ package main import ( "context" "fmt" - "github.com/consideritdone/landslidecore/abci/example/counter" - landslideCoreVM "github.com/consideritdone/landslidecore/vm" "os" - "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/ulimit" "github.com/ava-labs/avalanchego/vms/rpcchainvm" + "github.com/consideritdone/landslidecore/abci/example/counter" + landslideCoreVM "github.com/consideritdone/landslidecore/vm" ) func main() { - if err := ulimit.Set(ulimit.DefaultFDLimit, logging.NoLog{}); err != nil { fmt.Printf("failed to set fd limit correctly due to: %s", err) os.Exit(1) diff --git a/vm/database.go b/vm/database.go index 07b62ff18..a2ffcc1aa 100644 --- a/vm/database.go +++ b/vm/database.go @@ -5,9 +5,7 @@ import ( dbm "github.com/tendermint/tm-db" ) -var ( - _ dbm.DB = &Database{} -) +var _ dbm.DB = &Database{} type ( Database struct { @@ -35,11 +33,11 @@ func (db Database) Get(key []byte) ([]byte, error) { return res, nil } -func (db Database) Set(key []byte, value []byte) error { +func (db Database) Set(key, value []byte) error { return db.Database.Put(key, value) } -func (db Database) SetSync(key []byte, value []byte) error { +func (db Database) SetSync(key, value []byte) error { return db.Database.Put(key, value) } @@ -60,16 +58,16 @@ func (db Database) NewBatch() dbm.Batch { } func (db Database) Print() error { - //TODO implement me + // TODO implement me return nil } func (db Database) Stats() map[string]string { - //TODO implement me + // TODO implement me return nil } -func (iter Iterator) Domain() (start []byte, end []byte) { +func (iter Iterator) Domain() (start, end []byte) { return iter.start, iter.end } diff --git a/vm/service.go b/vm/service.go index 7caa1bcbd..33a614a77 100644 --- a/vm/service.go +++ b/vm/service.go @@ -161,9 +161,7 @@ type ( } ) -var ( - DefaultABCIQueryOptions = ABCIQueryOptions{Height: 0, Prove: false} -) +var DefaultABCIQueryOptions = ABCIQueryOptions{Height: 0, Prove: false} func NewService(vm *VM) Service { return &LocalService{vm} diff --git a/vm/vm.go b/vm/vm.go index a07226755..00e21a117 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -22,10 +22,6 @@ import ( "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/components/chain" - "github.com/gorilla/rpc/v2" - "github.com/prometheus/client_golang/prometheus" - dbm "github.com/tendermint/tm-db" - abciTypes "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/config" cs "github.com/consideritdone/landslidecore/consensus" @@ -44,6 +40,9 @@ import ( txidxkv "github.com/consideritdone/landslidecore/state/txindex/kv" "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" + "github.com/gorilla/rpc/v2" + "github.com/prometheus/client_golang/prometheus" + dbm "github.com/tendermint/tm-db" ) var ( @@ -185,7 +184,7 @@ func (vm *VM) Initialize( vm.tmLogger.Info("init block", "b", block, "part set", partSet) } - //vm.genesisHash = vm.ethConfig.Genesis.ToBlock(nil).Hash() // must create genesis hash before [vm.readLastAccepted] + // vm.genesisHash = vm.ethConfig.Genesis.ToBlock(nil).Hash() // must create genesis hash before [vm.readLastAccepted] // Create the proxyApp and establish connections to the ABCI app (consensus, mempool, query). proxyApp, err := node.CreateAndStartProxyAppConns(proxy.NewLocalClientCreator(vm.app), vm.tmLogger) @@ -382,7 +381,7 @@ func (vm *VM) initChainState(lastAcceptedBlock *types.Block) error { DecidedCacheSize: decidedCacheSize, MissingCacheSize: missingCacheSize, UnverifiedCacheSize: unverifiedCacheSize, - //GetBlockIDAtHeight: vm.GetBlockIDAtHeight, + // GetBlockIDAtHeight: vm.GetBlockIDAtHeight, GetBlock: vm.getBlock, UnmarshalBlock: vm.parseBlock, BuildBlock: vm.buildBlock, @@ -616,7 +615,7 @@ func (vm *VM) Version(ctx context.Context) (string, error) { } func (vm *VM) CreateStaticHandlers(ctx context.Context) (map[string]*common.HTTPHandler, error) { - //TODO implement me + // TODO implement me return nil, nil } @@ -645,7 +644,7 @@ func (vm *VM) ProxyApp() proxy.AppConns { } func (vm *VM) SetPreference(ctx context.Context, blkID ids.ID) error { - //TODO implement me + // TODO implement me return nil } diff --git a/vm/vm_test.go b/vm/vm_test.go index 02801de19..376c8aba0 100644 --- a/vm/vm_test.go +++ b/vm/vm_test.go @@ -7,8 +7,6 @@ import ( "os" "testing" - "github.com/consideritdone/landslidecore/abci/example/kvstore" - "github.com/ava-labs/avalanchego/database/manager" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" @@ -16,13 +14,13 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/components/chain" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/counter" + "github.com/consideritdone/landslidecore/abci/example/kvstore" atypes "github.com/consideritdone/landslidecore/abci/types" tmrand "github.com/consideritdone/landslidecore/libs/rand" ctypes "github.com/consideritdone/landslidecore/rpc/core/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( From 49ad0abd53308eeef788707cf9747fd76fc699cb Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 28 Jun 2023 17:38:10 +0800 Subject: [PATCH 2/5] gofumpt and gci --- consensus/byzantine_test.go | 12 ++--- consensus/common_test.go | 33 ++++++------ consensus/invalid_test.go | 3 +- consensus/mempool_test.go | 14 ++--- consensus/metrics.go | 1 - consensus/msgs.go | 3 +- consensus/msgs_test.go | 96 ++++++++++++++++++++++------------- consensus/reactor.go | 15 ++---- consensus/reactor_test.go | 42 ++++++++------- consensus/replay.go | 16 +++--- consensus/replay_file.go | 8 ++- consensus/replay_test.go | 53 +++++++++++-------- consensus/state.go | 10 +--- consensus/state_test.go | 14 ++--- consensus/ticker.go | 5 +- consensus/wal.go | 10 ++-- consensus/wal_generator.go | 6 +-- consensus/wal_test.go | 11 ++-- mempool/cache_test.go | 3 +- mempool/clist_mempool.go | 2 +- mempool/clist_mempool_test.go | 11 ++-- mempool/errors.go | 6 +-- mempool/reactor_test.go | 10 ++-- node/doc.go | 45 ++++++++-------- node/node.go | 58 ++++++++++----------- node/node_test.go | 8 ++- vm/cmd/main.go | 1 + 27 files changed, 251 insertions(+), 245 deletions(-) diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index 3b8ab2652..8360a795a 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -9,11 +9,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - abcicli "github.com/consideritdone/landslidecore/abci/client" abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/evidence" @@ -26,6 +21,9 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) //---------------------------------------------- @@ -50,7 +48,7 @@ func TestByzantinePrevoteEquivocation(t *testing.T) { state, _ := stateStore.LoadFromDBOrGenesisDoc(genDoc) thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) defer os.RemoveAll(thisConfig.RootDir) - ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal + ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal app := appFunc() vals := types.TM2PB.ValidatorUpdates(state.Validators) app.InitChain(abci.RequestInitChain{Validators: vals}) @@ -545,9 +543,11 @@ func (br *ByzantineReactor) AddPeer(peer p2p.Peer) { br.reactor.sendNewRoundStepMessage(peer) } } + func (br *ByzantineReactor) RemovePeer(peer p2p.Peer, reason interface{}) { br.reactor.RemovePeer(peer, reason) } + func (br *ByzantineReactor) Receive(chID byte, peer p2p.Peer, msgBytes []byte) { br.reactor.Receive(chID, peer, msgBytes) } diff --git a/consensus/common_test.go b/consensus/common_test.go index 96ccbfc62..6240d041d 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -6,19 +6,13 @@ import ( "fmt" "io/ioutil" "os" + "path" "path/filepath" "sort" "sync" "testing" "time" - "github.com/go-kit/log/term" - "github.com/stretchr/testify/require" - - "path" - - dbm "github.com/tendermint/tm-db" - abcicli "github.com/consideritdone/landslidecore/abci/client" "github.com/consideritdone/landslidecore/abci/example/counter" "github.com/consideritdone/landslidecore/abci/example/kvstore" @@ -38,6 +32,9 @@ import ( "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/go-kit/log/term" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) const ( @@ -90,8 +87,8 @@ func newValidatorStub(privValidator types.PrivValidator, valIndex int32) *valida func (vs *validatorStub) signVote( voteType tmproto.SignedMsgType, hash []byte, - header types.PartSetHeader) (*types.Vote, error) { - + header types.PartSetHeader, +) (*types.Vote, error) { pubKey, err := vs.PrivValidator.GetPubKey() if err != nil { return nil, fmt.Errorf("can't get pubkey: %w", err) @@ -139,7 +136,8 @@ func signVotes( voteType tmproto.SignedMsgType, hash []byte, header types.PartSetHeader, - vss ...*validatorStub) []*types.Vote { + vss ...*validatorStub, +) []*types.Vote { votes := make([]*types.Vote, len(vss)) for i, vs := range vss { votes[i] = signVote(vs, voteType, hash, header) @@ -426,7 +424,7 @@ func newStateWithConfigAndBlockStore( func loadPrivValidator(config *cfg.Config) *privval.FilePV { privValidatorKeyFile := config.PrivValidatorKeyFile() - ensureDir(filepath.Dir(privValidatorKeyFile), 0700) + ensureDir(filepath.Dir(privValidatorKeyFile), 0o700) privValidatorStateFile := config.PrivValidatorStateFile() privValidator := privval.LoadOrGenFilePV(privValidatorKeyFile, privValidatorStateFile) privValidator.Reset() @@ -453,7 +451,8 @@ func randState(nValidators int) (*State, []*validatorStub) { //------------------------------------------------------------------------------- func ensureNoNewEvent(ch <-chan tmpubsub.Message, timeout time.Duration, - errorMessage string) { + errorMessage string, +) { select { case <-time.After(timeout): break @@ -631,7 +630,8 @@ func ensurePrevote(voteCh <-chan tmpubsub.Message, height int64, round int32) { } func ensureVote(voteCh <-chan tmpubsub.Message, height int64, round int32, - voteType tmproto.SignedMsgType) { + voteType tmproto.SignedMsgType, +) { select { case <-time.After(ensureTimeout): panic("Timeout expired while waiting for NewVote event") @@ -687,7 +687,8 @@ func consensusLogger() log.Logger { } func randConsensusNet(nValidators int, testName string, tickerFunc func() TimeoutTicker, - appFunc func() abci.Application, configOpts ...func(*cfg.Config)) ([]*State, cleanupFunc) { + appFunc func() abci.Application, configOpts ...func(*cfg.Config), +) ([]*State, cleanupFunc) { genDoc, privVals := randGenesisDoc(nValidators, false, 30) css := make([]*State, nValidators) logger := consensusLogger() @@ -701,7 +702,7 @@ func randConsensusNet(nValidators int, testName string, tickerFunc func() Timeou for _, opt := range configOpts { opt(thisConfig) } - ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal + ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal app := appFunc() vals := types.TM2PB.ValidatorUpdates(state.Validators) app.InitChain(abci.RequestInitChain{Validators: vals}) @@ -736,7 +737,7 @@ func randConsensusNetWithPeers( state, _ := stateStore.LoadFromDBOrGenesisDoc(genDoc) thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) configRootDirs = append(configRootDirs, thisConfig.RootDir) - ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal + ensureDir(filepath.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal if i == 0 { peer0Config = thisConfig } diff --git a/consensus/invalid_test.go b/consensus/invalid_test.go index 852f0ab76..42fcd072a 100644 --- a/consensus/invalid_test.go +++ b/consensus/invalid_test.go @@ -80,7 +80,8 @@ func invalidDoPrevoteFunc(t *testing.T, height int64, round int32, cs *State, sw Type: tmproto.PrecommitType, BlockID: types.BlockID{ Hash: blockHash, - PartSetHeader: types.PartSetHeader{Total: 1, Hash: tmrand.Bytes(32)}}, + PartSetHeader: types.PartSetHeader{Total: 1, Hash: tmrand.Bytes(32)}, + }, } p := precommit.ToProto() err = cs.privValidator.SignVote(cs.state.ChainID, p) diff --git a/consensus/mempool_test.go b/consensus/mempool_test.go index a70899b0f..fb9fbe131 100644 --- a/consensus/mempool_test.go +++ b/consensus/mempool_test.go @@ -7,16 +7,14 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/code" abci "github.com/consideritdone/landslidecore/abci/types" mempl "github.com/consideritdone/landslidecore/mempool" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) // for testing @@ -224,7 +222,8 @@ func (app *CounterApplication) DeliverTx(req abci.RequestDeliverTx) abci.Respons if txValue != uint64(app.txCount) { return abci.ResponseDeliverTx{ Code: code.CodeTypeBadNonce, - Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)} + Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue), + } } app.txCount++ return abci.ResponseDeliverTx{Code: code.CodeTypeOK} @@ -235,7 +234,8 @@ func (app *CounterApplication) CheckTx(req abci.RequestCheckTx) abci.ResponseChe if txValue != uint64(app.mempoolTxCount) { return abci.ResponseCheckTx{ Code: code.CodeTypeBadNonce, - Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.mempoolTxCount, txValue)} + Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.mempoolTxCount, txValue), + } } app.mempoolTxCount++ return abci.ResponseCheckTx{Code: code.CodeTypeOK} diff --git a/consensus/metrics.go b/consensus/metrics.go index 527d53744..c8f2282e8 100644 --- a/consensus/metrics.go +++ b/consensus/metrics.go @@ -3,7 +3,6 @@ package consensus import ( "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/discard" - prometheus "github.com/go-kit/kit/metrics/prometheus" stdprometheus "github.com/prometheus/client_golang/prometheus" ) diff --git a/consensus/msgs.go b/consensus/msgs.go index 1739a2e5b..f52f4fcc2 100644 --- a/consensus/msgs.go +++ b/consensus/msgs.go @@ -4,8 +4,6 @@ import ( "errors" "fmt" - "github.com/gogo/protobuf/proto" - cstypes "github.com/consideritdone/landslidecore/consensus/types" "github.com/consideritdone/landslidecore/libs/bits" tmmath "github.com/consideritdone/landslidecore/libs/math" @@ -13,6 +11,7 @@ import ( tmcons "github.com/consideritdone/landslidecore/proto/tendermint/consensus" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" ) // MsgToProto takes a consensus message type and returns the proto defined consensus message diff --git a/consensus/msgs_test.go b/consensus/msgs_test.go index 42c966127..b4d4e5e13 100644 --- a/consensus/msgs_test.go +++ b/consensus/msgs_test.go @@ -6,10 +6,6 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/crypto/merkle" "github.com/consideritdone/landslidecore/libs/bits" tmrand "github.com/consideritdone/landslidecore/libs/rand" @@ -17,6 +13,9 @@ import ( tmcons "github.com/consideritdone/landslidecore/proto/tendermint/consensus" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMsgToProto(t *testing.T) { @@ -133,7 +132,8 @@ func TestMsgToProto(t *testing.T) { ProposalPolRound: 1, ProposalPol: *pbBits, }, - }}, false}, + }, + }, false}, {"successful ProposalMessage", &ProposalMessage{ Proposal: &proposal, }, &tmcons.Message{ @@ -210,7 +210,6 @@ func TestMsgToProto(t *testing.T) { } func TestWALMsgProto(t *testing.T) { - parts := types.Part{ Index: 1, Bytes: []byte("test"), @@ -385,34 +384,63 @@ func TestConsMsgsVectors(t *testing.T) { SecondsSinceStartTime: math.MaxInt64, LastCommitRound: math.MaxInt32, }}}, "0a2608ffffffffffffffff7f10ffffffff0718ffffffff0f20ffffffffffffffff7f28ffffffff07"}, - {"NewValidBlock", &tmcons.Message{Sum: &tmcons.Message_NewValidBlock{ - NewValidBlock: &tmcons.NewValidBlock{ - Height: 1, Round: 1, BlockPartSetHeader: pbPsh, BlockParts: pbBits, IsCommit: false}}}, - "1231080110011a24080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d22050801120100"}, - {"Proposal", &tmcons.Message{Sum: &tmcons.Message_Proposal{Proposal: &tmcons.Proposal{Proposal: *pbProposal}}}, - "1a720a7008201001180120012a480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d320608c0b89fdc053a146164645f6d6f72655f6578636c616d6174696f6e"}, - {"ProposalPol", &tmcons.Message{Sum: &tmcons.Message_ProposalPol{ - ProposalPol: &tmcons.ProposalPOL{Height: 1, ProposalPolRound: 1}}}, - "2206080110011a00"}, - {"BlockPart", &tmcons.Message{Sum: &tmcons.Message_BlockPart{ - BlockPart: &tmcons.BlockPart{Height: 1, Round: 1, Part: *pbParts}}}, - "2a36080110011a3008011204746573741a26080110011a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d"}, - {"Vote", &tmcons.Message{Sum: &tmcons.Message_Vote{ - Vote: &tmcons.Vote{Vote: vpb}}}, - "32700a6e0802100122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d2a0608c0b89fdc0532146164645f6d6f72655f6578636c616d6174696f6e3801"}, - {"HasVote", &tmcons.Message{Sum: &tmcons.Message_HasVote{ - HasVote: &tmcons.HasVote{Height: 1, Round: 1, Type: tmproto.PrevoteType, Index: 1}}}, - "3a080801100118012001"}, - {"HasVote", &tmcons.Message{Sum: &tmcons.Message_HasVote{ - HasVote: &tmcons.HasVote{Height: math.MaxInt64, Round: math.MaxInt32, - Type: tmproto.PrevoteType, Index: math.MaxInt32}}}, - "3a1808ffffffffffffffff7f10ffffffff07180120ffffffff07"}, - {"VoteSetMaj23", &tmcons.Message{Sum: &tmcons.Message_VoteSetMaj23{ - VoteSetMaj23: &tmcons.VoteSetMaj23{Height: 1, Round: 1, Type: tmproto.PrevoteType, BlockID: pbBi}}}, - "425008011001180122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d"}, - {"VoteSetBits", &tmcons.Message{Sum: &tmcons.Message_VoteSetBits{ - VoteSetBits: &tmcons.VoteSetBits{Height: 1, Round: 1, Type: tmproto.PrevoteType, BlockID: pbBi, Votes: *pbBits}}}, - "4a5708011001180122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d2a050801120100"}, + { + "NewValidBlock", &tmcons.Message{Sum: &tmcons.Message_NewValidBlock{ + NewValidBlock: &tmcons.NewValidBlock{ + Height: 1, Round: 1, BlockPartSetHeader: pbPsh, BlockParts: pbBits, IsCommit: false, + }, + }}, + "1231080110011a24080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d22050801120100", + }, + { + "Proposal", &tmcons.Message{Sum: &tmcons.Message_Proposal{Proposal: &tmcons.Proposal{Proposal: *pbProposal}}}, + "1a720a7008201001180120012a480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d320608c0b89fdc053a146164645f6d6f72655f6578636c616d6174696f6e", + }, + { + "ProposalPol", &tmcons.Message{Sum: &tmcons.Message_ProposalPol{ + ProposalPol: &tmcons.ProposalPOL{Height: 1, ProposalPolRound: 1}, + }}, + "2206080110011a00", + }, + { + "BlockPart", &tmcons.Message{Sum: &tmcons.Message_BlockPart{ + BlockPart: &tmcons.BlockPart{Height: 1, Round: 1, Part: *pbParts}, + }}, + "2a36080110011a3008011204746573741a26080110011a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d", + }, + { + "Vote", &tmcons.Message{Sum: &tmcons.Message_Vote{ + Vote: &tmcons.Vote{Vote: vpb}, + }}, + "32700a6e0802100122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d2a0608c0b89fdc0532146164645f6d6f72655f6578636c616d6174696f6e3801", + }, + { + "HasVote", &tmcons.Message{Sum: &tmcons.Message_HasVote{ + HasVote: &tmcons.HasVote{Height: 1, Round: 1, Type: tmproto.PrevoteType, Index: 1}, + }}, + "3a080801100118012001", + }, + { + "HasVote", &tmcons.Message{Sum: &tmcons.Message_HasVote{ + HasVote: &tmcons.HasVote{ + Height: math.MaxInt64, Round: math.MaxInt32, + Type: tmproto.PrevoteType, Index: math.MaxInt32, + }, + }}, + "3a1808ffffffffffffffff7f10ffffffff07180120ffffffff07", + }, + { + "VoteSetMaj23", &tmcons.Message{Sum: &tmcons.Message_VoteSetMaj23{ + VoteSetMaj23: &tmcons.VoteSetMaj23{Height: 1, Round: 1, Type: tmproto.PrevoteType, BlockID: pbBi}, + }}, + "425008011001180122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d", + }, + { + "VoteSetBits", &tmcons.Message{Sum: &tmcons.Message_VoteSetBits{ + VoteSetBits: &tmcons.VoteSetBits{Height: 1, Round: 1, Type: tmproto.PrevoteType, BlockID: pbBi, Votes: *pbBits}, + }}, + "4a5708011001180122480a206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d1224080112206164645f6d6f72655f6578636c616d6174696f6e5f6d61726b735f636f64652d2a050801120100", + }, } for _, tc := range testCases { diff --git a/consensus/reactor.go b/consensus/reactor.go index 221016f63..6b2ca8d15 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -7,8 +7,6 @@ import ( "sync" "time" - "github.com/gogo/protobuf/proto" - cstypes "github.com/consideritdone/landslidecore/consensus/types" "github.com/consideritdone/landslidecore/libs/bits" tmevents "github.com/consideritdone/landslidecore/libs/events" @@ -21,6 +19,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/gogo/protobuf/proto" ) const ( @@ -420,7 +419,6 @@ func (conR *Reactor) subscribeToBroadcastEvents() { }); err != nil { conR.Logger.Error("Error adding listener for events", "err", err) } - } func (conR *Reactor) unsubscribeFromBroadcastEvents() { @@ -608,8 +606,8 @@ OUTER_LOOP: } func (conR *Reactor) gossipDataForCatchup(logger log.Logger, rs *cstypes.RoundState, - prs *cstypes.PeerRoundState, ps *PeerState, peer p2p.Peer) { - + prs *cstypes.PeerRoundState, ps *PeerState, peer p2p.Peer, +) { if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok { // Ensure that the peer's PartSetHeader is correct blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height) @@ -654,7 +652,7 @@ func (conR *Reactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) { logger := conR.Logger.With("peer", peer) // Simple hack to throttle logs upon sleep. - var sleeping = 0 + sleeping := 0 OUTER_LOOP: for { @@ -728,7 +726,6 @@ func (conR *Reactor) gossipVotesForHeight( prs *cstypes.PeerRoundState, ps *PeerState, ) bool { - // If there are lastCommits to send... if prs.Step == cstypes.RoundStepNewHeight { if ps.PickSendVote(rs.LastCommit) { @@ -784,7 +781,6 @@ func (conR *Reactor) gossipVotesForHeight( // NOTE: `queryMaj23Routine` has a simple crude design since it only comes // into play for liveness when there's a signature DDoS attack happening. func (conR *Reactor) queryMaj23Routine(peer p2p.Peer, ps *PeerState) { - OUTER_LOOP: for { // Manage disconnects from self or peer. @@ -1093,8 +1089,7 @@ func (ps *PeerState) PickVoteToSend(votes types.VoteSetReader) (vote *types.Vote return nil, false } - height, round, votesType, size := - votes.GetHeight(), votes.GetRound(), tmproto.SignedMsgType(votes.Type()), votes.Size() + height, round, votesType, size := votes.GetHeight(), votes.GetRound(), tmproto.SignedMsgType(votes.Type()), votes.Size() // Lazily set data using 'votes'. if votes.IsCommit() { diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index 99cdbd75e..0a4ff5ae5 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -11,12 +11,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - abcicli "github.com/consideritdone/landslidecore/abci/client" "github.com/consideritdone/landslidecore/abci/example/kvstore" abci "github.com/consideritdone/landslidecore/abci/types" @@ -36,6 +30,10 @@ import ( statemocks "github.com/consideritdone/landslidecore/state/mocks" "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) //---------------------------------------------- @@ -69,7 +67,6 @@ func startConsensusNet(t *testing.T, css []*State, n int) ( if err := css[i].blockExec.Store().Save(css[i].state); err != nil { t.Error(err) } - } } // make connected switches and start all reactors @@ -140,7 +137,7 @@ func TestReactorWithEvidence(t *testing.T) { state, _ := stateStore.LoadFromDBOrGenesisDoc(genDoc) thisConfig := ResetConfig(fmt.Sprintf("%s_%d", testName, i)) defer os.RemoveAll(thisConfig.RootDir) - ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal + ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0o700) // dir for wal app := appFunc() vals := types.TM2PB.ValidatorUpdates(state.Validators) app.InitChain(abci.RequestInitChain{Validators: vals}) @@ -171,7 +168,8 @@ func TestReactorWithEvidence(t *testing.T) { evpool := &statemocks.EvidencePool{} evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil) evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return([]types.Evidence{ - ev}, int64(len(ev.Bytes()))) + ev, + }, int64(len(ev.Bytes()))) evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return() evpool2 := sm.EmptyEvidencePool{} @@ -241,8 +239,10 @@ func TestReactorReceiveDoesNotPanicIfAddPeerHasntBeenCalledYet(t *testing.T) { var ( reactor = reactors[0] peer = p2pmock.NewPeer(nil) - msg = MustEncode(&HasVoteMessage{Height: 1, - Round: 1, Index: 1, Type: tmproto.PrevoteType}) + msg = MustEncode(&HasVoteMessage{ + Height: 1, + Round: 1, Index: 1, Type: tmproto.PrevoteType, + }) ) reactor.InitPeer(peer) @@ -264,8 +264,10 @@ func TestReactorReceivePanicsIfInitPeerHasntBeenCalledYet(t *testing.T) { var ( reactor = reactors[0] peer = p2pmock.NewPeer(nil) - msg = MustEncode(&HasVoteMessage{Height: 1, - Round: 1, Index: 1, Type: tmproto.PrevoteType}) + msg = MustEncode(&HasVoteMessage{ + Height: 1, + Round: 1, Index: 1, Type: tmproto.PrevoteType, + }) ) // we should call InitPeer here @@ -569,7 +571,6 @@ func waitForAndValidateBlockWithTx( break BLOCK_TX_LOOP } } - }, css) } @@ -581,7 +582,6 @@ func waitForBlockWithUpdatedValsAndValidateIt( css []*State, ) { timeoutWaitGroup(t, n, func(j int) { - var newBlock *types.Block LOOP: for { @@ -795,8 +795,10 @@ func TestProposalPOLMessageValidateBasic(t *testing.T) { {func(msg *ProposalPOLMessage) { msg.Height = -1 }, "negative Height"}, {func(msg *ProposalPOLMessage) { msg.ProposalPOLRound = -1 }, "negative ProposalPOLRound"}, {func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(0) }, "empty ProposalPOL bit array"}, - {func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(types.MaxVotesCount + 1) }, - "proposalPOL bit array is too big: 10001, max: 10000"}, + { + func(msg *ProposalPOLMessage) { msg.ProposalPOL = bits.NewBitArray(types.MaxVotesCount + 1) }, + "proposalPOL bit array is too big: 10001, max: 10000", + }, } for i, tc := range testCases { @@ -949,8 +951,10 @@ func TestVoteSetBitsMessageValidateBasic(t *testing.T) { }, } }, "wrong BlockID: wrong PartSetHeader: wrong Hash:"}, - {func(msg *VoteSetBitsMessage) { msg.Votes = bits.NewBitArray(types.MaxVotesCount + 1) }, - "votes bit array is too big: 10001, max: 10000"}, + { + func(msg *VoteSetBitsMessage) { msg.Votes = bits.NewBitArray(types.MaxVotesCount + 1) }, + "votes bit array is too big: 10001, max: 10000", + }, } for i, tc := range testCases { diff --git a/consensus/replay.go b/consensus/replay.go index c28a8d6c9..9d5085cdc 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -91,7 +91,6 @@ func (cs *State) readReplayMessage(msg *TimedWALMessage, newStepSub types.Subscr // Replay only those messages since the last block. `timeoutRoutine` should // run concurrently to read off tickChan. func (cs *State) catchupReplay(csHeight int64) error { - // Set replayMode to true so we don't log signing errors. cs.replayMode = true defer func() { cs.replayMode = false }() @@ -209,8 +208,8 @@ type Handshaker struct { } func NewHandshaker(stateStore sm.Store, state sm.State, - store sm.BlockStore, genDoc *types.GenesisDoc) *Handshaker { - + store sm.BlockStore, genDoc *types.GenesisDoc, +) *Handshaker { return &Handshaker{ stateStore: stateStore, initialState: state, @@ -239,7 +238,6 @@ func (h *Handshaker) NBlocks() int { // TODO: retry the handshake/replay if it fails ? func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { - // Handshake is done via ABCI Info on the query conn. res, err := proxyApp.Query().InfoSync(proxy.RequestInfo) if err != nil { @@ -341,7 +339,7 @@ func (h *Handshaker) ReplayBlocks( } else if len(h.genDoc.Validators) == 0 { // If validator set is not set in genesis and still empty after InitChain, exit. // In Landslide we don't care about Validators - //return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain") + // return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain") } if res.ConsensusParams != nil { @@ -350,7 +348,7 @@ func (h *Handshaker) ReplayBlocks( } // We update the last results hash with the empty hash, to conform with RFC-6962. state.LastResultsHash = merkle.HashFromByteSlices(nil) - //h.logger.Info("state", "s", state) + // h.logger.Info("state", "s", state) if err := h.stateStore.Save(state); err != nil { return nil, err } @@ -393,13 +391,11 @@ func (h *Handshaker) ReplayBlocks( if appBlockHeight < storeBlockHeight { // the app is behind, so replay blocks, but no need to go through WAL (state is already synced to store) return h.replayBlocks(state, proxyApp, appBlockHeight, storeBlockHeight, false) - } else if appBlockHeight == storeBlockHeight { // We're good! assertAppHashEqualsOneFromState(appHash, state) return appHash, nil } - } else if storeBlockHeight == stateBlockHeight+1 { // We saved the block in the store but haven't updated the state, // so we'll need to replay a block using the WAL. @@ -429,7 +425,6 @@ func (h *Handshaker) ReplayBlocks( state, err = h.replayBlock(state, storeBlockHeight, mockApp) return state.AppHash, err } - } panic(fmt.Sprintf("uncovered case! appHeight: %d, storeHeight: %d, stateHeight: %d", @@ -441,7 +436,8 @@ func (h *Handshaker) replayBlocks( proxyApp proxy.AppConns, appBlockHeight, storeBlockHeight int64, - mutateState bool) ([]byte, error) { + mutateState bool, +) ([]byte, error) { // App is further behind than it should be, so we need to replay blocks. // We replay all blocks from appBlockHeight+1. // diff --git a/consensus/replay_file.go b/consensus/replay_file.go index bd514348e..0ff4cd9b8 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -10,8 +10,6 @@ import ( "strconv" "strings" - dbm "github.com/tendermint/tm-db" - cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/log" tmos "github.com/consideritdone/landslidecore/libs/os" @@ -19,6 +17,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" + dbm "github.com/tendermint/tm-db" ) const ( @@ -40,7 +39,6 @@ func RunReplayFile(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console // Replay msgs in file or start the console func (cs *State) ReplayFile(file string, console bool) error { - if cs.IsRunning() { return errors.New("cs is already running, cannot replay") } @@ -64,7 +62,7 @@ func (cs *State) ReplayFile(file string, console bool) error { }() // just open the file for reading, no need to use wal - fp, err := os.OpenFile(file, os.O_RDONLY, 0600) + fp, err := os.OpenFile(file, os.O_RDONLY, 0o600) if err != nil { return err } @@ -137,7 +135,7 @@ func (pb *playback) replayReset(count int, newStepSub types.Subscription) error if err := pb.fp.Close(); err != nil { return err } - fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0600) + fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0o600) if err != nil { return err } diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 4b5fe8a82..5bd054574 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -13,11 +13,6 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/kvstore" abci "github.com/consideritdone/landslidecore/abci/types" cfg "github.com/consideritdone/landslidecore/config" @@ -32,6 +27,10 @@ import ( "github.com/consideritdone/landslidecore/proxy" sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestMain(m *testing.M) { @@ -65,7 +64,8 @@ func TestMain(m *testing.M) { // wal writer when we need to, instead of with every message. func startNewStateAndWaitForBlock(t *testing.T, consensusReplayConfig *cfg.Config, - lastBlockHeight int64, blockDB dbm.DB, stateStore sm.Store) { + lastBlockHeight int64, blockDB dbm.DB, stateStore sm.Store, +) { logger := log.TestingLogger() state, _ := stateStore.LoadFromDBOrGenesisFile(consensusReplayConfig.GenesisFile()) privValidator := loadPrivValidator(consensusReplayConfig) @@ -126,14 +126,18 @@ func TestWALCrash(t *testing.T) { initFn func(dbm.DB, *State, context.Context) heightToStop int64 }{ - {"empty block", + { + "empty block", func(stateDB dbm.DB, cs *State, ctx context.Context) {}, - 1}, - {"many non-empty blocks", + 1, + }, + { + "many non-empty blocks", func(stateDB dbm.DB, cs *State, ctx context.Context) { go sendTxs(ctx, cs) }, - 3}, + 3, + }, } for i, tc := range testCases { @@ -146,7 +150,8 @@ func TestWALCrash(t *testing.T) { } func crashWALandCheckLiveness(t *testing.T, consensusReplayConfig *cfg.Config, - initFn func(dbm.DB, *State, context.Context), heightToStop int64) { + initFn func(dbm.DB, *State, context.Context), heightToStop int64, +) { walPanicked := make(chan error) crashingWal := &crashingWAL{panicCh: walPanicked, heightToStop: heightToStop} @@ -282,7 +287,8 @@ func (w *crashingWAL) FlushAndSync() error { return w.next.FlushAndSync() } func (w *crashingWAL) SearchForEndHeight( height int64, - options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) { + options *WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { return w.next.SearchForEndHeight(height, options) } @@ -586,7 +592,7 @@ func TestHandshakeReplayNone(t *testing.T) { func TestMockProxyApp(t *testing.T) { sim.CleanupFunc() // clean the test env created in TestSimulateValidatorsChange logger := log.TestingLogger() - var validTxs, invalidTxs = 0, 0 + validTxs, invalidTxs := 0, 0 txIndex := 0 assert.NotPanics(t, func() { @@ -788,7 +794,8 @@ func applyBlock(stateStore sm.Store, st sm.State, blk *types.Block, proxyApp pro } func buildAppStateFromChain(proxyApp proxy.AppConns, stateStore sm.Store, - state sm.State, chain []*types.Block, nBlocks int, mode uint) { + state sm.State, chain []*types.Block, nBlocks int, mode uint, +) { // start a new app without handshake, play nBlocks blocks if err := proxyApp.Start(); err != nil { panic(err) @@ -825,7 +832,6 @@ func buildAppStateFromChain(proxyApp proxy.AppConns, stateStore sm.Store, default: panic(fmt.Sprintf("unknown mode %v", mode)) } - } func buildTMStateFromChain( @@ -834,7 +840,8 @@ func buildTMStateFromChain( state sm.State, chain []*types.Block, nBlocks int, - mode uint) sm.State { + mode uint, +) sm.State { // run the whole chain against this client to build up the tendermint state clientCreator := proxy.NewLocalClientCreator( kvstore.NewPersistentKVStoreApplication( @@ -975,8 +982,8 @@ func makeBlocks(n int, state *sm.State, privVal types.PrivValidator) []*types.Bl } func makeBlock(state sm.State, lastBlock *types.Block, lastBlockMeta *types.BlockMeta, - privVal types.PrivValidator, height int64) (*types.Block, *types.PartSet) { - + privVal types.PrivValidator, height int64, +) (*types.Block, *types.PartSet) { lastCommit := types.NewCommit(height-1, 0, types.BlockID{}, nil) if height > 1 { vote, _ := types.MakeVote( @@ -1058,7 +1065,7 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) { case EndHeightMessage: // if its not the first one, we have a full block if thisBlockParts != nil { - var pbb = new(tmproto.Block) + pbb := new(tmproto.Block) bz, err := ioutil.ReadAll(thisBlockParts.GetReader()) if err != nil { panic(err) @@ -1102,7 +1109,7 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) { if err != nil { panic(err) } - var pbb = new(tmproto.Block) + pbb := new(tmproto.Block) err = proto.Unmarshal(bz, pbb) if err != nil { panic(err) @@ -1146,7 +1153,8 @@ func readPieceFromWAL(msg *TimedWALMessage) interface{} { func stateAndStore( config *cfg.Config, pubKey crypto.PubKey, - appVersion uint64) (dbm.DB, sm.State, *mockBlockStore) { + appVersion uint64, +) (dbm.DB, sm.State, *mockBlockStore) { stateDB := dbm.NewMemDB() stateStore := sm.NewStore(stateDB) state, _ := sm.MakeGenesisStateFromFile(config.GenesisFile()) @@ -1182,6 +1190,7 @@ func (bs *mockBlockStore) LoadBlock(height int64) *types.Block { return bs.chain func (bs *mockBlockStore) LoadBlockByHash(hash []byte) *types.Block { return bs.chain[int64(len(bs.chain))-1] } + func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta { block := bs.chain[height-1] return &types.BlockMeta{ @@ -1192,9 +1201,11 @@ func (bs *mockBlockStore) LoadBlockMeta(height int64) *types.BlockMeta { func (bs *mockBlockStore) LoadBlockPart(height int64, index int) *types.Part { return nil } func (bs *mockBlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) { } + func (bs *mockBlockStore) LoadBlockCommit(height int64) *types.Commit { return bs.commits[height-1] } + func (bs *mockBlockStore) LoadSeenCommit(height int64) *types.Commit { return bs.commits[height-1] } diff --git a/consensus/state.go b/consensus/state.go index 65b39fdf2..1ff9514fb 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -10,8 +10,6 @@ import ( "sort" "time" - "github.com/gogo/protobuf/proto" - cfg "github.com/consideritdone/landslidecore/config" cstypes "github.com/consideritdone/landslidecore/consensus/types" "github.com/consideritdone/landslidecore/crypto" @@ -28,6 +26,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/gogo/protobuf/proto" ) // Consensus sentinel errors @@ -468,7 +467,6 @@ func (cs *State) AddVote(vote *types.Vote, peerID p2p.ID) (added bool, err error // SetProposal inputs a proposal. func (cs *State) SetProposal(proposal *types.Proposal, peerID p2p.ID) error { - if peerID == "" { cs.internalMsgQueue <- msgInfo{&ProposalMessage{proposal}, ""} } else { @@ -481,7 +479,6 @@ func (cs *State) SetProposal(proposal *types.Proposal, peerID p2p.ID) error { // AddProposalBlockPart inputs a part of the proposal block. func (cs *State) AddProposalBlockPart(height int64, round int32, part *types.Part, peerID p2p.ID) error { - if peerID == "" { cs.internalMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, ""} } else { @@ -499,7 +496,6 @@ func (cs *State) SetProposalAndBlock( parts *types.PartSet, peerID p2p.ID, ) error { - if err := cs.SetProposal(proposal, peerID); err != nil { return err } @@ -937,7 +933,6 @@ func (cs *State) handleTimeout(ti timeoutInfo, rs cstypes.RoundState) { default: panic(fmt.Sprintf("invalid timeout step: %v", ti.Step)) } - } func (cs *State) handleTxsAvailable() { @@ -1181,7 +1176,6 @@ func (cs *State) isProposalComplete() bool { } // if this is false the proposer is lying or we haven't received the POL yet return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority() - } // Create the next block to propose and return it. Returns nil block upon error. @@ -1890,7 +1884,7 @@ func (cs *State) addProposalBlockPart(msg *BlockPartMessage, peerID p2p.ID) (add return added, err } - var pbb = new(tmproto.Block) + pbb := new(tmproto.Block) err = proto.Unmarshal(bz, pbb) if err != nil { return added, err diff --git a/consensus/state_test.go b/consensus/state_test.go index 1a96a91f2..69ef58ef6 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -7,9 +7,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/counter" cstypes "github.com/consideritdone/landslidecore/consensus/types" "github.com/consideritdone/landslidecore/crypto/tmhash" @@ -19,6 +16,8 @@ import ( p2pmock "github.com/consideritdone/landslidecore/p2p/mock" tmproto "github.com/consideritdone/landslidecore/proto/tendermint/types" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) /* @@ -128,7 +127,6 @@ func TestStateProposerSelection2(t *testing.T) { ensureNewRound(newRoundCh, height, i+round+1) // wait for the new round event each round incrementRound(vss[1:]...) } - } // a non-validator should timeout into the prevote round @@ -645,7 +643,7 @@ func TestStateLockPOLRelock(t *testing.T) { ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) round++ // moving to the next round - //XXX: this isnt guaranteed to get there before the timeoutPropose ... + // XXX: this isnt guaranteed to get there before the timeoutPropose ... if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { t.Fatal(err) } @@ -950,7 +948,7 @@ func TestStateLockPOLSafety1(t *testing.T) { round++ // moving to the next round ensureNewRound(newRoundCh, height, round) - //XXX: this isnt guaranteed to get there before the timeoutPropose ... + // XXX: this isnt guaranteed to get there before the timeoutPropose ... if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { t.Fatal(err) } @@ -1108,7 +1106,6 @@ func TestStateLockPOLSafety2(t *testing.T) { ensureNoNewUnlock(unlockCh) ensurePrevote(voteCh, height, round) validatePrevote(t, cs1, round, vss[0], propBlockHash1) - } // 4 vals. @@ -1472,7 +1469,6 @@ func TestEmitNewValidBlockEventOnCommitWithoutBlock(t *testing.T) { assert.True(t, rs.Step == cstypes.RoundStepCommit) assert.True(t, rs.ProposalBlock == nil) assert.True(t, rs.ProposalBlockParts.Header().Equals(propBlockParts.Header())) - } // What we want: @@ -1841,7 +1837,6 @@ func TestStateOutputsBlockPartsStats(t *testing.T) { t.Errorf("should not output stats message after receiving the known block part!") case <-time.After(50 * time.Millisecond): } - } func TestStateOutputVoteStats(t *testing.T) { @@ -1874,7 +1869,6 @@ func TestStateOutputVoteStats(t *testing.T) { t.Errorf("should not output stats message after receiving the known vote or vote from bigger height") case <-time.After(50 * time.Millisecond): } - } func TestSignSameVoteTwice(t *testing.T) { diff --git a/consensus/ticker.go b/consensus/ticker.go index 489e9b046..be9295b01 100644 --- a/consensus/ticker.go +++ b/consensus/ticker.go @@ -7,9 +7,7 @@ import ( "github.com/consideritdone/landslidecore/libs/service" ) -var ( - tickTockBufferSize = 10 -) +var tickTockBufferSize = 10 // TimeoutTicker is a timer that schedules timeouts // conditional on the height/round/step in the timeoutInfo. @@ -50,7 +48,6 @@ func NewTimeoutTicker() TimeoutTicker { // OnStart implements service.Service. It starts the timeout routine. func (t *timeoutTicker) OnStart() error { - go t.timeoutRoutine() return nil diff --git a/consensus/wal.go b/consensus/wal.go index c4f51c57b..201d7bdf9 100644 --- a/consensus/wal.go +++ b/consensus/wal.go @@ -9,8 +9,6 @@ import ( "path/filepath" "time" - "github.com/gogo/protobuf/proto" - auto "github.com/consideritdone/landslidecore/libs/autofile" tmjson "github.com/consideritdone/landslidecore/libs/json" "github.com/consideritdone/landslidecore/libs/log" @@ -18,6 +16,7 @@ import ( "github.com/consideritdone/landslidecore/libs/service" tmcons "github.com/consideritdone/landslidecore/proto/tendermint/consensus" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/gogo/protobuf/proto" ) const ( @@ -89,7 +88,7 @@ var _ WAL = &BaseWAL{} // NewWAL returns a new write-ahead logger based on `baseWAL`, which implements // WAL. It's flushed and synced to disk every 2s and once when stopped. func NewWAL(walFile string, groupOptions ...func(*auto.Group)) (*BaseWAL, error) { - err := tmos.EnsureDir(filepath.Dir(walFile), 0700) + err := tmos.EnsureDir(filepath.Dir(walFile), 0o700) if err != nil { return nil, fmt.Errorf("failed to ensure WAL directory is in place: %w", err) } @@ -230,7 +229,8 @@ type WALSearchOptions struct { // CONTRACT: caller must close group reader. func (wal *BaseWAL) SearchForEndHeight( height int64, - options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) { + options *WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { var ( msg *TimedWALMessage gr *auto.GroupReader @@ -400,7 +400,7 @@ func (dec *WALDecoder) Decode() (*TimedWALMessage, error) { return nil, DataCorruptionError{fmt.Errorf("checksums do not match: read: %v, actual: %v", crc, actualCRC)} } - var res = new(tmcons.TimedWALMessage) + res := new(tmcons.TimedWALMessage) err = proto.Unmarshal(data, res) if err != nil { return nil, DataCorruptionError{fmt.Errorf("failed to decode data: %v", err)} diff --git a/consensus/wal_generator.go b/consensus/wal_generator.go index a213d110f..33c300b3d 100644 --- a/consensus/wal_generator.go +++ b/consensus/wal_generator.go @@ -9,8 +9,6 @@ import ( "testing" "time" - db "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/kvstore" cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/libs/log" @@ -20,6 +18,7 @@ import ( sm "github.com/consideritdone/landslidecore/state" "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" + db "github.com/tendermint/tm-db" ) // WALGenerateNBlocks generates a consensus WAL. It does this by spinning up a @@ -217,7 +216,8 @@ func (w *byteBufferWAL) FlushAndSync() error { return nil } func (w *byteBufferWAL) SearchForEndHeight( height int64, - options *WALSearchOptions) (rd io.ReadCloser, found bool, err error) { + options *WALSearchOptions, +) (rd io.ReadCloser, found bool, err error) { return nil, false, nil } diff --git a/consensus/wal_test.go b/consensus/wal_test.go index 87bf26c2e..0581922a2 100644 --- a/consensus/wal_test.go +++ b/consensus/wal_test.go @@ -6,20 +6,18 @@ import ( "io/ioutil" "os" "path/filepath" - // "sync" "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/consensus/types" "github.com/consideritdone/landslidecore/crypto/merkle" "github.com/consideritdone/landslidecore/libs/autofile" "github.com/consideritdone/landslidecore/libs/log" tmtypes "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -269,18 +267,23 @@ func BenchmarkWalDecode512B(b *testing.B) { func BenchmarkWalDecode10KB(b *testing.B) { benchmarkWalDecode(b, 10*1024) } + func BenchmarkWalDecode100KB(b *testing.B) { benchmarkWalDecode(b, 100*1024) } + func BenchmarkWalDecode1MB(b *testing.B) { benchmarkWalDecode(b, 1024*1024) } + func BenchmarkWalDecode10MB(b *testing.B) { benchmarkWalDecode(b, 10*1024*1024) } + func BenchmarkWalDecode100MB(b *testing.B) { benchmarkWalDecode(b, 100*1024*1024) } + func BenchmarkWalDecode1GB(b *testing.B) { benchmarkWalDecode(b, 1024*1024*1024) } diff --git a/mempool/cache_test.go b/mempool/cache_test.go index d6b586fb8..17d48d853 100644 --- a/mempool/cache_test.go +++ b/mempool/cache_test.go @@ -5,12 +5,11 @@ import ( "crypto/sha256" "testing" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/kvstore" abci "github.com/consideritdone/landslidecore/abci/types" "github.com/consideritdone/landslidecore/proxy" "github.com/consideritdone/landslidecore/types" + "github.com/stretchr/testify/require" ) func TestCacheRemove(t *testing.T) { diff --git a/mempool/clist_mempool.go b/mempool/clist_mempool.go index d045ec3ba..4c955c7fd 100644 --- a/mempool/clist_mempool.go +++ b/mempool/clist_mempool.go @@ -146,7 +146,7 @@ func (mem *CListMempool) InitWAL() error { walFile = walDir + "/wal" ) - const perm = 0700 + const perm = 0o700 if err := tmos.EnsureDir(walDir, perm); err != nil { return err } diff --git a/mempool/clist_mempool_test.go b/mempool/clist_mempool_test.go index 1be594ed1..1b0fcd68a 100644 --- a/mempool/clist_mempool_test.go +++ b/mempool/clist_mempool_test.go @@ -12,11 +12,6 @@ import ( "testing" "time" - "github.com/gogo/protobuf/proto" - gogotypes "github.com/gogo/protobuf/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/counter" "github.com/consideritdone/landslidecore/abci/example/kvstore" abciserver "github.com/consideritdone/landslidecore/abci/server" @@ -27,6 +22,10 @@ import ( "github.com/consideritdone/landslidecore/libs/service" "github.com/consideritdone/landslidecore/proxy" "github.com/consideritdone/landslidecore/types" + "github.com/gogo/protobuf/proto" + gogotypes "github.com/gogo/protobuf/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // A cleanupFunc cleans up any config / test files created for a particular @@ -598,7 +597,6 @@ func TestMempoolTxsBytes(t *testing.T) { assert.EqualValues(t, 1, mempool.TxsBytes()) mempool.RemoveTxByKey(TxKey([]byte{0x06}), true) assert.EqualValues(t, 0, mempool.TxsBytes()) - } // This will non-deterministically catch some concurrency failures like @@ -660,6 +658,7 @@ func newRemoteApp( } return clientCreator, server } + func checksumIt(data []byte) string { h := sha256.New() h.Write(data) diff --git a/mempool/errors.go b/mempool/errors.go index e33e14ca3..a492ce8ce 100644 --- a/mempool/errors.go +++ b/mempool/errors.go @@ -5,10 +5,8 @@ import ( "fmt" ) -var ( - // ErrTxInCache is returned to the client if we saw tx earlier - ErrTxInCache = errors.New("tx already exists in cache") -) +// ErrTxInCache is returned to the client if we saw tx earlier +var ErrTxInCache = errors.New("tx already exists in cache") // ErrTxTooLarge means the tx is too big to be sent in a message to other peers type ErrTxTooLarge struct { diff --git a/mempool/reactor_test.go b/mempool/reactor_test.go index 683fe9403..cbcfb3aba 100644 --- a/mempool/reactor_test.go +++ b/mempool/reactor_test.go @@ -8,11 +8,6 @@ import ( "testing" "time" - "github.com/fortytw2/leaktest" - "github.com/go-kit/log/term" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/consideritdone/landslidecore/abci/example/kvstore" abci "github.com/consideritdone/landslidecore/abci/types" cfg "github.com/consideritdone/landslidecore/config" @@ -23,6 +18,10 @@ import ( memproto "github.com/consideritdone/landslidecore/proto/tendermint/mempool" "github.com/consideritdone/landslidecore/proxy" "github.com/consideritdone/landslidecore/types" + "github.com/fortytw2/leaktest" + "github.com/go-kit/log/term" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -313,7 +312,6 @@ func makeAndConnectReactors(config *cfg.Config, n int) []*Reactor { p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("MEMPOOL", reactors[i]) return s - }, p2p.Connect2Switches) return reactors } 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 fae024ae1..70979fa5e 100644 --- a/node/node.go +++ b/node/node.go @@ -7,14 +7,10 @@ import ( "fmt" "net" "net/http" + _ "net/http/pprof" // nolint: gosec // securely exposed on separate, optional port "strings" "time" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/rs/cors" - dbm "github.com/tendermint/tm-db" - abci "github.com/consideritdone/landslidecore/abci/types" bcv0 "github.com/consideritdone/landslidecore/blockchain/v0" bcv1 "github.com/consideritdone/landslidecore/blockchain/v1" @@ -49,10 +45,11 @@ import ( "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" "github.com/consideritdone/landslidecore/version" - - _ "net/http/pprof" // nolint: gosec // securely exposed on separate, optional port - _ "github.com/lib/pq" // provide the psql db driver + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/rs/cors" + dbm "github.com/tendermint/tm-db" ) //------------------------------------------------------------------------------ @@ -270,7 +267,6 @@ func createAndStartIndexerService( eventBus *types.EventBus, logger log.Logger, ) (*txindex.IndexerService, txindex.TxIndexer, indexer.BlockIndexer, error) { - var ( txIndexer txindex.TxIndexer blockIndexer indexer.BlockIndexer @@ -319,8 +315,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) @@ -364,8 +360,8 @@ func onlyValidatorIsUs(state sm.State, pubKey crypto.PubKey) bool { } func createMempoolAndMempoolReactor(config *cfg.Config, proxyApp proxy.AppConns, - state sm.State, memplMetrics *mempl.Metrics, logger log.Logger) (*mempl.Reactor, *mempl.CListMempool) { - + state sm.State, memplMetrics *mempl.Metrics, logger log.Logger, +) (*mempl.Reactor, *mempl.CListMempool) { mempool := mempl.NewCListMempool( config.Mempool, proxyApp.Mempool(), @@ -386,8 +382,8 @@ func createMempoolAndMempoolReactor(config *cfg.Config, proxyApp proxy.AppConns, } 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 @@ -407,8 +403,8 @@ func createBlockchainReactor(config *cfg.Config, blockExec *sm.BlockExecutor, blockStore *store.BlockStore, fastSync bool, - logger log.Logger) (bcReactor p2p.Reactor, err error) { - + logger log.Logger, +) (bcReactor p2p.Reactor, err error) { switch config.FastSync.Version { case "v0": bcReactor = bcv0.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync) @@ -434,8 +430,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(), @@ -537,8 +533,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, @@ -560,8 +556,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())) @@ -587,8 +583,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{ @@ -610,7 +606,8 @@ func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config, // startStateSync starts an asynchronous state sync process, then switches to fast sync mode. func startStateSync(ssR *statesync.Reactor, bcR fastSyncReactor, conR *cs.Reactor, stateProvider statesync.StateProvider, config *cfg.StateSyncConfig, fastSync 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 { @@ -672,8 +669,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 @@ -1182,7 +1179,6 @@ func (n *Node) startRPC() ([]net.Listener, error) { } return listeners, nil - } // startPrometheusServer starts a Prometheus HTTP server, listening for metrics @@ -1354,9 +1350,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/node/node_test.go b/node/node_test.go index 34af6b615..cc60d96b9 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -9,11 +9,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - dbm "github.com/tendermint/tm-db" - "github.com/consideritdone/landslidecore/abci/example/kvstore" cfg "github.com/consideritdone/landslidecore/config" "github.com/consideritdone/landslidecore/crypto/ed25519" @@ -30,6 +25,9 @@ import ( "github.com/consideritdone/landslidecore/store" "github.com/consideritdone/landslidecore/types" tmtime "github.com/consideritdone/landslidecore/types/time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ) func TestNodeStartStop(t *testing.T) { diff --git a/vm/cmd/main.go b/vm/cmd/main.go index 913c5b253..6314c1ab7 100644 --- a/vm/cmd/main.go +++ b/vm/cmd/main.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/ulimit" "github.com/ava-labs/avalanchego/vms/rpcchainvm" From df4e7d8daeb079f18230027c0756fff9822a98ef Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 28 Jun 2023 17:43:00 +0800 Subject: [PATCH 3/5] update golangci-lint confit --- .golangci.yml | 5 +---- abci/example/kvstore/kvstore.go | 2 +- consensus/state.go | 14 +++++++------- p2p/upnp/upnp.go | 18 +++++++++--------- test/maverick/consensus/state.go | 10 +++++----- 5 files changed, 23 insertions(+), 26 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index d555d3eaf..d20edc9fd 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -43,10 +43,6 @@ issues: - text: 'ST1016:' linters: - stylecheck - - path: 'migrations' - text: 'SA1019:' - linters: - - staticcheck - text: 'SA1019: codec.NewAminoCodec is deprecated' # TODO remove once migration path is set out linters: - staticcheck @@ -74,6 +70,7 @@ linters-settings: - default # Default section: contains all imports that could not be matched to another section type. - prefix(cosmossdk.io) - prefix(github.com/cosmos/cosmos-sdk) + - prefix(github.com/ConsiderItDone/LandslideCore) revive: rules: - name: redefines-builtin-id diff --git a/abci/example/kvstore/kvstore.go b/abci/example/kvstore/kvstore.go index a7d79da1a..528e28bf3 100644 --- a/abci/example/kvstore/kvstore.go +++ b/abci/example/kvstore/kvstore.go @@ -151,7 +151,7 @@ func (app *Application) Query(reqQuery types.RequestQuery) (resQuery types.Respo resQuery.Value = value resQuery.Height = app.state.Height - return + return resQuery } resQuery.Key = reqQuery.Data diff --git a/consensus/state.go b/consensus/state.go index 1ff9514fb..90823dcb0 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -1203,14 +1203,14 @@ func (cs *State) createProposalBlock() (block *types.Block, blockParts *types.Pa default: // This shouldn't happen. cs.Logger.Error("propose step; cannot propose anything without commit for the previous block") - return + return nil, nil } if cs.privValidatorPubKey == nil { // If this node is a validator & proposer in the current round, it will // miss the opportunity to create a block. cs.Logger.Error("propose step; empty priv validator public key", "err", errPubKeyIsNotSet) - return + return nil, nil } proposerAddr := cs.privValidatorPubKey.Address() @@ -2006,12 +2006,12 @@ func (cs *State) addVote(vote *types.Vote, peerID p2p.ID) (added bool, err error if cs.Step != cstypes.RoundStepNewHeight { // Late precommit at prior height is ignored cs.Logger.Debug("precommit vote came in after commit timeout and has been ignored", "vote", vote) - return + return false, nil } added, err = cs.LastCommit.AddVote(vote) if !added { - return + return added, err } cs.Logger.Debug("added vote to last precommits", "last_commit", cs.LastCommit.StringShort()) @@ -2028,21 +2028,21 @@ func (cs *State) addVote(vote *types.Vote, peerID p2p.ID) (added bool, err error cs.enterNewRound(cs.Height, 0) } - return + return added, err } // Height mismatch is ignored. // Not necessarily a bad peer, but not favourable behaviour. if vote.Height != cs.Height { cs.Logger.Debug("vote ignored and not added", "vote_height", vote.Height, "cs_height", cs.Height, "peer", peerID) - return + return false, nil } height := cs.Height added, err = cs.Votes.AddVote(vote, peerID) if !added { // Either duplicate, or error upon cs.Votes.AddByIndex() - return + return added, err } if err := cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote}); err != nil { diff --git a/p2p/upnp/upnp.go b/p2p/upnp/upnp.go index 3777f4a1d..b08ae0749 100644 --- a/p2p/upnp/upnp.go +++ b/p2p/upnp/upnp.go @@ -204,33 +204,33 @@ func localIPv4() (net.IP, error) { func getServiceURL(rootURL string) (url, urnDomain string, err error) { r, err := http.Get(rootURL) // nolint: gosec if err != nil { - return + return url, urnDomain, err } defer r.Body.Close() if r.StatusCode >= 400 { err = errors.New(string(rune(r.StatusCode))) - return + return url, urnDomain, err } var root Root err = xml.NewDecoder(r.Body).Decode(&root) if err != nil { - return + return url, urnDomain, err } a := &root.Device if !strings.Contains(a.DeviceType, "InternetGatewayDevice:1") { err = errors.New("no InternetGatewayDevice") - return + return url, urnDomain, err } b := getChildDevice(a, "WANDevice:1") if b == nil { err = errors.New("no WANDevice") - return + return url, urnDomain, err } c := getChildDevice(b, "WANConnectionDevice:1") if c == nil { err = errors.New("no WANConnectionDevice") - return + return url, urnDomain, err } d := getChildService(c, "WANIPConnection:1") if d == nil { @@ -240,7 +240,7 @@ func getServiceURL(rootURL string) (url, urnDomain string, err error) { if d == nil { err = errors.New("no WANIPConnection") - return + return url, urnDomain, err } } // Extract the domain name, which isn't always 'schemas-upnp-org' @@ -289,7 +289,7 @@ func soapRequest(url, function, message, domain string) (r *http.Response, err e // log.Stderr(function, r.StatusCode) err = errors.New("error " + strconv.Itoa(r.StatusCode) + " for " + function) r = nil - return + return nil, err } return r, err } @@ -368,7 +368,7 @@ func (n *upnpNAT) AddPortMapping( defer response.Body.Close() } if err != nil { - return + return 0, err } // TODO: check response to see if the port was forwarded diff --git a/test/maverick/consensus/state.go b/test/maverick/consensus/state.go index f4f491ecc..57d71d836 100644 --- a/test/maverick/consensus/state.go +++ b/test/maverick/consensus/state.go @@ -366,11 +366,11 @@ func (cs *State) addVote( if cs.Step != cstypes.RoundStepNewHeight { // Late precommit at prior height is ignored cs.Logger.Debug("Precommit vote came in after commit timeout and has been ignored", "vote", vote) - return + return false, nil } added, err = cs.LastCommit.AddVote(vote) if !added { - return + return added, err } cs.Logger.Info(fmt.Sprintf("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) @@ -384,20 +384,20 @@ func (cs *State) addVote( cs.enterNewRound(cs.Height, 0) } - return + return added, err } // Height mismatch is ignored. // Not necessarily a bad peer, but not favourable behaviour. if vote.Height != cs.Height { cs.Logger.Debug("vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "peerID", peerID) - return + return false, nil } added, err = cs.Votes.AddVote(vote, peerID) if !added { // Either duplicate, or error upon cs.Votes.AddByIndex() - return + return added, err } _ = cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote}) From 4b06ea9123df235497b35623724a544efd8901ae Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 28 Jun 2023 17:45:08 +0800 Subject: [PATCH 4/5] complete linting --- p2p/conn/secret_connection.go | 8 ++++---- p2p/upnp/probe.go | 4 ++-- p2p/upnp/upnp.go | 14 +++++++------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/p2p/conn/secret_connection.go b/p2p/conn/secret_connection.go index 95134f98c..c6e212c0a 100644 --- a/p2p/conn/secret_connection.go +++ b/p2p/conn/secret_connection.go @@ -233,7 +233,7 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { if 0 < len(sc.recvBuffer) { n = copy(data, sc.recvBuffer) sc.recvBuffer = sc.recvBuffer[n:] - return + return n, nil } // read off the conn @@ -241,7 +241,7 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { defer pool.Put(sealedFrame) _, err = io.ReadFull(sc.conn, sealedFrame) if err != nil { - return + return 0, err } // decrypt the frame. @@ -322,7 +322,7 @@ func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byt // If error: if trs.FirstError() != nil { err = trs.FirstError() - return + return nil, err } // Otherwise: @@ -434,7 +434,7 @@ func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte // If error: if trs.FirstError() != nil { err = trs.FirstError() - return + return authSigMessage{}, err } _recvMsg := trs.FirstValue().(authSigMessage) diff --git a/p2p/upnp/probe.go b/p2p/upnp/probe.go index e6f42a102..a92a1642d 100644 --- a/p2p/upnp/probe.go +++ b/p2p/upnp/probe.go @@ -66,13 +66,13 @@ func testHairpin(listener net.Listener, extAddr string, logger log.Logger) (supp outConn, err := net.Dial("tcp", extAddr) if err != nil { logger.Info(fmt.Sprintf("Outgoing connection dial error: %v", err)) - return + return false } n, err := outConn.Write([]byte("test data")) if err != nil { logger.Info(fmt.Sprintf("Outgoing connection write error: %v", err)) - return + return false } logger.Info(fmt.Sprintf("Outgoing connection wrote %v bytes", n)) diff --git a/p2p/upnp/upnp.go b/p2p/upnp/upnp.go index b08ae0749..30d2faad7 100644 --- a/p2p/upnp/upnp.go +++ b/p2p/upnp/upnp.go @@ -39,11 +39,11 @@ type NAT interface { func Discover() (nat NAT, err error) { ssdp, err := net.ResolveUDPAddr("udp4", "239.255.255.250:1900") if err != nil { - return + return nil, err } conn, err := net.ListenPacket("udp4", ":0") if err != nil { - return + return nil, err } socket := conn.(*net.UDPConn) defer socket.Close() @@ -65,12 +65,12 @@ func Discover() (nat NAT, err error) { for i := 0; i < 3; i++ { _, err = socket.WriteToUDP(message, ssdp) if err != nil { - return + return nil, err } var n int _, _, err = socket.ReadFromUDP(answerBytes) if err != nil { - return + return nil, err } for { n, _, err = socket.ReadFromUDP(answerBytes) @@ -98,15 +98,15 @@ func Discover() (nat NAT, err error) { var serviceURL, urnDomain string serviceURL, urnDomain, err = getServiceURL(locURL) if err != nil { - return + return nil, err } var ourIP net.IP ourIP, err = localIPv4() if err != nil { - return + return nil, err } nat = &upnpNAT{serviceURL: serviceURL, ourIP: ourIP.String(), urnDomain: urnDomain} - return + return nat, nil } } err = errors.New("upnp port discovery failed") From fc8de107bd72f82a2f21260e1f5821ec4b6d137f Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 28 Jun 2023 17:46:19 +0800 Subject: [PATCH 5/5] mvdan's github actions for golang --- .github/workflows/test.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..f82c42537 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,16 @@ +# github.com/mvdan/github-actions-golang +on: [push, pull_request] +name: Test +jobs: + test: + strategy: + matrix: + go-version: [1.19.x, 1.20.x] + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: ${{ matrix.go-version }} + - run: go test ./...