peer.go 37 KB

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