Skip to content

Commit

Permalink
fix some minor warn
Browse files Browse the repository at this point in the history
Signed-off-by: Chen Kai <[email protected]>
  • Loading branch information
GrapeBaBa committed Nov 27, 2024
1 parent ae9da89 commit 99ca45c
Show file tree
Hide file tree
Showing 15 changed files with 305 additions and 688 deletions.
30 changes: 15 additions & 15 deletions beacon/beacon_network.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const (
HistoricalSummaries storage.ContentType = 0x14
)

type BeaconNetwork struct {
type Network struct {
portalProtocol *portalwire.PortalProtocol
spec *common.Spec
log log.Logger
Expand All @@ -36,10 +36,10 @@ type BeaconNetwork struct {
lightClient *ConsensusLightClient
}

func NewBeaconNetwork(portalProtocol *portalwire.PortalProtocol) *BeaconNetwork {
func NewBeaconNetwork(portalProtocol *portalwire.PortalProtocol) *Network {
ctx, cancel := context.WithCancel(context.Background())

return &BeaconNetwork{
return &Network{
portalProtocol: portalProtocol,
spec: configs.Mainnet,
closeCtx: ctx,
Expand All @@ -48,7 +48,7 @@ func NewBeaconNetwork(portalProtocol *portalwire.PortalProtocol) *BeaconNetwork
}
}

func (bn *BeaconNetwork) Start() error {
func (bn *Network) Start() error {
err := bn.portalProtocol.Start()
if err != nil {
return err
Expand All @@ -58,12 +58,12 @@ func (bn *BeaconNetwork) Start() error {
return nil
}

func (bn *BeaconNetwork) Stop() {
func (bn *Network) Stop() {
bn.closeFunc()
bn.portalProtocol.Stop()
}

func (bn *BeaconNetwork) GetUpdates(firstPeriod, count uint64) ([]common.SpecObj, error) {
func (bn *Network) GetUpdates(firstPeriod, count uint64) ([]common.SpecObj, error) {
lightClientUpdateKey := &LightClientUpdateKey{
StartPeriod: firstPeriod,
Count: count,
Expand All @@ -86,7 +86,7 @@ func (bn *BeaconNetwork) GetUpdates(firstPeriod, count uint64) ([]common.SpecObj
return res, nil
}

func (bn *BeaconNetwork) GetCheckpointData(checkpointHash tree.Root) (common.SpecObj, error) {
func (bn *Network) GetCheckpointData(checkpointHash tree.Root) (common.SpecObj, error) {
bootstrapKey := &LightClientBootstrapKey{
BlockHash: checkpointHash[:],
}
Expand All @@ -104,7 +104,7 @@ func (bn *BeaconNetwork) GetCheckpointData(checkpointHash tree.Root) (common.Spe
return forkedLightClientBootstrap.Bootstrap, nil
}

func (bn *BeaconNetwork) GetFinalityUpdate(finalizedSlot uint64) (common.SpecObj, error) {
func (bn *Network) GetFinalityUpdate(finalizedSlot uint64) (common.SpecObj, error) {
finalityUpdateKey := &LightClientFinalityUpdateKey{
FinalizedSlot: finalizedSlot,
}
Expand All @@ -122,7 +122,7 @@ func (bn *BeaconNetwork) GetFinalityUpdate(finalizedSlot uint64) (common.SpecObj
return forkedLightClientFinalityUpdate.LightClientFinalityUpdate, nil
}

func (bn *BeaconNetwork) GetOptimisticUpdate(optimisticSlot uint64) (common.SpecObj, error) {
func (bn *Network) GetOptimisticUpdate(optimisticSlot uint64) (common.SpecObj, error) {
optimisticUpdateKey := &LightClientOptimisticUpdateKey{
OptimisticSlot: optimisticSlot,
}
Expand All @@ -141,7 +141,7 @@ func (bn *BeaconNetwork) GetOptimisticUpdate(optimisticSlot uint64) (common.Spec
return forkedLightClientOptimisticUpdate.LightClientOptimisticUpdate, nil
}

func (bn *BeaconNetwork) getContent(contentType storage.ContentType, beaconContentKey ssz.Marshaler) ([]byte, error) {
func (bn *Network) getContent(contentType storage.ContentType, beaconContentKey ssz.Marshaler) ([]byte, error) {
contentKeyBytes, err := beaconContentKey.MarshalSSZ()
if err != nil {
return nil, err
Expand All @@ -168,7 +168,7 @@ func (bn *BeaconNetwork) getContent(contentType storage.ContentType, beaconConte
return content, nil
}

func (bn *BeaconNetwork) validateContent(contentKey []byte, content []byte) error {
func (bn *Network) validateContent(contentKey []byte, content []byte) error {
switch storage.ContentType(contentKey[0]) {
case LightClientUpdate:
var lightClientUpdateRange LightClientUpdateRange = make([]ForkedLightClientUpdate, 0)
Expand Down Expand Up @@ -271,7 +271,7 @@ func (bn *BeaconNetwork) validateContent(contentKey []byte, content []byte) erro
}
}

func (bn *BeaconNetwork) validateContents(contentKeys [][]byte, contents [][]byte) error {
func (bn *Network) validateContents(contentKeys [][]byte, contents [][]byte) error {
for i, content := range contents {
contentKey := contentKeys[i]
err := bn.validateContent(contentKey, content)
Expand All @@ -289,7 +289,7 @@ func (bn *BeaconNetwork) validateContents(contentKeys [][]byte, contents [][]byt
return nil
}

func (bn *BeaconNetwork) processContentLoop(ctx context.Context) {
func (bn *Network) processContentLoop(ctx context.Context) {
contentChan := bn.portalProtocol.GetContent()
for {
select {
Expand Down Expand Up @@ -319,7 +319,7 @@ func (bn *BeaconNetwork) processContentLoop(ctx context.Context) {
}
}

func (bn *BeaconNetwork) generalSummariesValidation(contentKey, content []byte) (*ForkedHistoricalSummariesWithProof, error) {
func (bn *Network) generalSummariesValidation(contentKey, content []byte) (*ForkedHistoricalSummariesWithProof, error) {
key := &HistoricalSummariesWithProofKey{}
err := key.Deserialize(codec.NewDecodingReader(bytes.NewReader(contentKey[1:]), uint64(len(contentKey[1:]))))
if err != nil {
Expand All @@ -336,7 +336,7 @@ func (bn *BeaconNetwork) generalSummariesValidation(contentKey, content []byte)
return forkedHistoricalSummariesWithProof, nil
}

func (bn *BeaconNetwork) stateSummariesValidation(f ForkedHistoricalSummariesWithProof, latestFinalizedRoot common.Root) bool {
func (bn *Network) stateSummariesValidation(f ForkedHistoricalSummariesWithProof, latestFinalizedRoot common.Root) bool {
proof := f.HistoricalSummariesWithProof.Proof
summariesRoot := f.HistoricalSummariesWithProof.HistoricalSummaries.HashTreeRoot(bn.spec, tree.GetHashFn())

Expand Down
6 changes: 3 additions & 3 deletions beacon/portal_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (p *PortalLightApi) ChainID() uint64 {
return 1
}

// GetCheckpointData implements ConsensusAPI.
// GetBootstrap implements ConsensusAPI.
func (p *PortalLightApi) GetBootstrap(blockRoot tree.Root) (common.SpecObj, error) {
bootstrapKey := &LightClientBootstrapKey{
BlockHash: blockRoot[:],
Expand All @@ -54,7 +54,7 @@ func (p *PortalLightApi) GetBootstrap(blockRoot tree.Root) (common.SpecObj, erro
return forkedLightClientBootstrap.Bootstrap, nil
}

// GetFinalityData implements ConsensusAPI.
// GetFinalityUpdate implements ConsensusAPI.
func (p *PortalLightApi) GetFinalityUpdate() (common.SpecObj, error) {
// Get the finality update for the most recent finalized epoch. We use 0 as the finalized
// slot because the finalized slot is not known at this point and the protocol is
Expand All @@ -81,7 +81,7 @@ func (p *PortalLightApi) GetFinalityUpdate() (common.SpecObj, error) {
return finalityUpdate.LightClientFinalityUpdate, nil
}

// GetOptimisticData implements ConsensusAPI.
// GetOptimisticUpdate implements ConsensusAPI.
func (p *PortalLightApi) GetOptimisticUpdate() (common.SpecObj, error) {
currentSlot := p.spec.TimeToSlot(common.Timestamp(time.Now().Unix()), common.Timestamp(GenesisTime))
optimisticUpdateKey := &LightClientOptimisticUpdateKey{
Expand Down
1 change: 0 additions & 1 deletion beacon/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,6 @@ func (bs *Storage) getContentValue(contentId []byte) ([]byte, error) {
}

func (bs *Storage) getLcUpdateValueByRange(start, end uint64) ([]byte, error) {
// LightClientUpdateRange := make([]ForkedLightClientUpdate, 0)
var lightClientUpdateRange LightClientUpdateRange
rows, err := bs.db.QueryContext(context.Background(), LCUpdateLookupQueryByRange, start, end)
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions beacon/storage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/holiman/uint256"
_ "github.com/mattn/go-sqlite3"
storage2 "github.com/optimism-java/shisui2/storage"
"github.com/optimism-java/shisui2/storage"
"github.com/protolambda/zrnt/eth2/configs"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -42,7 +42,7 @@ func TestGetAndPut(t *testing.T) {

contentId := defaultContentIdFunc(key)
_, err = beaconStorage.Get(key, contentId)
require.Equal(t, storage2.ErrContentNotFound, err)
require.Equal(t, storage.ErrContentNotFound, err)

err = beaconStorage.Put(key, contentId, value)
require.NoError(t, err)
Expand All @@ -53,7 +53,7 @@ func TestGetAndPut(t *testing.T) {
}
}

func genStorage(testDir string) (storage2.ContentStorage, error) {
func genStorage(testDir string) (storage.ContentStorage, error) {
err := os.MkdirAll(testDir, 0755)
if err != nil {
return nil, err
Expand All @@ -62,7 +62,7 @@ func genStorage(testDir string) (storage2.ContentStorage, error) {
if err != nil {
return nil, err
}
config := &storage2.PortalStorageConfig{
config := &storage.PortalStorageConfig{
StorageCapacityMB: 1000,
DB: db,
NodeId: enode.ID(zeroNodeId),
Expand Down
2 changes: 1 addition & 1 deletion beacon/test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"github.com/protolambda/ztyp/tree"
)

func SetupBeaconNetwork(addr string, bootNodes []*enode.Node) (*BeaconNetwork, error) {
func SetupBeaconNetwork(addr string, bootNodes []*enode.Node) (*Network, error) {
conf := portalwire2.DefaultPortalProtocolConfig()
if addr != "" {
conf.ListenAddr = addr
Expand Down
46 changes: 31 additions & 15 deletions cmd/shisui/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ type Config struct {
type Client struct {
DiscV5API *portalwire.DiscV5API
HistoryNetwork *history.Network
BeaconNetwork *beacon.BeaconNetwork
StateNetwork *state.StateNetwork
BeaconNetwork *beacon.Network
StateNetwork *state.Network
Server *http.Server
}

Expand Down Expand Up @@ -113,7 +113,10 @@ func init() {

func main() {
if err := app.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
_, err = fmt.Fprintln(os.Stderr, err)
if err != nil {
log.Error("Failed to write error to stderr", "err", err)
}
os.Exit(1)
}
}
Expand Down Expand Up @@ -216,7 +219,10 @@ func (cli *Client) closePortalRpcServer() {
log.Info("Closing UDPv5 protocol...")
cli.DiscV5API.DiscV5.Close()
log.Info("Closing servers...")
cli.Server.Close()
err := cli.Server.Close()
if err != nil {
log.Error("Failed to close server", "err", err)
}
os.Exit(1)
}

Expand Down Expand Up @@ -252,7 +258,7 @@ func startPortalRpcServer(config Config, conn discover.UDPConn, addr string, cli
client.HistoryNetwork = historyNetwork
}

var beaconNetwork *beacon.BeaconNetwork
var beaconNetwork *beacon.Network
if slices.Contains(config.Networks, portalwire.Beacon.Name()) {
beaconNetwork, err = initBeacon(config, server, conn, localNode, discV5, utp)
if err != nil {
Expand All @@ -261,7 +267,7 @@ func startPortalRpcServer(config Config, conn discover.UDPConn, addr string, cli
client.BeaconNetwork = beaconNetwork
}

var stateNetwork *state.StateNetwork
var stateNetwork *state.Network
if slices.Contains(config.Networks, portalwire.State.Name()) {
stateNetwork, err = initState(config, server, conn, localNode, discV5, utp)
if err != nil {
Expand All @@ -270,12 +276,12 @@ func startPortalRpcServer(config Config, conn discover.UDPConn, addr string, cli
client.StateNetwork = stateNetwork
}

ethapi := &ethapi.API{
ethApi := &ethapi.API{
History: historyNetwork,
// static configuration of ChainId, currently only mainnet implemented
ChainID: core.DefaultGenesisBlock().Config.ChainID,
}
err = server.RegisterName("eth", ethapi)
err = server.RegisterName("eth", ethApi)
if err != nil {
return err
}
Expand Down Expand Up @@ -307,9 +313,9 @@ func initDiscV5(config Config, conn discover.UDPConn) (*discover.UDPv5, *enode.L

localNode.Set(portalwire.Tag)
listenerAddr := conn.LocalAddr().(*net.UDPAddr)
nat := config.Protocol.NAT
if nat != nil && !listenerAddr.IP.IsLoopback() {
doPortMapping(nat, localNode, listenerAddr)
natConf := config.Protocol.NAT
if natConf != nil && !listenerAddr.IP.IsLoopback() {
doPortMapping(natConf, localNode, listenerAddr)
}

discV5, err := discover.ListenV5(conn, localNode, discCfg)
Expand Down Expand Up @@ -415,7 +421,7 @@ func initHistory(config Config, server *rpc.Server, conn discover.UDPConn, local
return historyNetwork, historyNetwork.Start()
}

func initBeacon(config Config, server *rpc.Server, conn discover.UDPConn, localNode *enode.LocalNode, discV5 *discover.UDPv5, utp *portalwire.PortalUtp) (*beacon.BeaconNetwork, error) {
func initBeacon(config Config, server *rpc.Server, conn discover.UDPConn, localNode *enode.LocalNode, discV5 *discover.UDPv5, utp *portalwire.PortalUtp) (*beacon.Network, error) {
dbPath := path.Join(config.DataDir, "beacon")
err := os.MkdirAll(dbPath, 0755)
if err != nil {
Expand Down Expand Up @@ -464,7 +470,7 @@ func initBeacon(config Config, server *rpc.Server, conn discover.UDPConn, localN
return beaconNetwork, beaconNetwork.Start()
}

func initState(config Config, server *rpc.Server, conn discover.UDPConn, localNode *enode.LocalNode, discV5 *discover.UDPv5, utp *portalwire.PortalUtp) (*state.StateNetwork, error) {
func initState(config Config, server *rpc.Server, conn discover.UDPConn, localNode *enode.LocalNode, discV5 *discover.UDPv5, utp *portalwire.PortalUtp) (*state.Network, error) {
networkName := portalwire.State.Name()
db, err := history.NewDB(config.DataDir, networkName)
if err != nil {
Expand Down Expand Up @@ -575,7 +581,12 @@ func setPrivateKey(ctx *cli.Context, config *Config) error {
if err != nil {
log.Error("Failed to create file:", "err", err)
}
defer file.Close()
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Error("Failed to close file:", "err", err)
}
}(file)
}
log.Info("Creating new private key")
privateKey, err = crypto.GenerateKey()
Expand All @@ -601,7 +612,12 @@ func writePrivateKey(privateKey *ecdsa.PrivateKey, config *Config, fileName stri
if err != nil {
return err
}
defer file.Close()
defer func(file *os.File) {
err = file.Close()
if err != nil {
log.Error("Failed to close file", "err", err)
}
}(file)

_, err = file.WriteString(keyEnc)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions cmd/shisui/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ func newLocalNodeForTesting() (*enode.LocalNode, *enode.DB) {
}

func TestDoPortMapping(t *testing.T) {
nat := nat.ExtIP{33, 44, 55, 66}
extIP := nat.ExtIP{33, 44, 55, 66}
localNode, _ := newLocalNodeForTesting()
listenerAddr := &net.UDPAddr{IP: net.IP{127, 0, 0, 1}, Port: 1234}

doPortMapping(nat, localNode, listenerAddr)
doPortMapping(extIP, localNode, listenerAddr)

assert.Equal(t, localNode.Seq(), uint64(1))
assert.Equal(t, localNode.Node().IP(), net.IP{33, 44, 55, 66})
Expand Down
Loading

0 comments on commit 99ca45c

Please sign in to comment.