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.

817 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
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. /* Private methods */
  316. func (a *AddrBook) saveRoutine() {
  317. dumpAddressTicker := time.NewTicker(dumpAddressInterval)
  318. out:
  319. for {
  320. select {
  321. case <-dumpAddressTicker.C:
  322. log.Info("Saving AddrBook to file", "size", a.Size())
  323. a.saveToFile(a.filePath)
  324. case <-a.Quit:
  325. break out
  326. }
  327. }
  328. dumpAddressTicker.Stop()
  329. a.saveToFile(a.filePath)
  330. a.wg.Done()
  331. log.Notice("Address handler done")
  332. }
  333. func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress {
  334. switch bucketType {
  335. case bucketTypeNew:
  336. return a.addrNew[bucketIdx]
  337. case bucketTypeOld:
  338. return a.addrOld[bucketIdx]
  339. default:
  340. PanicSanity("Should not happen")
  341. return nil
  342. }
  343. }
  344. // Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full.
  345. // NOTE: currently it always returns true.
  346. func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool {
  347. // Sanity check
  348. if ka.isOld() {
  349. log.Warn(Fmt("Cannot add address already in old bucket to a new bucket: %v", ka))
  350. return false
  351. }
  352. addrStr := ka.Addr.String()
  353. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  354. // Already exists?
  355. if _, ok := bucket[addrStr]; ok {
  356. return true
  357. }
  358. // Enforce max addresses.
  359. if len(bucket) > newBucketSize {
  360. log.Notice("new bucket is full, expiring old ")
  361. a.expireNew(bucketIdx)
  362. }
  363. // Add to bucket.
  364. bucket[addrStr] = ka
  365. if ka.addBucketRef(bucketIdx) == 1 {
  366. a.nNew++
  367. }
  368. // Ensure in addrLookup
  369. a.addrLookup[addrStr] = ka
  370. return true
  371. }
  372. // Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full.
  373. func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool {
  374. // Sanity check
  375. if ka.isNew() {
  376. log.Warn(Fmt("Cannot add new address to old bucket: %v", ka))
  377. return false
  378. }
  379. if len(ka.Buckets) != 0 {
  380. log.Warn(Fmt("Cannot add already old address to another old bucket: %v", ka))
  381. return false
  382. }
  383. addrStr := ka.Addr.String()
  384. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  385. // Already exists?
  386. if _, ok := bucket[addrStr]; ok {
  387. return true
  388. }
  389. // Enforce max addresses.
  390. if len(bucket) > oldBucketSize {
  391. return false
  392. }
  393. // Add to bucket.
  394. bucket[addrStr] = ka
  395. if ka.addBucketRef(bucketIdx) == 1 {
  396. a.nOld++
  397. }
  398. // Ensure in addrLookup
  399. a.addrLookup[addrStr] = ka
  400. return true
  401. }
  402. func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) {
  403. if ka.BucketType != bucketType {
  404. log.Warn(Fmt("Bucket type mismatch: %v", ka))
  405. return
  406. }
  407. bucket := a.getBucket(bucketType, bucketIdx)
  408. delete(bucket, ka.Addr.String())
  409. if ka.removeBucketRef(bucketIdx) == 0 {
  410. if bucketType == bucketTypeNew {
  411. a.nNew--
  412. } else {
  413. a.nOld--
  414. }
  415. delete(a.addrLookup, ka.Addr.String())
  416. }
  417. }
  418. func (a *AddrBook) removeFromAllBuckets(ka *knownAddress) {
  419. for _, bucketIdx := range ka.Buckets {
  420. bucket := a.getBucket(ka.BucketType, bucketIdx)
  421. delete(bucket, ka.Addr.String())
  422. }
  423. ka.Buckets = nil
  424. if ka.BucketType == bucketTypeNew {
  425. a.nNew--
  426. } else {
  427. a.nOld--
  428. }
  429. delete(a.addrLookup, ka.Addr.String())
  430. }
  431. func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress {
  432. bucket := a.getBucket(bucketType, bucketIdx)
  433. var oldest *knownAddress
  434. for _, ka := range bucket {
  435. if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) {
  436. oldest = ka
  437. }
  438. }
  439. return oldest
  440. }
  441. func (a *AddrBook) addAddress(addr, src *NetAddress) {
  442. if a.routabilityStrict && !addr.Routable() {
  443. log.Warn(Fmt("Cannot add non-routable address %v", addr))
  444. return
  445. }
  446. if _, ok := a.ourAddrs[addr.String()]; ok {
  447. // Ignore our own listener address.
  448. return
  449. }
  450. ka := a.addrLookup[addr.String()]
  451. if ka != nil {
  452. // Already old.
  453. if ka.isOld() {
  454. return
  455. }
  456. // Already in max new buckets.
  457. if len(ka.Buckets) == maxNewBucketsPerAddress {
  458. return
  459. }
  460. // The more entries we have, the less likely we are to add more.
  461. factor := int32(2 * len(ka.Buckets))
  462. if a.rand.Int31n(factor) != 0 {
  463. return
  464. }
  465. } else {
  466. ka = newKnownAddress(addr, src)
  467. }
  468. bucket := a.calcNewBucket(addr, src)
  469. a.addToNewBucket(ka, bucket)
  470. log.Notice("Added new address", "address", addr, "total", a.size())
  471. }
  472. // Make space in the new buckets by expiring the really bad entries.
  473. // If no bad entries are available we remove the oldest.
  474. func (a *AddrBook) expireNew(bucketIdx int) {
  475. for addrStr, ka := range a.addrNew[bucketIdx] {
  476. // If an entry is bad, throw it away
  477. if ka.isBad() {
  478. log.Notice(Fmt("expiring bad address %v", addrStr))
  479. a.removeFromBucket(ka, bucketTypeNew, bucketIdx)
  480. return
  481. }
  482. }
  483. // If we haven't thrown out a bad entry, throw out the oldest entry
  484. oldest := a.pickOldest(bucketTypeNew, bucketIdx)
  485. a.removeFromBucket(oldest, bucketTypeNew, bucketIdx)
  486. }
  487. // Promotes an address from new to old.
  488. // TODO: Move to old probabilistically.
  489. // The better a node is, the less likely it should be evicted from an old bucket.
  490. func (a *AddrBook) moveToOld(ka *knownAddress) {
  491. // Sanity check
  492. if ka.isOld() {
  493. log.Warn(Fmt("Cannot promote address that is already old %v", ka))
  494. return
  495. }
  496. if len(ka.Buckets) == 0 {
  497. log.Warn(Fmt("Cannot promote address that isn't in any new buckets %v", ka))
  498. return
  499. }
  500. // Remember one of the buckets in which ka is in.
  501. freedBucket := ka.Buckets[0]
  502. // Remove from all (new) buckets.
  503. a.removeFromAllBuckets(ka)
  504. // It's officially old now.
  505. ka.BucketType = bucketTypeOld
  506. // Try to add it to its oldBucket destination.
  507. oldBucketIdx := a.calcOldBucket(ka.Addr)
  508. added := a.addToOldBucket(ka, oldBucketIdx)
  509. if !added {
  510. // No room, must evict something
  511. oldest := a.pickOldest(bucketTypeOld, oldBucketIdx)
  512. a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx)
  513. // Find new bucket to put oldest in
  514. newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src)
  515. added := a.addToNewBucket(oldest, newBucketIdx)
  516. // No space in newBucket either, just put it in freedBucket from above.
  517. if !added {
  518. added := a.addToNewBucket(oldest, freedBucket)
  519. if !added {
  520. log.Warn(Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket))
  521. }
  522. }
  523. // Finally, add to bucket again.
  524. added = a.addToOldBucket(ka, oldBucketIdx)
  525. if !added {
  526. log.Warn(Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx))
  527. }
  528. }
  529. }
  530. // doublesha256( key + sourcegroup +
  531. // int64(doublesha256(key + group + sourcegroup))%bucket_per_group ) % num_new_buckets
  532. func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int {
  533. data1 := []byte{}
  534. data1 = append(data1, []byte(a.key)...)
  535. data1 = append(data1, []byte(a.groupKey(addr))...)
  536. data1 = append(data1, []byte(a.groupKey(src))...)
  537. hash1 := doubleSha256(data1)
  538. hash64 := binary.BigEndian.Uint64(hash1)
  539. hash64 %= newBucketsPerGroup
  540. var hashbuf [8]byte
  541. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  542. data2 := []byte{}
  543. data2 = append(data2, []byte(a.key)...)
  544. data2 = append(data2, a.groupKey(src)...)
  545. data2 = append(data2, hashbuf[:]...)
  546. hash2 := doubleSha256(data2)
  547. return int(binary.BigEndian.Uint64(hash2) % newBucketCount)
  548. }
  549. // doublesha256( key + group +
  550. // int64(doublesha256(key + addr))%buckets_per_group ) % num_old_buckets
  551. func (a *AddrBook) calcOldBucket(addr *NetAddress) int {
  552. data1 := []byte{}
  553. data1 = append(data1, []byte(a.key)...)
  554. data1 = append(data1, []byte(addr.String())...)
  555. hash1 := doubleSha256(data1)
  556. hash64 := binary.BigEndian.Uint64(hash1)
  557. hash64 %= oldBucketsPerGroup
  558. var hashbuf [8]byte
  559. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  560. data2 := []byte{}
  561. data2 = append(data2, []byte(a.key)...)
  562. data2 = append(data2, a.groupKey(addr)...)
  563. data2 = append(data2, hashbuf[:]...)
  564. hash2 := doubleSha256(data2)
  565. return int(binary.BigEndian.Uint64(hash2) % oldBucketCount)
  566. }
  567. // Return a string representing the network group of this address.
  568. // This is the /16 for IPv6, the /32 (/36 for he.net) for IPv6, the string
  569. // "local" for a local address and the string "unroutable for an unroutable
  570. // address.
  571. func (a *AddrBook) groupKey(na *NetAddress) string {
  572. if a.routabilityStrict && na.Local() {
  573. return "local"
  574. }
  575. if a.routabilityStrict && !na.Routable() {
  576. return "unroutable"
  577. }
  578. if ipv4 := na.IP.To4(); ipv4 != nil {
  579. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String()
  580. }
  581. if na.RFC6145() || na.RFC6052() {
  582. // last four bytes are the ip address
  583. ip := net.IP(na.IP[12:16])
  584. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  585. }
  586. if na.RFC3964() {
  587. ip := net.IP(na.IP[2:7])
  588. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  589. }
  590. if na.RFC4380() {
  591. // teredo tunnels have the last 4 bytes as the v4 address XOR
  592. // 0xff.
  593. ip := net.IP(make([]byte, 4))
  594. for i, byte := range na.IP[12:16] {
  595. ip[i] = byte ^ 0xff
  596. }
  597. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  598. }
  599. // OK, so now we know ourselves to be a IPv6 address.
  600. // bitcoind uses /32 for everything, except for Hurricane Electric's
  601. // (he.net) IP range, which it uses /36 for.
  602. bits := 32
  603. heNet := &net.IPNet{IP: net.ParseIP("2001:470::"),
  604. Mask: net.CIDRMask(32, 128)}
  605. if heNet.Contains(na.IP) {
  606. bits = 36
  607. }
  608. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String()
  609. }
  610. //-----------------------------------------------------------------------------
  611. /*
  612. knownAddress
  613. tracks information about a known network address that is used
  614. to determine how viable an address is.
  615. */
  616. type knownAddress struct {
  617. Addr *NetAddress
  618. Src *NetAddress
  619. Attempts int32
  620. LastAttempt time.Time
  621. LastSuccess time.Time
  622. BucketType byte
  623. Buckets []int
  624. }
  625. func newKnownAddress(addr *NetAddress, src *NetAddress) *knownAddress {
  626. return &knownAddress{
  627. Addr: addr,
  628. Src: src,
  629. Attempts: 0,
  630. LastAttempt: time.Now(),
  631. BucketType: bucketTypeNew,
  632. Buckets: nil,
  633. }
  634. }
  635. func (ka *knownAddress) isOld() bool {
  636. return ka.BucketType == bucketTypeOld
  637. }
  638. func (ka *knownAddress) isNew() bool {
  639. return ka.BucketType == bucketTypeNew
  640. }
  641. func (ka *knownAddress) markAttempt() {
  642. now := time.Now()
  643. ka.LastAttempt = now
  644. ka.Attempts += 1
  645. }
  646. func (ka *knownAddress) markGood() {
  647. now := time.Now()
  648. ka.LastAttempt = now
  649. ka.Attempts = 0
  650. ka.LastSuccess = now
  651. }
  652. func (ka *knownAddress) addBucketRef(bucketIdx int) int {
  653. for _, bucket := range ka.Buckets {
  654. if bucket == bucketIdx {
  655. log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka))
  656. return -1
  657. }
  658. }
  659. ka.Buckets = append(ka.Buckets, bucketIdx)
  660. return len(ka.Buckets)
  661. }
  662. func (ka *knownAddress) removeBucketRef(bucketIdx int) int {
  663. buckets := []int{}
  664. for _, bucket := range ka.Buckets {
  665. if bucket != bucketIdx {
  666. buckets = append(buckets, bucket)
  667. }
  668. }
  669. if len(buckets) != len(ka.Buckets)-1 {
  670. log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka))
  671. return -1
  672. }
  673. ka.Buckets = buckets
  674. return len(ka.Buckets)
  675. }
  676. /*
  677. An address is bad if the address in question has not been tried in the last
  678. minute and meets one of the following criteria:
  679. 1) It claims to be from the future
  680. 2) It hasn't been seen in over a month
  681. 3) It has failed at least three times and never succeeded
  682. 4) It has failed ten times in the last week
  683. All addresses that meet these criteria are assumed to be worthless and not
  684. worth keeping hold of.
  685. */
  686. func (ka *knownAddress) isBad() bool {
  687. // Has been attempted in the last minute --> good
  688. if ka.LastAttempt.Before(time.Now().Add(-1 * time.Minute)) {
  689. return false
  690. }
  691. // Over a month old?
  692. if ka.LastAttempt.After(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) {
  693. return true
  694. }
  695. // Never succeeded?
  696. if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries {
  697. return true
  698. }
  699. // Hasn't succeeded in too long?
  700. if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) &&
  701. ka.Attempts >= maxFailures {
  702. return true
  703. }
  704. return false
  705. }