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.

882 lines
22 KiB

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