Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test/test execution execution.go #96

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 22 additions & 21 deletions common/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package common
import (
"encoding/json"
"fmt"
"math/big"
"strconv"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/holiman/uint256"
)
Expand Down Expand Up @@ -45,27 +45,28 @@ type Transactions struct {
Hashes [][32]byte
Full []Transaction // transaction needs to be defined
}

// Updated as earlier, txn data fetched from rpc was not able to unmarshal
// into the struct
type Transaction struct {
AccessList types.AccessList
Hash common.Hash
Nonce uint64
BlockHash [32]byte
BlockNumber *uint64
TransactionIndex uint64
From string
To *common.Address
Value *big.Int
GasPrice *big.Int
Gas uint64
Input []byte
ChainID *big.Int
TransactionType uint8
Signature *Signature
MaxFeePerGas *big.Int
MaxPriorityFeePerGas *big.Int
MaxFeePerBlobGas *big.Int
BlobVersionedHashes []common.Hash
AccessList types.AccessList `json:"accessList"`
Hash common.Hash `json:"hash"`
Nonce hexutil.Uint64 `json:"nonce"`
BlockHash string `json:"blockHash"` // Pointer because it's nullable
BlockNumber hexutil.Uint64 `json:"blockNumber"` // Pointer because it's nullable
TransactionIndex hexutil.Uint64 `json:"transactionIndex"`
From string `json:"from"`
To *common.Address `json:"to"` // Pointer because 'to' can be null for contract creation
Value hexutil.Big `json:"value"`
GasPrice hexutil.Big `json:"gasPrice"`
Gas hexutil.Uint64 `json:"gas"`
Input hexutil.Bytes `json:"input"`
ChainID hexutil.Big `json:"chainId"`
TransactionType hexutil.Uint `json:"type"`
Signature *Signature `json:"signature"`
MaxFeePerGas hexutil.Big `json:"maxFeePerGas"`
MaxPriorityFeePerGas hexutil.Big `json:"maxPriorityFeePerGas"`
MaxFeePerBlobGas hexutil.Big `json:"maxFeePerBlobGas"`
BlobVersionedHashes []common.Hash `json:"blobVersionedHashes"`
}

type Signature struct {
Expand Down
36 changes: 21 additions & 15 deletions consensus/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/ethereum/go-ethereum/core/types"
"github.com/holiman/uint256"
"github.com/pkg/errors"
"github.com/ethereum/go-ethereum/common/hexutil"
)

