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