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