github.com/Debrief-BC/go-debrief@v0.0.0-20200420203408-0c26ca968123/les/peer.go (about) 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 17 package les 18 19 import ( 20 "errors" 21 "fmt" 22 "math/big" 23 "math/rand" 24 "net" 25 "sync" 26 "sync/atomic" 27 "time" 28 29 "github.com/Debrief-BC/go-debrief/common" 30 "github.com/Debrief-BC/go-debrief/common/mclock" 31 "github.com/Debrief-BC/go-debrief/core" 32 "github.com/Debrief-BC/go-debrief/core/types" 33 "github.com/Debrief-BC/go-debrief/eth" 34 "github.com/Debrief-BC/go-debrief/les/flowcontrol" 35 "github.com/Debrief-BC/go-debrief/les/utils" 36 "github.com/Debrief-BC/go-debrief/light" 37 "github.com/Debrief-BC/go-debrief/p2p" 38 "github.com/Debrief-BC/go-debrief/p2p/enode" 39 "github.com/Debrief-BC/go-debrief/params" 40 "github.com/Debrief-BC/go-debrief/rlp" 41 ) 42 43 var ( 44 errClosed = errors.New("peer set is closed") 45 errAlreadyRegistered = errors.New("peer is already registered") 46 errNotRegistered = errors.New("peer is not registered") 47 ) 48 49 const ( 50 maxRequestErrors = 20 // number of invalid requests tolerated (makes the protocol less brittle but still avoids spam) 51 maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam) 52 53 allowedUpdateBytes = 100000 // initial/maximum allowed update size 54 allowedUpdateRate = time.Millisecond * 10 // time constant for recharging one byte of allowance 55 56 freezeTimeBase = time.Millisecond * 700 // fixed component of client freeze time 57 freezeTimeRandom = time.Millisecond * 600 // random component of client freeze time 58 freezeCheckPeriod = time.Millisecond * 100 // buffer value recheck period after initial freeze time has elapsed 59 60 // If the total encoded size of a sent transaction batch is over txSizeCostLimit 61 // per transaction then the request cost is calculated as proportional to the 62 // encoded size instead of the transaction count 63 txSizeCostLimit = 0x4000 64 65 // handshakeTimeout is the timeout LES handshake will be treated as failed. 66 handshakeTimeout = 5 * time.Second 67 68 // retrySendCachePeriod is the time interval a caching retry is performed. 69 retrySendCachePeriod = time.Millisecond * 100 70 ) 71 72 const ( 73 announceTypeNone = iota 74 announceTypeSimple 75 announceTypeSigned 76 ) 77 78 type keyValueEntry struct { 79 Key string 80 Value rlp.RawValue 81 } 82 83 type keyValueList []keyValueEntry 84 type keyValueMap map[string]rlp.RawValue 85 86 func (l keyValueList) add(key string, val interface{}) keyValueList { 87 var entry keyValueEntry 88 entry.Key = key 89 if val == nil { 90 val = uint64(0) 91 } 92 enc, err := rlp.EncodeToBytes(val) 93 if err == nil { 94 entry.Value = enc 95 } 96 return append(l, entry) 97 } 98 99 func (l keyValueList) decode() (keyValueMap, uint64) { 100 m := make(keyValueMap) 101 var size uint64 102 for _, entry := range l { 103 m[entry.Key] = entry.Value 104 size += uint64(len(entry.Key)) + uint64(len(entry.Value)) + 8 105 } 106 return m, size 107 } 108 109 func (m keyValueMap) get(key string, val interface{}) error { 110 enc, ok := m[key] 111 if !ok { 112 return errResp(ErrMissingKey, "%s", key) 113 } 114 if val == nil { 115 return nil 116 } 117 return rlp.DecodeBytes(enc, val) 118 } 119 120 // peerIdToString converts enode.ID to a string form 121 func peerIdToString(id enode.ID) string { 122 return fmt.Sprintf("%x", id.Bytes()) 123 } 124 125 // peerCommons contains fields needed by both server peer and client peer. 126 type peerCommons struct { 127 *p2p.Peer 128 rw p2p.MsgReadWriter 129 130 id string // Peer identity. 131 version int // Protocol version negotiated. 132 network uint64 // Network ID being on. 133 frozen uint32 // Flag whether the peer is frozen. 134 announceType uint64 // New block announcement type. 135 serving uint32 // The status indicates the peer is served. 136 headInfo blockInfo // Latest block information. 137 138 // Background task queue for caching peer tasks and executing in order. 139 sendQueue *utils.ExecQueue 140 141 // Flow control agreement. 142 fcParams flowcontrol.ServerParams // The config for token bucket. 143 fcCosts requestCostTable // The Maximum request cost table. 144 145 closeCh chan struct{} 146 lock sync.RWMutex // Lock used to protect all thread-sensitive fields. 147 } 148 149 // isFrozen returns true if the client is frozen or the server has put our 150 // client in frozen state 151 func (p *peerCommons) isFrozen() bool { 152 return atomic.LoadUint32(&p.frozen) != 0 153 } 154 155 // canQueue returns an indicator whether the peer can queue a operation. 156 func (p *peerCommons) canQueue() bool { 157 return p.sendQueue.CanQueue() && !p.isFrozen() 158 } 159 160 // queueSend caches a peer operation in the background task queue. 161 // Please ensure to check `canQueue` before call this function 162 func (p *peerCommons) queueSend(f func()) bool { 163 return p.sendQueue.Queue(f) 164 } 165 166 // mustQueueSend starts a for loop and retry the caching if failed. 167 // If the stopCh is closed, then it returns. 168 func (p *peerCommons) mustQueueSend(f func()) { 169 for { 170 // Check whether the stopCh is closed. 171 select { 172 case <-p.closeCh: 173 return 174 default: 175 } 176 // If the function is successfully cached, return. 177 if p.canQueue() && p.queueSend(f) { 178 return 179 } 180 time.Sleep(retrySendCachePeriod) 181 } 182 } 183 184 // String implements fmt.Stringer. 185 func (p *peerCommons) String() string { 186 return fmt.Sprintf("Peer %s [%s]", p.id, fmt.Sprintf("les/%d", p.version)) 187 } 188 189 // Info gathers and returns a collection of metadata known about a peer. 190 func (p *peerCommons) Info() *eth.PeerInfo { 191 return ð.PeerInfo{ 192 Version: p.version, 193 Difficulty: p.Td(), 194 Head: fmt.Sprintf("%x", p.Head()), 195 } 196 } 197 198 // Head retrieves a copy of the current head (most recent) hash of the peer. 199 func (p *peerCommons) Head() (hash common.Hash) { 200 p.lock.RLock() 201 defer p.lock.RUnlock() 202 203 return p.headInfo.Hash 204 } 205 206 // Td retrieves the current total difficulty of a peer. 207 func (p *peerCommons) Td() *big.Int { 208 p.lock.RLock() 209 defer p.lock.RUnlock() 210 211 return new(big.Int).Set(p.headInfo.Td) 212 } 213 214 // HeadAndTd retrieves the current head hash and total difficulty of a peer. 215 func (p *peerCommons) HeadAndTd() (hash common.Hash, td *big.Int) { 216 p.lock.RLock() 217 defer p.lock.RUnlock() 218 219 return p.headInfo.Hash, new(big.Int).Set(p.headInfo.Td) 220 } 221 222 // sendReceiveHandshake exchanges handshake packet with remote peer and returns any error 223 // if failed to send or receive packet. 224 func (p *peerCommons) sendReceiveHandshake(sendList keyValueList) (keyValueList, error) { 225 var ( 226 errc = make(chan error, 2) 227 recvList keyValueList 228 ) 229 // Send out own handshake in a new thread 230 go func() { 231 errc <- p2p.Send(p.rw, StatusMsg, sendList) 232 }() 233 go func() { 234 // In the mean time retrieve the remote status message 235 msg, err := p.rw.ReadMsg() 236 if err != nil { 237 errc <- err 238 return 239 } 240 if msg.Code != StatusMsg { 241 errc <- errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg) 242 return 243 } 244 if msg.Size > ProtocolMaxMsgSize { 245 errc <- errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize) 246 return 247 } 248 // Decode the handshake 249 if err := msg.Decode(&recvList); err != nil { 250 errc <- errResp(ErrDecode, "msg %v: %v", msg, err) 251 return 252 } 253 errc <- nil 254 }() 255 timeout := time.NewTimer(handshakeTimeout) 256 defer timeout.Stop() 257 for i := 0; i < 2; i++ { 258 select { 259 case err := <-errc: 260 if err != nil { 261 return nil, err 262 } 263 case <-timeout.C: 264 return nil, p2p.DiscReadTimeout 265 } 266 } 267 return recvList, nil 268 } 269 270 // handshake executes the les protocol handshake, negotiating version number, 271 // network IDs, difficulties, head and genesis blocks. Besides the basic handshake 272 // fields, server and client can exchange and resolve some specified fields through 273 // two callback functions. 274 func (p *peerCommons) handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, sendCallback func(*keyValueList), recvCallback func(keyValueMap) error) error { 275 p.lock.Lock() 276 defer p.lock.Unlock() 277 278 var send keyValueList 279 280 // Add some basic handshake fields 281 send = send.add("protocolVersion", uint64(p.version)) 282 send = send.add("networkId", p.network) 283 send = send.add("headTd", td) 284 send = send.add("headHash", head) 285 send = send.add("headNum", headNum) 286 send = send.add("genesisHash", genesis) 287 288 // Add client-specified or server-specified fields 289 if sendCallback != nil { 290 sendCallback(&send) 291 } 292 // Exchange the handshake packet and resolve the received one. 293 recvList, err := p.sendReceiveHandshake(send) 294 if err != nil { 295 return err 296 } 297 recv, size := recvList.decode() 298 if size > allowedUpdateBytes { 299 return errResp(ErrRequestRejected, "") 300 } 301 var rGenesis, rHash common.Hash 302 var rVersion, rNetwork, rNum uint64 303 var rTd *big.Int 304 if err := recv.get("protocolVersion", &rVersion); err != nil { 305 return err 306 } 307 if err := recv.get("networkId", &rNetwork); err != nil { 308 return err 309 } 310 if err := recv.get("headTd", &rTd); err != nil { 311 return err 312 } 313 if err := recv.get("headHash", &rHash); err != nil { 314 return err 315 } 316 if err := recv.get("headNum", &rNum); err != nil { 317 return err 318 } 319 if err := recv.get("genesisHash", &rGenesis); err != nil { 320 return err 321 } 322 if rGenesis != genesis { 323 return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", rGenesis[:8], genesis[:8]) 324 } 325 if rNetwork != p.network { 326 return errResp(ErrNetworkIdMismatch, "%d (!= %d)", rNetwork, p.network) 327 } 328 if int(rVersion) != p.version { 329 return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", rVersion, p.version) 330 } 331 p.headInfo = blockInfo{Hash: rHash, Number: rNum, Td: rTd} 332 if recvCallback != nil { 333 return recvCallback(recv) 334 } 335 return nil 336 } 337 338 // close closes the channel and notifies all background routines to exit. 339 func (p *peerCommons) close() { 340 close(p.closeCh) 341 p.sendQueue.Quit() 342 } 343 344 // serverPeer represents each node to which the client is connected. 345 // The node here refers to the les server. 346 type serverPeer struct { 347 peerCommons 348 349 // Status fields 350 trusted bool // The flag whether the server is selected as trusted server. 351 onlyAnnounce bool // The flag whether the server sends announcement only. 352 chainSince, chainRecent uint64 // The range of chain server peer can serve. 353 stateSince, stateRecent uint64 // The range of state server peer can serve. 354 355 // Advertised checkpoint fields 356 checkpointNumber uint64 // The block height which the checkpoint is registered. 357 checkpoint params.TrustedCheckpoint // The advertised checkpoint sent by server. 358 359 poolEntry *poolEntry // Statistic for server peer. 360 fcServer *flowcontrol.ServerNode // Client side mirror token bucket. 361 362 // Statistics 363 errCount int // Counter the invalid responses server has replied 364 updateCount uint64 365 updateTime mclock.AbsTime 366 367 // Callbacks 368 hasBlock func(common.Hash, uint64, bool) bool // Used to determine whether the server has the specified block. 369 } 370 371 func newServerPeer(version int, network uint64, trusted bool, p *p2p.Peer, rw p2p.MsgReadWriter) *serverPeer { 372 return &serverPeer{ 373 peerCommons: peerCommons{ 374 Peer: p, 375 rw: rw, 376 id: peerIdToString(p.ID()), 377 version: version, 378 network: network, 379 sendQueue: utils.NewExecQueue(100), 380 closeCh: make(chan struct{}), 381 }, 382 trusted: trusted, 383 } 384 } 385 386 // rejectUpdate returns true if a parameter update has to be rejected because 387 // the size and/or rate of updates exceed the capacity limitation 388 func (p *serverPeer) rejectUpdate(size uint64) bool { 389 now := mclock.Now() 390 if p.updateCount == 0 { 391 p.updateTime = now 392 } else { 393 dt := now - p.updateTime 394 p.updateTime = now 395 396 r := uint64(dt / mclock.AbsTime(allowedUpdateRate)) 397 if p.updateCount > r { 398 p.updateCount -= r 399 } else { 400 p.updateCount = 0 401 } 402 } 403 p.updateCount += size 404 return p.updateCount > allowedUpdateBytes 405 } 406 407 // freeze processes Stop messages from the given server and set the status as 408 // frozen. 409 func (p *serverPeer) freeze() { 410 if atomic.CompareAndSwapUint32(&p.frozen, 0, 1) { 411 p.sendQueue.Clear() 412 } 413 } 414 415 // unfreeze processes Resume messages from the given server and set the status 416 // as unfrozen. 417 func (p *serverPeer) unfreeze() { 418 atomic.StoreUint32(&p.frozen, 0) 419 } 420 421 // sendRequest send a request to the server based on the given message type 422 // and content. 423 func sendRequest(w p2p.MsgWriter, msgcode, reqID uint64, data interface{}) error { 424 type req struct { 425 ReqID uint64 426 Data interface{} 427 } 428 return p2p.Send(w, msgcode, req{reqID, data}) 429 } 430 431 // requestHeadersByHash fetches a batch of blocks' headers corresponding to the 432 // specified header query, based on the hash of an origin block. 433 func (p *serverPeer) requestHeadersByHash(reqID uint64, origin common.Hash, amount int, skip int, reverse bool) error { 434 p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse) 435 return sendRequest(p.rw, GetBlockHeadersMsg, reqID, &getBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}) 436 } 437 438 // requestHeadersByNumber fetches a batch of blocks' headers corresponding to the 439 // specified header query, based on the number of an origin block. 440 func (p *serverPeer) requestHeadersByNumber(reqID, origin uint64, amount int, skip int, reverse bool) error { 441 p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse) 442 return sendRequest(p.rw, GetBlockHeadersMsg, reqID, &getBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}) 443 } 444 445 // requestBodies fetches a batch of blocks' bodies corresponding to the hashes 446 // specified. 447 func (p *serverPeer) requestBodies(reqID uint64, hashes []common.Hash) error { 448 p.Log().Debug("Fetching batch of block bodies", "count", len(hashes)) 449 return sendRequest(p.rw, GetBlockBodiesMsg, reqID, hashes) 450 } 451 452 // requestCode fetches a batch of arbitrary data from a node's known state 453 // data, corresponding to the specified hashes. 454 func (p *serverPeer) requestCode(reqID uint64, reqs []CodeReq) error { 455 p.Log().Debug("Fetching batch of codes", "count", len(reqs)) 456 return sendRequest(p.rw, GetCodeMsg, reqID, reqs) 457 } 458 459 // requestReceipts fetches a batch of transaction receipts from a remote node. 460 func (p *serverPeer) requestReceipts(reqID uint64, hashes []common.Hash) error { 461 p.Log().Debug("Fetching batch of receipts", "count", len(hashes)) 462 return sendRequest(p.rw, GetReceiptsMsg, reqID, hashes) 463 } 464 465 // requestProofs fetches a batch of merkle proofs from a remote node. 466 func (p *serverPeer) requestProofs(reqID uint64, reqs []ProofReq) error { 467 p.Log().Debug("Fetching batch of proofs", "count", len(reqs)) 468 return sendRequest(p.rw, GetProofsV2Msg, reqID, reqs) 469 } 470 471 // requestHelperTrieProofs fetches a batch of HelperTrie merkle proofs from a remote node. 472 func (p *serverPeer) requestHelperTrieProofs(reqID uint64, reqs []HelperTrieReq) error { 473 p.Log().Debug("Fetching batch of HelperTrie proofs", "count", len(reqs)) 474 return sendRequest(p.rw, GetHelperTrieProofsMsg, reqID, reqs) 475 } 476 477 // requestTxStatus fetches a batch of transaction status records from a remote node. 478 func (p *serverPeer) requestTxStatus(reqID uint64, txHashes []common.Hash) error { 479 p.Log().Debug("Requesting transaction status", "count", len(txHashes)) 480 return sendRequest(p.rw, GetTxStatusMsg, reqID, txHashes) 481 } 482 483 // SendTxStatus creates a reply with a batch of transactions to be added to the remote transaction pool. 484 func (p *serverPeer) sendTxs(reqID uint64, txs rlp.RawValue) error { 485 p.Log().Debug("Sending batch of transactions", "size", len(txs)) 486 return sendRequest(p.rw, SendTxV2Msg, reqID, txs) 487 } 488 489 // waitBefore implements distPeer interface 490 func (p *serverPeer) waitBefore(maxCost uint64) (time.Duration, float64) { 491 return p.fcServer.CanSend(maxCost) 492 } 493 494 // getRequestCost returns an estimated request cost according to the flow control 495 // rules negotiated between the server and the client. 496 func (p *serverPeer) getRequestCost(msgcode uint64, amount int) uint64 { 497 p.lock.RLock() 498 defer p.lock.RUnlock() 499 500 costs := p.fcCosts[msgcode] 501 if costs == nil { 502 return 0 503 } 504 cost := costs.baseCost + costs.reqCost*uint64(amount) 505 if cost > p.fcParams.BufLimit { 506 cost = p.fcParams.BufLimit 507 } 508 return cost 509 } 510 511 // getTxRelayCost returns an estimated relay cost according to the flow control 512 // rules negotiated between the server and the client. 513 func (p *serverPeer) getTxRelayCost(amount, size int) uint64 { 514 p.lock.RLock() 515 defer p.lock.RUnlock() 516 517 costs := p.fcCosts[SendTxV2Msg] 518 if costs == nil { 519 return 0 520 } 521 cost := costs.baseCost + costs.reqCost*uint64(amount) 522 sizeCost := costs.baseCost + costs.reqCost*uint64(size)/txSizeCostLimit 523 if sizeCost > cost { 524 cost = sizeCost 525 } 526 if cost > p.fcParams.BufLimit { 527 cost = p.fcParams.BufLimit 528 } 529 return cost 530 } 531 532 // HasBlock checks if the peer has a given block 533 func (p *serverPeer) HasBlock(hash common.Hash, number uint64, hasState bool) bool { 534 p.lock.RLock() 535 head := p.headInfo.Number 536 var since, recent uint64 537 if hasState { 538 since = p.stateSince 539 recent = p.stateRecent 540 } else { 541 since = p.chainSince 542 recent = p.chainRecent 543 } 544 hasBlock := p.hasBlock 545 p.lock.RUnlock() 546 547 return head >= number && number >= since && (recent == 0 || number+recent+4 > head) && hasBlock != nil && hasBlock(hash, number, hasState) 548 } 549 550 // updateFlowControl updates the flow control parameters belonging to the server 551 // node if the announced key/value set contains relevant fields 552 func (p *serverPeer) updateFlowControl(update keyValueMap) { 553 p.lock.Lock() 554 defer p.lock.Unlock() 555 556 // If any of the flow control params is nil, refuse to update. 557 var params flowcontrol.ServerParams 558 if update.get("flowControl/BL", ¶ms.BufLimit) == nil && update.get("flowControl/MRR", ¶ms.MinRecharge) == nil { 559 // todo can light client set a minimal acceptable flow control params? 560 p.fcParams = params 561 p.fcServer.UpdateParams(params) 562 } 563 var MRC RequestCostList 564 if update.get("flowControl/MRC", &MRC) == nil { 565 costUpdate := MRC.decode(ProtocolLengths[uint(p.version)]) 566 for code, cost := range costUpdate { 567 p.fcCosts[code] = cost 568 } 569 } 570 } 571 572 // Handshake executes the les protocol handshake, negotiating version number, 573 // network IDs, difficulties, head and genesis blocks. 574 func (p *serverPeer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, server *LesServer) error { 575 return p.handshake(td, head, headNum, genesis, func(lists *keyValueList) { 576 // Add some client-specific handshake fields 577 // 578 // Enable signed announcement randomly even the server is not trusted. 579 p.announceType = announceTypeSimple 580 if p.trusted { 581 p.announceType = announceTypeSigned 582 } 583 *lists = (*lists).add("announceType", p.announceType) 584 }, func(recv keyValueMap) error { 585 if recv.get("serveChainSince", &p.chainSince) != nil { 586 p.onlyAnnounce = true 587 } 588 if recv.get("serveRecentChain", &p.chainRecent) != nil { 589 p.chainRecent = 0 590 } 591 if recv.get("serveStateSince", &p.stateSince) != nil { 592 p.onlyAnnounce = true 593 } 594 if recv.get("serveRecentState", &p.stateRecent) != nil { 595 p.stateRecent = 0 596 } 597 if recv.get("txRelay", nil) != nil { 598 p.onlyAnnounce = true 599 } 600 if p.onlyAnnounce && !p.trusted { 601 return errResp(ErrUselessPeer, "peer cannot serve requests") 602 } 603 // Parse flow control handshake packet. 604 var sParams flowcontrol.ServerParams 605 if err := recv.get("flowControl/BL", &sParams.BufLimit); err != nil { 606 return err 607 } 608 if err := recv.get("flowControl/MRR", &sParams.MinRecharge); err != nil { 609 return err 610 } 611 var MRC RequestCostList 612 if err := recv.get("flowControl/MRC", &MRC); err != nil { 613 return err 614 } 615 p.fcParams = sParams 616 p.fcServer = flowcontrol.NewServerNode(sParams, &mclock.System{}) 617 p.fcCosts = MRC.decode(ProtocolLengths[uint(p.version)]) 618 619 recv.get("checkpoint/value", &p.checkpoint) 620 recv.get("checkpoint/registerHeight", &p.checkpointNumber) 621 622 if !p.onlyAnnounce { 623 for msgCode := range reqAvgTimeCost { 624 if p.fcCosts[msgCode] == nil { 625 return errResp(ErrUselessPeer, "peer does not support message %d", msgCode) 626 } 627 } 628 } 629 return nil 630 }) 631 } 632 633 // clientPeer represents each node to which the les server is connected. 634 // The node here refers to the light client. 635 type clientPeer struct { 636 peerCommons 637 638 // responseLock ensures that responses are queued in the same order as 639 // RequestProcessed is called 640 responseLock sync.Mutex 641 server bool 642 invalidCount uint32 // Counter the invalid request the client peer has made. 643 responseCount uint64 // Counter to generate an unique id for request processing. 644 errCh chan error 645 fcClient *flowcontrol.ClientNode // Server side mirror token bucket. 646 } 647 648 func newClientPeer(version int, network uint64, p *p2p.Peer, rw p2p.MsgReadWriter) *clientPeer { 649 return &clientPeer{ 650 peerCommons: peerCommons{ 651 Peer: p, 652 rw: rw, 653 id: peerIdToString(p.ID()), 654 version: version, 655 network: network, 656 sendQueue: utils.NewExecQueue(100), 657 closeCh: make(chan struct{}), 658 }, 659 errCh: make(chan error, 1), 660 } 661 } 662 663 // freeClientId returns a string identifier for the peer. Multiple peers with 664 // the same identifier can not be connected in free mode simultaneously. 665 func (p *clientPeer) freeClientId() string { 666 if addr, ok := p.RemoteAddr().(*net.TCPAddr); ok { 667 if addr.IP.IsLoopback() { 668 // using peer id instead of loopback ip address allows multiple free 669 // connections from local machine to own server 670 return p.id 671 } else { 672 return addr.IP.String() 673 } 674 } 675 return p.id 676 } 677 678 // sendStop notifies the client about being in frozen state 679 func (p *clientPeer) sendStop() error { 680 return p2p.Send(p.rw, StopMsg, struct{}{}) 681 } 682 683 // sendResume notifies the client about getting out of frozen state 684 func (p *clientPeer) sendResume(bv uint64) error { 685 return p2p.Send(p.rw, ResumeMsg, bv) 686 } 687 688 // freeze temporarily puts the client in a frozen state which means all unprocessed 689 // and subsequent requests are dropped. Unfreezing happens automatically after a short 690 // time if the client's buffer value is at least in the slightly positive region. 691 // The client is also notified about being frozen/unfrozen with a Stop/Resume message. 692 func (p *clientPeer) freeze() { 693 if p.version < lpv3 { 694 // if Stop/Resume is not supported then just drop the peer after setting 695 // its frozen status permanently 696 atomic.StoreUint32(&p.frozen, 1) 697 p.Peer.Disconnect(p2p.DiscUselessPeer) 698 return 699 } 700 if atomic.SwapUint32(&p.frozen, 1) == 0 { 701 go func() { 702 p.sendStop() 703 time.Sleep(freezeTimeBase + time.Duration(rand.Int63n(int64(freezeTimeRandom)))) 704 for { 705 bufValue, bufLimit := p.fcClient.BufferStatus() 706 if bufLimit == 0 { 707 return 708 } 709 if bufValue <= bufLimit/8 { 710 time.Sleep(freezeCheckPeriod) 711 continue 712 } 713 atomic.StoreUint32(&p.frozen, 0) 714 p.sendResume(bufValue) 715 return 716 } 717 }() 718 } 719 } 720 721 // reply struct represents a reply with the actual data already RLP encoded and 722 // only the bv (buffer value) missing. This allows the serving mechanism to 723 // calculate the bv value which depends on the data size before sending the reply. 724 type reply struct { 725 w p2p.MsgWriter 726 msgcode, reqID uint64 727 data rlp.RawValue 728 } 729 730 // send sends the reply with the calculated buffer value 731 func (r *reply) send(bv uint64) error { 732 type resp struct { 733 ReqID, BV uint64 734 Data rlp.RawValue 735 } 736 return p2p.Send(r.w, r.msgcode, resp{r.reqID, bv, r.data}) 737 } 738 739 // size returns the RLP encoded size of the message data 740 func (r *reply) size() uint32 { 741 return uint32(len(r.data)) 742 } 743 744 // replyBlockHeaders creates a reply with a batch of block headers 745 func (p *clientPeer) replyBlockHeaders(reqID uint64, headers []*types.Header) *reply { 746 data, _ := rlp.EncodeToBytes(headers) 747 return &reply{p.rw, BlockHeadersMsg, reqID, data} 748 } 749 750 // replyBlockBodiesRLP creates a reply with a batch of block contents from 751 // an already RLP encoded format. 752 func (p *clientPeer) replyBlockBodiesRLP(reqID uint64, bodies []rlp.RawValue) *reply { 753 data, _ := rlp.EncodeToBytes(bodies) 754 return &reply{p.rw, BlockBodiesMsg, reqID, data} 755 } 756 757 // replyCode creates a reply with a batch of arbitrary internal data, corresponding to the 758 // hashes requested. 759 func (p *clientPeer) replyCode(reqID uint64, codes [][]byte) *reply { 760 data, _ := rlp.EncodeToBytes(codes) 761 return &reply{p.rw, CodeMsg, reqID, data} 762 } 763 764 // replyReceiptsRLP creates a reply with a batch of transaction receipts, corresponding to the 765 // ones requested from an already RLP encoded format. 766 func (p *clientPeer) replyReceiptsRLP(reqID uint64, receipts []rlp.RawValue) *reply { 767 data, _ := rlp.EncodeToBytes(receipts) 768 return &reply{p.rw, ReceiptsMsg, reqID, data} 769 } 770 771 // replyProofsV2 creates a reply with a batch of merkle proofs, corresponding to the ones requested. 772 func (p *clientPeer) replyProofsV2(reqID uint64, proofs light.NodeList) *reply { 773 data, _ := rlp.EncodeToBytes(proofs) 774 return &reply{p.rw, ProofsV2Msg, reqID, data} 775 } 776 777 // replyHelperTrieProofs creates a reply with a batch of HelperTrie proofs, corresponding to the ones requested. 778 func (p *clientPeer) replyHelperTrieProofs(reqID uint64, resp HelperTrieResps) *reply { 779 data, _ := rlp.EncodeToBytes(resp) 780 return &reply{p.rw, HelperTrieProofsMsg, reqID, data} 781 } 782 783 // replyTxStatus creates a reply with a batch of transaction status records, corresponding to the ones requested. 784 func (p *clientPeer) replyTxStatus(reqID uint64, stats []light.TxStatus) *reply { 785 data, _ := rlp.EncodeToBytes(stats) 786 return &reply{p.rw, TxStatusMsg, reqID, data} 787 } 788 789 // sendAnnounce announces the availability of a number of blocks through 790 // a hash notification. 791 func (p *clientPeer) sendAnnounce(request announceData) error { 792 return p2p.Send(p.rw, AnnounceMsg, request) 793 } 794 795 // updateCapacity updates the request serving capacity assigned to a given client 796 // and also sends an announcement about the updated flow control parameters 797 func (p *clientPeer) updateCapacity(cap uint64) { 798 p.lock.Lock() 799 defer p.lock.Unlock() 800 801 p.fcParams = flowcontrol.ServerParams{MinRecharge: cap, BufLimit: cap * bufLimitRatio} 802 p.fcClient.UpdateParams(p.fcParams) 803 var kvList keyValueList 804 kvList = kvList.add("flowControl/MRR", cap) 805 kvList = kvList.add("flowControl/BL", cap*bufLimitRatio) 806 p.mustQueueSend(func() { p.sendAnnounce(announceData{Update: kvList}) }) 807 } 808 809 // freezeClient temporarily puts the client in a frozen state which means all 810 // unprocessed and subsequent requests are dropped. Unfreezing happens automatically 811 // after a short time if the client's buffer value is at least in the slightly positive 812 // region. The client is also notified about being frozen/unfrozen with a Stop/Resume 813 // message. 814 func (p *clientPeer) freezeClient() { 815 if p.version < lpv3 { 816 // if Stop/Resume is not supported then just drop the peer after setting 817 // its frozen status permanently 818 atomic.StoreUint32(&p.frozen, 1) 819 p.Peer.Disconnect(p2p.DiscUselessPeer) 820 return 821 } 822 if atomic.SwapUint32(&p.frozen, 1) == 0 { 823 go func() { 824 p.sendStop() 825 time.Sleep(freezeTimeBase + time.Duration(rand.Int63n(int64(freezeTimeRandom)))) 826 for { 827 bufValue, bufLimit := p.fcClient.BufferStatus() 828 if bufLimit == 0 { 829 return 830 } 831 if bufValue <= bufLimit/8 { 832 time.Sleep(freezeCheckPeriod) 833 } else { 834 atomic.StoreUint32(&p.frozen, 0) 835 p.sendResume(bufValue) 836 break 837 } 838 } 839 }() 840 } 841 } 842 843 // Handshake executes the les protocol handshake, negotiating version number, 844 // network IDs, difficulties, head and genesis blocks. 845 func (p *clientPeer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, server *LesServer) error { 846 return p.handshake(td, head, headNum, genesis, func(lists *keyValueList) { 847 // Add some information which services server can offer. 848 if !server.config.UltraLightOnlyAnnounce { 849 *lists = (*lists).add("serveHeaders", nil) 850 *lists = (*lists).add("serveChainSince", uint64(0)) 851 *lists = (*lists).add("serveStateSince", uint64(0)) 852 853 // If local ethereum node is running in archive mode, advertise ourselves we have 854 // all version state data. Otherwise only recent state is available. 855 stateRecent := uint64(core.TriesInMemory - 4) 856 if server.archiveMode { 857 stateRecent = 0 858 } 859 *lists = (*lists).add("serveRecentState", stateRecent) 860 *lists = (*lists).add("txRelay", nil) 861 } 862 *lists = (*lists).add("flowControl/BL", server.defParams.BufLimit) 863 *lists = (*lists).add("flowControl/MRR", server.defParams.MinRecharge) 864 865 var costList RequestCostList 866 if server.costTracker.testCostList != nil { 867 costList = server.costTracker.testCostList 868 } else { 869 costList = server.costTracker.makeCostList(server.costTracker.globalFactor()) 870 } 871 *lists = (*lists).add("flowControl/MRC", costList) 872 p.fcCosts = costList.decode(ProtocolLengths[uint(p.version)]) 873 p.fcParams = server.defParams 874 875 // Add advertised checkpoint and register block height which 876 // client can verify the checkpoint validity. 877 if server.oracle != nil && server.oracle.IsRunning() { 878 cp, height := server.oracle.StableCheckpoint() 879 if cp != nil { 880 *lists = (*lists).add("checkpoint/value", cp) 881 *lists = (*lists).add("checkpoint/registerHeight", height) 882 } 883 } 884 }, func(recv keyValueMap) error { 885 p.server = recv.get("flowControl/MRR", nil) == nil 886 if p.server { 887 p.announceType = announceTypeNone // connected to another server, send no messages 888 } else { 889 if recv.get("announceType", &p.announceType) != nil { 890 // set default announceType on server side 891 p.announceType = announceTypeSimple 892 } 893 p.fcClient = flowcontrol.NewClientNode(server.fcManager, server.defParams) 894 } 895 return nil 896 }) 897 } 898 899 // serverPeerSubscriber is an interface to notify services about added or 900 // removed server peers 901 type serverPeerSubscriber interface { 902 registerPeer(*serverPeer) 903 unregisterPeer(*serverPeer) 904 } 905 906 // clientPeerSubscriber is an interface to notify services about added or 907 // removed client peers 908 type clientPeerSubscriber interface { 909 registerPeer(*clientPeer) 910 unregisterPeer(*clientPeer) 911 } 912 913 // clientPeerSet represents the set of active client peers currently 914 // participating in the Light Ethereum sub-protocol. 915 type clientPeerSet struct { 916 peers map[string]*clientPeer 917 // subscribers is a batch of subscribers and peerset will notify 918 // these subscribers when the peerset changes(new client peer is 919 // added or removed) 920 subscribers []clientPeerSubscriber 921 closed bool 922 lock sync.RWMutex 923 } 924 925 // newClientPeerSet creates a new peer set to track the client peers. 926 func newClientPeerSet() *clientPeerSet { 927 return &clientPeerSet{peers: make(map[string]*clientPeer)} 928 } 929 930 // subscribe adds a service to be notified about added or removed 931 // peers and also register all active peers into the given service. 932 func (ps *clientPeerSet) subscribe(sub clientPeerSubscriber) { 933 ps.lock.Lock() 934 defer ps.lock.Unlock() 935 936 ps.subscribers = append(ps.subscribers, sub) 937 for _, p := range ps.peers { 938 sub.registerPeer(p) 939 } 940 } 941 942 // unSubscribe removes the specified service from the subscriber pool. 943 func (ps *clientPeerSet) unSubscribe(sub clientPeerSubscriber) { 944 ps.lock.Lock() 945 defer ps.lock.Unlock() 946 947 for i, s := range ps.subscribers { 948 if s == sub { 949 ps.subscribers = append(ps.subscribers[:i], ps.subscribers[i+1:]...) 950 return 951 } 952 } 953 } 954 955 // register adds a new peer into the peer set, or returns an error if the 956 // peer is already known. 957 func (ps *clientPeerSet) register(peer *clientPeer) error { 958 ps.lock.Lock() 959 defer ps.lock.Unlock() 960 961 if ps.closed { 962 return errClosed 963 } 964 if _, exist := ps.peers[peer.id]; exist { 965 return errAlreadyRegistered 966 } 967 ps.peers[peer.id] = peer 968 for _, sub := range ps.subscribers { 969 sub.registerPeer(peer) 970 } 971 return nil 972 } 973 974 // unregister removes a remote peer from the peer set, disabling any further 975 // actions to/from that particular entity. It also initiates disconnection 976 // at the networking layer. 977 func (ps *clientPeerSet) unregister(id string) error { 978 ps.lock.Lock() 979 defer ps.lock.Unlock() 980 981 p, ok := ps.peers[id] 982 if !ok { 983 return errNotRegistered 984 } 985 delete(ps.peers, id) 986 for _, sub := range ps.subscribers { 987 sub.unregisterPeer(p) 988 } 989 p.Peer.Disconnect(p2p.DiscRequested) 990 return nil 991 } 992 993 // ids returns a list of all registered peer IDs 994 func (ps *clientPeerSet) ids() []string { 995 ps.lock.RLock() 996 defer ps.lock.RUnlock() 997 998 var ids []string 999 for id := range ps.peers { 1000 ids = append(ids, id) 1001 } 1002 return ids 1003 } 1004 1005 // peer retrieves the registered peer with the given id. 1006 func (ps *clientPeerSet) peer(id string) *clientPeer { 1007 ps.lock.RLock() 1008 defer ps.lock.RUnlock() 1009 1010 return ps.peers[id] 1011 } 1012 1013 // len returns if the current number of peers in the set. 1014 func (ps *clientPeerSet) len() int { 1015 ps.lock.RLock() 1016 defer ps.lock.RUnlock() 1017 1018 return len(ps.peers) 1019 } 1020 1021 // allClientPeers returns all client peers in a list. 1022 func (ps *clientPeerSet) allPeers() []*clientPeer { 1023 ps.lock.RLock() 1024 defer ps.lock.RUnlock() 1025 1026 list := make([]*clientPeer, 0, len(ps.peers)) 1027 for _, p := range ps.peers { 1028 list = append(list, p) 1029 } 1030 return list 1031 } 1032 1033 // close disconnects all peers. No new peers can be registered 1034 // after close has returned. 1035 func (ps *clientPeerSet) close() { 1036 ps.lock.Lock() 1037 defer ps.lock.Unlock() 1038 1039 for _, p := range ps.peers { 1040 p.Disconnect(p2p.DiscQuitting) 1041 } 1042 ps.closed = true 1043 } 1044 1045 // serverPeerSet represents the set of active server peers currently 1046 // participating in the Light Ethereum sub-protocol. 1047 type serverPeerSet struct { 1048 peers map[string]*serverPeer 1049 // subscribers is a batch of subscribers and peerset will notify 1050 // these subscribers when the peerset changes(new server peer is 1051 // added or removed) 1052 subscribers []serverPeerSubscriber 1053 closed bool 1054 lock sync.RWMutex 1055 } 1056 1057 // newServerPeerSet creates a new peer set to track the active server peers. 1058 func newServerPeerSet() *serverPeerSet { 1059 return &serverPeerSet{peers: make(map[string]*serverPeer)} 1060 } 1061 1062 // subscribe adds a service to be notified about added or removed 1063 // peers and also register all active peers into the given service. 1064 func (ps *serverPeerSet) subscribe(sub serverPeerSubscriber) { 1065 ps.lock.Lock() 1066 defer ps.lock.Unlock() 1067 1068 ps.subscribers = append(ps.subscribers, sub) 1069 for _, p := range ps.peers { 1070 sub.registerPeer(p) 1071 } 1072 } 1073 1074 // unSubscribe removes the specified service from the subscriber pool. 1075 func (ps *serverPeerSet) unSubscribe(sub serverPeerSubscriber) { 1076 ps.lock.Lock() 1077 defer ps.lock.Unlock() 1078 1079 for i, s := range ps.subscribers { 1080 if s == sub { 1081 ps.subscribers = append(ps.subscribers[:i], ps.subscribers[i+1:]...) 1082 return 1083 } 1084 } 1085 } 1086 1087 // register adds a new server peer into the set, or returns an error if the 1088 // peer is already known. 1089 func (ps *serverPeerSet) register(peer *serverPeer) error { 1090 ps.lock.Lock() 1091 defer ps.lock.Unlock() 1092 1093 if ps.closed { 1094 return errClosed 1095 } 1096 if _, exist := ps.peers[peer.id]; exist { 1097 return errAlreadyRegistered 1098 } 1099 ps.peers[peer.id] = peer 1100 for _, sub := range ps.subscribers { 1101 sub.registerPeer(peer) 1102 } 1103 return nil 1104 } 1105 1106 // unregister removes a remote peer from the active set, disabling any further 1107 // actions to/from that particular entity. It also initiates disconnection at 1108 // the networking layer. 1109 func (ps *serverPeerSet) unregister(id string) error { 1110 ps.lock.Lock() 1111 defer ps.lock.Unlock() 1112 1113 p, ok := ps.peers[id] 1114 if !ok { 1115 return errNotRegistered 1116 } 1117 delete(ps.peers, id) 1118 for _, sub := range ps.subscribers { 1119 sub.unregisterPeer(p) 1120 } 1121 p.Peer.Disconnect(p2p.DiscRequested) 1122 return nil 1123 } 1124 1125 // ids returns a list of all registered peer IDs 1126 func (ps *serverPeerSet) ids() []string { 1127 ps.lock.RLock() 1128 defer ps.lock.RUnlock() 1129 1130 var ids []string 1131 for id := range ps.peers { 1132 ids = append(ids, id) 1133 } 1134 return ids 1135 } 1136 1137 // peer retrieves the registered peer with the given id. 1138 func (ps *serverPeerSet) peer(id string) *serverPeer { 1139 ps.lock.RLock() 1140 defer ps.lock.RUnlock() 1141 1142 return ps.peers[id] 1143 } 1144 1145 // len returns if the current number of peers in the set. 1146 func (ps *serverPeerSet) len() int { 1147 ps.lock.RLock() 1148 defer ps.lock.RUnlock() 1149 1150 return len(ps.peers) 1151 } 1152 1153 // bestPeer retrieves the known peer with the currently highest total difficulty. 1154 // If the peerset is "client peer set", then nothing meaningful will return. The 1155 // reason is client peer never send back their latest status to server. 1156 func (ps *serverPeerSet) bestPeer() *serverPeer { 1157 ps.lock.RLock() 1158 defer ps.lock.RUnlock() 1159 1160 var ( 1161 bestPeer *serverPeer 1162 bestTd *big.Int 1163 ) 1164 for _, p := range ps.peers { 1165 if td := p.Td(); bestTd == nil || td.Cmp(bestTd) > 0 { 1166 bestPeer, bestTd = p, td 1167 } 1168 } 1169 return bestPeer 1170 } 1171 1172 // allServerPeers returns all server peers in a list. 1173 func (ps *serverPeerSet) allPeers() []*serverPeer { 1174 ps.lock.RLock() 1175 defer ps.lock.RUnlock() 1176 1177 list := make([]*serverPeer, 0, len(ps.peers)) 1178 for _, p := range ps.peers { 1179 list = append(list, p) 1180 } 1181 return list 1182 } 1183 1184 // close disconnects all peers. No new peers can be registered 1185 // after close has returned. 1186 func (ps *serverPeerSet) close() { 1187 ps.lock.Lock() 1188 defer ps.lock.Unlock() 1189 1190 for _, p := range ps.peers { 1191 p.Disconnect(p2p.DiscQuitting) 1192 } 1193 ps.closed = true 1194 }