Skip to content

Commit

Permalink
Block hash without seal (#127)
Browse files Browse the repository at this point in the history
* Refactor system transactions

* Small error fix

* Refactor damn stuff

* Ensure system transactions will be not reverted

* Remove some quotes

* Fix test units

* Use seal hash as block hash for now
  • Loading branch information
devfans committed Oct 12, 2023
1 parent 812a849 commit 217249a
Show file tree
Hide file tree
Showing 16 changed files with 47 additions and 67 deletions.
42 changes: 4 additions & 38 deletions consensus/hotstuff/signer/signer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,14 @@
package signer

import (
"bytes"
"crypto/ecdsa"
"sort"
"strings"
"testing"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/consensus/hotstuff"
"github.com/ethereum/go-ethereum/consensus/hotstuff/validator"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/stretchr/testify/assert"
)
Expand All @@ -38,11 +35,11 @@ import (
func TestSign(t *testing.T) {
s := newTestSigner()
data := []byte("Here is a string....")
sig, err := s.Sign(data)
hashData := crypto.Keccak256(data)
sig, err := s.SignHash(common.BytesToHash(hashData))
assert.NoError(t, err, "error mismatch: have %v, want nil", err)

//Check signature recover
hashData := crypto.Keccak256(data)
pubkey, _ := crypto.Ecrecover(hashData, sig)
var signer common.Address
copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
Expand All @@ -63,7 +60,7 @@ func TestCheckValidatorSignature(t *testing.T) {

// CheckValidatorSignature should succeed
signer := NewSigner(k)
addr, err := signer.CheckSignature(vset, data, sig)
addr, err := signer.CheckSignature(vset, common.BytesToHash(hashData), sig)
assert.NoError(t, err, "error mismatch: have %v, want nil", err)

val := vset.GetByIndex(uint64(i))
Expand All @@ -80,44 +77,13 @@ func TestCheckValidatorSignature(t *testing.T) {

// CheckValidatorSignature should return ErrUnauthorizedAddress
signer := NewSigner(key)
addr, err := signer.CheckSignature(vset, data, sig)
addr, err := signer.CheckSignature(vset, common.BytesToHash(hashData), sig)
assert.Equal(t, err, ErrUnauthorizedAddress, "error mismatch: have %v, want %v", err, ErrUnauthorizedAddress)

emptyAddr := common.Address{}
assert.Equal(t, emptyAddr, common.Address{}, "address mismatch: have %v, want %v", addr, emptyAddr)
}

// go test -v github.com/ethereum/go-ethereum/consensus/hotstuff/signer -run TestFillExtraAfterCommit
func TestFillExtraAfterCommit(t *testing.T) {
istRawData := hexutil.MustDecode("0x0000000000000000000000000000000000000000000000000000000000000000f89d801ef85494258af48e28e4a6846e931ddff8e1cdf8579821e5946a708455c8777630aac9d1e7702d13f7a865b27c948c09d936a1b408d6e0afaa537ba4e06c4504a0ae94ad3bf5ed640cc72f37bd21d64a65c3c756e9c88cb8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c080")
extra, _ := types.ExtractHotstuffExtraPayload(istRawData)

expectedCommittedSeal := append([]byte{1, 2, 3}, bytes.Repeat([]byte{0x00}, types.HotstuffExtraSeal-3)...)
expectedIstExtra := &types.HotstuffExtra{
StartHeight: 0,
EndHeight: 30,
Validators: extra.Validators,
Seal: extra.Seal,
CommittedSeal: [][]byte{expectedCommittedSeal},
Salt: extra.Salt,
}
h := &types.Header{
Extra: istRawData,
}

// normal case
assert.NoError(t, emptySigner.SealAfterCommit(h, [][]byte{expectedCommittedSeal}))

// verify istanbul extra-data
istExtra, err := types.ExtractHotstuffExtra(h)
assert.NoError(t, err)
assert.Equal(t, expectedIstExtra, istExtra)

// invalid seal
unexpectedCommittedSeal := append(expectedCommittedSeal, make([]byte, 1)...)
assert.Equal(t, ErrInvalidCommittedSeals, emptySigner.SealAfterCommit(h, [][]byte{unexpectedCommittedSeal}))
}

var emptySigner = &SignerImpl{}

type Keys []*ecdsa.PrivateKey
Expand Down
1 change: 0 additions & 1 deletion contracts/native/cross_chain_manager/entrance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ func init() {
node_manager.StoreGenesisGlobalConfig(sdb)

param := new(side_chain_manager.RegisterSideChainParam)
param.BlocksToWait = 4
param.ChainID = 8
param.Name = "mychain"

Expand Down
8 changes: 4 additions & 4 deletions contracts/native/economic/economic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func TestName(t *testing.T) {
payload, err := new(MethodContractNameInput).Encode()
assert.NoError(t, err)

raw, err := native.TestNativeCall(t, this, name, payload)
raw, err := native.TestNativeCall(t, this, name, payload, common.Big0)
assert.NoError(t, err)
var got string
assert.NoError(t, utils.UnpackOutputs(ABI, name, &got, raw))
Expand Down Expand Up @@ -78,7 +78,7 @@ func TestTotalSupply(t *testing.T) {
var supply *big.Int

payload, _ := new(MethodTotalSupplyInput).Encode()
raw, err := native.TestNativeCall(t, this, name, payload, tc.height)
raw, err := native.TestNativeCall(t, this, name, payload, common.Big0, tc.height)
assert.NoError(t, err)

if tc.testABI {
Expand Down Expand Up @@ -118,7 +118,7 @@ func TestReward(t *testing.T) {
got := new(MethodRewardOutput)

payload, _ := new(MethodRewardInput).Encode()
raw, err := native.TestNativeCall(t, this, name, payload, tc.height, func(state *state.StateDB) {
raw, err := native.TestNativeCall(t, this, name, payload, common.Big0, tc.height, func(state *state.StateDB) {
community.StoreCommunityInfo(state, big.NewInt(int64(tc.rate)), tc.pool)
})
if tc.err == nil {
Expand Down Expand Up @@ -146,7 +146,7 @@ func TestTransfer(t *testing.T) {
state := native.NewTestStateDB()
state.AddBalance(from, amount)

_, ctx := native.GenerateTestContext(t, state)
_, ctx := native.GenerateTestContext(t, common.Big0, to, state)
if state.GetBalance(from).Cmp(amount) < 0 {
t.Error("balance not enough")
}
Expand Down
2 changes: 2 additions & 0 deletions contracts/native/governance/entrance.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package governance
import (
"fmt"


"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/contracts/native/go_abi/node_manager_abi"
nm "github.com/ethereum/go-ethereum/contracts/native/governance/node_manager"
Expand Down Expand Up @@ -66,6 +67,7 @@ func AssembleSystemTransactions(state *state.StateDB, height uint64) (types.Tran
if err != nil {
return nil, err
}

gas, err := core.IntrinsicGas(payload, nil, false, true, true)
if err != nil {
return nil, err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func TestAddSignature(t *testing.T) {
payload := append(methodID, args...)
supplyGas := gasTable[name]

_, err = native.TestNativeCall(t, this, name, payload, supplyGas)
_, err = native.TestNativeCall(t, this, name, payload, common.Big0, supplyGas)
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "abi", "marshal")
}
Expand All @@ -83,7 +83,7 @@ func TestAddSignature(t *testing.T) {
assert.NoError(t, err)
supplyGas := gasTable[name] - 1

_, err = native.TestNativeCall(t, this, name, payload, supplyGas)
_, err = native.TestNativeCall(t, this, name, payload, common.Big0, supplyGas)
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "gas", "supply", "left")
}
Expand All @@ -98,7 +98,7 @@ func TestAddSignature(t *testing.T) {
payload, err := utils.PackMethod(ABI, name, addr, big.NewInt(2), []byte{'a'}, []byte{'1'})
assert.NoError(t, err)

_, err = native.TestNativeCall(t, this, name, payload, sender, supplyGas)
_, err = native.TestNativeCall(t, this, name, payload, common.Big0, sender, supplyGas)
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "checkWitness", "authentication")
}
Expand All @@ -118,7 +118,7 @@ func TestAddSignature(t *testing.T) {
payload, err := utils.PackMethod(ABI, name, sender, chainID, subject, errSig)
assert.NoError(t, err)

_, err = native.TestNativeCall(t, this, name, payload, sender, supplyGas, func(state *state.StateDB) {
_, err = native.TestNativeCall(t, this, name, payload, common.Big0, sender, supplyGas, func(state *state.StateDB) {
nm.StoreGenesisEpoch(state, peers, peers)
})
t.Error(err)
Expand Down
12 changes: 6 additions & 6 deletions contracts/native/info_sync/entrance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func TestNoAuthSyncRootInfo(t *testing.T) {

caller := crypto.PubkeyToAddress(*pub)
extra := uint64(21000000000000)
_, err = native.TestNativeCall(t, utils.InfoSyncContractAddress, "SyncRootInfo", input, caller, caller, extra, sdb)
_, err = native.TestNativeCall(t, utils.InfoSyncContractAddress, "SyncRootInfo", input, common.Big0, caller, caller, extra, sdb)
assert.NotNil(t, err)
}

Expand Down Expand Up @@ -138,7 +138,7 @@ func TestNormalSyncRootInfo(t *testing.T) {

input, err := param.Encode()
assert.Nil(t, err)
ret, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "SyncRootInfo", input, caller, caller, extra, sdb)
ret, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "SyncRootInfo", input, common.Big0, caller, caller, extra, sdb)
assert.Nil(t, err)
result, err := utils.PackOutputs(ABI, MethodSyncRootInfo, true)
assert.Nil(t, err)
Expand All @@ -151,7 +151,7 @@ func TestNormalSyncRootInfo(t *testing.T) {
input, err := q1.Encode()
assert.Nil(t, err)
extra := uint64(21000000000000)
ret1, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "GetInfo", input, extra, sdb)
ret1, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "GetInfo", input, common.Big0, extra, sdb)
rootInfo := new(GetInfoOutput)
err = rootInfo.Decode(ret1)
assert.Nil(t, err)
Expand All @@ -162,15 +162,15 @@ func TestNormalSyncRootInfo(t *testing.T) {
}
input, err = q2.Encode()
assert.Nil(t, err)
ret2, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "GetInfo", input, extra, sdb)
ret2, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "GetInfo", input, common.Big0, extra, sdb)
rootInfo = new(GetInfoOutput)
err = rootInfo.Decode(ret2)
assert.Nil(t, err)
assert.Equal(t, rootInfo.Info, []byte{0x02, 0x03})
q3 := &GetInfoHeightParam{CHAIN_ID}
input, err = q3.Encode()
assert.Nil(t, err)
ret3, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "GetInfoHeight", input, extra, sdb)
ret3, err := native.TestNativeCall(t, utils.InfoSyncContractAddress, "GetInfoHeight", input, common.Big0, extra, sdb)
height := new(GetInfoHeightOutput)
err = height.Decode(ret3)
assert.Nil(t, err)
Expand All @@ -186,6 +186,6 @@ func TestReplenish(t *testing.T) {
extra := uint64(21000000000000)
input, err := param.Encode()
assert.Nil(t, err)
_, err = native.TestNativeCall(t, utils.InfoSyncContractAddress, "Replenish", input, extra, sdb)
_, err = native.TestNativeCall(t, utils.InfoSyncContractAddress, "Replenish", input, common.Big0, extra, sdb)
assert.Nil(t, err)
}
12 changes: 10 additions & 2 deletions contracts/native/utils/event_emitter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,18 @@ import (

"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/contracts/native"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/state"
"github.com/stretchr/testify/assert"
)

func NewTestStateDB() *state.StateDB {
memdb := rawdb.NewMemoryDatabase()
db := state.NewDatabase(memdb)
stateDB, _ := state.New(common.Hash{}, db, nil)
return stateDB
}

func TestEventEmitter(t *testing.T) {
name := "propose"
abijson := `[
Expand All @@ -39,7 +47,7 @@ func TestEventEmitter(t *testing.T) {

contract := common.HexToAddress("0x05")
blockNo := uint64(36)
stateDB := native.NewTestStateDB()
stateDB := NewTestStateDB()
emmitter := NewEventEmitter(contract, blockNo, stateDB)

proposer := common.HexToAddress("0x12")
Expand Down
2 changes: 1 addition & 1 deletion contracts/native/utils/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,4 @@ var (
ETH_COMMON_ROUTER = uint64(2)

RIPPLE_ROUTER = uint64(6)
)
)
2 changes: 1 addition & 1 deletion core/state_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr
Difficulty: parent.Difficulty(),
UncleHash: parent.UncleHash(),
}),
GasLimit: CalcGasLimit(parent, parent.GasLimit(), parent.GasLimit()),
GasLimit: parent.GasLimit(),
Number: new(big.Int).Add(parent.Number(), common.Big1),
Time: parent.Time() + 10,
UncleHash: types.EmptyUncleHash,
Expand Down
5 changes: 4 additions & 1 deletion core/types/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ type headerMarshaling struct {
// Hash returns the block hash of the header, which is simply the keccak256 hash of its
// RLP encoding.
func (h *Header) Hash() common.Hash {
return rlpHash(h)
return SealHash(h)
}

// SealHash returns the hash of a block prior to it being sealed.
Expand Down Expand Up @@ -430,12 +430,15 @@ func (b *Block) Copy() *Block {
// Hash returns the keccak256 hash of b's header.
// The hash is computed on the first call and cached thereafter.
func (b *Block) Hash() common.Hash {
return b.SealHash()
/*
if hash := b.hash.Load(); hash != nil {
return hash.(common.Hash)
}
v := b.header.Hash()
b.hash.Store(v)
return v
*/
}

func (b *Block) SealHash() common.Hash {
Expand Down
2 changes: 1 addition & 1 deletion eth/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func TestStorageRangeAt(t *testing.T) {
}
)
for _, entry := range storage {
state.SetState(addr, *entry.Key, entry.Value.Bytes())
state.SetState(addr, *entry.Key, entry.Value)
}

// Check a few combinations of limit and start/end.
Expand Down
2 changes: 1 addition & 1 deletion eth/catalyst/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ func TestEth2NewBlock(t *testing.T) {
if err != nil || !success.Valid {
t.Fatalf("Failed to insert forked block #%d: %v", i, err)
}
lastBlock, err = insertBlockParamsToBlock(p)
lastBlock, err = insertBlockParamsToBlock(ethservice.APIBackend.ChainConfig(), lastBlock.Header(), p)
if err != nil {
t.Fatal(err)
}
Expand Down
4 changes: 2 additions & 2 deletions eth/tracers/tracers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func TestPrestateTracerCreate2(t *testing.T) {
}
evm := vm.NewEVM(context, txContext, statedb, params.MainnetChainConfig, vm.Config{Debug: true, Tracer: tracer})

msg, err := tx.AsMessage(signer)
msg, err := tx.AsMessage(signer, nil)
if err != nil {
t.Fatalf("failed to prepare transaction for tracing: %v", err)
}
Expand Down Expand Up @@ -254,7 +254,7 @@ func TestCallTracer(t *testing.T) {
}
evm := vm.NewEVM(context, txContext, statedb, test.Genesis.Config, vm.Config{Debug: true, Tracer: tracer})

msg, err := tx.AsMessage(signer)
msg, err := tx.AsMessage(signer, nil)
if err != nil {
t.Fatalf("failed to prepare transaction for tracing: %v", err)
}
Expand Down
6 changes: 2 additions & 4 deletions ethclient/ethclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ func TestUnmarshalHeader(t *testing.T) {

var (
blockNum uint64 = 1099
epochID uint64 = 5
epochID uint64 = 5
)
block, err := cli.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNum))
if err != nil {
Expand Down Expand Up @@ -680,8 +680,7 @@ func TestUnmarshalHeader(t *testing.T) {

// cache db slot
contractAddr := utils.NodeManagerContractAddress
proofHash := node_manager.EpochProofHash(epochID)
cacheKey := utils.ConcatKey(contractAddr, []byte("st_proof"), proofHash.Bytes())
cacheKey := utils.ConcatKey(contractAddr, []byte(node_manager.SKP_EPOCH_INFO), big.NewInt(int64(epochID)).Bytes())
slot := state.Key2Slot(cacheKey[common.AddressLength:])
t.Logf("slot hex before keccak: %s", slot.Hex())

Expand All @@ -699,5 +698,4 @@ func TestUnmarshalHeader(t *testing.T) {
t.Fatal(err)
}
t.Logf("proof result: %s", string(enc))
return
}
4 changes: 4 additions & 0 deletions miner/miner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ func (m *mockBackend) TxPool() *core.TxPool {
return m.txPool
}

func (m *mockBackend) PeerCount() int {
return 0
}

type testBlockChain struct {
statedb *state.StateDB
gasLimit uint64
Expand Down
2 changes: 1 addition & 1 deletion signer/rules/rules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ func dummyTx(value hexutil.Big) *core.SignTxRequest {
To: to,
Value: value,
Nonce: n,
GasPrice: gasPrice,
GasPrice: &gasPrice,
Gas: gas,
},
Callinfo: []core.ValidationInfo{
Expand Down

0 comments on commit 217249a

Please sign in to comment.