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.

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