From 3034c75403112f2aba6c244994aecdb3dee8561d Mon Sep 17 00:00:00 2001 From: Trung Nguyen <24930+trung@users.noreply.github.com> Date: Mon, 11 May 2020 16:15:27 -0400 Subject: [PATCH] fix linting issues (#995) --- .github/workflows/pr.yml | 24 ++++++++++--- cmd/geth/accountcmd_test.go | 2 +- cmd/geth/consolecmd_test.go | 2 +- cmd/puppeth/genesis_test.go | 8 ++--- cmd/utils/flags_test.go | 4 +-- consensus/istanbul/backend/backend.go | 2 +- consensus/istanbul/backend/backend_test.go | 7 ++-- consensus/istanbul/backend/engine.go | 8 ++--- consensus/istanbul/backend/engine_test.go | 36 ++++++++----------- consensus/istanbul/backend/handler.go | 5 ++- consensus/istanbul/backend/handler_test.go | 11 +++--- consensus/istanbul/backend/snapshot.go | 4 +-- consensus/istanbul/backend/snapshot_test.go | 4 +-- consensus/istanbul/core/backlog_test.go | 8 ++--- consensus/istanbul/core/commit_test.go | 2 +- consensus/istanbul/core/core_test.go | 10 ++---- consensus/istanbul/core/errors.go | 2 +- consensus/istanbul/core/roundchange.go | 2 +- consensus/istanbul/core/testbackend_test.go | 2 +- consensus/istanbul/core/types.go | 4 +-- consensus/istanbul/utils.go | 2 +- core/bench_test.go | 2 +- core/blockchain.go | 6 ++-- core/call_helper.go | 5 +-- core/state_transition_test.go | 6 ++-- core/types/permissions_cache.go | 4 +-- core/types/permissions_cache_test.go | 16 ++++----- ...transaction_signing_quorum_private_test.go | 1 - core/types/transaction_signing_quorum_test.go | 10 +++--- eth/config_test.go | 3 +- eth/handler_test.go | 8 ++--- eth/protocol.go | 2 +- internal/ethapi/api.go | 9 +++-- node/config.go | 2 +- node/service.go | 2 +- p2p/enode/urlv4.go | 1 - p2p/permissions.go | 5 +-- params/config_test.go | 3 +- params/protocol_params_test.go | 3 +- params/quorum.go | 4 +-- permission/api.go | 3 +- permission/permission.go | 17 ++++----- permission/permission_test.go | 29 ++++++--------- plugin/central.go | 8 ++--- plugin/initializer/gateway.go | 5 +-- plugin/utils.go | 10 +++--- raft/api.go | 8 ++--- raft/constants.go | 14 ++++---- raft/handler_test.go | 5 +-- raft/minter.go | 3 +- raft/minter_test.go | 18 +++++----- rpc/inproc.go | 1 - 52 files changed, 160 insertions(+), 202 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 2b942e63a..b971db07b 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -7,9 +7,25 @@ on: - .gitignore env: GO_VERSION: 1.13 - GOPATH: ${{ github.workspace }}/go - WORKING_DIR: ${{ github.workspace }}/go/src/github.com/ethereum/go-ethereum jobs: + lint: + name: 'Code linters' + runs-on: ubuntu-latest + steps: + - name: 'Setup Go ${{ env.GO_VERSION }}' + uses: actions/setup-go@v1 + with: + go-version: ${{ env.GO_VERSION }} + - name: 'Check out project files' + uses: actions/checkout@v2 + with: + submodules: false + - name: 'Prepare environment' + run: | + echo "::add-path::$(go env GOPATH)/bin" + - name: 'Run code linters' + run: | + GO111MODULE=off make lint unit-tests: name: 'Unit tests in ${{ matrix.os }}' strategy: @@ -25,10 +41,9 @@ jobs: with: go-version: ${{ env.GO_VERSION }} - name: 'Check out project files' - uses: actions/checkout@574281d + uses: actions/checkout@v2 with: submodules: recursive - path: ${{ env.WORKING_DIR }} - name: 'Prepare environment' run: | # https://github.com/actions/virtual-environments/issues/798 @@ -36,7 +51,6 @@ jobs: echo "::add-path::$(go env GOPATH)/bin" - name: 'Run unit tests' - working-directory: ${{ env.WORKING_DIR }} run: | make test docker-build: diff --git a/cmd/geth/accountcmd_test.go b/cmd/geth/accountcmd_test.go index b460e5448..7eedfa76d 100644 --- a/cmd/geth/accountcmd_test.go +++ b/cmd/geth/accountcmd_test.go @@ -176,7 +176,7 @@ func TestGethDoesntStartWithoutPrivateTransactionManagerVariableSet(t *testing.T expectedText := "the PRIVATE_CONFIG environment variable must be specified for Quorum" result := strings.TrimSpace(geth.StderrText()) - if strings.Index(result, expectedText) == -1 { + if !strings.Contains(result, expectedText) { geth.Fatalf("bad stderr text. want '%s', got '%s'", expectedText, result) } } diff --git a/cmd/geth/consolecmd_test.go b/cmd/geth/consolecmd_test.go index 678df204e..8ee9ea5b0 100644 --- a/cmd/geth/consolecmd_test.go +++ b/cmd/geth/consolecmd_test.go @@ -244,4 +244,4 @@ func SetResetPrivateConfig(value string) func() { return func() { os.Setenv("PRIVATE_CONFIG", existingValue) } -} \ No newline at end of file +} diff --git a/cmd/puppeth/genesis_test.go b/cmd/puppeth/genesis_test.go index 534b33fe6..3bbebe192 100644 --- a/cmd/puppeth/genesis_test.go +++ b/cmd/puppeth/genesis_test.go @@ -29,8 +29,8 @@ import ( // Tests the go-ethereum to Aleth chainspec conversion for the Stureby testnet. func TestAlethSturebyConverter(t *testing.T) { - // //Quorum - skip this test as MinGasLimit and GasLimitBoundDivisor has been overriden for quorum - t.Skipf("skipping this test as MinGasLimit and GasLimitBoundDivisor has been overriden for quorum") + // //Quorum - skip this test as MinGasLimit and GasLimitBoundDivisor has been overridden for quorum + t.Skipf("skipping this test as MinGasLimit and GasLimitBoundDivisor has been overridden for quorum") // /Quorum blob, err := ioutil.ReadFile("testdata/stureby_geth.json") @@ -72,8 +72,8 @@ func TestAlethSturebyConverter(t *testing.T) { // Tests the go-ethereum to Parity chainspec conversion for the Stureby testnet. func TestParitySturebyConverter(t *testing.T) { - // //Quorum - skip this test as MinGasLimit and GasLimitBoundDivisor has been overriden for quorum - t.Skipf("skipping this test as MinGasLimit and GasLimitBoundDivisor has been overriden for quorum") + // //Quorum - skip this test as MinGasLimit and GasLimitBoundDivisor has been overridden for quorum + t.Skipf("skipping this test as MinGasLimit and GasLimitBoundDivisor has been overridden for quorum") // /Quorum blob, err := ioutil.ReadFile("testdata/stureby_geth.json") diff --git a/cmd/utils/flags_test.go b/cmd/utils/flags_test.go index f8df2eee4..3359d6d2c 100644 --- a/cmd/utils/flags_test.go +++ b/cmd/utils/flags_test.go @@ -74,8 +74,8 @@ func TestSetImmutabilityThreshold(t *testing.T) { fs.Int(QuorumImmutabilityThreshold.Name, 0, "") arbitraryCLIContext := cli.NewContext(nil, fs, nil) assert.NoError(t, arbitraryCLIContext.GlobalSet(QuorumImmutabilityThreshold.Name, strconv.Itoa(100000))) - assert.True(t, arbitraryCLIContext.GlobalIsSet(QuorumImmutabilityThreshold.Name) == true, "immutability threshold flag not set") - assert.True(t, arbitraryCLIContext.GlobalInt(QuorumImmutabilityThreshold.Name) == 100000, "immutability threshold value not set") + assert.True(t, arbitraryCLIContext.GlobalIsSet(QuorumImmutabilityThreshold.Name), "immutability threshold flag not set") + assert.Equal(t, 100000, arbitraryCLIContext.GlobalInt(QuorumImmutabilityThreshold.Name), "immutability threshold value not set") } func TestSetPlugins_whenTypical(t *testing.T) { diff --git a/consensus/istanbul/backend/backend.go b/consensus/istanbul/backend/backend.go index 0b2f4ac17..3eb699fe1 100644 --- a/consensus/istanbul/backend/backend.go +++ b/consensus/istanbul/backend/backend.go @@ -242,7 +242,7 @@ func (sb *backend) Verify(proposal istanbul.Proposal) (time.Duration, error) { // Sign implements istanbul.Backend.Sign func (sb *backend) Sign(data []byte) ([]byte, error) { - hashData := crypto.Keccak256([]byte(data)) + hashData := crypto.Keccak256(data) return crypto.Sign(hashData, sb.privateKey) } diff --git a/consensus/istanbul/backend/backend_test.go b/consensus/istanbul/backend/backend_test.go index 5c9858209..822c0f5ec 100644 --- a/consensus/istanbul/backend/backend_test.go +++ b/consensus/istanbul/backend/backend_test.go @@ -148,11 +148,8 @@ func TestCommit(t *testing.T) { for _, test := range testCases { expBlock := test.expectedBlock() go func() { - select { - case result := <-backend.commitCh: - commitCh <- result - return - } + result := <-backend.commitCh + commitCh <- result }() backend.proposedBlockHash = expBlock.Hash() diff --git a/consensus/istanbul/backend/engine.go b/consensus/istanbul/backend/engine.go index 2965ef7c0..2610ceede 100644 --- a/consensus/istanbul/backend/engine.go +++ b/consensus/istanbul/backend/engine.go @@ -19,7 +19,6 @@ package backend import ( "bytes" "errors" - "golang.org/x/crypto/sha3" "math/big" "math/rand" "time" @@ -36,6 +35,7 @@ import ( "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rpc" lru "github.com/hashicorp/golang-lru" + "golang.org/x/crypto/sha3" ) const ( @@ -67,7 +67,7 @@ var ( // errInvalidUncleHash is returned if a block contains an non-empty uncle list. errInvalidUncleHash = errors.New("non empty uncle hash") // errInconsistentValidatorSet is returned if the validator set is inconsistent - errInconsistentValidatorSet = errors.New("non empty uncle hash") + // errInconsistentValidatorSet = errors.New("non empty uncle hash") // errInvalidTimestamp is returned if the timestamp of a block is lower than the previous block's timestamp + the minimum block period. errInvalidTimestamp = errors.New("invalid timestamp") // errInvalidVotingChain is returned if an authorization list is attempted to @@ -81,7 +81,7 @@ var ( // errEmptyCommittedSeals is returned if the field of committed seals is zero. errEmptyCommittedSeals = errors.New("zero committed seals") // errMismatchTxhashes is returned if the TxHash in header is mismatch. - errMismatchTxhashes = errors.New("mismatch transcations hashes") + errMismatchTxhashes = errors.New("mismatch transactions hashes") ) var ( defaultDifficulty = big.NewInt(1) @@ -195,7 +195,7 @@ func (sb *backend) verifyCascadingFields(chain consensus.ChainReader, header *ty if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash { return consensus.ErrUnknownAncestor } - if uint64(parent.Time)+sb.config.BlockPeriod > header.Time { + if parent.Time+sb.config.BlockPeriod > header.Time { return errInvalidTimestamp } // Verify validators in extraData. Validators in snapshot and extraData should be the same. diff --git a/consensus/istanbul/backend/engine_test.go b/consensus/istanbul/backend/engine_test.go index ac9e94543..299465da6 100644 --- a/consensus/istanbul/backend/engine_test.go +++ b/consensus/istanbul/backend/engine_test.go @@ -19,7 +19,6 @@ package backend import ( "bytes" "crypto/ecdsa" - "github.com/ethereum/go-ethereum/core/rawdb" "math/big" "reflect" "testing" @@ -30,6 +29,7 @@ import ( "github.com/ethereum/go-ethereum/consensus" "github.com/ethereum/go-ethereum/consensus/istanbul" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/crypto" @@ -167,14 +167,12 @@ func TestSealStopChannel(t *testing.T) { stop := make(chan struct{}, 1) eventSub := engine.EventMux().Subscribe(istanbul.RequestEvent{}) eventLoop := func() { - select { - case ev := <-eventSub.Chan(): - _, ok := ev.Data.(istanbul.RequestEvent) - if !ok { - t.Errorf("unexpected event comes: %v", reflect.TypeOf(ev.Data)) - } - stop <- struct{}{} + ev := <-eventSub.Chan() + _, ok := ev.Data.(istanbul.RequestEvent) + if !ok { + t.Errorf("unexpected event comes: %v", reflect.TypeOf(ev.Data)) } + stop <- struct{}{} eventSub.Unsubscribe() } go eventLoop() @@ -203,14 +201,12 @@ func TestSealCommittedOtherHash(t *testing.T) { stopChannel := make(chan struct{}) go func() { - select { - case ev := <-eventSub.Chan(): - if _, ok := ev.Data.(istanbul.RequestEvent); !ok { - t.Errorf("unexpected event comes: %v", reflect.TypeOf(ev.Data)) - } - if err := engine.Commit(otherBlock, [][]byte{expectedCommittedSeal}); err != nil { - t.Error(err.Error()) - } + ev := <-eventSub.Chan() + if _, ok := ev.Data.(istanbul.RequestEvent); !ok { + t.Errorf("unexpected event comes: %v", reflect.TypeOf(ev.Data)) + } + if err := engine.Commit(otherBlock, [][]byte{expectedCommittedSeal}); err != nil { + t.Error(err.Error()) } eventSub.Unsubscribe() }() @@ -229,11 +225,9 @@ func TestSealCommittedOtherHash(t *testing.T) { close(stopChannel) } - select { - case output := <-blockOutputChannel: - if output != nil { - t.Error("Block not nil!") - } + output := <-blockOutputChannel + if output != nil { + t.Error("Block not nil!") } } diff --git a/consensus/istanbul/backend/handler.go b/consensus/istanbul/backend/handler.go index 18572c7ac..7fd1d9c63 100644 --- a/consensus/istanbul/backend/handler.go +++ b/consensus/istanbul/backend/handler.go @@ -23,14 +23,13 @@ import ( "math/big" "reflect" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/consensus" "github.com/ethereum/go-ethereum/consensus/istanbul" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/p2p" - "github.com/hashicorp/golang-lru" + lru "github.com/hashicorp/golang-lru" ) const ( diff --git a/consensus/istanbul/backend/handler_test.go b/consensus/istanbul/backend/handler_test.go index c6c41f4e8..ea347c607 100644 --- a/consensus/istanbul/backend/handler_test.go +++ b/consensus/istanbul/backend/handler_test.go @@ -22,13 +22,12 @@ import ( "math/big" "testing" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/consensus/istanbul" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/rlp" - "github.com/hashicorp/golang-lru" + lru "github.com/hashicorp/golang-lru" ) func TestIstanbulMessage(t *testing.T) { @@ -147,10 +146,8 @@ func postAndWait(backend *backend, block *types.Block, t *testing.T) { defer eventSub.Unsubscribe() stop := make(chan struct{}, 1) eventLoop := func() { - select { - case <-eventSub.Chan(): - stop <- struct{}{} - } + <-eventSub.Chan() + stop <- struct{}{} } go eventLoop() if err := backend.EventMux().Post(istanbul.RequestEvent{ diff --git a/consensus/istanbul/backend/snapshot.go b/consensus/istanbul/backend/snapshot.go index 4ab8d9425..e369147f8 100644 --- a/consensus/istanbul/backend/snapshot.go +++ b/consensus/istanbul/backend/snapshot.go @@ -207,9 +207,9 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) { // Tally up the new vote from the validator var authorize bool switch { - case bytes.Compare(header.Nonce[:], nonceAuthVote) == 0: + case bytes.Equal(header.Nonce[:], nonceAuthVote): authorize = true - case bytes.Compare(header.Nonce[:], nonceDropVote) == 0: + case bytes.Equal(header.Nonce[:], nonceDropVote): authorize = false default: return nil, errInvalidVote diff --git a/consensus/istanbul/backend/snapshot_test.go b/consensus/istanbul/backend/snapshot_test.go index b45daa0f7..347368cad 100644 --- a/consensus/istanbul/backend/snapshot_test.go +++ b/consensus/istanbul/backend/snapshot_test.go @@ -19,7 +19,6 @@ package backend import ( "bytes" "crypto/ecdsa" - "github.com/ethereum/go-ethereum/core/rawdb" "math/big" "reflect" "testing" @@ -28,6 +27,7 @@ import ( "github.com/ethereum/go-ethereum/consensus/istanbul" "github.com/ethereum/go-ethereum/consensus/istanbul/validator" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/crypto" @@ -417,7 +417,7 @@ func TestSaveAndLoad(t *testing.T) { }, }, Tally: map[common.Address]Tally{ - common.StringToAddress("1234567893"): Tally{ + common.StringToAddress("1234567893"): { Authorize: false, Votes: 20, }, diff --git a/consensus/istanbul/core/backlog_test.go b/consensus/istanbul/core/backlog_test.go index 6e02493bc..64e5e5ec5 100644 --- a/consensus/istanbul/core/backlog_test.go +++ b/consensus/istanbul/core/backlog_test.go @@ -300,19 +300,19 @@ func TestProcessBacklog(t *testing.T) { subjectPayload, _ := Encode(subject) msgs := []*message{ - &message{ + { Code: msgPreprepare, Msg: prepreparePayload, }, - &message{ + { Code: msgPrepare, Msg: subjectPayload, }, - &message{ + { Code: msgCommit, Msg: subjectPayload, }, - &message{ + { Code: msgRoundChange, Msg: subjectPayload, }, diff --git a/consensus/istanbul/core/commit_test.go b/consensus/istanbul/core/commit_test.go index 97be7b062..9e7489331 100644 --- a/consensus/istanbul/core/commit_test.go +++ b/consensus/istanbul/core/commit_test.go @@ -210,7 +210,7 @@ OUTER: committedSeals := v0.committedMsgs[0].committedSeals for _, validator := range r0.valSet.List() { for _, seal := range committedSeals { - if bytes.Compare(validator.Address().Bytes(), seal[:common.AddressLength]) == 0 { + if bytes.Equal(validator.Address().Bytes(), seal[:common.AddressLength]) { signedCount++ break } diff --git a/consensus/istanbul/core/core_test.go b/consensus/istanbul/core/core_test.go index 8732e1aa5..8521f08ee 100644 --- a/consensus/istanbul/core/core_test.go +++ b/consensus/istanbul/core/core_test.go @@ -17,12 +17,12 @@ package core import ( - "github.com/ethereum/go-ethereum/common" "math/big" "reflect" "testing" "time" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/consensus/istanbul" "github.com/ethereum/go-ethereum/core/types" elog "github.com/ethereum/go-ethereum/log" @@ -58,16 +58,12 @@ func TestNewRequest(t *testing.T) { request1 := makeBlock(1) sys.backends[0].NewRequest(request1) - select { - case <-time.After(1 * time.Second): - } + <-time.After(1 * time.Second) request2 := makeBlock(2) sys.backends[0].NewRequest(request2) - select { - case <-time.After(1 * time.Second): - } + <-time.After(1 * time.Second) for _, backend := range sys.backends { if len(backend.committedMsgs) != 2 { diff --git a/consensus/istanbul/core/errors.go b/consensus/istanbul/core/errors.go index a97353204..23aebba5f 100644 --- a/consensus/istanbul/core/errors.go +++ b/consensus/istanbul/core/errors.go @@ -42,7 +42,7 @@ var ( // errFailedDecodeCommit is returned when the COMMIT message is malformed. errFailedDecodeCommit = errors.New("failed to decode COMMIT") // errFailedDecodeMessageSet is returned when the message set is malformed. - errFailedDecodeMessageSet = errors.New("failed to decode message set") + // errFailedDecodeMessageSet = errors.New("failed to decode message set") // errInvalidSigner is returned when the message is signed by a validator different than message sender errInvalidSigner = errors.New("message not signed by the sender") ) diff --git a/consensus/istanbul/core/roundchange.go b/consensus/istanbul/core/roundchange.go index 0289ef041..6c02f626e 100644 --- a/consensus/istanbul/core/roundchange.go +++ b/consensus/istanbul/core/roundchange.go @@ -93,7 +93,7 @@ func (c *core) handleRoundChange(msg *message, src istanbul.Validator) error { // Once we received f+1 ROUND CHANGE messages, those messages form a weak certificate. // If our round number is smaller than the certificate's round number, we would // try to catch up the round number. - if c.waitingForRoundChange && num == int(c.valSet.F()+1) { + if c.waitingForRoundChange && num == c.valSet.F()+1 { if cv.Round.Cmp(roundView.Round) < 0 { c.sendRoundChange(roundView.Round) } diff --git a/consensus/istanbul/core/testbackend_test.go b/consensus/istanbul/core/testbackend_test.go index d00ffb370..4fe5aaa68 100644 --- a/consensus/istanbul/core/testbackend_test.go +++ b/consensus/istanbul/core/testbackend_test.go @@ -18,13 +18,13 @@ package core import ( "crypto/ecdsa" - "github.com/ethereum/go-ethereum/core/rawdb" "math/big" "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/consensus/istanbul" "github.com/ethereum/go-ethereum/consensus/istanbul/validator" + "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/event" diff --git a/consensus/istanbul/core/types.go b/consensus/istanbul/core/types.go index fca60eb89..f8e1c8128 100644 --- a/consensus/istanbul/core/types.go +++ b/consensus/istanbul/core/types.go @@ -82,7 +82,7 @@ const ( msgPrepare msgCommit msgRoundChange - msgAll + // msgAll ) type message struct { @@ -142,7 +142,7 @@ func (m *message) FromPayload(b []byte, validateFn func([]byte, []byte) (common. if err != nil { return err } - if bytes.Compare(signerAdd.Bytes(), m.Address.Bytes()) != 0 { + if !bytes.Equal(signerAdd.Bytes(), m.Address.Bytes()) { return errInvalidSigner } } diff --git a/consensus/istanbul/utils.go b/consensus/istanbul/utils.go index f93b11112..1382ad03e 100644 --- a/consensus/istanbul/utils.go +++ b/consensus/istanbul/utils.go @@ -34,7 +34,7 @@ func RLPHash(v interface{}) (h common.Hash) { // GetSignatureAddress gets the signer address from the signature func GetSignatureAddress(data []byte, sig []byte) (common.Address, error) { // 1. Keccak data - hashData := crypto.Keccak256([]byte(data)) + hashData := crypto.Keccak256(data) // 2. Recover public key pubkey, err := crypto.SigToPub(hashData, sig) if err != nil { diff --git a/core/bench_test.go b/core/bench_test.go index 3b6cbe0dc..1181b0549 100644 --- a/core/bench_test.go +++ b/core/bench_test.go @@ -94,7 +94,7 @@ func genValueTx(nbytes int) func(int, *BlockGen) { var ( ringKeys = make([]*ecdsa.PrivateKey, 1000) ringAddrs = make([]common.Address, len(ringKeys)) - bigTxGas = new(big.Int).SetUint64(params.TxGas) + // bigTxGas = new(big.Int).SetUint64(params.TxGas) ) func init() { diff --git a/core/blockchain.go b/core/blockchain.go index 86f8e6371..0d3ce8dae 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -43,7 +43,7 @@ import ( "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/trie" - "github.com/hashicorp/golang-lru" + lru "github.com/hashicorp/golang-lru" ) var ( @@ -1295,7 +1295,7 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types. // QUORUM // checks if the consensus engine is Rfat -func(bc *BlockChain) isRaft() bool{ +func (bc *BlockChain) isRaft() bool { return bc.chainConfig.IsQuorum && bc.chainConfig.Istanbul == nil && bc.chainConfig.Clique == nil } @@ -1318,6 +1318,7 @@ func (bc *BlockChain) CommitBlockWithState(deleteEmptyObjects bool, state, priva } return nil } + // END QUORUM // writeBlockWithState writes the block and all associated state to the database, @@ -1366,7 +1367,6 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. } triedb := bc.stateCache.TrieDB() - // If we're running an archive node, always flush if bc.cacheConfig.TrieDirtyDisabled { if err := triedb.Commit(root, false); err != nil { diff --git a/core/call_helper.go b/core/call_helper.go index 378f2b5bd..e2c4dea9d 100644 --- a/core/call_helper.go +++ b/core/call_helper.go @@ -73,10 +73,7 @@ func (cg *callHelper) MakeCall(private bool, key *ecdsa.PrivateKey, to common.Ad vmenv := vm.NewEVM(context, publicState, privateState, params.QuorumTestChainConfig, vm.Config{}) sender := vm.AccountRef(msg.From()) vmenv.Call(sender, to, msg.Data(), 100000000, new(big.Int)) - if err != nil { - return err - } - return nil + return err } // MakeCallHelper returns a new callHelper diff --git a/core/state_transition_test.go b/core/state_transition_test.go index 68c962661..d9fc1a92d 100644 --- a/core/state_transition_test.go +++ b/core/state_transition_test.go @@ -2,17 +2,15 @@ package core import ( "fmt" - "github.com/ethereum/go-ethereum/core/rawdb" "math/big" "testing" - "github.com/ethereum/go-ethereum/private" - "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/params" - + "github.com/ethereum/go-ethereum/private" testifyassert "github.com/stretchr/testify/assert" ) diff --git a/core/types/permissions_cache.go b/core/types/permissions_cache.go index f0e8a2823..84a05376a 100644 --- a/core/types/permissions_cache.go +++ b/core/types/permissions_cache.go @@ -195,7 +195,7 @@ func GetSyncStatus() bool { } // sets the default access to Readonly upon QIP714Blokc -func SetDefaultAccess(){ +func SetDefaultAccess() { DefaultAccess = ReadOnly QIP714BlockReached = true } @@ -393,7 +393,7 @@ func GetAcctAccess(acctId common.Address) AccessType { } func ValidateNodeForTxn(hexnodeId string, from common.Address) bool { - if !QIP714BlockReached || hexnodeId == ""{ + if !QIP714BlockReached || hexnodeId == "" { return true } diff --git a/core/types/permissions_cache_test.go b/core/types/permissions_cache_test.go index 47df8430b..f0ea8ed6b 100644 --- a/core/types/permissions_cache_test.go +++ b/core/types/permissions_cache_test.go @@ -28,7 +28,7 @@ func TestSetSyncStatus(t *testing.T) { // check if the value is set properly by calling Get syncStatus := GetSyncStatus() - assert.True(syncStatus == true, fmt.Sprintf("Expected syncstatus %v . Got %v ", true, syncStatus)) + assert.True(syncStatus, fmt.Sprintf("Expected syncstatus %v . Got %v ", true, syncStatus)) } func TestSetDefaults(t *testing.T) { @@ -119,7 +119,7 @@ func TestRoleCache_UpsertRole(t *testing.T) { // update role status and validate RoleInfoMap.UpsertRole(ORGADMIN, ORGADMIN, true, true, FullAccess, false) roleInfo = RoleInfoMap.GetRole(ORGADMIN, ORGADMIN) - assert.True(roleInfo.Active == false, fmt.Sprintf("Expected role active status to be %v, got %v", true, roleInfo.Active)) + assert.True(!roleInfo.Active, fmt.Sprintf("Expected role active status to be %v, got %v", true, roleInfo.Active)) } func TestAcctCache_UpsertAccount(t *testing.T) { @@ -189,32 +189,32 @@ func TestValidateNodeForTxn(t *testing.T) { assert := testifyassert.New(t) // pass the enode as null and the response should be true txnAllowed := ValidateNodeForTxn("", Acct1) - assert.True(txnAllowed == true, "Expected access %v, got %v", true, txnAllowed) + assert.True(txnAllowed, "Expected access %v, got %v", true, txnAllowed) SetDefaultAccess() // if a proper enode id is not passed, return should be false txnAllowed = ValidateNodeForTxn("ABCDE", Acct1) - assert.True(txnAllowed == false, "Expected access %v, got %v", true, txnAllowed) + assert.True(!txnAllowed, "Expected access %v, got %v", true, txnAllowed) // if cache is not populated but the enode and account details are proper, // should return true txnAllowed = ValidateNodeForTxn(NODE1, Acct1) - assert.True(txnAllowed == true, "Expected access %v, got %v", true, txnAllowed) + assert.True(txnAllowed, "Expected access %v, got %v", true, txnAllowed) // populate an org, account and node. validate access OrgInfoMap.UpsertOrg(NETWORKADMIN, "", NETWORKADMIN, big.NewInt(1), OrgApproved) NodeInfoMap.UpsertNode(NETWORKADMIN, NODE1, NodeApproved) AcctInfoMap.UpsertAccount(NETWORKADMIN, NETWORKADMIN, Acct1, true, AcctActive) txnAllowed = ValidateNodeForTxn(NODE1, Acct1) - assert.True(txnAllowed == true, "Expected access %v, got %v", true, txnAllowed) + assert.True(txnAllowed, "Expected access %v, got %v", true, txnAllowed) // test access from a node not linked to the org. should return false OrgInfoMap.UpsertOrg(ORGADMIN, "", ORGADMIN, big.NewInt(1), OrgApproved) NodeInfoMap.UpsertNode(ORGADMIN, NODE2, NodeApproved) AcctInfoMap.UpsertAccount(ORGADMIN, ORGADMIN, Acct2, true, AcctActive) txnAllowed = ValidateNodeForTxn(NODE1, Acct2) - assert.True(txnAllowed == false, "Expected access %v, got %v", true, txnAllowed) + assert.True(!txnAllowed, "Expected access %v, got %v", true, txnAllowed) } // This is to make sure enode.ParseV4() honors single hexNodeId value eventhough it does follow enode URI scheme @@ -234,7 +234,7 @@ func TestValidateNodeForTxn_whenUsingOnlyHexNodeId(t *testing.T) { // test the cache limit func TestLRUCacheLimit(t *testing.T) { - for i := 0; i < defaultOrgMapLimit ; i++ { + for i := 0; i < defaultOrgMapLimit; i++ { orgName := "ORG" + strconv.Itoa(i) OrgInfoMap.UpsertOrg(orgName, "", NETWORKADMIN, big.NewInt(1), OrgApproved) } diff --git a/core/types/transaction_signing_quorum_private_test.go b/core/types/transaction_signing_quorum_private_test.go index 13ff83020..694a3fd29 100644 --- a/core/types/transaction_signing_quorum_private_test.go +++ b/core/types/transaction_signing_quorum_private_test.go @@ -60,4 +60,3 @@ func TestQuorumSignPrivateQuorum(t *testing.T) { } } - diff --git a/core/types/transaction_signing_quorum_test.go b/core/types/transaction_signing_quorum_test.go index 277c638b5..8cce90852 100644 --- a/core/types/transaction_signing_quorum_test.go +++ b/core/types/transaction_signing_quorum_test.go @@ -20,12 +20,12 @@ import ( "crypto/ecdsa" "crypto/elliptic" "fmt" - testifyassert "github.com/stretchr/testify/assert" "math/big" "testing" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + testifyassert "github.com/stretchr/testify/assert" ) // run all the tests in this file @@ -115,8 +115,7 @@ func TestSignQuorumEIP155Public(t *testing.T) { k1, _ := createKey(crypto.S256(), k1v) // chainId 1 even EIP155Signer should be 37 conflicts with private transaction - var chainId int64 - chainId = 2 // 7 2 10 + var chainId int64 = 2 // 7 2 10 v0 := chainId*2 + 35 // sig[64] + 35 .. where sig[64] == 0 v1 := chainId*2 + 36 // sig[64] + 35 .. where sig[64] == 1 @@ -139,7 +138,7 @@ func TestSignQuorumEIP155Public(t *testing.T) { assert.True(from == addr, fmt.Sprintf("Expected from and address to be equal. Got %x want %x", from, addr)) // chainId 1 even EIP155Signer should be 38 conflicts with private transaction - assert.False(signedTx.IsPrivate(), fmt.Sprintf("Public transaction is set to a private transation v == [%v]", signedTx.data.V)) + assert.False(signedTx.IsPrivate(), fmt.Sprintf("Public transaction is set to a private transition v == [%v]", signedTx.data.V)) signedTx, addr, _ = signTx(k1, EIPsigner) @@ -166,8 +165,7 @@ func TestSignQuorumEIP155FailPublicChain1(t *testing.T) { k1, _ := createKey(crypto.S256(), k1v) // chainId 1 even EIP155Signer should be 37.38 which conflicts with private transaction - var chainId int64 - chainId = 1 + var chainId int64 = 1 v0 := chainId*2 + 35 // sig[64] + 35 .. where sig[64] == 0 v1 := chainId*2 + 36 // sig[64] + 35 .. where sig[64] == 1 diff --git a/eth/config_test.go b/eth/config_test.go index b509e567d..b50ae1b25 100644 --- a/eth/config_test.go +++ b/eth/config_test.go @@ -1,8 +1,9 @@ package eth import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestQuorumDefautConfig(t *testing.T) { diff --git a/eth/handler_test.go b/eth/handler_test.go index 73ece3263..21f261394 100644 --- a/eth/handler_test.go +++ b/eth/handler_test.go @@ -254,10 +254,10 @@ func testGetBlockBodies(t *testing.T, protocol int) { available []bool // Availability of explicitly requested blocks expected int // Total number of existing blocks to expect }{ - {1, nil, nil, 1}, // A single random block should be retrievable - {10, nil, nil, 10}, // Multiple random blocks should be retrievable - {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable - {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned + {1, nil, nil, 1}, // A single random block should be retrievable + {10, nil, nil, 10}, // Multiple random blocks should be retrievable + {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable + {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable {0, []common.Hash{{}}, []bool{false}, 0}, // A non existent block should not be returned diff --git a/eth/protocol.go b/eth/protocol.go index c8768dfe5..48259980a 100644 --- a/eth/protocol.go +++ b/eth/protocol.go @@ -42,7 +42,7 @@ var protocolName = "eth" var ProtocolVersions = []uint{eth64, eth63} // protocolLengths are the number of implemented message corresponding to different protocol versions. -var protocolLengths = map[uint]uint64{eth64: 17, eth63: 17} +// var protocolLengths = map[uint]uint64{eth64: 17, eth63: 17} const protocolMaxMsgSize = 10 * 1024 * 1024 // Maximum cap on the size of a protocol message diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 05488a9d0..18c2c02a2 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1618,8 +1618,7 @@ func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args Sen // /Quorum // Assemble the transaction and sign with the wallet - var tx *types.Transaction - tx = args.toTransaction() + tx := args.toTransaction() if args.IsPrivate() { tx.SetPrivate() @@ -1688,7 +1687,7 @@ func (s *PublicTransactionPoolAPI) SendRawPrivateTransaction(ctx context.Context return common.Hash{}, err } - txHash := []byte(tx.Data()) + txHash := tx.Data() isPrivate := (args.PrivateFor != nil) && tx.IsPrivate() if isPrivate { @@ -1756,7 +1755,7 @@ func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args Sen // set gas to constant if nil if args.IsPrivate() && args.Gas == nil { gas := (hexutil.Uint64)(90000) - args.Gas = (*hexutil.Uint64)(&gas) + args.Gas = &gas } // /Quorum if err := args.setDefaults(ctx, s.b); err != nil { @@ -1817,7 +1816,7 @@ func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxAr // set gas to constant if nil if sendArgs.IsPrivate() && sendArgs.Gas == nil { gas := (hexutil.Uint64)(90000) - sendArgs.Gas = (*hexutil.Uint64)(&gas) + sendArgs.Gas = &gas } if err := sendArgs.setDefaults(ctx, s.b); err != nil { return common.Hash{}, err diff --git a/node/config.go b/node/config.go index 1c2eab695..9e4afb146 100644 --- a/node/config.go +++ b/node/config.go @@ -193,7 +193,7 @@ type Config struct { staticNodesWarning bool trustedNodesWarning bool oldGethResourceWarning bool - Plugins *plugin.Settings `toml:",omitempty"` + Plugins *plugin.Settings `toml:",omitempty"` // Quorum: EnableNodePermission comes from EnableNodePermissionFlag --permissioned. EnableNodePermission bool `toml:",omitempty"` } diff --git a/node/service.go b/node/service.go index 28825c44b..19b27a60c 100644 --- a/node/service.go +++ b/node/service.go @@ -17,8 +17,8 @@ package node import ( - "path/filepath" "crypto/ecdsa" + "path/filepath" "reflect" "github.com/ethereum/go-ethereum/accounts" diff --git a/p2p/enode/urlv4.go b/p2p/enode/urlv4.go index 9b5b674f1..daadb034c 100644 --- a/p2p/enode/urlv4.go +++ b/p2p/enode/urlv4.go @@ -110,7 +110,6 @@ func isNewV4(n *Node) bool { return n.r.IdentityScheme() == "" && n.r.Load(&k) == nil && len(n.r.Signature()) == 0 } - // Quorum // NewV4Hostname creates a node from discovery v4 node information. The record diff --git a/p2p/permissions.go b/p2p/permissions.go index 334310b8e..58b21d709 100644 --- a/p2p/permissions.go +++ b/p2p/permissions.go @@ -30,10 +30,7 @@ func isNodePermissioned(nodename string, currentNode string, datadir string, dir if v == nodename { log.Debug("isNodePermissioned", "connection", direction, "nodename", nodename[:NODE_NAME_LENGTH], "ALLOWED-BY", currentNode[:NODE_NAME_LENGTH]) // check if the node is blacklisted - if isNodeBlackListed(nodename, datadir) { - return false - } - return true + return !isNodeBlackListed(nodename, datadir) } } log.Debug("isNodePermissioned", "connection", direction, "nodename", nodename[:NODE_NAME_LENGTH], "DENIED-BY", currentNode[:NODE_NAME_LENGTH]) diff --git a/params/config_test.go b/params/config_test.go index 5f3189b34..8ebd08d77 100644 --- a/params/config_test.go +++ b/params/config_test.go @@ -98,7 +98,6 @@ func TestCheckCompatible(t *testing.T) { rec2 := MaxCodeConfigStruct{big.NewInt(10), 40} rec3 := MaxCodeConfigStruct{big.NewInt(8), 40} - storedMaxCodeConfig0 = append(storedMaxCodeConfig0, defaultRec) storedMaxCodeConfig1 = append(storedMaxCodeConfig1, defaultRec) @@ -274,7 +273,7 @@ func TestCheckCompatible(t *testing.T) { wantErr: nil, }, { - stored: &ChainConfig{MaxCodeSize: 32, MaxCodeSizeChangeBlock:big.NewInt(10)}, + stored: &ChainConfig{MaxCodeSize: 32, MaxCodeSizeChangeBlock: big.NewInt(10)}, new: &ChainConfig{MaxCodeSizeConfig: storedMaxCodeConfig1}, head: 15, wantErr: nil, diff --git a/params/protocol_params_test.go b/params/protocol_params_test.go index ad175d075..104a00231 100644 --- a/params/protocol_params_test.go +++ b/params/protocol_params_test.go @@ -1,8 +1,9 @@ package params import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) //Quorum - test key constant values modified by Quorum diff --git a/params/quorum.go b/params/quorum.go index aae309c54..7d060d4f1 100644 --- a/params/quorum.go +++ b/params/quorum.go @@ -1,7 +1,7 @@ package params const ( - PERMISSIONED_CONFIG = "permissioned-nodes.json" - BLACKLIST_CONFIG = "disallowed-nodes.json" + PERMISSIONED_CONFIG = "permissioned-nodes.json" + BLACKLIST_CONFIG = "disallowed-nodes.json" PERMISSION_MODEL_CONFIG = "permission-config.json" ) diff --git a/permission/api.go b/permission/api.go index 87c6598e9..486b365be 100644 --- a/permission/api.go +++ b/permission/api.go @@ -643,8 +643,7 @@ func (q *QuorumControlsAPI) valNodeStatusChange(orgId, url string, op NodeUpdate } func (q *QuorumControlsAPI) validateRole(orgId, roleId string) bool { - var r *types.RoleInfo - r = types.RoleInfoMap.GetRole(orgId, roleId) + r := types.RoleInfoMap.GetRole(orgId, roleId) if r == nil { r = types.RoleInfoMap.GetRole(types.OrgInfoMap.GetOrg(orgId).UltimateParent, roleId) } diff --git a/permission/permission.go b/permission/permission.go index 5ba24cdb4..7b65ddfa1 100644 --- a/permission/permission.go +++ b/permission/permission.go @@ -4,7 +4,6 @@ import ( "crypto/ecdsa" "encoding/json" "fmt" - "github.com/ethereum/go-ethereum/core" "io/ioutil" "math/big" "os" @@ -13,22 +12,20 @@ import ( "sync" "time" - "github.com/ethereum/go-ethereum/ethclient" - - "github.com/ethereum/go-ethereum/event" - - "github.com/ethereum/go-ethereum/raft" - "github.com/ethereum/go-ethereum/rpc" - "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/params" pbind "github.com/ethereum/go-ethereum/permission/bind" + "github.com/ethereum/go-ethereum/raft" + "github.com/ethereum/go-ethereum/rpc" ) type NodeOperation uint8 @@ -52,7 +49,7 @@ type PermissionCtrl struct { permOrg *pbind.OrgManager permConfig *types.PermissionConfig - startWaitGroup *sync.WaitGroup // waitgroup to make sure all dependenies are ready before we start the service + startWaitGroup *sync.WaitGroup // waitgroup to make sure all dependencies are ready before we start the service stopFeed event.Feed // broadcasting stopEvent when service is being stopped errorChan chan error // channel to capture error when starting aysnc @@ -296,7 +293,7 @@ func (p *PermissionCtrl) monitorQIP714Block() error { defer stopSubscription.Unsubscribe() for { select { - case head := <-chainHeadCh: + case head := <-chainHeadCh: if p.eth.BlockChain().Config().IsQIP714(head.Block.Number()) { types.SetDefaultAccess() return diff --git a/permission/permission_test.go b/permission/permission_test.go index 355f23298..3934e9e06 100644 --- a/permission/permission_test.go +++ b/permission/permission_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/ethereum/go-ethereum/miner" "io/ioutil" "log" "math/big" @@ -13,27 +12,22 @@ import ( "testing" "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/internal/ethapi" - - "github.com/ethereum/go-ethereum/core/types" - - "github.com/ethereum/go-ethereum/params" - - "github.com/ethereum/go-ethereum/p2p" - - "github.com/ethereum/go-ethereum/consensus/ethash" - "github.com/ethereum/go-ethereum/eth" - - "github.com/stretchr/testify/assert" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" + "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/consensus/ethash" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/eth" + "github.com/ethereum/go-ethereum/internal/ethapi" + "github.com/ethereum/go-ethereum/miner" "github.com/ethereum/go-ethereum/node" + "github.com/ethereum/go-ethereum/p2p" + "github.com/ethereum/go-ethereum/params" pbind "github.com/ethereum/go-ethereum/permission/bind" + "github.com/stretchr/testify/assert" ) const ( @@ -111,8 +105,8 @@ func setup() { }, } ethConf := ð.Config{ - Genesis: &core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: 10000000000, Alloc: genesisAlloc}, - Miner: miner.Config{Etherbase: guardianAddress}, + Genesis: &core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: 10000000000, Alloc: genesisAlloc}, + Miner: miner.Config{Etherbase: guardianAddress}, Ethash: ethash.Config{ PowMode: ethash.ModeTest, }, @@ -273,7 +267,6 @@ func TestQuorumControlsAPI_OrgAPIs(t *testing.T) { testObject := typicalQuorumControlsAPI(t) invalidTxa := ethapi.SendTxArgs{From: getArbitraryAccount()} - // test AddOrg orgAdminKey, _ := crypto.GenerateKey() orgAdminAddress := crypto.PubkeyToAddress(orgAdminKey.PublicKey) diff --git a/plugin/central.go b/plugin/central.go index 65e41f7bb..f87667970 100644 --- a/plugin/central.go +++ b/plugin/central.go @@ -44,7 +44,7 @@ func (cc *CentralClient) getNewSecureDialer() Dialer { if cc.config.CertFingerprint != "" { conState := c.ConnectionState() for _, peercert := range conState.PeerCertificates { - if bytes.Compare(peercert.Signature[0:], []byte(cc.config.CertFingerprint)) == 0 { + if bytes.Equal(peercert.Signature[0:], []byte(cc.config.CertFingerprint)) { return c, nil } } @@ -100,10 +100,8 @@ func (cc *CentralClient) PluginDistribution(definition *PluginDefinition, outFil defer func() { _ = readCloser.Close() }() - if _, err := io.Copy(outFile, readCloser); err != nil { - return err - } - return nil + _, err = io.Copy(outFile, readCloser) + return err } // perform HTTP GET diff --git a/plugin/initializer/gateway.go b/plugin/initializer/gateway.go index 542fbb10b..ddd42bcbb 100644 --- a/plugin/initializer/gateway.go +++ b/plugin/initializer/gateway.go @@ -15,8 +15,5 @@ func (g *PluginGateway) Init(ctx context.Context, nodeIdentity string, rawConfig HostIdentity: nodeIdentity, RawConfiguration: rawConfiguration, }) - if err != nil { - return err - } - return nil + return err } diff --git a/plugin/utils.go b/plugin/utils.go index 443ba7d5c..10ec52a22 100644 --- a/plugin/utils.go +++ b/plugin/utils.go @@ -56,10 +56,8 @@ func unzipFile(output string, input *zip.File) error { defer func() { _ = outputFile.Close() }() - if _, err = io.Copy(outputFile, inputFile); err != nil { - return err - } - return nil + _, err = io.Copy(outputFile, inputFile) + return err } // Unzip src path to dest. Creates dest if the file doesnt exists. @@ -109,7 +107,7 @@ func getSha256Checksum(filePath string) (string, error) { func unpackPlugin(pluginPath string) (string, *MetaData, error) { // Unpack pluginMeta // Reduce TOC/TOU risk - unpackDir := path.Join(os.TempDir(), string(uuid.New()), string(uuid.New())) + unpackDir := path.Join(os.TempDir(), uuid.New(), uuid.New()) err := os.MkdirAll(unpackDir, os.ModePerm) if err != nil { @@ -139,7 +137,7 @@ func unpackPlugin(pluginPath string) (string, *MetaData, error) { return unpackDir, nil, fmt.Errorf("plugin-meta.json entry point not set") } - if isCleanEntryPoint(pluginMeta.EntryPoint) == false { + if !isCleanEntryPoint(pluginMeta.EntryPoint) { return unpackDir, nil, fmt.Errorf("entrypoint must be only alphanumeric value") } return unpackDir, &pluginMeta, nil diff --git a/raft/api.go b/raft/api.go index c03520248..f0641110b 100755 --- a/raft/api.go +++ b/raft/api.go @@ -2,6 +2,7 @@ package raft import ( "errors" + "github.com/coreos/etcd/pkg/types" ) @@ -124,11 +125,8 @@ func (s *PublicRaftAPI) checkIfNodeIsActive(raftId uint16) bool { if raftId == s.raftService.raftProtocolManager.raftId { return true } - activeSince := s.raftService.raftProtocolManager.transport.ActiveSince(types.ID(raftId)) - if activeSince.IsZero() { - return false - } - return true + activeSince := s.raftService.raftProtocolManager.transport.ActiveSince(types.ID(raftId)) + return !activeSince.IsZero() } func (s *PublicRaftAPI) GetRaftId(enodeId string) (uint16, error) { diff --git a/raft/constants.go b/raft/constants.go index 2057909b1..012df25d1 100644 --- a/raft/constants.go +++ b/raft/constants.go @@ -5,19 +5,19 @@ import ( ) const ( - protocolName = "raft" - protocolVersion uint64 = 0x01 + //protocolName = "raft" + //protocolVersion uint64 = 0x01 - raftMsg = 0x00 + //raftMsg = 0x00 - minterRole = etcdRaft.LEADER - verifierRole = etcdRaft.NOT_LEADER + minterRole = etcdRaft.LEADER + //verifierRole = etcdRaft.NOT_LEADER // Raft's ticker interval tickerMS = 100 // We use a bounded channel of constant size buffering incoming messages - msgChanSize = 1000 + //msgChanSize = 1000 // Snapshot after this many raft messages // @@ -25,7 +25,7 @@ const ( // snapshotPeriod = 250 - peerUrlKeyPrefix = "peerUrl-" + //peerUrlKeyPrefix = "peerUrl-" chainExtensionMessage = "Successfully extended chain" ) diff --git a/raft/handler_test.go b/raft/handler_test.go index 433fba32a..b6bd5a182 100644 --- a/raft/handler_test.go +++ b/raft/handler_test.go @@ -118,10 +118,7 @@ func writeAppliedIndex(workingDir string, node int, index uint64) error { }() buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, index) - if err := db.Put(appliedDbKey, buf, noFsync); err != nil { - return err - } - return nil + return db.Put(appliedDbKey, buf, noFsync) } func mustNewNodeKey(t *testing.T) *ecdsa.PrivateKey { diff --git a/raft/minter.go b/raft/minter.go index 0658cda36..573379c60 100644 --- a/raft/minter.go +++ b/raft/minter.go @@ -429,8 +429,7 @@ func (minter *minter) buildExtraSeal(headerHash common.Hash) []byte { //build the extraSeal struct raftIdString := hexutil.EncodeUint64(uint64(minter.eth.raftProtocolManager.raftId)) - var extra extraSeal - extra = extraSeal{ + extra := extraSeal{ RaftId: []byte(raftIdString[2:]), //remove the 0x prefix Signature: sig, } diff --git a/raft/minter_test.go b/raft/minter_test.go index 4ec241265..f7629b50b 100644 --- a/raft/minter_test.go +++ b/raft/minter_test.go @@ -1,7 +1,6 @@ package raft import ( - "errors" "fmt" "math/big" "strings" @@ -9,14 +8,13 @@ import ( "time" "github.com/coreos/etcd/raft/raftpb" - "github.com/deckarep/golang-set" - "github.com/ethereum/go-ethereum/p2p/enode" - + mapset "github.com/deckarep/golang-set" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/node" + "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rlp" ) @@ -100,7 +98,7 @@ func TestAddLearner_whenTypical(t *testing.T) { t.Errorf("2. wrong raft id. expected %d got %d\n", raftService.raftProtocolManager.raftId+1, uint16(confChange.NodeID)) } case <-time.After(time.Millisecond * 200): - t.Errorf("add learner conf change not recieved") + t.Errorf("add learner conf change not received") } } @@ -123,7 +121,7 @@ func TestPromoteLearnerToPeer_whenTypical(t *testing.T) { t.Errorf("2. wrong raft id. expected %d got %d\n", learnerRaftId, uint16(confChange.NodeID)) } case <-time.After(time.Millisecond * 200): - t.Errorf("add learner conf change not recieved") + t.Errorf("add learner conf change not received") } } @@ -137,7 +135,7 @@ func TestAddLearnerOrPeer_fromLearner(t *testing.T) { t.Errorf("learner should not be allowed to add learner or peer") } - if err != nil && strings.Index(err.Error(), "learner node can't add peer or learner") == -1 { + if err != nil && !strings.Contains(err.Error(), "learner node can't add peer or learner") { t.Errorf("expect error message: propose new peer failed, got: %v\n", err) } @@ -147,7 +145,7 @@ func TestAddLearnerOrPeer_fromLearner(t *testing.T) { t.Errorf("learner should not be allowed to add learner or peer") } - if err != nil && strings.Index(err.Error(), "learner node can't add peer or learner") == -1 { + if err != nil && !strings.Contains(err.Error(), "learner node can't add peer or learner") { t.Errorf("expect error message: propose new peer failed, got: %v\n", err) } @@ -163,7 +161,7 @@ func TestPromoteLearnerToPeer_fromLearner(t *testing.T) { t.Errorf("learner should not be allowed to promote to peer") } - if err != nil && strings.Index(err.Error(), "learner node can't promote to peer") == -1 { + if err != nil && !strings.Contains(err.Error(), "learner node can't promote to peer") { t.Errorf("expect error message: propose new peer failed, got: %v\n", err) } @@ -177,7 +175,7 @@ func peerList(url string) (error, []*enode.Node) { var nodes []*enode.Node node, err := enode.ParseV4(url) if err != nil { - return errors.New(fmt.Sprintf("Node URL %s: %v\n", url, err)), nil + return fmt.Errorf("Node URL %s: %v\n", url, err), nil } nodes = append(nodes, node) return nil, nodes diff --git a/rpc/inproc.go b/rpc/inproc.go index 76a8690af..496e5be31 100644 --- a/rpc/inproc.go +++ b/rpc/inproc.go @@ -22,7 +22,6 @@ import ( ) type InProcServerReadyEvent struct { - } // DialInProc attaches an in-process connection to the given RPC server.