Skip to content

Commit

Permalink
Introduce test cases for istanbul BFT
Browse files Browse the repository at this point in the history
  • Loading branch information
Aidan authored and KimKyungup committed Apr 27, 2020
1 parent 7963873 commit b223055
Show file tree
Hide file tree
Showing 2 changed files with 728 additions and 5 deletions.
226 changes: 221 additions & 5 deletions consensus/istanbul/backend/backend_test.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
// Copyright 2019 The klaytn Authors
// This file is part of the klaytn library.
// Modifications Copyright 2020 The klaytn Authors
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The klaytn library is free software: you can redistribute it and/or modify
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The klaytn library is distributed in the hope that it will be useful,
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the klaytn library. If not, see <http://www.gnu.org/licenses/>.
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
//
// This file is derived from quorum/consensus/istanbul/backend/backend_test.go (2020/04/16).
// Modified and improved for the klaytn development.

package backend

import (
"bytes"
"crypto/ecdsa"
"fmt"
"github.com/hashicorp/golang-lru"
"github.com/klaytn/klaytn/blockchain/types"
Expand All @@ -31,10 +37,14 @@ import (
"github.com/klaytn/klaytn/reward"
"github.com/klaytn/klaytn/storage/database"
"math/big"
"sort"
"strings"
"testing"
"time"
)

var (
testSigningData = []byte("dummy data")
// testing node's private key
PRIVKEY = "ce7671a2880493dfb8d04218707a16b1532dfcac97f0289d770a919d5ff7b068"
// Max blockNum
Expand Down Expand Up @@ -434,6 +444,20 @@ var (
}
)

type keys []*ecdsa.PrivateKey

func (slice keys) Len() int {
return len(slice)
}

func (slice keys) Less(i, j int) bool {
return strings.Compare(crypto.PubkeyToAddress(slice[i].PublicKey).String(), crypto.PubkeyToAddress(slice[j].PublicKey).String()) < 0
}

func (slice keys) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}

type Pair struct {
Sequence int64
Round int64
Expand Down Expand Up @@ -838,3 +862,195 @@ func checkInCommitteeBlocks(seq int64, round int64) bool {
}
return false
}

func newTestBackend() (b *backend) {
dbm := database.NewDBManager(&database.DBConfig{DBType: database.MemoryDB})
key, _ := crypto.GenerateKey()
istanbul.DefaultConfig.ProposerPolicy = istanbul.WeightedRandom

backend := New(getTestRewards()[0], istanbul.DefaultConfig, key, dbm, getGovernance(dbm), common.CONSENSUSNODE).(*backend)
return backend
}

func newTestValidatorSet(n int, policy istanbul.ProposerPolicy) (istanbul.ValidatorSet, []*ecdsa.PrivateKey) {
// generate validators
keys := make(keys, n)
addrs := make([]common.Address, n)
for i := 0; i < n; i++ {
privateKey, _ := crypto.GenerateKey()
keys[i] = privateKey
addrs[i] = crypto.PubkeyToAddress(privateKey.PublicKey)
}
vset := validator.NewSet(addrs, policy)
sort.Sort(keys) //Keys need to be sorted by its public key address
return vset, keys
}

func TestSign(t *testing.T) {
b := newTestBackend()

sig, err := b.Sign(testSigningData)
if err != nil {
t.Errorf("error mismatch: have %v, want nil", err)
}

//Check signature recover
hashData := crypto.Keccak256([]byte(testSigningData))
pubkey, _ := crypto.Ecrecover(hashData, sig)
actualSigner := common.BytesToAddress(crypto.Keccak256(pubkey[1:])[12:])

if actualSigner != b.address {
t.Errorf("address mismatch: have %v, want %s", actualSigner.Hex(), b.address.Hex())
}
}

func TestCheckSignature(t *testing.T) {
b := newTestBackend()

// testAddr is derived from testPrivateKey.
testPrivateKey, _ := crypto.HexToECDSA("bb047e5940b6d83354d9432db7c449ac8fca2248008aaa7271369880f9f11cc1")
testAddr := common.HexToAddress("0x70524d664ffe731100208a0154e556f9bb679ae6")
testInvalidAddr := common.HexToAddress("0x9535b2e7faaba5288511d89341d94a38063a349b")

hashData := crypto.Keccak256([]byte(testSigningData))
sig, err := crypto.Sign(hashData, testPrivateKey)
if err != nil {
t.Fatalf("unexpected failure: %v", err)
}

if err := b.CheckSignature(testSigningData, testAddr, sig); err != nil {
t.Errorf("error mismatch: have %v, want nil", err)
}

if err := b.CheckSignature(testSigningData, testInvalidAddr, sig); err != errInvalidSignature {
t.Errorf("error mismatch: have %v, want %v", err, errInvalidSignature)
}
}

