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.

847 lines
21 KiB

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