github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/consensus/raft/raft_test.go (about)

     1  package raft
     2  
     3  import (
     4  	"math/big"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/bigzoro/my_simplechain/common"
     9  	"github.com/bigzoro/my_simplechain/common/hexutil"
    10  	"github.com/bigzoro/my_simplechain/core/types"
    11  	"github.com/bigzoro/my_simplechain/crypto"
    12  	"github.com/bigzoro/my_simplechain/node"
    13  	"github.com/bigzoro/my_simplechain/rlp"
    14  )
    15  
    16  func TestSignHeader(t *testing.T) {
    17  	//create only what we need to test the seal
    18  	var testRaftId uint16 = 5
    19  	config := &node.Config{Name: "unit-test", DataDir: ""}
    20  
    21  	nodeKey := config.NodeKey()
    22  
    23  	//create some fake header to sign
    24  	fakeParentHash := common.HexToHash("0xc2c1dc1be8054808c69e06137429899d")
    25  
    26  	header := &types.Header{
    27  		ParentHash: fakeParentHash,
    28  		Number:     big.NewInt(1),
    29  		Difficulty: big.NewInt(1),
    30  		GasLimit:   uint64(0),
    31  		GasUsed:    uint64(0),
    32  		Time:       uint64(time.Now().UnixNano()),
    33  	}
    34  
    35  	engine := New(nodeKey)
    36  	engine.SetId(testRaftId)
    37  
    38  	headerHash := header.Hash()
    39  	extraDataBytes := engine.buildExtraSeal(headerHash)
    40  	var seal *ExtraSeal
    41  	err := rlp.DecodeBytes(extraDataBytes[:], &seal)
    42  	if err != nil {
    43  		t.Fatalf("Unable to decode seal: %s", err.Error())
    44  	}
    45  
    46  	// Check raftId
    47  	sealRaftId, err := hexutil.DecodeUint64("0x" + string(seal.RaftId)) //add the 0x prefix
    48  	if err != nil {
    49  		t.Errorf("Unable to get RaftId: %s", err.Error())
    50  	}
    51  	if sealRaftId != uint64(testRaftId) {
    52  		t.Errorf("RaftID does not match. Expected: %d, Actual: %d", testRaftId, sealRaftId)
    53  	}
    54  
    55  	//Identify who signed it
    56  	sig := seal.Signature
    57  	pubKey, err := crypto.SigToPub(headerHash.Bytes(), sig)
    58  	if err != nil {
    59  		t.Fatalf("Unable to get public key from signature: %s", err.Error())
    60  	}
    61  
    62  	//Compare derived public key to original public key
    63  	if pubKey.X.Cmp(nodeKey.X) != 0 {
    64  		t.Errorf("Signature incorrect!")
    65  	}
    66  
    67  }