// Error definitions
Expand Down Expand Up @@ -953,20 +954,24 @@ func processTransaction(txBytes *[1073741824]byte, blockHash consensus_core.Byte
if err != nil {
return common.Transaction{}, fmt.Errorf("failed to decode transaction: %v", err)
}

// Updated due to update in Transaction struct
tx := common.Transaction{
Hash: txEnvelope.Hash(),
Nonce: txEnvelope.Nonce(),
BlockHash: blockHash,
BlockNumber: blockNumber,
TransactionIndex: index,
Nonce: hexutil.Uint64(txEnvelope.Nonce()),
BlockHash: func() string {
data := [32]byte(blockHash)
hexString := hex.EncodeToString(data[:])
return hexString
}(),
BlockNumber: hexutil.Uint64(*blockNumber),
TransactionIndex: hexutil.Uint64(index),
To: txEnvelope.To(),
Value: txEnvelope.Value(),
GasPrice: txEnvelope.GasPrice(),
Gas: txEnvelope.Gas(),
Value: hexutil.Big(*txEnvelope.Value()),
GasPrice: hexutil.Big(*txEnvelope.GasPrice()),
Gas: hexutil.Uint64(txEnvelope.Gas()),
Input: txEnvelope.Data(),
ChainID: txEnvelope.ChainId(),
TransactionType: txEnvelope.Type(),
ChainID: hexutil.Big(*txEnvelope.ChainId()),
TransactionType: hexutil.Uint(uint(txEnvelope.Type())),
}

// Handle signature and transaction type logic
Expand All @@ -990,12 +995,13 @@ func processTransaction(txBytes *[1073741824]byte, blockHash consensus_core.Byte
case types.AccessListTxType:
tx.AccessList = txEnvelope.AccessList()
case types.DynamicFeeTxType:
tx.MaxFeePerGas = new(big.Int).Set(txEnvelope.GasFeeCap())
tx.MaxPriorityFeePerGas = new(big.Int).Set(txEnvelope.GasTipCap())
// Update due to update in Transaction struct
tx.MaxFeePerGas = hexutil.Big(*new(big.Int).Set(txEnvelope.GasFeeCap()))
tx.MaxPriorityFeePerGas = hexutil.Big(*new(big.Int).Set(txEnvelope.GasTipCap()))
case types.BlobTxType:
tx.MaxFeePerGas = new(big.Int).Set(txEnvelope.GasFeeCap())
tx.MaxPriorityFeePerGas = new(big.Int).Set(txEnvelope.GasTipCap())
tx.MaxFeePerBlobGas = new(big.Int).Set(txEnvelope.BlobGasFeeCap())
tx.MaxFeePerGas = hexutil.Big(*new(big.Int).Set(txEnvelope.GasFeeCap()))
tx.MaxPriorityFeePerGas = hexutil.Big(*new(big.Int).Set(txEnvelope.GasTipCap()))
tx.MaxFeePerBlobGas = hexutil.Big(*new(big.Int).Set(txEnvelope.BlobGasFeeCap()))
tx.BlobVersionedHashes = txEnvelope.BlobHashes()
default:
fmt.Println("Unhandled transaction type")
Expand Down
85 changes: 85 additions & 0 deletions execution/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package execution

import (
"errors"
"testing"

"github.com/BlocSoc-iitr/selene/consensus/consensus_core"
"github.com/BlocSoc-iitr/selene/consensus/types"
"github.com/stretchr/testify/assert"
)

func TestExecutionErrors(t *testing.T) {
// Test InvalidAccountProofError
address := types.Address{0x01, 0x02}
err := NewInvalidAccountProofError(address)
assert.EqualError(t, err, "invalid account proof for string: [1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]")

// Test InvalidStorageProofError
slot := consensus_core.Bytes32{0x0a}
err = NewInvalidStorageProofError(address, slot)
assert.EqualError(t, err, "invalid storage proof for string: [1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0], slot: [10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]")

// Test CodeHashMismatchError
found := consensus_core.Bytes32{0x03}
expected := consensus_core.Bytes32{0x04}
err = NewCodeHashMismatchError(address, found, expected)
assert.EqualError(t, err, "code hash mismatch for string: [1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0], found: [3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0], expected: [4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]")

// Test ReceiptRootMismatchError
tx := consensus_core.Bytes32{0x05}
err = NewReceiptRootMismatchError(tx)
assert.EqualError(t, err, "receipt root mismatch for tx: [5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]")

// Test MissingTransactionError
err = NewMissingTransactionError(tx)
assert.EqualError(t, err, "missing transaction for tx: [5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]")

// Test MissingLogError
err = NewMissingLogError(tx, 3)
assert.EqualError(t, err, "missing log for transaction: [5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0], index: 3")

// Test TooManyLogsToProveError
err = NewTooManyLogsToProveError(5000, 1000)
assert.EqualError(t, err, "too many logs to prove: 5000, current limit is: 1000")

// Test InvalidBaseGasFeeError
err = NewInvalidBaseGasFeeError(1000, 2000, 123456)
assert.EqualError(t, err, "Invalid base gas fee selene 1000 vs rpc endpoint 2000 at block 123456")

// Test BlockNotFoundError
err = NewBlockNotFoundError(123456)
assert.EqualError(t, err, "Block 123456 not found")

// Test EmptyExecutionPayloadError
err = NewEmptyExecutionPayloadError()
assert.EqualError(t, err, "Selene Execution Payload is empty")
}

func TestEvmErrors(t *testing.T) {
// Test RevertError
data := []byte{0x08, 0xc3, 0x79, 0xa0}
err := NewRevertError(data)
assert.EqualError(t, err, "execution reverted: [8 195 121 160]")

// Test GenericError
err = NewGenericError("generic error")
assert.EqualError(t, err, "evm error: generic error")

// Test RpcError
rpcErr := errors.New("rpc connection failed")
err = NewRpcError(rpcErr)
assert.EqualError(t, err, "rpc error: rpc connection failed")
}

func TestDecodeRevertReason(t *testing.T) {
// Test successful revert reason decoding
reasonData := []byte{0x08, 0xc3, 0x79, 0xa0}
reason := DecodeRevertReason(reasonData)
assert.NotEmpty(t, reason, "Revert reason should be decoded")

// Test invalid revert data
invalidData := []byte{0x00}
reason = DecodeRevertReason(invalidData)
assert.Contains(t, reason, "invalid data for unpacking")
}
61 changes: 38 additions & 23 deletions execution/execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,15 @@ type ExecutionClient struct {
}

func (e *ExecutionClient) New(rpc string, state *State) (*ExecutionClient, error) {
r, err := ExecutionRpc.New(nil, &rpc)
// This is updated as earlier, when ExecutionRpc.New() was called, it was giving an
// invalid address or nil pointer dereference error as there wasn't a concrete type that implemented ExecutionRpc
var r ExecutionRpc
r, err := (&HttpRpc{}).New(&rpc)
if err != nil {
return nil, err
}
return &ExecutionClient{
Rpc: *r,
Rpc: r,
state: state,
}, nil
}
Expand Down Expand Up @@ -60,12 +63,18 @@ func (e *ExecutionClient) CheckRpc(chainID uint64) error {
}

// GetAccount retrieves the account information
func (e *ExecutionClient) GetAccount(address *seleneCommon.Address, slots []common.Hash, tag seleneCommon.BlockTag) (Account, error) { //Account from execution/types.go
func (e *ExecutionClient) GetAccount(address *seleneCommon.Address, slots *[]common.Hash, tag seleneCommon.BlockTag) (Account, error) { //Account from execution/types.go
block := e.state.GetBlock(tag)
proof, _ := e.Rpc.GetProof(address, &slots, block.Number)

// Error Handling
proof, err := e.Rpc.GetProof(address, slots, block.Number)
if err != nil {
return Account{}, err
}
accountPath := crypto.Keccak256(address.Addr[:])
accountEncoded, _ := EncodeAccount(&proof)
accountEncoded, err := EncodeAccount(&proof)
if err != nil {
return Account{}, err
}
accountProofBytes := make([][]byte, len(proof.AccountProof))
for i, hexByte := range proof.AccountProof {
accountProofBytes[i] = hexByte
Expand All @@ -78,7 +87,7 @@ func (e *ExecutionClient) GetAccount(address *seleneCommon.Address, slots []comm
return Account{}, NewInvalidAccountProofError(address.Addr)
}
// modify
slotMap := make(map[common.Hash]*big.Int)
slotMap := []Slot{}
for _, storageProof := range proof.StorageProof {
key, err := utils.Hex_str_to_bytes(storageProof.Key.Hex())
if err != nil {
Expand All @@ -105,7 +114,10 @@ func (e *ExecutionClient) GetAccount(address *seleneCommon.Address, slots []comm
if !isValid {
return Account{}, fmt.Errorf("invalid storage proof for address: %v, key: %v", *address, storageProof.Key)
}
slotMap[storageProof.Key] = storageProof.Value.ToBig()
slotMap = append(slotMap, Slot{
Key: storageProof.Key,
Value: storageProof.Value.ToBig(),
})
}
var code []byte
if bytes.Equal(proof.CodeHash.Bytes(), crypto.Keccak256([]byte(KECCAK_EMPTY))) {
Expand All @@ -123,7 +135,7 @@ func (e *ExecutionClient) GetAccount(address *seleneCommon.Address, slots []comm
}
account := Account{
Balance: proof.Balance.ToBig(),
Nonce: proof.Nonce,
Nonce: uint64(proof.Nonce),
Code: code,
CodeHash: proof.CodeHash,
StorageHash: proof.StorageHash,
Expand Down Expand Up @@ -298,10 +310,8 @@ func (e *ExecutionClient) GetLogs(filter ethereum.FilterQuery) ([]types.Log, err
select {
case logs := <-logsChan:
if len(logs) > MAX_SUPPORTED_LOGS_NUMBER {
return nil, &ExecutionError{
Kind: "TooManyLogs",
Details: fmt.Sprintf("Too many logs to prove: %d, max: %d", len(logs), MAX_SUPPORTED_LOGS_NUMBER),
}
// The earlier error was not returning properly
return nil, errors.New("logs exceed max supported logs number")
}
logPtrs := make([]*types.Log, len(logs))
for i := range logs {
Expand Down Expand Up @@ -506,19 +516,24 @@ func rlpHash(obj interface{}) (common.Hash, error) {
}
return crypto.Keccak256Hash(encoded), nil
}
// This function is updated as it was going in an infinite loop
func calculateMerkleRoot(hashes []common.Hash) common.Hash {
if len(hashes) == 1 {
switch len(hashes) {
case 0:
return common.Hash{} // Return empty hash for empty slice
case 1:
return hashes[0]
default:
if len(hashes)%2 != 0 {
hashes = append(hashes, hashes[len(hashes)-1])
}
var newLevel []common.Hash
for i := 0; i < len(hashes); i += 2 {
combinedHash := crypto.Keccak256(append(hashes[i].Bytes(), hashes[i+1].Bytes()...))
newLevel = append(newLevel, common.BytesToHash(combinedHash))
}
return calculateMerkleRoot(newLevel)
}
if len(hashes)%2 != 0 {
hashes = append(hashes, hashes[len(hashes)-1])
}
var newLevel []common.Hash
for i := 0; i < len(hashes); i += 2 {
combinedHash := crypto.Keccak256(append(hashes[i].Bytes(), hashes[i+1].Bytes()...))
newLevel = append(newLevel, common.BytesToHash(combinedHash))
}
return calculateMerkleRoot(newLevel)
}

// contains checks if a receipt is in the list of receipts
Expand Down
Loading
Loading