From 5ee9170d416379fd4a301aa2fec17c7a4e7343c0 Mon Sep 17 00:00:00 2001 From: gammazero Date: Wed, 26 Jul 2023 09:35:24 -0700 Subject: [PATCH] Fix panic when backup bootstrap peer load and save funcs are nil A panic occurs when the first bootstrap round runs is these functions are not assigned in the configuration: - `LoadBackupBootstrapPeers` - `SaveBackupBootstrapPeers` This fix assumes that it is acceptable for these functions to be nil, as it may be desirable to disable the bakcup peer load and save functionality. --- core/bootstrap/bootstrap.go | 9 ++++++++- core/bootstrap/bootstrap_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/core/bootstrap/bootstrap.go b/core/bootstrap/bootstrap.go index b566e0e978e..2c80f3ccea4 100644 --- a/core/bootstrap/bootstrap.go +++ b/core/bootstrap/bootstrap.go @@ -125,7 +125,9 @@ func Bootstrap(id peer.ID, host host.Host, rt routing.Routing, cfg BootstrapConf doneWithRound <- struct{}{} close(doneWithRound) // it no longer blocks periodic - startSavePeersAsTemporaryBootstrapProc(cfg, host, proc) + if cfg.LoadBackupBootstrapPeers != nil && cfg.SaveBackupBootstrapPeers != nil { + startSavePeersAsTemporaryBootstrapProc(cfg, host, proc) + } return proc, nil } @@ -243,6 +245,11 @@ func bootstrapRound(ctx context.Context, host host.Host, cfg BootstrapConfig) er } } + if cfg.LoadBackupBootstrapPeers == nil { + log.Debugf("not enough bootstrap peers to fill the remaining target of %d connections", numToDial) + return ErrNotEnoughBootstrapPeers + } + log.Debugf("not enough bootstrap peers to fill the remaining target of %d connections, trying backup list", numToDial) tempBootstrapPeers := cfg.LoadBackupBootstrapPeers(ctx) diff --git a/core/bootstrap/bootstrap_test.go b/core/bootstrap/bootstrap_test.go index 39490a474c7..7a727ee62c3 100644 --- a/core/bootstrap/bootstrap_test.go +++ b/core/bootstrap/bootstrap_test.go @@ -1,8 +1,12 @@ package bootstrap import ( + "crypto/rand" "testing" + "time" + "github.com/libp2p/go-libp2p" + "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/test" ) @@ -23,3 +27,31 @@ func TestRandomizeAddressList(t *testing.T) { t.Fail() } } + +func TestNoTempPeersLoadAndSave(t *testing.T) { + period := 500 * time.Millisecond + bootCfg := BootstrapConfigWithPeers(nil) + bootCfg.MinPeerThreshold = 2 + bootCfg.Period = period + + priv, pub, err := crypto.GenerateEd25519Key(rand.Reader) + if err != nil { + t.Fatal(err) + } + peerID, err := peer.IDFromPublicKey(pub) + if err != nil { + t.Fatal(err) + } + p2pHost, err := libp2p.New(libp2p.Identity(priv)) + if err != nil { + t.Fatal(err) + } + + bootstrapper, err := Bootstrap(peerID, p2pHost, nil, bootCfg) + if err != nil { + t.Fatal(err) + } + + time.Sleep(4 * period) + bootstrapper.Close() +}