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.

838 lines
21 KiB

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