You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

815 lines
20 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. // Modified for Tendermint
  2. // Originally Copyright (c) 2013-2014 Conformal Systems LLC.
  3. // https://github.com/conformal/btcd/blob/master/LICENSE
  4. package p2p
  5. import (
  6. "encoding/binary"
  7. "encoding/json"
  8. "math"
  9. "math/rand"
  10. "net"
  11. "os"
  12. "sync"
  13. "time"
  14. . "github.com/tendermint/go-common"
  15. "github.com/tendermint/go-crypto"
  16. )
  17. const (
  18. // addresses under which the address manager will claim to need more addresses.
  19. needAddressThreshold = 1000
  20. // interval used to dump the address cache to disk for future use.
  21. dumpAddressInterval = time.Minute * 2
  22. // max addresses in each old address bucket.
  23. oldBucketSize = 64
  24. // buckets we split old addresses over.
  25. oldBucketCount = 64
  26. // max addresses in each new address bucket.
  27. newBucketSize = 64
  28. // buckets that we spread new addresses over.
  29. newBucketCount = 256
  30. // old buckets over which an address group will be spread.
  31. oldBucketsPerGroup = 4
  32. // new buckets over which an source address group will be spread.
  33. newBucketsPerGroup = 32
  34. // buckets a frequently seen new address may end up in.
  35. maxNewBucketsPerAddress = 4
  36. // days before which we assume an address has vanished
  37. // if we have not seen it announced in that long.
  38. numMissingDays = 30
  39. // tries without a single success before we assume an address is bad.
  40. numRetries = 3
  41. // max failures we will accept without a success before considering an address bad.
  42. maxFailures = 10
  43. // days since the last success before we will consider evicting an address.
  44. minBadDays = 7
  45. // % of total addresses known returned by GetSelection.
  46. getSelectionPercent = 23
  47. // min addresses that must be returned by GetSelection. Useful for bootstrapping.
  48. minGetSelection = 32
  49. // max addresses returned by GetSelection
  50. // NOTE: this must match "maxPexMessageSize"
  51. maxGetSelection = 250
  52. // current version of the on-disk format.
  53. serializationVersion = 1
  54. )
  55. /* AddrBook - concurrency safe peer address manager */
  56. type AddrBook struct {
  57. QuitService
  58. mtx sync.Mutex
  59. filePath string
  60. rand *rand.Rand
  61. key string
  62. ourAddrs map[string]*NetAddress
  63. addrLookup map[string]*knownAddress // new & old
  64. addrNew []map[string]*knownAddress
  65. addrOld []map[string]*knownAddress
  66. wg sync.WaitGroup
  67. nOld int
  68. nNew int
  69. }
  70. const (
  71. bucketTypeNew = 0x01
  72. bucketTypeOld = 0x02
  73. )
  74. // Use Start to begin processing asynchronous address updates.
  75. func NewAddrBook(filePath string) *AddrBook {
  76. am := &AddrBook{
  77. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  78. ourAddrs: make(map[string]*NetAddress),
  79. addrLookup: make(map[string]*knownAddress),
  80. filePath: filePath,
  81. }
  82. am.init()
  83. am.QuitService = *NewQuitService(log, "AddrBook", am)
  84. return am
  85. }
  86. // When modifying this, don't forget to update loadFromFile()
  87. func (a *AddrBook) init() {
  88. a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits
  89. // New addr buckets
  90. a.addrNew = make([]map[string]*knownAddress, newBucketCount)
  91. for i := range a.addrNew {
  92. a.addrNew[i] = make(map[string]*knownAddress)
  93. }
  94. // Old addr buckets
  95. a.addrOld = make([]map[string]*knownAddress, oldBucketCount)
  96. for i := range a.addrOld {
  97. a.addrOld[i] = make(map[string]*knownAddress)
  98. }
  99. }
  100. func (a *AddrBook) OnStart() error {
  101. a.QuitService.OnStart()
  102. a.loadFromFile(a.filePath)
  103. a.wg.Add(1)
  104. go a.saveRoutine()
  105. return nil
  106. }
  107. func (a *AddrBook) OnStop() {
  108. a.QuitService.OnStop()
  109. a.wg.Wait()
  110. }
  111. func (a *AddrBook) AddOurAddress(addr *NetAddress) {
  112. a.mtx.Lock()
  113. defer a.mtx.Unlock()
  114. log.Info("Add our address to book", "addr", addr)
  115. a.ourAddrs[addr.String()] = addr
  116. }
  117. func (a *AddrBook) OurAddresses() []*NetAddress {
  118. addrs := []*NetAddress{}
  119. for _, addr := range a.ourAddrs {
  120. addrs = append(addrs, addr)
  121. }
  122. return addrs
  123. }
  124. func (a *AddrBook) AddAddress(addr *NetAddress, src *NetAddress) {
  125. a.mtx.Lock()
  126. defer a.mtx.Unlock()
  127. log.Info("Add address to book", "addr", addr, "src", src)
  128. a.addAddress(addr, src)
  129. }
  130. func (a *AddrBook) NeedMoreAddrs() bool {
  131. return a.Size() < needAddressThreshold
  132. }
  133. func (a *AddrBook) Size() int {
  134. a.mtx.Lock()
  135. defer a.mtx.Unlock()
  136. return a.size()
  137. }
  138. func (a *AddrBook) size() int {
  139. return a.nNew + a.nOld
  140. }
  141. // Pick an address to connect to with new/old bias.
  142. func (a *AddrBook) PickAddress(newBias int) *NetAddress {
  143. a.mtx.Lock()
  144. defer a.mtx.Unlock()
  145. if a.size() == 0 {
  146. return nil
  147. }
  148. if newBias > 100 {
  149. newBias = 100
  150. }
  151. if newBias < 0 {
  152. newBias = 0
  153. }
  154. // Bias between new and old addresses.
  155. oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(newBias))
  156. newCorrelation := math.Sqrt(float64(a.nNew)) * float64(newBias)
  157. if (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation {
  158. // pick random Old bucket.
  159. var bucket map[string]*knownAddress = nil
  160. for len(bucket) == 0 {
  161. bucket = a.addrOld[a.rand.Intn(len(a.addrOld))]
  162. }
  163. // pick a random ka from bucket.
  164. randIndex := a.rand.Intn(len(bucket))
  165. for _, ka := range bucket {
  166. if randIndex == 0 {
  167. return ka.Addr
  168. }
  169. randIndex--
  170. }
  171. PanicSanity("Should not happen")
  172. } else {
  173. // pick random New bucket.
  174. var bucket map[string]*knownAddress = nil
  175. for len(bucket) == 0 {
  176. bucket = a.addrNew[a.rand.Intn(len(a.addrNew))]
  177. }
  178. // pick a random ka from bucket.
  179. randIndex := a.rand.Intn(len(bucket))
  180. for _, ka := range bucket {
  181. if randIndex == 0 {
  182. return ka.Addr
  183. }
  184. randIndex--
  185. }
  186. PanicSanity("Should not happen")
  187. }
  188. return nil
  189. }
  190. func (a *AddrBook) MarkGood(addr *NetAddress) {
  191. a.mtx.Lock()
  192. defer a.mtx.Unlock()
  193. ka := a.addrLookup[addr.String()]
  194. if ka == nil {
  195. return
  196. }
  197. ka.markGood()
  198. if ka.isNew() {
  199. a.moveToOld(ka)
  200. }
  201. }
  202. func (a *AddrBook) MarkAttempt(addr *NetAddress) {
  203. a.mtx.Lock()
  204. defer a.mtx.Unlock()
  205. ka := a.addrLookup[addr.String()]
  206. if ka == nil {
  207. return
  208. }
  209. ka.markAttempt()
  210. }
  211. func (a *AddrBook) MarkBad(addr *NetAddress) {
  212. a.mtx.Lock()
  213. defer a.mtx.Unlock()
  214. ka := a.addrLookup[addr.String()]
  215. if ka == nil {
  216. return
  217. }
  218. // We currently just eject the address.
  219. // In the future, consider blacklisting.
  220. a.removeFromAllBuckets(ka)
  221. }
  222. /* Peer exchange */
  223. // GetSelection randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
  224. func (a *AddrBook) GetSelection() []*NetAddress {
  225. a.mtx.Lock()
  226. defer a.mtx.Unlock()
  227. if a.size() == 0 {
  228. return nil
  229. }
  230. allAddr := make([]*NetAddress, a.size())
  231. i := 0
  232. for _, v := range a.addrLookup {
  233. allAddr[i] = v.Addr
  234. i++
  235. }
  236. numAddresses := MaxInt(
  237. MinInt(minGetSelection, len(allAddr)),
  238. len(allAddr)*getSelectionPercent/100)
  239. numAddresses = MinInt(maxGetSelection, numAddresses)
  240. // Fisher-Yates shuffle the array. We only need to do the first
  241. // `numAddresses' since we are throwing the rest.
  242. for i := 0; i < numAddresses; i++ {
  243. // pick a number between current index and the end
  244. j := rand.Intn(len(allAddr)-i) + i
  245. allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
  246. }
  247. // slice off the limit we are willing to share.
  248. return allAddr[:numAddresses]
  249. }
  250. /* Loading & Saving */
  251. type addrBookJSON struct {
  252. Key string
  253. Addrs []*knownAddress
  254. }
  255. func (a *AddrBook) saveToFile(filePath string) {
  256. // Compile Addrs
  257. addrs := []*knownAddress{}
  258. for _, ka := range a.addrLookup {
  259. addrs = append(addrs, ka)
  260. }
  261. aJSON := &addrBookJSON{
  262. Key: a.key,
  263. Addrs: addrs,
  264. }
  265. jsonBytes, err := json.MarshalIndent(aJSON, "", "\t")
  266. if err != nil {
  267. log.Error("Failed to save AddrBook to file", "err", err)
  268. return
  269. }
  270. err = WriteFileAtomic(filePath, jsonBytes, 0644)
  271. if err != nil {
  272. log.Error("Failed to save AddrBook to file", "file", filePath, "error", err)
  273. }
  274. }
  275. // Returns false if file does not exist.
  276. // Panics if file is corrupt.
  277. func (a *AddrBook) loadFromFile(filePath string) bool {
  278. // If doesn't exist, do nothing.
  279. _, err := os.Stat(filePath)
  280. if os.IsNotExist(err) {
  281. return false
  282. }
  283. // Load addrBookJSON{}
  284. r, err := os.Open(filePath)
  285. if err != nil {
  286. PanicCrisis(Fmt("Error opening file %s: %v", filePath, err))
  287. }
  288. defer r.Close()
  289. aJSON := &addrBookJSON{}
  290. dec := json.NewDecoder(r)
  291. err = dec.Decode(aJSON)
  292. if err != nil {
  293. PanicCrisis(Fmt("Error reading file %s: %v", filePath, err))
  294. }
  295. // Restore all the fields...
  296. // Restore the key
  297. a.key = aJSON.Key
  298. // Restore .addrNew & .addrOld
  299. for _, ka := range aJSON.Addrs {
  300. for _, bucketIndex := range ka.Buckets {
  301. bucket := a.getBucket(ka.BucketType, bucketIndex)
  302. bucket[ka.Addr.String()] = ka
  303. }
  304. a.addrLookup[ka.Addr.String()] = ka
  305. if ka.BucketType == bucketTypeNew {
  306. a.nNew++
  307. } else {
  308. a.nOld++
  309. }
  310. }
  311. return true
  312. }
  313. /* Private methods */
  314. func (a *AddrBook) saveRoutine() {
  315. dumpAddressTicker := time.NewTicker(dumpAddressInterval)
  316. out:
  317. for {
  318. select {
  319. case <-dumpAddressTicker.C:
  320. log.Info("Saving AddrBook to file", "size", a.Size())
  321. a.saveToFile(a.filePath)
  322. case <-a.Quit:
  323. break out
  324. }
  325. }
  326. dumpAddressTicker.Stop()
  327. a.saveToFile(a.filePath)
  328. a.wg.Done()
  329. log.Notice("Address handler done")
  330. }
  331. func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress {
  332. switch bucketType {
  333. case bucketTypeNew:
  334. return a.addrNew[bucketIdx]
  335. case bucketTypeOld:
  336. return a.addrOld[bucketIdx]
  337. default:
  338. PanicSanity("Should not happen")
  339. return nil
  340. }
  341. }
  342. // Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full.
  343. // NOTE: currently it always returns true.
  344. func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool {
  345. // Sanity check
  346. if ka.isOld() {
  347. log.Warn(Fmt("Cannot add address already in old bucket to a new bucket: %v", ka))
  348. return false
  349. }
  350. addrStr := ka.Addr.String()
  351. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  352. // Already exists?
  353. if _, ok := bucket[addrStr]; ok {
  354. return true
  355. }
  356. // Enforce max addresses.
  357. if len(bucket) > newBucketSize {
  358. log.Notice("new bucket is full, expiring old ")
  359. a.expireNew(bucketIdx)
  360. }
  361. // Add to bucket.
  362. bucket[addrStr] = ka
  363. if ka.addBucketRef(bucketIdx) == 1 {
  364. a.nNew++
  365. }
  366. // Ensure in addrLookup
  367. a.addrLookup[addrStr] = ka
  368. return true
  369. }
  370. // Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full.
  371. func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool {
  372. // Sanity check
  373. if ka.isNew() {
  374. log.Warn(Fmt("Cannot add new address to old bucket: %v", ka))
  375. return false
  376. }
  377. if len(ka.Buckets) != 0 {
  378. log.Warn(Fmt("Cannot add already old address to another old bucket: %v", ka))
  379. return false
  380. }
  381. addrStr := ka.Addr.String()
  382. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  383. // Already exists?
  384. if _, ok := bucket[addrStr]; ok {
  385. return true
  386. }
  387. // Enforce max addresses.
  388. if len(bucket) > oldBucketSize {
  389. return false
  390. }
  391. // Add to bucket.
  392. bucket[addrStr] = ka
  393. if ka.addBucketRef(bucketIdx) == 1 {
  394. a.nOld++
  395. }
  396. // Ensure in addrLookup
  397. a.addrLookup[addrStr] = ka
  398. return true
  399. }
  400. func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) {
  401. if ka.BucketType != bucketType {
  402. log.Warn(Fmt("Bucket type mismatch: %v", ka))
  403. return
  404. }
  405. bucket := a.getBucket(bucketType, bucketIdx)
  406. delete(bucket, ka.Addr.String())
  407. if ka.removeBucketRef(bucketIdx) == 0 {
  408. if bucketType == bucketTypeNew {
  409. a.nNew--
  410. } else {
  411. a.nOld--
  412. }
  413. delete(a.addrLookup, ka.Addr.String())
  414. }
  415. }
  416. func (a *AddrBook) removeFromAllBuckets(ka *knownAddress) {
  417. for _, bucketIdx := range ka.Buckets {
  418. bucket := a.getBucket(ka.BucketType, bucketIdx)
  419. delete(bucket, ka.Addr.String())
  420. }
  421. ka.Buckets = nil
  422. if ka.BucketType == bucketTypeNew {
  423. a.nNew--
  424. } else {
  425. a.nOld--
  426. }
  427. delete(a.addrLookup, ka.Addr.String())
  428. }
  429. func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress {
  430. bucket := a.getBucket(bucketType, bucketIdx)
  431. var oldest *knownAddress
  432. for _, ka := range bucket {
  433. if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) {
  434. oldest = ka
  435. }
  436. }
  437. return oldest
  438. }
  439. func (a *AddrBook) addAddress(addr, src *NetAddress) {
  440. if !addr.Routable() {
  441. log.Warn(Fmt("Cannot add non-routable address %v", addr))
  442. return
  443. }
  444. if _, ok := a.ourAddrs[addr.String()]; ok {
  445. // Ignore our own listener address.
  446. return
  447. }
  448. ka := a.addrLookup[addr.String()]
  449. if ka != nil {
  450. // Already old.
  451. if ka.isOld() {
  452. return
  453. }
  454. // Already in max new buckets.
  455. if len(ka.Buckets) == maxNewBucketsPerAddress {
  456. return
  457. }
  458. // The more entries we have, the less likely we are to add more.
  459. factor := int32(2 * len(ka.Buckets))
  460. if a.rand.Int31n(factor) != 0 {
  461. return
  462. }
  463. } else {
  464. ka = newKnownAddress(addr, src)
  465. }
  466. bucket := a.calcNewBucket(addr, src)
  467. a.addToNewBucket(ka, bucket)
  468. log.Notice("Added new address", "address", addr, "total", a.size())
  469. }
  470. // Make space in the new buckets by expiring the really bad entries.
  471. // If no bad entries are available we remove the oldest.
  472. func (a *AddrBook) expireNew(bucketIdx int) {
  473. for addrStr, ka := range a.addrNew[bucketIdx] {
  474. // If an entry is bad, throw it away
  475. if ka.isBad() {
  476. log.Notice(Fmt("expiring bad address %v", addrStr))
  477. a.removeFromBucket(ka, bucketTypeNew, bucketIdx)
  478. return
  479. }
  480. }
  481. // If we haven't thrown out a bad entry, throw out the oldest entry
  482. oldest := a.pickOldest(bucketTypeNew, bucketIdx)
  483. a.removeFromBucket(oldest, bucketTypeNew, bucketIdx)
  484. }
  485. // Promotes an address from new to old.
  486. // TODO: Move to old probabilistically.
  487. // The better a node is, the less likely it should be evicted from an old bucket.
  488. func (a *AddrBook) moveToOld(ka *knownAddress) {
  489. // Sanity check
  490. if ka.isOld() {
  491. log.Warn(Fmt("Cannot promote address that is already old %v", ka))
  492. return
  493. }
  494. if len(ka.Buckets) == 0 {
  495. log.Warn(Fmt("Cannot promote address that isn't in any new buckets %v", ka))
  496. return
  497. }
  498. // Remember one of the buckets in which ka is in.
  499. freedBucket := ka.Buckets[0]
  500. // Remove from all (new) buckets.
  501. a.removeFromAllBuckets(ka)
  502. // It's officially old now.
  503. ka.BucketType = bucketTypeOld
  504. // Try to add it to its oldBucket destination.
  505. oldBucketIdx := a.calcOldBucket(ka.Addr)
  506. added := a.addToOldBucket(ka, oldBucketIdx)
  507. if !added {
  508. // No room, must evict something
  509. oldest := a.pickOldest(bucketTypeOld, oldBucketIdx)
  510. a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx)
  511. // Find new bucket to put oldest in
  512. newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src)
  513. added := a.addToNewBucket(oldest, newBucketIdx)
  514. // No space in newBucket either, just put it in freedBucket from above.
  515. if !added {
  516. added := a.addToNewBucket(oldest, freedBucket)
  517. if !added {
  518. log.Warn(Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket))
  519. }
  520. }
  521. // Finally, add to bucket again.
  522. added = a.addToOldBucket(ka, oldBucketIdx)
  523. if !added {
  524. log.Warn(Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx))
  525. }
  526. }
  527. }
  528. // doublesha256( key + sourcegroup +
  529. // int64(doublesha256(key + group + sourcegroup))%bucket_per_group ) % num_new_buckets
  530. func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int {
  531. data1 := []byte{}
  532. data1 = append(data1, []byte(a.key)...)
  533. data1 = append(data1, []byte(groupKey(addr))...)
  534. data1 = append(data1, []byte(groupKey(src))...)
  535. hash1 := doubleSha256(data1)
  536. hash64 := binary.BigEndian.Uint64(hash1)
  537. hash64 %= newBucketsPerGroup
  538. var hashbuf [8]byte
  539. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  540. data2 := []byte{}
  541. data2 = append(data2, []byte(a.key)...)
  542. data2 = append(data2, groupKey(src)...)
  543. data2 = append(data2, hashbuf[:]...)
  544. hash2 := doubleSha256(data2)
  545. return int(binary.BigEndian.Uint64(hash2) % newBucketCount)
  546. }
  547. // doublesha256( key + group +
  548. // int64(doublesha256(key + addr))%buckets_per_group ) % num_old_buckets
  549. func (a *AddrBook) calcOldBucket(addr *NetAddress) int {
  550. data1 := []byte{}
  551. data1 = append(data1, []byte(a.key)...)
  552. data1 = append(data1, []byte(addr.String())...)
  553. hash1 := doubleSha256(data1)
  554. hash64 := binary.BigEndian.Uint64(hash1)
  555. hash64 %= oldBucketsPerGroup
  556. var hashbuf [8]byte
  557. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  558. data2 := []byte{}
  559. data2 = append(data2, []byte(a.key)...)
  560. data2 = append(data2, groupKey(addr)...)
  561. data2 = append(data2, hashbuf[:]...)
  562. hash2 := doubleSha256(data2)
  563. return int(binary.BigEndian.Uint64(hash2) % oldBucketCount)
  564. }
  565. // Return a string representing the network group of this address.
  566. // This is the /16 for IPv6, the /32 (/36 for he.net) for IPv6, the string
  567. // "local" for a local address and the string "unroutable for an unroutable
  568. // address.
  569. func groupKey(na *NetAddress) string {
  570. if na.Local() {
  571. return "local"
  572. }
  573. if !na.Routable() {
  574. return "unroutable"
  575. }
  576. if ipv4 := na.IP.To4(); ipv4 != nil {
  577. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String()
  578. }
  579. if na.RFC6145() || na.RFC6052() {
  580. // last four bytes are the ip address
  581. ip := net.IP(na.IP[12:16])
  582. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  583. }
  584. if na.RFC3964() {
  585. ip := net.IP(na.IP[2:7])
  586. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  587. }
  588. if na.RFC4380() {
  589. // teredo tunnels have the last 4 bytes as the v4 address XOR
  590. // 0xff.
  591. ip := net.IP(make([]byte, 4))
  592. for i, byte := range na.IP[12:16] {
  593. ip[i] = byte ^ 0xff
  594. }
  595. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  596. }
  597. // OK, so now we know ourselves to be a IPv6 address.
  598. // bitcoind uses /32 for everything, except for Hurricane Electric's
  599. // (he.net) IP range, which it uses /36 for.
  600. bits := 32
  601. heNet := &net.IPNet{IP: net.ParseIP("2001:470::"),
  602. Mask: net.CIDRMask(32, 128)}
  603. if heNet.Contains(na.IP) {
  604. bits = 36
  605. }
  606. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String()
  607. }
  608. //-----------------------------------------------------------------------------
  609. /*
  610. knownAddress
  611. tracks information about a known network address that is used
  612. to determine how viable an address is.
  613. */
  614. type knownAddress struct {
  615. Addr *NetAddress
  616. Src *NetAddress
  617. Attempts int32
  618. LastAttempt time.Time
  619. LastSuccess time.Time
  620. BucketType byte
  621. Buckets []int
  622. }
  623. func newKnownAddress(addr *NetAddress, src *NetAddress) *knownAddress {
  624. return &knownAddress{
  625. Addr: addr,
  626. Src: src,
  627. Attempts: 0,
  628. LastAttempt: time.Now(),
  629. BucketType: bucketTypeNew,
  630. Buckets: nil,
  631. }
  632. }
  633. func (ka *knownAddress) isOld() bool {
  634. return ka.BucketType == bucketTypeOld
  635. }
  636. func (ka *knownAddress) isNew() bool {
  637. return ka.BucketType == bucketTypeNew
  638. }
  639. func (ka *knownAddress) markAttempt() {
  640. now := time.Now()
  641. ka.LastAttempt = now
  642. ka.Attempts += 1
  643. }
  644. func (ka *knownAddress) markGood() {
  645. now := time.Now()
  646. ka.LastAttempt = now
  647. ka.Attempts = 0
  648. ka.LastSuccess = now
  649. }
  650. func (ka *knownAddress) addBucketRef(bucketIdx int) int {
  651. for _, bucket := range ka.Buckets {
  652. if bucket == bucketIdx {
  653. log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka))
  654. return -1
  655. }
  656. }
  657. ka.Buckets = append(ka.Buckets, bucketIdx)
  658. return len(ka.Buckets)
  659. }
  660. func (ka *knownAddress) removeBucketRef(bucketIdx int) int {
  661. buckets := []int{}
  662. for _, bucket := range ka.Buckets {
  663. if bucket != bucketIdx {
  664. buckets = append(buckets, bucket)
  665. }
  666. }
  667. if len(buckets) != len(ka.Buckets)-1 {
  668. log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka))
  669. return -1
  670. }
  671. ka.Buckets = buckets
  672. return len(ka.Buckets)
  673. }
  674. /*
  675. An address is bad if the address in question has not been tried in the last
  676. minute and meets one of the following criteria:
  677. 1) It claims to be from the future
  678. 2) It hasn't been seen in over a month
  679. 3) It has failed at least three times and never succeeded
  680. 4) It has failed ten times in the last week
  681. All addresses that meet these criteria are assumed to be worthless and not
  682. worth keeping hold of.
  683. */
  684. func (ka *knownAddress) isBad() bool {
  685. // Has been attempted in the last minute --> good
  686. if ka.LastAttempt.Before(time.Now().Add(-1 * time.Minute)) {
  687. return false
  688. }
  689. // Over a month old?
  690. if ka.LastAttempt.After(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) {
  691. return true
  692. }
  693. // Never succeeded?
  694. if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries {
  695. return true
  696. }
  697. // Hasn't succeeded in too long?
  698. if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) &&
  699. ka.Attempts >= maxFailures {
  700. return true
  701. }
  702. return false
  703. }