github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/consensus/pbft/backend/backend_test.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package backend
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/ecdsa"
    22  	"sort"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/bigzoro/my_simplechain/common"
    28  	"github.com/bigzoro/my_simplechain/consensus/pbft"
    29  	"github.com/bigzoro/my_simplechain/consensus/pbft/validator"
    30  	"github.com/bigzoro/my_simplechain/core/types"
    31  	"github.com/bigzoro/my_simplechain/crypto"
    32  )
    33  
    34  func TestSign(t *testing.T) {
    35  	b := newBackend()
    36  	data := []byte("Here is a string....")
    37  	sig, err := b.Sign(data)
    38  	if err != nil {
    39  		t.Errorf("error mismatch: have %v, want nil", err)
    40  	}
    41  	//Check signature recover
    42  	hashData := crypto.Keccak256(data)
    43  	pubkey, _ := crypto.Ecrecover(hashData, sig)
    44  	var signer common.Address
    45  	copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
    46  	if signer != getAddress() {
    47  		t.Errorf("address mismatch: have %v, want %s", signer.Hex(), getAddress().Hex())
    48  	}
    49  }
    50  
    51  func TestCheckSignature(t *testing.T) {
    52  	key, _ := generatePrivateKey()
    53  	data := []byte("Here is a string....")
    54  	hashData := crypto.Keccak256(data)
    55  	sig, _ := crypto.Sign(hashData, key)
    56  	b := newBackend()
    57  	a := getAddress()
    58  	err := b.CheckSignature(data, a, sig)
    59  	if err != nil {
    60  		t.Errorf("error mismatch: have %v, want nil", err)
    61  	}
    62  	a = getInvalidAddress()
    63  	err = b.CheckSignature(data, a, sig)
    64  	if err != errInvalidSignature {
    65  		t.Errorf("error mismatch: have %v, want %v", err, errInvalidSignature)
    66  	}
    67  }
    68  
    69  func TestCheckValidatorSignature(t *testing.T) {
    70  	vset, keys := newTestValidatorSet(5)
    71  
    72  	// 1. Positive test: sign with validator's key should succeed
    73  	data := []byte("dummy data")
    74  	hashData := crypto.Keccak256(data)
    75  	for i, k := range keys {
    76  		// Sign
    77  		sig, err := crypto.Sign(hashData, k)
    78  		if err != nil {
    79  			t.Errorf("error mismatch: have %v, want nil", err)
    80  		}
    81  		// CheckValidatorSignature should succeed
    82  		addr, err := pbft.CheckValidatorSignature(vset, data, sig)
    83  		if err != nil {
    84  			t.Errorf("error mismatch: have %v, want nil", err)
    85  		}
    86  		validator := vset.GetByIndex(uint64(i))
    87  		if addr != validator.Address() {
    88  			t.Errorf("validator address mismatch: have %v, want %v", addr, validator.Address())
    89  		}
    90  	}
    91  
    92  	// 2. Negative test: sign with any key other than validator's key should return error
    93  	key, err := crypto.GenerateKey()
    94  	if err != nil {
    95  		t.Errorf("error mismatch: have %v, want nil", err)
    96  	}
    97  	// Sign
    98  	sig, err := crypto.Sign(hashData, key)
    99  	if err != nil {
   100  		t.Errorf("error mismatch: have %v, want nil", err)
   101  	}
   102  
   103  	// CheckValidatorSignature should return ErrUnauthorizedAddress
   104  	addr, err := pbft.CheckValidatorSignature(vset, data, sig)
   105  	if err != pbft.ErrUnauthorizedAddress {
   106  		t.Errorf("error mismatch: have %v, want %v", err, pbft.ErrUnauthorizedAddress)
   107  	}
   108  	emptyAddr := common.Address{}
   109  	if addr != emptyAddr {
   110  		t.Errorf("address mismatch: have %v, want %v", addr, emptyAddr)
   111  	}
   112  }
   113  
   114  func TestCommit(t *testing.T) {
   115  	backend := newBackend()
   116  	commitCh := make(chan *types.Block)
   117  	// Case: it's a proposer, so the backend.commit will receive channel result from backend.Commit function
   118  	testCases := []struct {
   119  		expectedErr       error
   120  		expectedSignature [][]byte
   121  		expectedBlock     func() *types.Block
   122  	}{
   123  		{
   124  			// normal case
   125  			nil,
   126  			[][]byte{append([]byte{1}, bytes.Repeat([]byte{0x00}, types.ByzantineExtraSeal-1)...)},
   127  			func() *types.Block {
   128  				chain, engine := newBlockChain(1)
   129  				block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
   130  				expectedBlock, _ := engine.signBlock(engine.chain.GetHeader(block.ParentHash(), block.NumberU64()-1), block)
   131  				return expectedBlock
   132  			},
   133  		},
   134  		{
   135  			// invalid signature
   136  			errInvalidCommittedSeals,
   137  			nil,
   138  			func() *types.Block {
   139  				chain, engine := newBlockChain(1)
   140  				block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
   141  				expectedBlock, _ := engine.signBlock(engine.chain.GetHeader(block.ParentHash(), block.NumberU64()-1), block)
   142  				return expectedBlock
   143  			},
   144  		},
   145  	}
   146  
   147  	for _, test := range testCases {
   148  		expBlock := test.expectedBlock()
   149  		go func() {
   150  			commitCh <- <-backend.commitCh
   151  		}()
   152  
   153  		backend.proposedBlockHash = expBlock.PendingHash()
   154  		if err := backend.Commit(expBlock, test.expectedSignature); err != nil {
   155  			if err != test.expectedErr {
   156  				t.Errorf("error mismatch: have %v, want %v", err, test.expectedErr)
   157  			}
   158  		}
   159  
   160  		if test.expectedErr == nil {
   161  			// to avoid race condition is occurred by goroutine
   162  			select {
   163  			case result := <-commitCh:
   164  				if result.Hash() != expBlock.Hash() {
   165  					t.Errorf("hash mismatch: have %v, want %v", result.Hash(), expBlock.Hash())
   166  				}
   167  			case <-time.After(10 * time.Second):
   168  				t.Fatal("timeout")
   169  			}
   170  		}
   171  	}
   172  }
   173  
   174  func TestGetProposer(t *testing.T) {
   175  	chain, engine := newBlockChain(1)
   176  
   177  	block := makeBlock(chain, engine, chain.Genesis())
   178  	chain.InsertChain(types.Blocks{block})
   179  	expected := engine.GetProposer(1)
   180  	actual := engine.Address()
   181  	if actual != expected {
   182  		t.Errorf("proposer mismatch: have %v, want %v", actual.Hex(), expected.Hex())
   183  	}
   184  }
   185  
   186  /**
   187   * SimpleBackend
   188   * Private key: bb047e5940b6d83354d9432db7c449ac8fca2248008aaa7271369880f9f11cc1
   189   * Public key: 04a2bfb0f7da9e1b9c0c64e14f87e8fb82eb0144e97c25fe3a977a921041a50976984d18257d2495e7bfd3d4b280220217f429287d25ecdf2b0d7c0f7aae9aa624
   190   * Address: 0x70524d664ffe731100208a0154e556f9bb679ae6
   191   */
   192  func getAddress() common.Address {
   193  	return common.HexToAddress("0x70524d664ffe731100208a0154e556f9bb679ae6")
   194  }
   195  
   196  func getInvalidAddress() common.Address {
   197  	return common.HexToAddress("0x9535b2e7faaba5288511d89341d94a38063a349b")
   198  }
   199  
   200  func generatePrivateKey() (*ecdsa.PrivateKey, error) {
   201  	key := "bb047e5940b6d83354d9432db7c449ac8fca2248008aaa7271369880f9f11cc1"
   202  	return crypto.HexToECDSA(key)
   203  }
   204  
   205  func newTestValidatorSet(n int) (pbft.ValidatorSet, []*ecdsa.PrivateKey) {
   206  	// generate validators
   207  	keys := make(Keys, n)
   208  	addrs := make([]common.Address, n)
   209  	for i := 0; i < n; i++ {
   210  		privateKey, _ := crypto.GenerateKey()
   211  		keys[i] = privateKey
   212  		addrs[i] = crypto.PubkeyToAddress(privateKey.PublicKey)
   213  	}
   214  	vset := validator.NewSet(addrs, pbft.RoundRobin)
   215  	sort.Sort(keys) //Keys need to be sorted by its public key address
   216  	return vset, keys
   217  }
   218  
   219  type Keys []*ecdsa.PrivateKey
   220  
   221  func (slice Keys) Len() int {
   222  	return len(slice)
   223  }
   224  
   225  func (slice Keys) Less(i, j int) bool {
   226  	return strings.Compare(crypto.PubkeyToAddress(slice[i].PublicKey).String(), crypto.PubkeyToAddress(slice[j].PublicKey).String()) < 0
   227  }
   228  
   229  func (slice Keys) Swap(i, j int) {
   230  	slice[i], slice[j] = slice[j], slice[i]
   231  }
   232  
   233  func newBackend() (b *backend) {
   234  	_, b = newBlockChain(4)
   235  	key, _ := generatePrivateKey()
   236  	b.privateKey = key
   237  	return
   238  }
   239  
   240  type testSealer struct {
   241  }
   242  
   243  func (testSealer) Execute(block *types.Block) (*types.Block, error) {
   244  	return block, nil
   245  }
   246  
   247  func (testSealer) OnTimeout()           {}
   248  func (testSealer) OnCommit(uint64, int) {}