net.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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 discv5
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/common/mclock"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/crypto/sha3"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/p2p/nat"
  30. "github.com/ethereum/go-ethereum/p2p/netutil"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. )
  33. var (
  34. errInvalidEvent = errors.New("invalid in current state")
  35. errNoQuery = errors.New("no pending query")
  36. errWrongAddress = errors.New("unknown sender address")
  37. )
  38. const (
  39. autoRefreshInterval = 1 * time.Hour
  40. bucketRefreshInterval = 1 * time.Minute
  41. seedCount = 30
  42. seedMaxAge = 5 * 24 * time.Hour
  43. lowPort = 1024
  44. )
  45. const testTopic = "foo"
  46. const (
  47. printDebugLogs = false
  48. printTestImgLogs = false
  49. )
  50. func debugLog(s string) {
  51. if printDebugLogs {
  52. fmt.Println(s)
  53. }
  54. }
  55. // Network manages the table and all protocol interaction.
  56. type Network struct {
  57. db *nodeDB // database of known nodes
  58. conn transport
  59. netrestrict *netutil.Netlist
  60. closed chan struct{} // closed when loop is done
  61. closeReq chan struct{} // 'request to close'
  62. refreshReq chan []*Node // lookups ask for refresh on this channel
  63. refreshResp chan (<-chan struct{}) // ...and get the channel to block on from this one
  64. read chan ingressPacket // ingress packets arrive here
  65. timeout chan timeoutEvent
  66. queryReq chan *findnodeQuery // lookups submit findnode queries on this channel
  67. tableOpReq chan func()
  68. tableOpResp chan struct{}
  69. topicRegisterReq chan topicRegisterReq
  70. topicSearchReq chan topicSearchReq
  71. // State of the main loop.
  72. tab *Table
  73. topictab *topicTable
  74. ticketStore *ticketStore
  75. nursery []*Node
  76. nodes map[NodeID]*Node // tracks active nodes with state != known
  77. timeoutTimers map[timeoutEvent]*time.Timer
  78. // Revalidation queues.
  79. // Nodes put on these queues will be pinged eventually.
  80. slowRevalidateQueue []*Node
  81. fastRevalidateQueue []*Node
  82. // Buffers for state transition.
  83. sendBuf []*ingressPacket
  84. }
  85. // transport is implemented by the UDP transport.
  86. // it is an interface so we can test without opening lots of UDP
  87. // sockets and without generating a private key.
  88. type transport interface {
  89. sendPing(remote *Node, remoteAddr *net.UDPAddr, topics []Topic) (hash []byte)
  90. sendNeighbours(remote *Node, nodes []*Node)
  91. sendFindnodeHash(remote *Node, target common.Hash)
  92. sendTopicRegister(remote *Node, topics []Topic, topicIdx int, pong []byte)
  93. sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node)
  94. send(remote *Node, ptype nodeEvent, p interface{}) (hash []byte)
  95. localAddr() *net.UDPAddr
  96. Close()
  97. }
  98. type findnodeQuery struct {
  99. remote *Node
  100. target common.Hash
  101. reply chan<- []*Node
  102. nresults int // counter for received nodes
  103. }
  104. type topicRegisterReq struct {
  105. add bool
  106. topic Topic
  107. }
  108. type topicSearchReq struct {
  109. topic Topic
  110. found chan<- *Node
  111. lookup chan<- bool
  112. delay time.Duration
  113. }
  114. type topicSearchResult struct {
  115. target lookupInfo
  116. nodes []*Node
  117. }
  118. type timeoutEvent struct {
  119. ev nodeEvent
  120. node *Node
  121. }
  122. func newNetwork(conn transport, ourPubkey ecdsa.PublicKey, natm nat.Interface, dbPath string, netrestrict *netutil.Netlist) (*Network, error) {
  123. ourID := PubkeyID(&ourPubkey)
  124. var db *nodeDB
  125. if dbPath != "<no database>" {
  126. var err error
  127. if db, err = newNodeDB(dbPath, Version, ourID); err != nil {
  128. return nil, err
  129. }
  130. }
  131. tab := newTable(ourID, conn.localAddr())
  132. net := &Network{
  133. db: db,
  134. conn: conn,
  135. netrestrict: netrestrict,
  136. tab: tab,
  137. topictab: newTopicTable(db, tab.self),
  138. ticketStore: newTicketStore(),
  139. refreshReq: make(chan []*Node),
  140. refreshResp: make(chan (<-chan struct{})),
  141. closed: make(chan struct{}),
  142. closeReq: make(chan struct{}),
  143. read: make(chan ingressPacket, 100),
  144. timeout: make(chan timeoutEvent),
  145. timeoutTimers: make(map[timeoutEvent]*time.Timer),
  146. tableOpReq: make(chan func()),
  147. tableOpResp: make(chan struct{}),
  148. queryReq: make(chan *findnodeQuery),
  149. topicRegisterReq: make(chan topicRegisterReq),
  150. topicSearchReq: make(chan topicSearchReq),
  151. nodes: make(map[NodeID]*Node),
  152. }
  153. go net.loop()
  154. return net, nil
  155. }
  156. // Close terminates the network listener and flushes the node database.
  157. func (net *Network) Close() {
  158. net.conn.Close()
  159. select {
  160. case <-net.closed:
  161. case net.closeReq <- struct{}{}:
  162. <-net.closed
  163. }
  164. }
  165. // Self returns the local node.
  166. // The returned node should not be modified by the caller.
  167. func (net *Network) Self() *Node {
  168. return net.tab.self
  169. }
  170. // ReadRandomNodes fills the given slice with random nodes from the
  171. // table. It will not write the same node more than once. The nodes in
  172. // the slice are copies and can be modified by the caller.
  173. func (net *Network) ReadRandomNodes(buf []*Node) (n int) {
  174. net.reqTableOp(func() { n = net.tab.readRandomNodes(buf) })
  175. return n
  176. }
  177. // SetFallbackNodes sets the initial points of contact. These nodes
  178. // are used to connect to the network if the table is empty and there
  179. // are no known nodes in the database.
  180. func (net *Network) SetFallbackNodes(nodes []*Node) error {
  181. nursery := make([]*Node, 0, len(nodes))
  182. for _, n := range nodes {
  183. if err := n.validateComplete(); err != nil {
  184. return fmt.Errorf("bad bootstrap/fallback node %q (%v)", n, err)
  185. }
  186. // Recompute cpy.sha because the node might not have been
  187. // created by NewNode or ParseNode.
  188. cpy := *n
  189. cpy.sha = crypto.Keccak256Hash(n.ID[:])
  190. nursery = append(nursery, &cpy)
  191. }
  192. net.reqRefresh(nursery)
  193. return nil
  194. }
  195. // Resolve searches for a specific node with the given ID.
  196. // It returns nil if the node could not be found.
  197. func (net *Network) Resolve(targetID NodeID) *Node {
  198. result := net.lookup(crypto.Keccak256Hash(targetID[:]), true)
  199. for _, n := range result {
  200. if n.ID == targetID {
  201. return n
  202. }
  203. }
  204. return nil
  205. }
  206. // Lookup performs a network search for nodes close
  207. // to the given target. It approaches the target by querying
  208. // nodes that are closer to it on each iteration.
  209. // The given target does not need to be an actual node
  210. // identifier.
  211. //
  212. // The local node may be included in the result.
  213. func (net *Network) Lookup(targetID NodeID) []*Node {
  214. return net.lookup(crypto.Keccak256Hash(targetID[:]), false)
  215. }
  216. func (net *Network) lookup(target common.Hash, stopOnMatch bool) []*Node {
  217. var (
  218. asked = make(map[NodeID]bool)
  219. seen = make(map[NodeID]bool)
  220. reply = make(chan []*Node, alpha)
  221. result = nodesByDistance{target: target}
  222. pendingQueries = 0
  223. )
  224. // Get initial answers from the local node.
  225. result.push(net.tab.self, bucketSize)
  226. for {
  227. // Ask the α closest nodes that we haven't asked yet.
  228. for i := 0; i < len(result.entries) && pendingQueries < alpha; i++ {
  229. n := result.entries[i]
  230. if !asked[n.ID] {
  231. asked[n.ID] = true
  232. pendingQueries++
  233. net.reqQueryFindnode(n, target, reply)
  234. }
  235. }
  236. if pendingQueries == 0 {
  237. // We have asked all closest nodes, stop the search.
  238. break
  239. }
  240. // Wait for the next reply.
  241. select {
  242. case nodes := <-reply:
  243. for _, n := range nodes {
  244. if n != nil && !seen[n.ID] {
  245. seen[n.ID] = true
  246. result.push(n, bucketSize)
  247. if stopOnMatch && n.sha == target {
  248. return result.entries
  249. }
  250. }
  251. }
  252. pendingQueries--
  253. case <-time.After(respTimeout):
  254. // forget all pending requests, start new ones
  255. pendingQueries = 0
  256. reply = make(chan []*Node, alpha)
  257. }
  258. }
  259. return result.entries
  260. }
  261. func (net *Network) RegisterTopic(topic Topic, stop <-chan struct{}) {
  262. select {
  263. case net.topicRegisterReq <- topicRegisterReq{true, topic}:
  264. case <-net.closed:
  265. return
  266. }
  267. select {
  268. case <-net.closed:
  269. case <-stop:
  270. select {
  271. case net.topicRegisterReq <- topicRegisterReq{false, topic}:
  272. case <-net.closed:
  273. }
  274. }
  275. }
  276. func (net *Network) SearchTopic(topic Topic, setPeriod <-chan time.Duration, found chan<- *Node, lookup chan<- bool) {
  277. for {
  278. select {
  279. case <-net.closed:
  280. return
  281. case delay, ok := <-setPeriod:
  282. select {
  283. case net.topicSearchReq <- topicSearchReq{topic: topic, found: found, lookup: lookup, delay: delay}:
  284. case <-net.closed:
  285. return
  286. }
  287. if !ok {
  288. return
  289. }
  290. }
  291. }
  292. }
  293. func (net *Network) reqRefresh(nursery []*Node) <-chan struct{} {
  294. select {
  295. case net.refreshReq <- nursery:
  296. return <-net.refreshResp
  297. case <-net.closed:
  298. return net.closed
  299. }
  300. }
  301. func (net *Network) reqQueryFindnode(n *Node, target common.Hash, reply chan []*Node) bool {
  302. q := &findnodeQuery{remote: n, target: target, reply: reply}
  303. select {
  304. case net.queryReq <- q:
  305. return true
  306. case <-net.closed:
  307. return false
  308. }
  309. }
  310. func (net *Network) reqReadPacket(pkt ingressPacket) {
  311. select {
  312. case net.read <- pkt:
  313. case <-net.closed:
  314. }
  315. }
  316. func (net *Network) reqTableOp(f func()) (called bool) {
  317. select {
  318. case net.tableOpReq <- f:
  319. <-net.tableOpResp
  320. return true
  321. case <-net.closed:
  322. return false
  323. }
  324. }
  325. // TODO: external address handling.
  326. type topicSearchInfo struct {
  327. lookupChn chan<- bool
  328. period time.Duration
  329. }
  330. const maxSearchCount = 5
  331. func (net *Network) loop() {
  332. var (
  333. refreshTimer = time.NewTicker(autoRefreshInterval)
  334. bucketRefreshTimer = time.NewTimer(bucketRefreshInterval)
  335. refreshDone chan struct{} // closed when the 'refresh' lookup has ended
  336. )
  337. // Tracking the next ticket to register.
  338. var (
  339. nextTicket *ticketRef
  340. nextRegisterTimer *time.Timer
  341. nextRegisterTime <-chan time.Time
  342. )
  343. defer func() {
  344. if nextRegisterTimer != nil {
  345. nextRegisterTimer.Stop()
  346. }
  347. }()
  348. resetNextTicket := func() {
  349. t, timeout := net.ticketStore.nextFilteredTicket()
  350. if t != nextTicket {
  351. nextTicket = t
  352. if nextRegisterTimer != nil {
  353. nextRegisterTimer.Stop()
  354. nextRegisterTime = nil
  355. }
  356. if t != nil {
  357. nextRegisterTimer = time.NewTimer(timeout)
  358. nextRegisterTime = nextRegisterTimer.C
  359. }
  360. }
  361. }
  362. // Tracking registration and search lookups.
  363. var (
  364. topicRegisterLookupTarget lookupInfo
  365. topicRegisterLookupDone chan []*Node
  366. topicRegisterLookupTick = time.NewTimer(0)
  367. searchReqWhenRefreshDone []topicSearchReq
  368. searchInfo = make(map[Topic]topicSearchInfo)
  369. activeSearchCount int
  370. )
  371. topicSearchLookupDone := make(chan topicSearchResult, 100)
  372. topicSearch := make(chan Topic, 100)
  373. <-topicRegisterLookupTick.C
  374. statsDump := time.NewTicker(10 * time.Second)
  375. loop:
  376. for {
  377. resetNextTicket()
  378. select {
  379. case <-net.closeReq:
  380. debugLog("<-net.closeReq")
  381. break loop
  382. // Ingress packet handling.
  383. case pkt := <-net.read:
  384. //fmt.Println("read", pkt.ev)
  385. debugLog("<-net.read")
  386. n := net.internNode(&pkt)
  387. prestate := n.state
  388. status := "ok"
  389. if err := net.handle(n, pkt.ev, &pkt); err != nil {
  390. status = err.Error()
  391. }
  392. log.Trace("", "msg", log.Lazy{Fn: func() string {
  393. return fmt.Sprintf("<<< (%d) %v from %x@%v: %v -> %v (%v)",
  394. net.tab.count, pkt.ev, pkt.remoteID[:8], pkt.remoteAddr, prestate, n.state, status)
  395. }})
  396. // TODO: persist state if n.state goes >= known, delete if it goes <= known
  397. // State transition timeouts.
  398. case timeout := <-net.timeout:
  399. debugLog("<-net.timeout")
  400. if net.timeoutTimers[timeout] == nil {
  401. // Stale timer (was aborted).
  402. continue
  403. }
  404. delete(net.timeoutTimers, timeout)
  405. prestate := timeout.node.state
  406. status := "ok"
  407. if err := net.handle(timeout.node, timeout.ev, nil); err != nil {
  408. status = err.Error()
  409. }
  410. log.Trace("", "msg", log.Lazy{Fn: func() string {
  411. return fmt.Sprintf("--- (%d) %v for %x@%v: %v -> %v (%v)",
  412. net.tab.count, timeout.ev, timeout.node.ID[:8], timeout.node.addr(), prestate, timeout.node.state, status)
  413. }})
  414. // Querying.
  415. case q := <-net.queryReq:
  416. debugLog("<-net.queryReq")
  417. if !q.start(net) {
  418. q.remote.deferQuery(q)
  419. }
  420. // Interacting with the table.
  421. case f := <-net.tableOpReq:
  422. debugLog("<-net.tableOpReq")
  423. f()
  424. net.tableOpResp <- struct{}{}
  425. // Topic registration stuff.
  426. case req := <-net.topicRegisterReq:
  427. debugLog("<-net.topicRegisterReq")
  428. if !req.add {
  429. net.ticketStore.removeRegisterTopic(req.topic)
  430. continue
  431. }
  432. net.ticketStore.addTopic(req.topic, true)
  433. // If we're currently waiting idle (nothing to look up), give the ticket store a
  434. // chance to start it sooner. This should speed up convergence of the radius
  435. // determination for new topics.
  436. // if topicRegisterLookupDone == nil {
  437. if topicRegisterLookupTarget.target == (common.Hash{}) {
  438. debugLog("topicRegisterLookupTarget == null")
  439. if topicRegisterLookupTick.Stop() {
  440. <-topicRegisterLookupTick.C
  441. }
  442. target, delay := net.ticketStore.nextRegisterLookup()
  443. topicRegisterLookupTarget = target
  444. topicRegisterLookupTick.Reset(delay)
  445. }
  446. case nodes := <-topicRegisterLookupDone:
  447. debugLog("<-topicRegisterLookupDone")
  448. net.ticketStore.registerLookupDone(topicRegisterLookupTarget, nodes, func(n *Node) []byte {
  449. net.ping(n, n.addr())
  450. return n.pingEcho
  451. })
  452. target, delay := net.ticketStore.nextRegisterLookup()
  453. topicRegisterLookupTarget = target
  454. topicRegisterLookupTick.Reset(delay)
  455. topicRegisterLookupDone = nil
  456. case <-topicRegisterLookupTick.C:
  457. debugLog("<-topicRegisterLookupTick")
  458. if (topicRegisterLookupTarget.target == common.Hash{}) {
  459. target, delay := net.ticketStore.nextRegisterLookup()
  460. topicRegisterLookupTarget = target
  461. topicRegisterLookupTick.Reset(delay)
  462. topicRegisterLookupDone = nil
  463. } else {
  464. topicRegisterLookupDone = make(chan []*Node)
  465. target := topicRegisterLookupTarget.target
  466. go func() { topicRegisterLookupDone <- net.lookup(target, false) }()
  467. }
  468. case <-nextRegisterTime:
  469. debugLog("<-nextRegisterTime")
  470. net.ticketStore.ticketRegistered(*nextTicket)
  471. //fmt.Println("sendTopicRegister", nextTicket.t.node.addr().String(), nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong)
  472. net.conn.sendTopicRegister(nextTicket.t.node, nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong)
  473. case req := <-net.topicSearchReq:
  474. if refreshDone == nil {
  475. debugLog("<-net.topicSearchReq")
  476. info, ok := searchInfo[req.topic]
  477. if ok {
  478. if req.delay == time.Duration(0) {
  479. delete(searchInfo, req.topic)
  480. net.ticketStore.removeSearchTopic(req.topic)
  481. } else {
  482. info.period = req.delay
  483. searchInfo[req.topic] = info
  484. }
  485. continue
  486. }
  487. if req.delay != time.Duration(0) {
  488. var info topicSearchInfo
  489. info.period = req.delay
  490. info.lookupChn = req.lookup
  491. searchInfo[req.topic] = info
  492. net.ticketStore.addSearchTopic(req.topic, req.found)
  493. topicSearch <- req.topic
  494. }
  495. } else {
  496. searchReqWhenRefreshDone = append(searchReqWhenRefreshDone, req)
  497. }
  498. case topic := <-topicSearch:
  499. if activeSearchCount < maxSearchCount {
  500. activeSearchCount++
  501. target := net.ticketStore.nextSearchLookup(topic)
  502. go func() {
  503. nodes := net.lookup(target.target, false)
  504. topicSearchLookupDone <- topicSearchResult{target: target, nodes: nodes}
  505. }()
  506. }
  507. period := searchInfo[topic].period
  508. if period != time.Duration(0) {
  509. go func() {
  510. time.Sleep(period)
  511. topicSearch <- topic
  512. }()
  513. }
  514. case res := <-topicSearchLookupDone:
  515. activeSearchCount--
  516. if lookupChn := searchInfo[res.target.topic].lookupChn; lookupChn != nil {
  517. lookupChn <- net.ticketStore.radius[res.target.topic].converged
  518. }
  519. net.ticketStore.searchLookupDone(res.target, res.nodes, func(n *Node) []byte {
  520. net.ping(n, n.addr())
  521. return n.pingEcho
  522. }, func(n *Node, topic Topic) []byte {
  523. if n.state == known {
  524. return net.conn.send(n, topicQueryPacket, topicQuery{Topic: topic}) // TODO: set expiration
  525. } else {
  526. if n.state == unknown {
  527. net.ping(n, n.addr())
  528. }
  529. return nil
  530. }
  531. })
  532. case <-statsDump.C:
  533. debugLog("<-statsDump.C")
  534. /*r, ok := net.ticketStore.radius[testTopic]
  535. if !ok {
  536. fmt.Printf("(%x) no radius @ %v\n", net.tab.self.ID[:8], time.Now())
  537. } else {
  538. topics := len(net.ticketStore.tickets)
  539. tickets := len(net.ticketStore.nodes)
  540. rad := r.radius / (maxRadius/10000+1)
  541. fmt.Printf("(%x) topics:%d radius:%d tickets:%d @ %v\n", net.tab.self.ID[:8], topics, rad, tickets, time.Now())
  542. }*/
  543. tm := mclock.Now()
  544. for topic, r := range net.ticketStore.radius {
  545. if printTestImgLogs {
  546. rad := r.radius / (maxRadius/1000000 + 1)
  547. minrad := r.minRadius / (maxRadius/1000000 + 1)
  548. fmt.Printf("*R %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], rad)
  549. fmt.Printf("*MR %d %v %016x %v\n", tm/1000000, topic, net.tab.self.sha[:8], minrad)
  550. }
  551. }
  552. for topic, t := range net.topictab.topics {
  553. wp := t.wcl.nextWaitPeriod(tm)
  554. if printTestImgLogs {
  555. fmt.Printf("*W %d %v %016x %d\n", tm/1000000, topic, net.tab.self.sha[:8], wp/1000000)
  556. }
  557. }
  558. // Periodic / lookup-initiated bucket refresh.
  559. case <-refreshTimer.C:
  560. debugLog("<-refreshTimer.C")
  561. // TODO: ideally we would start the refresh timer after
  562. // fallback nodes have been set for the first time.
  563. if refreshDone == nil {
  564. refreshDone = make(chan struct{})
  565. net.refresh(refreshDone)
  566. }
  567. case <-bucketRefreshTimer.C:
  568. target := net.tab.chooseBucketRefreshTarget()
  569. go func() {
  570. net.lookup(target, false)
  571. bucketRefreshTimer.Reset(bucketRefreshInterval)
  572. }()
  573. case newNursery := <-net.refreshReq:
  574. debugLog("<-net.refreshReq")
  575. if newNursery != nil {
  576. net.nursery = newNursery
  577. }
  578. if refreshDone == nil {
  579. refreshDone = make(chan struct{})
  580. net.refresh(refreshDone)
  581. }
  582. net.refreshResp <- refreshDone
  583. case <-refreshDone:
  584. debugLog("<-net.refreshDone")
  585. refreshDone = nil
  586. list := searchReqWhenRefreshDone
  587. searchReqWhenRefreshDone = nil
  588. go func() {
  589. for _, req := range list {
  590. net.topicSearchReq <- req
  591. }
  592. }()
  593. }
  594. }
  595. debugLog("loop stopped")
  596. log.Debug(fmt.Sprintf("shutting down"))
  597. if net.conn != nil {
  598. net.conn.Close()
  599. }
  600. if refreshDone != nil {
  601. // TODO: wait for pending refresh.
  602. //<-refreshResults
  603. }
  604. // Cancel all pending timeouts.
  605. for _, timer := range net.timeoutTimers {
  606. timer.Stop()
  607. }
  608. if net.db != nil {
  609. net.db.close()
  610. }
  611. close(net.closed)
  612. }
  613. // Everything below runs on the Network.loop goroutine
  614. // and can modify Node, Table and Network at any time without locking.
  615. func (net *Network) refresh(done chan<- struct{}) {
  616. var seeds []*Node
  617. if net.db != nil {
  618. seeds = net.db.querySeeds(seedCount, seedMaxAge)
  619. }
  620. if len(seeds) == 0 {
  621. seeds = net.nursery
  622. }
  623. if len(seeds) == 0 {
  624. log.Trace("no seed nodes found")
  625. close(done)
  626. return
  627. }
  628. for _, n := range seeds {
  629. log.Debug("", "msg", log.Lazy{Fn: func() string {
  630. var age string
  631. if net.db != nil {
  632. age = time.Since(net.db.lastPong(n.ID)).String()
  633. } else {
  634. age = "unknown"
  635. }
  636. return fmt.Sprintf("seed node (age %s): %v", age, n)
  637. }})
  638. n = net.internNodeFromDB(n)
  639. if n.state == unknown {
  640. net.transition(n, verifyinit)
  641. }
  642. // Force-add the seed node so Lookup does something.
  643. // It will be deleted again if verification fails.
  644. net.tab.add(n)
  645. }
  646. // Start self lookup to fill up the buckets.
  647. go func() {
  648. net.Lookup(net.tab.self.ID)
  649. close(done)
  650. }()
  651. }
  652. // Node Interning.
  653. func (net *Network) internNode(pkt *ingressPacket) *Node {
  654. if n := net.nodes[pkt.remoteID]; n != nil {
  655. n.IP = pkt.remoteAddr.IP
  656. n.UDP = uint16(pkt.remoteAddr.Port)
  657. n.TCP = uint16(pkt.remoteAddr.Port)
  658. return n
  659. }
  660. n := NewNode(pkt.remoteID, pkt.remoteAddr.IP, uint16(pkt.remoteAddr.Port), uint16(pkt.remoteAddr.Port))
  661. n.state = unknown
  662. net.nodes[pkt.remoteID] = n
  663. return n
  664. }
  665. func (net *Network) internNodeFromDB(dbn *Node) *Node {
  666. if n := net.nodes[dbn.ID]; n != nil {
  667. return n
  668. }
  669. n := NewNode(dbn.ID, dbn.IP, dbn.UDP, dbn.TCP)
  670. n.state = unknown
  671. net.nodes[n.ID] = n
  672. return n
  673. }
  674. func (net *Network) internNodeFromNeighbours(sender *net.UDPAddr, rn rpcNode) (n *Node, err error) {
  675. if rn.ID == net.tab.self.ID {
  676. return nil, errors.New("is self")
  677. }
  678. if rn.UDP <= lowPort {
  679. return nil, errors.New("low port")
  680. }
  681. n = net.nodes[rn.ID]
  682. if n == nil {
  683. // We haven't seen this node before.
  684. n, err = nodeFromRPC(sender, rn)
  685. if net.netrestrict != nil && !net.netrestrict.Contains(n.IP) {
  686. return n, errors.New("not contained in netrestrict whitelist")
  687. }
  688. if err == nil {
  689. n.state = unknown
  690. net.nodes[n.ID] = n
  691. }
  692. return n, err
  693. }
  694. if !n.IP.Equal(rn.IP) || n.UDP != rn.UDP || n.TCP != rn.TCP {
  695. err = fmt.Errorf("metadata mismatch: got %v, want %v", rn, n)
  696. }
  697. return n, err
  698. }
  699. // nodeNetGuts is embedded in Node and contains fields.
  700. type nodeNetGuts struct {
  701. // This is a cached copy of sha3(ID) which is used for node
  702. // distance calculations. This is part of Node in order to make it
  703. // possible to write tests that need a node at a certain distance.
  704. // In those tests, the content of sha will not actually correspond
  705. // with ID.
  706. sha common.Hash
  707. // State machine fields. Access to these fields
  708. // is restricted to the Network.loop goroutine.
  709. state *nodeState
  710. pingEcho []byte // hash of last ping sent by us
  711. pingTopics []Topic // topic set sent by us in last ping
  712. deferredQueries []*findnodeQuery // queries that can't be sent yet
  713. pendingNeighbours *findnodeQuery // current query, waiting for reply
  714. queryTimeouts int
  715. }
  716. func (n *nodeNetGuts) deferQuery(q *findnodeQuery) {
  717. n.deferredQueries = append(n.deferredQueries, q)
  718. }
  719. func (n *nodeNetGuts) startNextQuery(net *Network) {
  720. if len(n.deferredQueries) == 0 {
  721. return
  722. }
  723. nextq := n.deferredQueries[0]
  724. if nextq.start(net) {
  725. n.deferredQueries = append(n.deferredQueries[:0], n.deferredQueries[1:]...)
  726. }
  727. }
  728. func (q *findnodeQuery) start(net *Network) bool {
  729. // Satisfy queries against the local node directly.
  730. if q.remote == net.tab.self {
  731. closest := net.tab.closest(crypto.Keccak256Hash(q.target[:]), bucketSize)
  732. q.reply <- closest.entries
  733. return true
  734. }
  735. if q.remote.state.canQuery && q.remote.pendingNeighbours == nil {
  736. net.conn.sendFindnodeHash(q.remote, q.target)
  737. net.timedEvent(respTimeout, q.remote, neighboursTimeout)
  738. q.remote.pendingNeighbours = q
  739. return true
  740. }
  741. // If the node is not known yet, it won't accept queries.
  742. // Initiate the transition to known.
  743. // The request will be sent later when the node reaches known state.
  744. if q.remote.state == unknown {
  745. net.transition(q.remote, verifyinit)
  746. }
  747. return false
  748. }
  749. // Node Events (the input to the state machine).
  750. type nodeEvent uint
  751. //go:generate stringer -type=nodeEvent
  752. const (
  753. invalidEvent nodeEvent = iota // zero is reserved
  754. // Packet type events.
  755. // These correspond to packet types in the UDP protocol.
  756. pingPacket
  757. pongPacket
  758. findnodePacket
  759. neighborsPacket
  760. findnodeHashPacket
  761. topicRegisterPacket
  762. topicQueryPacket
  763. topicNodesPacket
  764. // Non-packet events.
  765. // Event values in this category are allocated outside
  766. // the packet type range (packet types are encoded as a single byte).
  767. pongTimeout nodeEvent = iota + 256
  768. pingTimeout
  769. neighboursTimeout
  770. )
  771. // Node State Machine.
  772. type nodeState struct {
  773. name string
  774. handle func(*Network, *Node, nodeEvent, *ingressPacket) (next *nodeState, err error)
  775. enter func(*Network, *Node)
  776. canQuery bool
  777. }
  778. func (s *nodeState) String() string {
  779. return s.name
  780. }
  781. var (
  782. unknown *nodeState
  783. verifyinit *nodeState
  784. verifywait *nodeState
  785. remoteverifywait *nodeState
  786. known *nodeState
  787. contested *nodeState
  788. unresponsive *nodeState
  789. )
  790. func init() {
  791. unknown = &nodeState{
  792. name: "unknown",
  793. enter: func(net *Network, n *Node) {
  794. net.tab.delete(n)
  795. n.pingEcho = nil
  796. // Abort active queries.
  797. for _, q := range n.deferredQueries {
  798. q.reply <- nil
  799. }
  800. n.deferredQueries = nil
  801. if n.pendingNeighbours != nil {
  802. n.pendingNeighbours.reply <- nil
  803. n.pendingNeighbours = nil
  804. }
  805. n.queryTimeouts = 0
  806. },
  807. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  808. switch ev {
  809. case pingPacket:
  810. net.handlePing(n, pkt)
  811. net.ping(n, pkt.remoteAddr)
  812. return verifywait, nil
  813. default:
  814. return unknown, errInvalidEvent
  815. }
  816. },
  817. }
  818. verifyinit = &nodeState{
  819. name: "verifyinit",
  820. enter: func(net *Network, n *Node) {
  821. net.ping(n, n.addr())
  822. },
  823. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  824. switch ev {
  825. case pingPacket:
  826. net.handlePing(n, pkt)
  827. return verifywait, nil
  828. case pongPacket:
  829. err := net.handleKnownPong(n, pkt)
  830. return remoteverifywait, err
  831. case pongTimeout:
  832. return unknown, nil
  833. default:
  834. return verifyinit, errInvalidEvent
  835. }
  836. },
  837. }
  838. verifywait = &nodeState{
  839. name: "verifywait",
  840. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  841. switch ev {
  842. case pingPacket:
  843. net.handlePing(n, pkt)
  844. return verifywait, nil
  845. case pongPacket:
  846. err := net.handleKnownPong(n, pkt)
  847. return known, err
  848. case pongTimeout:
  849. return unknown, nil
  850. default:
  851. return verifywait, errInvalidEvent
  852. }
  853. },
  854. }
  855. remoteverifywait = &nodeState{
  856. name: "remoteverifywait",
  857. enter: func(net *Network, n *Node) {
  858. net.timedEvent(respTimeout, n, pingTimeout)
  859. },
  860. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  861. switch ev {
  862. case pingPacket:
  863. net.handlePing(n, pkt)
  864. return remoteverifywait, nil
  865. case pingTimeout:
  866. return known, nil
  867. default:
  868. return remoteverifywait, errInvalidEvent
  869. }
  870. },
  871. }
  872. known = &nodeState{
  873. name: "known",
  874. canQuery: true,
  875. enter: func(net *Network, n *Node) {
  876. n.queryTimeouts = 0
  877. n.startNextQuery(net)
  878. // Insert into the table and start revalidation of the last node
  879. // in the bucket if it is full.
  880. last := net.tab.add(n)
  881. if last != nil && last.state == known {
  882. // TODO: do this asynchronously
  883. net.transition(last, contested)
  884. }
  885. },
  886. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  887. switch ev {
  888. case pingPacket:
  889. net.handlePing(n, pkt)
  890. return known, nil
  891. case pongPacket:
  892. err := net.handleKnownPong(n, pkt)
  893. return known, err
  894. default:
  895. return net.handleQueryEvent(n, ev, pkt)
  896. }
  897. },
  898. }
  899. contested = &nodeState{
  900. name: "contested",
  901. canQuery: true,
  902. enter: func(net *Network, n *Node) {
  903. net.ping(n, n.addr())
  904. },
  905. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  906. switch ev {
  907. case pongPacket:
  908. // Node is still alive.
  909. err := net.handleKnownPong(n, pkt)
  910. return known, err
  911. case pongTimeout:
  912. net.tab.deleteReplace(n)
  913. return unresponsive, nil
  914. case pingPacket:
  915. net.handlePing(n, pkt)
  916. return contested, nil
  917. default:
  918. return net.handleQueryEvent(n, ev, pkt)
  919. }
  920. },
  921. }
  922. unresponsive = &nodeState{
  923. name: "unresponsive",
  924. canQuery: true,
  925. handle: func(net *Network, n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  926. switch ev {
  927. case pingPacket:
  928. net.handlePing(n, pkt)
  929. return known, nil
  930. case pongPacket:
  931. err := net.handleKnownPong(n, pkt)
  932. return known, err
  933. default:
  934. return net.handleQueryEvent(n, ev, pkt)
  935. }
  936. },
  937. }
  938. }
  939. // handle processes packets sent by n and events related to n.
  940. func (net *Network) handle(n *Node, ev nodeEvent, pkt *ingressPacket) error {
  941. //fmt.Println("handle", n.addr().String(), n.state, ev)
  942. if pkt != nil {
  943. if err := net.checkPacket(n, ev, pkt); err != nil {
  944. //fmt.Println("check err:", err)
  945. return err
  946. }
  947. // Start the background expiration goroutine after the first
  948. // successful communication. Subsequent calls have no effect if it
  949. // is already running. We do this here instead of somewhere else
  950. // so that the search for seed nodes also considers older nodes
  951. // that would otherwise be removed by the expirer.
  952. if net.db != nil {
  953. net.db.ensureExpirer()
  954. }
  955. }
  956. if n.state == nil {
  957. n.state = unknown //???
  958. }
  959. next, err := n.state.handle(net, n, ev, pkt)
  960. net.transition(n, next)
  961. //fmt.Println("new state:", n.state)
  962. return err
  963. }
  964. func (net *Network) checkPacket(n *Node, ev nodeEvent, pkt *ingressPacket) error {
  965. // Replay prevention checks.
  966. switch ev {
  967. case pingPacket, findnodeHashPacket, neighborsPacket:
  968. // TODO: check date is > last date seen
  969. // TODO: check ping version
  970. case pongPacket:
  971. if !bytes.Equal(pkt.data.(*pong).ReplyTok, n.pingEcho) {
  972. // fmt.Println("pong reply token mismatch")
  973. return fmt.Errorf("pong reply token mismatch")
  974. }
  975. n.pingEcho = nil
  976. }
  977. // Address validation.
  978. // TODO: Ideally we would do the following:
  979. // - reject all packets with wrong address except ping.
  980. // - for ping with new address, transition to verifywait but keep the
  981. // previous node (with old address) around. if the new one reaches known,
  982. // swap it out.
  983. return nil
  984. }
  985. func (net *Network) transition(n *Node, next *nodeState) {
  986. if n.state != next {
  987. n.state = next
  988. if next.enter != nil {
  989. next.enter(net, n)
  990. }
  991. }
  992. // TODO: persist/unpersist node
  993. }
  994. func (net *Network) timedEvent(d time.Duration, n *Node, ev nodeEvent) {
  995. timeout := timeoutEvent{ev, n}
  996. net.timeoutTimers[timeout] = time.AfterFunc(d, func() {
  997. select {
  998. case net.timeout <- timeout:
  999. case <-net.closed:
  1000. }
  1001. })
  1002. }
  1003. func (net *Network) abortTimedEvent(n *Node, ev nodeEvent) {
  1004. timer := net.timeoutTimers[timeoutEvent{ev, n}]
  1005. if timer != nil {
  1006. timer.Stop()
  1007. delete(net.timeoutTimers, timeoutEvent{ev, n})
  1008. }
  1009. }
  1010. func (net *Network) ping(n *Node, addr *net.UDPAddr) {
  1011. //fmt.Println("ping", n.addr().String(), n.ID.String(), n.sha.Hex())
  1012. if n.pingEcho != nil || n.ID == net.tab.self.ID {
  1013. //fmt.Println(" not sent")
  1014. return
  1015. }
  1016. debugLog(fmt.Sprintf("ping(node = %x)", n.ID[:8]))
  1017. n.pingTopics = net.ticketStore.regTopicSet()
  1018. n.pingEcho = net.conn.sendPing(n, addr, n.pingTopics)
  1019. net.timedEvent(respTimeout, n, pongTimeout)
  1020. }
  1021. func (net *Network) handlePing(n *Node, pkt *ingressPacket) {
  1022. debugLog(fmt.Sprintf("handlePing(node = %x)", n.ID[:8]))
  1023. ping := pkt.data.(*ping)
  1024. n.TCP = ping.From.TCP
  1025. t := net.topictab.getTicket(n, ping.Topics)
  1026. pong := &pong{
  1027. To: makeEndpoint(n.addr(), n.TCP), // TODO: maybe use known TCP port from DB
  1028. ReplyTok: pkt.hash,
  1029. Expiration: uint64(time.Now().Add(expiration).Unix()),
  1030. }
  1031. ticketToPong(t, pong)
  1032. net.conn.send(n, pongPacket, pong)
  1033. }
  1034. func (net *Network) handleKnownPong(n *Node, pkt *ingressPacket) error {
  1035. debugLog(fmt.Sprintf("handleKnownPong(node = %x)", n.ID[:8]))
  1036. net.abortTimedEvent(n, pongTimeout)
  1037. now := mclock.Now()
  1038. ticket, err := pongToTicket(now, n.pingTopics, n, pkt)
  1039. if err == nil {
  1040. // fmt.Printf("(%x) ticket: %+v\n", net.tab.self.ID[:8], pkt.data)
  1041. net.ticketStore.addTicket(now, pkt.data.(*pong).ReplyTok, ticket)
  1042. } else {
  1043. debugLog(fmt.Sprintf(" error: %v", err))
  1044. }
  1045. n.pingEcho = nil
  1046. n.pingTopics = nil
  1047. return err
  1048. }
  1049. func (net *Network) handleQueryEvent(n *Node, ev nodeEvent, pkt *ingressPacket) (*nodeState, error) {
  1050. switch ev {
  1051. case findnodePacket:
  1052. target := crypto.Keccak256Hash(pkt.data.(*findnode).Target[:])
  1053. results := net.tab.closest(target, bucketSize).entries
  1054. net.conn.sendNeighbours(n, results)
  1055. return n.state, nil
  1056. case neighborsPacket:
  1057. err := net.handleNeighboursPacket(n, pkt)
  1058. return n.state, err
  1059. case neighboursTimeout:
  1060. if n.pendingNeighbours != nil {
  1061. n.pendingNeighbours.reply <- nil
  1062. n.pendingNeighbours = nil
  1063. }
  1064. n.queryTimeouts++
  1065. if n.queryTimeouts > maxFindnodeFailures && n.state == known {
  1066. return contested, errors.New("too many timeouts")
  1067. }
  1068. return n.state, nil
  1069. // v5
  1070. case findnodeHashPacket:
  1071. results := net.tab.closest(pkt.data.(*findnodeHash).Target, bucketSize).entries
  1072. net.conn.sendNeighbours(n, results)
  1073. return n.state, nil
  1074. case topicRegisterPacket:
  1075. //fmt.Println("got topicRegisterPacket")
  1076. regdata := pkt.data.(*topicRegister)
  1077. pong, err := net.checkTopicRegister(regdata)
  1078. if err != nil {
  1079. //fmt.Println(err)
  1080. return n.state, fmt.Errorf("bad waiting ticket: %v", err)
  1081. }
  1082. net.topictab.useTicket(n, pong.TicketSerial, regdata.Topics, int(regdata.Idx), pong.Expiration, pong.WaitPeriods)
  1083. return n.state, nil
  1084. case topicQueryPacket:
  1085. // TODO: handle expiration
  1086. topic := pkt.data.(*topicQuery).Topic
  1087. results := net.topictab.getEntries(topic)
  1088. if _, ok := net.ticketStore.tickets[topic]; ok {
  1089. results = append(results, net.tab.self) // we're not registering in our own table but if we're advertising, return ourselves too
  1090. }
  1091. if len(results) > 10 {
  1092. results = results[:10]
  1093. }
  1094. var hash common.Hash
  1095. copy(hash[:], pkt.hash)
  1096. net.conn.sendTopicNodes(n, hash, results)
  1097. return n.state, nil
  1098. case topicNodesPacket:
  1099. p := pkt.data.(*topicNodes)
  1100. if net.ticketStore.gotTopicNodes(n, p.Echo, p.Nodes) {
  1101. n.queryTimeouts++
  1102. if n.queryTimeouts > maxFindnodeFailures && n.state == known {
  1103. return contested, errors.New("too many timeouts")
  1104. }
  1105. }
  1106. return n.state, nil
  1107. default:
  1108. return n.state, errInvalidEvent
  1109. }
  1110. }
  1111. func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) {
  1112. var pongpkt ingressPacket
  1113. if err := decodePacket(data.Pong, &pongpkt); err != nil {
  1114. return nil, err
  1115. }
  1116. if pongpkt.ev != pongPacket {
  1117. return nil, errors.New("is not pong packet")
  1118. }
  1119. if pongpkt.remoteID != net.tab.self.ID {
  1120. return nil, errors.New("not signed by us")
  1121. }
  1122. // check that we previously authorised all topics
  1123. // that the other side is trying to register.
  1124. if rlpHash(data.Topics) != pongpkt.data.(*pong).TopicHash {
  1125. return nil, errors.New("topic hash mismatch")
  1126. }
  1127. if data.Idx < 0 || int(data.Idx) >= len(data.Topics) {
  1128. return nil, errors.New("topic index out of range")
  1129. }
  1130. return pongpkt.data.(*pong), nil
  1131. }
  1132. func rlpHash(x interface{}) (h common.Hash) {
  1133. hw := sha3.NewKeccak256()
  1134. rlp.Encode(hw, x)
  1135. hw.Sum(h[:0])
  1136. return h
  1137. }
  1138. func (net *Network) handleNeighboursPacket(n *Node, pkt *ingressPacket) error {
  1139. if n.pendingNeighbours == nil {
  1140. return errNoQuery
  1141. }
  1142. net.abortTimedEvent(n, neighboursTimeout)
  1143. req := pkt.data.(*neighbors)
  1144. nodes := make([]*Node, len(req.Nodes))
  1145. for i, rn := range req.Nodes {
  1146. nn, err := net.internNodeFromNeighbours(pkt.remoteAddr, rn)
  1147. if err != nil {
  1148. log.Debug(fmt.Sprintf("invalid neighbour (%v) from %x@%v: %v", rn.IP, n.ID[:8], pkt.remoteAddr, err))
  1149. continue
  1150. }
  1151. nodes[i] = nn
  1152. // Start validation of query results immediately.
  1153. // This fills the table quickly.
  1154. // TODO: generates way too many packets, maybe do it via queue.
  1155. if nn.state == unknown {
  1156. net.transition(nn, verifyinit)
  1157. }
  1158. }
  1159. // TODO: don't ignore second packet
  1160. n.pendingNeighbours.reply <- nodes
  1161. n.pendingNeighbours = nil
  1162. // Now that this query is done, start the next one.
  1163. n.startNextQuery(net)
  1164. return nil
  1165. }