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.

798 lines
19 KiB

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