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.

824 lines
20 KiB

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