From 147c1d04603246a1026d1cddcbd314b0ba83887b Mon Sep 17 00:00:00 2001 From: Giulio rebuffo Date: Mon, 17 Oct 2022 19:13:23 +0200 Subject: [PATCH] fixed messaage id (more efficient gossip, reduction in bandwidth). (#5770) Co-authored-by: giuliorebuffo --- cmd/lightclient/clparams/config.go | 12 +- cmd/lightclient/fork/fork.go | 7 -- cmd/lightclient/fork/id.go | 99 +++++++++++++++ cmd/lightclient/lightclient/lightclient.go | 8 ++ cmd/lightclient/main.go | 27 ++-- cmd/lightclient/rpc/common.go | 41 ------- cmd/lightclient/sentinel/config.go | 12 +- .../sentinel/handlers/heartbeats.go | 9 -- cmd/lightclient/sentinel/sentinel.go | 9 +- cmd/lightclient/utils/bytes.go | 40 ++---- cmd/lightclient/utils/bytes_test.go | 37 ++++++ cmd/lightclient/utils/time_test.go | 27 ++++ cmd/sentinel_node/cli/cliSettings.go | 21 ++-- cmd/sentinel_node/main.go | 115 ++---------------- 14 files changed, 231 insertions(+), 233 deletions(-) create mode 100644 cmd/lightclient/fork/id.go create mode 100644 cmd/lightclient/utils/bytes_test.go create mode 100644 cmd/lightclient/utils/time_test.go diff --git a/cmd/lightclient/clparams/config.go b/cmd/lightclient/clparams/config.go index 65adac89a..62a9c1dff 100644 --- a/cmd/lightclient/clparams/config.go +++ b/cmd/lightclient/clparams/config.go @@ -15,6 +15,7 @@ package clparams import ( "crypto/rand" + "fmt" "math" "math/big" "time" @@ -681,20 +682,19 @@ func GetConfigsByNetwork(net NetworkType) (*GenesisConfig, *NetworkConfig, *Beac return &genesisConfig, &networkConfig, &beaconConfig } -func GetConfigsByNetworkName(net string) (*GenesisConfig, *NetworkConfig, *BeaconChainConfig, string) { +func GetConfigsByNetworkName(net string) (*GenesisConfig, *NetworkConfig, *BeaconChainConfig, NetworkType, error) { switch net { case networkname.MainnetChainName: genesisCfg, networkCfg, beaconCfg := GetConfigsByNetwork(MainnetNetwork) - return genesisCfg, networkCfg, beaconCfg, networkname.MainnetChainName + return genesisCfg, networkCfg, beaconCfg, MainnetNetwork, nil case networkname.GoerliChainName: genesisCfg, networkCfg, beaconCfg := GetConfigsByNetwork(GoerliNetwork) - return genesisCfg, networkCfg, beaconCfg, networkname.GoerliChainName + return genesisCfg, networkCfg, beaconCfg, GoerliNetwork, nil case networkname.SepoliaChainName: genesisCfg, networkCfg, beaconCfg := GetConfigsByNetwork(SepoliaNetwork) - return genesisCfg, networkCfg, beaconCfg, networkname.SepoliaChainName + return genesisCfg, networkCfg, beaconCfg, SepoliaNetwork, nil default: - genesisCfg, networkCfg, beaconCfg := GetConfigsByNetwork(MainnetNetwork) - return genesisCfg, networkCfg, beaconCfg, networkname.MainnetChainName + return nil, nil, nil, MainnetNetwork, fmt.Errorf("chain not found") } } func GetCheckpointSyncEndpoint(net NetworkType) string { diff --git a/cmd/lightclient/fork/fork.go b/cmd/lightclient/fork/fork.go index b5003f5d1..637a9651e 100644 --- a/cmd/lightclient/fork/fork.go +++ b/cmd/lightclient/fork/fork.go @@ -23,7 +23,6 @@ import ( "github.com/ledgerwatch/erigon/cmd/lightclient/cltypes" "github.com/ledgerwatch/erigon/cmd/lightclient/utils" "github.com/ledgerwatch/erigon/common" - pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" ) func ComputeForkDigest( @@ -132,12 +131,6 @@ func GetLastFork( return currentFork } -// The one suggested by the spec is too over-engineered. -func MsgID(pmsg *pubsubpb.Message) string { - hash := utils.Keccak256(pmsg.Data) - return string(hash[:]) -} - func ComputeDomain( domainType []byte, currentVersion [4]byte, diff --git a/cmd/lightclient/fork/id.go b/cmd/lightclient/fork/id.go new file mode 100644 index 000000000..0258b961b --- /dev/null +++ b/cmd/lightclient/fork/id.go @@ -0,0 +1,99 @@ +package fork + +import ( + "github.com/ledgerwatch/erigon/cmd/lightclient/clparams" + "github.com/ledgerwatch/erigon/cmd/lightclient/utils" + pubsubpb "github.com/libp2p/go-libp2p-pubsub/pb" +) + +// MsgID return the id of Gossip message during subscription. +func MsgID(pmsg *pubsubpb.Message, networkConfig *clparams.NetworkConfig, beaconConfig *clparams.BeaconChainConfig, genesisConfig *clparams.GenesisConfig) string { + if pmsg == nil || pmsg.Data == nil || pmsg.Topic == nil { + // Impossible condition that should + // never be hit. + msg := make([]byte, 20) + copy(msg, "invalid") + return string(msg) + } + + fEpoch := getLastForkEpoch(beaconConfig, genesisConfig) + + if fEpoch >= beaconConfig.AltairForkEpoch { + return postAltairMsgID(pmsg, fEpoch, networkConfig, beaconConfig) + } + + decodedData, err := utils.DecompressSnappy(pmsg.Data) + if err != nil { + msg := make([]byte, 20) + copy(msg, "invalid") + return string(msg) + } + + if err != nil { + combinedData := append(networkConfig.MessageDomainInvalidSnappy[:], pmsg.Data...) + h := utils.Keccak256(combinedData) + return string(h[:20]) + } + combinedData := append(networkConfig.MessageDomainValidSnappy[:], decodedData...) + h := utils.Keccak256(combinedData) + return string(h[:20]) +} + +func postAltairMsgID(pmsg *pubsubpb.Message, fEpoch uint64, networkConfig *clparams.NetworkConfig, beaconConfig *clparams.BeaconChainConfig) string { + topic := *pmsg.Topic + topicLen := len(topic) + topicLenBytes := utils.Uint64ToLE(uint64(topicLen)) // topicLen cannot be negative + + // beyond Bellatrix epoch, allow 10 Mib gossip data size + gossipPubSubSize := networkConfig.GossipMaxSize + if fEpoch >= beaconConfig.BellatrixForkEpoch { + gossipPubSubSize = networkConfig.GossipMaxSizeBellatrix + } + + decodedData, err := utils.DecompressSnappy(pmsg.Data) + if err != nil { + totalLength := len(networkConfig.MessageDomainValidSnappy) + len(topicLenBytes) + topicLen + len(pmsg.Data) + if uint64(totalLength) > gossipPubSubSize { + // this should never happen + msg := make([]byte, 20) + copy(msg, "invalid") + return string(msg) + } + combinedData := make([]byte, 0, totalLength) + combinedData = append(combinedData, networkConfig.MessageDomainInvalidSnappy[:]...) + combinedData = append(combinedData, topicLenBytes...) + combinedData = append(combinedData, topic...) + combinedData = append(combinedData, pmsg.Data...) + h := utils.Keccak256(combinedData) + return string(h[:20]) + } + totalLength := len(networkConfig.MessageDomainValidSnappy) + + len(topicLenBytes) + + topicLen + + len(decodedData) + + combinedData := make([]byte, 0, totalLength) + combinedData = append(combinedData, networkConfig.MessageDomainValidSnappy[:]...) + combinedData = append(combinedData, topicLenBytes...) + combinedData = append(combinedData, topic...) + combinedData = append(combinedData, decodedData...) + h := utils.Keccak256(combinedData) + return string(h[:20]) +} + +func getLastForkEpoch( + beaconConfig *clparams.BeaconChainConfig, + genesisConfig *clparams.GenesisConfig, +) uint64 { + currentEpoch := utils.GetCurrentEpoch(genesisConfig.GenesisTime, beaconConfig.SecondsPerSlot, beaconConfig.SlotsPerEpoch) + // Retrieve current fork version. + currentForkEpoch := beaconConfig.GenesisEpoch + for _, fork := range forkList(beaconConfig.ForkVersionSchedule) { + if currentEpoch >= fork.epoch { + currentForkEpoch = fork.epoch + continue + } + break + } + return currentForkEpoch +} diff --git a/cmd/lightclient/lightclient/lightclient.go b/cmd/lightclient/lightclient/lightclient.go index 4c555f1ac..3b6aaeacd 100644 --- a/cmd/lightclient/lightclient/lightclient.go +++ b/cmd/lightclient/lightclient/lightclient.go @@ -28,6 +28,7 @@ import ( ) const maxRecentHashes = 5 // 0.16 KB +const safetyRange = 8 // 8 block of safety type LightClient struct { ctx context.Context @@ -35,6 +36,7 @@ type LightClient struct { beaconConfig *clparams.BeaconChainConfig chainTip *ChainTipSubscriber + highestSeen uint64 // Highest ETH1 block seen recentHashesCache *lru.Cache sentinel lightrpc.SentinelClient execution remote.ETHBACKENDServer @@ -178,9 +180,15 @@ func (l *LightClient) Start() { log.Warn("[LightClient] Wrong ETH1 hashes") continue } + eth1Number := curr.Body.ExecutionPayload.BlockNumber + if l.highestSeen > safetyRange && eth1Number < l.highestSeen-safetyRange { + continue + } // If all of the above is gud then do the push if err := l.processBeaconBlock(curr); err != nil { log.Warn("Could not send beacon block to ETH1", "err", err) + } else { + l.highestSeen = eth1Number } } // do not have high CPU load diff --git a/cmd/lightclient/main.go b/cmd/lightclient/main.go index b0211a4a7..d25224bfb 100644 --- a/cmd/lightclient/main.go +++ b/cmd/lightclient/main.go @@ -28,8 +28,6 @@ import ( "github.com/urfave/cli" ) -const DefaultUri = "https://beaconstate.ethstaker.cc/eth/v2/debug/beacon/states/finalized" - func main() { app := lightclientapp.MakeApp(runLightClientNode, flags.LightClientDefaultFlags) if err := app.Run(os.Args); err != nil { @@ -43,25 +41,28 @@ func main() { func runLightClientNode(cliCtx *cli.Context) { ctx := context.Background() - lcCfg, chain := lcCli.SetUpLightClientCfg(cliCtx) + lcCfg, err := lcCli.SetUpLightClientCfg(cliCtx) + if err != nil { + log.Error("[Lightclient] Could not initialize lightclient", "err", err) + } log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(lcCfg.LogLvl), log.StderrHandler)) - log.Info("[LC]", "chain", chain) - log.Info("[LC] Running lightclient", "cfg", lcCfg) + log.Info("[LightClient]", "chain", cliCtx.GlobalString(flags.LightClientChain.Name)) + log.Info("[LightClient] Running lightclient", "cfg", lcCfg) sentinel, err := service.StartSentinelService(&sentinel.SentinelConfig{ - IpAddr: lcCfg.Addr, - Port: int(lcCfg.Port), - TCPPort: lcCfg.ServerTcpPort, - GenesisConfig: lcCfg.GenesisCfg, - NetworkConfig: lcCfg.NetworkCfg, - BeaconConfig: lcCfg.BeaconCfg, - IsDiscoverable: lcCfg.IsDiscoverable, + IpAddr: lcCfg.Addr, + Port: int(lcCfg.Port), + TCPPort: lcCfg.ServerTcpPort, + GenesisConfig: lcCfg.GenesisCfg, + NetworkConfig: lcCfg.NetworkCfg, + BeaconConfig: lcCfg.BeaconCfg, + NoDiscovery: lcCfg.NoDiscovery, }, &service.ServerConfig{Network: lcCfg.ServerProtocol, Addr: lcCfg.ServerAddr}) if err != nil { log.Error("Could not start sentinel", "err", err) } log.Info("Sentinel started", "addr", lcCfg.ServerAddr) - bs, err := lightclient.RetrieveBeaconState(ctx, DefaultUri) + bs, err := lightclient.RetrieveBeaconState(ctx, lcCfg.CheckpointUri) if err != nil { log.Error("[Checkpoint Sync] Failed", "reason", err) diff --git a/cmd/lightclient/rpc/common.go b/cmd/lightclient/rpc/common.go index b8f957839..d3ea2c1b8 100644 --- a/cmd/lightclient/rpc/common.go +++ b/cmd/lightclient/rpc/common.go @@ -34,47 +34,6 @@ func DecodeGossipData(data *lightrpc.GossipData) (ssz.Unmarshaler, error) { } } -func SendPingReqV1(ctx context.Context, req *cltypes.Ping, client lightrpc.SentinelClient) (*cltypes.Ping, error) { - var buffer buffer.Buffer - if err := ssz_snappy.EncodeAndWrite(&buffer, req); err != nil { - return nil, err - } - responsePacket := &cltypes.Ping{} - data := common.CopyBytes(buffer.Bytes()) - message, err := client.SendRequest(ctx, &lightrpc.RequestData{ - Data: data, - Topic: handlers.PingProtocolV1, - }) - if err != nil { - return nil, err - } - if message.Error { - log.Warn("received error", "err", string(message.Data)) - return nil, nil - } - - err = ssz_snappy.DecodeAndRead(bytes.NewReader(message.Data), responsePacket) - return responsePacket, err -} - -func SendMetadataReqV1(ctx context.Context, client lightrpc.SentinelClient) (*cltypes.MetadataV1, error) { - responsePacket := &cltypes.MetadataV1{} - - message, err := client.SendRequest(ctx, &lightrpc.RequestData{ - Topic: handlers.MetadataProtocolV1, - }) - if err != nil { - return nil, err - } - if message.Error { - log.Warn("received error", "err", string(message.Data)) - return nil, nil - } - - err = ssz_snappy.DecodeAndRead(bytes.NewReader(message.Data), responsePacket) - return responsePacket, err -} - func SendLightClientFinaltyUpdateReqV1(ctx context.Context, client lightrpc.SentinelClient) (*cltypes.LightClientFinalityUpdate, error) { responsePacket := &cltypes.LightClientFinalityUpdate{} diff --git a/cmd/lightclient/sentinel/config.go b/cmd/lightclient/sentinel/config.go index c44caa7da..ab02a86ac 100644 --- a/cmd/lightclient/sentinel/config.go +++ b/cmd/lightclient/sentinel/config.go @@ -37,12 +37,12 @@ type SentinelConfig struct { Port int TCPPort uint // Optional - LocalIP string - EnableUPnP bool - RelayNodeAddr string - HostAddress string - HostDNS string - IsDiscoverable bool + LocalIP string + EnableUPnP bool + RelayNodeAddr string + HostAddress string + HostDNS string + NoDiscovery bool } func convertToCryptoPrivkey(privkey *ecdsa.PrivateKey) (crypto.PrivKey, error) { diff --git a/cmd/lightclient/sentinel/handlers/heartbeats.go b/cmd/lightclient/sentinel/handlers/heartbeats.go index 007662c37..c47405caa 100644 --- a/cmd/lightclient/sentinel/handlers/heartbeats.go +++ b/cmd/lightclient/sentinel/handlers/heartbeats.go @@ -16,8 +16,6 @@ package handlers import ( "github.com/ledgerwatch/erigon/cmd/lightclient/cltypes" "github.com/ledgerwatch/erigon/cmd/lightclient/sentinel/communication" - "github.com/ledgerwatch/erigon/cmd/lightclient/utils" - "github.com/ledgerwatch/log/v3" ) // type safe handlers which all have access to the original stream & decompressed data @@ -47,12 +45,5 @@ func nilHandler(ctx *communication.StreamContext, dat *communication.EmptyPacket // TODO: Actually respond with proper status func statusHandler(ctx *communication.StreamContext, dat *cltypes.Status) error { - log.Debug("[ReqResp] Status", - "epoch", dat.FinalizedEpoch, - "final root", utils.BytesToHex(dat.FinalizedRoot[:]), - "head root", utils.BytesToHex(dat.HeadRoot[:]), - "head slot", dat.HeadSlot, - "fork digest", utils.BytesToHex(dat.ForkDigest[:]), - ) return ctx.Codec.WritePacket(dat, SuccessfullResponsePrefix) } diff --git a/cmd/lightclient/sentinel/sentinel.go b/cmd/lightclient/sentinel/sentinel.go index 4a471113b..0e01275ff 100644 --- a/cmd/lightclient/sentinel/sentinel.go +++ b/cmd/lightclient/sentinel/sentinel.go @@ -32,6 +32,7 @@ import ( "github.com/ledgerwatch/log/v3" "github.com/libp2p/go-libp2p" pubsub "github.com/libp2p/go-libp2p-pubsub" + pubsub_pb "github.com/libp2p/go-libp2p-pubsub/pb" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/p2p/protocol/identify" "github.com/pkg/errors" @@ -142,8 +143,10 @@ func (s *Sentinel) pubsubOptions() []pubsub.Option { gsp := pubsub.DefaultGossipSubParams() psOpts := []pubsub.Option{ pubsub.WithMessageSignaturePolicy(pubsub.StrictNoSign), - pubsub.WithMessageIdFn(fork.MsgID), - pubsub.WithNoAuthor(), + pubsub.WithMessageSignaturePolicy(pubsub.StrictNoSign), + pubsub.WithMessageIdFn(func(pmsg *pubsub_pb.Message) string { + return fork.MsgID(pmsg, s.cfg.NetworkConfig, s.cfg.BeaconConfig, s.cfg.GenesisConfig) + }), pubsub.WithNoAuthor(), pubsub.WithSubscriptionFilter(nil), pubsub.WithPeerOutboundQueueSize(pubsubQueueSize), pubsub.WithMaxMessageSize(int(s.cfg.NetworkConfig.GossipMaxSize)), @@ -223,7 +226,7 @@ func (s *Sentinel) Start( return fmt.Errorf("failed to connect to bootnodes err=%w", err) } - if s.cfg.IsDiscoverable { + if !s.cfg.NoDiscovery { go s.listenForPeers() } s.subManager = NewGossipManager(s.ctx) diff --git a/cmd/lightclient/utils/bytes.go b/cmd/lightclient/utils/bytes.go index 45b9a2f55..f42235acd 100644 --- a/cmd/lightclient/utils/bytes.go +++ b/cmd/lightclient/utils/bytes.go @@ -15,7 +15,6 @@ package utils import ( "encoding/binary" - "encoding/hex" ssz "github.com/ferranbt/fastssz" "github.com/golang/snappy" @@ -31,8 +30,10 @@ func BytesToBytes4(b []byte) (ret [4]byte) { return } -func BytesToHex(b []byte) string { - return hex.EncodeToString(b) +func Uint64ToLE(i uint64) []byte { + buf := make([]byte, 8) + binary.LittleEndian.PutUint64(buf, i) + return buf } func DecompressSnappy(data []byte) ([]byte, error) { @@ -43,38 +44,11 @@ func DecompressSnappy(data []byte) ([]byte, error) { } decodedData := make([]byte, lenDecoded) - snappy.Decode(decodedData, data) - return decodedData, nil + return snappy.Decode(decodedData, data) } -func CompressSnappy(data []byte) ([]byte, error) { - // Decode the snappy - lenDecoded, err := snappy.DecodedLen(data) - if err != nil { - return nil, err - } - decodedData := make([]byte, lenDecoded) - - snappy.Decode(decodedData, data) - return decodedData, nil -} - -func Uint64ToLE(i uint64) []byte { - buf := make([]byte, 8) - binary.LittleEndian.PutUint64(buf, i) - return buf -} - -func BytesToBytes32(b []byte) (ret [32]byte) { - copy(ret[:], b) - return -} - -func BytesSliceToBytes32Slice(b [][]byte) (ret [][32]byte) { - for _, str := range b { - ret = append(ret, BytesToBytes32(str)) - } - return +func CompressSnappy(data []byte) []byte { + return snappy.Encode(nil, data) } func EncodeSSZSnappy(data ssz.Marshaler) ([]byte, error) { diff --git a/cmd/lightclient/utils/bytes_test.go b/cmd/lightclient/utils/bytes_test.go new file mode 100644 index 000000000..0aa202d2f --- /dev/null +++ b/cmd/lightclient/utils/bytes_test.go @@ -0,0 +1,37 @@ +package utils_test + +import ( + "testing" + + "github.com/ledgerwatch/erigon/cmd/lightclient/cltypes" + "github.com/ledgerwatch/erigon/cmd/lightclient/utils" + "github.com/ledgerwatch/erigon/common" + "github.com/stretchr/testify/require" +) + +func TestSSZSnappy(t *testing.T) { + verySussyMessage := &cltypes.MetadataV1{ + SeqNumber: 69, // :D + Attnets: 96, // :( + } + sussyEncoded, err := utils.EncodeSSZSnappy(verySussyMessage) + require.NoError(t, err) + sussyDecoded := &cltypes.MetadataV1{} + require.NoError(t, utils.DecodeSSZSnappy(sussyDecoded, sussyEncoded)) + require.Equal(t, verySussyMessage.SeqNumber, sussyDecoded.SeqNumber) + require.Equal(t, verySussyMessage.Attnets, sussyDecoded.Attnets) +} + +func TestPlainSnappy(t *testing.T) { + msg := common.Hex2Bytes("10103849358111387348383738784374783811111754097864786873478675489485765483936576486387645456876772090909090ff") + sussyEncoded := utils.CompressSnappy(msg) + sussyDecoded, err := utils.DecompressSnappy(sussyEncoded) + require.NoError(t, err) + require.Equal(t, msg, sussyDecoded) +} + +func TestLiteralConverters(t *testing.T) { + require.Equal(t, utils.Uint32ToBytes4(600), [4]byte{0x0, 0x0, 0x2, 0x58}) + require.Equal(t, utils.BytesToBytes4([]byte{10, 23, 56, 7, 8, 5}), [4]byte{10, 23, 56, 7}) + require.Equal(t, utils.Uint64ToLE(600), []byte{0x58, 0x2, 0x0, 0x0, 0x0, 0x0, 0x00, 0x00}) +} diff --git a/cmd/lightclient/utils/time_test.go b/cmd/lightclient/utils/time_test.go new file mode 100644 index 000000000..6b02a4dd1 --- /dev/null +++ b/cmd/lightclient/utils/time_test.go @@ -0,0 +1,27 @@ +package utils_test + +import ( + "testing" + "time" + + "github.com/ledgerwatch/erigon/cmd/lightclient/utils" + "github.com/stretchr/testify/assert" +) + +func TestGetCurrentSlot(t *testing.T) { + now := uint64(time.Now().Unix()) + timePerSlot := 12 + genesisTime := now - 12*10 + assert.Equal(t, utils.GetCurrentSlot(genesisTime, uint64(timePerSlot)), uint64(10)) +} + +func TestGetCurrentEpoch(t *testing.T) { + now := uint64(time.Now().Unix()) + timePerSlot := 12 + genesisTime := now - 86*10 + assert.Equal(t, utils.GetCurrentEpoch(genesisTime, uint64(timePerSlot), 32), uint64(2)) +} + +func TestSlotToPeriod(t *testing.T) { + assert.Equal(t, utils.SlotToPeriod(20000), uint64(2)) +} diff --git a/cmd/sentinel_node/cli/cliSettings.go b/cmd/sentinel_node/cli/cliSettings.go index 0ed02de16..680b428d8 100644 --- a/cmd/sentinel_node/cli/cliSettings.go +++ b/cmd/sentinel_node/cli/cliSettings.go @@ -18,16 +18,19 @@ type LightClientCliCfg struct { ServerProtocol string `json:"serverProtocol"` ServerTcpPort uint `json:"serverTcpPort"` LogLvl uint `json:"logLevel"` - IsDiscoverable bool `json:"discoverable"` + NoDiscovery bool `json:"noDiscovery"` + CheckpointUri string `json:"checkpointUri"` } -func SetUpLightClientCfg(ctx *cli.Context) (*LightClientCliCfg, string) { +func SetUpLightClientCfg(ctx *cli.Context) (*LightClientCliCfg, error) { cfg := &LightClientCliCfg{} chainName := ctx.GlobalString(flags.LightClientChain.Name) - - var chain string - cfg.GenesisCfg, cfg.NetworkCfg, cfg.BeaconCfg, chain = clparams.GetConfigsByNetworkName(chainName) - + var err error + var network clparams.NetworkType + cfg.GenesisCfg, cfg.NetworkCfg, cfg.BeaconCfg, network, err = clparams.GetConfigsByNetworkName(chainName) + if err != nil { + return nil, err + } cfg.ServerAddr = fmt.Sprintf("%s:%d", ctx.GlobalString(flags.LightClientServerAddr.Name), ctx.GlobalInt(flags.LightClientServerPort.Name)) cfg.ServerProtocol = ServerProtocolFromInt(ctx.GlobalUint(flags.LightClientServerProtocol.Name)) @@ -35,9 +38,9 @@ func SetUpLightClientCfg(ctx *cli.Context) (*LightClientCliCfg, string) { cfg.Addr = ctx.GlobalString(flags.LightClientAddr.Name) cfg.LogLvl = ctx.GlobalUint(flags.LightClientVerbosity.Name) - cfg.IsDiscoverable = ctx.GlobalBoolT(flags.LightClientDiscovery.Name) - - return cfg, chain + cfg.NoDiscovery = !ctx.GlobalBoolT(flags.LightClientDiscovery.Name) + cfg.CheckpointUri = clparams.GetCheckpointSyncEndpoint(network) + return cfg, nil } func ServerProtocolFromInt(n uint) string { diff --git a/cmd/sentinel_node/main.go b/cmd/sentinel_node/main.go index 5aaa67c48..520257ae4 100644 --- a/cmd/sentinel_node/main.go +++ b/cmd/sentinel_node/main.go @@ -40,20 +40,19 @@ func main() { } func runSentinelNode(cliCtx *cli.Context) { - lcCfg, chain := lcCli.SetUpLightClientCfg(cliCtx) + lcCfg, _ := lcCli.SetUpLightClientCfg(cliCtx) ctx := context.Background() log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(lcCfg.LogLvl), log.StderrHandler)) - log.Info("[LC-Sentinel]", "chain", chain) - log.Info("[LC-Sentinel] running sentinel with configuration", "cfg", lcCfg) + log.Info("[Sentinel] running sentinel with configuration", "cfg", lcCfg) _, err := service.StartSentinelService(&sentinel.SentinelConfig{ - IpAddr: lcCfg.Addr, - Port: int(lcCfg.Port), - TCPPort: lcCfg.ServerTcpPort, - GenesisConfig: lcCfg.GenesisCfg, - NetworkConfig: lcCfg.NetworkCfg, - BeaconConfig: lcCfg.BeaconCfg, - IsDiscoverable: lcCfg.IsDiscoverable, + IpAddr: lcCfg.Addr, + Port: int(lcCfg.Port), + TCPPort: lcCfg.ServerTcpPort, + GenesisConfig: lcCfg.GenesisCfg, + NetworkConfig: lcCfg.NetworkCfg, + BeaconConfig: lcCfg.BeaconCfg, + NoDiscovery: lcCfg.NoDiscovery, }, &service.ServerConfig{Network: lcCfg.ServerProtocol, Addr: lcCfg.ServerAddr}) if err != nil { log.Error("Could not start sentinel", "err", err) @@ -62,99 +61,3 @@ func runSentinelNode(cliCtx *cli.Context) { log.Info("Sentinel started", "addr", lcCfg.ServerAddr) <-ctx.Done() } - -/* -func main() { - ctx := context.Background() - log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StderrHandler)) - genesisCfg, networkCfg, beaconCfg := clparams.GetConfigsByNetwork(clparams.MainnetNetwork) - sentinelClient, err := service.StartSentinelService(&sentinel.SentinelConfig{ - IpAddr: defaultIpAddr, - Port: defaultPort, - TCPPort: defaultTcpPort, - GenesisConfig: genesisCfg, - NetworkConfig: networkCfg, - BeaconConfig: beaconCfg, - }, &service.ServerConfig{Network: "tcp", Addr: "localhost:7777"}) - if err != nil { - log.Error("Could not start sentinel", "err", err) - } - log.Info("Sentinel started") - - logInterval := time.NewTicker(5 * time.Second) - sendReqInterval := time.NewTicker(500 * time.Millisecond) - - stream, err := sentinelClient.SubscribeGossip(ctx, &lightrpc.EmptyRequest{}) - if err != nil { - log.Error("Could not start stream", "err", err) - return - } - - go gossipHandler(stream) - - for { - select { - case <-logInterval.C: - count, err := sentinelClient.GetPeers(ctx, &lightrpc.EmptyRequest{}) - if err != nil { - log.Error("Could not get peer count", "err", err) - return - } - - log.Info("[Lightclient] Networking Report", "peers", count.Amount) - case <-sendReqInterval.C: - go func() { - var err error - if _, err = rpc.SendPingReqV1(ctx, &cltypes.Ping{Id: 10}, sentinelClient); err != nil { - log.Debug("failed to send ping request", "err", err) - } - - if _, err = rpc.SendMetadataReqV1(ctx, sentinelClient); err != nil { - log.Debug("failed to send ping request", "err", err) - } - - var lol *cltypes.LightClientUpdate - if lol, err = rpc.SendLightClientUpdatesReqV1(ctx, 597, sentinelClient); err != nil { - log.Warn("failed to send updates by range request", "err", err) - } - if lol != nil { - log.Info("Lightclient responded", "msg", lol) - } - }() - } - } -} - -func gossipHandler(stream lightrpc.Sentinel_SubscribeGossipClient) { - for { - gossipData, err := stream.Recv() - if err != nil { - log.Warn("ending consensus gossip", "err", err) - return - } - pkt, err := rpc.DecodeGossipData(gossipData) - if err != nil { - log.Warn("cannot decode gossip", "err", err) - return - } - switch u := pkt.(type) { - case *cltypes.SignedBeaconBlockBellatrix: - log.Debug("[Gossip] beacon_block", - "Slot", u.Block.Slot, - "Signature", hex.EncodeToString(u.Signature[:]), - "graffiti", string(u.Block.Body.Graffiti), - "eth1_blockhash", hex.EncodeToString(u.Block.Body.Eth1Data.BlockHash[:]), - "stateRoot", hex.EncodeToString(u.Block.StateRoot[:]), - "parentRoot", hex.EncodeToString(u.Block.ParentRoot[:]), - "proposerIdx", u.Block.ProposerIndex, - ) - case *cltypes.LightClientFinalityUpdate: - log.Info("[Gossip] Got Finalty Update", "sig", utils.BytesToHex(u.FinalizedHeader.Root[:])) - case *cltypes.LightClientOptimisticUpdate: - log.Info("[Gossip] Got Optimistic Update", "sig", utils.BytesToHex(u.SyncAggregate.SyncCommiteeSignature[:])) - default: - } - } -} - -*/