github.com/jimmyx0x/go-ethereum@v1.10.28/p2p/discover/common.go (about) 1 // Copyright 2019 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package discover 18 19 import ( 20 "crypto/ecdsa" 21 "net" 22 23 "github.com/ethereum/go-ethereum/common/mclock" 24 "github.com/ethereum/go-ethereum/log" 25 "github.com/ethereum/go-ethereum/p2p/enode" 26 "github.com/ethereum/go-ethereum/p2p/enr" 27 "github.com/ethereum/go-ethereum/p2p/netutil" 28 ) 29 30 // UDPConn is a network connection on which discovery can operate. 31 type UDPConn interface { 32 ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) 33 WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) 34 Close() error 35 LocalAddr() net.Addr 36 } 37 38 type V5Config struct { 39 ProtocolID *[6]byte 40 } 41 42 // Config holds settings for the discovery listener. 43 type Config struct { 44 // These settings are required and configure the UDP listener: 45 PrivateKey *ecdsa.PrivateKey 46 47 // These settings are optional: 48 NetRestrict *netutil.Netlist // list of allowed IP networks 49 Bootnodes []*enode.Node // list of bootstrap nodes 50 Unhandled chan<- ReadPacket // unhandled packets are sent on this channel 51 Log log.Logger // if set, log messages go here 52 53 // V5ProtocolID configures the discv5 protocol identifier. 54 V5ProtocolID *[6]byte 55 56 ValidSchemes enr.IdentityScheme // allowed identity schemes 57 Clock mclock.Clock 58 } 59 60 func (cfg Config) withDefaults() Config { 61 if cfg.Log == nil { 62 cfg.Log = log.Root() 63 } 64 if cfg.ValidSchemes == nil { 65 cfg.ValidSchemes = enode.ValidSchemes 66 } 67 if cfg.Clock == nil { 68 cfg.Clock = mclock.System{} 69 } 70 return cfg 71 } 72 73 // ListenUDP starts listening for discovery packets on the given UDP socket. 74 func ListenUDP(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) { 75 return ListenV4(c, ln, cfg) 76 } 77 78 // ReadPacket is a packet that couldn't be handled. Those packets are sent to the unhandled 79 // channel if configured. 80 type ReadPacket struct { 81 Data []byte 82 Addr *net.UDPAddr 83 } 84 85 func min(x, y int) int { 86 if x > y { 87 return y 88 } 89 return x 90 }