github.com/amazechain/amc@v0.1.3/internal/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 "github.com/amazechain/amc/common/mclock" 22 "github.com/amazechain/amc/internal/p2p/enode" 23 "github.com/amazechain/amc/internal/p2p/enr" 24 "github.com/amazechain/amc/internal/p2p/netutil" 25 "github.com/amazechain/amc/log" 26 "net" 27 ) 28 29 // UDPConn is a network connection on which discovery can operate. 30 type UDPConn interface { 31 ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) 32 WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) 33 Close() error 34 LocalAddr() net.Addr 35 } 36 37 type V5Config struct { 38 ProtocolID *[6]byte 39 } 40 41 // Config holds settings for the discovery listener. 42 type Config struct { 43 // These settings are required and configure the UDP listener: 44 PrivateKey *ecdsa.PrivateKey 45 46 // These settings are optional: 47 NetRestrict *netutil.Netlist // list of allowed IP networks 48 Bootnodes []*enode.Node // list of bootstrap nodes 49 Unhandled chan<- ReadPacket // unhandled packets are sent on this channel 50 Log log.Logger // if set, log messages go here 51 52 // V5ProtocolID configures the discv5 protocol identifier. 53 V5ProtocolID *[6]byte 54 55 ValidSchemes enr.IdentityScheme // allowed identity schemes 56 Clock mclock.Clock 57 } 58 59 func (cfg Config) withDefaults() Config { 60 if cfg.Log == nil { 61 cfg.Log = log.Root() 62 } 63 if cfg.ValidSchemes == nil { 64 cfg.ValidSchemes = enode.ValidSchemes 65 } 66 if cfg.Clock == nil { 67 cfg.Clock = mclock.System{} 68 } 69 return cfg 70 } 71 72 // ListenUDP starts listening for discovery packets on the given UDP socket. 73 func ListenUDP(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) { 74 return ListenV4(c, ln, cfg) 75 } 76 77 // ReadPacket is a packet that couldn't be handled. Those packets are sent to the unhandled 78 // channel if configured. 79 type ReadPacket struct { 80 Data []byte 81 Addr *net.UDPAddr 82 } 83 84 func min(x, y int) int { 85 if x > y { 86 return y 87 } 88 return x 89 }