udp.go 12 KB

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