Skip to content

Commit

Permalink
Changed how loading works.
Browse files Browse the repository at this point in the history
  • Loading branch information
StefanIliev545 committed Dec 16, 2024
1 parent 75ef65b commit aaeac32
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 60 deletions.
11 changes: 11 additions & 0 deletions go/common/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"math/big"

gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/params"

"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -196,3 +197,13 @@ func (cf *ChainFork) String() string {
func MaskedSender(address L2Address) L2Address {
return common.BigToAddress(big.NewInt(0).Sub(address.Big(), big.NewInt(1)))
}

type SystemContractAddresses map[string]*gethcommon.Address

func (s *SystemContractAddresses) ToString() string {
var str string
for name, addr := range *s {
str += fmt.Sprintf("%s: %s; ", name, addr.Hex())
}
return str
}
2 changes: 1 addition & 1 deletion go/enclave/crosschain/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ type Manager interface {
GetBusAddress() *common.L2Address

// Initialize - Derives the address of the message bus contract.
Initialize(systemAddresses system.SystemContractAddresses) error
Initialize(systemAddresses common.SystemContractAddresses) error

// GenerateMessageBusDeployTx - Returns a signed message bus deployment transaction.
GenerateMessageBusDeployTx() (*common.L2Tx, error)
Expand Down
3 changes: 1 addition & 2 deletions go/enclave/crosschain/message_bus_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/holiman/uint256"

"github.com/ten-protocol/go-ten/go/enclave/core"
"github.com/ten-protocol/go-ten/go/enclave/system"

"github.com/ten-protocol/go-ten/go/enclave/storage"

Expand Down Expand Up @@ -79,7 +78,7 @@ func (m *MessageBusManager) GetBusAddress() *common.L2Address {
}

// DeriveMessageBusAddress - Derives the address of the message bus contract.
func (m *MessageBusManager) Initialize(systemAddresses system.SystemContractAddresses) error {
func (m *MessageBusManager) Initialize(systemAddresses common.SystemContractAddresses) error {
address, ok := systemAddresses["MessageBus"]
if !ok {
return fmt.Errorf("message bus contract not found in system addresses")
Expand Down
2 changes: 1 addition & 1 deletion go/enclave/enclave.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func NewEnclave(config *enclaveconfig.EnclaveConfig, genesis *genesis.Genesis, m

// initialise system contracts
scb := system.NewSystemContractCallbacks(storage, &config.SystemContractOwner, logger)
err = scb.Load()
err = scb.Load(crossChainProcessors.Local)
if err != nil && !errors.Is(err, errutil.ErrNotFound) {
logger.Crit("failed to load system contracts", log.ErrKey, err)
}
Expand Down
6 changes: 6 additions & 0 deletions go/enclave/storage/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@ type EnclaveKeyStorage interface {
GetEnclaveKey(ctx context.Context) ([]byte, error)
}

type SystemContractAddressesStorage interface {
StoreSystemContractAddresses(ctx context.Context, addresses common.SystemContractAddresses) error
GetSystemContractAddresses(ctx context.Context) (common.SystemContractAddresses, error)
}

// Storage is the enclave's interface for interacting with the enclave's datastore
type Storage interface {
BlockResolver
Expand All @@ -132,6 +137,7 @@ type Storage interface {
CrossChainMessagesStorage
EnclaveKeyStorage
ScanStorage
SystemContractAddressesStorage
io.Closer

// HealthCheck returns whether the storage is deemed healthy or not
Expand Down
43 changes: 41 additions & 2 deletions go/enclave/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"crypto/ecdsa"
"database/sql"
"encoding/json"
"errors"
"fmt"
"math/big"
Expand Down Expand Up @@ -41,8 +42,9 @@ import (
// these are the keys from the config table
const (
// todo - this will require a dedicated table when upgrades are implemented
masterSeedCfg = "MASTER_SEED"
enclaveKeyCfg = "ENCLAVE_KEY"
masterSeedCfg = "MASTER_SEED"
enclaveKeyCfg = "ENCLAVE_KEY"
systemContractAddressesCfg = "SYSTEM_CONTRACT_ADDRESSES"
)

type AttestedEnclave struct {
Expand Down Expand Up @@ -872,3 +874,40 @@ func (s *storageImpl) ReadEventType(ctx context.Context, contractAddress gethcom
func (s *storageImpl) logDuration(method string, stopWatch *measure.Stopwatch) {
core.LogMethodDuration(s.logger, stopWatch, fmt.Sprintf("Storage::%s completed", method))
}

func (s *storageImpl) StoreSystemContractAddresses(ctx context.Context, addresses common.SystemContractAddresses) error {
defer s.logDuration("StoreSystemContractAddresses", measure.NewStopwatch())

dbTx, err := s.db.NewDBTransaction(ctx)
if err != nil {
return fmt.Errorf("could not create DB transaction - %w", err)
}
defer dbTx.Rollback()

addressesBytes, err := json.Marshal(addresses)
if err != nil {
return fmt.Errorf("could not marshal system contract addresses - %w", err)
}
_, err = enclavedb.WriteConfig(ctx, dbTx, systemContractAddressesCfg, addressesBytes)
if err != nil {
return fmt.Errorf("could not write system contract addresses - %w", err)
}

if err := dbTx.Commit(); err != nil {
return fmt.Errorf("could not commit system contract addresses - %w", err)
}
return nil
}

func (s *storageImpl) GetSystemContractAddresses(ctx context.Context) (common.SystemContractAddresses, error) {
defer s.logDuration("GetSystemContractAddresses", measure.NewStopwatch())
addressesBytes, err := enclavedb.FetchConfig(ctx, s.db.GetSQLDB(), systemContractAddressesCfg)
if err != nil {
return nil, fmt.Errorf("could not fetch system contract addresses - %w", err)
}
var addresses common.SystemContractAddresses
if err := json.Unmarshal(addressesBytes, &addresses); err != nil {
return nil, fmt.Errorf("could not unmarshal system contract addresses - %w", err)
}
return addresses, nil
}
12 changes: 1 addition & 11 deletions go/enclave/system/contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func VerifyLogs(receipt *types.Receipt) error {
return nil
}

func DeriveAddresses(receipt *types.Receipt) (SystemContractAddresses, error) {
func DeriveAddresses(receipt *types.Receipt) (common.SystemContractAddresses, error) {
if receipt.Status != types.ReceiptStatusSuccessful {
return nil, fmt.Errorf("cannot derive system contract addresses from failed receipt")
}
Expand Down Expand Up @@ -76,13 +76,3 @@ func DeriveAddresses(receipt *types.Receipt) (SystemContractAddresses, error) {

return addresses, nil
}

type SystemContractAddresses map[string]*gethcommon.Address

func (s *SystemContractAddresses) ToString() string {
var str string
for name, addr := range *s {
str += fmt.Sprintf("%s: %s; ", name, addr.Hex())
}
return str
}
79 changes: 36 additions & 43 deletions go/enclave/system/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type SystemContractCallbacks interface {
PublicSystemContracts() map[string]*gethcommon.Address
// Initialization
Initialize(batch *core.Batch, receipts types.Receipt, msgBusManager SystemContractsInitializable) error
Load() error
Load(msgBusManager SystemContractsInitializable) error

// Usage
CreateOnBatchEndTransaction(ctx context.Context, stateDB *state.StateDB, results core.TxExecResults) (*types.Transaction, error)
Expand All @@ -46,13 +46,13 @@ type SystemContractCallbacks interface {
}

type SystemContractsInitializable interface {
Initialize(SystemContractAddresses) error
Initialize(common.SystemContractAddresses) error
}

type systemContractCallbacks struct {
transactionsPostProcessorAddress *gethcommon.Address
storage storage.Storage
systemAddresses SystemContractAddresses
systemAddresses common.SystemContractAddresses
systemContractsUpgrader *gethcommon.Address

logger gethlog.Logger
Expand All @@ -63,7 +63,7 @@ func NewSystemContractCallbacks(storage storage.Storage, upgrader *gethcommon.Ad
transactionsPostProcessorAddress: nil,
logger: logger,
storage: storage,
systemAddresses: make(SystemContractAddresses),
systemAddresses: make(common.SystemContractAddresses),
systemContractsUpgrader: upgrader,
}
}
Expand All @@ -84,75 +84,68 @@ func (s *systemContractCallbacks) PublicSystemContracts() map[string]*gethcommon
return s.systemAddresses
}

func (s *systemContractCallbacks) Load() error {
func (s *systemContractCallbacks) Load(msgBusManager SystemContractsInitializable) error {
s.logger.Info("Load: Initializing system contracts")

if s.storage == nil {
s.logger.Error("Load: Storage is not set")
return fmt.Errorf("storage is not set")
}

batchSeqNo := uint64(2)
s.logger.Debug("Load: Fetching batch", "batchSeqNo", batchSeqNo)
batch, err := s.storage.FetchBatchBySeqNo(context.Background(), batchSeqNo)
addresses, err := s.storage.GetSystemContractAddresses(context.Background())
if err != nil {
s.logger.Error("Load: Failed fetching batch", "batchSeqNo", batchSeqNo, "error", err)
return fmt.Errorf("failed fetching batch %w", err)
s.logger.Error("Load: Failed fetching system contract addresses", "error", err)
return fmt.Errorf("failed fetching system contract addresses %w", err)
}
s.logger.Info("Load: Fetched system contract addresses", "addresses", addresses)

tx, err := SystemDeployerInitTransaction(s.logger, *s.systemContractsUpgrader)
if err != nil {
s.logger.Error("Load: Failed creating system deployer init transaction", "error", err)
return fmt.Errorf("failed creating system deployer init transaction %w", err)
}

receipt, err := s.storage.GetFilteredInternalReceipt(context.Background(), tx.Hash(), nil, true)
if err != nil {
s.logger.Error("Load: Failed fetching receipt", "transactionHash", batch.Transactions[0].Hash().Hex(), "error", err)
return fmt.Errorf("failed fetching receipt %w", err)
}

addresses, err := DeriveAddresses(receipt.ToReceipt())
if err != nil {
s.logger.Error("Load: Failed deriving addresses", "error", err, "receiptHash", receipt.TxHash.Hex())
return fmt.Errorf("failed deriving addresses %w", err)
}

return s.initializeRequiredAddresses(addresses)
return s.initializeRequiredAddresses(addresses, msgBusManager)
}

func (s *systemContractCallbacks) initializeRequiredAddresses(addresses SystemContractAddresses) error {
func (s *systemContractCallbacks) initializeRequiredAddresses(addresses common.SystemContractAddresses, msgBusManager SystemContractsInitializable) error {
if addresses["TransactionsPostProcessor"] == nil {
return fmt.Errorf("required contract address TransactionsPostProcessor is nil")
}

s.transactionsPostProcessorAddress = addresses["TransactionsPostProcessor"]
s.systemAddresses = addresses

if err := msgBusManager.Initialize(addresses); err != nil {
s.logger.Error("Initialize: Failed deriving message bus address", "error", err)
return fmt.Errorf("failed deriving message bus address %w", err)
}

return nil
}

func (s *systemContractCallbacks) StoreSystemContractAddresses(addresses common.SystemContractAddresses) error {
return s.storage.StoreSystemContractAddresses(context.Background(), addresses)
}

func (s *systemContractCallbacks) Initialize(batch *core.Batch, receipt types.Receipt, msgBusManager SystemContractsInitializable) error {
s.logger.Info("Initialize: Starting initialization of system contracts", "batchSeqNo", batch.SeqNo())
if batch.SeqNo().Uint64() != common.L2SysContractGenesisSeqNo {
s.logger.Error("Initialize: Batch is not genesis", "batchSeqNo", batch.SeqNo)
return fmt.Errorf("batch is not genesis")
}

s.logger.Debug("Initialize: Deriving addresses from receipt", "transactionHash", receipt.TxHash.Hex())
addresses, err := DeriveAddresses(&receipt)
addresses, err := verifyAndDeriveAddresses(batch, &receipt)
if err != nil {
s.logger.Error("Initialize: Failed deriving addresses", "error", err, "receiptHash", receipt.TxHash.Hex())
return fmt.Errorf("failed deriving addresses %w", err)
s.logger.Error("Initialize: Failed verifying and deriving addresses", "error", err)
return fmt.Errorf("failed verifying and deriving addresses %w", err)
}

if err := msgBusManager.Initialize(addresses); err != nil {
s.logger.Error("Initialize: Failed deriving message bus address", "error", err)
return fmt.Errorf("failed deriving message bus address %w", err)
s.logger.Info("Initialize: Initializing required addresses", "addresses", addresses)
return s.initializeRequiredAddresses(addresses, msgBusManager)
}

func verifyAndDeriveAddresses(batch *core.Batch, receipt *types.Receipt) (common.SystemContractAddresses, error) {
if batch.SeqNo().Uint64() != common.L2SysContractGenesisSeqNo {
return nil, fmt.Errorf("batch is not genesis")
}

s.logger.Info("Initialize: Initializing required addresses", "addresses", addresses)
return s.initializeRequiredAddresses(addresses)
addresses, err := DeriveAddresses(receipt)
if err != nil {
return nil, fmt.Errorf("failed deriving addresses %w", err)
}

return addresses, nil
}

func (s *systemContractCallbacks) CreatePublicCallbackHandlerTransaction(ctx context.Context, l2State *state.StateDB) (*types.Transaction, error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package helpful

import (
"encoding/hex"
"fmt"
"math/big"
"os"
Expand All @@ -10,6 +11,7 @@ import (
"time"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ten-protocol/go-ten/go/ethadapter"
"github.com/ten-protocol/go-ten/go/wallet"
"github.com/ten-protocol/go-ten/integration/common/testlog"
Expand Down Expand Up @@ -43,6 +45,29 @@ func TestRunLocalNetwork(t *testing.T) {
keepRunning(networkConnector)
}

func TestGenerateKeys(t *testing.T) {
genKey := func() {
pk, err := crypto.GenerateKey()
if err != nil {
t.Fatal(err)
}
fmt.Println(hex.EncodeToString(crypto.FromECDSA(pk)))
fmt.Printf("Address: 0x%x\n", crypto.PubkeyToAddress(pk.PublicKey))
}

genKey()
genKey()
genKey()
}

func TestPrintAddress(t *testing.T) {
pk, err := crypto.HexToECDSA("c5f74c49670c0151261af346efb9022792585110bd45ed44933acfde5063067c")
if err != nil {
t.Fatal(err)
}
fmt.Println(crypto.PubkeyToAddress(pk.PublicKey))
}

func TestRunLocalGatewayAgainstRemoteTestnet(t *testing.T) {
networktest.TestOnlyRunsInIDE(t)
networktest.EnsureTestLogsSetUp("local-faucet-remote-testnet")
Expand Down

0 comments on commit aaeac32

Please sign in to comment.