From 351cd49c21c245fc35d69e60fb87382f0dc65a6e Mon Sep 17 00:00:00 2001 From: Alex Sharov Date: Wed, 10 Aug 2022 19:04:13 +0700 Subject: [PATCH] go1.19 gofmt (#4988) --- .github/workflows/ci.yml | 2 +- Makefile | 2 +- accounts/abi/abi_test.go | 35 +++-- accounts/abi/bind/backends/simulated_test.go | 23 ++-- accounts/abi/pack_test.go | 1 + accounts/abi/reflect.go | 22 +-- accounts/abi/unpack_test.go | 1 + cmd/bootnode/main.go | 3 +- cmd/devnettest/commands/all.go | 1 + cmd/devnettest/commands/event.go | 3 +- cmd/devnettest/commands/parity.go | 3 +- cmd/devnettest/commands/requests.go | 1 + cmd/devnettest/requests/requests.go | 3 +- cmd/devnettest/services/account.go | 1 + cmd/devnettest/services/block.go | 3 +- cmd/devnettest/services/event.go | 1 + cmd/downloader/main.go | 2 +- cmd/evm/internal/t8ntool/transition.go | 7 +- cmd/evm/main.go | 3 +- cmd/hack/db/lmdb.go | 3 +- cmd/hack/flow/flow.go | 2 +- cmd/observer/database/db_retrier.go | 5 +- cmd/observer/database/db_sqlite.go | 3 +- cmd/observer/database/db_sqlite_test.go | 5 +- cmd/observer/main.go | 3 +- cmd/observer/observer/command.go | 5 +- cmd/observer/observer/diplomacy.go | 5 +- cmd/observer/observer/diplomat.go | 3 +- cmd/observer/observer/handshake_test.go | 3 +- cmd/observer/observer/interrogator.go | 5 +- cmd/observer/observer/keygen.go | 3 +- cmd/observer/observer/keygen_test.go | 7 +- cmd/observer/observer/node_utils/node_addr.go | 3 +- cmd/observer/observer/node_utils/node_id.go | 3 +- .../observer/sentry_candidates/intake.go | 3 +- .../observer/sentry_candidates/log.go | 5 +- .../observer/sentry_candidates/log_test.go | 5 +- cmd/observer/observer/server.go | 5 +- cmd/observer/observer/status_logger.go | 3 +- .../reports/clients_estimate_report.go | 3 +- cmd/observer/reports/clients_report.go | 3 +- cmd/observer/reports/command.go | 1 + .../reports/sentry_candidates_report.go | 5 +- cmd/observer/reports/status_report.go | 3 +- cmd/observer/utils/pubkey_hex.go | 1 + cmd/observer/utils/retry.go | 3 +- cmd/p2psim/main.go | 21 ++- cmd/rpcdaemon/commands/eth_mining.go | 9 +- cmd/rpcdaemon/commands/starknet_api.go | 1 + cmd/rpcdaemon/commands/starknet_call.go | 5 +- .../commands/starknet_send_transaction.go | 1 + cmd/rpcdaemon/commands/validator_set.go | 17 +-- cmd/rpcdaemon22/commands/erigon_api.go | 1 + cmd/rpcdaemon22/commands/erigon_receipts.go | 5 +- cmd/rpcdaemon22/commands/eth_mining.go | 9 +- cmd/rpcdaemon22/commands/starknet_api.go | 1 + cmd/rpcdaemon22/commands/starknet_call.go | 5 +- .../commands/starknet_send_transaction.go | 1 + cmd/rpcdaemon22/commands/validator_set.go | 17 +-- cmd/rpctest/rpctest/bench1.go | 4 +- cmd/rpctest/rpctest/bench3.go | 5 +- cmd/rpctest/rpctest/bench4.go | 3 +- cmd/rpctest/rpctest/bench6.go | 3 +- cmd/rpctest/rpctest/bench_ethcall.go | 7 +- cmd/rpctest/rpctest/bench_ethgetlogs.go | 7 +- cmd/rpctest/rpctest/utils.go | 10 +- cmd/starknet/services/raw_tx_generator.go | 3 +- .../services/raw_tx_generator_test.go | 5 +- cmd/state/commands/erigon22.go | 2 +- cmd/state/commands/opcode_tracer.go | 4 +- cmd/utils/flags.go | 4 +- common/bitutil/compress_test.go | 3 +- common/compiler/solidity.go | 3 +- common/dbutils/history_index.go | 1 - common/debugprint/receipts.go | 6 +- common/hexutil/hexutil.go | 2 +- common/math/big.go | 8 +- common/mclock/mclock.go | 1 - consensus/aura/aura.go | 61 ++++----- consensus/aura/aura_test.go | 125 +++++++++--------- consensus/aura/aurainterfaces/interface.go | 2 +- consensus/aura/config.go | 2 +- consensus/aura/validators.go | 24 ++-- consensus/bor/bor.go | 2 +- consensus/bor/merkle.go | 2 +- consensus/bor/validator_set.go | 17 +-- consensus/ethash/api.go | 9 +- consensus/ethash/sealer.go | 9 +- consensus/misc/dao.go | 9 +- consensus/parlia/snapshot.go | 2 +- core/asm/asm_test.go | 3 +- core/genesis.go | 15 ++- core/mkalloc.go | 8 +- core/rlp_test.go | 1 + core/skip_analysis.go | 2 +- core/state/access_list_test.go | 3 +- core/state/database_test.go | 4 +- core/state/intra_block_state.go | 4 +- core/state_transition.go | 22 +-- core/vm/absint_cfg.go | 22 +-- core/vm/absint_cfg_proof_check.go | 3 +- core/vm/absint_cfg_proof_gen.go | 2 +- core/vm/access_list_tracer.go | 5 +- core/vm/contracts.go | 9 +- core/vm/gas_table.go | 18 +-- core/vm/instructions.go | 19 ++- core/vm/interpreter.go | 3 +- core/vm/lightclient/iavl/doc.go | 48 ++++--- core/vm/lightclient/iavl/key_format.go | 12 +- crypto/crypto.go | 2 +- eth/ethconfig/config.go | 2 +- eth/gasprice/feehistory.go | 9 +- eth/protocols/eth/discovery.go | 1 + eth/protocols/eth/handlers.go | 2 +- eth/stagedsync/stage_finish.go | 2 +- eth/stagedsync/stage_mining_create_block.go | 2 +- eth/stagedsync/stage_mining_exec.go | 2 +- eth/tracers/jsvm.go | 3 +- eth/tracers/jsvm_test.go | 3 +- eth/tracers/tracer.go | 3 +- ethdb/bitmapdb/dbutils.go | 1 + ethdb/olddb/mutation.go | 2 +- ethdb/olddb/object_db.go | 2 +- ethdb/olddb/tx_db.go | 6 +- ethdb/privateapi/engine_test.go | 4 +- ethdb/prune/storage_mode.go | 4 +- ethstats/ethstats.go | 15 ++- internal/cmdtest/test_cmd.go | 5 +- migrations/migrations.go | 18 +-- node/doc.go | 62 ++++----- node/node_example_test.go | 4 +- p2p/dial.go | 13 +- p2p/discover/v5_udp.go | 1 + p2p/discover/v5_udp_integration_test.go | 3 +- p2p/discover/v5wire/encoding.go | 3 + p2p/discover/v5wire/encoding_test.go | 3 +- p2p/enode/urlv4.go | 6 +- p2p/enr/enr.go | 2 +- p2p/message.go | 5 +- p2p/nat/nat.go | 16 +-- p2p/nat/nat_stun.go | 3 +- p2p/node_key_config.go | 3 +- p2p/simulations/adapters/types.go | 1 - p2p/simulations/mocker.go | 22 +-- params/denomination.go | 3 +- params/protocol_params.go | 2 +- params/version.go | 3 +- rlp/decode.go | 5 +- rlp/doc.go | 45 +++---- rpc/doc.go | 57 ++++---- rpc/handler.go | 15 +-- tests/block_test_util.go | 17 +-- tests/fuzzers/bls12381/precompile_fuzzer.go | 6 +- tests/fuzzers/difficulty/difficulty-fuzz.go | 6 +- turbo/adapter/ethapi/internal.go | 8 +- turbo/stages/blockchain_test.go | 35 +++-- turbo/stages/headerdownload/header_algos.go | 4 +- turbo/transactions/tracing.go | 2 +- turbo/trie/stream.go | 2 +- turbo/trie/trie.go | 14 +- turbo/trie/trie_root.go | 61 +++++---- turbo/trie/trie_test.go | 2 +- turbo/trie/witness_builder.go | 2 +- 163 files changed, 741 insertions(+), 639 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c24643c3..243cd8e1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,7 +60,7 @@ jobs: if: runner.os == 'Linux' uses: golangci/golangci-lint-action@v3 with: - version: v1.47 + version: v1.48 - name: Test run: make test diff --git a/Makefile b/Makefile index 1d10e205f..8dfbc0d6b 100644 --- a/Makefile +++ b/Makefile @@ -155,7 +155,7 @@ lintci: ## lintci-deps: (re)installs golangci-lint to build/bin/golangci-lint lintci-deps: rm -f ./build/bin/golangci-lint - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b ./build/bin v1.47.2 + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b ./build/bin v1.48.0 ## clean: cleans the go cache, build dir, libmdbx db dir clean: diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index ce1f35c65..ca2ff1656 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -13,6 +13,7 @@ // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . +// //nolint:scopelint package abi @@ -165,8 +166,9 @@ func TestInvalidABI(t *testing.T) { // TestConstructor tests a constructor function. // The test is based on the following contract: -// contract TestConstructor { -// constructor(uint256 a, uint256 b) public{} +// +// contract TestConstructor { +// constructor(uint256 a, uint256 b) public{} // } func TestConstructor(t *testing.T) { json := `[{ "inputs": [{"internalType": "uint256","name": "a","type": "uint256" },{ "internalType": "uint256","name": "b","type": "uint256"}],"stateMutability": "nonpayable","type": "constructor"}]` @@ -710,16 +712,19 @@ func TestBareEvents(t *testing.T) { } // TestUnpackEvent is based on this contract: -// contract T { -// event received(address sender, uint amount, bytes memo); -// event receivedAddr(address sender); -// function receive(bytes memo) external payable { -// received(msg.sender, msg.value, memo); -// receivedAddr(msg.sender); -// } -// } +// +// contract T { +// event received(address sender, uint amount, bytes memo); +// event receivedAddr(address sender); +// function receive(bytes memo) external payable { +// received(msg.sender, msg.value, memo); +// receivedAddr(msg.sender); +// } +// } +// // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt: -// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} +// +// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} func TestUnpackEvent(t *testing.T) { const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]` abi, err := JSON(strings.NewReader(abiJSON)) @@ -1064,8 +1069,9 @@ func TestDoubleDuplicateMethodNames(t *testing.T) { // TestDoubleDuplicateEventNames checks that if send0 already exists, there won't be a name // conflict and that the second send event will be renamed send1. // The test runs the abi of the following contract. -// contract DuplicateEvent { -// event send(uint256 a); +// +// contract DuplicateEvent { +// event send(uint256 a); // event send0(); // event send(); // } @@ -1092,7 +1098,8 @@ func TestDoubleDuplicateEventNames(t *testing.T) { // TestUnnamedEventParam checks that an event with unnamed parameters is // correctly handled. // The test runs the abi of the following contract. -// contract TestEvent { +// +// contract TestEvent { // event send(uint256, uint256); // } func TestUnnamedEventParam(t *testing.T) { diff --git a/accounts/abi/bind/backends/simulated_test.go b/accounts/abi/bind/backends/simulated_test.go index 3e813c911..19242607a 100644 --- a/accounts/abi/bind/backends/simulated_test.go +++ b/accounts/abi/bind/backends/simulated_test.go @@ -94,17 +94,17 @@ func TestSimulatedBackend(t *testing.T) { var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") -// the following is based on this contract: -// contract T { -// event received(address sender, uint amount, bytes memo); -// event receivedAddr(address sender); +// the following is based on this contract: +// contract T { +// event received(address sender, uint amount, bytes memo); +// event receivedAddr(address sender); // -// function receive(bytes calldata memo) external payable returns (string memory res) { -// emit received(msg.sender, msg.value, memo); -// emit receivedAddr(msg.sender); -// return "hello world"; -// } -// } +// function receive(bytes calldata memo) external payable returns (string memory res) { +// emit received(msg.sender, msg.value, memo); +// emit receivedAddr(msg.sender); +// return "hello world"; +// } +// } const abiJSON = `[ { "constant": false, "inputs": [ { "name": "memo", "type": "bytes" } ], "name": "receive", "outputs": [ { "name": "res", "type": "string" } ], "payable": true, "stateMutability": "payable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "memo", "type": "bytes" } ], "name": "received", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" } ], "name": "receivedAddr", "type": "event" } ]` const abiBin = `0x608060405234801561001057600080fd5b506102a0806100206000396000f3fe60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029` const deployedCode = `60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029` @@ -954,7 +954,8 @@ func TestSimulatedBackend_CodeAt(t *testing.T) { } // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt: -// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} +// +// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} func TestSimulatedBackend_PendingAndCallContract(t *testing.T) { testAddr := crypto.PubkeyToAddress(testKey.PublicKey) sim := simTestBackend(t, testAddr) diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index 9ac81e570..b1f5c4040 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -13,6 +13,7 @@ // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . +// //nolint:scopelint package abi diff --git a/accounts/abi/reflect.go b/accounts/abi/reflect.go index be417a8f2..bbec540b3 100644 --- a/accounts/abi/reflect.go +++ b/accounts/abi/reflect.go @@ -28,11 +28,13 @@ import ( // given type // e.g. turn // var fields []reflect.StructField -// fields = append(fields, reflect.StructField{ -// Name: "X", -// Type: reflect.TypeOf(new(big.Int)), -// Tag: reflect.StructTag("json:\"" + "x" + "\""), -// } +// +// fields = append(fields, reflect.StructField{ +// Name: "X", +// Type: reflect.TypeOf(new(big.Int)), +// Tag: reflect.StructTag("json:\"" + "x" + "\""), +// } +// // into // type TupleT struct { X *big.Int } func ConvertType(in interface{}, proto interface{}) interface{} { @@ -178,10 +180,14 @@ func setStruct(dst, src reflect.Value) error { // mapArgNamesToStructFields maps a slice of argument names to struct fields. // first round: for each Exportable field that contains a `abi:""` tag -// and this field name exists in the given argument name list, pair them together. +// +// and this field name exists in the given argument name list, pair them together. +// // second round: for each argument name that has not been already linked, -// find what variable is expected to be mapped into, if it exists and has not been -// used, pair them. +// +// find what variable is expected to be mapped into, if it exists and has not been +// used, pair them. +// // Note this function assumes the given value is a struct value. func mapArgNamesToStructFields(argNames []string, value reflect.Value) (map[string]string, error) { typ := value.Type() diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index 2d169d65f..22858cddb 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -13,6 +13,7 @@ // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . +// //nolint:scopelint package abi diff --git a/cmd/bootnode/main.go b/cmd/bootnode/main.go index 7a36c249c..852ad295f 100644 --- a/cmd/bootnode/main.go +++ b/cmd/bootnode/main.go @@ -21,10 +21,11 @@ import ( "crypto/ecdsa" "flag" "fmt" - "github.com/ledgerwatch/erigon-lib/common" "net" "os" + "github.com/ledgerwatch/erigon-lib/common" + "github.com/ledgerwatch/erigon/cmd/utils" "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/p2p/discover" diff --git a/cmd/devnettest/commands/all.go b/cmd/devnettest/commands/all.go index 4da64a164..4a44f8360 100644 --- a/cmd/devnettest/commands/all.go +++ b/cmd/devnettest/commands/all.go @@ -2,6 +2,7 @@ package commands import ( "fmt" + "github.com/spf13/cobra" ) diff --git a/cmd/devnettest/commands/event.go b/cmd/devnettest/commands/event.go index bd59b052c..69ca031ec 100644 --- a/cmd/devnettest/commands/event.go +++ b/cmd/devnettest/commands/event.go @@ -2,9 +2,10 @@ package commands import ( "fmt" + "sync" + "github.com/ledgerwatch/erigon/cmd/devnettest/services" "github.com/spf13/cobra" - "sync" ) var ( diff --git a/cmd/devnettest/commands/parity.go b/cmd/devnettest/commands/parity.go index e07d4169c..50fec5ade 100644 --- a/cmd/devnettest/commands/parity.go +++ b/cmd/devnettest/commands/parity.go @@ -2,9 +2,10 @@ package commands import ( "fmt" - "github.com/ledgerwatch/erigon/cmd/devnettest/services" "strings" + "github.com/ledgerwatch/erigon/cmd/devnettest/services" + "github.com/ledgerwatch/erigon/cmd/devnettest/requests" "github.com/ledgerwatch/erigon/common" "github.com/spf13/cobra" diff --git a/cmd/devnettest/commands/requests.go b/cmd/devnettest/commands/requests.go index d34bc3630..353e68670 100644 --- a/cmd/devnettest/commands/requests.go +++ b/cmd/devnettest/commands/requests.go @@ -2,6 +2,7 @@ package commands import ( "fmt" + "github.com/ledgerwatch/erigon/cmd/devnettest/requests" "github.com/spf13/cobra" ) diff --git a/cmd/devnettest/requests/requests.go b/cmd/devnettest/requests/requests.go index 3e9405c07..b12558fad 100644 --- a/cmd/devnettest/requests/requests.go +++ b/cmd/devnettest/requests/requests.go @@ -4,13 +4,14 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/ledgerwatch/erigon/cmd/devnettest/utils" "io" "net/http" "strconv" "strings" "time" + "github.com/ledgerwatch/erigon/cmd/devnettest/utils" + "github.com/ledgerwatch/erigon/cmd/rpctest/rpctest" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/core/types" diff --git a/cmd/devnettest/services/account.go b/cmd/devnettest/services/account.go index da067ed68..2b233ba91 100644 --- a/cmd/devnettest/services/account.go +++ b/cmd/devnettest/services/account.go @@ -2,6 +2,7 @@ package services import ( "fmt" + "github.com/ledgerwatch/erigon/cmd/devnettest/requests" "github.com/ledgerwatch/erigon/common" ) diff --git a/cmd/devnettest/services/block.go b/cmd/devnettest/services/block.go index 62ad69ead..cc2fc62f7 100644 --- a/cmd/devnettest/services/block.go +++ b/cmd/devnettest/services/block.go @@ -3,11 +3,12 @@ package services import ( "context" "fmt" - "github.com/ledgerwatch/erigon/cmd/devnettest/utils" "math/big" "os/exec" "time" + "github.com/ledgerwatch/erigon/cmd/devnettest/utils" + "github.com/holiman/uint256" "github.com/ledgerwatch/erigon/accounts/abi/bind" "github.com/ledgerwatch/erigon/accounts/abi/bind/backends" diff --git a/cmd/devnettest/services/event.go b/cmd/devnettest/services/event.go index a52489806..1073919f0 100644 --- a/cmd/devnettest/services/event.go +++ b/cmd/devnettest/services/event.go @@ -3,6 +3,7 @@ package services import ( "context" "fmt" + "github.com/ledgerwatch/erigon/cmd/devnettest/utils" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/rpc" diff --git a/cmd/downloader/main.go b/cmd/downloader/main.go index b93aae120..a14bf451a 100644 --- a/cmd/downloader/main.go +++ b/cmd/downloader/main.go @@ -233,7 +233,7 @@ var printTorrentHashes = &cobra.Command{ }, } -//nolint +// nolint func removePieceCompletionStorage(snapDir string) { _ = os.RemoveAll(filepath.Join(snapDir, "db")) _ = os.RemoveAll(filepath.Join(snapDir, ".torrent.db")) diff --git a/cmd/evm/internal/t8ntool/transition.go b/cmd/evm/internal/t8ntool/transition.go index b047cf0aa..7a75ffdc9 100644 --- a/cmd/evm/internal/t8ntool/transition.go +++ b/cmd/evm/internal/t8ntool/transition.go @@ -380,7 +380,7 @@ func getTransaction(txJson commands.RPCTransaction) (types.Transaction, error) { switch txJson.Type { case types.LegacyTxType, types.AccessListTxType: - var toAddr common.Address = common.Address{} + var toAddr = common.Address{} if txJson.To != nil { toAddr = *txJson.To } @@ -446,8 +446,9 @@ func getTransaction(txJson commands.RPCTransaction) (types.Transaction, error) { // signUnsignedTransactions converts the input txs to canonical transactions. // // The transactions can have two forms, either -// 1. unsigned or -// 2. signed +// 1. unsigned or +// 2. signed +// // For (1), r, s, v, need so be zero, and the `secretKey` needs to be set. // If so, we sign it here and now, with the given `secretKey` // If the condition above is not met, then it's considered a signed transaction. diff --git a/cmd/evm/main.go b/cmd/evm/main.go index e1cc6f43c..3c95823ac 100644 --- a/cmd/evm/main.go +++ b/cmd/evm/main.go @@ -19,10 +19,11 @@ package main import ( "fmt" - "github.com/ledgerwatch/log/v3" "math/big" "os" + "github.com/ledgerwatch/log/v3" + "github.com/ledgerwatch/erigon/cmd/evm/internal/t8ntool" "github.com/ledgerwatch/erigon/cmd/utils" "github.com/ledgerwatch/erigon/internal/flags" diff --git a/cmd/hack/db/lmdb.go b/cmd/hack/db/lmdb.go index 640bfb446..8b6c5d6c8 100644 --- a/cmd/hack/db/lmdb.go +++ b/cmd/hack/db/lmdb.go @@ -5,7 +5,6 @@ import ( "bytes" "context" "encoding/binary" - // "errors" "fmt" "io" @@ -212,7 +211,7 @@ type mdbx_db struct { txnID uint64 /* txnid of last committed modification */ } -//nolint // database size-related parameters, used as placeholder, doesn't have any meaning in this code +// nolint // database size-related parameters, used as placeholder, doesn't have any meaning in this code type mdbx_geo struct { grow_pv uint16 //nolint shrink_pv uint16 //nolint diff --git a/cmd/hack/flow/flow.go b/cmd/hack/flow/flow.go index e619c48e9..212e6f94f 100644 --- a/cmd/hack/flow/flow.go +++ b/cmd/hack/flow/flow.go @@ -344,7 +344,7 @@ func absIntAndJumpImprecision() { runCfgAnly("AndJumpImprecision00", s) } -//17891 transactions, 588 bytecode len +// 17891 transactions, 588 bytecode len func absIntTestSmallImprecision2() { const s = "6080604052600436106100405763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166393e84cd98114610045575b600080fd5b34801561005157600080fd5b5061005a61005c565b005b60008060008060008060008060008060008060008073a62142888aba8370742be823c1782d17a0389da173ffffffffffffffffffffffffffffffffffffffff1663747dff426040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004016101c060405180830381600087803b1580156100ea57600080fd5b505af11580156100fe573d6000803e3d6000fd5b505050506040513d6101c081101561011557600080fd5b8101908080519060200190929190805190602001909291908051906020019092919080519060200190929190805190602001909291908051906020019092919080519060200190929190805190602001909291908051906020019092919080519060200190929190805190602001909291908051906020019092919080519060200190929190805190602001909291905050509d509d509d509d509d509d509d509d509d509d509d509d509d509d508673ffffffffffffffffffffffffffffffffffffffff167318a0451ea56fd4ff58f59837e9ec30f346ffdca573ffffffffffffffffffffffffffffffffffffffff161415151561021057fe5b50505050505050505050505050505600a165627a7a72305820ec5e1703d3b74688c3350622a2bcfc097615733fa5f8df7adf51d66ebf42d0260029" runCfgAnly("SmallImprecision02", s) diff --git a/cmd/observer/database/db_retrier.go b/cmd/observer/database/db_retrier.go index 09674f2b2..2838b95f8 100644 --- a/cmd/observer/database/db_retrier.go +++ b/cmd/observer/database/db_retrier.go @@ -2,10 +2,11 @@ package database import ( "context" - "github.com/ledgerwatch/erigon/cmd/observer/utils" - "github.com/ledgerwatch/log/v3" "math/rand" "time" + + "github.com/ledgerwatch/erigon/cmd/observer/utils" + "github.com/ledgerwatch/log/v3" ) type DBRetrier struct { diff --git a/cmd/observer/database/db_sqlite.go b/cmd/observer/database/db_sqlite.go index b59e33974..0823b3715 100644 --- a/cmd/observer/database/db_sqlite.go +++ b/cmd/observer/database/db_sqlite.go @@ -5,10 +5,11 @@ import ( "database/sql" "errors" "fmt" - _ "modernc.org/sqlite" "net" "strings" "time" + + _ "modernc.org/sqlite" ) type DBSQLite struct { diff --git a/cmd/observer/database/db_sqlite_test.go b/cmd/observer/database/db_sqlite_test.go index c43e39f15..fdb18c767 100644 --- a/cmd/observer/database/db_sqlite_test.go +++ b/cmd/observer/database/db_sqlite_test.go @@ -2,11 +2,12 @@ package database import ( "context" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "net" "path/filepath" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDBSQLiteInsertAndFind(t *testing.T) { diff --git a/cmd/observer/main.go b/cmd/observer/main.go index 7063beb42..5173d4828 100644 --- a/cmd/observer/main.go +++ b/cmd/observer/main.go @@ -4,6 +4,8 @@ import ( "context" "errors" "fmt" + "path/filepath" + "github.com/ledgerwatch/erigon-lib/common" "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/cmd/observer/observer" @@ -11,7 +13,6 @@ import ( "github.com/ledgerwatch/erigon/cmd/utils" "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/log/v3" - "path/filepath" ) func mainWithFlags(ctx context.Context, flags observer.CommandFlags) error { diff --git a/cmd/observer/observer/command.go b/cmd/observer/observer/command.go index 24d139548..3686987c5 100644 --- a/cmd/observer/observer/command.go +++ b/cmd/observer/observer/command.go @@ -3,12 +3,13 @@ package observer import ( "context" "errors" + "runtime" + "time" + "github.com/ledgerwatch/erigon/cmd/utils" "github.com/ledgerwatch/erigon/internal/debug" "github.com/spf13/cobra" "github.com/urfave/cli" - "runtime" - "time" ) type CommandFlags struct { diff --git a/cmd/observer/observer/diplomacy.go b/cmd/observer/observer/diplomacy.go index 18be20f4f..836c0e57a 100644 --- a/cmd/observer/observer/diplomacy.go +++ b/cmd/observer/observer/diplomacy.go @@ -5,13 +5,14 @@ import ( "crypto/ecdsa" "errors" "fmt" + "sync/atomic" + "time" + "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/cmd/observer/observer/node_utils" "github.com/ledgerwatch/erigon/cmd/observer/utils" "github.com/ledgerwatch/log/v3" "golang.org/x/sync/semaphore" - "sync/atomic" - "time" ) type Diplomacy struct { diff --git a/cmd/observer/observer/diplomat.go b/cmd/observer/observer/diplomat.go index 9812b3bc0..b75757ef3 100644 --- a/cmd/observer/observer/diplomat.go +++ b/cmd/observer/observer/diplomat.go @@ -4,11 +4,12 @@ import ( "context" "crypto/ecdsa" "errors" + "time" + "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/p2p" "github.com/ledgerwatch/erigon/p2p/enode" "github.com/ledgerwatch/log/v3" - "time" ) type Diplomat struct { diff --git a/cmd/observer/observer/handshake_test.go b/cmd/observer/observer/handshake_test.go index 2691cd240..92dc7c12f 100644 --- a/cmd/observer/observer/handshake_test.go +++ b/cmd/observer/observer/handshake_test.go @@ -2,13 +2,14 @@ package observer import ( "context" + "testing" + "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/eth/protocols/eth" "github.com/ledgerwatch/erigon/p2p/enode" "github.com/ledgerwatch/erigon/params" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "testing" ) func TestHandshake(t *testing.T) { diff --git a/cmd/observer/observer/interrogator.go b/cmd/observer/observer/interrogator.go index a66bd8116..c1f9e83a6 100644 --- a/cmd/observer/observer/interrogator.go +++ b/cmd/observer/observer/interrogator.go @@ -5,14 +5,15 @@ import ( "crypto/ecdsa" "errors" "fmt" + "strings" + "time" + "github.com/ledgerwatch/erigon/cmd/observer/utils" "github.com/ledgerwatch/erigon/core/forkid" "github.com/ledgerwatch/erigon/eth/protocols/eth" "github.com/ledgerwatch/erigon/p2p/enode" "github.com/ledgerwatch/log/v3" "golang.org/x/sync/semaphore" - "strings" - "time" ) type DiscV4Transport interface { diff --git a/cmd/observer/observer/keygen.go b/cmd/observer/observer/keygen.go index 5de9bc3f9..525a8ad5a 100644 --- a/cmd/observer/observer/keygen.go +++ b/cmd/observer/observer/keygen.go @@ -3,10 +3,11 @@ package observer import ( "context" "crypto/ecdsa" + "time" + "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/p2p/enode" "github.com/ledgerwatch/log/v3" - "time" ) func keygen( diff --git a/cmd/observer/observer/keygen_test.go b/cmd/observer/observer/keygen_test.go index b57e56b0d..c2d0b0fb5 100644 --- a/cmd/observer/observer/keygen_test.go +++ b/cmd/observer/observer/keygen_test.go @@ -2,12 +2,13 @@ package observer import ( "context" - "github.com/ledgerwatch/erigon/crypto" - "github.com/ledgerwatch/log/v3" - "github.com/stretchr/testify/assert" "runtime" "testing" "time" + + "github.com/ledgerwatch/erigon/crypto" + "github.com/ledgerwatch/log/v3" + "github.com/stretchr/testify/assert" ) func TestKeygen(t *testing.T) { diff --git a/cmd/observer/observer/node_utils/node_addr.go b/cmd/observer/observer/node_utils/node_addr.go index 0e09add51..e59b762c5 100644 --- a/cmd/observer/observer/node_utils/node_addr.go +++ b/cmd/observer/observer/node_utils/node_addr.go @@ -2,11 +2,12 @@ package node_utils import ( "fmt" + "net" + "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/cmd/observer/utils" "github.com/ledgerwatch/erigon/p2p/enode" "github.com/ledgerwatch/erigon/p2p/enr" - "net" ) func MakeNodeAddr(node *enode.Node) database.NodeAddr { diff --git a/cmd/observer/observer/node_utils/node_id.go b/cmd/observer/observer/node_utils/node_id.go index e7c27f0e9..ae9dedb7e 100644 --- a/cmd/observer/observer/node_utils/node_id.go +++ b/cmd/observer/observer/node_utils/node_id.go @@ -3,9 +3,10 @@ package node_utils import ( "errors" "fmt" + "net/url" + "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/p2p/enode" - "net/url" ) func NodeID(node *enode.Node) (database.NodeID, error) { diff --git a/cmd/observer/observer/sentry_candidates/intake.go b/cmd/observer/observer/sentry_candidates/intake.go index d6ba42fe7..05ece15cb 100644 --- a/cmd/observer/observer/sentry_candidates/intake.go +++ b/cmd/observer/observer/sentry_candidates/intake.go @@ -3,6 +3,8 @@ package sentry_candidates import ( "context" "fmt" + "time" + "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/cmd/observer/observer/node_utils" "github.com/ledgerwatch/erigon/cmd/observer/utils" @@ -10,7 +12,6 @@ import ( "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/log/v3" "github.com/nxadm/tail" - "time" ) type Intake struct { diff --git a/cmd/observer/observer/sentry_candidates/log.go b/cmd/observer/observer/sentry_candidates/log.go index 71ad2a3f0..f8b5129de 100644 --- a/cmd/observer/observer/sentry_candidates/log.go +++ b/cmd/observer/observer/sentry_candidates/log.go @@ -4,12 +4,13 @@ import ( "bufio" "context" "encoding/json" - "github.com/ledgerwatch/erigon/eth/protocols/eth" - "github.com/nxadm/tail" "io" "strconv" "strings" "time" + + "github.com/ledgerwatch/erigon/eth/protocols/eth" + "github.com/nxadm/tail" ) type Log struct { diff --git a/cmd/observer/observer/sentry_candidates/log_test.go b/cmd/observer/observer/sentry_candidates/log_test.go index e1ac9c391..3afba7a0b 100644 --- a/cmd/observer/observer/sentry_candidates/log_test.go +++ b/cmd/observer/observer/sentry_candidates/log_test.go @@ -2,11 +2,12 @@ package sentry_candidates import ( "context" + "strings" + "testing" + "github.com/nxadm/tail" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "strings" - "testing" ) func TestLogRead(t *testing.T) { diff --git a/cmd/observer/observer/server.go b/cmd/observer/observer/server.go index 907b7c709..e89e70f08 100644 --- a/cmd/observer/observer/server.go +++ b/cmd/observer/observer/server.go @@ -5,6 +5,9 @@ import ( "crypto/ecdsa" "errors" "fmt" + "net" + "path/filepath" + "github.com/ledgerwatch/erigon/cmd/utils" "github.com/ledgerwatch/erigon/common/debug" "github.com/ledgerwatch/erigon/core/forkid" @@ -17,8 +20,6 @@ import ( "github.com/ledgerwatch/erigon/p2p/netutil" "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/log/v3" - "net" - "path/filepath" ) type Server struct { diff --git a/cmd/observer/observer/status_logger.go b/cmd/observer/observer/status_logger.go index 2757ecd7c..0a9363d3d 100644 --- a/cmd/observer/observer/status_logger.go +++ b/cmd/observer/observer/status_logger.go @@ -3,10 +3,11 @@ package observer import ( "context" "errors" + "time" + "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/cmd/observer/utils" "github.com/ledgerwatch/log/v3" - "time" ) func StatusLoggerLoop(ctx context.Context, db database.DB, networkID uint, period time.Duration, logger log.Logger) { diff --git a/cmd/observer/reports/clients_estimate_report.go b/cmd/observer/reports/clients_estimate_report.go index 4ec7d149b..9920d1f2d 100644 --- a/cmd/observer/reports/clients_estimate_report.go +++ b/cmd/observer/reports/clients_estimate_report.go @@ -3,9 +3,10 @@ package reports import ( "context" "fmt" - "github.com/ledgerwatch/erigon/cmd/observer/database" "math" "strings" + + "github.com/ledgerwatch/erigon/cmd/observer/database" ) type ClientsEstimateReportEntry struct { diff --git a/cmd/observer/reports/clients_report.go b/cmd/observer/reports/clients_report.go index e41b82e49..3ce39d99e 100644 --- a/cmd/observer/reports/clients_report.go +++ b/cmd/observer/reports/clients_report.go @@ -3,9 +3,10 @@ package reports import ( "context" "fmt" + "strings" + "github.com/ledgerwatch/erigon/cmd/observer/database" "github.com/ledgerwatch/erigon/cmd/observer/observer" - "strings" ) type ClientsReportEntry struct { diff --git a/cmd/observer/reports/command.go b/cmd/observer/reports/command.go index bba73cbe3..eace18c05 100644 --- a/cmd/observer/reports/command.go +++ b/cmd/observer/reports/command.go @@ -2,6 +2,7 @@ package reports import ( "context" + "github.com/ledgerwatch/erigon/cmd/utils" "github.com/spf13/cobra" "github.com/urfave/cli" diff --git a/cmd/observer/reports/sentry_candidates_report.go b/cmd/observer/reports/sentry_candidates_report.go index 29e7b7cfb..1c9ecc1b6 100644 --- a/cmd/observer/reports/sentry_candidates_report.go +++ b/cmd/observer/reports/sentry_candidates_report.go @@ -3,11 +3,12 @@ package reports import ( "context" "fmt" - "github.com/ledgerwatch/erigon/cmd/observer/database" - "github.com/ledgerwatch/erigon/cmd/observer/observer/sentry_candidates" "net/url" "os" "strings" + + "github.com/ledgerwatch/erigon/cmd/observer/database" + "github.com/ledgerwatch/erigon/cmd/observer/observer/sentry_candidates" ) type SentryCandidatesReport struct { diff --git a/cmd/observer/reports/status_report.go b/cmd/observer/reports/status_report.go index c094e9b20..11c800639 100644 --- a/cmd/observer/reports/status_report.go +++ b/cmd/observer/reports/status_report.go @@ -3,8 +3,9 @@ package reports import ( "context" "fmt" - "github.com/ledgerwatch/erigon/cmd/observer/database" "strings" + + "github.com/ledgerwatch/erigon/cmd/observer/database" ) type StatusReport struct { diff --git a/cmd/observer/utils/pubkey_hex.go b/cmd/observer/utils/pubkey_hex.go index 0644bba00..94a596f15 100644 --- a/cmd/observer/utils/pubkey_hex.go +++ b/cmd/observer/utils/pubkey_hex.go @@ -4,6 +4,7 @@ import ( "crypto/ecdsa" "encoding/hex" "fmt" + "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/p2p/enode" ) diff --git a/cmd/observer/utils/retry.go b/cmd/observer/utils/retry.go index ab745415a..14cdebc74 100644 --- a/cmd/observer/utils/retry.go +++ b/cmd/observer/utils/retry.go @@ -2,8 +2,9 @@ package utils import ( "context" - "github.com/ledgerwatch/log/v3" "time" + + "github.com/ledgerwatch/log/v3" ) func Retry( diff --git a/cmd/p2psim/main.go b/cmd/p2psim/main.go index 456b0ce0b..0031437c1 100644 --- a/cmd/p2psim/main.go +++ b/cmd/p2psim/main.go @@ -19,21 +19,20 @@ // Here is an example of creating a 2 node network with the first node // connected to the second: // -// $ p2psim node create -// Created node01 +// $ p2psim node create +// Created node01 // -// $ p2psim node start node01 -// Started node01 +// $ p2psim node start node01 +// Started node01 // -// $ p2psim node create -// Created node02 +// $ p2psim node create +// Created node02 // -// $ p2psim node start node02 -// Started node02 -// -// $ p2psim node connect node01 node02 -// Connected node01 to node02 +// $ p2psim node start node02 +// Started node02 // +// $ p2psim node connect node01 node02 +// Connected node01 to node02 package main import ( diff --git a/cmd/rpcdaemon/commands/eth_mining.go b/cmd/rpcdaemon/commands/eth_mining.go index 9f4cf4982..425692f50 100644 --- a/cmd/rpcdaemon/commands/eth_mining.go +++ b/cmd/rpcdaemon/commands/eth_mining.go @@ -43,10 +43,11 @@ func (api *APIImpl) Mining(ctx context.Context) (bool, error) { // GetWork returns a work package for external miner. // // The work package consists of 3 strings: -// result[0] - 32 bytes hex encoded current block header pow-hash -// result[1] - 32 bytes hex encoded seed hash used for DAG -// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty -// result[3] - hex encoded block number +// +// result[0] - 32 bytes hex encoded current block header pow-hash +// result[1] - 32 bytes hex encoded seed hash used for DAG +// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty +// result[3] - hex encoded block number func (api *APIImpl) GetWork(ctx context.Context) ([4]string, error) { var res [4]string repl, err := api.mining.GetWork(ctx, &txpool.GetWorkRequest{}) diff --git a/cmd/rpcdaemon/commands/starknet_api.go b/cmd/rpcdaemon/commands/starknet_api.go index 0423e31e7..ff05cc341 100644 --- a/cmd/rpcdaemon/commands/starknet_api.go +++ b/cmd/rpcdaemon/commands/starknet_api.go @@ -2,6 +2,7 @@ package commands import ( "context" + "github.com/ledgerwatch/erigon-lib/gointerfaces/starknet" "github.com/ledgerwatch/erigon-lib/gointerfaces/txpool" "github.com/ledgerwatch/erigon/common/hexutil" diff --git a/cmd/rpcdaemon/commands/starknet_call.go b/cmd/rpcdaemon/commands/starknet_call.go index 4b68eac9c..3312f6cda 100644 --- a/cmd/rpcdaemon/commands/starknet_call.go +++ b/cmd/rpcdaemon/commands/starknet_call.go @@ -2,13 +2,14 @@ package commands import ( "context" + "reflect" + "strings" + "github.com/ledgerwatch/erigon-lib/gointerfaces/starknet" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/rpc" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/wrapperspb" - "reflect" - "strings" ) type StarknetGrpcCallArgs struct { diff --git a/cmd/rpcdaemon/commands/starknet_send_transaction.go b/cmd/rpcdaemon/commands/starknet_send_transaction.go index 7bb90ea3b..8bd4b305c 100644 --- a/cmd/rpcdaemon/commands/starknet_send_transaction.go +++ b/cmd/rpcdaemon/commands/starknet_send_transaction.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + txPoolProto "github.com/ledgerwatch/erigon-lib/gointerfaces/txpool" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/hexutil" diff --git a/cmd/rpcdaemon/commands/validator_set.go b/cmd/rpcdaemon/commands/validator_set.go index 5ebbe3521..5ba50c09c 100644 --- a/cmd/rpcdaemon/commands/validator_set.go +++ b/cmd/rpcdaemon/commands/validator_set.go @@ -578,14 +578,15 @@ func (vals *ValidatorSet) updateWithChangeSet(changes []*bor.Validator, allowDel // UpdateWithChangeSet attempts to update the validator set with 'changes'. // It performs the following steps: -// - validates the changes making sure there are no duplicates and splits them in updates and deletes -// - verifies that applying the changes will not result in errors -// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities -// across old and newly added validators are fair -// - computes the priorities of new validators against the final set -// - applies the updates against the validator set -// - applies the removals against the validator set -// - performs scaling and centering of priority values +// - validates the changes making sure there are no duplicates and splits them in updates and deletes +// - verifies that applying the changes will not result in errors +// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities +// across old and newly added validators are fair +// - computes the priorities of new validators against the final set +// - applies the updates against the validator set +// - applies the removals against the validator set +// - performs scaling and centering of priority values +// // If an error is detected during verification steps, it is returned and the validator set // is not changed. func (vals *ValidatorSet) UpdateWithChangeSet(changes []*bor.Validator) error { diff --git a/cmd/rpcdaemon22/commands/erigon_api.go b/cmd/rpcdaemon22/commands/erigon_api.go index 85486e3f2..a83d82d9f 100644 --- a/cmd/rpcdaemon22/commands/erigon_api.go +++ b/cmd/rpcdaemon22/commands/erigon_api.go @@ -2,6 +2,7 @@ package commands import ( "context" + ethFilters "github.com/ledgerwatch/erigon/eth/filters" "github.com/ledgerwatch/erigon-lib/kv" diff --git a/cmd/rpcdaemon22/commands/erigon_receipts.go b/cmd/rpcdaemon22/commands/erigon_receipts.go index 296a1b9e3..d95d03bb1 100644 --- a/cmd/rpcdaemon22/commands/erigon_receipts.go +++ b/cmd/rpcdaemon22/commands/erigon_receipts.go @@ -3,6 +3,9 @@ package commands import ( "context" "fmt" + "sort" + "time" + "github.com/RoaringBitmap/roaring/roaring64" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/rawdb" @@ -13,8 +16,6 @@ import ( "github.com/ledgerwatch/erigon/rpc" "github.com/ledgerwatch/erigon/turbo/transactions" "github.com/ledgerwatch/log/v3" - "sort" - "time" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/core/types" diff --git a/cmd/rpcdaemon22/commands/eth_mining.go b/cmd/rpcdaemon22/commands/eth_mining.go index 9f4cf4982..425692f50 100644 --- a/cmd/rpcdaemon22/commands/eth_mining.go +++ b/cmd/rpcdaemon22/commands/eth_mining.go @@ -43,10 +43,11 @@ func (api *APIImpl) Mining(ctx context.Context) (bool, error) { // GetWork returns a work package for external miner. // // The work package consists of 3 strings: -// result[0] - 32 bytes hex encoded current block header pow-hash -// result[1] - 32 bytes hex encoded seed hash used for DAG -// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty -// result[3] - hex encoded block number +// +// result[0] - 32 bytes hex encoded current block header pow-hash +// result[1] - 32 bytes hex encoded seed hash used for DAG +// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty +// result[3] - hex encoded block number func (api *APIImpl) GetWork(ctx context.Context) ([4]string, error) { var res [4]string repl, err := api.mining.GetWork(ctx, &txpool.GetWorkRequest{}) diff --git a/cmd/rpcdaemon22/commands/starknet_api.go b/cmd/rpcdaemon22/commands/starknet_api.go index 0423e31e7..ff05cc341 100644 --- a/cmd/rpcdaemon22/commands/starknet_api.go +++ b/cmd/rpcdaemon22/commands/starknet_api.go @@ -2,6 +2,7 @@ package commands import ( "context" + "github.com/ledgerwatch/erigon-lib/gointerfaces/starknet" "github.com/ledgerwatch/erigon-lib/gointerfaces/txpool" "github.com/ledgerwatch/erigon/common/hexutil" diff --git a/cmd/rpcdaemon22/commands/starknet_call.go b/cmd/rpcdaemon22/commands/starknet_call.go index 4b68eac9c..3312f6cda 100644 --- a/cmd/rpcdaemon22/commands/starknet_call.go +++ b/cmd/rpcdaemon22/commands/starknet_call.go @@ -2,13 +2,14 @@ package commands import ( "context" + "reflect" + "strings" + "github.com/ledgerwatch/erigon-lib/gointerfaces/starknet" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/rpc" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/wrapperspb" - "reflect" - "strings" ) type StarknetGrpcCallArgs struct { diff --git a/cmd/rpcdaemon22/commands/starknet_send_transaction.go b/cmd/rpcdaemon22/commands/starknet_send_transaction.go index 7bb90ea3b..8bd4b305c 100644 --- a/cmd/rpcdaemon22/commands/starknet_send_transaction.go +++ b/cmd/rpcdaemon22/commands/starknet_send_transaction.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + txPoolProto "github.com/ledgerwatch/erigon-lib/gointerfaces/txpool" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/hexutil" diff --git a/cmd/rpcdaemon22/commands/validator_set.go b/cmd/rpcdaemon22/commands/validator_set.go index 5ebbe3521..5ba50c09c 100644 --- a/cmd/rpcdaemon22/commands/validator_set.go +++ b/cmd/rpcdaemon22/commands/validator_set.go @@ -578,14 +578,15 @@ func (vals *ValidatorSet) updateWithChangeSet(changes []*bor.Validator, allowDel // UpdateWithChangeSet attempts to update the validator set with 'changes'. // It performs the following steps: -// - validates the changes making sure there are no duplicates and splits them in updates and deletes -// - verifies that applying the changes will not result in errors -// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities -// across old and newly added validators are fair -// - computes the priorities of new validators against the final set -// - applies the updates against the validator set -// - applies the removals against the validator set -// - performs scaling and centering of priority values +// - validates the changes making sure there are no duplicates and splits them in updates and deletes +// - verifies that applying the changes will not result in errors +// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities +// across old and newly added validators are fair +// - computes the priorities of new validators against the final set +// - applies the updates against the validator set +// - applies the removals against the validator set +// - performs scaling and centering of priority values +// // If an error is detected during verification steps, it is returned and the validator set // is not changed. func (vals *ValidatorSet) UpdateWithChangeSet(changes []*bor.Validator) error { diff --git a/cmd/rpctest/rpctest/bench1.go b/cmd/rpctest/rpctest/bench1.go index 065c8fe62..51e1685d1 100644 --- a/cmd/rpctest/rpctest/bench1.go +++ b/cmd/rpctest/rpctest/bench1.go @@ -19,7 +19,9 @@ var routes map[string]string // but also can be used for comparing RPCDaemon with Geth // parameters: // needCompare - if false - doesn't call Erigon and doesn't compare responses -// use false value - to generate vegeta files, it's faster but we can generate vegeta files for Geth and Erigon +// +// use false value - to generate vegeta files, it's faster but we can generate vegeta files for Geth and Erigon +// // fullTest - if false - then call only methods which RPCDaemon currently supports func Bench1(erigonURL, gethURL string, needCompare bool, fullTest bool, blockFrom uint64, blockTo uint64, recordFile string) { setRoutes(erigonURL, gethURL) diff --git a/cmd/rpctest/rpctest/bench3.go b/cmd/rpctest/rpctest/bench3.go index 0e650da13..1f48921fa 100644 --- a/cmd/rpctest/rpctest/bench3.go +++ b/cmd/rpctest/rpctest/bench3.go @@ -3,10 +3,11 @@ package rpctest import ( "encoding/base64" "fmt" - "github.com/ledgerwatch/erigon/common" - "github.com/ledgerwatch/erigon/core/state" "net/http" "time" + + "github.com/ledgerwatch/erigon/common" + "github.com/ledgerwatch/erigon/core/state" ) func Bench3(erigon_url, geth_url string) { diff --git a/cmd/rpctest/rpctest/bench4.go b/cmd/rpctest/rpctest/bench4.go index 0d0f0b552..d8e0194aa 100644 --- a/cmd/rpctest/rpctest/bench4.go +++ b/cmd/rpctest/rpctest/bench4.go @@ -2,9 +2,10 @@ package rpctest import ( "fmt" - "github.com/ledgerwatch/erigon/common" "net/http" "time" + + "github.com/ledgerwatch/erigon/common" ) func Bench4(erigon_url string) { diff --git a/cmd/rpctest/rpctest/bench6.go b/cmd/rpctest/rpctest/bench6.go index fabe2ed70..08d66a7ba 100644 --- a/cmd/rpctest/rpctest/bench6.go +++ b/cmd/rpctest/rpctest/bench6.go @@ -2,9 +2,10 @@ package rpctest import ( "fmt" - "github.com/ledgerwatch/erigon/common" "net/http" "time" + + "github.com/ledgerwatch/erigon/common" ) func Bench6(erigon_url string) { diff --git a/cmd/rpctest/rpctest/bench_ethcall.go b/cmd/rpctest/rpctest/bench_ethcall.go index ddf1ba533..6d2e03545 100644 --- a/cmd/rpctest/rpctest/bench_ethcall.go +++ b/cmd/rpctest/rpctest/bench_ethcall.go @@ -12,9 +12,10 @@ import ( // but also can be used for comparing RPCDaemon with Geth or infura // parameters: // needCompare - if false - doesn't call Erigon and doesn't compare responses -// false value - to generate vegeta files, it's faster but we can generate vegeta files for Geth and Erigon -// recordFile stores all eth_call returned with success -// errorFile stores information when erigon and geth doesn't return same data +// +// false value - to generate vegeta files, it's faster but we can generate vegeta files for Geth and Erigon +// recordFile stores all eth_call returned with success +// errorFile stores information when erigon and geth doesn't return same data func BenchEthCall(erigonURL, gethURL string, needCompare, latest bool, blockFrom, blockTo uint64, recordFile string, errorFile string) { setRoutes(erigonURL, gethURL) var client = &http.Client{ diff --git a/cmd/rpctest/rpctest/bench_ethgetlogs.go b/cmd/rpctest/rpctest/bench_ethgetlogs.go index 0d02f1ade..61c921bf3 100644 --- a/cmd/rpctest/rpctest/bench_ethgetlogs.go +++ b/cmd/rpctest/rpctest/bench_ethgetlogs.go @@ -13,9 +13,10 @@ import ( // but also can be used for comparing RPCDaemon with Geth or infura // parameters: // needCompare - if false - doesn't call Erigon and doesn't compare responses -// false value - to generate vegeta files, it's faster but we can generate vegeta files for Geth and Erigon -// recordFile stores all eth_getlogs returned with success -// errorFile stores information when erigon and geth doesn't return same data +// +// false value - to generate vegeta files, it's faster but we can generate vegeta files for Geth and Erigon +// recordFile stores all eth_getlogs returned with success +// errorFile stores information when erigon and geth doesn't return same data func BenchEthGetLogs(erigonURL, gethURL string, needCompare bool, blockFrom uint64, blockTo uint64, recordFile string, errorFile string) { setRoutes(erigonURL, gethURL) var client = &http.Client{ diff --git a/cmd/rpctest/rpctest/utils.go b/cmd/rpctest/rpctest/utils.go index 629332ee4..76e85652a 100644 --- a/cmd/rpctest/rpctest/utils.go +++ b/cmd/rpctest/rpctest/utils.go @@ -40,7 +40,7 @@ func compareBlocks(b, bg *EthBlockByNumber) bool { return false } if (tx.To == nil && txg.To != nil) || (tx.To != nil && txg.To == nil) { - fmt.Printf("Tx %d different To nilness: %t %t\n", i, (tx.To == nil), (txg.To == nil)) + fmt.Printf("Tx %d different To nilness: %t %t\n", i, tx.To == nil, txg.To == nil) return false } if tx.To != nil && txg.To != nil && *tx.To != *txg.To { @@ -89,8 +89,8 @@ func compareTraces(trace, traceg *EthTxTrace) bool { } func compareJsonValues(prefix string, v, vg *fastjson.Value) error { - var vType fastjson.Type = fastjson.TypeNull - var vgType fastjson.Type = fastjson.TypeNull + var vType = fastjson.TypeNull + var vgType = fastjson.TypeNull if v != nil { vType = v.Type() } @@ -205,8 +205,8 @@ func compareErrors(errVal *fastjson.Value, errValg *fastjson.Value, methodName s return fmt.Errorf("different result (Erigon) returns OK, while G/OE returns error code=%d message=%s", errValg.GetInt("code"), errValg.GetStringBytes("message")) } } else { - s1 := strings.ToUpper(string((errVal.GetStringBytes("message")))) - s2 := strings.ToUpper(string((errValg.GetStringBytes("message")))) + s1 := strings.ToUpper(string(errVal.GetStringBytes("message"))) + s2 := strings.ToUpper(string(errValg.GetStringBytes("message"))) if strings.Compare(s1, s2) != 0 { if errs != nil { fmt.Printf("different error-message for method %s, errCtx: %s\n", methodName, errCtx) diff --git a/cmd/starknet/services/raw_tx_generator.go b/cmd/starknet/services/raw_tx_generator.go index f3728bcfa..c637bcbf1 100644 --- a/cmd/starknet/services/raw_tx_generator.go +++ b/cmd/starknet/services/raw_tx_generator.go @@ -7,6 +7,8 @@ import ( "encoding/hex" "errors" "fmt" + "io/fs" + "github.com/holiman/uint256" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon/common" @@ -17,7 +19,6 @@ import ( "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/erigon/rlp" "github.com/ledgerwatch/erigon/turbo/adapter" - "io/fs" ) var ( diff --git a/cmd/starknet/services/raw_tx_generator_test.go b/cmd/starknet/services/raw_tx_generator_test.go index e20ad33b8..89619e531 100644 --- a/cmd/starknet/services/raw_tx_generator_test.go +++ b/cmd/starknet/services/raw_tx_generator_test.go @@ -4,11 +4,12 @@ import ( "bytes" "context" "encoding/hex" - "github.com/ledgerwatch/erigon-lib/kv/memdb" - "github.com/ledgerwatch/erigon/cmd/starknet/services" "testing" "testing/fstest" + "github.com/ledgerwatch/erigon-lib/kv/memdb" + "github.com/ledgerwatch/erigon/cmd/starknet/services" + "github.com/ledgerwatch/erigon/crypto" ) diff --git a/cmd/state/commands/erigon22.go b/cmd/state/commands/erigon22.go index fbd56e1bf..60f931eae 100644 --- a/cmd/state/commands/erigon22.go +++ b/cmd/state/commands/erigon22.go @@ -204,7 +204,7 @@ func Erigon22(genesis *core.Genesis, logger log.Logger) error { } var inputBlockNum, outputBlockNum uint64 // Go-routine gathering results from the workers - var maxTxNum uint64 = txNums[len(txNums)-1] + var maxTxNum = txNums[len(txNums)-1] if workerCount > 1 { go func() { defer func() { diff --git a/cmd/state/commands/opcode_tracer.go b/cmd/state/commands/opcode_tracer.go index ee6a5d861..9f8c7e65c 100644 --- a/cmd/state/commands/opcode_tracer.go +++ b/cmd/state/commands/opcode_tracer.go @@ -57,8 +57,8 @@ var opcodeTracerCmd = &cobra.Command{ }, } -//const MaxUint = ^uint(0) -//const MaxUint64 = ^uint64(0) +// const MaxUint = ^uint(0) +// const MaxUint64 = ^uint64(0) const MaxUint16 = ^uint16(0) type opcode struct { diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 093836920..3c55d6986 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -851,7 +851,7 @@ func ParseNodesFromURLs(urls []string) ([]*enode.Node, error) { } // NewP2PConfig -// - doesn't setup bootnodes - they will set when genesisHash will know +// - doesn't setup bootnodes - they will set when genesisHash will know func NewP2PConfig( nodiscover bool, dirs datadir.Dirs, @@ -1182,7 +1182,7 @@ func setGPO(ctx *cli.Context, cfg *gasprice.Config) { } } -//nolint +// nolint func setGPOCobra(f *pflag.FlagSet, cfg *gasprice.Config) { if v := f.Int(GpoBlocksFlag.Name, GpoBlocksFlag.Value, GpoBlocksFlag.Usage); v != nil { cfg.Blocks = *v diff --git a/common/bitutil/compress_test.go b/common/bitutil/compress_test.go index 78637eeda..d797498ca 100644 --- a/common/bitutil/compress_test.go +++ b/common/bitutil/compress_test.go @@ -18,10 +18,11 @@ package bitutil import ( "bytes" - "github.com/ledgerwatch/log/v3" "math/rand" "testing" + "github.com/ledgerwatch/log/v3" + "github.com/ledgerwatch/erigon/common/hexutil" ) diff --git a/common/compiler/solidity.go b/common/compiler/solidity.go index 370ef5512..a8966bec3 100644 --- a/common/compiler/solidity.go +++ b/common/compiler/solidity.go @@ -22,10 +22,11 @@ import ( "encoding/json" "errors" "fmt" - "github.com/ledgerwatch/log/v3" "os/exec" "strconv" "strings" + + "github.com/ledgerwatch/log/v3" ) // Solidity contains information about the solidity compiler. diff --git a/common/dbutils/history_index.go b/common/dbutils/history_index.go index 4853a1efb..7794a11bf 100644 --- a/common/dbutils/history_index.go +++ b/common/dbutils/history_index.go @@ -14,7 +14,6 @@ func AccountIndexChunkKey(key []byte, blockNumber uint64) []byte { return blockNumBytes } -// func StorageIndexChunkKey(key []byte, blockNumber uint64) []byte { //remove incarnation and add block number blockNumBytes := make([]byte, common.AddressLength+common.HashLength+8) diff --git a/common/debugprint/receipts.go b/common/debugprint/receipts.go index f21beda47..ade3e65d1 100644 --- a/common/debugprint/receipts.go +++ b/common/debugprint/receipts.go @@ -6,7 +6,7 @@ import ( "github.com/ledgerwatch/erigon/core/types" ) -//nolint +// nolint func Transactions(ts1, ts2 types.Transactions) { fmt.Printf("==== Transactions ====\n") fmt.Printf("len(Transactions): %d, %d\n", len(ts1), len(ts2)) @@ -26,7 +26,7 @@ func Transactions(ts1, ts2 types.Transactions) { } } -//nolint +// nolint func Receipts(rs1, rs2 types.Receipts) { fmt.Printf("==== Receipts ====\n") fmt.Printf("len(Receipts): %d, %d\n", len(rs1), len(rs2)) @@ -75,7 +75,7 @@ func Receipts(rs1, rs2 types.Receipts) { } } -//nolint +// nolint func Headers(h1, h2 *types.Header) { fmt.Printf("==== Header ====\n") fmt.Printf("root: %x, %x\n", h1.Root, h2.Root) diff --git a/common/hexutil/hexutil.go b/common/hexutil/hexutil.go index ad59d2ff8..f74ea23db 100644 --- a/common/hexutil/hexutil.go +++ b/common/hexutil/hexutil.go @@ -18,7 +18,7 @@ Package hexutil implements hex encoding with 0x prefix. This encoding is used by the Ethereum RPC API to transport binary data in JSON payloads. -Encoding Rules +# Encoding Rules All hex data must have prefix "0x". diff --git a/common/math/big.go b/common/math/big.go index 29a2a8eb0..e95f7fa1c 100644 --- a/common/math/big.go +++ b/common/math/big.go @@ -245,10 +245,10 @@ func U256Bytes(n *big.Int) []byte { // S256 interprets x as a two's complement number. // x must not exceed 256 bits (the result is undefined if it does) and is not modified. // -// S256(0) = 0 -// S256(1) = 1 -// S256(2**255) = -2**255 -// S256(2**256-1) = -1 +// S256(0) = 0 +// S256(1) = 1 +// S256(2**255) = -2**255 +// S256(2**256-1) = -1 func S256(x *big.Int) *big.Int { if x.Cmp(tt255) < 0 { return x diff --git a/common/mclock/mclock.go b/common/mclock/mclock.go index c05738cf2..915081ff2 100644 --- a/common/mclock/mclock.go +++ b/common/mclock/mclock.go @@ -19,7 +19,6 @@ package mclock import ( "time" - _ "unsafe" // for go:linkname ) diff --git a/consensus/aura/aura.go b/consensus/aura/aura.go index 67e081973..1700cb1d0 100644 --- a/consensus/aura/aura.go +++ b/consensus/aura/aura.go @@ -140,7 +140,7 @@ type PermissionedStep struct { type ReceivedStepHashes map[uint64]map[common.Address]common.Hash //BTreeMap<(u64, Address), H256> -//nolint +// nolint func (r ReceivedStepHashes) get(step uint64, author common.Address) (common.Hash, bool) { res, ok := r[step] if !ok { @@ -150,7 +150,7 @@ func (r ReceivedStepHashes) get(step uint64, author common.Address) (common.Hash return result, ok } -//nolint +// nolint func (r ReceivedStepHashes) insert(step uint64, author common.Address, blockHash common.Hash) { res, ok := r[step] if !ok { @@ -160,7 +160,7 @@ func (r ReceivedStepHashes) insert(step uint64, author common.Address, blockHash res[author] = blockHash } -//nolint +// nolint func (r ReceivedStepHashes) dropAncient(step uint64) { for i := range r { if i < step { @@ -169,7 +169,7 @@ func (r ReceivedStepHashes) dropAncient(step uint64) { } } -//nolint +// nolint type EpochManager struct { epochTransitionHash common.Hash // H256, epochTransitionNumber uint64 // BlockNumber @@ -188,7 +188,7 @@ func (e *EpochManager) noteNewEpoch() { e.force = true } // zoomValidators - Zooms to the epoch after the header with the given hash. Returns true if succeeded, false otherwise. // It's analog of zoom_to_after function in OE, but doesn't require external locking -//nolint +// nolint func (e *EpochManager) zoomToAfter(chain consensus.ChainHeaderReader, er consensus.EpochReader, validators ValidatorSet, hash common.Hash, call consensus.SystemCall) (*RollingFinality, uint64, bool) { var lastWasParent bool if e.finalityChecker.lastPushed != nil { @@ -246,12 +246,12 @@ func (e *EpochManager) zoomToAfter(chain consensus.ChainHeaderReader, er consens return e.finalityChecker, e.epochTransitionNumber, true } -/// Get the transition to the epoch the given parent hash is part of -/// or transitions to. -/// This will give the epoch that any children of this parent belong to. -/// -/// The block corresponding the the parent hash must be stored already. -//nolint +// / Get the transition to the epoch the given parent hash is part of +// / or transitions to. +// / This will give the epoch that any children of this parent belong to. +// / +// / The block corresponding the the parent hash must be stored already. +// nolint func epochTransitionFor2(chain consensus.ChainHeaderReader, e consensus.EpochReader, parentHash common.Hash) (transition EpochTransition, ok bool) { //TODO: probably this version of func doesn't support non-canonical epoch transitions h := chain.GetHeaderByHash(parentHash) @@ -268,7 +268,7 @@ func epochTransitionFor2(chain consensus.ChainHeaderReader, e consensus.EpochRea return EpochTransition{BlockNumber: num, BlockHash: hash, ProofRlp: transitionProof}, true } -//nolint +// nolint func epochTransitionFor(chain consensus.ChainHeaderReader, e consensus.EpochReader, parentHash common.Hash) (transition EpochTransition, ok bool) { // slow path: loop back block by block for { @@ -321,7 +321,7 @@ func epochTransitionFor(chain consensus.ChainHeaderReader, e consensus.EpochRead } // AuRa -//nolint +// nolint type AuRa struct { db kv.RwDB // Database to store and retrieve snapshot checkpoints exitCh chan struct{} @@ -522,7 +522,7 @@ func (c *AuRa) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Hea return nil } -//nolint +// nolint func (c *AuRa) hasReceivedStepHashes(step uint64, author common.Address, newHash common.Hash) bool { /* self @@ -534,7 +534,7 @@ func (c *AuRa) hasReceivedStepHashes(step uint64, author common.Address, newHash return false } -//nolint +// nolint func (c *AuRa) insertReceivedStepHashes(step uint64, author common.Address, newHash common.Hash) { /* self.received_step_hashes @@ -543,7 +543,7 @@ func (c *AuRa) insertReceivedStepHashes(step uint64, author common.Address, newH */ } -//nolint +// nolint func (c *AuRa) verifyFamily(chain consensus.ChainHeaderReader, e consensus.EpochReader, header *types.Header, call consensus.Call, syscall consensus.SystemCall) error { // TODO: I call it from Initialize - because looks like no much reason to have separated "verifyFamily" call @@ -830,7 +830,7 @@ func (c *AuRa) Initialize(config *params.ChainConfig, chain consensus.ChainHeade } -//word `signal epoch` == word `pending epoch` +// word `signal epoch` == word `pending epoch` func (c *AuRa) Finalize(config *params.ChainConfig, header *types.Header, state *state.IntraBlockState, txs types.Transactions, uncles []*types.Header, receipts types.Receipts, e consensus.EpochReader, chain consensus.ChainHeaderReader, syscall consensus.SystemCall, @@ -1200,7 +1200,7 @@ func (c *AuRa) epochSet(chain consensus.ChainHeaderReader, e consensus.EpochRead return finalityChecker.signers, epochTransitionNumber, nil } -//nolint +// nolint func headerStep(current *types.Header) (val uint64, err error) { if len(current.Seal) < 1 { panic("was either checked with verify_block_basic or is genesis; has 2 fields; qed (Make sure the spec file has a correct genesis seal)") @@ -1235,7 +1235,8 @@ func (c *AuRa) CalcDifficulty(chain consensus.ChainHeaderReader, time, parentTim } // calculateScore - analog of PoW difficulty: -// sqrt(U256::max_value()) + parent_step - current_step + current_empty_steps +// +// sqrt(U256::max_value()) + parent_step - current_step + current_empty_steps func calculateScore(parentStep, currentStep, currentEmptySteps uint64) *uint256.Int { maxU128 := uint256.NewInt(0).SetAllOne() maxU128 = maxU128.Rsh(maxU128, 128) @@ -1268,7 +1269,7 @@ func (c *AuRa) APIs(chain consensus.ChainHeaderReader) []rpc.API { } } -//nolint +// nolint func (c *AuRa) emptySteps(fromStep, toStep uint64, parentHash common.Hash) []EmptyStep { from := EmptyStep{step: fromStep + 1, parentHash: parentHash} to := EmptyStep{step: toStep} @@ -1376,7 +1377,7 @@ func blockRewardAbi() abi.ABI { // the `parent_hash` in order to save space. The included signature is of the original empty step // message, which can be reconstructed by using the parent hash of the block in which this sealed // empty message is inc luded. -//nolint +// nolint type SealedEmptyStep struct { signature []byte // H520 step uint64 @@ -1423,12 +1424,12 @@ func headerEmptyStepsRaw(header *types.Header) []byte { // // An empty step message is created _instead of_ a block if there are no pending transactions. // It cannot itself be a parent, and `parent_hash` always points to the most recent block. E.g.: -// * Validator A creates block `bA`. -// * Validator B has no pending transactions, so it signs an empty step message `mB` -// instead whose hash points to block `bA`. -// * Validator C also has no pending transactions, so it also signs an empty step message `mC` -// instead whose hash points to block `bA`. -// * Validator D creates block `bD`. The parent is block `bA`, and the header includes `mB` and `mC`. +// - Validator A creates block `bA`. +// - Validator B has no pending transactions, so it signs an empty step message `mB` +// instead whose hash points to block `bA`. +// - Validator C also has no pending transactions, so it also signs an empty step message `mC` +// instead whose hash points to block `bA`. +// - Validator D creates block `bD`. The parent is block `bA`, and the header includes `mB` and `mC`. type EmptyStep struct { // The signature of the other two fields, by the message's author. signature []byte // H520 @@ -1480,7 +1481,7 @@ func (s *EmptyStep) verify(validators ValidatorSet) (bool, error) { //nolint return true, nil } -//nolint +// nolint func (s *EmptyStep) author() (common.Address, error) { sRlp, err := EmptyStepRlp(s.step, s.parentHash) if err != nil { @@ -1538,7 +1539,7 @@ func EmptyStepRlp(step uint64, parentHash common.Hash) ([]byte, error) { return rlp.EncodeToBytes(A{s: step, h: parentHash}) } -//nolint +// nolint type unAssembledHeader struct { hash common.Hash number uint64 @@ -1568,7 +1569,7 @@ func (u unAssembledHeaders) Front() *unAssembledHeader { // RollingFinality checker for authority round consensus. // Stores a chain of unfinalized hashes that can be pushed onto. -//nolint +// nolint type RollingFinality struct { headers unAssembledHeaders //nolint signers *SimpleList diff --git a/consensus/aura/aura_test.go b/consensus/aura/aura_test.go index a04eda652..9c2ad12bc 100644 --- a/consensus/aura/aura_test.go +++ b/consensus/aura/aura_test.go @@ -18,77 +18,78 @@ import ( ) /* - #[test] - fn block_reward_contract() { - let spec = Spec::new_test_round_block_reward_contract(); - let tap = Arc::new(AccountProvider::transient_provider()); +#[test] - let addr1 = tap.insert_account(keccak("1").into(), &"1".into()).unwrap(); + fn block_reward_contract() { + let spec = Spec::new_test_round_block_reward_contract(); + let tap = Arc::new(AccountProvider::transient_provider()); - let engine = &*spec.engine; - let genesis_header = spec.genesis_header(); - let db1 = spec - .ensure_db_good(get_temp_state_db(), &Default::default()) - .unwrap(); - let db2 = spec - .ensure_db_good(get_temp_state_db(), &Default::default()) - .unwrap(); + let addr1 = tap.insert_account(keccak("1").into(), &"1".into()).unwrap(); - let last_hashes = Arc::new(vec![genesis_header.hash()]); + let engine = &*spec.engine; + let genesis_header = spec.genesis_header(); + let db1 = spec + .ensure_db_good(get_temp_state_db(), &Default::default()) + .unwrap(); + let db2 = spec + .ensure_db_good(get_temp_state_db(), &Default::default()) + .unwrap(); - let client = generate_dummy_client_with_spec(Spec::new_test_round_block_reward_contract); - engine.register_client(Arc::downgrade(&client) as _); + let last_hashes = Arc::new(vec![genesis_header.hash()]); - // step 2 - let b1 = OpenBlock::new( - engine, - Default::default(), - false, - db1, - &genesis_header, - last_hashes.clone(), - addr1, - (3141562.into(), 31415620.into()), - vec![], - false, - None, - ) - .unwrap(); - let b1 = b1.close_and_lock().unwrap(); + let client = generate_dummy_client_with_spec(Spec::new_test_round_block_reward_contract); + engine.register_client(Arc::downgrade(&client) as _); - // since the block is empty it isn't sealed and we generate empty steps - engine.set_signer(Some(Box::new((tap.clone(), addr1, "1".into())))); - assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); - engine.step(); + // step 2 + let b1 = OpenBlock::new( + engine, + Default::default(), + false, + db1, + &genesis_header, + last_hashes.clone(), + addr1, + (3141562.into(), 31415620.into()), + vec![], + false, + None, + ) + .unwrap(); + let b1 = b1.close_and_lock().unwrap(); - // step 3 - // the signer of the accumulated empty step message should be rewarded - let b2 = OpenBlock::new( - engine, - Default::default(), - false, - db2, - &genesis_header, - last_hashes.clone(), - addr1, - (3141562.into(), 31415620.into()), - vec![], - false, - None, - ) - .unwrap(); - let addr1_balance = b2.state.balance(&addr1).unwrap(); + // since the block is empty it isn't sealed and we generate empty steps + engine.set_signer(Some(Box::new((tap.clone(), addr1, "1".into())))); + assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); + engine.step(); - // after closing the block `addr1` should be reward twice, one for the included empty step - // message and another for block creation - let b2 = b2.close_and_lock().unwrap(); + // step 3 + // the signer of the accumulated empty step message should be rewarded + let b2 = OpenBlock::new( + engine, + Default::default(), + false, + db2, + &genesis_header, + last_hashes.clone(), + addr1, + (3141562.into(), 31415620.into()), + vec![], + false, + None, + ) + .unwrap(); + let addr1_balance = b2.state.balance(&addr1).unwrap(); - // the contract rewards (1000 + kind) for each benefactor/reward kind - assert_eq!( - b2.state.balance(&addr1).unwrap(), - addr1_balance + (1000 + 0) + (1000 + 2), - ) - } + // after closing the block `addr1` should be reward twice, one for the included empty step + // message and another for block creation + let b2 = b2.close_and_lock().unwrap(); + + // the contract rewards (1000 + kind) for each benefactor/reward kind + assert_eq!( + b2.state.balance(&addr1).unwrap(), + addr1_balance + (1000 + 0) + (1000 + 2), + ) + } */ func TestRewardContract(t *testing.T) { t.Skip("not ready yet") diff --git a/consensus/aura/aurainterfaces/interface.go b/consensus/aura/aurainterfaces/interface.go index 367e34651..0f2af178a 100644 --- a/consensus/aura/aurainterfaces/interface.go +++ b/consensus/aura/aurainterfaces/interface.go @@ -45,7 +45,7 @@ type SealRegular SealKind // Engine does not generate seal for this block right now. type None SealKind -/// The type of sealing the engine is currently able to perform. +// / The type of sealing the engine is currently able to perform. type SealingState uint8 const ( diff --git a/consensus/aura/config.go b/consensus/aura/config.go index 5e12fe640..3c71b32d8 100644 --- a/consensus/aura/config.go +++ b/consensus/aura/config.go @@ -73,7 +73,7 @@ func newValidatorSetFromJson(j *ValidatorSetJson, posdaoTransition *uint64) Vali return nil } -//TODO: StepDuration and BlockReward - now are uint64, but it can be an object in non-sokol consensus +// TODO: StepDuration and BlockReward - now are uint64, but it can be an object in non-sokol consensus type JsonSpec struct { StepDuration *uint64 `json:"stepDuration"` // Block duration, in seconds. Validators *ValidatorSetJson `json:"validators"` // Valid authorities diff --git a/consensus/aura/validators.go b/consensus/aura/validators.go index bab7e6759..3033c1912 100644 --- a/consensus/aura/validators.go +++ b/consensus/aura/validators.go @@ -22,7 +22,7 @@ import ( "go.uber.org/atomic" ) -//nolint +// nolint type CallResults struct { data []byte proof [][]byte @@ -192,7 +192,7 @@ func count(s ValidatorSet, h common.Hash, call consensus.Call) (uint64, error) { return s.countWithCaller(h, call) } -//nolint +// nolint type MultiItem struct { num uint64 hash common.Hash @@ -274,7 +274,7 @@ func (s *Multi) onCloseBlock(header *types.Header, address common.Address) error } // TODO: do we need add `proof` argument? -//nolint +// nolint func (s *Multi) epochSet(firstInEpoch bool, num uint64, proof []byte, call consensus.SystemCall) (SimpleList, common.Hash, error) { setBlock, set := s.correctSetByNumber(num) firstInEpoch = setBlock == num @@ -333,20 +333,20 @@ func NewSimpleList(validators []common.Address) *SimpleList { return &SimpleList{validators: validators} } -//nolint +// nolint type ReportQueueItem struct { addr common.Address blockNum uint64 data []byte } -//nolint +// nolint type ReportQueue struct { mu sync.RWMutex list *list.List } -//nolint +// nolint func (q *ReportQueue) push(addr common.Address, blockNum uint64, data []byte) { q.mu.Lock() defer q.mu.Unlock() @@ -354,7 +354,7 @@ func (q *ReportQueue) push(addr common.Address, blockNum uint64, data []byte) { } // Filters reports of validators that have already been reported or are banned. -//nolint +// nolint func (q *ReportQueue) filter(abi aurainterfaces.ValidatorSetABI, client client, ourAddr, contractAddr common.Address) error { q.mu.Lock() defer q.mu.Unlock() @@ -384,7 +384,7 @@ func (q *ReportQueue) filter(abi aurainterfaces.ValidatorSetABI, client client, } // Removes reports from the queue if it contains more than `MAX_QUEUED_REPORTS` entries. -//nolint +// nolint func (q *ReportQueue) truncate() { // The maximum number of reports to keep queued. const MaxQueuedReports = 10 @@ -405,7 +405,7 @@ func (q *ReportQueue) truncate() { } // The validator contract should have the following interface: -//nolint +// nolint type ValidatorSafeContract struct { contractAddress common.Address validators *lru.Cache // RwLock>, @@ -439,7 +439,7 @@ func NewValidatorSafeContract(contractAddress common.Address, posdaoTransition * // but with the same parameters. // // Returns a list of contract calls to be pushed onto the new block. -//func generateEngineTransactions(_firstInEpoch bool, _header *types.Header, _call SystemCall) -> Result, EthcoreError> +// func generateEngineTransactions(_firstInEpoch bool, _header *types.Header, _call SystemCall) -> Result, EthcoreError> func (s *ValidatorSafeContract) epochSet(firstInEpoch bool, num uint64, setProof []byte, call consensus.SystemCall) (SimpleList, common.Hash, error) { if firstInEpoch { var proof FirstValidatorSetProof @@ -512,7 +512,7 @@ func (s *ValidatorSafeContract) epochSet(firstInEpoch bool, num uint64, setProof } // check a first proof: fetch the validator set at the given block. -//nolint +// nolint func checkFirstValidatorSetProof(contract_address common.Address, oldHeader *types.Header, dbItems [][]byte) ([]common.Address, error) { /* fn check_first_proof( @@ -579,7 +579,7 @@ func checkFirstValidatorSetProof(contract_address common.Address, oldHeader *typ // inter-contract proofs are a header and receipts. // checking will involve ensuring that the receipts match the header and // extracting the validator set from the receipts. -//nolint +// nolint func (s *ValidatorSafeContract) defaultCaller(blockHash common.Hash) (Call, error) { return func(addr common.Address, data []byte) (CallResults, error) { return s.client.CallAtBlockHash(blockHash, addr, data) diff --git a/consensus/bor/bor.go b/consensus/bor/bor.go index 18e28a3f6..41ffd9cb1 100644 --- a/consensus/bor/bor.go +++ b/consensus/bor/bor.go @@ -1081,7 +1081,7 @@ func (c *Bor) getSpanForBlock(blockNum uint64) (*HeimdallSpan, error) { } else { for span.StartBlock > blockNum { // Span wit low enough block number is not loaded - var spanID uint64 = span.ID - 1 + var spanID = span.ID - 1 var heimdallSpan HeimdallSpan log.Info("Span with low enough block number is not loaded", "fetching span", spanID) response, err := c.HeimdallClient.FetchWithRetry(c.execCtx, fmt.Sprintf("bor/span/%d", spanID), "") diff --git a/consensus/bor/merkle.go b/consensus/bor/merkle.go index 68244f8d0..c0c76fd66 100644 --- a/consensus/bor/merkle.go +++ b/consensus/bor/merkle.go @@ -36,7 +36,7 @@ func ConvertTo32(input []byte) (output [32]byte, err error) { return } -func Convert(input []([32]byte)) [][]byte { +func Convert(input [][32]byte) [][]byte { var output [][]byte for _, in := range input { newInput := make([]byte, len(in[:])) diff --git a/consensus/bor/validator_set.go b/consensus/bor/validator_set.go index c1b7f1810..93c341f7d 100644 --- a/consensus/bor/validator_set.go +++ b/consensus/bor/validator_set.go @@ -577,14 +577,15 @@ func (vals *ValidatorSet) updateWithChangeSet(changes []*Validator, allowDeletes // UpdateWithChangeSet attempts to update the validator set with 'changes'. // It performs the following steps: -// - validates the changes making sure there are no duplicates and splits them in updates and deletes -// - verifies that applying the changes will not result in errors -// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities -// across old and newly added validators are fair -// - computes the priorities of new validators against the final set -// - applies the updates against the validator set -// - applies the removals against the validator set -// - performs scaling and centering of priority values +// - validates the changes making sure there are no duplicates and splits them in updates and deletes +// - verifies that applying the changes will not result in errors +// - computes the total voting power BEFORE removals to ensure that in the next steps the priorities +// across old and newly added validators are fair +// - computes the priorities of new validators against the final set +// - applies the updates against the validator set +// - applies the removals against the validator set +// - performs scaling and centering of priority values +// // If an error is detected during verification steps, it is returned and the validator set // is not changed. func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error { diff --git a/consensus/ethash/api.go b/consensus/ethash/api.go index 64eba4bab..16d2747d9 100644 --- a/consensus/ethash/api.go +++ b/consensus/ethash/api.go @@ -34,10 +34,11 @@ type API struct { // GetWork returns a work package for external miner. // // The work package consists of 3 strings: -// result[0] - 32 bytes hex encoded current block header pow-hash -// result[1] - 32 bytes hex encoded seed hash used for DAG -// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty -// result[3] - hex encoded block number +// +// result[0] - 32 bytes hex encoded current block header pow-hash +// result[1] - 32 bytes hex encoded seed hash used for DAG +// result[2] - 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty +// result[3] - hex encoded block number func (api *API) GetWork() ([4]string, error) { if api.ethash.remote == nil { return [4]string{}, errors.New("not supported") diff --git a/consensus/ethash/sealer.go b/consensus/ethash/sealer.go index 02155b187..4c655b03f 100644 --- a/consensus/ethash/sealer.go +++ b/consensus/ethash/sealer.go @@ -220,10 +220,11 @@ func (s *remoteSealer) loop() { // makeWork creates a work package for external miner. // // The work package consists of 3 strings: -// result[0], 32 bytes hex encoded current block header pow-hash -// result[1], 32 bytes hex encoded seed hash used for DAG -// result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty -// result[3], hex encoded block number +// +// result[0], 32 bytes hex encoded current block header pow-hash +// result[1], 32 bytes hex encoded seed hash used for DAG +// result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty +// result[3], hex encoded block number func (s *remoteSealer) makeWork(block *types.Block) { hash := s.ethash.SealHash(block.Header()) s.currentWork[0] = hash.Hex() diff --git a/consensus/misc/dao.go b/consensus/misc/dao.go index a13dbbd4d..4fb068d84 100644 --- a/consensus/misc/dao.go +++ b/consensus/misc/dao.go @@ -42,10 +42,11 @@ var ( // ensure it conforms to DAO hard-fork rules. // // DAO hard-fork extension to the header validity: -// a) if the node is no-fork, do not accept blocks in the [fork, fork+10) range -// with the fork specific extra-data set -// b) if the node is pro-fork, require blocks in the specific range to have the -// unique extra-data set. +// +// a) if the node is no-fork, do not accept blocks in the [fork, fork+10) range +// with the fork specific extra-data set +// b) if the node is pro-fork, require blocks in the specific range to have the +// unique extra-data set. func VerifyDAOHeaderExtraData(config *params.ChainConfig, header *types.Header) error { // Short circuit validation if the node doesn't care about the DAO fork if config.DAOForkBlock == nil { diff --git a/consensus/parlia/snapshot.go b/consensus/parlia/snapshot.go index 2d9198d1d..ef53b252f 100644 --- a/consensus/parlia/snapshot.go +++ b/consensus/parlia/snapshot.go @@ -149,7 +149,7 @@ func (s *Snapshot) copy() *Snapshot { return cpy } -//nolint +// nolint func (s *Snapshot) isMajorityFork(forkHash string) bool { ally := 0 for _, h := range s.RecentForkHashes { diff --git a/core/asm/asm_test.go b/core/asm/asm_test.go index 92b26b67a..3a20d2db7 100644 --- a/core/asm/asm_test.go +++ b/core/asm/asm_test.go @@ -17,9 +17,8 @@ package asm import ( - "testing" - "encoding/hex" + "testing" ) // Tests disassembling the instructions for valid evm code diff --git a/core/genesis.go b/core/genesis.go index c737308de..852e8653a 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -166,10 +166,10 @@ func (e *GenesisMismatchError) Error() string { // CommitGenesisBlock writes or updates the genesis block in db. // The block that will be used is: // -// genesis == nil genesis != nil -// +------------------------------------------ -// db has no genesis | main-net default | genesis -// db has genesis | from DB | genesis (if compatible) +// genesis == nil genesis != nil +// +------------------------------------------ +// db has no genesis | main-net default | genesis +// db has genesis | from DB | genesis (if compatible) // // The stored chain configuration will be updated if it is compatible (i.e. does not // specify a fork block below the local head block). In case of a conflict, the @@ -695,7 +695,7 @@ func DefaultMumbaiGenesisBlock() *Genesis { } } -//DefaultBorMainnet returns the Bor Mainnet network gensis block. +// DefaultBorMainnet returns the Bor Mainnet network gensis block. func DefaultBorMainnetGenesisBlock() *Genesis { return &Genesis{ Config: params.BorMainnetChainConfig, @@ -743,8 +743,9 @@ func DefaultGnosisGenesisBlock() *Genesis { } // Pre-calculated version of: -// DevnetSignPrivateKey = crypto.HexToECDSA(sha256.Sum256([]byte("erigon devnet key"))) -// DevnetEtherbase=crypto.PubkeyToAddress(DevnetSignPrivateKey.PublicKey) +// +// DevnetSignPrivateKey = crypto.HexToECDSA(sha256.Sum256([]byte("erigon devnet key"))) +// DevnetEtherbase=crypto.PubkeyToAddress(DevnetSignPrivateKey.PublicKey) var DevnetSignPrivateKey, _ = crypto.HexToECDSA("26e86e45f6fc45ec6e2ecd128cec80fa1d1505e5507dcd2ae58c3130a7a97b48") var DevnetEtherbase = common.HexToAddress("67b1d87101671b127f5f8714789c7192f7ad340e") diff --git a/core/mkalloc.go b/core/mkalloc.go index 3f72c78b1..bb941e805 100644 --- a/core/mkalloc.go +++ b/core/mkalloc.go @@ -17,12 +17,10 @@ //go:build none /* +The mkalloc tool creates the genesis allocation constants in genesis_alloc.go +It outputs a const declaration that contains an RLP-encoded list of (address, balance) tuples. - The mkalloc tool creates the genesis allocation constants in genesis_alloc.go - It outputs a const declaration that contains an RLP-encoded list of (address, balance) tuples. - - go run mkalloc.go genesis.json - + go run mkalloc.go genesis.json */ package main diff --git a/core/rlp_test.go b/core/rlp_test.go index 2bb4f9e1a..d36c621be 100644 --- a/core/rlp_test.go +++ b/core/rlp_test.go @@ -13,6 +13,7 @@ // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . +// //nolint:errcheck,prealloc package core diff --git a/core/skip_analysis.go b/core/skip_analysis.go index 53eaea842..6ade8f935 100644 --- a/core/skip_analysis.go +++ b/core/skip_analysis.go @@ -35,7 +35,7 @@ import ( // 0xcdb5bf0b4b51093e1c994f471921f88623c9d3e1b6aa2782049f53a0048f2b32 (block 11079912) // 0x21ab7bf7245a87eae265124aaf180d91133377e47db2b1a4866493ec4b371150 (block 13119520) -var analysisBlocks map[string][]uint64 = map[string][]uint64{ +var analysisBlocks = map[string][]uint64{ networkname.MainnetChainName: {5_800_596, 6_426_298, 6_426_432, 11_079_912, 13_119_520, 15_081_051}, networkname.BSCChainName: {19_278_044}, networkname.BorMainnetChainName: {29_447_463}, diff --git a/core/state/access_list_test.go b/core/state/access_list_test.go index 119990e72..b81182079 100644 --- a/core/state/access_list_test.go +++ b/core/state/access_list_test.go @@ -1,9 +1,10 @@ package state import ( + "testing" + "github.com/ledgerwatch/erigon-lib/kv/memdb" "github.com/ledgerwatch/erigon/common" - "testing" ) func verifyAddrs(t *testing.T, s *IntraBlockState, astrings ...string) { diff --git a/core/state/database_test.go b/core/state/database_test.go index c9b052df1..38518ca38 100644 --- a/core/state/database_test.go +++ b/core/state/database_test.go @@ -1012,7 +1012,7 @@ func TestEip2200Gas(t *testing.T) { require.NoError(t, err) } -//Create contract, drop trie, reload trie from disk and add block with contract call +// Create contract, drop trie, reload trie from disk and add block with contract call func TestWrongIncarnation(t *testing.T) { // Configure and generate a sample block chain var ( @@ -1125,7 +1125,7 @@ func TestWrongIncarnation(t *testing.T) { require.NoError(t, err) } -//create acc, deploy to it contract, reorg to state without contract +// create acc, deploy to it contract, reorg to state without contract func TestWrongIncarnation2(t *testing.T) { // Configure and generate a sample block chain var ( diff --git a/core/state/intra_block_state.go b/core/state/intra_block_state.go index ba4859c91..5c87d27cd 100644 --- a/core/state/intra_block_state.go +++ b/core/state/intra_block_state.go @@ -583,8 +583,8 @@ func (sdb *IntraBlockState) createObject(addr common.Address, previous *stateObj // CreateAccount is called during the EVM CREATE operation. The situation might arise that // a contract does the following: // -// 1. sends funds to sha(account ++ (nonce + 1)) -// 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) +// 1. sends funds to sha(account ++ (nonce + 1)) +// 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) // // Carrying over the balance ensures that Ether doesn't disappear. func (sdb *IntraBlockState) CreateAccount(addr common.Address, contractCreation bool) { diff --git a/core/state_transition.go b/core/state_transition.go index 43a17bab0..d259c02f1 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -45,8 +45,10 @@ The state transitioning model does all the necessary work to work out a valid ne 3) Create a new state object if the recipient is \0*32 4) Value transfer == If contract creation == - 4a) Attempt to run transaction data - 4b) If valid, use result as code for the new state object + + 4a) Attempt to run transaction data + 4b) If valid, use result as code for the new state object + == end == 5) Run Script section 6) Derive new state root @@ -257,7 +259,7 @@ func (st *StateTransition) buyGas(gasBailout bool) error { return fmt.Errorf("%w: address %v", ErrInsufficientFunds, st.msg.From().Hex()) } } - var subBalance bool = false + var subBalance = false if have, want := st.state.GetBalance(st.msg.From()), balanceCheck; have.Cmp(want) < 0 { if !gasBailout { return fmt.Errorf("%w: address %v have %v want %v", ErrInsufficientFunds, st.msg.From().Hex(), have, want) @@ -332,13 +334,13 @@ func (st *StateTransition) preCheck(gasBailout bool) error { // TransitionDb will transition the state by applying the current message and // returning the evm execution result with following fields. // -// - used gas: -// total gas used (including gas being refunded) -// - returndata: -// the returned data from evm -// - concrete execution error: -// various **EVM** error which aborts the execution, -// e.g. ErrOutOfGas, ErrExecutionReverted +// - used gas: +// total gas used (including gas being refunded) +// - returndata: +// the returned data from evm +// - concrete execution error: +// various **EVM** error which aborts the execution, +// e.g. ErrOutOfGas, ErrExecutionReverted // // However if any consensus issue encountered, return the error directly with // nil evm execution result. diff --git a/core/vm/absint_cfg.go b/core/vm/absint_cfg.go index 65473813f..8b9c88300 100644 --- a/core/vm/absint_cfg.go +++ b/core/vm/absint_cfg.go @@ -131,7 +131,7 @@ func AbsValueDestringify(s string) AbsValue { return AbsValue{} } -////////////////////////////////////////////////// +// //////////////////////////////////////////////// type astack struct { values []AbsValue hash uint64 @@ -295,7 +295,7 @@ func (state *astate) Add(stack *astack) { ////////////////////////////////////////////////// -//-1 block id is invalid jump +// -1 block id is invalid jump type CfgProofState struct { Pc int Stacks [][]string @@ -361,15 +361,15 @@ func (proof *CfgProof) ToString() string { return string(proof.Serialize()) } -//block.{Entry|Exit}.Pc in code, block.{Succs|Preds} in some block.{Entry}.Pc -//Entry <= Exit -//No overlap of blocks -//Must have block starting at 0 with a empty state -//Succs,Preds consistency -//No duplicate succs -//No duplicate preds -//succs are sorted -//preds are sorted +// block.{Entry|Exit}.Pc in code, block.{Succs|Preds} in some block.{Entry}.Pc +// Entry <= Exit +// No overlap of blocks +// Must have block starting at 0 with a empty state +// Succs,Preds consistency +// No duplicate succs +// No duplicate preds +// succs are sorted +// preds are sorted func (proof *CfgProof) isValid() bool { return true } diff --git a/core/vm/absint_cfg_proof_check.go b/core/vm/absint_cfg_proof_check.go index e10375dd4..ac16f618d 100644 --- a/core/vm/absint_cfg_proof_check.go +++ b/core/vm/absint_cfg_proof_check.go @@ -2,9 +2,10 @@ package vm import ( "errors" - "github.com/holiman/uint256" "log" "reflect" + + "github.com/holiman/uint256" ) type CfgOpSem struct { diff --git a/core/vm/absint_cfg_proof_gen.go b/core/vm/absint_cfg_proof_gen.go index 8a2ce1c5f..216bed304 100644 --- a/core/vm/absint_cfg_proof_gen.go +++ b/core/vm/absint_cfg_proof_gen.go @@ -15,7 +15,7 @@ import ( "github.com/holiman/uint256" ) -////////////////////////////////////////////////// +// //////////////////////////////////////////////// type AbsValueKind int ////////////////////////// diff --git a/core/vm/access_list_tracer.go b/core/vm/access_list_tracer.go index f63d6336e..3388a1286 100644 --- a/core/vm/access_list_tracer.go +++ b/core/vm/access_list_tracer.go @@ -17,10 +17,11 @@ package vm import ( - "github.com/ledgerwatch/erigon/common" - "github.com/ledgerwatch/erigon/core/types" "math/big" "time" + + "github.com/ledgerwatch/erigon/common" + "github.com/ledgerwatch/erigon/core/types" ) // accessList is an accumulator for the set of accounts and storage slots an EVM diff --git a/core/vm/contracts.go b/core/vm/contracts.go index 404ead713..5d86ae74a 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -289,9 +289,10 @@ var ( // modexpMultComplexity implements bigModexp multComplexity formula, as defined in EIP-198 // // def mult_complexity(x): -// if x <= 64: return x ** 2 -// elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 -// else: return x ** 2 // 16 + 480 * x - 199680 +// +// if x <= 64: return x ** 2 +// elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072 +// else: return x ** 2 // 16 + 480 * x - 199680 // // where is x is max(length_of_MODULUS, length_of_BASE) func modexpMultComplexity(x *big.Int) *big.Int { @@ -614,7 +615,7 @@ func (c *blake2F) Run(input []byte) ([]byte, error) { // Parse the input into the Blake2b call parameters var ( rounds = binary.BigEndian.Uint32(input[0:4]) - final = (input[212] == blake2FFinalBlockBytes) + final = input[212] == blake2FFinalBlockBytes h [8]uint64 m [16]uint64 diff --git a/core/vm/gas_table.go b/core/vm/gas_table.go index fcbe14b47..1208c39a2 100644 --- a/core/vm/gas_table.go +++ b/core/vm/gas_table.go @@ -166,19 +166,19 @@ func gasSStore(evm *EVM, contract *Contract, stack *stack.Stack, mem *Memory, me return params.NetSstoreDirtyGas, nil } -// 0. If *gasleft* is less than or equal to 2300, fail the current call. -// 1. If current value equals new value (this is a no-op), SLOAD_GAS is deducted. -// 2. If current value does not equal new value: -// 2.1. If original value equals current value (this storage slot has not been changed by the current execution context): +// 0. If *gasleft* is less than or equal to 2300, fail the current call. +// 1. If current value equals new value (this is a no-op), SLOAD_GAS is deducted. +// 2. If current value does not equal new value: +// 2.1. If original value equals current value (this storage slot has not been changed by the current execution context): // 2.1.1. If original value is 0, SSTORE_SET_GAS (20K) gas is deducted. // 2.1.2. Otherwise, SSTORE_RESET_GAS gas is deducted. If new value is 0, add SSTORE_CLEARS_SCHEDULE to refund counter. -// 2.2. If original value does not equal current value (this storage slot is dirty), SLOAD_GAS gas is deducted. Apply both of the following clauses: +// 2.2. If original value does not equal current value (this storage slot is dirty), SLOAD_GAS gas is deducted. Apply both of the following clauses: // 2.2.1. If original value is not 0: -// 2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEARS_SCHEDULE gas from refund counter. -// 2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEARS_SCHEDULE gas to refund counter. +// 2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEARS_SCHEDULE gas from refund counter. +// 2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEARS_SCHEDULE gas to refund counter. // 2.2.2. If original value equals new value (this storage slot is reset): -// 2.2.2.1. If original value is 0, add SSTORE_SET_GAS - SLOAD_GAS to refund counter. -// 2.2.2.2. Otherwise, add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter. +// 2.2.2.1. If original value is 0, add SSTORE_SET_GAS - SLOAD_GAS to refund counter. +// 2.2.2.2. Otherwise, add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter. func gasSStoreEIP2200(evm *EVM, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { // If we fail the minimum gas availability invariant, fail (0) if contract.Gas <= params.SstoreSentryGasEIP2200 { diff --git a/core/vm/instructions.go b/core/vm/instructions.go index 335851515..22e8f9227 100644 --- a/core/vm/instructions.go +++ b/core/vm/instructions.go @@ -415,16 +415,21 @@ func opExtCodeCopy(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) // opExtCodeHash returns the code hash of a specified account. // There are several cases when the function is called, while we can relay everything // to `state.GetCodeHash` function to ensure the correctness. -// (1) Caller tries to get the code hash of a normal contract account, state +// +// (1) Caller tries to get the code hash of a normal contract account, state +// // should return the relative code hash and set it as the result. // -// (2) Caller tries to get the code hash of a non-existent account, state should +// (2) Caller tries to get the code hash of a non-existent account, state should +// // return common.Hash{} and zero will be set as the result. // -// (3) Caller tries to get the code hash for an account without contract code, +// (3) Caller tries to get the code hash for an account without contract code, +// // state should return emptyCodeHash(0xc5d246...) as the result. // -// (4) Caller tries to get the code hash of a precompiled account, the result +// (4) Caller tries to get the code hash of a precompiled account, the result +// // should be zero or emptyCodeHash. // // It is worth noting that in order to avoid unnecessary create and clean, @@ -433,10 +438,12 @@ func opExtCodeCopy(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) // If the precompile account is not transferred any amount on a private or // customized chain, the return value will be zero. // -// (5) Caller tries to get the code hash for an account which is marked as suicided +// (5) Caller tries to get the code hash for an account which is marked as suicided +// // in the current transaction, the code hash of this account should be returned. // -// (6) Caller tries to get the code hash for an account which is marked as deleted, +// (6) Caller tries to get the code hash for an account which is marked as deleted, +// // this account should be regarded as a non-existent account and zero should be returned. func opExtCodeHash(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) { slot := scope.Stack.Peek() diff --git a/core/vm/interpreter.go b/core/vm/interpreter.go index 019149132..3ec8ff569 100644 --- a/core/vm/interpreter.go +++ b/core/vm/interpreter.go @@ -73,7 +73,8 @@ type EVMInterpreter struct { jt *JumpTable // EVM instruction table } -//structcheck doesn't see embedding +// structcheck doesn't see embedding +// //nolint:structcheck type VM struct { evm *EVM diff --git a/core/vm/lightclient/iavl/doc.go b/core/vm/lightclient/iavl/doc.go index 7751bccad..d3ccfb801 100644 --- a/core/vm/lightclient/iavl/doc.go +++ b/core/vm/lightclient/iavl/doc.go @@ -1,49 +1,47 @@ // Package iavl implements a versioned, snapshottable (immutable) AVL+ tree // for persisting key-value pairs. // -// // Basic usage of MutableTree. // -// import "github.com/tendermint/iavl" -// import "github.com/tendermint/tendermint/libs/db" -// ... +// import "github.com/tendermint/iavl" +// import "github.com/tendermint/tendermint/libs/db" +// ... // -// tree := iavl.NewMutableTree(db.NewMemDB(), 128) +// tree := iavl.NewMutableTree(db.NewMemDB(), 128) // -// tree.IsEmpty() // true +// tree.IsEmpty() // true // -// tree.Set([]byte("alice"), []byte("abc")) -// tree.SaveVersion(1) +// tree.Set([]byte("alice"), []byte("abc")) +// tree.SaveVersion(1) // -// tree.Set([]byte("alice"), []byte("xyz")) -// tree.Set([]byte("bob"), []byte("xyz")) -// tree.SaveVersion(2) +// tree.Set([]byte("alice"), []byte("xyz")) +// tree.Set([]byte("bob"), []byte("xyz")) +// tree.SaveVersion(2) // -// tree.LatestVersion() // 2 +// tree.LatestVersion() // 2 // -// tree.GetVersioned([]byte("alice"), 1) // "abc" -// tree.GetVersioned([]byte("alice"), 2) // "xyz" +// tree.GetVersioned([]byte("alice"), 1) // "abc" +// tree.GetVersioned([]byte("alice"), 2) // "xyz" // // Proof of existence: // -// root := tree.Hash() -// val, proof, err := tree.GetVersionedWithProof([]byte("bob"), 2) // "xyz", RangeProof, nil -// proof.Verify([]byte("bob"), val, root) // nil +// root := tree.Hash() +// val, proof, err := tree.GetVersionedWithProof([]byte("bob"), 2) // "xyz", RangeProof, nil +// proof.Verify([]byte("bob"), val, root) // nil // // Proof of absence: // -// _, proof, err = tree.GetVersionedWithProof([]byte("tom"), 2) // nil, RangeProof, nil -// proof.Verify([]byte("tom"), nil, root) // nil +// _, proof, err = tree.GetVersionedWithProof([]byte("tom"), 2) // nil, RangeProof, nil +// proof.Verify([]byte("tom"), nil, root) // nil // // Now we delete an old version: // -// tree.DeleteVersion(1) -// tree.VersionExists(1) // false -// tree.Get([]byte("alice")) // "xyz" -// tree.GetVersioned([]byte("alice"), 1) // nil +// tree.DeleteVersion(1) +// tree.VersionExists(1) // false +// tree.Get([]byte("alice")) // "xyz" +// tree.GetVersioned([]byte("alice"), 1) // nil // // Can't create a proof of absence for a version we no longer have: // -// _, proof, err = tree.GetVersionedWithProof([]byte("tom"), 1) // nil, nil, error -// +// _, proof, err = tree.GetVersionedWithProof([]byte("tom"), 1) // nil, nil, error package iavl diff --git a/core/vm/lightclient/iavl/key_format.go b/core/vm/lightclient/iavl/key_format.go index b63f9ea7b..b34384961 100644 --- a/core/vm/lightclient/iavl/key_format.go +++ b/core/vm/lightclient/iavl/key_format.go @@ -18,15 +18,15 @@ type KeyFormat struct { // For example, to store keys that could index some objects by a version number and their SHA256 hash using the form: // 'c' then you would define the KeyFormat with: // -// var keyFormat = NewKeyFormat('c', 8, 32) +// var keyFormat = NewKeyFormat('c', 8, 32) // // Then you can create a key with: // -// func ObjectKey(version uint64, objectBytes []byte) []byte { -// hasher := sha256.New() -// hasher.Sum(nil) -// return keyFormat.Key(version, hasher.Sum(nil)) -// } +// func ObjectKey(version uint64, objectBytes []byte) []byte { +// hasher := sha256.New() +// hasher.Sum(nil) +// return keyFormat.Key(version, hasher.Sum(nil)) +// } func NewKeyFormat(prefix byte, layout ...int) *KeyFormat { // For prefix byte length := 1 diff --git a/crypto/crypto.go b/crypto/crypto.go index 59adaa237..1f993eb5b 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -39,7 +39,7 @@ import ( "github.com/ledgerwatch/erigon/rlp" ) -//SignatureLength indicates the byte length required to carry a signature with recovery id. +// SignatureLength indicates the byte length required to carry a signature with recovery id. const SignatureLength = 64 + 1 // 64 bytes ECDSA signature + 1 byte recovery id // RecoveryIDOffset points to the byte offset within the signature that contains the recovery id. diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go index dc54c9b31..ffda9d008 100644 --- a/eth/ethconfig/config.go +++ b/eth/ethconfig/config.go @@ -244,7 +244,7 @@ type Sync struct { } // Chains where snapshots are enabled by default -var ChainsWithSnapshots map[string]struct{} = map[string]struct{}{ +var ChainsWithSnapshots = map[string]struct{}{ networkname.MainnetChainName: {}, networkname.BSCChainName: {}, networkname.GoerliChainName: {}, diff --git a/eth/gasprice/feehistory.go b/eth/gasprice/feehistory.go index 673f53bce..9e00318ef 100644 --- a/eth/gasprice/feehistory.go +++ b/eth/gasprice/feehistory.go @@ -194,10 +194,11 @@ func (oracle *Oracle) resolveBlockRange(ctx context.Context, lastBlock rpc.Block // actually processed range is returned to avoid ambiguity when parts of the requested range // are not available or when the head has changed during processing this request. // Three arrays are returned based on the processed blocks: -// - reward: the requested percentiles of effective priority fees per gas of transactions in each -// block, sorted in ascending order and weighted by gas used. -// - baseFee: base fee per gas in the given block -// - gasUsedRatio: gasUsed/gasLimit in the given block +// - reward: the requested percentiles of effective priority fees per gas of transactions in each +// block, sorted in ascending order and weighted by gas used. +// - baseFee: base fee per gas in the given block +// - gasUsedRatio: gasUsed/gasLimit in the given block +// // Note: baseFee includes the next block after the newest of the returned range, because this // value can be derived from the newest block. func (oracle *Oracle) FeeHistory(ctx context.Context, blocks int, unresolvedLastBlock rpc.BlockNumber, rewardPercentiles []float64) (*big.Int, [][]*big.Int, []*big.Int, []float64, error) { diff --git a/eth/protocols/eth/discovery.go b/eth/protocols/eth/discovery.go index 4bd009da7..7613a28d2 100644 --- a/eth/protocols/eth/discovery.go +++ b/eth/protocols/eth/discovery.go @@ -18,6 +18,7 @@ package eth import ( "fmt" + "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/core/forkid" "github.com/ledgerwatch/erigon/p2p/enr" diff --git a/eth/protocols/eth/handlers.go b/eth/protocols/eth/handlers.go index ee5e2b3e7..f8090451a 100644 --- a/eth/protocols/eth/handlers.go +++ b/eth/protocols/eth/handlers.go @@ -85,7 +85,7 @@ func AnswerGetBlockHeadersQuery(db kv.Tx, query *GetBlockHeadersPacket, blockRea unknown = true } else { query.Origin.Hash, query.Origin.Number = rawdb.ReadAncestor(db, query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical, blockReader) - unknown = (query.Origin.Hash == common.Hash{}) + unknown = query.Origin.Hash == common.Hash{} } case hashMode && !query.Reverse: // Hash based traversal towards the leaf block diff --git a/eth/stagedsync/stage_finish.go b/eth/stagedsync/stage_finish.go index a938853c9..42232b0b8 100644 --- a/eth/stagedsync/stage_finish.go +++ b/eth/stagedsync/stage_finish.go @@ -152,7 +152,7 @@ func NotifyNewHeaders(ctx context.Context, finishStageBeforeSync uint64, finishS } notifyFrom++ - var notifyTo uint64 = notifyFrom + var notifyTo = notifyFrom var headersRlp [][]byte if err := tx.ForEach(kv.Headers, dbutils.EncodeBlockNumber(notifyFrom), func(k, headerRLP []byte) error { if len(headerRLP) == 0 { diff --git a/eth/stagedsync/stage_mining_create_block.go b/eth/stagedsync/stage_mining_create_block.go index f148f2ef8..26a7e09f1 100644 --- a/eth/stagedsync/stage_mining_create_block.go +++ b/eth/stagedsync/stage_mining_create_block.go @@ -89,7 +89,7 @@ func StageMiningCreateBlockCfg(db kv.RwDB, miner MiningState, chainConfig params } // SpawnMiningCreateBlockStage -//TODO: +// TODO: // - resubmitAdjustCh - variable is not implemented func SpawnMiningCreateBlockStage(s *StageState, tx kv.RwTx, cfg MiningCreateBlockCfg, quit <-chan struct{}) (err error) { current := cfg.miner.MiningBlock diff --git a/eth/stagedsync/stage_mining_exec.go b/eth/stagedsync/stage_mining_exec.go index a17425480..984a5d28c 100644 --- a/eth/stagedsync/stage_mining_exec.go +++ b/eth/stagedsync/stage_mining_exec.go @@ -60,7 +60,7 @@ func StageMiningExecCfg( } // SpawnMiningExecStage -//TODO: +// TODO: // - resubmitAdjustCh - variable is not implemented func SpawnMiningExecStage(s *StageState, tx kv.RwTx, cfg MiningExecCfg, quit <-chan struct{}) error { cfg.vmConfig.NoReceipts = false diff --git a/eth/tracers/jsvm.go b/eth/tracers/jsvm.go index b7914032b..10ae7ed99 100644 --- a/eth/tracers/jsvm.go +++ b/eth/tracers/jsvm.go @@ -1,8 +1,9 @@ package tracers import ( - "github.com/dop251/goja" "unsafe" + + "github.com/dop251/goja" ) type JSVM struct { diff --git a/eth/tracers/jsvm_test.go b/eth/tracers/jsvm_test.go index 00b7d881b..4adc0f07d 100644 --- a/eth/tracers/jsvm_test.go +++ b/eth/tracers/jsvm_test.go @@ -1,8 +1,9 @@ package tracers import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestSwap(t *testing.T) { diff --git a/eth/tracers/tracer.go b/eth/tracers/tracer.go index 21a1e823a..81c6ebaa2 100644 --- a/eth/tracers/tracer.go +++ b/eth/tracers/tracer.go @@ -20,12 +20,13 @@ import ( "encoding/json" "errors" "fmt" - "github.com/ledgerwatch/erigon/core" "math/big" "sync/atomic" "time" "unsafe" + "github.com/ledgerwatch/erigon/core" + "github.com/holiman/uint256" "github.com/ledgerwatch/erigon/common" diff --git a/ethdb/bitmapdb/dbutils.go b/ethdb/bitmapdb/dbutils.go index 0631a4f57..7379ffd24 100644 --- a/ethdb/bitmapdb/dbutils.go +++ b/ethdb/bitmapdb/dbutils.go @@ -154,6 +154,7 @@ func Get(db kv.Tx, bucket string, key []byte, from, to uint32) (*roaring.Bitmap, } // SeekInBitmap - returns value in bitmap which is >= n +// //nolint:deadcode func SeekInBitmap(m *roaring.Bitmap, n uint32) (found uint32, ok bool) { i := m.Iterator() diff --git a/ethdb/olddb/mutation.go b/ethdb/olddb/mutation.go index fb3782425..f395bbd13 100644 --- a/ethdb/olddb/mutation.go +++ b/ethdb/olddb/mutation.go @@ -195,7 +195,7 @@ func (m *mutation) Put(table string, k, v []byte) error { m.size += int(unsafe.Sizeof(newMi)) + len(k) + len(v) if i != nil { oldMi := i.(*MutationItem) - m.size -= (int(unsafe.Sizeof(oldMi)) + len(oldMi.key) + len(oldMi.value)) + m.size -= int(unsafe.Sizeof(oldMi)) + len(oldMi.key) + len(oldMi.value) } return nil } diff --git a/ethdb/olddb/object_db.go b/ethdb/olddb/object_db.go index a8252f4ab..24d035231 100644 --- a/ethdb/olddb/object_db.go +++ b/ethdb/olddb/object_db.go @@ -33,7 +33,7 @@ type ObjectDatabase struct { } // NewObjectDatabase returns a AbstractDB wrapper. -//Deprecated +// Deprecated func NewObjectDatabase(kv kv.RwDB) *ObjectDatabase { return &ObjectDatabase{ kv: kv, diff --git a/ethdb/olddb/tx_db.go b/ethdb/olddb/tx_db.go index 5dd1ce38b..f54727ba0 100644 --- a/ethdb/olddb/tx_db.go +++ b/ethdb/olddb/tx_db.go @@ -14,8 +14,8 @@ import ( // TxDb not usable after .Commit()/.Rollback() call, but usable after .CommitAndBegin() call // you can put unlimited amount of data into this class // Walk and MultiWalk methods - work outside of Tx object yet, will implement it later -//Deprecated -//nolint +// Deprecated +// nolint type TxDb struct { db ethdb.Database tx kv.Tx @@ -24,7 +24,7 @@ type TxDb struct { len uint64 } -//nolint +// nolint func WrapIntoTxDB(tx kv.RwTx) *TxDb { return &TxDb{tx: tx, cursors: map[string]kv.Cursor{}} } diff --git a/ethdb/privateapi/engine_test.go b/ethdb/privateapi/engine_test.go index a2c5eb9c1..f62b91f8a 100644 --- a/ethdb/privateapi/engine_test.go +++ b/ethdb/privateapi/engine_test.go @@ -27,7 +27,7 @@ var ( // Payloads var ( - mockPayload1 *types2.ExecutionPayload = &types2.ExecutionPayload{ + mockPayload1 = &types2.ExecutionPayload{ ParentHash: gointerfaces.ConvertHashToH256(common.HexToHash("0x2")), BlockHash: gointerfaces.ConvertHashToH256(payload1Hash), ReceiptRoot: gointerfaces.ConvertHashToH256(common.HexToHash("0x3")), @@ -43,7 +43,7 @@ var ( Coinbase: gointerfaces.ConvertAddressToH160(common.HexToAddress("0x1")), Transactions: make([][]byte, 0), } - mockPayload2 *types2.ExecutionPayload = &types2.ExecutionPayload{ + mockPayload2 = &types2.ExecutionPayload{ ParentHash: gointerfaces.ConvertHashToH256(payload1Hash), BlockHash: gointerfaces.ConvertHashToH256(payload2Hash), ReceiptRoot: gointerfaces.ConvertHashToH256(common.HexToHash("0x3")), diff --git a/ethdb/prune/storage_mode.go b/ethdb/prune/storage_mode.go index 296078500..868956786 100644 --- a/ethdb/prune/storage_mode.go +++ b/ethdb/prune/storage_mode.go @@ -160,7 +160,9 @@ type BlockAmount interface { // Distance amount of blocks to keep in DB // but manual manipulation with such distance is very unsafe // for example: -// deleteUntil := currentStageProgress - pruningDistance +// +// deleteUntil := currentStageProgress - pruningDistance +// // may delete whole db - because of uint64 underflow when pruningDistance > currentStageProgress type Distance uint64 diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go index 70de6676c..86689bcb2 100644 --- a/ethstats/ethstats.go +++ b/ethstats/ethstats.go @@ -73,13 +73,14 @@ type Service struct { // websocket. // // From Gorilla websocket docs: -// Connections support one concurrent reader and one concurrent writer. -// Applications are responsible for ensuring that no more than one goroutine calls the write methods -// - NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, SetCompressionLevel -// concurrently and that no more than one goroutine calls the read methods -// - NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler -// concurrently. -// The Close and WriteControl methods can be called concurrently with all other methods. +// +// Connections support one concurrent reader and one concurrent writer. +// Applications are responsible for ensuring that no more than one goroutine calls the write methods +// - NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, SetCompressionLevel +// concurrently and that no more than one goroutine calls the read methods +// - NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler +// concurrently. +// The Close and WriteControl methods can be called concurrently with all other methods. type connWrapper struct { conn *websocket.Conn diff --git a/internal/cmdtest/test_cmd.go b/internal/cmdtest/test_cmd.go index 77b71360b..fa3bbdd74 100644 --- a/internal/cmdtest/test_cmd.go +++ b/internal/cmdtest/test_cmd.go @@ -20,7 +20,6 @@ import ( "bufio" "bytes" "fmt" - "github.com/ledgerwatch/log/v3" "io" "os" "os/exec" @@ -33,6 +32,8 @@ import ( "text/template" "time" + "github.com/ledgerwatch/log/v3" + "github.com/docker/docker/pkg/reexec" ) @@ -84,7 +85,7 @@ func (tt *TestCmd) Run(name string, args ...string) { // InputLine writes the given text to the child's stdin. // This method can also be called from an expect template, e.g.: // -// geth.expect(`Passphrase: {{.InputLine "password"}}`) +// geth.expect(`Passphrase: {{.InputLine "password"}}`) func (tt *TestCmd) InputLine(s string) string { io.WriteString(tt.stdin, s+"\n") return "" diff --git a/migrations/migrations.go b/migrations/migrations.go index 1890bca35..e5158f427 100644 --- a/migrations/migrations.go +++ b/migrations/migrations.go @@ -21,15 +21,15 @@ import ( // // Idempotency is expected // Best practices to achieve Idempotency: -// - in dbutils/bucket.go add suffix for existing bucket variable, create new bucket with same variable name. -// Example: -// - SyncStageProgress = []byte("SSP1") -// + SyncStageProgressOld1 = []byte("SSP1") -// + SyncStageProgress = []byte("SSP2") -// - in the beginning of migration: check that old bucket exists, clear new bucket -// - in the end:drop old bucket (not in defer!). -// - if you need migrate multiple buckets - create separate migration for each bucket -// - write test - and check that it's safe to apply same migration twice +// - in dbutils/bucket.go add suffix for existing bucket variable, create new bucket with same variable name. +// Example: +// - SyncStageProgress = []byte("SSP1") +// - SyncStageProgressOld1 = []byte("SSP1") +// - SyncStageProgress = []byte("SSP2") +// - in the beginning of migration: check that old bucket exists, clear new bucket +// - in the end:drop old bucket (not in defer!). +// - if you need migrate multiple buckets - create separate migration for each bucket +// - write test - and check that it's safe to apply same migration twice var migrations = map[kv.Label][]Migration{ kv.ChainDB: { dbSchemaVersion5, diff --git a/node/doc.go b/node/doc.go index e7de9491c..7c9efeaae 100644 --- a/node/doc.go +++ b/node/doc.go @@ -21,25 +21,22 @@ In the model exposed by this package, a node is a collection of services which u resources to provide RPC APIs. Services can also offer devp2p protocols, which are wired up to the devp2p network when the node instance is started. - -Node Lifecycle +# Node Lifecycle The Node object has a lifecycle consisting of three basic states, INITIALIZING, RUNNING and CLOSED. - - ●───────┐ - New() - │ - ▼ - INITIALIZING ────Start()─┐ - │ │ - │ ▼ - Close() RUNNING - │ │ - ▼ │ - CLOSED ◀──────Close()─┘ - + ●───────┐ + New() + │ + ▼ + INITIALIZING ────Start()─┐ + │ │ + │ ▼ + Close() RUNNING + │ │ + ▼ │ + CLOSED ◀──────Close()─┘ Creating a Node allocates basic resources such as the data directory and returns the node in its INITIALIZING state. Lifecycle objects, RPC APIs and peer-to-peer networking @@ -58,8 +55,7 @@ objects and shuts down RPC and peer-to-peer networking. You must always call Close on Node, even if the node was not started. - -Resources Managed By Node +# Resources Managed By Node All file-system resources used by a node instance are located in a directory called the data directory. The location of each resource can be overridden through additional node @@ -83,8 +79,7 @@ without a data directory, databases are opened in memory instead. Node also creates the shared store of encrypted Ethereum account keys. Services can access the account manager through the service context. - -Sharing Data Directory Among Instances +# Sharing Data Directory Among Instances Multiple node instances can share a single data directory if they have distinct instance names (set through the Name config option). Sharing behaviour depends on the type of @@ -99,25 +94,24 @@ Databases are also stored within the instance subdirectory. If multiple node instances use the same data directory, opening the databases with identical names will create one database for each instance. - -Data Directory Sharing Example +# Data Directory Sharing Example In this example, two node instances named A and B are started with the same data directory. Node instance A opens the database "db", node instance B opens the databases "db" and "db-2". The following files will be created in the data directory: - data-directory/ - A/ - nodekey -- devp2p node key of instance A - nodes/ -- devp2p discovery knowledge database of instance A - db/ -- data for "db" - A.ipc -- JSON-RPC UNIX domain socket endpoint of instance A - B/ - nodekey -- devp2p node key of node B - nodes/ -- devp2p discovery knowledge database of instance B - static-nodes.json -- devp2p static node list of instance B - db/ -- data for "db" - db-2/ -- data for "db-2" - B.ipc -- JSON-RPC UNIX domain socket endpoint of instance B + data-directory/ + A/ + nodekey -- devp2p node key of instance A + nodes/ -- devp2p discovery knowledge database of instance A + db/ -- data for "db" + A.ipc -- JSON-RPC UNIX domain socket endpoint of instance A + B/ + nodekey -- devp2p node key of node B + nodes/ -- devp2p discovery knowledge database of instance B + static-nodes.json -- devp2p static node list of instance B + db/ -- data for "db" + db-2/ -- data for "db-2" + B.ipc -- JSON-RPC UNIX domain socket endpoint of instance B */ package node diff --git a/node/node_example_test.go b/node/node_example_test.go index 43ffc8cb5..14ce0ff97 100644 --- a/node/node_example_test.go +++ b/node/node_example_test.go @@ -28,8 +28,8 @@ import ( // life cycle management. // // The following methods are needed to implement a node.Lifecycle: -// - Start() error - method invoked when the node is ready to start the service -// - Stop() error - method invoked when the node terminates the service +// - Start() error - method invoked when the node is ready to start the service +// - Stop() error - method invoked when the node terminates the service type SampleLifecycle struct{} func (s *SampleLifecycle) Start() error { fmt.Println("Service starting..."); return nil } diff --git a/p2p/dial.go b/p2p/dial.go index d1ce4d57d..e52c2b4d3 100644 --- a/p2p/dial.go +++ b/p2p/dial.go @@ -86,13 +86,12 @@ var ( // dialer creates outbound connections and submits them into Server. // Two types of peer connections can be created: // -// - static dials are pre-configured connections. The dialer attempts -// keep these nodes connected at all times. -// -// - dynamic dials are created from node discovery results. The dialer -// continuously reads candidate nodes from its input iterator and attempts -// to create peer connections to nodes arriving through the iterator. +// - static dials are pre-configured connections. The dialer attempts +// keep these nodes connected at all times. // +// - dynamic dials are created from node discovery results. The dialer +// continuously reads candidate nodes from its input iterator and attempts +// to create peer connections to nodes arriving through the iterator. type dialScheduler struct { dialConfig setupFunc dialSetupFunc @@ -336,7 +335,7 @@ func (d *dialScheduler) readNodes(it enode.Iterator) { } // or comes back online. -//nolint +// nolint func (d *dialScheduler) logStats() { now := d.clock.Now() if d.lastStatsLog.Add(dialStatsLogInterval) > now { diff --git a/p2p/discover/v5_udp.go b/p2p/discover/v5_udp.go index f27a075dc..b02ad6faa 100644 --- a/p2p/discover/v5_udp.go +++ b/p2p/discover/v5_udp.go @@ -756,6 +756,7 @@ func (t *UDPv5) handleWhoareyou(p *v5wire.Whoareyou, fromID enode.ID, fromAddr * } // matchWithCall checks whether a handshake attempt matches the active call. +// //nolint:unparam func (t *UDPv5) matchWithCall(fromID enode.ID, nonce v5wire.Nonce) (*callV5, error) { c := t.activeCallByAuth[nonce] diff --git a/p2p/discover/v5_udp_integration_test.go b/p2p/discover/v5_udp_integration_test.go index 58d432bbc..ddb7193f4 100644 --- a/p2p/discover/v5_udp_integration_test.go +++ b/p2p/discover/v5_udp_integration_test.go @@ -4,11 +4,12 @@ package discover import ( "context" - "github.com/ledgerwatch/erigon/p2p/discover/v5wire" "net" "runtime" "testing" "time" + + "github.com/ledgerwatch/erigon/p2p/discover/v5wire" ) // This test checks that calls with n replies may take up to n * respTimeout. diff --git a/p2p/discover/v5wire/encoding.go b/p2p/discover/v5wire/encoding.go index 5e983d0b9..3b8023022 100644 --- a/p2p/discover/v5wire/encoding.go +++ b/p2p/discover/v5wire/encoding.go @@ -232,6 +232,7 @@ func (c *Codec) writeHeaders(head *Header) { } // makeHeader creates a packet header. +// //nolint:unparam func (c *Codec) makeHeader(toID enode.ID, flag byte, authsizeExtra int) Header { var authsize int @@ -279,6 +280,7 @@ func (c *Codec) encodeRandom(toID enode.ID) (Header, []byte, error) { } // encodeWhoareyou encodes a WHOAREYOU packet. +// //nolint:unparam func (c *Codec) encodeWhoareyou(toID enode.ID, packet *Whoareyou) (Header, error) { // Sanity check node field to catch misbehaving callers. @@ -340,6 +342,7 @@ func (c *Codec) encodeHandshakeHeader(toID enode.ID, addr string, challenge *Who } // encodeAuthHeader creates the auth header on a request packet following WHOAREYOU. +// //nolint:unparam func (c *Codec) makeHandshakeAuth(toID enode.ID, addr string, challenge *Whoareyou) (*handshakeAuthData, *session, error) { auth := new(handshakeAuthData) diff --git a/p2p/discover/v5wire/encoding_test.go b/p2p/discover/v5wire/encoding_test.go index 0fcc1bc86..b143c4e22 100644 --- a/p2p/discover/v5wire/encoding_test.go +++ b/p2p/discover/v5wire/encoding_test.go @@ -39,8 +39,7 @@ import ( // To regenerate discv5 test vectors, run // -// go test -run TestVectors -write-test-vectors -// +// go test -run TestVectors -write-test-vectors var writeTestVectorsFlag = flag.Bool("write-test-vectors", false, "Overwrite discv5 test vectors in testdata/") var ( diff --git a/p2p/enode/urlv4.go b/p2p/enode/urlv4.go index 724806e7c..6145178bc 100644 --- a/p2p/enode/urlv4.go +++ b/p2p/enode/urlv4.go @@ -53,8 +53,8 @@ func MustParseV4(rawurl string) *Node { // // For incomplete nodes, the designator must look like one of these // -// enode:// -// +// enode:// +// // // For complete nodes, the node ID is encoded in the username portion // of the URL, separated from the host by an @ sign. The hostname can @@ -67,7 +67,7 @@ func MustParseV4(rawurl string) *Node { // a node with IP address 10.3.58.6, TCP listening port 30303 // and UDP discovery port 30301. // -// enode://@10.3.58.6:30303?discport=30301 +// enode://@10.3.58.6:30303?discport=30301 func ParseV4(rawurl string) (*Node, error) { if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil { id, err := parsePubkey(m[1]) diff --git a/p2p/enr/enr.go b/p2p/enr/enr.go index 10f2f79c5..f28b233f2 100644 --- a/p2p/enr/enr.go +++ b/p2p/enr/enr.go @@ -19,7 +19,7 @@ // stored in key/value pairs. To store and retrieve key/values in a record, use the Entry // interface. // -// Signature Handling +// # Signature Handling // // Records must be signed before transmitting them to another node. // diff --git a/p2p/message.go b/p2p/message.go index b277ce39d..ed1067c9a 100644 --- a/p2p/message.go +++ b/p2p/message.go @@ -111,12 +111,11 @@ func Send(w MsgWriter, msgcode uint64, data interface{}) error { // SendItems writes an RLP with the given code and data elements. // For a call such as: // -// SendItems(w, code, e1, e2, e3) +// SendItems(w, code, e1, e2, e3) // // the message payload will be an RLP list containing the items: // -// [e1, e2, e3] -// +// [e1, e2, e3] func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error { defer debug.LogPanic() return Send(w, msgcode, elems) diff --git a/p2p/nat/nat.go b/p2p/nat/nat.go index 05aaacdb2..9e328ecf6 100644 --- a/p2p/nat/nat.go +++ b/p2p/nat/nat.go @@ -55,14 +55,14 @@ type Interface interface { // The following formats are currently accepted. // Note that mechanism names are not case-sensitive. // -// "" or "none" return nil -// "extip:77.12.33.4" will assume the local machine is reachable on the given IP -// "any" uses the first auto-detected mechanism -// "upnp" uses the Universal Plug and Play protocol -// "pmp" uses NAT-PMP with an auto-detected gateway address -// "pmp:192.168.0.1" uses NAT-PMP with the given gateway address -// "stun" uses STUN to detect an external IP using a default server -// "stun:" uses STUN to detect an external IP using the given server (host:port) +// "" or "none" return nil +// "extip:77.12.33.4" will assume the local machine is reachable on the given IP +// "any" uses the first auto-detected mechanism +// "upnp" uses the Universal Plug and Play protocol +// "pmp" uses NAT-PMP with an auto-detected gateway address +// "pmp:192.168.0.1" uses NAT-PMP with the given gateway address +// "stun" uses STUN to detect an external IP using a default server +// "stun:" uses STUN to detect an external IP using the given server (host:port) func Parse(spec string) (Interface, error) { var ( parts = strings.SplitN(spec, ":", 2) diff --git a/p2p/nat/nat_stun.go b/p2p/nat/nat_stun.go index 03e4a5e5c..321eca176 100644 --- a/p2p/nat/nat_stun.go +++ b/p2p/nat/nat_stun.go @@ -2,9 +2,10 @@ package nat import ( "fmt" - "github.com/pion/stun" "net" "time" + + "github.com/pion/stun" ) const STUNDefaultServerAddr = "stun.l.google.com:19302" diff --git a/p2p/node_key_config.go b/p2p/node_key_config.go index dd46aee8f..ad32a58ef 100644 --- a/p2p/node_key_config.go +++ b/p2p/node_key_config.go @@ -3,9 +3,10 @@ package p2p import ( "crypto/ecdsa" "fmt" - "github.com/ledgerwatch/erigon/crypto" "os" "path" + + "github.com/ledgerwatch/erigon/crypto" ) type NodeKeyConfig struct { diff --git a/p2p/simulations/adapters/types.go b/p2p/simulations/adapters/types.go index 49cf4c397..af275e91a 100644 --- a/p2p/simulations/adapters/types.go +++ b/p2p/simulations/adapters/types.go @@ -41,7 +41,6 @@ import ( // * SimNode - An in-memory node // * ExecNode - A child process node // * DockerNode - A Docker container node -// type Node interface { // Addr returns the node's address (e.g. an Enode URL) Addr() []byte diff --git a/p2p/simulations/mocker.go b/p2p/simulations/mocker.go index 9c3f76d2e..5e97094a5 100644 --- a/p2p/simulations/mocker.go +++ b/p2p/simulations/mocker.go @@ -29,20 +29,20 @@ import ( "github.com/ledgerwatch/log/v3" ) -//a map of mocker names to its function +// a map of mocker names to its function var mockerList = map[string]func(net *Network, quit chan struct{}, nodeCount int){ "startStop": startStop, "probabilistic": probabilistic, "boot": boot, } -//Lookup a mocker by its name, returns the mockerFn +// Lookup a mocker by its name, returns the mockerFn func LookupMocker(mockerType string) func(net *Network, quit chan struct{}, nodeCount int) { return mockerList[mockerType] } -//Get a list of mockers (keys of the map) -//Useful for frontend to build available mocker selection +// Get a list of mockers (keys of the map) +// Useful for frontend to build available mocker selection func GetMockerList() []string { list := make([]string, 0, len(mockerList)) for k := range mockerList { @@ -51,7 +51,7 @@ func GetMockerList() []string { return list } -//The boot mockerFn only connects the node in a ring and doesn't do anything else +// The boot mockerFn only connects the node in a ring and doesn't do anything else func boot(net *Network, quit chan struct{}, nodeCount int) { _, err := connectNodesInRing(net, nodeCount) if err != nil { @@ -59,7 +59,7 @@ func boot(net *Network, quit chan struct{}, nodeCount int) { } } -//The startStop mockerFn stops and starts nodes in a defined period (ticker) +// The startStop mockerFn stops and starts nodes in a defined period (ticker) func startStop(net *Network, quit chan struct{}, nodeCount int) { nodes, err := connectNodesInRing(net, nodeCount) if err != nil { @@ -96,10 +96,10 @@ func startStop(net *Network, quit chan struct{}, nodeCount int) { } } -//The probabilistic mocker func has a more probabilistic pattern -//(the implementation could probably be improved): -//nodes are connected in a ring, then a varying number of random nodes is selected, -//mocker then stops and starts them in random intervals, and continues the loop +// The probabilistic mocker func has a more probabilistic pattern +// (the implementation could probably be improved): +// nodes are connected in a ring, then a varying number of random nodes is selected, +// mocker then stops and starts them in random intervals, and continues the loop func probabilistic(net *Network, quit chan struct{}, nodeCount int) { nodes, err := connectNodesInRing(net, nodeCount) if err != nil { @@ -168,7 +168,7 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) { } -//connect nodeCount number of nodes in a ring +// connect nodeCount number of nodes in a ring func connectNodesInRing(net *Network, nodeCount int) ([]enode.ID, error) { ids := make([]enode.ID, nodeCount) for i := 0; i < nodeCount; i++ { diff --git a/params/denomination.go b/params/denomination.go index fb4da7f41..bcedd271e 100644 --- a/params/denomination.go +++ b/params/denomination.go @@ -19,8 +19,7 @@ package params // These are the multipliers for ether denominations. // Example: To get the wei value of an amount in 'gwei', use // -// new(big.Int).Mul(value, big.NewInt(params.GWei)) -// +// new(big.Int).Mul(value, big.NewInt(params.GWei)) const ( Wei = 1 GWei = 1e9 diff --git a/params/protocol_params.go b/params/protocol_params.go index b2f3c1b3c..1765aa709 100644 --- a/params/protocol_params.go +++ b/params/protocol_params.go @@ -68,7 +68,7 @@ const ( // In EIP-2929: SstoreResetGas was changed to '5000 - COLD_SLOAD_COST'. // In EIP-3529: SSTORE_CLEARS_SCHEDULE is defined as SSTORE_RESET_GAS + ACCESS_LIST_STORAGE_KEY_COST // Which becomes: 5000 - 2100 + 1900 = 4800 - SstoreClearsScheduleRefundEIP3529 uint64 = SstoreResetGasEIP2200 - ColdSloadCostEIP2929 + TxAccessListStorageKeyGas + SstoreClearsScheduleRefundEIP3529 = SstoreResetGasEIP2200 - ColdSloadCostEIP2929 + TxAccessListStorageKeyGas JumpdestGas uint64 = 1 // Once per JUMPDEST operation. EpochDuration uint64 = 30000 // Duration between proof-of-work epochs. diff --git a/params/version.go b/params/version.go index 56d8388b8..d04bb02f4 100644 --- a/params/version.go +++ b/params/version.go @@ -70,7 +70,8 @@ var VersionWithMeta = func() string { // ArchiveVersion holds the textual version string used for Geth archives. // e.g. "1.8.11-dea1ce05" for stable releases, or -// "1.8.13-unstable-21c059b6" for unstable releases +// +// "1.8.13-unstable-21c059b6" for unstable releases func ArchiveVersion(gitCommit string) string { vsn := withModifier(Version) if len(gitCommit) >= 8 { diff --git a/rlp/decode.go b/rlp/decode.go index d311f5478..831e8aff2 100644 --- a/rlp/decode.go +++ b/rlp/decode.go @@ -22,13 +22,14 @@ import ( "encoding/binary" "errors" "fmt" - "github.com/ledgerwatch/log/v3" "io" "math/big" "reflect" "strings" "sync" + "github.com/ledgerwatch/log/v3" + "github.com/holiman/uint256" ) @@ -102,7 +103,7 @@ type Decoder interface { // Note that Decode does not set an input limit for all readers and may be vulnerable to // panics cause by huge value sizes. If you need an input limit, use // -// NewStream(r, limit).Decode(val) +// NewStream(r, limit).Decode(val) func Decode(r io.Reader, val interface{}) error { stream, ok := streamPool.Get().(*Stream) if !ok { diff --git a/rlp/doc.go b/rlp/doc.go index 113828e39..8dd5c89b8 100644 --- a/rlp/doc.go +++ b/rlp/doc.go @@ -27,8 +27,7 @@ value zero equivalent to the empty string). RLP values are distinguished by a type tag. The type tag precedes the value in the input stream and defines the size and kind of the bytes that follow. - -Encoding Rules +# Encoding Rules Package rlp uses reflection and encodes RLP based on the Go type of the value. @@ -58,8 +57,7 @@ An interface value encodes as the value contained in the interface. Floating point numbers, maps, channels and functions are not supported. - -Decoding Rules +# Decoding Rules Decoding uses the following type-dependent rules: @@ -93,30 +91,29 @@ or one (true). To decode into an interface value, one of these types is stored in the value: - []interface{}, for RLP lists - []byte, for RLP strings + []interface{}, for RLP lists + []byte, for RLP strings Non-empty interface types are not supported when decoding. Signed integers, floating point numbers, maps, channels and functions cannot be decoded into. - -Struct Tags +# Struct Tags As with other encoding packages, the "-" tag ignores fields. - type StructWithIgnoredField struct{ - Ignored uint `rlp:"-"` - Field uint - } + type StructWithIgnoredField struct{ + Ignored uint `rlp:"-"` + Field uint + } Go struct values encode/decode as RLP lists. There are two ways of influencing the mapping of fields to list elements. The "tail" tag, which may only be used on the last exported struct field, allows slurping up any excess list elements into a slice. - type StructWithTail struct{ - Field uint - Tail []string `rlp:"tail"` - } + type StructWithTail struct{ + Field uint + Tail []string `rlp:"tail"` + } The "optional" tag says that the field may be omitted if it is zero-valued. If this tag is used on a struct field, all subsequent public fields must also be declared optional. @@ -128,11 +125,11 @@ When decoding into a struct, optional fields may be omitted from the end of the list. For the example below, this means input lists of one, two, or three elements are accepted. - type StructWithOptionalFields struct{ - Required uint - Optional1 uint `rlp:"optional"` - Optional2 uint `rlp:"optional"` - } + type StructWithOptionalFields struct{ + Required uint + Optional1 uint `rlp:"optional"` + Optional2 uint `rlp:"optional"` + } The "nil", "nilList" and "nilString" tags apply to pointer-typed fields only, and change the decoding rules for the field type. For regular pointer fields without the "nil" tag, @@ -140,9 +137,9 @@ input values must always match the required input length exactly and the decoder produce nil values. When the "nil" tag is set, input values of size zero decode as a nil pointer. This is especially useful for recursive types. - type StructWithNilField struct { - Field *[3]byte `rlp:"nil"` - } + type StructWithNilField struct { + Field *[3]byte `rlp:"nil"` + } In the example above, Field allows two possible input sizes. For input 0xC180 (a list containing an empty string) Field is set to nil after decoding. For input 0xC483000000 (a diff --git a/rpc/doc.go b/rpc/doc.go index b9d0636b9..c3370ada1 100644 --- a/rpc/doc.go +++ b/rpc/doc.go @@ -15,7 +15,6 @@ // along with the go-ethereum library. If not, see . /* - Package rpc implements bi-directional JSON-RPC 2.0 on multiple transports. It provides access to the exported methods of an object across a network or other I/O @@ -23,16 +22,16 @@ connection. After creating a server or client instance, objects can be registere them visible as 'services'. Exported methods that follow specific conventions can be called remotely. It also has support for the publish/subscribe pattern. -RPC Methods +# RPC Methods Methods that satisfy the following criteria are made available for remote access: - - method must be exported - - method returns 0, 1 (response or error) or 2 (response and error) values + - method must be exported + - method returns 0, 1 (response or error) or 2 (response and error) values An example method: - func (s *CalcService) Add(a, b int) (int, error) + func (s *CalcService) Add(a, b int) (int, error) When the returned error isn't nil the returned integer is ignored and the error is sent back to the client. Otherwise the returned integer is sent back to the client. @@ -41,7 +40,7 @@ Optional arguments are supported by accepting pointer values as arguments. E.g. to do the addition in an optional finite field we can accept a mod argument as pointer value. - func (s *CalcService) Add(a, b int, mod *int) (int, error) + func (s *CalcService) Add(a, b int, mod *int) (int, error) This RPC method can be called with 2 integers and a null value as third argument. In that case the mod argument will be nil. Or it can be called with 3 integers, in that case mod @@ -56,40 +55,40 @@ to the client out of order. An example server which uses the JSON codec: - type CalculatorService struct {} + type CalculatorService struct {} - func (s *CalculatorService) Add(a, b int) int { - return a + b - } + func (s *CalculatorService) Add(a, b int) int { + return a + b + } - func (s *CalculatorService) Div(a, b int) (int, error) { - if b == 0 { - return 0, errors.New("divide by zero") - } - return a/b, nil - } + func (s *CalculatorService) Div(a, b int) (int, error) { + if b == 0 { + return 0, errors.New("divide by zero") + } + return a/b, nil + } - calculator := new(CalculatorService) - server := NewServer() - server.RegisterName("calculator", calculator) - l, _ := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: "/tmp/calculator.sock"}) - server.ServeListener(l) + calculator := new(CalculatorService) + server := NewServer() + server.RegisterName("calculator", calculator) + l, _ := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: "/tmp/calculator.sock"}) + server.ServeListener(l) -Subscriptions +# Subscriptions The package also supports the publish subscribe pattern through the use of subscriptions. A method that is considered eligible for notifications must satisfy the following criteria: - - method must be exported - - first method argument type must be context.Context - - method must have return types (rpc.Subscription, error) + - method must be exported + - first method argument type must be context.Context + - method must have return types (rpc.Subscription, error) An example method: - func (s *BlockChainService) NewBlocks(ctx context.Context) (rpc.Subscription, error) { - ... - } + func (s *BlockChainService) NewBlocks(ctx context.Context) (rpc.Subscription, error) { + ... + } When the service containing the subscription method is registered to the server, for example under the "blockchain" namespace, a subscription is created by calling the @@ -101,7 +100,7 @@ the client and server. The server will close the connection for any write error. For more information about subscriptions, see https://github.com/ledgerwatch/erigon/wiki/RPC-PUB-SUB. -Reverse Calls +# Reverse Calls In any method handler, an instance of rpc.Client can be accessed through the ClientFromContext method. Using this client instance, server-to-client method calls can be diff --git a/rpc/handler.go b/rpc/handler.go index 3a0da661e..c710f75f9 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -37,21 +37,20 @@ import ( // // The entry points for incoming messages are: // -// h.handleMsg(message) -// h.handleBatch(message) +// h.handleMsg(message) +// h.handleBatch(message) // // Outgoing calls use the requestOp struct. Register the request before sending it // on the connection: // -// op := &requestOp{ids: ...} -// h.addRequestOp(op) +// op := &requestOp{ids: ...} +// h.addRequestOp(op) // // Now send the request, then wait for the reply to be delivered through handleMsg: // -// if err := op.wait(...); err != nil { -// h.removeRequestOp(op) // timeout, etc. -// } -// +// if err := op.wait(...); err != nil { +// h.removeRequestOp(op) // timeout, etc. +// } type handler struct { reg *serviceRegistry unsubscribeCb *callback diff --git a/tests/block_test_util.go b/tests/block_test_util.go index 6635656bd..6d21727a3 100644 --- a/tests/block_test_util.go +++ b/tests/block_test_util.go @@ -163,17 +163,18 @@ func (t *BlockTest) genesis(config *params.ChainConfig) *core.Genesis { } } -/* See https://github.com/ethereum/tests/wiki/Blockchain-Tests-II +/* +See https://github.com/ethereum/tests/wiki/Blockchain-Tests-II - Whether a block is valid or not is a bit subtle, it's defined by presence of - blockHeader, transactions and uncleHeaders fields. If they are missing, the block is - invalid and we must verify that we do not accept it. + Whether a block is valid or not is a bit subtle, it's defined by presence of + blockHeader, transactions and uncleHeaders fields. If they are missing, the block is + invalid and we must verify that we do not accept it. - Since some tests mix valid and invalid blocks we need to check this for every block. + Since some tests mix valid and invalid blocks we need to check this for every block. - If a block is invalid it does not necessarily fail the test, if it's invalidness is - expected we are expected to ignore it and continue processing and then validate the - post state. + If a block is invalid it does not necessarily fail the test, if it's invalidness is + expected we are expected to ignore it and continue processing and then validate the + post state. */ func (t *BlockTest) insertBlocks(m *stages.MockSentry) ([]btBlock, error) { validBlocks := make([]btBlock, 0) diff --git a/tests/fuzzers/bls12381/precompile_fuzzer.go b/tests/fuzzers/bls12381/precompile_fuzzer.go index 963b157b3..1308ca3d2 100644 --- a/tests/fuzzers/bls12381/precompile_fuzzer.go +++ b/tests/fuzzers/bls12381/precompile_fuzzer.go @@ -72,8 +72,10 @@ func checkInput(id byte, inputLen int) bool { // The fuzzer functions must return // 1 if the fuzzer should increase priority of the -// given input during subsequent fuzzing (for example, the input is lexically -// correct and was parsed successfully); +// +// given input during subsequent fuzzing (for example, the input is lexically +// correct and was parsed successfully); +// // -1 if the input must not be added to corpus even if gives new coverage; and // 0 otherwise // other values are reserved for future use. diff --git a/tests/fuzzers/difficulty/difficulty-fuzz.go b/tests/fuzzers/difficulty/difficulty-fuzz.go index 80528f6e2..b5bee7d90 100644 --- a/tests/fuzzers/difficulty/difficulty-fuzz.go +++ b/tests/fuzzers/difficulty/difficulty-fuzz.go @@ -70,8 +70,10 @@ func (f *fuzzer) readBool() bool { // The function must return // 1 if the fuzzer should increase priority of the -// given input during subsequent fuzzing (for example, the input is lexically -// correct and was parsed successfully); +// +// given input during subsequent fuzzing (for example, the input is lexically +// correct and was parsed successfully); +// // -1 if the input must not be added to corpus even if gives new coverage; and // 0 otherwise // other values are reserved for future use. diff --git a/turbo/adapter/ethapi/internal.go b/turbo/adapter/ethapi/internal.go index 12d0ce2e4..0c90fcc7b 100644 --- a/turbo/adapter/ethapi/internal.go +++ b/turbo/adapter/ethapi/internal.go @@ -26,12 +26,12 @@ type ExecutionResult struct { *ethapi.ExecutionResult } -//nolint +// nolint func RPCMarshalHeader(head *types.Header) map[string]interface{} { return ethapi.RPCMarshalHeader(head) } -//nolint +// nolint func RPCMarshalBlock(b *types.Block, inclTx bool, fullTx bool, additional map[string]interface{}) (map[string]interface{}, error) { fields, err := ethapi.RPCMarshalBlock(b, inclTx, fullTx) if err != nil { @@ -45,7 +45,7 @@ func RPCMarshalBlock(b *types.Block, inclTx bool, fullTx bool, additional map[st return fields, err } -//nolint +// nolint func RPCMarshalBlockEx(b *types.Block, inclTx bool, fullTx bool, borTx types.Transaction, borTxHash common.Hash, additional map[string]interface{}) (map[string]interface{}, error) { fields, err := ethapi.RPCMarshalBlockEx(b, inclTx, fullTx, borTx, borTxHash) if err != nil { @@ -59,7 +59,7 @@ func RPCMarshalBlockEx(b *types.Block, inclTx bool, fullTx bool, borTx types.Tra return fields, err } -//nolint +// nolint type RPCTransaction struct { *ethapi.RPCTransaction } diff --git a/turbo/stages/blockchain_test.go b/turbo/stages/blockchain_test.go index 9323db209..392c60581 100644 --- a/turbo/stages/blockchain_test.go +++ b/turbo/stages/blockchain_test.go @@ -1136,8 +1136,8 @@ func TestLargeReorgTrieGC(t *testing.T) { // overtake the 'canon' chain until after it's passed canon by about 200 blocks. // // Details at: -// - https://github.com/ethereum/go-ethereum/issues/18977 -// - https://github.com/ethereum/go-ethereum/pull/18988 +// - https://github.com/ethereum/go-ethereum/issues/18977 +// - https://github.com/ethereum/go-ethereum/pull/18988 func TestLowDiffLongChain(t *testing.T) { // Generate a canonical chain to act as the main dataset m := stages.Mock(t) @@ -1677,20 +1677,19 @@ func TestDeleteRecreateSlotsAcrossManyBlocks(t *testing.T) { // TestInitThenFailCreateContract tests a pretty notorious case that happened // on mainnet over blocks 7338108, 7338110 and 7338115. -// - Block 7338108: address e771789f5cccac282f23bb7add5690e1f6ca467c is initiated -// with 0.001 ether (thus created but no code) -// - Block 7338110: a CREATE2 is attempted. The CREATE2 would deploy code on -// the same address e771789f5cccac282f23bb7add5690e1f6ca467c. However, the -// deployment fails due to OOG during initcode execution -// - Block 7338115: another tx checks the balance of -// e771789f5cccac282f23bb7add5690e1f6ca467c, and the snapshotter returned it as -// zero. +// - Block 7338108: address e771789f5cccac282f23bb7add5690e1f6ca467c is initiated +// with 0.001 ether (thus created but no code) +// - Block 7338110: a CREATE2 is attempted. The CREATE2 would deploy code on +// the same address e771789f5cccac282f23bb7add5690e1f6ca467c. However, the +// deployment fails due to OOG during initcode execution +// - Block 7338115: another tx checks the balance of +// e771789f5cccac282f23bb7add5690e1f6ca467c, and the snapshotter returned it as +// zero. // // The problem being that the snapshotter maintains a destructset, and adds items // to the destructset in case something is created "onto" an existing item. // We need to either roll back the snapDestructs, or not place it into snapDestructs // in the first place. -// func TestInitThenFailCreateContract(t *testing.T) { var ( // Generate a canonical chain to act as the main dataset @@ -1884,13 +1883,13 @@ func TestEIP2718Transition(t *testing.T) { // TestEIP1559Transition tests the following: // -// 1. A tranaction whose feeCap is greater than the baseFee is valid. -// 2. Gas accounting for access lists on EIP-1559 transactions is correct. -// 3. Only the transaction's tip will be received by the coinbase. -// 4. The transaction sender pays for both the tip and baseFee. -// 5. The coinbase receives only the partially realized tip when -// feeCap - tip < baseFee. -// 6. Legacy transaction behave as expected (e.g. gasPrice = feeCap = tip). +// 1. A tranaction whose feeCap is greater than the baseFee is valid. +// 2. Gas accounting for access lists on EIP-1559 transactions is correct. +// 3. Only the transaction's tip will be received by the coinbase. +// 4. The transaction sender pays for both the tip and baseFee. +// 5. The coinbase receives only the partially realized tip when +// feeCap - tip < baseFee. +// 6. Legacy transaction behave as expected (e.g. gasPrice = feeCap = tip). func TestEIP1559Transition(t *testing.T) { t.Skip("needs fixing") var ( diff --git a/turbo/stages/headerdownload/header_algos.go b/turbo/stages/headerdownload/header_algos.go index 53cea0779..67334eae0 100644 --- a/turbo/stages/headerdownload/header_algos.go +++ b/turbo/stages/headerdownload/header_algos.go @@ -159,7 +159,7 @@ func (hd *HeaderDownload) removeUpwards(link *Link) { if link == nil { return } - var toRemove []*Link = []*Link{link} + var toRemove = []*Link{link} for len(toRemove) > 0 { removal := toRemove[len(toRemove)-1] toRemove = toRemove[:len(toRemove)-1] @@ -599,7 +599,7 @@ func (hd *HeaderDownload) InsertHeader(hf FeedHeaderFunc, terminalTotalDifficult // InsertHeaders attempts to insert headers into the database, verifying them first // It returns true in the first return value if the system is "in sync" func (hd *HeaderDownload) InsertHeaders(hf FeedHeaderFunc, terminalTotalDifficulty *big.Int, logPrefix string, logChannel <-chan time.Time) (bool, error) { - var more bool = true + var more = true var err error var force bool var blocksToTTD uint64 diff --git a/turbo/transactions/tracing.go b/turbo/transactions/tracing.go index d0d569c93..462a3c265 100644 --- a/turbo/transactions/tracing.go +++ b/turbo/transactions/tracing.go @@ -132,7 +132,7 @@ func TraceTx( } // Run the transaction with tracing enabled. vmenv := vm.NewEVM(blockCtx, txCtx, ibs, chainConfig, vm.Config{Debug: true, Tracer: tracer}) - var refunds bool = true + var refunds = true if config != nil && config.NoRefunds != nil && *config.NoRefunds { refunds = false } diff --git a/turbo/trie/stream.go b/turbo/trie/stream.go index e2e773821..957843f3e 100644 --- a/turbo/trie/stream.go +++ b/turbo/trie/stream.go @@ -676,7 +676,7 @@ func StreamHash(it *StreamMergeIterator, storagePrefixLen int, hb *HashBuilder, itemType = newItemType switch itemType { case AccountStreamItem: - var a *accounts.Account = aVal + var a = aVal accData.Balance.Set(&a.Balance) accData.Nonce = a.Nonce accData.Incarnation = a.Incarnation diff --git a/turbo/trie/trie.go b/turbo/trie/trie.go index 33e067e87..ffda87355 100644 --- a/turbo/trie/trie.go +++ b/turbo/trie/trie.go @@ -44,8 +44,8 @@ var ( // Use New to create a trie that sits on top of a database. // // Trie is not safe for concurrent use. -//Deprecated -//use package turbo/trie +// Deprecated +// use package turbo/trie type Trie struct { root node @@ -58,7 +58,7 @@ type Trie struct { // trie is initially empty and does not require a database. Otherwise, // New will panic if db is nil and returns a MissingNodeError if root does // not exist in the database. Accessing the trie loads nodes from db on demand. -//Deprecated +// Deprecated // use package turbo/trie func New(root common.Hash) *Trie { trie := &Trie{ @@ -381,7 +381,7 @@ func findSubTriesToLoad(nd node, nibblePath []byte, hook []byte, rl RetainDecide dbPrefix = append(dbPrefix, b<<4) } else { dbPrefix[len(dbPrefix)-1] &= 0xf0 - dbPrefix[len(dbPrefix)-1] |= (b & 0xf) + dbPrefix[len(dbPrefix)-1] |= b & 0xf } bits += 4 } @@ -400,7 +400,7 @@ func findSubTriesToLoad(nd node, nibblePath []byte, hook []byte, rl RetainDecide } else { newDbPrefix = dbPrefix newDbPrefix[len(newDbPrefix)-1] &= 0xf0 - newDbPrefix[len(newDbPrefix)-1] |= (i1 & 0xf) + newDbPrefix[len(newDbPrefix)-1] |= i1 & 0xf } newPrefixes, newFixedBits, newHooks = findSubTriesToLoad(n.child1, newNibblePath, newHook, rl, newDbPrefix, bits+4, newPrefixes, newFixedBits, newHooks) } @@ -413,7 +413,7 @@ func findSubTriesToLoad(nd node, nibblePath []byte, hook []byte, rl RetainDecide } else { newDbPrefix = dbPrefix newDbPrefix[len(newDbPrefix)-1] &= 0xf0 - newDbPrefix[len(newDbPrefix)-1] |= (i2 & 0xf) + newDbPrefix[len(newDbPrefix)-1] |= i2 & 0xf } newPrefixes, newFixedBits, newHooks = findSubTriesToLoad(n.child2, newNibblePath, newHook, rl, newDbPrefix, bits+4, newPrefixes, newFixedBits, newHooks) } @@ -435,7 +435,7 @@ func findSubTriesToLoad(nd node, nibblePath []byte, hook []byte, rl RetainDecide } else { newDbPrefix = dbPrefix newDbPrefix[len(newDbPrefix)-1] &= 0xf0 - newDbPrefix[len(newDbPrefix)-1] |= (byte(i) & 0xf) + newDbPrefix[len(newDbPrefix)-1] |= byte(i) & 0xf } newPrefixes, newFixedBits, newHooks = findSubTriesToLoad(child, newNibblePath, newHook, rl, newDbPrefix, bits+4, newPrefixes, newFixedBits, newHooks) } diff --git a/turbo/trie/trie_root.go b/turbo/trie/trie_root.go index 2e3ee867a..494dbe1b6 100644 --- a/turbo/trie/trie_root.go +++ b/turbo/trie/trie_root.go @@ -174,26 +174,27 @@ func (l *FlatDBTrieLoader) SetStreamReceiver(receiver StreamReceiver) { } // CalcTrieRoot algo: -// for iterateIHOfAccounts { -// if canSkipState -// goto SkipAccounts // -// for iterateAccounts from prevIH to currentIH { -// use(account) -// for iterateIHOfStorage within accountWithIncarnation{ -// if canSkipState -// goto SkipStorage +// for iterateIHOfAccounts { +// if canSkipState +// goto SkipAccounts // -// for iterateStorage from prevIHOfStorage to currentIHOfStorage { -// use(storage) +// for iterateAccounts from prevIH to currentIH { +// use(account) +// for iterateIHOfStorage within accountWithIncarnation{ +// if canSkipState +// goto SkipStorage +// +// for iterateStorage from prevIHOfStorage to currentIHOfStorage { +// use(storage) +// } +// SkipStorage: +// use(ihStorage) // } -// SkipStorage: -// use(ihStorage) // } +// SkipAccounts: +// use(AccTrie) // } -// SkipAccounts: -// use(AccTrie) -// } func (l *FlatDBTrieLoader) CalcTrieRoot(tx kv.Tx, prefix []byte, quit <-chan struct{}) (common.Hash, error) { accC, err := tx.Cursor(kv.HashedAccounts) @@ -1318,18 +1319,24 @@ func (c *StorageTrieCursor) _deleteCurrent() error { } /* - Dense Sequence - if between 2 AccTrie records not possible insert any state record - then they form "dense sequence" - If 2 AccTrie records form Dense Sequence - then no reason to iterate over state - just use AccTrie one after another - Example1: - 1234 - 1235 - Example2: - 12ff - 13 - Example3: - 12ff - 13000000 - If 2 AccTrie records form "sequence" then it can be consumed without moving StateCursor +Dense Sequence - if between 2 AccTrie records not possible insert any state record - then they form "dense sequence" +If 2 AccTrie records form Dense Sequence - then no reason to iterate over state - just use AccTrie one after another +Example1: + + 1234 + 1235 + +Example2: + + 12ff + 13 + +Example3: + + 12ff + 13000000 + +If 2 AccTrie records form "sequence" then it can be consumed without moving StateCursor */ func isDenseSequence(prev []byte, next []byte) bool { isSequence := false diff --git a/turbo/trie/trie_test.go b/turbo/trie/trie_test.go index f4691cb33..9cfbf06ae 100644 --- a/turbo/trie/trie_test.go +++ b/turbo/trie/trie_test.go @@ -73,7 +73,7 @@ func TestLargeValue(t *testing.T) { // TestRandomCases tests som cases that were found via random fuzzing func TestRandomCases(t *testing.T) { - var rt []randTestStep = []randTestStep{ + var rt = []randTestStep{ {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 0 {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 1 {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000002")}, // step 2 diff --git a/turbo/trie/witness_builder.go b/turbo/trie/witness_builder.go index a9a233086..77d050eff 100644 --- a/turbo/trie/witness_builder.go +++ b/turbo/trie/witness_builder.go @@ -263,7 +263,7 @@ func (b *WitnessBuilder) makeBlockWitness( if err := b.makeBlockWitness(child, expandKeyHex(hex, byte(i)), limiter, false); err != nil { return err } - mask |= (uint32(1) << uint(i)) + mask |= uint32(1) << uint(i) } } return b.addBranchOp(mask)