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.

812 lines
20 KiB

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