fix linting issues (#995)

This commit is contained in:
Trung Nguyen 2020-05-11 16:15:27 -04:00 committed by GitHub
parent 2e9462ee20
commit 3034c75403
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
52 changed files with 160 additions and 202 deletions

View File

@ -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:

View File

@ -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)
}
}

View File

@ -244,4 +244,4 @@ func SetResetPrivateConfig(value string) func() {
return func() {
os.Setenv("PRIVATE_CONFIG", existingValue)
}
}
}

View File

@ -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")

View File

@ -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) {

View File

@ -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)
}

View File

@ -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()

View File

@ -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.

View File

@ -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!")
}
}

View File

@ -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 (

View File

@ -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{

View File

@ -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

View File

@ -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,
},

View File

@ -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,
},

View File

@ -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
}

View File

@ -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 {

View File

@ -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")
)

View File

@ -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)
}

View File

@ -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"

View File

@ -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
}
}

View File

@ -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 {

View File

@ -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() {

View File

@ -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 {

View File

@ -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

View File

@ -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"
)

View File

@ -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
}

View File

@ -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)
}

View File

@ -60,4 +60,3 @@ func TestQuorumSignPrivateQuorum(t *testing.T) {
}
}

View File

@ -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

View File

@ -1,8 +1,9 @@
package eth
import (
"github.com/stretchr/testify/assert"
"testing"
"github.com/stretchr/testify/assert"
)
func TestQuorumDefautConfig(t *testing.T) {

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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"`
}

View File

@ -17,8 +17,8 @@
package node
import (
"path/filepath"
"crypto/ecdsa"
"path/filepath"
"reflect"
"github.com/ethereum/go-ethereum/accounts"

View File

@ -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

View File

@ -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])

View File

@ -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,

View File

@ -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

View File

@ -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"
)

View File

@ -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)
}

View File

@ -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

View File

@ -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 := &eth.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)

View File

@ -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

View File

@ -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
}

View File

@ -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

View File

@ -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) {

View File

@ -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"
)

View File

@ -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 {

View File

@ -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,
}

View File

@ -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

View File

@ -22,7 +22,6 @@ import (
)
type InProcServerReadyEvent struct {
}
// DialInProc attaches an in-process connection to the given RPC server.