Skip to content

Commit a72fa88

Browse files
zsfelfoldifjl
andauthored
les: switch to new discv5 (#21940)
This PR enables running the new discv5 protocol in both LES client and server mode. In client mode it mixes discv5 and dnsdisc iterators (if both are enabled) and filters incoming ENRs for "les" tag and fork ID. The old p2p/discv5 package and all references to it are removed. Co-authored-by: Felix Lange <fjl@twurst.com>
1 parent 9c57293 commit a72fa88

31 files changed

Lines changed: 113 additions & 6184 deletions

‎cmd/bootnode/main.go‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import (
2828
"github.com/ethereum/go-ethereum/crypto"
2929
"github.com/ethereum/go-ethereum/log"
3030
"github.com/ethereum/go-ethereum/p2p/discover"
31-
"github.com/ethereum/go-ethereum/p2p/discv5"
3231
"github.com/ethereum/go-ethereum/p2p/enode"
3332
"github.com/ethereum/go-ethereum/p2p/nat"
3433
"github.com/ethereum/go-ethereum/p2p/netutil"
@@ -121,17 +120,17 @@ func main() {
121120

122121
printNotice(&nodeKey.PublicKey, *realaddr)
123122

123+
db, _ := enode.OpenDB("")
124+
ln := enode.NewLocalNode(db, nodeKey)
125+
cfg := discover.Config{
126+
PrivateKey: nodeKey,
127+
NetRestrict: restrictList,
128+
}
124129
if *runv5 {
125-
if _, err := discv5.ListenUDP(nodeKey, conn, "", restrictList); err != nil {
130+
if _, err := discover.ListenV5(conn, ln, cfg); err != nil {
126131
utils.Fatalf("%v", err)
127132
}
128133
} else {
129-
db, _ := enode.OpenDB("")
130-
ln := enode.NewLocalNode(db, nodeKey)
131-
cfg := discover.Config{
132-
PrivateKey: nodeKey,
133-
NetRestrict: restrictList,
134-
}
135134
if _, err := discover.ListenUDP(conn, ln, cfg); err != nil {
136135
utils.Fatalf("%v", err)
137136
}

‎cmd/faucet/faucet.go‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ import (
5555
"github.com/ethereum/go-ethereum/log"
5656
"github.com/ethereum/go-ethereum/node"
5757
"github.com/ethereum/go-ethereum/p2p"
58-
"github.com/ethereum/go-ethereum/p2p/discv5"
5958
"github.com/ethereum/go-ethereum/p2p/enode"
6059
"github.com/ethereum/go-ethereum/p2p/nat"
6160
"github.com/ethereum/go-ethereum/params"
@@ -154,9 +153,9 @@ func main() {
154153
log.Crit("Failed to parse genesis block json", "err", err)
155154
}
156155
// Convert the bootnodes to internal enode representations
157-
var enodes []*discv5.Node
156+
var enodes []*enode.Node
158157
for _, boot := range strings.Split(*bootFlag, ",") {
159-
if url, err := discv5.ParseNode(boot); err == nil {
158+
if url, err := enode.Parse(enode.ValidSchemes, boot); err == nil {
160159
enodes = append(enodes, url)
161160
} else {
162161
log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
@@ -228,7 +227,7 @@ type wsConn struct {
228227
wlock sync.Mutex
229228
}
230229

231-
func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
230+
func newFaucet(genesis *core.Genesis, port int, enodes []*enode.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
232231
// Assemble the raw devp2p protocol stack
233232
stack, err := node.New(&node.Config{
234233
Name: "geth",

‎cmd/utils/flags.go‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,6 @@ import (
5959
"github.com/ethereum/go-ethereum/miner"
6060
"github.com/ethereum/go-ethereum/node"
6161
"github.com/ethereum/go-ethereum/p2p"
62-
"github.com/ethereum/go-ethereum/p2p/discv5"
6362
"github.com/ethereum/go-ethereum/p2p/enode"
6463
"github.com/ethereum/go-ethereum/p2p/nat"
6564
"github.com/ethereum/go-ethereum/p2p/netutil"
@@ -842,30 +841,22 @@ func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) {
842841
// setBootstrapNodesV5 creates a list of bootstrap nodes from the command line
843842
// flags, reverting to pre-configured ones if none have been specified.
844843
func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) {
845-
urls := params.MainnetBootnodes
844+
urls := params.V5Bootnodes
846845
switch {
847846
case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(LegacyBootnodesV5Flag.Name):
848847
if ctx.GlobalIsSet(LegacyBootnodesV5Flag.Name) {
849848
urls = SplitAndTrim(ctx.GlobalString(LegacyBootnodesV5Flag.Name))
850849
} else {
851850
urls = SplitAndTrim(ctx.GlobalString(BootnodesFlag.Name))
852851
}
853-
case ctx.GlobalBool(RopstenFlag.Name):
854-
urls = params.RopstenBootnodes
855-
case ctx.GlobalBool(RinkebyFlag.Name):
856-
urls = params.RinkebyBootnodes
857-
case ctx.GlobalBool(GoerliFlag.Name):
858-
urls = params.GoerliBootnodes
859-
case ctx.GlobalBool(YoloV2Flag.Name):
860-
urls = params.YoloV2Bootnodes
861852
case cfg.BootstrapNodesV5 != nil:
862853
return // already set, don't apply defaults.
863854
}
864855

865-
cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls))
856+
cfg.BootstrapNodesV5 = make([]*enode.Node, 0, len(urls))
866857
for _, url := range urls {
867858
if url != "" {
868-
node, err := discv5.ParseNode(url)
859+
node, err := enode.Parse(enode.ValidSchemes, url)
869860
if err != nil {
870861
log.Error("Bootstrap URL invalid", "enode", url, "err", err)
871862
continue

‎les/client.go‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ type LightEthereum struct {
7272
netRPCService *ethapi.PublicNetAPI
7373

7474
p2pServer *p2p.Server
75+
p2pConfig *p2p.Config
7576
}
7677

7778
// New creates an instance of the light client.
@@ -109,14 +110,11 @@ func New(stack *node.Node, config *eth.Config) (*LightEthereum, error) {
109110
bloomIndexer: eth.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
110111
valueTracker: lpc.NewValueTracker(lespayDb, &mclock.System{}, requestList, time.Minute, 1/float64(time.Hour), 1/float64(time.Hour*100), 1/float64(time.Hour*1000)),
111112
p2pServer: stack.Server(),
113+
p2pConfig: &stack.Config().P2P,
112114
}
113115
peers.subscribe((*vtSubscription)(leth.valueTracker))
114116

115-
dnsdisc, err := leth.setupDiscovery()
116-
if err != nil {
117-
return nil, err
118-
}
119-
leth.serverPool = newServerPool(lespayDb, []byte("serverpool:"), leth.valueTracker, dnsdisc, time.Second, nil, &mclock.System{}, config.UltraLightServers)
117+
leth.serverPool = newServerPool(lespayDb, []byte("serverpool:"), leth.valueTracker, time.Second, nil, &mclock.System{}, config.UltraLightServers)
120118
peers.subscribe(leth.serverPool)
121119
leth.dialCandidates = leth.serverPool.dialIterator
122120

@@ -299,6 +297,11 @@ func (s *LightEthereum) Protocols() []p2p.Protocol {
299297
func (s *LightEthereum) Start() error {
300298
log.Warn("Light client mode is an experimental feature")
301299

300+
discovery, err := s.setupDiscovery(s.p2pConfig)
301+
if err != nil {
302+
return err
303+
}
304+
s.serverPool.addSource(discovery)
302305
s.serverPool.start()
303306
// Start bloom request workers.
304307
s.wg.Add(bloomServiceThreads)

‎les/commons.go‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ import (
3333
"github.com/ethereum/go-ethereum/log"
3434
"github.com/ethereum/go-ethereum/node"
3535
"github.com/ethereum/go-ethereum/p2p"
36-
"github.com/ethereum/go-ethereum/p2p/discv5"
3736
"github.com/ethereum/go-ethereum/p2p/enode"
3837
"github.com/ethereum/go-ethereum/params"
3938
)
@@ -42,17 +41,6 @@ func errResp(code errCode, format string, v ...interface{}) error {
4241
return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
4342
}
4443

45-
func lesTopic(genesisHash common.Hash, protocolVersion uint) discv5.Topic {
46-
var name string
47-
switch protocolVersion {
48-
case lpv2:
49-
name = "LES2"
50-
default:
51-
panic(nil)
52-
}
53-
return discv5.Topic(name + "@" + common.Bytes2Hex(genesisHash.Bytes()[0:8]))
54-
}
55-
5644
type chainReader interface {
5745
CurrentHeader() *types.Header
5846
}

‎les/enr_entry.go‎

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
package les
1818

1919
import (
20+
"github.com/ethereum/go-ethereum/core/forkid"
21+
"github.com/ethereum/go-ethereum/p2p"
2022
"github.com/ethereum/go-ethereum/p2p/dnsdisc"
2123
"github.com/ethereum/go-ethereum/p2p/enode"
2224
"github.com/ethereum/go-ethereum/rlp"
@@ -25,19 +27,46 @@ import (
2527
// lesEntry is the "les" ENR entry. This is set for LES servers only.
2628
type lesEntry struct {
2729
// Ignore additional fields (for forward compatibility).
28-
Rest []rlp.RawValue `rlp:"tail"`
30+
_ []rlp.RawValue `rlp:"tail"`
2931
}
3032

31-
// ENRKey implements enr.Entry.
32-
func (e lesEntry) ENRKey() string {
33-
return "les"
33+
func (lesEntry) ENRKey() string { return "les" }
34+
35+
// ethEntry is the "eth" ENR entry. This is redeclared here to avoid depending on package eth.
36+
type ethEntry struct {
37+
ForkID forkid.ID
38+
_ []rlp.RawValue `rlp:"tail"`
3439
}
3540

41+
func (ethEntry) ENRKey() string { return "eth" }
42+
3643
// setupDiscovery creates the node discovery source for the eth protocol.
37-
func (eth *LightEthereum) setupDiscovery() (enode.Iterator, error) {
38-
if len(eth.config.EthDiscoveryURLs) == 0 {
39-
return nil, nil
44+
func (eth *LightEthereum) setupDiscovery(cfg *p2p.Config) (enode.Iterator, error) {
45+
it := enode.NewFairMix(0)
46+
47+
// Enable DNS discovery.
48+
if len(eth.config.EthDiscoveryURLs) != 0 {
49+
client := dnsdisc.NewClient(dnsdisc.Config{})
50+
dns, err := client.NewIterator(eth.config.EthDiscoveryURLs...)
51+
if err != nil {
52+
return nil, err
53+
}
54+
it.AddSource(dns)
55+
}
56+
57+
// Enable DHT.
58+
if cfg.DiscoveryV5 && eth.p2pServer.DiscV5 != nil {
59+
it.AddSource(eth.p2pServer.DiscV5.RandomNodes())
4060
}
41-
client := dnsdisc.NewClient(dnsdisc.Config{})
42-
return client.NewIterator(eth.config.EthDiscoveryURLs...)
61+
62+
forkFilter := forkid.NewFilter(eth.blockchain)
63+
iterator := enode.Filter(it, func(n *enode.Node) bool { return nodeIsServer(forkFilter, n) })
64+
return iterator, nil
65+
}
66+
67+
// nodeIsServer checks whether n is an LES server node.
68+
func nodeIsServer(forkFilter forkid.Filter, n *enode.Node) bool {
69+
var les lesEntry
70+
var eth ethEntry
71+
return n.Load(&les) == nil && n.Load(&eth) == nil && forkFilter(eth.ForkID) == nil
4372
}

‎les/server.go‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ import (
2929
"github.com/ethereum/go-ethereum/log"
3030
"github.com/ethereum/go-ethereum/node"
3131
"github.com/ethereum/go-ethereum/p2p"
32-
"github.com/ethereum/go-ethereum/p2p/discv5"
3332
"github.com/ethereum/go-ethereum/p2p/enode"
3433
"github.com/ethereum/go-ethereum/p2p/enr"
3534
"github.com/ethereum/go-ethereum/p2p/nodestate"
@@ -58,7 +57,6 @@ type LesServer struct {
5857
archiveMode bool // Flag whether the ethereum node runs in archive mode.
5958
handler *serverHandler
6059
broadcaster *broadcaster
61-
lesTopics []discv5.Topic
6260
privateKey *ecdsa.PrivateKey
6361

6462
// Flow control and capacity management
@@ -77,11 +75,6 @@ type LesServer struct {
7775

7876
func NewLesServer(node *node.Node, e *eth.Ethereum, config *eth.Config) (*LesServer, error) {
7977
ns := nodestate.NewNodeStateMachine(nil, nil, mclock.System{}, serverSetup)
80-
// Collect les protocol version information supported by local node.
81-
lesTopics := make([]discv5.Topic, len(AdvertiseProtocolVersions))
82-
for i, pv := range AdvertiseProtocolVersions {
83-
lesTopics[i] = lesTopic(e.BlockChain().Genesis().Hash(), pv)
84-
}
8578
// Calculate the number of threads used to service the light client
8679
// requests based on the user-specified value.
8780
threads := config.LightServ * 4 / 100
@@ -103,7 +96,6 @@ func NewLesServer(node *node.Node, e *eth.Ethereum, config *eth.Config) (*LesSer
10396
ns: ns,
10497
archiveMode: e.ArchiveMode(),
10598
broadcaster: newBroadcaster(ns),
106-
lesTopics: lesTopics,
10799
fcManager: flowcontrol.NewClientManager(nil, &mclock.System{}),
108100
servingQueue: newServingQueue(int64(time.Millisecond*10), float64(config.LightServ)/100),
109101
threadsBusy: config.LightServ/100 + 1,
@@ -203,19 +195,6 @@ func (s *LesServer) Start() error {
203195
s.wg.Add(1)
204196
go s.capacityManagement()
205197

206-
if s.p2pSrv.DiscV5 != nil {
207-
for _, topic := range s.lesTopics {
208-
topic := topic
209-
go func() {
210-
logger := log.New("topic", topic)
211-
logger.Info("Starting topic registration")
212-
defer logger.Info("Terminated topic registration")
213-
214-
s.p2pSrv.DiscV5.RegisterTopic(topic, s.closeCh)
215-
}()
216-
}
217-
}
218-
219198
return nil
220199
}
221200

‎les/serverpool.go‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ var (
131131
)
132132

133133
// newServerPool creates a new server pool
134-
func newServerPool(db ethdb.KeyValueStore, dbKey []byte, vt *lpc.ValueTracker, discovery enode.Iterator, mixTimeout time.Duration, query queryFunc, clock mclock.Clock, trustedURLs []string) *serverPool {
134+
func newServerPool(db ethdb.KeyValueStore, dbKey []byte, vt *lpc.ValueTracker, mixTimeout time.Duration, query queryFunc, clock mclock.Clock, trustedURLs []string) *serverPool {
135135
s := &serverPool{
136136
db: db,
137137
clock: clock,
@@ -147,9 +147,6 @@ func newServerPool(db ethdb.KeyValueStore, dbKey []byte, vt *lpc.ValueTracker, d
147147
alwaysConnect := lpc.NewQueueIterator(s.ns, sfAlwaysConnect, sfDisableSelection, true, nil)
148148
s.mixSources = append(s.mixSources, knownSelector)
149149
s.mixSources = append(s.mixSources, alwaysConnect)
150-
if discovery != nil {
151-
s.mixSources = append(s.mixSources, discovery)
152-
}
153150

154151
iter := enode.Iterator(s.mixer)
155152
if query != nil {
@@ -175,6 +172,13 @@ func newServerPool(db ethdb.KeyValueStore, dbKey []byte, vt *lpc.ValueTracker, d
175172
return s
176173
}
177174

175+
// addSource adds a node discovery source to the server pool (should be called before start)
176+
func (s *serverPool) addSource(source enode.Iterator) {
177+
if source != nil {
178+
s.mixSources = append(s.mixSources, source)
179+
}
180+
}
181+
178182
// addPreNegFilter installs a node filter mechanism that performs a pre-negotiation query.
179183
// Nodes that are filtered out and does not appear on the output iterator are put back
180184
// into redialWait state.

‎les/serverpool_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,8 @@ func (s *serverPoolTest) start() {
145145
}
146146

147147
s.vt = lpc.NewValueTracker(s.db, s.clock, requestList, time.Minute, 1/float64(time.Hour), 1/float64(time.Hour*100), 1/float64(time.Hour*1000))
148-
s.sp = newServerPool(s.db, []byte("serverpool:"), s.vt, s.input, 0, testQuery, s.clock, s.trusted)
148+
s.sp = newServerPool(s.db, []byte("serverpool:"), s.vt, 0, testQuery, s.clock, s.trusted)
149+
s.sp.addSource(s.input)
149150
s.sp.validSchemes = enode.ValidSchemesForTesting
150151
s.sp.unixTime = func() int64 { return int64(s.clock.Now()) / int64(time.Second) }
151152
s.disconnect = make(map[int][]int)

‎mobile/discover.go‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@ package geth
2222
import (
2323
"errors"
2424

25-
"github.com/ethereum/go-ethereum/p2p/discv5"
25+
"github.com/ethereum/go-ethereum/p2p/enode"
2626
)
2727

2828
// Enode represents a host on the network.
2929
type Enode struct {
30-
node *discv5.Node
30+
node *enode.Node
3131
}
3232

3333
// NewEnode parses a node designator.
@@ -53,21 +53,21 @@ type Enode struct {
5353
// and UDP discovery port 30301.
5454
//
5555
// enode://<hex node id>@10.3.58.6:30303?discport=30301
56-
func NewEnode(rawurl string) (enode *Enode, _ error) {
57-
node, err := discv5.ParseNode(rawurl)
56+
func NewEnode(rawurl string) (*Enode, error) {
57+
node, err := enode.Parse(enode.ValidSchemes, rawurl)
5858
if err != nil {
5959
return nil, err
6060
}
6161
return &Enode{node}, nil
6262
}
6363

6464
// Enodes represents a slice of accounts.
65-
type Enodes struct{ nodes []*discv5.Node }
65+
type Enodes struct{ nodes []*enode.Node }
6666

6767
// NewEnodes creates a slice of uninitialized enodes.
6868
func NewEnodes(size int) *Enodes {
6969
return &Enodes{
70-
nodes: make([]*discv5.Node, size),
70+
nodes: make([]*enode.Node, size),
7171
}
7272
}
7373

0 commit comments

Comments
 (0)