udp.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. // Copyright 2016 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. package discv5
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/p2p/nat"
  28. "github.com/ethereum/go-ethereum/p2p/netutil"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. )
  31. const Version = 4
  32. // Errors
  33. var (
  34. errPacketTooSmall = errors.New("too small")
  35. errBadPrefix = errors.New("bad prefix")
  36. errTimeout = errors.New("RPC timeout")
  37. )
  38. // Timeouts
  39. const (
  40. respTimeout = 500 * time.Millisecond
  41. expiration = 20 * time.Second
  42. driftThreshold = 10 * time.Second // Allowed clock drift before warning user
  43. )
  44. // RPC request structures
  45. type (
  46. ping struct {
  47. Version uint
  48. From, To rpcEndpoint
  49. Expiration uint64
  50. // v5
  51. Topics []Topic
  52. // Ignore additional fields (for forward compatibility).
  53. Rest []rlp.RawValue `rlp:"tail"`
  54. }
  55. // pong is the reply to ping.
  56. pong struct {
  57. // This field should mirror the UDP envelope address
  58. // of the ping packet, which provides a way to discover the
  59. // the external address (after NAT).
  60. To rpcEndpoint
  61. ReplyTok []byte // This contains the hash of the ping packet.
  62. Expiration uint64 // Absolute timestamp at which the packet becomes invalid.
  63. // v5
  64. TopicHash common.Hash
  65. TicketSerial uint32
  66. WaitPeriods []uint32
  67. // Ignore additional fields (for forward compatibility).
  68. Rest []rlp.RawValue `rlp:"tail"`
  69. }
  70. // findnode is a query for nodes close to the given target.
  71. findnode struct {
  72. Target NodeID // doesn't need to be an actual public key
  73. Expiration uint64
  74. // Ignore additional fields (for forward compatibility).
  75. Rest []rlp.RawValue `rlp:"tail"`
  76. }
  77. // findnode is a query for nodes close to the given target.
  78. findnodeHash struct {
  79. Target common.Hash
  80. Expiration uint64
  81. // Ignore additional fields (for forward compatibility).
  82. Rest []rlp.RawValue `rlp:"tail"`
  83. }
  84. // reply to findnode
  85. neighbors struct {
  86. Nodes []rpcNode
  87. Expiration uint64
  88. // Ignore additional fields (for forward compatibility).
  89. Rest []rlp.RawValue `rlp:"tail"`
  90. }
  91. topicRegister struct {
  92. Topics []Topic
  93. Idx uint
  94. Pong []byte
  95. }
  96. topicQuery struct {
  97. Topic Topic
  98. Expiration uint64
  99. }
  100. // reply to topicQuery
  101. topicNodes struct {
  102. Echo common.Hash
  103. Nodes []rpcNode
  104. }
  105. rpcNode struct {
  106. IP net.IP // len 4 for IPv4 or 16 for IPv6
  107. UDP uint16 // for discovery protocol
  108. TCP uint16 // for RLPx protocol
  109. ID NodeID
  110. }
  111. rpcEndpoint struct {
  112. IP net.IP // len 4 for IPv4 or 16 for IPv6
  113. UDP uint16 // for discovery protocol
  114. TCP uint16 // for RLPx protocol
  115. }
  116. )
  117. var (
  118. versionPrefix = []byte("temporary discovery v5")
  119. versionPrefixSize = len(versionPrefix)
  120. sigSize = 520 / 8
  121. headSize = versionPrefixSize + sigSize // space of packet frame data
  122. )
  123. // Neighbors replies are sent across multiple packets to
  124. // stay below the 1280 byte limit. We compute the maximum number
  125. // of entries by stuffing a packet until it grows too large.
  126. var maxNeighbors = func() int {
  127. p := neighbors{Expiration: ^uint64(0)}
  128. maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
  129. for n := 0; ; n++ {
  130. p.Nodes = append(p.Nodes, maxSizeNode)
  131. size, _, err := rlp.EncodeToReader(p)
  132. if err != nil {
  133. // If this ever happens, it will be caught by the unit tests.
  134. panic("cannot encode: " + err.Error())
  135. }
  136. if headSize+size+1 >= 1280 {
  137. return n
  138. }
  139. }
  140. }()
  141. var maxTopicNodes = func() int {
  142. p := topicNodes{}
  143. maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
  144. for n := 0; ; n++ {
  145. p.Nodes = append(p.Nodes, maxSizeNode)
  146. size, _, err := rlp.EncodeToReader(p)
  147. if err != nil {
  148. // If this ever happens, it will be caught by the unit tests.
  149. panic("cannot encode: " + err.Error())
  150. }
  151. if headSize+size+1 >= 1280 {
  152. return n
  153. }
  154. }
  155. }()
  156. func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint {
  157. ip := addr.IP.To4()
  158. if ip == nil {
  159. ip = addr.IP.To16()
  160. }
  161. return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort}
  162. }
  163. func (e1 rpcEndpoint) equal(e2 rpcEndpoint) bool {
  164. return e1.UDP == e2.UDP && e1.TCP == e2.TCP && e1.IP.Equal(e2.IP)
  165. }
  166. func nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*Node, error) {
  167. if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
  168. return nil, err
  169. }
  170. n := NewNode(rn.ID, rn.IP, rn.UDP, rn.TCP)
  171. err := n.validateComplete()
  172. return n, err
  173. }
  174. func nodeToRPC(n *Node) rpcNode {
  175. return rpcNode{ID: n.ID, IP: n.IP, UDP: n.UDP, TCP: n.TCP}
  176. }
  177. type ingressPacket struct {
  178. remoteID NodeID
  179. remoteAddr *net.UDPAddr
  180. ev nodeEvent
  181. hash []byte
  182. data interface{} // one of the RPC structs
  183. rawData []byte
  184. }
  185. type conn interface {
  186. ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error)
  187. WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error)
  188. Close() error
  189. LocalAddr() net.Addr
  190. }
  191. // udp implements the RPC protocol.
  192. type udp struct {
  193. conn conn
  194. priv *ecdsa.PrivateKey
  195. ourEndpoint rpcEndpoint
  196. nat nat.Interface
  197. net *Network
  198. }
  199. // ListenUDP returns a new table that listens for UDP packets on laddr.
  200. func ListenUDP(priv *ecdsa.PrivateKey, conn conn, nodeDBPath string, netrestrict *netutil.Netlist) (*Network, error) {
  201. realaddr := conn.LocalAddr().(*net.UDPAddr)
  202. transport, err := listenUDP(priv, conn, realaddr)
  203. if err != nil {
  204. return nil, err
  205. }
  206. net, err := newNetwork(transport, priv.PublicKey, nodeDBPath, netrestrict)
  207. if err != nil {
  208. return nil, err
  209. }
  210. log.Info("UDP listener up", "net", net.tab.self)
  211. transport.net = net
  212. go transport.readLoop()
  213. return net, nil
  214. }
  215. func listenUDP(priv *ecdsa.PrivateKey, conn conn, realaddr *net.UDPAddr) (*udp, error) {
  216. return &udp{conn: conn, priv: priv, ourEndpoint: makeEndpoint(realaddr, uint16(realaddr.Port))}, nil
  217. }
  218. func (t *udp) localAddr() *net.UDPAddr {
  219. return t.conn.LocalAddr().(*net.UDPAddr)
  220. }
  221. func (t *udp) Close() {
  222. t.conn.Close()
  223. }
  224. func (t *udp) send(remote *Node, ptype nodeEvent, data interface{}) (hash []byte) {
  225. hash, _ = t.sendPacket(remote.ID, remote.addr(), byte(ptype), data)
  226. return hash
  227. }
  228. func (t *udp) sendPing(remote *Node, toaddr *net.UDPAddr, topics []Topic) (hash []byte) {
  229. hash, _ = t.sendPacket(remote.ID, toaddr, byte(pingPacket), ping{
  230. Version: Version,
  231. From: t.ourEndpoint,
  232. To: makeEndpoint(toaddr, uint16(toaddr.Port)), // TODO: maybe use known TCP port from DB
  233. Expiration: uint64(time.Now().Add(expiration).Unix()),
  234. Topics: topics,
  235. })
  236. return hash
  237. }
  238. func (t *udp) sendFindnode(remote *Node, target NodeID) {
  239. t.sendPacket(remote.ID, remote.addr(), byte(findnodePacket), findnode{
  240. Target: target,
  241. Expiration: uint64(time.Now().Add(expiration).Unix()),
  242. })
  243. }
  244. func (t *udp) sendNeighbours(remote *Node, results []*Node) {
  245. // Send neighbors in chunks with at most maxNeighbors per packet
  246. // to stay below the 1280 byte limit.
  247. p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
  248. for i, result := range results {
  249. p.Nodes = append(p.Nodes, nodeToRPC(result))
  250. if len(p.Nodes) == maxNeighbors || i == len(results)-1 {
  251. t.sendPacket(remote.ID, remote.addr(), byte(neighborsPacket), p)
  252. p.Nodes = p.Nodes[:0]
  253. }
  254. }
  255. }
  256. func (t *udp) sendFindnodeHash(remote *Node, target common.Hash) {
  257. t.sendPacket(remote.ID, remote.addr(), byte(findnodeHashPacket), findnodeHash{
  258. Target: target,
  259. Expiration: uint64(time.Now().Add(expiration).Unix()),
  260. })
  261. }
  262. func (t *udp) sendTopicRegister(remote *Node, topics []Topic, idx int, pong []byte) {
  263. t.sendPacket(remote.ID, remote.addr(), byte(topicRegisterPacket), topicRegister{
  264. Topics: topics,
  265. Idx: uint(idx),
  266. Pong: pong,
  267. })
  268. }
  269. func (t *udp) sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node) {
  270. p := topicNodes{Echo: queryHash}
  271. var sent bool
  272. for _, result := range nodes {
  273. if result.IP.Equal(t.net.tab.self.IP) || netutil.CheckRelayIP(remote.IP, result.IP) == nil {
  274. p.Nodes = append(p.Nodes, nodeToRPC(result))
  275. }
  276. if len(p.Nodes) == maxTopicNodes {
  277. t.sendPacket(remote.ID, remote.addr(), byte(topicNodesPacket), p)
  278. p.Nodes = p.Nodes[:0]
  279. sent = true
  280. }
  281. }
  282. if !sent || len(p.Nodes) > 0 {
  283. t.sendPacket(remote.ID, remote.addr(), byte(topicNodesPacket), p)
  284. }
  285. }
  286. func (t *udp) sendPacket(toid NodeID, toaddr *net.UDPAddr, ptype byte, req interface{}) (hash []byte, err error) {
  287. //fmt.Println("sendPacket", nodeEvent(ptype), toaddr.String(), toid.String())
  288. packet, hash, err := encodePacket(t.priv, ptype, req)
  289. if err != nil {
  290. //fmt.Println(err)
  291. return hash, err
  292. }
  293. log.Trace(fmt.Sprintf(">>> %v to %x@%v", nodeEvent(ptype), toid[:8], toaddr))
  294. if nbytes, err := t.conn.WriteToUDP(packet, toaddr); err != nil {
  295. log.Trace(fmt.Sprint("UDP send failed:", err))
  296. } else {
  297. egressTrafficMeter.Mark(int64(nbytes))
  298. }
  299. //fmt.Println(err)
  300. return hash, err
  301. }
  302. // zeroed padding space for encodePacket.
  303. var headSpace = make([]byte, headSize)
  304. func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (p, hash []byte, err error) {
  305. b := new(bytes.Buffer)
  306. b.Write(headSpace)
  307. b.WriteByte(ptype)
  308. if err := rlp.Encode(b, req); err != nil {
  309. log.Error(fmt.Sprint("error encoding packet:", err))
  310. return nil, nil, err
  311. }
  312. packet := b.Bytes()
  313. sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
  314. if err != nil {
  315. log.Error(fmt.Sprint("could not sign packet:", err))
  316. return nil, nil, err
  317. }
  318. copy(packet, versionPrefix)
  319. copy(packet[versionPrefixSize:], sig)
  320. hash = crypto.Keccak256(packet[versionPrefixSize:])
  321. return packet, hash, nil
  322. }
  323. // readLoop runs in its own goroutine. it injects ingress UDP packets
  324. // into the network loop.
  325. func (t *udp) readLoop() {
  326. defer t.conn.Close()
  327. // Discovery packets are defined to be no larger than 1280 bytes.
  328. // Packets larger than this size will be cut at the end and treated
  329. // as invalid because their hash won't match.
  330. buf := make([]byte, 1280)
  331. for {
  332. nbytes, from, err := t.conn.ReadFromUDP(buf)
  333. ingressTrafficMeter.Mark(int64(nbytes))
  334. if netutil.IsTemporaryError(err) {
  335. // Ignore temporary read errors.
  336. log.Debug(fmt.Sprintf("Temporary read error: %v", err))
  337. continue
  338. } else if err != nil {
  339. // Shut down the loop for permament errors.
  340. log.Debug(fmt.Sprintf("Read error: %v", err))
  341. return
  342. }
  343. t.handlePacket(from, buf[:nbytes])
  344. }
  345. }
  346. func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error {
  347. pkt := ingressPacket{remoteAddr: from}
  348. if err := decodePacket(buf, &pkt); err != nil {
  349. log.Debug(fmt.Sprintf("Bad packet from %v: %v", from, err))
  350. //fmt.Println("bad packet", err)
  351. return err
  352. }
  353. t.net.reqReadPacket(pkt)
  354. return nil
  355. }
  356. func decodePacket(buffer []byte, pkt *ingressPacket) error {
  357. if len(buffer) < headSize+1 {
  358. return errPacketTooSmall
  359. }
  360. buf := make([]byte, len(buffer))
  361. copy(buf, buffer)
  362. prefix, sig, sigdata := buf[:versionPrefixSize], buf[versionPrefixSize:headSize], buf[headSize:]
  363. if !bytes.Equal(prefix, versionPrefix) {
  364. return errBadPrefix
  365. }
  366. fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig)
  367. if err != nil {
  368. return err
  369. }
  370. pkt.rawData = buf
  371. pkt.hash = crypto.Keccak256(buf[versionPrefixSize:])
  372. pkt.remoteID = fromID
  373. switch pkt.ev = nodeEvent(sigdata[0]); pkt.ev {
  374. case pingPacket:
  375. pkt.data = new(ping)
  376. case pongPacket:
  377. pkt.data = new(pong)
  378. case findnodePacket:
  379. pkt.data = new(findnode)
  380. case neighborsPacket:
  381. pkt.data = new(neighbors)
  382. case findnodeHashPacket:
  383. pkt.data = new(findnodeHash)
  384. case topicRegisterPacket:
  385. pkt.data = new(topicRegister)
  386. case topicQueryPacket:
  387. pkt.data = new(topicQuery)
  388. case topicNodesPacket:
  389. pkt.data = new(topicNodes)
  390. default:
  391. return fmt.Errorf("unknown packet type: %d", sigdata[0])
  392. }
  393. s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0)
  394. err = s.Decode(pkt.data)
  395. return err
  396. }