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.

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