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

feat: frost keygen handler #279

Merged
merged 4 commits into from
May 24, 2024
Merged
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
3 changes: 3 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ func Run() error {
electorFactory := elector.NewCoordinatorElectorFactory(host, configuration.RelayerConfig.BullyConfig)
coordinator := tss.NewCoordinator(host, communication, electorFactory)
keyshareStore := keyshare.NewECDSAKeyshareStore(configuration.RelayerConfig.MpcConfig.KeysharePath)
frostKeyshareStore := keyshare.NewFrostKeyshareStore(configuration.RelayerConfig.MpcConfig.FrostKeysharePath)

// this is temporary solution related to specifics of aws deployment
// effectively it waits until old instance is killed
Expand Down Expand Up @@ -170,6 +171,7 @@ func Run() error {
log.Info().Str("domain", config.String()).Msgf("Registering EVM domain")

bridgeAddress := common.HexToAddress(config.Bridge)
frostAddress := common.HexToAddress(config.FrostKeygen)
gasPricer := gas.NewLondonGasPriceClient(client, &gas.GasPricerOpts{
UpperLimitFeePerGas: config.MaxGasPrice,
GasPriceFactor: config.GasMultiplier,
Expand Down Expand Up @@ -213,6 +215,7 @@ func Run() error {
l := log.With().Str("chain", fmt.Sprintf("%v", config.GeneralChainConfig.Name)).Uint8("domainID", *config.GeneralChainConfig.Id)
eventHandlers = append(eventHandlers, hubEventHandlers.NewDepositEventHandler(depositListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id, msgChan))
eventHandlers = append(eventHandlers, hubEventHandlers.NewKeygenEventHandler(l, tssListener, coordinator, host, communication, keyshareStore, bridgeAddress, networkTopology.Threshold))
eventHandlers = append(eventHandlers, hubEventHandlers.NewFrostKeygenEventHandler(l, tssListener, coordinator, host, communication, frostKeyshareStore, frostAddress, networkTopology.Threshold))
eventHandlers = append(eventHandlers, hubEventHandlers.NewRefreshEventHandler(l, topologyProvider, topologyStore, tssListener, coordinator, host, communication, connectionGate, keyshareStore, bridgeAddress))
eventHandlers = append(eventHandlers, hubEventHandlers.NewRetryEventHandler(l, tssListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id, config.BlockConfirmations, msgChan))
evmListener := listener.NewEVMListener(client, eventHandlers, blockstore, sygmaMetrics, *config.GeneralChainConfig.Id, config.BlockRetryInterval, config.BlockConfirmations, config.BlockInterval)
Expand Down
1 change: 1 addition & 0 deletions chains/evm/calls/events/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ func (es EventSig) GetTopic() common.Hash {
const (
DepositSig EventSig = "Deposit(uint8,bytes32,uint64,address,bytes,bytes)"
StartKeygenSig EventSig = "StartKeygen()"
StartFrostKeygenSig EventSig = "StartedFROSTKeygen()"
KeyRefreshSig EventSig = "KeyRefresh(string)"
ProposalExecutionSig EventSig = "ProposalExecution(uint8,uint64,bytes32,bytes)"
FeeChangedSig EventSig = "FeeChanged(uint256)"
Expand Down
9 changes: 9 additions & 0 deletions chains/evm/calls/events/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,15 @@ func (l *Listener) FetchKeygenEvents(ctx context.Context, contractAddress common
return logs, nil
}

func (l *Listener) FetchFrostKeygenEvents(ctx context.Context, contractAddress common.Address, startBlock *big.Int, endBlock *big.Int) ([]ethTypes.Log, error) {
logs, err := l.client.FetchEventLogs(ctx, contractAddress, string(StartFrostKeygenSig), startBlock, endBlock)
if err != nil {
return nil, err
}

return logs, nil
}

func (l *Listener) FetchRefreshEvents(ctx context.Context, contractAddress common.Address, startBlock *big.Int, endBlock *big.Int) ([]*Refresh, error) {
logs, err := l.client.FetchEventLogs(ctx, contractAddress, string(KeyRefreshSig), startBlock, endBlock)
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions chains/evm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type HandlerConfig struct {
type EVMConfig struct {
GeneralChainConfig chain.GeneralChainConfig
Bridge string
FrostKeygen string
Handlers []HandlerConfig
MaxGasPrice *big.Int
GasMultiplier *big.Float
Expand Down Expand Up @@ -61,6 +62,7 @@ func (c *EVMConfig) String() string {
type RawEVMConfig struct {
chain.GeneralChainConfig `mapstructure:",squash"`
Bridge string `mapstructure:"bridge"`
FrostKeygen string `mapstructure:"frostKeygen"`
Handlers []HandlerConfig `mapstrcture:"handlers"`
MaxGasPrice int64 `mapstructure:"maxGasPrice" default:"500000000000"`
GasMultiplier float64 `mapstructure:"gasMultiplier" default:"1"`
Expand Down Expand Up @@ -109,6 +111,7 @@ func NewEVMConfig(chainConfig map[string]interface{}) (*EVMConfig, error) {
GeneralChainConfig: c.GeneralChainConfig,
Handlers: c.Handlers,
Bridge: c.Bridge,
FrostKeygen: c.FrostKeygen,
BlockRetryInterval: time.Duration(c.BlockRetryInterval) * time.Second,
GasLimit: big.NewInt(c.GasLimit),
MaxGasPrice: big.NewInt(c.MaxGasPrice),
Expand Down
26 changes: 15 additions & 11 deletions chains/evm/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,12 @@ func (s *NewEVMConfigTestSuite) Test_InvalidBlockConfirmation() {

func (s *NewEVMConfigTestSuite) Test_ValidConfig() {
rawConfig := map[string]interface{}{
"id": 1,
"endpoint": "ws://domain.com",
"name": "evm1",
"from": "address",
"bridge": "bridgeAddress",
"id": 1,
"endpoint": "ws://domain.com",
"name": "evm1",
"from": "address",
"bridge": "bridgeAddress",
"frostKeygen": "frostKeygen",
}

actualConfig, err := evm.NewEVMConfig(rawConfig)
Expand All @@ -81,6 +82,7 @@ func (s *NewEVMConfigTestSuite) Test_ValidConfig() {
Id: id,
},
Bridge: "bridgeAddress",
FrostKeygen: "frostKeygen",
GasLimit: big.NewInt(15000000),
MaxGasPrice: big.NewInt(500000000000),
GasMultiplier: big.NewFloat(1),
Expand All @@ -94,11 +96,12 @@ func (s *NewEVMConfigTestSuite) Test_ValidConfig() {

func (s *NewEVMConfigTestSuite) Test_ValidConfigWithCustomTxParams() {
rawConfig := map[string]interface{}{
"id": 1,
"endpoint": "ws://domain.com",
"name": "evm1",
"from": "address",
"bridge": "bridgeAddress",
"id": 1,
"endpoint": "ws://domain.com",
"name": "evm1",
"from": "address",
"bridge": "bridgeAddress",
"frostKeygen": "frostKeygen",
"handlers": []evm.HandlerConfig{
{
Type: "erc20",
Expand Down Expand Up @@ -130,7 +133,8 @@ func (s *NewEVMConfigTestSuite) Test_ValidConfigWithCustomTxParams() {
Endpoint: "ws://domain.com",
Id: id,
},
Bridge: "bridgeAddress",
Bridge: "bridgeAddress",
FrostKeygen: "frostKeygen",
Handlers: []evm.HandlerConfig{
{
Type: "erc20",
Expand Down
73 changes: 72 additions & 1 deletion chains/evm/listener/eventHandlers/event-handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ import (
"github.com/ChainSafe/sygma-relayer/tss"
"github.com/ChainSafe/sygma-relayer/tss/ecdsa/keygen"
"github.com/ChainSafe/sygma-relayer/tss/ecdsa/resharing"
frostKeygen "github.com/ChainSafe/sygma-relayer/tss/frost/keygen"
"github.com/ethereum/go-ethereum/common"
ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/libp2p/go-libp2p/core/host"
)

type EventListener interface {
FetchKeygenEvents(ctx context.Context, address common.Address, startBlock *big.Int, endBlock *big.Int) ([]ethTypes.Log, error)
FetchFrostKeygenEvents(ctx context.Context, address common.Address, startBlock *big.Int, endBlock *big.Int) ([]ethTypes.Log, error)
FetchRefreshEvents(ctx context.Context, address common.Address, startBlock *big.Int, endBlock *big.Int) ([]*events.Refresh, error)
FetchRetryEvents(ctx context.Context, contractAddress common.Address, startBlock *big.Int, endBlock *big.Int) ([]events.RetryEvent, error)
FetchRetryDepositEvents(event events.RetryEvent, bridgeAddress common.Address, blockConfirmations *big.Int) ([]events.Deposit, error)
Expand Down Expand Up @@ -167,7 +169,6 @@ func (eh *KeygenEventHandler) HandleEvents(
if err != nil {
return fmt.Errorf("unable to fetch keygen events because of: %+v", err)
}

if len(keygenEvents) == 0 {
return nil
}
Expand All @@ -189,6 +190,76 @@ func (eh *KeygenEventHandler) sessionID(block *big.Int) string {
return fmt.Sprintf("keygen-%s", block.String())
}

type FrostKeygenEventHandler struct {
log zerolog.Logger
eventListener EventListener
coordinator *tss.Coordinator
host host.Host
communication comm.Communication
storer frostKeygen.FrostKeyshareStorer
contractAddress common.Address
threshold int
}

func NewFrostKeygenEventHandler(
logC zerolog.Context,
eventListener EventListener,
coordinator *tss.Coordinator,
host host.Host,
communication comm.Communication,
storer frostKeygen.FrostKeyshareStorer,
contractAddress common.Address,
threshold int,
) *FrostKeygenEventHandler {
return &FrostKeygenEventHandler{
log: logC.Logger(),
eventListener: eventListener,
coordinator: coordinator,
host: host,
communication: communication,
storer: storer,
contractAddress: contractAddress,
threshold: threshold,
}
}

func (eh *FrostKeygenEventHandler) HandleEvents(
startBlock *big.Int,
endBlock *big.Int,
) error {
key, err := eh.storer.GetKeyshare()
if (key.Threshold != 0) && (err == nil) {
return nil
}

keygenEvents, err := eh.eventListener.FetchFrostKeygenEvents(
context.Background(), eh.contractAddress, startBlock, endBlock,
)
if err != nil {
return fmt.Errorf("unable to fetch keygen events because of: %+v", err)
}

if len(keygenEvents) == 0 {
return nil
}

eh.log.Info().Msgf(
"Resolved FROST keygen message in block range: %s-%s", startBlock.String(), endBlock.String(),
)

keygenBlockNumber := big.NewInt(0).SetUint64(keygenEvents[0].BlockNumber)
keygen := frostKeygen.NewKeygen(eh.sessionID(keygenBlockNumber), eh.threshold, eh.host, eh.communication, eh.storer)
err = eh.coordinator.Execute(context.Background(), keygen, make(chan interface{}, 1))
if err != nil {
log.Err(err).Msgf("Failed executing keygen")
}
return nil
}

func (eh *FrostKeygenEventHandler) sessionID(block *big.Int) string {
return fmt.Sprintf("frost-keygen-%s", block.String())
}

type RefreshEventHandler struct {
log zerolog.Logger
topologyProvider topology.NetworkTopologyProvider
Expand Down
15 changes: 15 additions & 0 deletions chains/evm/listener/eventHandlers/mock/listener.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func (s *GetConfigTestSuite) Test_GetConfigFromENV() {

_ = os.Setenv("SYG_RELAYER_MPCCONFIG_KEY", "test-pk")
_ = os.Setenv("SYG_RELAYER_MPCCONFIG_KEYSHAREPATH", "/cfg/keyshares/0.keyshare")
_ = os.Setenv("SYG_RELAYER_MPCCONFIG_FROSTKEYSHAREPATH", "/cfg/keyshares/0-frost.keyshare")
_ = os.Setenv("SYG_RELAYER_MPCCONFIG_PORT", "9000")
_ = os.Setenv("SYG_RELAYER_MPCCONFIG_TOPOLOGYCONFIGURATION_ENCRYPTIONKEY", "test-enc-key")
_ = os.Setenv("SYG_RELAYER_MPCCONFIG_TOPOLOGYCONFIGURATION_URL", "http://test.com")
Expand Down Expand Up @@ -97,6 +98,7 @@ func (s *GetConfigTestSuite) Test_GetConfigFromENV() {
},
Port: 9000,
KeysharePath: "/cfg/keyshares/0.keyshare",
FrostKeysharePath: "/cfg/keyshares/0-frost.keyshare",
Key: "test-pk",
CommHealthCheckInterval: 5 * time.Minute,
},
Expand Down
3 changes: 3 additions & 0 deletions config/relayer/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type MpcRelayerConfig struct {
TopologyConfiguration TopologyConfiguration
Port uint16
KeysharePath string
FrostKeysharePath string
Key string
CommHealthCheckInterval time.Duration
}
Expand Down Expand Up @@ -58,6 +59,7 @@ type RawRelayerConfig struct {

type RawMpcRelayerConfig struct {
KeysharePath string `mapstructure:"KeysharePath" json:"keysharePath"`
FrostKeysharePath string `mapstructure:"FrostKeysharePath" json:"frostKeysharePath"`
Key string `mapstructure:"Key" json:"key"`
Port string `mapstructure:"Port" json:"port" default:"9000"`
TopologyConfiguration TopologyConfiguration `mapstructure:"TopologyConfiguration" json:"topologyConfiguration"`
Expand Down Expand Up @@ -135,6 +137,7 @@ func parseMpcConfig(rawConfig RawRelayerConfig) (MpcRelayerConfig, error) {

mpcConfig.TopologyConfiguration = rawConfig.MpcConfig.TopologyConfiguration
mpcConfig.KeysharePath = rawConfig.MpcConfig.KeysharePath
mpcConfig.FrostKeysharePath = rawConfig.MpcConfig.FrostKeysharePath
mpcConfig.Key = rawConfig.MpcConfig.Key

duration, err := time.ParseDuration(rawConfig.MpcConfig.CommHealthCheckInterval)
Expand Down
3 changes: 3 additions & 0 deletions example/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ func Run() error {
electorFactory := elector.NewCoordinatorElectorFactory(host, configuration.RelayerConfig.BullyConfig)
coordinator := tss.NewCoordinator(host, communication, electorFactory)
keyshareStore := keyshare.NewECDSAKeyshareStore(configuration.RelayerConfig.MpcConfig.KeysharePath)
frostKeyshareStore := keyshare.NewFrostKeyshareStore(configuration.RelayerConfig.MpcConfig.FrostKeysharePath)

// wait until executions are done and then stop further executions before exiting
exitLock := &sync.RWMutex{}
Expand Down Expand Up @@ -144,6 +145,7 @@ func Run() error {
log.Info().Str("domain", config.String()).Msgf("Registering EVM domain")

bridgeAddress := common.HexToAddress(config.Bridge)
frostAddress := common.HexToAddress(config.FrostKeygen)
dummyGasPricer := gas.NewStaticGasPriceDeterminant(client, nil)
t := monitored.NewMonitoredTransactor(transaction.NewTransaction, dummyGasPricer, client, config.MaxGasPrice, config.GasIncreasePercentage)
go t.Monitor(ctx, time.Minute*3, time.Minute*10, time.Minute)
Expand Down Expand Up @@ -185,6 +187,7 @@ func Run() error {
l := log.With().Str("chain", fmt.Sprintf("%v", config.GeneralChainConfig.Name)).Uint8("domainID", *config.GeneralChainConfig.Id)
eventHandlers = append(eventHandlers, hubEventHandlers.NewDepositEventHandler(depositListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id, msgChan))
eventHandlers = append(eventHandlers, hubEventHandlers.NewKeygenEventHandler(l, tssListener, coordinator, host, communication, keyshareStore, bridgeAddress, networkTopology.Threshold))
eventHandlers = append(eventHandlers, hubEventHandlers.NewFrostKeygenEventHandler(l, tssListener, coordinator, host, communication, frostKeyshareStore, frostAddress, networkTopology.Threshold))
eventHandlers = append(eventHandlers, hubEventHandlers.NewRefreshEventHandler(l, nil, nil, tssListener, coordinator, host, communication, connectionGate, keyshareStore, bridgeAddress))
eventHandlers = append(eventHandlers, hubEventHandlers.NewRetryEventHandler(l, tssListener, depositHandler, bridgeAddress, *config.GeneralChainConfig.Id, config.BlockConfirmations, msgChan))
evmListener := listener.NewEVMListener(client, eventHandlers, blockstore, sygmaMetrics, *config.GeneralChainConfig.Id, config.BlockRetryInterval, config.BlockConfirmations, config.BlockInterval)
Expand Down
Loading