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

Fixes issues in #96 #100

Closed
wants to merge 63 commits into from
Closed
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
f605e60
Updated
18aaddy Sep 19, 2024
2291d91
Revert "Updated"
18aaddy Sep 24, 2024
025f101
Modified go.mod and go.sum
18aaddy Oct 29, 2024
313a7a0
Updated
18aaddy Sep 19, 2024
020954f
Revert "Updated"
18aaddy Sep 24, 2024
a8fae8a
Initial Commit
18aaddy Oct 23, 2024
6e8ee83
Updated
18aaddy Oct 29, 2024
1e1d769
Update
18aaddy Oct 29, 2024
b09b233
Update
18aaddy Oct 29, 2024
8bbedbe
Tests working locally
18aaddy Oct 29, 2024
6635d26
Added test file
18aaddy Oct 29, 2024
6402277
Update
18aaddy Oct 30, 2024
2da2aa2
Commented CreateAccessListTest
18aaddy Oct 30, 2024
b137762
Update
18aaddy Oct 30, 2024
460629c
fix for #96
ABD-AZE Nov 1, 2024
efb93d5
json error resolved from createaccess list
ABD-AZE Nov 1, 2024
4a05db6
resolved warnings
ABD-AZE Nov 1, 2024
664b81d
tests passing
ABD-AZE Nov 1, 2024
ad0e041
final warnings resolved
ABD-AZE Nov 1, 2024
c76a2a2
edit common/types.go
ABD-AZE Nov 2, 2024
826916b
Running workflow again
ABD-AZE Nov 4, 2024
a28f2d1
Tests passing
ABD-AZE Nov 4, 2024
5778b54
type consistency maintained
ABD-AZE Nov 4, 2024
8aa8dc0
refactoring
ABD-AZE Nov 4, 2024
5898174
.gitignore
ABD-AZE Nov 4, 2024
ee4a0f0
Delete go.mod
ABD-AZE Nov 4, 2024
8d8156d
Delete go.sum
ABD-AZE Nov 4, 2024
f52b2a9
Update consensus.go
DarkLord017 Oct 15, 2024
4325390
Update consensus_core.go
DarkLord017 Oct 15, 2024
60d1a76
Create serde_utils.go
DarkLord017 Oct 15, 2024
69e5dc9
Update utils.go
DarkLord017 Oct 15, 2024
231cfd4
Update consensus_rpc.go
DarkLord017 Oct 15, 2024
7c5644e
Update consensus_rpc_test.go
DarkLord017 Oct 15, 2024
ede23f9
Update mock_rpc.go
DarkLord017 Oct 15, 2024
a01bad1
Update mock_rpc_test.go
DarkLord017 Oct 15, 2024
dd5efbf
Update nimbus_rpc.go
DarkLord017 Oct 15, 2024
58af92e
Update nimbus_rpc_test.go
DarkLord017 Oct 15, 2024
f57d83a
Update go.mod
DarkLord017 Oct 15, 2024
95b027a
Update go.sum
DarkLord017 Oct 15, 2024
b3bf300
Create consensus_test.go
DarkLord017 Oct 15, 2024
13982ab
Refactor consensus/rpc/consensus_rpc.go
DarkLord017 Sep 27, 2024
e240988
Refactor mock_rpc.go
DarkLord017 Sep 27, 2024
5feb1aa
Refactor nimbus_rpc.go
DarkLord017 Sep 27, 2024
a25749a
Update consensus_rpc.go
DarkLord017 Nov 4, 2024
069c873
Update consensus.go
DarkLord017 Nov 4, 2024
c9023e8
Removed duplicated types and structs in basic.go
DarkLord017 Oct 1, 2024
dbcf04a
Refactor beacon.go to remove duplicxatoed types and structs
DarkLord017 Oct 1, 2024
468590d
Update consensus_core.go to remove import cycle errors after refactor…
DarkLord017 Oct 1, 2024
de838bd
Update basic.go
DarkLord017 Nov 4, 2024
cb66bee
Resolved builder errors
Nov 4, 2024
0d1c3eb
Create tests consensus/database_test.go
DarkLord017 Nov 4, 2024
5e0ccf7
Update consensus.go to correctly use rlp unmarsahalling and handle le…
DarkLord017 Nov 4, 2024
bb46c01
Update serde_utils.go to correctly handle unmarsahhlihng
DarkLord017 Nov 4, 2024
c3fb924
Update consensus_test.go to handle block Tests
DarkLord017 Nov 4, 2024
dbca377
Update mock_rpc_test.go to handle Blocks
DarkLord017 Nov 4, 2024
7704238
Update nimbus_rpc_test.go to handle Blocks
DarkLord017 Nov 4, 2024
512f8c4
Update consensus_core.go to handle Transactions correctly
DarkLord017 Nov 4, 2024
ce5cb70
Updated
18aaddy Sep 19, 2024
fc21118
Revert "Updated"
18aaddy Sep 24, 2024
d1a2886
Modified go.mod and go.sum
18aaddy Oct 29, 2024
5f61b96
Updated
18aaddy Sep 19, 2024
e48119b
Revert "Updated"
18aaddy Sep 24, 2024
4e55d9c
Update
18aaddy Oct 29, 2024
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
45 changes: 23 additions & 22 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 Expand Up @@ -116,7 +117,7 @@ func (b BlockTag) String() string {
if b.Finalized {
return "finalized"
}
return fmt.Sprintf("%d", b.Number)
return fmt.Sprintf("0x%x", b.Number)
}

func (b *BlockTag) UnmarshalJSON(data []byte) error {
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")
}
72 changes: 45 additions & 27 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,25 +63,33 @@ 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
block := e.state.GetBlock(tag)
proof, _ := e.Rpc.GetProof(address, &slots, block.Number)

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)
// Error Handling
proof, err := e.Rpc.GetProof(address, slots, 21093292) // block.Number instead of hardcoded value
// fmt.Printf("%v",proof);
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
}
isValid, err := VerifyProof(accountProofBytes, block.StateRoot[:], accountPath, accountEncoded)
// fmt.Printf("%v",accountProofBytes)
isValid, err := VerifyProof(accountProofBytes, common.Hex2Bytes("0xaba5664183bc9b0bbb9d092bc85cf895ab729b9d5ff98f4055e8869e8d948ad4"), accountPath, accountEncoded) //block.StateRoot[:] instead of hardcoded value
if err != nil {
return Account{}, err
}
if !isValid {
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,13 +116,16 @@ 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))) {
if proof.CodeHash == [32]byte{} {
code = []byte{}
} else {
code, err := e.Rpc.GetCode(address, block.Number)
code, err := e.Rpc.GetCode(address, 21093292) // block.Number instead of hardcoded value
if err != nil {
return Account{}, err
}
Expand All @@ -123,7 +137,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,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is some build error because of access of either null pointer or an invalid memory access, please check that. Mostly coming from GetBlock function

Expand Down Expand Up @@ -298,10 +312,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 +518,25 @@ 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