func TestCheckValidatorSignature(t *testing.T) {
vset, keys := newTestValidatorSet(5, istanbul.WeightedRandom)

// 1. Positive test: sign with validator's key should succeed
hashData := crypto.Keccak256([]byte(testSigningData))
for i, k := range keys {
// Sign
sig, err := crypto.Sign(hashData, k)
if err != nil {
t.Errorf("error mismatch: have %v, want nil", err)
}
// CheckValidatorSignature should succeed
addr, err := istanbul.CheckValidatorSignature(vset, testSigningData, sig)
if err != nil {
t.Errorf("error mismatch: have %v, want nil", err)
}
validator := vset.GetByIndex(uint64(i))
if addr != validator.Address() {
t.Errorf("validator address mismatch: have %v, want %v", addr, validator.Address())
}
}

// 2. Negative test: sign with any key other than validator's key should return error
key, err := crypto.GenerateKey()
if err != nil {
t.Errorf("error mismatch: have %v, want nil", err)
}
// Sign
sig, err := crypto.Sign(hashData, key)
if err != nil {
t.Errorf("error mismatch: have %v, want nil", err)
}
// CheckValidatorSignature should return ErrUnauthorizedAddress
addr, err := istanbul.CheckValidatorSignature(vset, testSigningData, sig)
if err != istanbul.ErrUnauthorizedAddress {
t.Errorf("error mismatch: have %v, want %v", err, istanbul.ErrUnauthorizedAddress)
}
emptyAddr := common.Address{}
if addr != emptyAddr {
t.Errorf("address mismatch: have %v, want %v", addr, emptyAddr)
}
}

func TestCommit(t *testing.T) {
backend := newTestBackend()

commitCh := make(chan *types.Block)
// Case: it's a proposer, so the backend.commit will receive channel result from backend.Commit function
testCases := []struct {
expectedErr error
expectedSignature [][]byte
expectedBlock func() *types.Block
}{
{
// normal case
nil,
[][]byte{append([]byte{1}, bytes.Repeat([]byte{0x00}, types.IstanbulExtraSeal-1)...)},
func() *types.Block {
chain, engine := newBlockChain(1)
defer engine.Stop()

block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
expectedBlock, _ := engine.updateBlock(engine.chain.GetHeader(block.ParentHash(), block.NumberU64()-1), block)
return expectedBlock
},
},
{
// invalid signature
errInvalidCommittedSeals,
nil,
func() *types.Block {
chain, engine := newBlockChain(1)
defer engine.Stop()

block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
expectedBlock, _ := engine.updateBlock(engine.chain.GetHeader(block.ParentHash(), block.NumberU64()-1), block)
return expectedBlock
},
},
}

for _, test := range testCases {
expBlock := test.expectedBlock()
go func() {
select {
case result := <-backend.commitCh:
commitCh <- result.Block
return
}
}()

backend.proposedBlockHash = expBlock.Hash()
if err := backend.Commit(expBlock, test.expectedSignature); err != nil {
if err != test.expectedErr {
t.Errorf("error mismatch: have %v, want %v", err, test.expectedErr)
}
}

if test.expectedErr == nil {
// to avoid race condition is occurred by goroutine
select {
case result := <-commitCh:
if result.Hash() != expBlock.Hash() {
t.Errorf("hash mismatch: have %v, want %v", result.Hash(), expBlock.Hash())
}
case <-time.After(10 * time.Second):
t.Fatal("timeout")
}
}
}
}

func TestGetProposer(t *testing.T) {
chain, engine := newBlockChain(1)
defer engine.Stop()

block := makeBlock(chain, engine, chain.Genesis())
_, err := chain.InsertChain(types.Blocks{block})
if err != nil {
t.Errorf("failed to insert chain: %v", err)
}
expected := engine.GetProposer(1)
actual := engine.Address()
if actual != expected {
t.Errorf("proposer mismatch: have %v, want %v", actual.Hex(), expected.Hex())
}
}
Loading

0 comments on commit b223055

Please sign in to comment.