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, realaddr *net.UDPAddr, nodeDBPath string, netrestrict *netutil.Netlist) (*Network, error) {
  201. transport, err := listenUDP(priv, conn, realaddr)
  202. if err != nil {
  203. return nil, err
  204. }
  205. net, err := newNetwork(transport, priv.PublicKey, nodeDBPath, netrestrict)
  206. if err != nil {
  207. return nil, err
  208. }
  209. log.Info("UDP listener up", "net", net.tab.self)
  210. transport.net = net
  211. go transport.readLoop()
  212. return net, nil
  213. }
  214. func listenUDP(priv *ecdsa.PrivateKey, conn conn, realaddr *net.UDPAddr) (*udp, error) {
  215. return &udp{conn: conn, priv: priv, ourEndpoint: makeEndpoint(realaddr, uint16(realaddr.Port))}, nil
  216. }
  217. func (t *udp) localAddr() *net.UDPAddr {
  218. return t.conn.LocalAddr().(*net.UDPAddr)
  219. }
  220. func (t *udp) Close() {
  221. t.conn.Close()
  222. }
  223. func (t *udp) send(remote *Node, ptype nodeEvent, data interface{}) (hash []byte) {
  224. hash, _ = t.sendPacket(remote.ID, remote.addr(), byte(ptype), data)
  225. return hash
  226. }
  227. func (t *udp) sendPing(remote *Node, toaddr *net.UDPAddr, topics []Topic) (hash []byte) {
  228. hash, _ = t.sendPacket(remote.ID, toaddr, byte(pingPacket), ping{
  229. Version: Version,
  230. From: t.ourEndpoint,
  231. To: makeEndpoint(toaddr, uint16(toaddr.Port)), // TODO: maybe use known TCP port from DB
  232. Expiration: uint64(time.Now().Add(expiration).Unix()),
  233. Topics: topics,
  234. })
  235. return hash
  236. }
  237. func (t *udp) sendFindnode(remote *Node, target NodeID) {
  238. t.sendPacket(remote.ID, remote.addr(), byte(findnodePacket), findnode{
  239. Target: target,
  240. Expiration: uint64(time.Now().Add(expiration).Unix()),
  241. })
  242. }
  243. func (t *udp) sendNeighbours(remote *Node, results []*Node) {
  244. // Send neighbors in chunks with at most maxNeighbors per packet
  245. // to stay below the 1280 byte limit.
  246. p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
  247. for i, result := range results {
  248. p.Nodes = append(p.Nodes, nodeToRPC(result))
  249. if len(p.Nodes) == maxNeighbors || i == len(results)-1 {
  250. t.sendPacket(remote.ID, remote.addr(), byte(neighborsPacket), p)
  251. p.Nodes = p.Nodes[:0]
  252. }
  253. }
  254. }
  255. func (t *udp) sendFindnodeHash(remote *Node, target common.Hash) {
  256. t.sendPacket(remote.ID, remote.addr(), byte(findnodeHashPacket), findnodeHash{
  257. Target: target,
  258. Expiration: uint64(time.Now().Add(expiration).Unix()),
  259. })
  260. }
  261. func (t *udp) sendTopicRegister(remote *Node, topics []Topic, idx int, pong []byte) {
  262. t.sendPacket(remote.ID, remote.addr(), byte(topicRegisterPacket), topicRegister{
  263. Topics: topics,
  264. Idx: uint(idx),
  265. Pong: pong,
  266. })
  267. }
  268. func (t *udp) sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node) {
  269. p := topicNodes{Echo: queryHash}
  270. var sent bool
  271. for _, result := range nodes {
  272. if result.IP.Equal(t.net.tab.self.IP) || netutil.CheckRelayIP(remote.IP, result.IP) == nil {
  273. p.Nodes = append(p.Nodes, nodeToRPC(result))
  274. }
  275. if len(p.Nodes) == maxTopicNodes {
  276. t.sendPacket(remote.ID, remote.addr(), byte(topicNodesPacket), p)
  277. p.Nodes = p.Nodes[:0]
  278. sent = true
  279. }
  280. }
  281. if !sent || len(p.Nodes) > 0 {
  282. t.sendPacket(remote.ID, remote.addr(), byte(topicNodesPacket), p)
  283. }
  284. }
  285. func (t *udp) sendPacket(toid NodeID, toaddr *net.UDPAddr, ptype byte, req interface{}) (hash []byte, err error) {
  286. //fmt.Println("sendPacket", nodeEvent(ptype), toaddr.String(), toid.String())
  287. packet, hash, err := encodePacket(t.priv, ptype, req)
  288. if err != nil {
  289. //fmt.Println(err)
  290. return hash, err
  291. }
  292. log.Trace(fmt.Sprintf(">>> %v to %x@%v", nodeEvent(ptype), toid[:8], toaddr))
  293. if nbytes, err := t.conn.WriteToUDP(packet, toaddr); err != nil {
  294. log.Trace(fmt.Sprint("UDP send failed:", err))
  295. } else {
  296. egressTrafficMeter.Mark(int64(nbytes))
  297. }
  298. //fmt.Println(err)
  299. return hash, err
  300. }
  301. // zeroed padding space for encodePacket.
  302. var headSpace = make([]byte, headSize)
  303. func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (p, hash []byte, err error) {
  304. b := new(bytes.Buffer)
  305. b.Write(headSpace)
  306. b.WriteByte(ptype)
  307. if err := rlp.Encode(b, req); err != nil {
  308. log.Error(fmt.Sprint("error encoding packet:", err))
  309. return nil, nil, err
  310. }
  311. packet := b.Bytes()
  312. sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
  313. if err != nil {
  314. log.Error(fmt.Sprint("could not sign packet:", err))
  315. return nil, nil, err
  316. }
  317. copy(packet, versionPrefix)
  318. copy(packet[versionPrefixSize:], sig)
  319. hash = crypto.Keccak256(packet[versionPrefixSize:])
  320. return packet, hash, nil
  321. }
  322. // readLoop runs in its own goroutine. it injects ingress UDP packets
  323. // into the network loop.
  324. func (t *udp) readLoop() {
  325. defer t.conn.Close()
  326. // Discovery packets are defined to be no larger than 1280 bytes.
  327. // Packets larger than this size will be cut at the end and treated
  328. // as invalid because their hash won't match.
  329. buf := make([]byte, 1280)
  330. for {
  331. nbytes, from, err := t.conn.ReadFromUDP(buf)
  332. ingressTrafficMeter.Mark(int64(nbytes))
  333. if netutil.IsTemporaryError(err) {
  334. // Ignore temporary read errors.
  335. log.Debug(fmt.Sprintf("Temporary read error: %v", err))
  336. continue
  337. } else if err != nil {
  338. // Shut down the loop for permament errors.
  339. log.Debug(fmt.Sprintf("Read error: %v", err))
  340. return
  341. }
  342. t.handlePacket(from, buf[:nbytes])
  343. }
  344. }
  345. func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error {
  346. pkt := ingressPacket{remoteAddr: from}
  347. if err := decodePacket(buf, &pkt); err != nil {
  348. log.Debug(fmt.Sprintf("Bad packet from %v: %v", from, err))
  349. //fmt.Println("bad packet", err)
  350. return err
  351. }
  352. t.net.reqReadPacket(pkt)
  353. return nil
  354. }
  355. func decodePacket(buffer []byte, pkt *ingressPacket) error {
  356. if len(buffer) < headSize+1 {
  357. return errPacketTooSmall
  358. }
  359. buf := make([]byte, len(buffer))
  360. copy(buf, buffer)
  361. prefix, sig, sigdata := buf[:versionPrefixSize], buf[versionPrefixSize:headSize], buf[headSize:]
  362. if !bytes.Equal(prefix, versionPrefix) {
  363. return errBadPrefix
  364. }
  365. fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig)
  366. if err != nil {
  367. return err
  368. }
  369. pkt.rawData = buf
  370. pkt.hash = crypto.Keccak256(buf[versionPrefixSize:])
  371. pkt.remoteID = fromID
  372. switch pkt.ev = nodeEvent(sigdata[0]); pkt.ev {
  373. case pingPacket:
  374. pkt.data = new(ping)
  375. case pongPacket:
  376. pkt.data = new(pong)
  377. case findnodePacket:
  378. pkt.data = new(findnode)
  379. case neighborsPacket:
  380. pkt.data = new(neighbors)
  381. case findnodeHashPacket:
  382. pkt.data = new(findnodeHash)
  383. case topicRegisterPacket:
  384. pkt.data = new(topicRegister)
  385. case topicQueryPacket:
  386. pkt.data = new(topicQuery)
  387. case topicNodesPacket:
  388. pkt.data = new(topicNodes)
  389. default:
  390. return fmt.Errorf("unknown packet type: %d", sigdata[0])
  391. }
  392. s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0)
  393. err = s.Decode(pkt.data)
  394. return err
  395. }