github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/les/peer.go (about) 1 // Copyright 2016 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package les implements the Light Ethereum Subprotocol. 18 package les 19 20 import ( 21 "crypto/ecdsa" 22 "encoding/binary" 23 "errors" 24 "fmt" 25 "math/big" 26 "sync" 27 "time" 28 29 "github.com/SmartMeshFoundation/Spectrum/common" 30 "github.com/SmartMeshFoundation/Spectrum/core/types" 31 "github.com/SmartMeshFoundation/Spectrum/eth" 32 "github.com/SmartMeshFoundation/Spectrum/les/flowcontrol" 33 "github.com/SmartMeshFoundation/Spectrum/light" 34 "github.com/SmartMeshFoundation/Spectrum/p2p" 35 "github.com/SmartMeshFoundation/Spectrum/rlp" 36 ) 37 38 var ( 39 errClosed = errors.New("peer set is closed") 40 errAlreadyRegistered = errors.New("peer is already registered") 41 errNotRegistered = errors.New("peer is not registered") 42 ) 43 44 const maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam) 45 46 const ( 47 announceTypeNone = iota 48 announceTypeSimple 49 announceTypeSigned 50 ) 51 52 type peer struct { 53 *p2p.Peer 54 pubKey *ecdsa.PublicKey 55 56 rw p2p.MsgReadWriter 57 58 version int // Protocol version negotiated 59 network uint64 // Network ID being on 60 61 announceType, requestAnnounceType uint64 62 63 id string 64 65 headInfo *announceData 66 lock sync.RWMutex 67 68 announceChn chan announceData 69 sendQueue *execQueue 70 71 poolEntry *poolEntry 72 hasBlock func(common.Hash, uint64) bool 73 responseErrors int 74 75 fcClient *flowcontrol.ClientNode // nil if the peer is server only 76 fcServer *flowcontrol.ServerNode // nil if the peer is client only 77 fcServerParams *flowcontrol.ServerParams 78 fcCosts requestCostTable 79 } 80 81 func newPeer(version int, network uint64, p *p2p.Peer, rw p2p.MsgReadWriter) *peer { 82 id := p.ID() 83 pubKey, _ := id.Pubkey() 84 85 return &peer{ 86 Peer: p, 87 pubKey: pubKey, 88 rw: rw, 89 version: version, 90 network: network, 91 id: fmt.Sprintf("%x", id[:8]), 92 announceChn: make(chan announceData, 20), 93 } 94 } 95 96 func (p *peer) canQueue() bool { 97 return p.sendQueue.canQueue() 98 } 99 100 func (p *peer) queueSend(f func()) { 101 p.sendQueue.queue(f) 102 } 103 104 // Info gathers and returns a collection of metadata known about a peer. 105 func (p *peer) Info() *eth.PeerInfo { 106 return ð.PeerInfo{ 107 Version: p.version, 108 Difficulty: p.Td(), 109 Head: fmt.Sprintf("%x", p.Head()), 110 } 111 } 112 113 // Head retrieves a copy of the current head (most recent) hash of the peer. 114 func (p *peer) Head() (hash common.Hash) { 115 p.lock.RLock() 116 defer p.lock.RUnlock() 117 118 copy(hash[:], p.headInfo.Hash[:]) 119 return hash 120 } 121 122 func (p *peer) HeadAndTd() (hash common.Hash, td *big.Int) { 123 p.lock.RLock() 124 defer p.lock.RUnlock() 125 126 copy(hash[:], p.headInfo.Hash[:]) 127 return hash, p.headInfo.Td 128 } 129 130 func (p *peer) headBlockInfo() blockInfo { 131 p.lock.RLock() 132 defer p.lock.RUnlock() 133 134 return blockInfo{Hash: p.headInfo.Hash, Number: p.headInfo.Number, Td: p.headInfo.Td} 135 } 136 137 // Td retrieves the current total difficulty of a peer. 138 func (p *peer) Td() *big.Int { 139 p.lock.RLock() 140 defer p.lock.RUnlock() 141 142 return new(big.Int).Set(p.headInfo.Td) 143 } 144 145 // waitBefore implements distPeer interface 146 func (p *peer) waitBefore(maxCost uint64) (time.Duration, float64) { 147 return p.fcServer.CanSend(maxCost) 148 } 149 150 func sendRequest(w p2p.MsgWriter, msgcode, reqID, cost uint64, data interface{}) error { 151 type req struct { 152 ReqID uint64 153 Data interface{} 154 } 155 return p2p.Send(w, msgcode, req{reqID, data}) 156 } 157 158 func sendResponse(w p2p.MsgWriter, msgcode, reqID, bv uint64, data interface{}) error { 159 type resp struct { 160 ReqID, BV uint64 161 Data interface{} 162 } 163 return p2p.Send(w, msgcode, resp{reqID, bv, data}) 164 } 165 166 func (p *peer) GetRequestCost(msgcode uint64, amount int) uint64 { 167 p.lock.RLock() 168 defer p.lock.RUnlock() 169 170 cost := p.fcCosts[msgcode].baseCost + p.fcCosts[msgcode].reqCost*uint64(amount) 171 if cost > p.fcServerParams.BufLimit { 172 cost = p.fcServerParams.BufLimit 173 } 174 return cost 175 } 176 177 // HasBlock checks if the peer has a given block 178 func (p *peer) HasBlock(hash common.Hash, number uint64) bool { 179 p.lock.RLock() 180 hasBlock := p.hasBlock 181 p.lock.RUnlock() 182 return hasBlock != nil && hasBlock(hash, number) 183 } 184 185 // SendAnnounce announces the availability of a number of blocks through 186 // a hash notification. 187 func (p *peer) SendAnnounce(request announceData) error { 188 return p2p.Send(p.rw, AnnounceMsg, request) 189 } 190 191 // SendBlockHeaders sends a batch of block headers to the remote peer. 192 func (p *peer) SendBlockHeaders(reqID, bv uint64, headers []*types.Header) error { 193 return sendResponse(p.rw, BlockHeadersMsg, reqID, bv, headers) 194 } 195 196 // SendBlockBodiesRLP sends a batch of block contents to the remote peer from 197 // an already RLP encoded format. 198 func (p *peer) SendBlockBodiesRLP(reqID, bv uint64, bodies []rlp.RawValue) error { 199 return sendResponse(p.rw, BlockBodiesMsg, reqID, bv, bodies) 200 } 201 202 // SendCodeRLP sends a batch of arbitrary internal data, corresponding to the 203 // hashes requested. 204 func (p *peer) SendCode(reqID, bv uint64, data [][]byte) error { 205 return sendResponse(p.rw, CodeMsg, reqID, bv, data) 206 } 207 208 // SendReceiptsRLP sends a batch of transaction receipts, corresponding to the 209 // ones requested from an already RLP encoded format. 210 func (p *peer) SendReceiptsRLP(reqID, bv uint64, receipts []rlp.RawValue) error { 211 return sendResponse(p.rw, ReceiptsMsg, reqID, bv, receipts) 212 } 213 214 // SendProofs sends a batch of legacy LES/1 merkle proofs, corresponding to the ones requested. 215 func (p *peer) SendProofs(reqID, bv uint64, proofs proofsData) error { 216 return sendResponse(p.rw, ProofsV1Msg, reqID, bv, proofs) 217 } 218 219 // SendProofsV2 sends a batch of merkle proofs, corresponding to the ones requested. 220 func (p *peer) SendProofsV2(reqID, bv uint64, proofs light.NodeList) error { 221 return sendResponse(p.rw, ProofsV2Msg, reqID, bv, proofs) 222 } 223 224 // SendHeaderProofs sends a batch of legacy LES/1 header proofs, corresponding to the ones requested. 225 func (p *peer) SendHeaderProofs(reqID, bv uint64, proofs []ChtResp) error { 226 return sendResponse(p.rw, HeaderProofsMsg, reqID, bv, proofs) 227 } 228 229 // SendHelperTrieProofs sends a batch of HelperTrie proofs, corresponding to the ones requested. 230 func (p *peer) SendHelperTrieProofs(reqID, bv uint64, resp HelperTrieResps) error { 231 return sendResponse(p.rw, HelperTrieProofsMsg, reqID, bv, resp) 232 } 233 234 // SendTxStatus sends a batch of transaction status records, corresponding to the ones requested. 235 func (p *peer) SendTxStatus(reqID, bv uint64, stats []txStatus) error { 236 return sendResponse(p.rw, TxStatusMsg, reqID, bv, stats) 237 } 238 239 // RequestHeadersByHash fetches a batch of blocks' headers corresponding to the 240 // specified header query, based on the hash of an origin block. 241 func (p *peer) RequestHeadersByHash(reqID, cost uint64, origin common.Hash, amount int, skip int, reverse bool) error { 242 p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse) 243 return sendRequest(p.rw, GetBlockHeadersMsg, reqID, cost, &getBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}) 244 } 245 246 // RequestHeadersByNumber fetches a batch of blocks' headers corresponding to the 247 // specified header query, based on the number of an origin block. 248 func (p *peer) RequestHeadersByNumber(reqID, cost, origin uint64, amount int, skip int, reverse bool) error { 249 p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse) 250 return sendRequest(p.rw, GetBlockHeadersMsg, reqID, cost, &getBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}) 251 } 252 253 // RequestBodies fetches a batch of blocks' bodies corresponding to the hashes 254 // specified. 255 func (p *peer) RequestBodies(reqID, cost uint64, hashes []common.Hash) error { 256 p.Log().Debug("Fetching batch of block bodies", "count", len(hashes)) 257 return sendRequest(p.rw, GetBlockBodiesMsg, reqID, cost, hashes) 258 } 259 260 // RequestCode fetches a batch of arbitrary data from a node's known state 261 // data, corresponding to the specified hashes. 262 func (p *peer) RequestCode(reqID, cost uint64, reqs []CodeReq) error { 263 p.Log().Debug("Fetching batch of codes", "count", len(reqs)) 264 return sendRequest(p.rw, GetCodeMsg, reqID, cost, reqs) 265 } 266 267 // RequestReceipts fetches a batch of transaction receipts from a remote node. 268 func (p *peer) RequestReceipts(reqID, cost uint64, hashes []common.Hash) error { 269 p.Log().Debug("Fetching batch of receipts", "count", len(hashes)) 270 return sendRequest(p.rw, GetReceiptsMsg, reqID, cost, hashes) 271 } 272 273 // RequestProofs fetches a batch of merkle proofs from a remote node. 274 func (p *peer) RequestProofs(reqID, cost uint64, reqs []ProofReq) error { 275 p.Log().Debug("Fetching batch of proofs", "count", len(reqs)) 276 switch p.version { 277 case lpv1: 278 return sendRequest(p.rw, GetProofsV1Msg, reqID, cost, reqs) 279 case lpv2: 280 return sendRequest(p.rw, GetProofsV2Msg, reqID, cost, reqs) 281 default: 282 panic(nil) 283 } 284 285 } 286 287 // RequestHelperTrieProofs fetches a batch of HelperTrie merkle proofs from a remote node. 288 func (p *peer) RequestHelperTrieProofs(reqID, cost uint64, reqs []HelperTrieReq) error { 289 p.Log().Debug("Fetching batch of HelperTrie proofs", "count", len(reqs)) 290 switch p.version { 291 case lpv1: 292 reqsV1 := make([]ChtReq, len(reqs)) 293 for i, req := range reqs { 294 if req.HelperTrieType != htCanonical || req.AuxReq != auxHeader || len(req.Key) != 8 { 295 return fmt.Errorf("Request invalid in LES/1 mode") 296 } 297 blockNum := binary.BigEndian.Uint64(req.Key) 298 // convert HelperTrie request to old CHT request 299 reqsV1[i] = ChtReq{ChtNum: (req.TrieIdx+1)*(light.ChtFrequency/light.ChtV1Frequency) - 1, BlockNum: blockNum, FromLevel: req.FromLevel} 300 } 301 return sendRequest(p.rw, GetHeaderProofsMsg, reqID, cost, reqsV1) 302 case lpv2: 303 return sendRequest(p.rw, GetHelperTrieProofsMsg, reqID, cost, reqs) 304 default: 305 panic(nil) 306 } 307 } 308 309 // RequestTxStatus fetches a batch of transaction status records from a remote node. 310 func (p *peer) RequestTxStatus(reqID, cost uint64, txHashes []common.Hash) error { 311 p.Log().Debug("Requesting transaction status", "count", len(txHashes)) 312 return sendRequest(p.rw, GetTxStatusMsg, reqID, cost, txHashes) 313 } 314 315 // SendTxStatus sends a batch of transactions to be added to the remote transaction pool. 316 func (p *peer) SendTxs(reqID, cost uint64, txs types.Transactions) error { 317 p.Log().Debug("Fetching batch of transactions", "count", len(txs)) 318 switch p.version { 319 case lpv1: 320 return p2p.Send(p.rw, SendTxMsg, txs) // old message format does not include reqID 321 case lpv2: 322 return sendRequest(p.rw, SendTxV2Msg, reqID, cost, txs) 323 default: 324 panic(nil) 325 } 326 } 327 328 type keyValueEntry struct { 329 Key string 330 Value rlp.RawValue 331 } 332 type keyValueList []keyValueEntry 333 type keyValueMap map[string]rlp.RawValue 334 335 func (l keyValueList) add(key string, val interface{}) keyValueList { 336 var entry keyValueEntry 337 entry.Key = key 338 if val == nil { 339 val = uint64(0) 340 } 341 enc, err := rlp.EncodeToBytes(val) 342 if err == nil { 343 entry.Value = enc 344 } 345 return append(l, entry) 346 } 347 348 func (l keyValueList) decode() keyValueMap { 349 m := make(keyValueMap) 350 for _, entry := range l { 351 m[entry.Key] = entry.Value 352 } 353 return m 354 } 355 356 func (m keyValueMap) get(key string, val interface{}) error { 357 enc, ok := m[key] 358 if !ok { 359 return errResp(ErrMissingKey, "%s", key) 360 } 361 if val == nil { 362 return nil 363 } 364 return rlp.DecodeBytes(enc, val) 365 } 366 367 func (p *peer) sendReceiveHandshake(sendList keyValueList) (keyValueList, error) { 368 // Send out own handshake in a new thread 369 errc := make(chan error, 1) 370 go func() { 371 errc <- p2p.Send(p.rw, StatusMsg, sendList) 372 }() 373 // In the mean time retrieve the remote status message 374 msg, err := p.rw.ReadMsg() 375 if err != nil { 376 return nil, err 377 } 378 if msg.Code != StatusMsg { 379 return nil, errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg) 380 } 381 if msg.Size > ProtocolMaxMsgSize { 382 return nil, errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize) 383 } 384 // Decode the handshake 385 var recvList keyValueList 386 if err := msg.Decode(&recvList); err != nil { 387 return nil, errResp(ErrDecode, "msg %v: %v", msg, err) 388 } 389 if err := <-errc; err != nil { 390 return nil, err 391 } 392 return recvList, nil 393 } 394 395 // Handshake executes the les protocol handshake, negotiating version number, 396 // network IDs, difficulties, head and genesis blocks. 397 func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, server *LesServer) error { 398 p.lock.Lock() 399 defer p.lock.Unlock() 400 401 var send keyValueList 402 send = send.add("protocolVersion", uint64(p.version)) 403 send = send.add("networkId", p.network) 404 send = send.add("headTd", td) 405 send = send.add("headHash", head) 406 send = send.add("headNum", headNum) 407 send = send.add("genesisHash", genesis) 408 if server != nil { 409 send = send.add("serveHeaders", nil) 410 send = send.add("serveChainSince", uint64(0)) 411 send = send.add("serveStateSince", uint64(0)) 412 send = send.add("txRelay", nil) 413 send = send.add("flowControl/BL", server.defParams.BufLimit) 414 send = send.add("flowControl/MRR", server.defParams.MinRecharge) 415 list := server.fcCostStats.getCurrentList() 416 send = send.add("flowControl/MRC", list) 417 p.fcCosts = list.decode() 418 } else { 419 p.requestAnnounceType = announceTypeSimple // set to default until "very light" client mode is implemented 420 send = send.add("announceType", p.requestAnnounceType) 421 } 422 recvList, err := p.sendReceiveHandshake(send) 423 if err != nil { 424 return err 425 } 426 recv := recvList.decode() 427 428 var rGenesis, rHash common.Hash 429 var rVersion, rNetwork, rNum uint64 430 var rTd *big.Int 431 432 if err := recv.get("protocolVersion", &rVersion); err != nil { 433 return err 434 } 435 if err := recv.get("networkId", &rNetwork); err != nil { 436 return err 437 } 438 if err := recv.get("headTd", &rTd); err != nil { 439 return err 440 } 441 if err := recv.get("headHash", &rHash); err != nil { 442 return err 443 } 444 if err := recv.get("headNum", &rNum); err != nil { 445 return err 446 } 447 if err := recv.get("genesisHash", &rGenesis); err != nil { 448 return err 449 } 450 451 if rGenesis != genesis { 452 return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", rGenesis[:8], genesis[:8]) 453 } 454 if rNetwork != p.network { 455 return errResp(ErrNetworkIdMismatch, "%d (!= %d)", rNetwork, p.network) 456 } 457 if int(rVersion) != p.version { 458 return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", rVersion, p.version) 459 } 460 if server != nil { 461 // until we have a proper peer connectivity API, allow LES connection to other servers 462 /*if recv.get("serveStateSince", nil) == nil { 463 return errResp(ErrUselessPeer, "wanted client, got server") 464 }*/ 465 if recv.get("announceType", &p.announceType) != nil { 466 p.announceType = announceTypeSimple 467 } 468 p.fcClient = flowcontrol.NewClientNode(server.fcManager, server.defParams) 469 } else { 470 if recv.get("serveChainSince", nil) != nil { 471 return errResp(ErrUselessPeer, "peer cannot serve chain") 472 } 473 if recv.get("serveStateSince", nil) != nil { 474 return errResp(ErrUselessPeer, "peer cannot serve state") 475 } 476 if recv.get("txRelay", nil) != nil { 477 return errResp(ErrUselessPeer, "peer cannot relay transactions") 478 } 479 params := &flowcontrol.ServerParams{} 480 if err := recv.get("flowControl/BL", ¶ms.BufLimit); err != nil { 481 return err 482 } 483 if err := recv.get("flowControl/MRR", ¶ms.MinRecharge); err != nil { 484 return err 485 } 486 var MRC RequestCostList 487 if err := recv.get("flowControl/MRC", &MRC); err != nil { 488 return err 489 } 490 p.fcServerParams = params 491 p.fcServer = flowcontrol.NewServerNode(params) 492 p.fcCosts = MRC.decode() 493 } 494 495 p.headInfo = &announceData{Td: rTd, Hash: rHash, Number: rNum} 496 return nil 497 } 498 499 // String implements fmt.Stringer. 500 func (p *peer) String() string { 501 return fmt.Sprintf("Peer %s [%s]", p.id, 502 fmt.Sprintf("les/%d", p.version), 503 ) 504 } 505 506 // peerSetNotify is a callback interface to notify services about added or 507 // removed peers 508 type peerSetNotify interface { 509 registerPeer(*peer) 510 unregisterPeer(*peer) 511 } 512 513 // peerSet represents the collection of active peers currently participating in 514 // the Light Ethereum sub-protocol. 515 type peerSet struct { 516 peers map[string]*peer 517 lock sync.RWMutex 518 notifyList []peerSetNotify 519 closed bool 520 } 521 522 // newPeerSet creates a new peer set to track the active participants. 523 func newPeerSet() *peerSet { 524 return &peerSet{ 525 peers: make(map[string]*peer), 526 } 527 } 528 529 // notify adds a service to be notified about added or removed peers 530 func (ps *peerSet) notify(n peerSetNotify) { 531 ps.lock.Lock() 532 ps.notifyList = append(ps.notifyList, n) 533 peers := make([]*peer, 0, len(ps.peers)) 534 for _, p := range ps.peers { 535 peers = append(peers, p) 536 } 537 ps.lock.Unlock() 538 539 for _, p := range peers { 540 n.registerPeer(p) 541 } 542 } 543 544 // Register injects a new peer into the working set, or returns an error if the 545 // peer is already known. 546 func (ps *peerSet) Register(p *peer) error { 547 ps.lock.Lock() 548 if ps.closed { 549 return errClosed 550 } 551 if _, ok := ps.peers[p.id]; ok { 552 return errAlreadyRegistered 553 } 554 ps.peers[p.id] = p 555 p.sendQueue = newExecQueue(100) 556 peers := make([]peerSetNotify, len(ps.notifyList)) 557 copy(peers, ps.notifyList) 558 ps.lock.Unlock() 559 560 for _, n := range peers { 561 n.registerPeer(p) 562 } 563 return nil 564 } 565 566 // Unregister removes a remote peer from the active set, disabling any further 567 // actions to/from that particular entity. It also initiates disconnection at the networking layer. 568 func (ps *peerSet) Unregister(id string) error { 569 ps.lock.Lock() 570 if p, ok := ps.peers[id]; !ok { 571 ps.lock.Unlock() 572 return errNotRegistered 573 } else { 574 delete(ps.peers, id) 575 peers := make([]peerSetNotify, len(ps.notifyList)) 576 copy(peers, ps.notifyList) 577 ps.lock.Unlock() 578 579 for _, n := range peers { 580 n.unregisterPeer(p) 581 } 582 p.sendQueue.quit() 583 p.Peer.Disconnect(p2p.DiscUselessPeer) 584 return nil 585 } 586 } 587 588 // AllPeerIDs returns a list of all registered peer IDs 589 func (ps *peerSet) AllPeerIDs() []string { 590 ps.lock.RLock() 591 defer ps.lock.RUnlock() 592 593 res := make([]string, len(ps.peers)) 594 idx := 0 595 for id := range ps.peers { 596 res[idx] = id 597 idx++ 598 } 599 return res 600 } 601 602 // Peer retrieves the registered peer with the given id. 603 func (ps *peerSet) Peer(id string) *peer { 604 ps.lock.RLock() 605 defer ps.lock.RUnlock() 606 607 return ps.peers[id] 608 } 609 610 // Len returns if the current number of peers in the set. 611 func (ps *peerSet) Len() int { 612 ps.lock.RLock() 613 defer ps.lock.RUnlock() 614 615 return len(ps.peers) 616 } 617 618 // BestPeer retrieves the known peer with the currently highest total difficulty. 619 func (ps *peerSet) BestPeer() *peer { 620 ps.lock.RLock() 621 defer ps.lock.RUnlock() 622 623 var ( 624 bestPeer *peer 625 bestTd *big.Int 626 ) 627 for _, p := range ps.peers { 628 if td := p.Td(); bestPeer == nil || td.Cmp(bestTd) > 0 { 629 bestPeer, bestTd = p, td 630 } 631 } 632 return bestPeer 633 } 634 635 // AllPeers returns all peers in a list 636 func (ps *peerSet) AllPeers() []*peer { 637 ps.lock.RLock() 638 defer ps.lock.RUnlock() 639 640 list := make([]*peer, len(ps.peers)) 641 i := 0 642 for _, peer := range ps.peers { 643 list[i] = peer 644 i++ 645 } 646 return list 647 } 648 649 // Close disconnects all peers. 650 // No new peers can be registered after Close has returned. 651 func (ps *peerSet) Close() { 652 ps.lock.Lock() 653 defer ps.lock.Unlock() 654 655 for _, p := range ps.peers { 656 p.Disconnect(p2p.DiscQuitting) 657 } 658 ps.closed = true 659 }