From 4e0d72bfd4973b11ad9087285e21fb407aab4fe6 Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Sat, 28 Sep 2024 02:23:29 +0530 Subject: [PATCH 01/10] Refactor consensus/rpc/consensus_rpc.go --- consensus/rpc/consensus_rpc.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/consensus/rpc/consensus_rpc.go b/consensus/rpc/consensus_rpc.go index 22dc00e..255d939 100644 --- a/consensus/rpc/consensus_rpc.go +++ b/consensus/rpc/consensus_rpc.go @@ -2,6 +2,7 @@ package rpc import ( "github.com/BlocSoc-iitr/selene/consensus/consensus_core" + "github.com/BlocSoc-iitr/selene/utils" ) // return types not mention and oarameters as well @@ -15,5 +16,10 @@ type ConsensusRpc interface { } func NewConsensusRpc(rpc string) ConsensusRpc { - return NewNimbusRpc(rpc) + if utils.IsURL(rpc) { + return NewNimbusRpc(rpc) + } else { + return NewMockRpc(rpc) + } + } From af1cf3c4e621730709fb15240dff59361101a359 Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Sat, 28 Sep 2024 02:24:13 +0530 Subject: [PATCH 02/10] Refactor mock_rpc.go --- consensus/rpc/mock_rpc.go | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/consensus/rpc/mock_rpc.go b/consensus/rpc/mock_rpc.go index 971f381..1801a64 100644 --- a/consensus/rpc/mock_rpc.go +++ b/consensus/rpc/mock_rpc.go @@ -5,31 +5,33 @@ package rpc import ( "encoding/json" "fmt" - "github.com/BlocSoc-iitr/selene/consensus/consensus_core" "os" "path/filepath" + + "github.com/BlocSoc-iitr/selene/consensus/consensus_core" ) type MockRpc struct { testdata string } + func NewMockRpc(path string) *MockRpc { return &MockRpc{ testdata: path, } } -func (m *MockRpc) GetBootstrap(block_root []byte) (*consensus_core.Bootstrap, error) { +func (m *MockRpc) GetBootstrap(block_root [32]byte) (consensus_core.Bootstrap, error) { path := filepath.Join(m.testdata, "bootstrap.json") res, err := os.ReadFile(path) if err != nil { - return nil, fmt.Errorf("failed to read file: %w", err) + return consensus_core.Bootstrap{}, fmt.Errorf("failed to read file: %w", err) } var bootstrap BootstrapResponse err = json.Unmarshal(res, &bootstrap) if err != nil { - return &consensus_core.Bootstrap{}, fmt.Errorf("bootstrap error: %w", err) + return consensus_core.Bootstrap{}, fmt.Errorf("bootstrap error: %w", err) } - return &bootstrap.Data, nil + return bootstrap.Data, nil } func (m *MockRpc) GetUpdates(period uint64, count uint8) ([]consensus_core.Update, error) { path := filepath.Join(m.testdata, "updates.json") @@ -48,44 +50,44 @@ func (m *MockRpc) GetUpdates(period uint64, count uint8) ([]consensus_core.Updat } return updates, nil } -func (m *MockRpc) GetFinalityUpdate() (*consensus_core.FinalityUpdate, error) { +func (m *MockRpc) GetFinalityUpdate() (consensus_core.FinalityUpdate, error) { path := filepath.Join(m.testdata, "finality.json") res, err := os.ReadFile(path) if err != nil { - return nil, fmt.Errorf("failed to read file: %w", err) + return consensus_core.FinalityUpdate{}, fmt.Errorf("failed to read file: %w", err) } var finality FinalityUpdateResponse err = json.Unmarshal(res, &finality) if err != nil { - return &consensus_core.FinalityUpdate{}, fmt.Errorf("finality update error: %w", err) + return consensus_core.FinalityUpdate{}, fmt.Errorf("finality update error: %w", err) } - return &finality.Data, nil + return finality.Data, nil } -func (m *MockRpc) GetOptimisticUpdate() (*consensus_core.OptimisticUpdate, error) { +func (m *MockRpc) GetOptimisticUpdate() (consensus_core.OptimisticUpdate, error) { path := filepath.Join(m.testdata, "optimistic.json") res, err := os.ReadFile(path) if err != nil { - return nil, fmt.Errorf("failed to read file: %w", err) + return consensus_core.OptimisticUpdate{}, fmt.Errorf("failed to read file: %w", err) } var optimistic OptimisticUpdateResponse err = json.Unmarshal(res, &optimistic) if err != nil { - return &consensus_core.OptimisticUpdate{}, fmt.Errorf("optimistic update error: %w", err) + return consensus_core.OptimisticUpdate{}, fmt.Errorf("optimistic update error: %w", err) } - return &optimistic.Data, nil + return optimistic.Data, nil } -func (m *MockRpc) GetBlock(slot uint64) (*consensus_core.BeaconBlock, error) { +func (m *MockRpc) GetBlock(slot uint64) (consensus_core.BeaconBlock, error) { path := filepath.Join(m.testdata, fmt.Sprintf("blocks/%d.json", slot)) res, err := os.ReadFile(path) if err != nil { - return nil, fmt.Errorf("failed to read file: %w", err) + return consensus_core.BeaconBlock{}, fmt.Errorf("failed to read file: %w", err) } var block BeaconBlockResponse err = json.Unmarshal(res, &block) if err != nil { - return nil, err + return consensus_core.BeaconBlock{}, err } - return &block.Data.Message, nil + return block.Data.Message, nil } func (m *MockRpc) ChainId() (uint64, error) { return 0, fmt.Errorf("not implemented") From 9fa9710752b8e2ab31d46fcf3a1b69574be60f6b Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Sat, 28 Sep 2024 02:24:40 +0530 Subject: [PATCH 03/10] Refactor nimbus_rpc.go From ea9cca16a296d914e3c0cd60cd44bf45879aa29c Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Sat, 28 Sep 2024 02:25:03 +0530 Subject: [PATCH 04/10] Refactor mock_rpc_test.go --- consensus/rpc/mock_rpc_test.go | 260 +++++++++++++++------------------ 1 file changed, 114 insertions(+), 146 deletions(-) diff --git a/consensus/rpc/mock_rpc_test.go b/consensus/rpc/mock_rpc_test.go index b371a54..8eaf833 100644 --- a/consensus/rpc/mock_rpc_test.go +++ b/consensus/rpc/mock_rpc_test.go @@ -1,163 +1,131 @@ package rpc + import ( "encoding/json" - "os" - "path/filepath" + "fmt" + "net/http" + "net/http/httptest" "testing" "github.com/BlocSoc-iitr/selene/consensus/consensus_core" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func TestNewMockRpc(t *testing.T) { - path := "/tmp/testdata" - mockRpc := NewMockRpc(path) - if mockRpc.testdata != path { - t.Errorf("Expected testdata path to be %s, got %s", path, mockRpc.testdata) - } + +func TestNewNimbusRpc(t *testing.T) { + rpcURL := "http://example.com" + nimbusRpc := NewNimbusRpc(rpcURL) + assert.Equal(t, rpcURL, nimbusRpc.rpc) } -func TestGetBootstrap(t *testing.T) { - tempDir, err := os.MkdirTemp("", "mock_rpc_test") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) - mockBootstrap := BootstrapResponse{ - Data: consensus_core.Bootstrap{ - Header: consensus_core.Header{ - Slot: 1000, +func TestNimbusGetBootstrap(t *testing.T) { + blockRoot := [32]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32} + expectedPath := fmt.Sprintf("/eth/v1/beacon/light_client/bootstrap/0x%x", blockRoot) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, expectedPath, r.URL.Path) + response := BootstrapResponse{ + Data: consensus_core.Bootstrap{ + Header: consensus_core.Header{ + Slot: 1000, + }, }, - }, - } - bootstrapJSON, _ := json.Marshal(mockBootstrap) - err = os.WriteFile(filepath.Join(tempDir, "bootstrap.json"), bootstrapJSON, 0644) - if err != nil { - t.Fatalf("Failed to write mock bootstrap file: %v", err) - } - mockRpc := NewMockRpc(tempDir) - bootstrap, err := mockRpc.GetBootstrap([]byte{}) - if err != nil { - t.Fatalf("GetBootstrap failed: %v", err) - } - if bootstrap.Header.Slot != 1000 { - t.Errorf("Expected bootstrap slot to be 1000, got %d", bootstrap.Header.Slot) - } + } + err := json.NewEncoder(w).Encode(response) + require.NoError(t, err) + })) + defer server.Close() + nimbusRpc := NewNimbusRpc(server.URL) + bootstrap, err := nimbusRpc.GetBootstrap(blockRoot) + assert.NoError(t, err) + assert.Equal(t, uint64(1000), bootstrap.Header.Slot) } -func TestGetUpdates(t *testing.T) { - tempDir, err := os.MkdirTemp("", "mock_rpc_test") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) - mockUpdates := UpdateResponse{ - {Data: consensus_core.Update{SignatureSlot: 1}}, - {Data: consensus_core.Update{SignatureSlot: 2}}, - } - updatesJSON, _ := json.Marshal(mockUpdates) - err = os.WriteFile(filepath.Join(tempDir, "updates.json"), updatesJSON, 0644) - if err != nil { - t.Fatalf("Failed to write mock updates file: %v", err) - } - mockRpc := NewMockRpc(tempDir) - updates, err := mockRpc.GetUpdates(1, 2) - if err != nil { - t.Fatalf("GetUpdates failed: %v", err) - } - if len(updates) != 2 { - t.Errorf("Expected 2 updates, got %d", len(updates)) - } - if updates[0].SignatureSlot != 1 || updates[1].SignatureSlot != 2 { - t.Errorf("Unexpected update signature slots") - } +func TestNimbusGetUpdates(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/eth/v1/beacon/light_client/updates", r.URL.Path) + assert.Equal(t, "start_period=1000&count=5", r.URL.RawQuery) + response := UpdateResponse{ + {Data: consensus_core.Update{AttestedHeader: consensus_core.Header{Slot: 1000}}}, + {Data: consensus_core.Update{AttestedHeader: consensus_core.Header{Slot: 1001}}}, + } + err := json.NewEncoder(w).Encode(response) + require.NoError(t, err) + })) + defer server.Close() + nimbusRpc := NewNimbusRpc(server.URL) + updates, err := nimbusRpc.GetUpdates(1000, 5) + assert.NoError(t, err) + assert.Len(t, updates, 2) + assert.Equal(t, uint64(1000), updates[0].AttestedHeader.Slot) + assert.Equal(t, uint64(1001), updates[1].AttestedHeader.Slot) } -func TestGetFinalityUpdate(t *testing.T) { - tempDir, err := os.MkdirTemp("", "mock_rpc_test") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) - mockFinality := FinalityUpdateResponse{ - Data: consensus_core.FinalityUpdate{ - FinalizedHeader: consensus_core.Header{ - Slot: 2000, +func TestNimbusGetFinalityUpdate(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/eth/v1/beacon/light_client/finality_update", r.URL.Path) + response := FinalityUpdateResponse{ + Data: consensus_core.FinalityUpdate{ + FinalizedHeader: consensus_core.Header{ + Slot: 2000, + }, }, - }, - } - finalityJSON, _ := json.Marshal(mockFinality) - err = os.WriteFile(filepath.Join(tempDir, "finality.json"), finalityJSON, 0644) - if err != nil { - t.Fatalf("Failed to write mock finality file: %v", err) - } - mockRpc := NewMockRpc(tempDir) - finality, err := mockRpc.GetFinalityUpdate() - if err != nil { - t.Fatalf("GetFinalityUpdate failed: %v", err) - } - if finality.FinalizedHeader.Slot != 2000 { - t.Errorf("Expected finality slot to be 2000, got %d", finality.FinalizedHeader.Slot) - } + } + err := json.NewEncoder(w).Encode(response) + require.NoError(t, err) + })) + defer server.Close() + nimbusRpc := NewNimbusRpc(server.URL) + finalityUpdate, err := nimbusRpc.GetFinalityUpdate() + assert.NoError(t, err) + assert.Equal(t, uint64(2000), finalityUpdate.FinalizedHeader.Slot) } -func TestGetOptimisticUpdate(t *testing.T) { - tempDir, err := os.MkdirTemp("", "mock_rpc_test") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) - mockOptimistic := OptimisticUpdateResponse{ - Data: consensus_core.OptimisticUpdate{ - SignatureSlot: 3000, - }, - } - optimisticJSON, _ := json.Marshal(mockOptimistic) - err = os.WriteFile(filepath.Join(tempDir, "optimistic.json"), optimisticJSON, 0644) - if err != nil { - t.Fatalf("Failed to write mock optimistic file: %v", err) - } - mockRpc := NewMockRpc(tempDir) - optimistic, err := mockRpc.GetOptimisticUpdate() - if err != nil { - t.Fatalf("GetOptimisticUpdate failed: %v", err) - } - if optimistic.SignatureSlot != 3000 { - t.Errorf("Expected optimistic signature slot to be 3000, got %d", optimistic.SignatureSlot) - } +func TestNimbusGetOptimisticUpdate(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/eth/v1/beacon/light_client/optimistic_update", r.URL.Path) + response := OptimisticUpdateResponse{ + Data: consensus_core.OptimisticUpdate{ + SignatureSlot: 3000, + }, + } + err := json.NewEncoder(w).Encode(response) + require.NoError(t, err) + })) + defer server.Close() + nimbusRpc := NewNimbusRpc(server.URL) + optimisticUpdate, err := nimbusRpc.GetOptimisticUpdate() + assert.NoError(t, err) + assert.Equal(t, uint64(3000), optimisticUpdate.SignatureSlot) } -func TestGetBlock(t *testing.T) { - tempDir, err := os.MkdirTemp("", "mock_rpc_test") - if err != nil { - t.Fatalf("Failed to create temp dir: %v", err) - } - defer os.RemoveAll(tempDir) - blocksDir := filepath.Join(tempDir, "blocks") - err = os.Mkdir(blocksDir, 0755) - if err != nil { - t.Fatalf("Failed to create blocks directory: %v", err) - } - mockBlock := BeaconBlockResponse{ - Data: struct { - Message consensus_core.BeaconBlock - }{ - Message: consensus_core.BeaconBlock{ - Slot: 4000, +func TestNimbusGetBlock(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/eth/v2/beacon/blocks/4000", r.URL.Path) + response := BeaconBlockResponse{ + Data: BeaconBlockData{ + Message: consensus_core.BeaconBlock{ + Slot: 4000, + }, }, - }, - } - blockJSON, _ := json.Marshal(mockBlock) - err = os.WriteFile(filepath.Join(blocksDir, "4000.json"), blockJSON, 0644) - if err != nil { - t.Fatalf("Failed to write mock block file: %v", err) - } - mockRpc := NewMockRpc(tempDir) - block, err := mockRpc.GetBlock(4000) - if err != nil { - t.Fatalf("GetBlock failed: %v", err) - } - if block.Slot != 4000 { - t.Errorf("Expected block slot to be 4000, got %d", block.Slot) - } + } + err := json.NewEncoder(w).Encode(response) + require.NoError(t, err) + })) + defer server.Close() + nimbusRpc := NewNimbusRpc(server.URL) + block, err := nimbusRpc.GetBlock(4000) + assert.NoError(t, err) + assert.Equal(t, uint64(4000), block.Slot) } -func TestChainId(t *testing.T) { - mockRpc := NewMockRpc("/tmp/testdata") - _, err := mockRpc.ChainId() - if err == nil || err.Error() != "not implemented" { - t.Errorf("Expected 'not implemented' error, got %v", err) - } +func TestNimbusChainId(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/eth/v1/config/spec", r.URL.Path) + response := SpecResponse{ + Data: Spec{ + ChainId: 5000, + }, + } + err := json.NewEncoder(w).Encode(response) + require.NoError(t, err) + })) + defer server.Close() + nimbusRpc := NewNimbusRpc(server.URL) + chainId, err := nimbusRpc.ChainId() + assert.NoError(t, err) + assert.Equal(t, uint64(5000), chainId) } From f0f0f368397c60c05b200307c1d93e370ace89ce Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Sat, 28 Sep 2024 02:26:31 +0530 Subject: [PATCH 05/10] Refactor RPC module --- utils/utils.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/utils/utils.go b/utils/utils.go index c44317c..e2f614a 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -2,7 +2,7 @@ package utils import ( "encoding/hex" - + "net/url" "strings" "bytes" @@ -279,3 +279,7 @@ func BranchToNodes(branch []consensus_core.Bytes32) ([][]byte, error) { } return nodes, nil } +func IsURL(str string) bool { + u, err := url.Parse(str) + return err == nil && u.Scheme != "" && u.Host != "" +} From 94f35d5e51819d721021289cb2fdc96f01113157 Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Sat, 28 Sep 2024 02:28:27 +0530 Subject: [PATCH 06/10] Update mock_rpc_test.go --- consensus/rpc/mock_rpc_test.go | 258 +++++++++++++++++++-------------- 1 file changed, 146 insertions(+), 112 deletions(-) diff --git a/consensus/rpc/mock_rpc_test.go b/consensus/rpc/mock_rpc_test.go index 8eaf833..550080e 100644 --- a/consensus/rpc/mock_rpc_test.go +++ b/consensus/rpc/mock_rpc_test.go @@ -2,130 +2,164 @@ package rpc import ( "encoding/json" - "fmt" - "net/http" - "net/http/httptest" + "os" + "path/filepath" "testing" "github.com/BlocSoc-iitr/selene/consensus/consensus_core" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) -func TestNewNimbusRpc(t *testing.T) { - rpcURL := "http://example.com" - nimbusRpc := NewNimbusRpc(rpcURL) - assert.Equal(t, rpcURL, nimbusRpc.rpc) +func TestNewMockRpc(t *testing.T) { + path := "/tmp/testdata" + mockRpc := NewMockRpc(path) + if mockRpc.testdata != path { + t.Errorf("Expected testdata path to be %s, got %s", path, mockRpc.testdata) + } } -func TestNimbusGetBootstrap(t *testing.T) { - blockRoot := [32]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32} - expectedPath := fmt.Sprintf("/eth/v1/beacon/light_client/bootstrap/0x%x", blockRoot) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, expectedPath, r.URL.Path) - response := BootstrapResponse{ - Data: consensus_core.Bootstrap{ - Header: consensus_core.Header{ - Slot: 1000, - }, +func TestGetBootstrap(t *testing.T) { + tempDir, err := os.MkdirTemp("", "mock_rpc_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + mockBootstrap := BootstrapResponse{ + Data: consensus_core.Bootstrap{ + Header: consensus_core.Header{ + Slot: 1000, }, - } - err := json.NewEncoder(w).Encode(response) - require.NoError(t, err) - })) - defer server.Close() - nimbusRpc := NewNimbusRpc(server.URL) - bootstrap, err := nimbusRpc.GetBootstrap(blockRoot) - assert.NoError(t, err) - assert.Equal(t, uint64(1000), bootstrap.Header.Slot) + }, + } + bootstrapJSON, _ := json.Marshal(mockBootstrap) + err = os.WriteFile(filepath.Join(tempDir, "bootstrap.json"), bootstrapJSON, 0644) + if err != nil { + t.Fatalf("Failed to write mock bootstrap file: %v", err) + } + mockRpc := NewMockRpc(tempDir) + bootstrap, err := mockRpc.GetBootstrap([32]byte{}) + if err != nil { + t.Fatalf("GetBootstrap failed: %v", err) + } + if bootstrap.Header.Slot != 1000 { + t.Errorf("Expected bootstrap slot to be 1000, got %d", bootstrap.Header.Slot) + } } -func TestNimbusGetUpdates(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/eth/v1/beacon/light_client/updates", r.URL.Path) - assert.Equal(t, "start_period=1000&count=5", r.URL.RawQuery) - response := UpdateResponse{ - {Data: consensus_core.Update{AttestedHeader: consensus_core.Header{Slot: 1000}}}, - {Data: consensus_core.Update{AttestedHeader: consensus_core.Header{Slot: 1001}}}, - } - err := json.NewEncoder(w).Encode(response) - require.NoError(t, err) - })) - defer server.Close() - nimbusRpc := NewNimbusRpc(server.URL) - updates, err := nimbusRpc.GetUpdates(1000, 5) - assert.NoError(t, err) - assert.Len(t, updates, 2) - assert.Equal(t, uint64(1000), updates[0].AttestedHeader.Slot) - assert.Equal(t, uint64(1001), updates[1].AttestedHeader.Slot) +func TestGetUpdates(t *testing.T) { + tempDir, err := os.MkdirTemp("", "mock_rpc_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + mockUpdates := UpdateResponse{ + {Data: consensus_core.Update{SignatureSlot: 1}}, + {Data: consensus_core.Update{SignatureSlot: 2}}, + } + updatesJSON, _ := json.Marshal(mockUpdates) + err = os.WriteFile(filepath.Join(tempDir, "updates.json"), updatesJSON, 0644) + if err != nil { + t.Fatalf("Failed to write mock updates file: %v", err) + } + mockRpc := NewMockRpc(tempDir) + updates, err := mockRpc.GetUpdates(1, 2) + if err != nil { + t.Fatalf("GetUpdates failed: %v", err) + } + if len(updates) != 2 { + t.Errorf("Expected 2 updates, got %d", len(updates)) + } + if updates[0].SignatureSlot != 1 || updates[1].SignatureSlot != 2 { + t.Errorf("Unexpected update signature slots") + } } -func TestNimbusGetFinalityUpdate(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/eth/v1/beacon/light_client/finality_update", r.URL.Path) - response := FinalityUpdateResponse{ - Data: consensus_core.FinalityUpdate{ - FinalizedHeader: consensus_core.Header{ - Slot: 2000, - }, +func TestGetFinalityUpdate(t *testing.T) { + tempDir, err := os.MkdirTemp("", "mock_rpc_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + mockFinality := FinalityUpdateResponse{ + Data: consensus_core.FinalityUpdate{ + FinalizedHeader: consensus_core.Header{ + Slot: 2000, }, - } - err := json.NewEncoder(w).Encode(response) - require.NoError(t, err) - })) - defer server.Close() - nimbusRpc := NewNimbusRpc(server.URL) - finalityUpdate, err := nimbusRpc.GetFinalityUpdate() - assert.NoError(t, err) - assert.Equal(t, uint64(2000), finalityUpdate.FinalizedHeader.Slot) + }, + } + finalityJSON, _ := json.Marshal(mockFinality) + err = os.WriteFile(filepath.Join(tempDir, "finality.json"), finalityJSON, 0644) + if err != nil { + t.Fatalf("Failed to write mock finality file: %v", err) + } + mockRpc := NewMockRpc(tempDir) + finality, err := mockRpc.GetFinalityUpdate() + if err != nil { + t.Fatalf("GetFinalityUpdate failed: %v", err) + } + if finality.FinalizedHeader.Slot != 2000 { + t.Errorf("Expected finality slot to be 2000, got %d", finality.FinalizedHeader.Slot) + } } -func TestNimbusGetOptimisticUpdate(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/eth/v1/beacon/light_client/optimistic_update", r.URL.Path) - response := OptimisticUpdateResponse{ - Data: consensus_core.OptimisticUpdate{ - SignatureSlot: 3000, - }, - } - err := json.NewEncoder(w).Encode(response) - require.NoError(t, err) - })) - defer server.Close() - nimbusRpc := NewNimbusRpc(server.URL) - optimisticUpdate, err := nimbusRpc.GetOptimisticUpdate() - assert.NoError(t, err) - assert.Equal(t, uint64(3000), optimisticUpdate.SignatureSlot) +func TestGetOptimisticUpdate(t *testing.T) { + tempDir, err := os.MkdirTemp("", "mock_rpc_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + mockOptimistic := OptimisticUpdateResponse{ + Data: consensus_core.OptimisticUpdate{ + SignatureSlot: 3000, + }, + } + optimisticJSON, _ := json.Marshal(mockOptimistic) + err = os.WriteFile(filepath.Join(tempDir, "optimistic.json"), optimisticJSON, 0644) + if err != nil { + t.Fatalf("Failed to write mock optimistic file: %v", err) + } + mockRpc := NewMockRpc(tempDir) + optimistic, err := mockRpc.GetOptimisticUpdate() + if err != nil { + t.Fatalf("GetOptimisticUpdate failed: %v", err) + } + if optimistic.SignatureSlot != 3000 { + t.Errorf("Expected optimistic signature slot to be 3000, got %d", optimistic.SignatureSlot) + } } -func TestNimbusGetBlock(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/eth/v2/beacon/blocks/4000", r.URL.Path) - response := BeaconBlockResponse{ - Data: BeaconBlockData{ - Message: consensus_core.BeaconBlock{ - Slot: 4000, - }, +func TestGetBlock(t *testing.T) { + tempDir, err := os.MkdirTemp("", "mock_rpc_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + blocksDir := filepath.Join(tempDir, "blocks") + err = os.Mkdir(blocksDir, 0755) + if err != nil { + t.Fatalf("Failed to create blocks directory: %v", err) + } + mockBlock := BeaconBlockResponse{ + Data: struct { + Message consensus_core.BeaconBlock + }{ + Message: consensus_core.BeaconBlock{ + Slot: 4000, }, - } - err := json.NewEncoder(w).Encode(response) - require.NoError(t, err) - })) - defer server.Close() - nimbusRpc := NewNimbusRpc(server.URL) - block, err := nimbusRpc.GetBlock(4000) - assert.NoError(t, err) - assert.Equal(t, uint64(4000), block.Slot) + }, + } + blockJSON, _ := json.Marshal(mockBlock) + err = os.WriteFile(filepath.Join(blocksDir, "4000.json"), blockJSON, 0644) + if err != nil { + t.Fatalf("Failed to write mock block file: %v", err) + } + mockRpc := NewMockRpc(tempDir) + block, err := mockRpc.GetBlock(4000) + if err != nil { + t.Fatalf("GetBlock failed: %v", err) + } + if block.Slot != 4000 { + t.Errorf("Expected block slot to be 4000, got %d", block.Slot) + } } -func TestNimbusChainId(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/eth/v1/config/spec", r.URL.Path) - response := SpecResponse{ - Data: Spec{ - ChainId: 5000, - }, - } - err := json.NewEncoder(w).Encode(response) - require.NoError(t, err) - })) - defer server.Close() - nimbusRpc := NewNimbusRpc(server.URL) - chainId, err := nimbusRpc.ChainId() - assert.NoError(t, err) - assert.Equal(t, uint64(5000), chainId) +func TestChainId(t *testing.T) { + mockRpc := NewMockRpc("/tmp/testdata") + _, err := mockRpc.ChainId() + if err == nil || err.Error() != "not implemented" { + t.Errorf("Expected 'not implemented' error, got %v", err) + } } From 1eb60402ed407218a33ca10becb0adec19a1911a Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Tue, 1 Oct 2024 23:07:24 +0530 Subject: [PATCH 07/10] Refactor consensus.go --- consensus/consensus.go | 251 +++++++++++++++++++++++++++-------------- 1 file changed, 165 insertions(+), 86 deletions(-) diff --git a/consensus/consensus.go b/consensus/consensus.go index 2a25cf3..04cf710 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -6,7 +6,6 @@ package consensus // uses common for datatypes import ( "bytes" - "context" "encoding/hex" "fmt" "log" @@ -181,48 +180,72 @@ func (con ConsensusClient) Expected_current_slot() uint64 { } func sync_fallback(inner *Inner, fallback *string) error { - cf, err := (&checkpoints.CheckpointFallback{}).FetchLatestCheckpointFromApi(*fallback) - if err != nil { - return errors.Wrap(err, "failed to fetch checkpoint from API") - } - return inner.sync(cf) + // Create a buffered channel to receive any errors from the goroutine + errorChan := make(chan error, 1) + + go func() { + // Attempt to fetch the latest checkpoint from the API + cf, err := (&checkpoints.CheckpointFallback{}).FetchLatestCheckpointFromApi(*fallback) + if err != nil { + + errorChan <- err + return + } + + if err := inner.sync(cf); err != nil { + + errorChan <- err + return + } + + errorChan <- nil + }() + return <-errorChan } + func sync_all_fallback(inner *Inner, chainID uint64) error { var n config.Network network, err := n.ChainID(chainID) if err != nil { return err } + errorChan := make(chan error, 1) - ch := checkpoints.CheckpointFallback{} + go func() { - checkpointFallback, errWhileCheckpoint := ch.Build() - if errWhileCheckpoint != nil { - return err - } + ch := checkpoints.CheckpointFallback{} - chainId := network.Chain.ChainID - var networkName config.Network - if chainId == 1 { - networkName = config.MAINNET - } else if chainId == 5 { - networkName = config.GOERLI - } else if chainId == 11155111 { - networkName = config.SEPOLIA - } else { - return errors.New("chain id not recognized") - } + checkpointFallback, errWhileCheckpoint := ch.Build() + if errWhileCheckpoint != nil { + errorChan <- errWhileCheckpoint + return + } - // Fetch the latest checkpoint from the network - checkpoint := checkpointFallback.FetchLatestCheckpoint(networkName) + chainId := network.Chain.ChainID + var networkName config.Network + if chainId == 1 { + networkName = config.MAINNET + } else if chainId == 5 { + networkName = config.GOERLI + } else if chainId == 11155111 { + networkName = config.SEPOLIA + } else { + errorChan <- errors.New("chain id not recognized") + return + } - // Sync using the inner struct's sync method - if err := inner.sync(checkpoint); err != nil { - return err - } + // Fetch the latest checkpoint from the network + checkpoint := checkpointFallback.FetchLatestCheckpoint(networkName) - return nil + // Sync using the inner struct's sync method + if err := inner.sync(checkpoint); err != nil { + errorChan <- err + } + + errorChan <- nil + }() + return <-errorChan } func (in *Inner) New(rpcURL string, blockSend chan common.Block, finalizedBlockSend chan *common.Block, checkpointSend chan *[]byte, config *config.Config) *Inner { @@ -240,21 +263,40 @@ func (in *Inner) New(rpcURL string, blockSend chan common.Block, finalizedBlockS } func (in *Inner) Check_rpc() error { - chainID, err := in.RPC.ChainId() - if err != nil { - return err - } - if chainID != in.Config.Chain.ChainID { - return ErrIncorrectRpcNetwork - } - return nil + errorChan := make(chan error, 1) + + go func() { + chainID, err := in.RPC.ChainId() + if err != nil { + errorChan <- err + return + } + if chainID != in.Config.Chain.ChainID { + errorChan <- ErrIncorrectRpcNetwork + return + } + errorChan <- nil + }() + return <-errorChan } -func (in *Inner) get_execution_payload(ctx context.Context, slot *uint64) (*consensus_core.ExecutionPayload, error) { - block, err := in.RPC.GetBlock(*slot) - if err != nil { +func (in *Inner) get_execution_payload(slot *uint64) (*consensus_core.ExecutionPayload, error) { + errorChan := make(chan error, 1) + blockChan := make(chan consensus_core.BeaconBlock, 1) + go func() { + var err error + block, err := in.RPC.GetBlock(*slot) + if err != nil { + errorChan <- err + } + errorChan <- nil + blockChan <- block + }() + + if err := <-errorChan; err != nil { return nil, err } + block := <-blockChan blockHash, err := utils.TreeHashRoot(block.Body.ToBytes()) if err != nil { return nil, err @@ -288,7 +330,7 @@ func (in *Inner) get_execution_payload(ctx context.Context, slot *uint64) (*cons return &payload, nil } -func (in *Inner) Get_payloads(ctx context.Context, startSlot, endSlot uint64) ([]interface{}, error) { +func (in *Inner) Get_payloads(startSlot, endSlot uint64) ([]interface{}, error) { var payloads []interface{} // Fetch the block at endSlot to get the initial parent hash @@ -345,11 +387,22 @@ func (in *Inner) Get_payloads(ctx context.Context, startSlot, endSlot uint64) ([ } } func (in *Inner) advance() error { - // Fetch and apply finality update - finalityUpdate, err := in.RPC.GetFinalityUpdate() - if err != nil { - return err + ErrorChan := make(chan error, 1) + finalityChan := make(chan consensus_core.FinalityUpdate, 1) + + go func() { + finalityUpdate, err := in.RPC.GetFinalityUpdate() + if err != nil { + ErrorChan <- err + return + } + finalityChan <- finalityUpdate + ErrorChan <- nil + }() + if ErrorChan != nil { + return <-ErrorChan } + finalityUpdate := <-finalityChan if err := in.verify_finality_update(&finalityUpdate); err != nil { return err } @@ -394,60 +447,72 @@ func (in *Inner) sync(checkpoint [32]byte) error { // Perform bootstrap with the given checkpoint in.bootstrap(checkpoint) - // Calculate the current sync period + currentPeriod := utils.CalcSyncPeriod(in.Store.FinalizedHeader.Slot) - // Fetch updates - updates, err := in.RPC.GetUpdates(currentPeriod, MAX_REQUEST_LIGHT_CLIENT_UPDATES) - if err != nil { - return err - } + errorChan := make(chan error, 1) + var updates []consensus_core.Update + var err error + go func() { + updates, err = in.RPC.GetUpdates(currentPeriod, MAX_REQUEST_LIGHT_CLIENT_UPDATES) + if err != nil { + errorChan <- err + } - // Apply updates - for _, update := range updates { - if err := in.verify_update(&update); err != nil { - return err + // Apply updates + for _, update := range updates { + if err := in.verify_update(&update); err != nil { + errorChan <- err + return + } + in.apply_update(&update) } - in.apply_update(&update) - } - // Fetch and apply finality update - finalityUpdate, err := in.RPC.GetFinalityUpdate() - if err != nil { - return err - } - if err := in.verify_finality_update(&finalityUpdate); err != nil { - return err - } - in.apply_finality_update(&finalityUpdate) + finalityUpdate, err := in.RPC.GetFinalityUpdate() + if err != nil { + errorChan <- err + return + } + if err := in.verify_finality_update(&finalityUpdate); err != nil { + errorChan <- err + return + } + in.apply_finality_update(&finalityUpdate) - // Fetch and apply optimistic update + // Fetch and apply optimistic update - optimisticUpdate, err := in.RPC.GetOptimisticUpdate() - if err != nil { - return err - } - if err := in.verify_optimistic_update(&optimisticUpdate); err != nil { + optimisticUpdate, err := in.RPC.GetOptimisticUpdate() + if err != nil { + errorChan <- err + return + } + if err := in.verify_optimistic_update(&optimisticUpdate); err != nil { + errorChan <- err + return + } + in.apply_optimistic_update(&optimisticUpdate) + errorChan <- nil + log.Printf("consensus client in sync with checkpoint: 0x%s", hex.EncodeToString(checkpoint[:])) + }() + + if err := <-errorChan; err != nil { return err } - in.apply_optimistic_update(&optimisticUpdate) - // Log the success message - log.Printf("consensus client in sync with checkpoint: 0x%s", hex.EncodeToString(checkpoint[:])) return nil } func (in *Inner) send_blocks() error { // Get slot from the optimistic header slot := in.Store.OptimisticHeader.Slot - payload, err := in.get_execution_payload(context.Background(), &slot) + payload, err := in.get_execution_payload(&slot) if err != nil { return err } // Get finalized slot from the finalized header finalizedSlot := in.Store.FinalizedHeader.Slot - finalizedPayload, err := in.get_execution_payload(context.Background(), &finalizedSlot) + finalizedPayload, err := in.get_execution_payload(&finalizedSlot) if err != nil { return err } @@ -493,12 +558,25 @@ func (in *Inner) duration_until_next_update() time.Duration { return time.Duration(nextUpdate) * time.Second } func (in *Inner) bootstrap(checkpoint [32]byte) { - - bootstrap, errInBootstrap := in.RPC.GetBootstrap(checkpoint) - if errInBootstrap != nil { - log.Printf("failed to fetch bootstrap: %v", errInBootstrap) + errorChan := make(chan error, 1) + bootstrapChan := make(chan consensus_core.Bootstrap, 1) + go func() { + bootstrap, errInBootstrap := in.RPC.GetBootstrap(checkpoint) + + if errInBootstrap != nil { + log.Printf("failed to fetch bootstrap: %v", errInBootstrap) + errorChan <- errInBootstrap + return + } + bootstrapChan <- bootstrap + errorChan <- nil + }() + if err := <-errorChan; err != nil { return } + bootstrap := <-bootstrapChan + + isValid := in.is_valid_checkpoint(bootstrap.Header.Slot) if !isValid { @@ -547,7 +625,7 @@ func apply_bootstrap(store *LightClientStore, bootstrap consensus_core.Bootstrap func (in *Inner) verify_generic_update(update *GenericUpdate, expectedCurrentSlot uint64, store *LightClientStore, genesisRoots []byte, forks consensus_core.Forks) error { { - bits := getBits(update.SyncAggregate.SyncCommitteeBits) + bits := getBits(update.SyncAggregate.SyncCommitteeBits[:]) if bits == 0 { return ErrInsufficientParticipation } @@ -614,6 +692,7 @@ func (in *Inner) verify_generic_update(update *GenericUpdate, expectedCurrentSlo forkVersion := utils.CalculateForkVersion(&forks, update.SignatureSlot) forkDataRoot := utils.ComputeForkDataRoot(forkVersion, consensus_core.Bytes32(in.Config.Chain.GenesisRoot)) + if !verifySyncCommitteeSignature(pks, &update.AttestedHeader, &update.SyncAggregate.SyncCommitteeSignature, forkDataRoot) { return ErrInvalidSignature @@ -653,7 +732,7 @@ func (in *Inner) verify_optimistic_update(update *consensus_core.OptimisticUpdat return in.verify_generic_update(&genUpdate, in.expected_current_slot(), &in.Store, in.Config.Chain.GenesisRoot, in.Config.Forks) } func (in *Inner) apply_generic_update(store *LightClientStore, update *GenericUpdate) *[]byte { - committeeBits := getBits(update.SyncAggregate.SyncCommitteeBits) + committeeBits := getBits(update.SyncAggregate.SyncCommitteeBits[:]) // Update max active participants if committeeBits > store.CurrentMaxActiveParticipants { @@ -766,7 +845,7 @@ func (in *Inner) apply_optimistic_update(update *consensus_core.OptimisticUpdate } } func (in *Inner) Log_finality_update(update *consensus_core.FinalityUpdate) { - participation := float32(getBits(update.SyncAggregate.SyncCommitteeBits)) / 512.0 * 100.0 + participation := float32(getBits(update.SyncAggregate.SyncCommitteeBits[:])) / 512.0 * 100.0 decimals := 2 if participation == 100.0 { decimals = 1 @@ -784,7 +863,7 @@ func (in *Inner) Log_finality_update(update *consensus_core.FinalityUpdate) { ) } func (in *Inner) Log_optimistic_update(update *consensus_core.OptimisticUpdate) { - participation := float32(getBits(update.SyncAggregate.SyncCommitteeBits)) / 512.0 * 100.0 + participation := float32(getBits(update.SyncAggregate.SyncCommitteeBits[:])) / 512.0 * 100.0 decimals := 2 if participation == 100.0 { decimals = 1 @@ -1005,7 +1084,7 @@ func processTransaction(txBytes *[1073741824]byte, blockHash consensus_core.Byte } // getBits counts the number of bits set to 1 in a [64]byte array -func getBits(bitfield [64]byte) uint64 { +func getBits(bitfield []byte) uint64 { var count uint64 for _, b := range bitfield { count += uint64(popCount(b)) From 0e552c150ed5873a2d8de35a5587de8f0623af92 Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Tue, 1 Oct 2024 23:15:04 +0530 Subject: [PATCH 08/10] Removed duplicated types and structs in basic.go --- consensus/types/basic.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/consensus/types/basic.go b/consensus/types/basic.go index b910edb..0ed1582 100644 --- a/consensus/types/basic.go +++ b/consensus/types/basic.go @@ -1,8 +1,3 @@ package types type Address = [20]byte -type Bytes32 = [32]byte -type LogsBloom = [256]byte -type BLSPubKey = [48]byte -type SignatureBytes = [96]byte -type Transaction = [1073741824]byte //1073741824 From 0c89f9bbb9194dc6639dade96783095e2750116b Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Tue, 1 Oct 2024 23:17:57 +0530 Subject: [PATCH 09/10] Refactor beacon.go to remove duplicxatoed types and structs --- consensus/types/beacon.go | 235 +++----------------------------------- 1 file changed, 16 insertions(+), 219 deletions(-) diff --git a/consensus/types/beacon.go b/consensus/types/beacon.go index 18ded48..00b89b9 100644 --- a/consensus/types/beacon.go +++ b/consensus/types/beacon.go @@ -1,230 +1,27 @@ package types -// Serialization and Deserialization for ExecutionPayload and BeaconBlockBody can be done by importing from prewritten functions in utils wherever needed. - - - -type BeaconBlock struct { - Slot uint64 - ProposerIndex uint64 - ParentRoot [32]byte - StateRoot [32]byte - Body BeaconBlockBody -} +import ( + "github.com/BlocSoc-iitr/selene/consensus/consensus_core" +) -// just implemented the deneb variant -type BeaconBlockBody struct { - RandaoReveal SignatureBytes `json:"randao_reveal"` - Eth1Data Eth1Data `json:"eth1_data"` - Graffiti Bytes32 `json:"graffiti"` - ProposerSlashings [16]ProposerSlashing `json:"proposer_slashings"` // max length 16 to be ensured - AttesterSlashings [2]AttesterSlashing `json:"attester_slashings"` // max length 2 to be ensured - Attestations [128]Attestation `json:"attestations"` // max length 128 to be ensured - Deposits [16]Deposit `json:"deposits"` // max length 16 to be ensured - VoluntaryExits [16]SignedVoluntaryExit `json:"voluntary_exits"` // max length 16 to be ensured - SyncAggregate SyncAggregate `json:"sync_aggregate"` - ExecutionPayload ExecutionPayload `json:"execution_payload"` - BlsToExecutionChanges [16]SignedBlsToExecutionChange `json:"bls_to_execution_changes"` // max length 16 to be ensured - BlobKzgCommitments [4096][48]byte `json:"blob_kzg_commitments"` // max length 4096 to be ensured -} // 1 method - -func (b *BeaconBlockBody) Def() { - b.RandaoReveal = SignatureBytes{} - b.Eth1Data = Eth1Data{} - b.Graffiti = Bytes32{} - b.ProposerSlashings = [16]ProposerSlashing{} - b.AttesterSlashings = [2]AttesterSlashing{} - b.Attestations = [128]Attestation{} - b.Deposits = [16]Deposit{} - b.VoluntaryExits = [16]SignedVoluntaryExit{} - b.SyncAggregate = SyncAggregate{} - b.ExecutionPayload = ExecutionPayload{} - b.BlsToExecutionChanges = [16]SignedBlsToExecutionChange{} - b.BlobKzgCommitments = [4096][48]byte{} -} - -type SignedBlsToExecutionChange struct { - Message BlsToExecutionChange - Signature SignatureBytes -} -type BlsToExecutionChange struct { - ValidatorIndex uint64 - FromBlsPubkey [48]byte -} - -type ExecutionPayload struct { - ParentHash Bytes32 `json:"parent_hash"` - FeeRecipient Address `json:"fee_recipient"` - StateRoot Bytes32 `json:"state_root"` - ReceiptsRoot Bytes32 `json:"receipts_root"` - LogsBloom LogsBloom `json:"logs_bloom"` - PrevRandao Bytes32 `json:"prev_randao"` - BlockNumber uint64 `json:"block_number"` - GasLimit uint64 `json:"gas_limit"` - GasUsed uint64 `json:"gas_used"` - Timestamp uint64 `json:"timestamp"` - ExtraData [32]byte `json:"extra_data"` - BaseFeePerGas uint64 `json:"base_fee_per_gas"` - BlockHash Bytes32 `json:"block_hash"` - Transactions [1073741824]byte `json:"transactions"` // max length 1073741824 to be implemented - Withdrawals [16]Withdrawal `json:"withdrawals"` // max length 16 to be implemented - BlobGasUsed uint64 `json:"blob_gas_used"` // Deneb variant only - ExcessBlobGas uint64 `json:"excess_blob_gas"` // Deneb variant only -} // 1 method - -func (exe *ExecutionPayload) Def() { - exe.ParentHash = Bytes32{} - exe.FeeRecipient = Address{} - exe.StateRoot = Bytes32{} - exe.ReceiptsRoot = Bytes32{} - exe.LogsBloom = LogsBloom{} - exe.PrevRandao = Bytes32{} - exe.BlockNumber = 0 - exe.GasLimit = 0 - exe.GasUsed = 0 - exe.Timestamp = 0 - exe.ExtraData = [32]byte{} - exe.BaseFeePerGas = 0 - exe.BlockHash = Bytes32{} - exe.Transactions = [1073741824]byte{} // max length 1073741824 to be implemented - exe.Withdrawals = [16]Withdrawal{} // max length 16 to be implemented - exe.BlobGasUsed = 0 // Only for Deneb - exe.ExcessBlobGas = 0 // Only for Deneb -} // default - - - -type Withdrawal struct { - Index uint64 - Amount uint64 - Address Address - ValidatorIndex uint64 -} -type ProposalSlashing struct { - SignedHeader1 SignedBeaconBlockHeader - SignedHeader2 SignedBeaconBlockHeader -} -type SignedBeaconBlockHeader struct { - Message BeaconBlockHeader - Signature SignatureBytes -} -type AttesterSlashing struct { - Attestation1 IndexedAttestation - Attestation2 IndexedAttestation -} -type IndexedAttestation struct { - AttestingIndices [2048]uint64 - Data AttestationData - Signature SignatureBytes -} -type Attestation struct { - AggregateBits [2048]bool - Data AttestationData - Signature SignatureBytes -} -type AttestationData struct { - Slot uint64 - Index uint64 - BeaconBlockRoot Bytes32 - Source Checkpoint - Target Checkpoint -} -type Checkpoint struct { - Epoch uint64 - Root Bytes32 -} -type SignedVoluntaryExit struct { - Message VoluntaryExit - Signature SignatureBytes -} -type VoluntaryExit struct { - Epoch uint64 - ValidatorIndex uint64 -} -type Deposit struct { - Proof [33]byte - Data DepositData -} -type DepositData struct { - Pubkey [48]byte - WitdrawalCredentials [32]byte - Amount uint64 - Signature SignatureBytes -} -type Eth1Data struct { - DepositRoot Bytes32 - DepositCount uint64 - BlockHash Bytes32 -} -type BeaconBlockHeader struct { - Slot uint64 - ProposeIndex uint64 - ParentRoot Bytes32 - StateRoot Bytes32 - BodyRoot Bytes32 -} -type Update struct { - AttestedHeader Header - NextSyncCommittee SyncCommittee - NextSyncCommitteBranch []Bytes32 - FinalizedHeader Header - FinalizedBranch []Bytes32 - SyncAggregate SyncAggregate - SignatureSlot uint64 -} -type FinalityUpdate struct { - AttestedHeader Header - FinalizedHeader Header - FinalizedBranch []Bytes32 - SyncAggregate SyncAggregate - SignatureSlot uint64 -} -type OptimisticUpdate struct { - AttestedHeader Header - SyncAggregate SyncAggregate - SignatureSlot uint64 -} -type Bootstrap struct { - Header Header - CurrentSyncCommittee SyncCommittee - CurrentSyncCommitteeBranch []Bytes32 -} +// Serialization and Deserialization for ExecutionPayload and BeaconBlockBody can be done by importing from prewritten functions in utils wherever needed. -type Header struct { - Slot uint64 - ProposerIndex uint64 - ParentRoot Bytes32 - StateRoot Bytes32 - BodyRoot Bytes32 -} -type SyncCommittee struct { - Pubkeys [512]BLSPubKey - AggregatePubkey BLSPubKey -} -type SyncAggregate struct { - SyncCommitteeBits [512]bool - SyncCommitteeSignature SignatureBytes -} -type ProposerSlashing struct { - SignedHeader1 SignedBeaconBlockHeader - SignedHeader2 SignedBeaconBlockHeader -} type GenericUpdate struct { - AttestedHeader Header - SyncAggregate SyncAggregate + AttestedHeader consensus_core.Header + SyncAggregate consensus_core.SyncAggregate SignatureSlot uint64 - NextSyncCommittee SyncCommittee - NextSyncCommitteeBranch []Bytes32 - FinalizedHeader Header - FinalityBranch []Bytes32 + NextSyncCommittee consensus_core.SyncCommittee + NextSyncCommitteeBranch []consensus_core.Bytes32 + FinalizedHeader consensus_core.Header + FinalityBranch []consensus_core.Bytes32 } func (g *GenericUpdate) From() { - g.AttestedHeader = Header{} - g.SyncAggregate = SyncAggregate{} + g.AttestedHeader = consensus_core.Header{} + g.SyncAggregate = consensus_core.SyncAggregate{} g.SignatureSlot = 0 - g.NextSyncCommittee = SyncCommittee{} - g.NextSyncCommitteeBranch = [][32]byte{} - g.FinalizedHeader = Header{} - g.FinalityBranch = [][32]byte{} + g.NextSyncCommittee = consensus_core.SyncCommittee{} + g.NextSyncCommitteeBranch = []consensus_core.Bytes32{} + g.FinalizedHeader = consensus_core.Header{} + g.FinalityBranch = []consensus_core.Bytes32{} } From 61b69d4b862f1797e5998067274145dc57b59bcd Mon Sep 17 00:00:00 2001 From: Sambhav Jain <136801346+DarkLord017@users.noreply.github.com> Date: Tue, 1 Oct 2024 23:18:35 +0530 Subject: [PATCH 10/10] Update consensus_core.go to remove import cycle errors after refactoring types --- consensus/consensus_core/consensus_core.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/consensus/consensus_core/consensus_core.go b/consensus/consensus_core/consensus_core.go index aab009b..84b199c 100644 --- a/consensus/consensus_core/consensus_core.go +++ b/consensus/consensus_core/consensus_core.go @@ -3,7 +3,6 @@ package consensus_core import ( "bytes" - "github.com/BlocSoc-iitr/selene/consensus/types" "github.com/ugorji/go/codec" ) @@ -12,6 +11,7 @@ type BLSPubKey [48]byte type Address [20]byte type LogsBloom [256]byte type SignatureBytes [96]byte +type Transaction = [1073741824]byte //1073741824 type BeaconBlock struct { Slot uint64 @@ -125,10 +125,10 @@ type ExecutionPayload struct { ExtraData [32]byte BaseFeePerGas uint64 BlockHash Bytes32 - Transactions []types.Transaction `ssz-max:"1048576"` - Withdrawals []types.Withdrawal `ssz-max:"16"` - BlobGasUsed *uint64 // Deneb-specific field, use pointer for optionality - ExcessBlobGas *uint64 // Deneb-specific field, use pointer for optionality + Transactions []Transaction `ssz-max:"1048576"` + Withdrawals []Withdrawal `ssz-max:"16"` + BlobGasUsed *uint64 // Deneb-specific field, use pointer for optionality + ExcessBlobGas *uint64 // Deneb-specific field, use pointer for optionality } type SignedBlsToExecutionChange struct {