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.

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