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.

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