udp.go 13 KB

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