ticket.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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. "encoding/binary"
  20. "fmt"
  21. "math"
  22. "math/rand"
  23. "sort"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/mclock"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. )
  29. const (
  30. ticketTimeBucketLen = time.Minute
  31. timeWindow = 10 // * ticketTimeBucketLen
  32. wantTicketsInWindow = 10
  33. collectFrequency = time.Second * 30
  34. registerFrequency = time.Second * 60
  35. maxCollectDebt = 10
  36. maxRegisterDebt = 5
  37. keepTicketConst = time.Minute * 10
  38. keepTicketExp = time.Minute * 5
  39. targetWaitTime = time.Minute * 10
  40. topicQueryTimeout = time.Second * 5
  41. topicQueryResend = time.Minute
  42. // topic radius detection
  43. maxRadius = 0xffffffffffffffff
  44. radiusTC = time.Minute * 20
  45. radiusBucketsPerBit = 8
  46. minSlope = 1
  47. minPeakSize = 40
  48. maxNoAdjust = 20
  49. lookupWidth = 8
  50. minRightSum = 20
  51. searchForceQuery = 4
  52. )
  53. // timeBucket represents absolute monotonic time in minutes.
  54. // It is used as the index into the per-topic ticket buckets.
  55. type timeBucket int
  56. type ticket struct {
  57. topics []Topic
  58. regTime []mclock.AbsTime // Per-topic local absolute time when the ticket can be used.
  59. // The serial number that was issued by the server.
  60. serial uint32
  61. // Used by registrar, tracks absolute time when the ticket was created.
  62. issueTime mclock.AbsTime
  63. // Fields used only by registrants
  64. node *Node // the registrar node that signed this ticket
  65. refCnt int // tracks number of topics that will be registered using this ticket
  66. pong []byte // encoded pong packet signed by the registrar
  67. }
  68. // ticketRef refers to a single topic in a ticket.
  69. type ticketRef struct {
  70. t *ticket
  71. idx int // index of the topic in t.topics and t.regTime
  72. }
  73. func (ref ticketRef) topic() Topic {
  74. return ref.t.topics[ref.idx]
  75. }
  76. func (ref ticketRef) topicRegTime() mclock.AbsTime {
  77. return ref.t.regTime[ref.idx]
  78. }
  79. func pongToTicket(localTime mclock.AbsTime, topics []Topic, node *Node, p *ingressPacket) (*ticket, error) {
  80. wps := p.data.(*pong).WaitPeriods
  81. if len(topics) != len(wps) {
  82. return nil, fmt.Errorf("bad wait period list: got %d values, want %d", len(topics), len(wps))
  83. }
  84. if rlpHash(topics) != p.data.(*pong).TopicHash {
  85. return nil, fmt.Errorf("bad topic hash")
  86. }
  87. t := &ticket{
  88. issueTime: localTime,
  89. node: node,
  90. topics: topics,
  91. pong: p.rawData,
  92. regTime: make([]mclock.AbsTime, len(wps)),
  93. }
  94. // Convert wait periods to local absolute time.
  95. for i, wp := range wps {
  96. t.regTime[i] = localTime + mclock.AbsTime(time.Second*time.Duration(wp))
  97. }
  98. return t, nil
  99. }
  100. func ticketToPong(t *ticket, pong *pong) {
  101. pong.Expiration = uint64(t.issueTime / mclock.AbsTime(time.Second))
  102. pong.TopicHash = rlpHash(t.topics)
  103. pong.TicketSerial = t.serial
  104. pong.WaitPeriods = make([]uint32, len(t.regTime))
  105. for i, regTime := range t.regTime {
  106. pong.WaitPeriods[i] = uint32(time.Duration(regTime-t.issueTime) / time.Second)
  107. }
  108. }
  109. type ticketStore struct {
  110. // radius detector and target address generator
  111. // exists for both searched and registered topics
  112. radius map[Topic]*topicRadius
  113. // Contains buckets (for each absolute minute) of tickets
  114. // that can be used in that minute.
  115. // This is only set if the topic is being registered.
  116. tickets map[Topic]topicTickets
  117. regtopics []Topic
  118. nodes map[*Node]*ticket
  119. nodeLastReq map[*Node]reqInfo
  120. lastBucketFetched timeBucket
  121. nextTicketCached *ticketRef
  122. nextTicketReg mclock.AbsTime
  123. searchTopicMap map[Topic]searchTopic
  124. nextTopicQueryCleanup mclock.AbsTime
  125. queriesSent map[*Node]map[common.Hash]sentQuery
  126. }
  127. type searchTopic struct {
  128. foundChn chan<- *Node
  129. }
  130. type sentQuery struct {
  131. sent mclock.AbsTime
  132. lookup lookupInfo
  133. }
  134. type topicTickets struct {
  135. buckets map[timeBucket][]ticketRef
  136. nextLookup, nextReg mclock.AbsTime
  137. }
  138. func newTicketStore() *ticketStore {
  139. return &ticketStore{
  140. radius: make(map[Topic]*topicRadius),
  141. tickets: make(map[Topic]topicTickets),
  142. nodes: make(map[*Node]*ticket),
  143. nodeLastReq: make(map[*Node]reqInfo),
  144. searchTopicMap: make(map[Topic]searchTopic),
  145. queriesSent: make(map[*Node]map[common.Hash]sentQuery),
  146. }
  147. }
  148. // addTopic starts tracking a topic. If register is true,
  149. // the local node will register the topic and tickets will be collected.
  150. func (s *ticketStore) addTopic(t Topic, register bool) {
  151. debugLog(fmt.Sprintf(" addTopic(%v, %v)", t, register))
  152. if s.radius[t] == nil {
  153. s.radius[t] = newTopicRadius(t)
  154. }
  155. if register && s.tickets[t].buckets == nil {
  156. s.tickets[t] = topicTickets{buckets: make(map[timeBucket][]ticketRef)}
  157. }
  158. }
  159. func (s *ticketStore) addSearchTopic(t Topic, foundChn chan<- *Node) {
  160. s.addTopic(t, false)
  161. if s.searchTopicMap[t].foundChn == nil {
  162. s.searchTopicMap[t] = searchTopic{foundChn: foundChn}
  163. }
  164. }
  165. func (s *ticketStore) removeSearchTopic(t Topic) {
  166. if st := s.searchTopicMap[t]; st.foundChn != nil {
  167. delete(s.searchTopicMap, t)
  168. }
  169. }
  170. // removeRegisterTopic deletes all tickets for the given topic.
  171. func (s *ticketStore) removeRegisterTopic(topic Topic) {
  172. debugLog(fmt.Sprintf(" removeRegisterTopic(%v)", topic))
  173. for _, list := range s.tickets[topic].buckets {
  174. for _, ref := range list {
  175. ref.t.refCnt--
  176. if ref.t.refCnt == 0 {
  177. delete(s.nodes, ref.t.node)
  178. delete(s.nodeLastReq, ref.t.node)
  179. }
  180. }
  181. }
  182. delete(s.tickets, topic)
  183. }
  184. func (s *ticketStore) regTopicSet() []Topic {
  185. topics := make([]Topic, 0, len(s.tickets))
  186. for topic := range s.tickets {
  187. topics = append(topics, topic)
  188. }
  189. return topics
  190. }
  191. // nextRegisterLookup returns the target of the next lookup for ticket collection.
  192. func (s *ticketStore) nextRegisterLookup() (lookup lookupInfo, delay time.Duration) {
  193. debugLog("nextRegisterLookup()")
  194. firstTopic, ok := s.iterRegTopics()
  195. for topic := firstTopic; ok; {
  196. debugLog(fmt.Sprintf(" checking topic %v, len(s.tickets[topic]) = %d", topic, len(s.tickets[topic].buckets)))
  197. if s.tickets[topic].buckets != nil && s.needMoreTickets(topic) {
  198. next := s.radius[topic].nextTarget(false)
  199. debugLog(fmt.Sprintf(" %x 1s", next.target[:8]))
  200. return next, 100 * time.Millisecond
  201. }
  202. topic, ok = s.iterRegTopics()
  203. if topic == firstTopic {
  204. break // We have checked all topics.
  205. }
  206. }
  207. debugLog(" null, 40s")
  208. return lookupInfo{}, 40 * time.Second
  209. }
  210. func (s *ticketStore) nextSearchLookup(topic Topic) lookupInfo {
  211. tr := s.radius[topic]
  212. target := tr.nextTarget(tr.radiusLookupCnt >= searchForceQuery)
  213. if target.radiusLookup {
  214. tr.radiusLookupCnt++
  215. } else {
  216. tr.radiusLookupCnt = 0
  217. }
  218. return target
  219. }
  220. // iterRegTopics returns topics to register in arbitrary order.
  221. // The second return value is false if there are no topics.
  222. func (s *ticketStore) iterRegTopics() (Topic, bool) {
  223. debugLog("iterRegTopics()")
  224. if len(s.regtopics) == 0 {
  225. if len(s.tickets) == 0 {
  226. debugLog(" false")
  227. return "", false
  228. }
  229. // Refill register list.
  230. for t := range s.tickets {
  231. s.regtopics = append(s.regtopics, t)
  232. }
  233. }
  234. topic := s.regtopics[len(s.regtopics)-1]
  235. s.regtopics = s.regtopics[:len(s.regtopics)-1]
  236. debugLog(" " + string(topic) + " true")
  237. return topic, true
  238. }
  239. func (s *ticketStore) needMoreTickets(t Topic) bool {
  240. return s.tickets[t].nextLookup < mclock.Now()
  241. }
  242. // ticketsInWindow returns the tickets of a given topic in the registration window.
  243. func (s *ticketStore) ticketsInWindow(t Topic) []ticketRef {
  244. ltBucket := s.lastBucketFetched
  245. var res []ticketRef
  246. tickets := s.tickets[t].buckets
  247. for g := ltBucket; g < ltBucket+timeWindow; g++ {
  248. res = append(res, tickets[g]...)
  249. }
  250. debugLog(fmt.Sprintf("ticketsInWindow(%v) = %v", t, len(res)))
  251. return res
  252. }
  253. func (s *ticketStore) removeExcessTickets(t Topic) {
  254. tickets := s.ticketsInWindow(t)
  255. if len(tickets) <= wantTicketsInWindow {
  256. return
  257. }
  258. sort.Sort(ticketRefByWaitTime(tickets))
  259. for _, r := range tickets[wantTicketsInWindow:] {
  260. s.removeTicketRef(r)
  261. }
  262. }
  263. type ticketRefByWaitTime []ticketRef
  264. // Len is the number of elements in the collection.
  265. func (s ticketRefByWaitTime) Len() int {
  266. return len(s)
  267. }
  268. func (r ticketRef) waitTime() mclock.AbsTime {
  269. return r.t.regTime[r.idx] - r.t.issueTime
  270. }
  271. // Less reports whether the element with
  272. // index i should sort before the element with index j.
  273. func (s ticketRefByWaitTime) Less(i, j int) bool {
  274. return s[i].waitTime() < s[j].waitTime()
  275. }
  276. // Swap swaps the elements with indexes i and j.
  277. func (s ticketRefByWaitTime) Swap(i, j int) {
  278. s[i], s[j] = s[j], s[i]
  279. }
  280. func (s *ticketStore) addTicketRef(r ticketRef) {
  281. topic := r.t.topics[r.idx]
  282. t := s.tickets[topic]
  283. if t.buckets == nil {
  284. return
  285. }
  286. bucket := timeBucket(r.t.regTime[r.idx] / mclock.AbsTime(ticketTimeBucketLen))
  287. t.buckets[bucket] = append(t.buckets[bucket], r)
  288. r.t.refCnt++
  289. min := mclock.Now() - mclock.AbsTime(collectFrequency)*maxCollectDebt
  290. if t.nextLookup < min {
  291. t.nextLookup = min
  292. }
  293. t.nextLookup += mclock.AbsTime(collectFrequency)
  294. s.tickets[topic] = t
  295. //s.removeExcessTickets(topic)
  296. }
  297. func (s *ticketStore) nextFilteredTicket() (t *ticketRef, wait time.Duration) {
  298. now := mclock.Now()
  299. for {
  300. t, wait = s.nextRegisterableTicket()
  301. if t == nil {
  302. return
  303. }
  304. regTime := now + mclock.AbsTime(wait)
  305. topic := t.t.topics[t.idx]
  306. if regTime >= s.tickets[topic].nextReg {
  307. return
  308. }
  309. s.removeTicketRef(*t)
  310. }
  311. }
  312. func (s *ticketStore) ticketRegistered(t ticketRef) {
  313. now := mclock.Now()
  314. topic := t.t.topics[t.idx]
  315. tt := s.tickets[topic]
  316. min := now - mclock.AbsTime(registerFrequency)*maxRegisterDebt
  317. if min > tt.nextReg {
  318. tt.nextReg = min
  319. }
  320. tt.nextReg += mclock.AbsTime(registerFrequency)
  321. s.tickets[topic] = tt
  322. s.removeTicketRef(t)
  323. }
  324. // nextRegisterableTicket returns the next ticket that can be used
  325. // to register.
  326. //
  327. // If the returned wait time <= zero the ticket can be used. For a positive
  328. // wait time, the caller should requery the next ticket later.
  329. //
  330. // A ticket can be returned more than once with <= zero wait time in case
  331. // the ticket contains multiple topics.
  332. func (s *ticketStore) nextRegisterableTicket() (t *ticketRef, wait time.Duration) {
  333. defer func() {
  334. if t == nil {
  335. debugLog(" nil")
  336. } else {
  337. debugLog(fmt.Sprintf(" node = %x sn = %v wait = %v", t.t.node.ID[:8], t.t.serial, wait))
  338. }
  339. }()
  340. debugLog("nextRegisterableTicket()")
  341. now := mclock.Now()
  342. if s.nextTicketCached != nil {
  343. return s.nextTicketCached, time.Duration(s.nextTicketCached.topicRegTime() - now)
  344. }
  345. for bucket := s.lastBucketFetched; ; bucket++ {
  346. var (
  347. empty = true // true if there are no tickets
  348. nextTicket ticketRef // uninitialized if this bucket is empty
  349. )
  350. for _, tickets := range s.tickets {
  351. //s.removeExcessTickets(topic)
  352. if len(tickets.buckets) != 0 {
  353. empty = false
  354. list := tickets.buckets[bucket]
  355. for _, ref := range list {
  356. //debugLog(fmt.Sprintf(" nrt bucket = %d node = %x sn = %v wait = %v", bucket, ref.t.node.ID[:8], ref.t.serial, time.Duration(ref.topicRegTime()-now)))
  357. if nextTicket.t == nil || ref.topicRegTime() < nextTicket.topicRegTime() {
  358. nextTicket = ref
  359. }
  360. }
  361. }
  362. }
  363. if empty {
  364. return nil, 0
  365. }
  366. if nextTicket.t != nil {
  367. wait = time.Duration(nextTicket.topicRegTime() - now)
  368. s.nextTicketCached = &nextTicket
  369. return &nextTicket, wait
  370. }
  371. s.lastBucketFetched = bucket
  372. }
  373. }
  374. // removeTicket removes a ticket from the ticket store
  375. func (s *ticketStore) removeTicketRef(ref ticketRef) {
  376. debugLog(fmt.Sprintf("removeTicketRef(node = %x sn = %v)", ref.t.node.ID[:8], ref.t.serial))
  377. topic := ref.topic()
  378. tickets := s.tickets[topic].buckets
  379. if tickets == nil {
  380. return
  381. }
  382. bucket := timeBucket(ref.t.regTime[ref.idx] / mclock.AbsTime(ticketTimeBucketLen))
  383. list := tickets[bucket]
  384. idx := -1
  385. for i, bt := range list {
  386. if bt.t == ref.t {
  387. idx = i
  388. break
  389. }
  390. }
  391. if idx == -1 {
  392. panic(nil)
  393. }
  394. list = append(list[:idx], list[idx+1:]...)
  395. if len(list) != 0 {
  396. tickets[bucket] = list
  397. } else {
  398. delete(tickets, bucket)
  399. }
  400. ref.t.refCnt--
  401. if ref.t.refCnt == 0 {
  402. delete(s.nodes, ref.t.node)
  403. delete(s.nodeLastReq, ref.t.node)
  404. }
  405. // Make nextRegisterableTicket return the next available ticket.
  406. s.nextTicketCached = nil
  407. }
  408. type lookupInfo struct {
  409. target common.Hash
  410. topic Topic
  411. radiusLookup bool
  412. }
  413. type reqInfo struct {
  414. pingHash []byte
  415. lookup lookupInfo
  416. time mclock.AbsTime
  417. }
  418. // returns -1 if not found
  419. func (t *ticket) findIdx(topic Topic) int {
  420. for i, tt := range t.topics {
  421. if tt == topic {
  422. return i
  423. }
  424. }
  425. return -1
  426. }
  427. func (s *ticketStore) registerLookupDone(lookup lookupInfo, nodes []*Node, ping func(n *Node) []byte) {
  428. now := mclock.Now()
  429. for i, n := range nodes {
  430. if i == 0 || (binary.BigEndian.Uint64(n.sha[:8])^binary.BigEndian.Uint64(lookup.target[:8])) < s.radius[lookup.topic].minRadius {
  431. if lookup.radiusLookup {
  432. if lastReq, ok := s.nodeLastReq[n]; !ok || time.Duration(now-lastReq.time) > radiusTC {
  433. s.nodeLastReq[n] = reqInfo{pingHash: ping(n), lookup: lookup, time: now}
  434. }
  435. } else {
  436. if s.nodes[n] == nil {
  437. s.nodeLastReq[n] = reqInfo{pingHash: ping(n), lookup: lookup, time: now}
  438. }
  439. }
  440. }
  441. }
  442. }
  443. func (s *ticketStore) searchLookupDone(lookup lookupInfo, nodes []*Node, ping func(n *Node) []byte, query func(n *Node, topic Topic) []byte) {
  444. now := mclock.Now()
  445. for i, n := range nodes {
  446. if i == 0 || (binary.BigEndian.Uint64(n.sha[:8])^binary.BigEndian.Uint64(lookup.target[:8])) < s.radius[lookup.topic].minRadius {
  447. if lookup.radiusLookup {
  448. if lastReq, ok := s.nodeLastReq[n]; !ok || time.Duration(now-lastReq.time) > radiusTC {
  449. s.nodeLastReq[n] = reqInfo{pingHash: ping(n), lookup: lookup, time: now}
  450. }
  451. } // else {
  452. if s.canQueryTopic(n, lookup.topic) {
  453. hash := query(n, lookup.topic)
  454. if hash != nil {
  455. s.addTopicQuery(common.BytesToHash(hash), n, lookup)
  456. }
  457. }
  458. //}
  459. }
  460. }
  461. }
  462. func (s *ticketStore) adjustWithTicket(now mclock.AbsTime, targetHash common.Hash, t *ticket) {
  463. for i, topic := range t.topics {
  464. if tt, ok := s.radius[topic]; ok {
  465. tt.adjustWithTicket(now, targetHash, ticketRef{t, i})
  466. }
  467. }
  468. }
  469. func (s *ticketStore) addTicket(localTime mclock.AbsTime, pingHash []byte, t *ticket) {
  470. debugLog(fmt.Sprintf("add(node = %x sn = %v)", t.node.ID[:8], t.serial))
  471. lastReq, ok := s.nodeLastReq[t.node]
  472. if !(ok && bytes.Equal(pingHash, lastReq.pingHash)) {
  473. return
  474. }
  475. s.adjustWithTicket(localTime, lastReq.lookup.target, t)
  476. if lastReq.lookup.radiusLookup || s.nodes[t.node] != nil {
  477. return
  478. }
  479. topic := lastReq.lookup.topic
  480. topicIdx := t.findIdx(topic)
  481. if topicIdx == -1 {
  482. return
  483. }
  484. bucket := timeBucket(localTime / mclock.AbsTime(ticketTimeBucketLen))
  485. if s.lastBucketFetched == 0 || bucket < s.lastBucketFetched {
  486. s.lastBucketFetched = bucket
  487. }
  488. if _, ok := s.tickets[topic]; ok {
  489. wait := t.regTime[topicIdx] - localTime
  490. rnd := rand.ExpFloat64()
  491. if rnd > 10 {
  492. rnd = 10
  493. }
  494. if float64(wait) < float64(keepTicketConst)+float64(keepTicketExp)*rnd {
  495. // use the ticket to register this topic
  496. //fmt.Println("addTicket", t.node.ID[:8], t.node.addr().String(), t.serial, t.pong)
  497. s.addTicketRef(ticketRef{t, topicIdx})
  498. }
  499. }
  500. if t.refCnt > 0 {
  501. s.nextTicketCached = nil
  502. s.nodes[t.node] = t
  503. }
  504. }
  505. func (s *ticketStore) getNodeTicket(node *Node) *ticket {
  506. if s.nodes[node] == nil {
  507. debugLog(fmt.Sprintf("getNodeTicket(%x) sn = nil", node.ID[:8]))
  508. } else {
  509. debugLog(fmt.Sprintf("getNodeTicket(%x) sn = %v", node.ID[:8], s.nodes[node].serial))
  510. }
  511. return s.nodes[node]
  512. }
  513. func (s *ticketStore) canQueryTopic(node *Node, topic Topic) bool {
  514. qq := s.queriesSent[node]
  515. if qq != nil {
  516. now := mclock.Now()
  517. for _, sq := range qq {
  518. if sq.lookup.topic == topic && sq.sent > now-mclock.AbsTime(topicQueryResend) {
  519. return false
  520. }
  521. }
  522. }
  523. return true
  524. }
  525. func (s *ticketStore) addTopicQuery(hash common.Hash, node *Node, lookup lookupInfo) {
  526. now := mclock.Now()
  527. qq := s.queriesSent[node]
  528. if qq == nil {
  529. qq = make(map[common.Hash]sentQuery)
  530. s.queriesSent[node] = qq
  531. }
  532. qq[hash] = sentQuery{sent: now, lookup: lookup}
  533. s.cleanupTopicQueries(now)
  534. }
  535. func (s *ticketStore) cleanupTopicQueries(now mclock.AbsTime) {
  536. if s.nextTopicQueryCleanup > now {
  537. return
  538. }
  539. exp := now - mclock.AbsTime(topicQueryResend)
  540. for n, qq := range s.queriesSent {
  541. for h, q := range qq {
  542. if q.sent < exp {
  543. delete(qq, h)
  544. }
  545. }
  546. if len(qq) == 0 {
  547. delete(s.queriesSent, n)
  548. }
  549. }
  550. s.nextTopicQueryCleanup = now + mclock.AbsTime(topicQueryTimeout)
  551. }
  552. func (s *ticketStore) gotTopicNodes(from *Node, hash common.Hash, nodes []rpcNode) (timeout bool) {
  553. now := mclock.Now()
  554. //fmt.Println("got", from.addr().String(), hash, len(nodes))
  555. qq := s.queriesSent[from]
  556. if qq == nil {
  557. return true
  558. }
  559. q, ok := qq[hash]
  560. if !ok || now > q.sent+mclock.AbsTime(topicQueryTimeout) {
  561. return true
  562. }
  563. inside := float64(0)
  564. if len(nodes) > 0 {
  565. inside = 1
  566. }
  567. s.radius[q.lookup.topic].adjust(now, q.lookup.target, from.sha, inside)
  568. chn := s.searchTopicMap[q.lookup.topic].foundChn
  569. if chn == nil {
  570. //fmt.Println("no channel")
  571. return false
  572. }
  573. for _, node := range nodes {
  574. ip := node.IP
  575. if ip.IsUnspecified() || ip.IsLoopback() {
  576. ip = from.IP
  577. }
  578. n := NewNode(node.ID, ip, node.UDP-1, node.TCP-1) // subtract one from port while discv5 is running in test mode on UDPport+1
  579. select {
  580. case chn <- n:
  581. default:
  582. return false
  583. }
  584. }
  585. return false
  586. }
  587. type topicRadius struct {
  588. topic Topic
  589. topicHashPrefix uint64
  590. radius, minRadius uint64
  591. buckets []topicRadiusBucket
  592. converged bool
  593. radiusLookupCnt int
  594. }
  595. type topicRadiusEvent int
  596. const (
  597. trOutside topicRadiusEvent = iota
  598. trInside
  599. trNoAdjust
  600. trCount
  601. )
  602. type topicRadiusBucket struct {
  603. weights [trCount]float64
  604. lastTime mclock.AbsTime
  605. value float64
  606. lookupSent map[common.Hash]mclock.AbsTime
  607. }
  608. func (b *topicRadiusBucket) update(now mclock.AbsTime) {
  609. if now == b.lastTime {
  610. return
  611. }
  612. exp := math.Exp(-float64(now-b.lastTime) / float64(radiusTC))
  613. for i, w := range b.weights {
  614. b.weights[i] = w * exp
  615. }
  616. b.lastTime = now
  617. for target, tm := range b.lookupSent {
  618. if now-tm > mclock.AbsTime(respTimeout) {
  619. b.weights[trNoAdjust] += 1
  620. delete(b.lookupSent, target)
  621. }
  622. }
  623. }
  624. func (b *topicRadiusBucket) adjust(now mclock.AbsTime, inside float64) {
  625. b.update(now)
  626. if inside <= 0 {
  627. b.weights[trOutside] += 1
  628. } else {
  629. if inside >= 1 {
  630. b.weights[trInside] += 1
  631. } else {
  632. b.weights[trInside] += inside
  633. b.weights[trOutside] += 1 - inside
  634. }
  635. }
  636. }
  637. func newTopicRadius(t Topic) *topicRadius {
  638. topicHash := crypto.Keccak256Hash([]byte(t))
  639. topicHashPrefix := binary.BigEndian.Uint64(topicHash[0:8])
  640. return &topicRadius{
  641. topic: t,
  642. topicHashPrefix: topicHashPrefix,
  643. radius: maxRadius,
  644. minRadius: maxRadius,
  645. }
  646. }
  647. func (r *topicRadius) getBucketIdx(addrHash common.Hash) int {
  648. prefix := binary.BigEndian.Uint64(addrHash[0:8])
  649. var log2 float64
  650. if prefix != r.topicHashPrefix {
  651. log2 = math.Log2(float64(prefix ^ r.topicHashPrefix))
  652. }
  653. bucket := int((64 - log2) * radiusBucketsPerBit)
  654. max := 64*radiusBucketsPerBit - 1
  655. if bucket > max {
  656. return max
  657. }
  658. if bucket < 0 {
  659. return 0
  660. }
  661. return bucket
  662. }
  663. func (r *topicRadius) targetForBucket(bucket int) common.Hash {
  664. min := math.Pow(2, 64-float64(bucket+1)/radiusBucketsPerBit)
  665. max := math.Pow(2, 64-float64(bucket)/radiusBucketsPerBit)
  666. a := uint64(min)
  667. b := randUint64n(uint64(max - min))
  668. xor := a + b
  669. if xor < a {
  670. xor = ^uint64(0)
  671. }
  672. prefix := r.topicHashPrefix ^ xor
  673. var target common.Hash
  674. binary.BigEndian.PutUint64(target[0:8], prefix)
  675. globalRandRead(target[8:])
  676. return target
  677. }
  678. // package rand provides a Read function in Go 1.6 and later, but
  679. // we can't use it yet because we still support Go 1.5.
  680. func globalRandRead(b []byte) {
  681. pos := 0
  682. val := 0
  683. for n := 0; n < len(b); n++ {
  684. if pos == 0 {
  685. val = rand.Int()
  686. pos = 7
  687. }
  688. b[n] = byte(val)
  689. val >>= 8
  690. pos--
  691. }
  692. }
  693. func (r *topicRadius) isInRadius(addrHash common.Hash) bool {
  694. nodePrefix := binary.BigEndian.Uint64(addrHash[0:8])
  695. dist := nodePrefix ^ r.topicHashPrefix
  696. return dist < r.radius
  697. }
  698. func (r *topicRadius) chooseLookupBucket(a, b int) int {
  699. if a < 0 {
  700. a = 0
  701. }
  702. if a > b {
  703. return -1
  704. }
  705. c := 0
  706. for i := a; i <= b; i++ {
  707. if i >= len(r.buckets) || r.buckets[i].weights[trNoAdjust] < maxNoAdjust {
  708. c++
  709. }
  710. }
  711. if c == 0 {
  712. return -1
  713. }
  714. rnd := randUint(uint32(c))
  715. for i := a; i <= b; i++ {
  716. if i >= len(r.buckets) || r.buckets[i].weights[trNoAdjust] < maxNoAdjust {
  717. if rnd == 0 {
  718. return i
  719. }
  720. rnd--
  721. }
  722. }
  723. panic(nil) // should never happen
  724. }
  725. func (r *topicRadius) needMoreLookups(a, b int, maxValue float64) bool {
  726. var max float64
  727. if a < 0 {
  728. a = 0
  729. }
  730. if b >= len(r.buckets) {
  731. b = len(r.buckets) - 1
  732. if r.buckets[b].value > max {
  733. max = r.buckets[b].value
  734. }
  735. }
  736. if b >= a {
  737. for i := a; i <= b; i++ {
  738. if r.buckets[i].value > max {
  739. max = r.buckets[i].value
  740. }
  741. }
  742. }
  743. return maxValue-max < minPeakSize
  744. }
  745. func (r *topicRadius) recalcRadius() (radius uint64, radiusLookup int) {
  746. maxBucket := 0
  747. maxValue := float64(0)
  748. now := mclock.Now()
  749. v := float64(0)
  750. for i := range r.buckets {
  751. r.buckets[i].update(now)
  752. v += r.buckets[i].weights[trOutside] - r.buckets[i].weights[trInside]
  753. r.buckets[i].value = v
  754. //fmt.Printf("%v %v | ", v, r.buckets[i].weights[trNoAdjust])
  755. }
  756. //fmt.Println()
  757. slopeCross := -1
  758. for i, b := range r.buckets {
  759. v := b.value
  760. if v < float64(i)*minSlope {
  761. slopeCross = i
  762. break
  763. }
  764. if v > maxValue {
  765. maxValue = v
  766. maxBucket = i + 1
  767. }
  768. }
  769. minRadBucket := len(r.buckets)
  770. sum := float64(0)
  771. for minRadBucket > 0 && sum < minRightSum {
  772. minRadBucket--
  773. b := r.buckets[minRadBucket]
  774. sum += b.weights[trInside] + b.weights[trOutside]
  775. }
  776. r.minRadius = uint64(math.Pow(2, 64-float64(minRadBucket)/radiusBucketsPerBit))
  777. lookupLeft := -1
  778. if r.needMoreLookups(0, maxBucket-lookupWidth-1, maxValue) {
  779. lookupLeft = r.chooseLookupBucket(maxBucket-lookupWidth, maxBucket-1)
  780. }
  781. lookupRight := -1
  782. if slopeCross != maxBucket && (minRadBucket <= maxBucket || r.needMoreLookups(maxBucket+lookupWidth, len(r.buckets)-1, maxValue)) {
  783. for len(r.buckets) <= maxBucket+lookupWidth {
  784. r.buckets = append(r.buckets, topicRadiusBucket{lookupSent: make(map[common.Hash]mclock.AbsTime)})
  785. }
  786. lookupRight = r.chooseLookupBucket(maxBucket, maxBucket+lookupWidth-1)
  787. }
  788. if lookupLeft == -1 {
  789. radiusLookup = lookupRight
  790. } else {
  791. if lookupRight == -1 {
  792. radiusLookup = lookupLeft
  793. } else {
  794. if randUint(2) == 0 {
  795. radiusLookup = lookupLeft
  796. } else {
  797. radiusLookup = lookupRight
  798. }
  799. }
  800. }
  801. //fmt.Println("mb", maxBucket, "sc", slopeCross, "mrb", minRadBucket, "ll", lookupLeft, "lr", lookupRight, "mv", maxValue)
  802. if radiusLookup == -1 {
  803. // no more radius lookups needed at the moment, return a radius
  804. r.converged = true
  805. rad := maxBucket
  806. if minRadBucket < rad {
  807. rad = minRadBucket
  808. }
  809. radius = ^uint64(0)
  810. if rad > 0 {
  811. radius = uint64(math.Pow(2, 64-float64(rad)/radiusBucketsPerBit))
  812. }
  813. r.radius = radius
  814. }
  815. return
  816. }
  817. func (r *topicRadius) nextTarget(forceRegular bool) lookupInfo {
  818. if !forceRegular {
  819. _, radiusLookup := r.recalcRadius()
  820. if radiusLookup != -1 {
  821. target := r.targetForBucket(radiusLookup)
  822. r.buckets[radiusLookup].lookupSent[target] = mclock.Now()
  823. return lookupInfo{target: target, topic: r.topic, radiusLookup: true}
  824. }
  825. }
  826. radExt := r.radius / 2
  827. if radExt > maxRadius-r.radius {
  828. radExt = maxRadius - r.radius
  829. }
  830. rnd := randUint64n(r.radius) + randUint64n(2*radExt)
  831. if rnd > radExt {
  832. rnd -= radExt
  833. } else {
  834. rnd = radExt - rnd
  835. }
  836. prefix := r.topicHashPrefix ^ rnd
  837. var target common.Hash
  838. binary.BigEndian.PutUint64(target[0:8], prefix)
  839. globalRandRead(target[8:])
  840. return lookupInfo{target: target, topic: r.topic, radiusLookup: false}
  841. }
  842. func (r *topicRadius) adjustWithTicket(now mclock.AbsTime, targetHash common.Hash, t ticketRef) {
  843. wait := t.t.regTime[t.idx] - t.t.issueTime
  844. inside := float64(wait)/float64(targetWaitTime) - 0.5
  845. if inside > 1 {
  846. inside = 1
  847. }
  848. if inside < 0 {
  849. inside = 0
  850. }
  851. r.adjust(now, targetHash, t.t.node.sha, inside)
  852. }
  853. func (r *topicRadius) adjust(now mclock.AbsTime, targetHash, addrHash common.Hash, inside float64) {
  854. bucket := r.getBucketIdx(addrHash)
  855. //fmt.Println("adjust", bucket, len(r.buckets), inside)
  856. if bucket >= len(r.buckets) {
  857. return
  858. }
  859. r.buckets[bucket].adjust(now, inside)
  860. delete(r.buckets[bucket].lookupSent, targetHash)
  861. }