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.

813 lines
22 KiB

9 years ago
9 years ago
7 years ago
9 years ago
8 years ago
9 years ago
7 years ago
9 years ago
7 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
7 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
8 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 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
7 years ago
9 years ago
9 years ago
7 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
8 years ago
7 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
7 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
9 years ago
7 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
8 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
7 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
7 years ago
9 years ago
8 years ago
9 years ago
7 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
7 years ago
9 years ago
9 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 pex
  5. import (
  6. "crypto/sha256"
  7. "encoding/binary"
  8. "math"
  9. "net"
  10. "sync"
  11. "time"
  12. crypto "github.com/tendermint/go-crypto"
  13. "github.com/tendermint/tendermint/p2p"
  14. cmn "github.com/tendermint/tmlibs/common"
  15. )
  16. const (
  17. bucketTypeNew = 0x01
  18. bucketTypeOld = 0x02
  19. )
  20. // AddrBook is an address book used for tracking peers
  21. // so we can gossip about them to others and select
  22. // peers to dial.
  23. // TODO: break this up?
  24. type AddrBook interface {
  25. cmn.Service
  26. // Add our own addresses so we don't later add ourselves
  27. AddOurAddress(*p2p.NetAddress)
  28. // Check if it is our address
  29. OurAddress(*p2p.NetAddress) bool
  30. // Add and remove an address
  31. AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error
  32. RemoveAddress(*p2p.NetAddress)
  33. // Check if the address is in the book
  34. HasAddress(*p2p.NetAddress) bool
  35. // Do we need more peers?
  36. NeedMoreAddrs() bool
  37. // Pick an address to dial
  38. PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress
  39. // Mark address
  40. MarkGood(*p2p.NetAddress)
  41. MarkAttempt(*p2p.NetAddress)
  42. MarkBad(*p2p.NetAddress)
  43. IsGood(*p2p.NetAddress) bool
  44. // Send a selection of addresses to peers
  45. GetSelection() []*p2p.NetAddress
  46. // Send a selection of addresses with bias
  47. GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress
  48. // TODO: remove
  49. ListOfKnownAddresses() []*knownAddress
  50. // Persist to disk
  51. Save()
  52. }
  53. var _ AddrBook = (*addrBook)(nil)
  54. // addrBook - concurrency safe peer address manager.
  55. // Implements AddrBook.
  56. type addrBook struct {
  57. cmn.BaseService
  58. // immutable after creation
  59. filePath string
  60. routabilityStrict bool
  61. key string // random prefix for bucket placement
  62. // accessed concurrently
  63. mtx sync.Mutex
  64. rand *cmn.Rand
  65. ourAddrs map[string]struct{}
  66. addrLookup map[p2p.ID]*knownAddress // new & old
  67. bucketsOld []map[string]*knownAddress
  68. bucketsNew []map[string]*knownAddress
  69. nOld int
  70. nNew int
  71. wg sync.WaitGroup
  72. }
  73. // NewAddrBook creates a new address book.
  74. // Use Start to begin processing asynchronous address updates.
  75. func NewAddrBook(filePath string, routabilityStrict bool) *addrBook {
  76. am := &addrBook{
  77. rand: cmn.NewRand(),
  78. ourAddrs: make(map[string]struct{}),
  79. addrLookup: make(map[p2p.ID]*knownAddress),
  80. filePath: filePath,
  81. routabilityStrict: routabilityStrict,
  82. }
  83. am.init()
  84. am.BaseService = *cmn.NewBaseService(nil, "AddrBook", am)
  85. return am
  86. }
  87. // Initialize the buckets.
  88. // When modifying this, don't forget to update loadFromFile()
  89. func (a *addrBook) init() {
  90. a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits
  91. // New addr buckets
  92. a.bucketsNew = make([]map[string]*knownAddress, newBucketCount)
  93. for i := range a.bucketsNew {
  94. a.bucketsNew[i] = make(map[string]*knownAddress)
  95. }
  96. // Old addr buckets
  97. a.bucketsOld = make([]map[string]*knownAddress, oldBucketCount)
  98. for i := range a.bucketsOld {
  99. a.bucketsOld[i] = make(map[string]*knownAddress)
  100. }
  101. }
  102. // OnStart implements Service.
  103. func (a *addrBook) OnStart() error {
  104. if err := a.BaseService.OnStart(); err != nil {
  105. return err
  106. }
  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. func (a *addrBook) FilePath() string {
  122. return a.filePath
  123. }
  124. //-------------------------------------------------------
  125. // AddOurAddress one of our addresses.
  126. func (a *addrBook) AddOurAddress(addr *p2p.NetAddress) {
  127. a.mtx.Lock()
  128. defer a.mtx.Unlock()
  129. a.Logger.Info("Add our address to book", "addr", addr)
  130. a.ourAddrs[addr.String()] = struct{}{}
  131. }
  132. // OurAddress returns true if it is our address.
  133. func (a *addrBook) OurAddress(addr *p2p.NetAddress) bool {
  134. a.mtx.Lock()
  135. _, ok := a.ourAddrs[addr.String()]
  136. a.mtx.Unlock()
  137. return ok
  138. }
  139. // AddAddress implements AddrBook
  140. // Add address to a "new" bucket. If it's already in one, only add it probabilistically.
  141. // Returns error if the addr is non-routable. Does not add self.
  142. // NOTE: addr must not be nil
  143. func (a *addrBook) AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error {
  144. a.mtx.Lock()
  145. defer a.mtx.Unlock()
  146. return a.addAddress(addr, src)
  147. }
  148. // RemoveAddress implements AddrBook - removes the address from the book.
  149. func (a *addrBook) RemoveAddress(addr *p2p.NetAddress) {
  150. a.mtx.Lock()
  151. defer a.mtx.Unlock()
  152. ka := a.addrLookup[addr.ID]
  153. if ka == nil {
  154. return
  155. }
  156. a.Logger.Info("Remove address from book", "addr", ka.Addr, "ID", ka.ID())
  157. a.removeFromAllBuckets(ka)
  158. }
  159. // IsGood returns true if peer was ever marked as good and haven't
  160. // done anything wrong since then.
  161. func (a *addrBook) IsGood(addr *p2p.NetAddress) bool {
  162. a.mtx.Lock()
  163. defer a.mtx.Unlock()
  164. return a.addrLookup[addr.ID].isOld()
  165. }
  166. // HasAddress returns true if the address is in the book.
  167. func (a *addrBook) HasAddress(addr *p2p.NetAddress) bool {
  168. a.mtx.Lock()
  169. defer a.mtx.Unlock()
  170. ka := a.addrLookup[addr.ID]
  171. return ka != nil
  172. }
  173. // NeedMoreAddrs implements AddrBook - returns true if there are not have enough addresses in the book.
  174. func (a *addrBook) NeedMoreAddrs() bool {
  175. return a.Size() < needAddressThreshold
  176. }
  177. // PickAddress implements AddrBook. It picks an address to connect to.
  178. // The address is picked randomly from an old or new bucket according
  179. // to the biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to that range)
  180. // and determines how biased we are to pick an address from a new bucket.
  181. // PickAddress returns nil if the AddrBook is empty or if we try to pick
  182. // from an empty bucket.
  183. func (a *addrBook) PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress {
  184. a.mtx.Lock()
  185. defer a.mtx.Unlock()
  186. bookSize := a.size()
  187. if bookSize <= 0 {
  188. if bookSize < 0 {
  189. a.Logger.Error("Addrbook size less than 0", "nNew", a.nNew, "nOld", a.nOld)
  190. }
  191. return nil
  192. }
  193. if biasTowardsNewAddrs > 100 {
  194. biasTowardsNewAddrs = 100
  195. }
  196. if biasTowardsNewAddrs < 0 {
  197. biasTowardsNewAddrs = 0
  198. }
  199. // Bias between new and old addresses.
  200. oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(biasTowardsNewAddrs))
  201. newCorrelation := math.Sqrt(float64(a.nNew)) * float64(biasTowardsNewAddrs)
  202. // pick a random peer from a random bucket
  203. var bucket map[string]*knownAddress
  204. pickFromOldBucket := (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation
  205. if (pickFromOldBucket && a.nOld == 0) ||
  206. (!pickFromOldBucket && a.nNew == 0) {
  207. return nil
  208. }
  209. // loop until we pick a random non-empty bucket
  210. for len(bucket) == 0 {
  211. if pickFromOldBucket {
  212. bucket = a.bucketsOld[a.rand.Intn(len(a.bucketsOld))]
  213. } else {
  214. bucket = a.bucketsNew[a.rand.Intn(len(a.bucketsNew))]
  215. }
  216. }
  217. // pick a random index and loop over the map to return that index
  218. randIndex := a.rand.Intn(len(bucket))
  219. for _, ka := range bucket {
  220. if randIndex == 0 {
  221. return ka.Addr
  222. }
  223. randIndex--
  224. }
  225. return nil
  226. }
  227. // MarkGood implements AddrBook - it marks the peer as good and
  228. // moves it into an "old" bucket.
  229. func (a *addrBook) MarkGood(addr *p2p.NetAddress) {
  230. a.mtx.Lock()
  231. defer a.mtx.Unlock()
  232. ka := a.addrLookup[addr.ID]
  233. if ka == nil {
  234. return
  235. }
  236. ka.markGood()
  237. if ka.isNew() {
  238. a.moveToOld(ka)
  239. }
  240. }
  241. // MarkAttempt implements AddrBook - it marks that an attempt was made to connect to the address.
  242. func (a *addrBook) MarkAttempt(addr *p2p.NetAddress) {
  243. a.mtx.Lock()
  244. defer a.mtx.Unlock()
  245. ka := a.addrLookup[addr.ID]
  246. if ka == nil {
  247. return
  248. }
  249. ka.markAttempt()
  250. }
  251. // MarkBad implements AddrBook. Currently it just ejects the address.
  252. // TODO: black list for some amount of time
  253. func (a *addrBook) MarkBad(addr *p2p.NetAddress) {
  254. a.RemoveAddress(addr)
  255. }
  256. // GetSelection implements AddrBook.
  257. // It randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
  258. // Must never return a nil address.
  259. func (a *addrBook) GetSelection() []*p2p.NetAddress {
  260. a.mtx.Lock()
  261. defer a.mtx.Unlock()
  262. bookSize := a.size()
  263. if bookSize <= 0 {
  264. if bookSize < 0 {
  265. a.Logger.Error("Addrbook size less than 0", "nNew", a.nNew, "nOld", a.nOld)
  266. }
  267. return nil
  268. }
  269. numAddresses := cmn.MaxInt(
  270. cmn.MinInt(minGetSelection, bookSize),
  271. bookSize*getSelectionPercent/100)
  272. numAddresses = cmn.MinInt(maxGetSelection, numAddresses)
  273. // XXX: instead of making a list of all addresses, shuffling, and slicing a random chunk,
  274. // could we just select a random numAddresses of indexes?
  275. allAddr := make([]*p2p.NetAddress, bookSize)
  276. i := 0
  277. for _, ka := range a.addrLookup {
  278. allAddr[i] = ka.Addr
  279. i++
  280. }
  281. // Fisher-Yates shuffle the array. We only need to do the first
  282. // `numAddresses' since we are throwing the rest.
  283. for i := 0; i < numAddresses; i++ {
  284. // pick a number between current index and the end
  285. j := cmn.RandIntn(len(allAddr)-i) + i
  286. allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
  287. }
  288. // slice off the limit we are willing to share.
  289. return allAddr[:numAddresses]
  290. }
  291. // GetSelectionWithBias implements AddrBook.
  292. // It randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
  293. // Must never return a nil address.
  294. //
  295. // Each address is picked randomly from an old or new bucket according to the
  296. // biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to
  297. // that range) and determines how biased we are to pick an address from a new
  298. // bucket.
  299. func (a *addrBook) GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress {
  300. a.mtx.Lock()
  301. defer a.mtx.Unlock()
  302. bookSize := a.size()
  303. if bookSize <= 0 {
  304. if bookSize < 0 {
  305. a.Logger.Error("Addrbook size less than 0", "nNew", a.nNew, "nOld", a.nOld)
  306. }
  307. return nil
  308. }
  309. if biasTowardsNewAddrs > 100 {
  310. biasTowardsNewAddrs = 100
  311. }
  312. if biasTowardsNewAddrs < 0 {
  313. biasTowardsNewAddrs = 0
  314. }
  315. numAddresses := cmn.MaxInt(
  316. cmn.MinInt(minGetSelection, bookSize),
  317. bookSize*getSelectionPercent/100)
  318. numAddresses = cmn.MinInt(maxGetSelection, numAddresses)
  319. selection := make([]*p2p.NetAddress, numAddresses)
  320. oldBucketToAddrsMap := make(map[int]map[string]struct{})
  321. var oldIndex int
  322. newBucketToAddrsMap := make(map[int]map[string]struct{})
  323. var newIndex int
  324. selectionIndex := 0
  325. ADDRS_LOOP:
  326. for selectionIndex < numAddresses {
  327. pickFromOldBucket := int((float64(selectionIndex)/float64(numAddresses))*100) >= biasTowardsNewAddrs
  328. pickFromOldBucket = (pickFromOldBucket && a.nOld > 0) || a.nNew == 0
  329. bucket := make(map[string]*knownAddress)
  330. // loop until we pick a random non-empty bucket
  331. for len(bucket) == 0 {
  332. if pickFromOldBucket {
  333. oldIndex = a.rand.Intn(len(a.bucketsOld))
  334. bucket = a.bucketsOld[oldIndex]
  335. } else {
  336. newIndex = a.rand.Intn(len(a.bucketsNew))
  337. bucket = a.bucketsNew[newIndex]
  338. }
  339. }
  340. // pick a random index
  341. randIndex := a.rand.Intn(len(bucket))
  342. // loop over the map to return that index
  343. var selectedAddr *p2p.NetAddress
  344. for _, ka := range bucket {
  345. if randIndex == 0 {
  346. selectedAddr = ka.Addr
  347. break
  348. }
  349. randIndex--
  350. }
  351. // if we have selected the address before, restart the loop
  352. // otherwise, record it and continue
  353. if pickFromOldBucket {
  354. if addrsMap, ok := oldBucketToAddrsMap[oldIndex]; ok {
  355. if _, ok = addrsMap[selectedAddr.String()]; ok {
  356. continue ADDRS_LOOP
  357. }
  358. } else {
  359. oldBucketToAddrsMap[oldIndex] = make(map[string]struct{})
  360. }
  361. oldBucketToAddrsMap[oldIndex][selectedAddr.String()] = struct{}{}
  362. } else {
  363. if addrsMap, ok := newBucketToAddrsMap[newIndex]; ok {
  364. if _, ok = addrsMap[selectedAddr.String()]; ok {
  365. continue ADDRS_LOOP
  366. }
  367. } else {
  368. newBucketToAddrsMap[newIndex] = make(map[string]struct{})
  369. }
  370. newBucketToAddrsMap[newIndex][selectedAddr.String()] = struct{}{}
  371. }
  372. selection[selectionIndex] = selectedAddr
  373. selectionIndex++
  374. }
  375. return selection
  376. }
  377. // ListOfKnownAddresses returns the new and old addresses.
  378. func (a *addrBook) ListOfKnownAddresses() []*knownAddress {
  379. a.mtx.Lock()
  380. defer a.mtx.Unlock()
  381. addrs := []*knownAddress{}
  382. for _, addr := range a.addrLookup {
  383. addrs = append(addrs, addr.copy())
  384. }
  385. return addrs
  386. }
  387. //------------------------------------------------
  388. // Size returns the number of addresses in the book.
  389. func (a *addrBook) Size() int {
  390. a.mtx.Lock()
  391. defer a.mtx.Unlock()
  392. return a.size()
  393. }
  394. func (a *addrBook) size() int {
  395. return a.nNew + a.nOld
  396. }
  397. //----------------------------------------------------------
  398. // Save persists the address book to disk.
  399. func (a *addrBook) Save() {
  400. a.saveToFile(a.filePath) // thread safe
  401. }
  402. func (a *addrBook) saveRoutine() {
  403. defer a.wg.Done()
  404. saveFileTicker := time.NewTicker(dumpAddressInterval)
  405. out:
  406. for {
  407. select {
  408. case <-saveFileTicker.C:
  409. a.saveToFile(a.filePath)
  410. case <-a.Quit():
  411. break out
  412. }
  413. }
  414. saveFileTicker.Stop()
  415. a.saveToFile(a.filePath)
  416. a.Logger.Info("Address handler done")
  417. }
  418. //----------------------------------------------------------
  419. func (a *addrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress {
  420. switch bucketType {
  421. case bucketTypeNew:
  422. return a.bucketsNew[bucketIdx]
  423. case bucketTypeOld:
  424. return a.bucketsOld[bucketIdx]
  425. default:
  426. cmn.PanicSanity("Should not happen")
  427. return nil
  428. }
  429. }
  430. // Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full.
  431. // NOTE: currently it always returns true.
  432. func (a *addrBook) addToNewBucket(ka *knownAddress, bucketIdx int) {
  433. // Sanity check
  434. if ka.isOld() {
  435. a.Logger.Error("Failed Sanity Check! Cant add old address to new bucket", "ka", ka, "bucket", bucketIdx)
  436. return
  437. }
  438. addrStr := ka.Addr.String()
  439. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  440. // Already exists?
  441. if _, ok := bucket[addrStr]; ok {
  442. return
  443. }
  444. // Enforce max addresses.
  445. if len(bucket) > newBucketSize {
  446. a.Logger.Info("new bucket is full, expiring new")
  447. a.expireNew(bucketIdx)
  448. }
  449. // Add to bucket.
  450. bucket[addrStr] = ka
  451. // increment nNew if the peer doesnt already exist in a bucket
  452. if ka.addBucketRef(bucketIdx) == 1 {
  453. a.nNew++
  454. }
  455. // Add it to addrLookup
  456. a.addrLookup[ka.ID()] = ka
  457. }
  458. // Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full.
  459. func (a *addrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool {
  460. // Sanity check
  461. if ka.isNew() {
  462. a.Logger.Error(cmn.Fmt("Cannot add new address to old bucket: %v", ka))
  463. return false
  464. }
  465. if len(ka.Buckets) != 0 {
  466. a.Logger.Error(cmn.Fmt("Cannot add already old address to another old bucket: %v", ka))
  467. return false
  468. }
  469. addrStr := ka.Addr.String()
  470. bucket := a.getBucket(bucketTypeOld, bucketIdx)
  471. // Already exists?
  472. if _, ok := bucket[addrStr]; ok {
  473. return true
  474. }
  475. // Enforce max addresses.
  476. if len(bucket) > oldBucketSize {
  477. return false
  478. }
  479. // Add to bucket.
  480. bucket[addrStr] = ka
  481. if ka.addBucketRef(bucketIdx) == 1 {
  482. a.nOld++
  483. }
  484. // Ensure in addrLookup
  485. a.addrLookup[ka.ID()] = ka
  486. return true
  487. }
  488. func (a *addrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) {
  489. if ka.BucketType != bucketType {
  490. a.Logger.Error(cmn.Fmt("Bucket type mismatch: %v", ka))
  491. return
  492. }
  493. bucket := a.getBucket(bucketType, bucketIdx)
  494. delete(bucket, ka.Addr.String())
  495. if ka.removeBucketRef(bucketIdx) == 0 {
  496. if bucketType == bucketTypeNew {
  497. a.nNew--
  498. } else {
  499. a.nOld--
  500. }
  501. delete(a.addrLookup, ka.ID())
  502. }
  503. }
  504. func (a *addrBook) removeFromAllBuckets(ka *knownAddress) {
  505. for _, bucketIdx := range ka.Buckets {
  506. bucket := a.getBucket(ka.BucketType, bucketIdx)
  507. delete(bucket, ka.Addr.String())
  508. }
  509. ka.Buckets = nil
  510. if ka.BucketType == bucketTypeNew {
  511. a.nNew--
  512. } else {
  513. a.nOld--
  514. }
  515. delete(a.addrLookup, ka.ID())
  516. }
  517. //----------------------------------------------------------
  518. func (a *addrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress {
  519. bucket := a.getBucket(bucketType, bucketIdx)
  520. var oldest *knownAddress
  521. for _, ka := range bucket {
  522. if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) {
  523. oldest = ka
  524. }
  525. }
  526. return oldest
  527. }
  528. // adds the address to a "new" bucket. if its already in one,
  529. // it only adds it probabilistically
  530. func (a *addrBook) addAddress(addr, src *p2p.NetAddress) error {
  531. if addr == nil || src == nil {
  532. return ErrAddrBookNilAddr{addr, src}
  533. }
  534. if a.routabilityStrict && !addr.Routable() {
  535. return ErrAddrBookNonRoutable{addr}
  536. }
  537. // TODO: we should track ourAddrs by ID and by IP:PORT and refuse both.
  538. if _, ok := a.ourAddrs[addr.String()]; ok {
  539. return ErrAddrBookSelf{addr}
  540. }
  541. ka := a.addrLookup[addr.ID]
  542. if ka != nil {
  543. // If its already old and the addr is the same, ignore it.
  544. if ka.isOld() && ka.Addr.Equals(addr) {
  545. return nil
  546. }
  547. // Already in max new buckets.
  548. if len(ka.Buckets) == maxNewBucketsPerAddress {
  549. return nil
  550. }
  551. // The more entries we have, the less likely we are to add more.
  552. factor := int32(2 * len(ka.Buckets))
  553. if a.rand.Int31n(factor) != 0 {
  554. return nil
  555. }
  556. } else {
  557. ka = newKnownAddress(addr, src)
  558. }
  559. bucket := a.calcNewBucket(addr, src)
  560. a.addToNewBucket(ka, bucket)
  561. return nil
  562. }
  563. // Make space in the new buckets by expiring the really bad entries.
  564. // If no bad entries are available we remove the oldest.
  565. func (a *addrBook) expireNew(bucketIdx int) {
  566. for addrStr, ka := range a.bucketsNew[bucketIdx] {
  567. // If an entry is bad, throw it away
  568. if ka.isBad() {
  569. a.Logger.Info(cmn.Fmt("expiring bad address %v", addrStr))
  570. a.removeFromBucket(ka, bucketTypeNew, bucketIdx)
  571. return
  572. }
  573. }
  574. // If we haven't thrown out a bad entry, throw out the oldest entry
  575. oldest := a.pickOldest(bucketTypeNew, bucketIdx)
  576. a.removeFromBucket(oldest, bucketTypeNew, bucketIdx)
  577. }
  578. // Promotes an address from new to old. If the destination bucket is full,
  579. // demote the oldest one to a "new" bucket.
  580. // TODO: Demote more probabilistically?
  581. func (a *addrBook) moveToOld(ka *knownAddress) {
  582. // Sanity check
  583. if ka.isOld() {
  584. a.Logger.Error(cmn.Fmt("Cannot promote address that is already old %v", ka))
  585. return
  586. }
  587. if len(ka.Buckets) == 0 {
  588. a.Logger.Error(cmn.Fmt("Cannot promote address that isn't in any new buckets %v", ka))
  589. return
  590. }
  591. // Remove from all (new) buckets.
  592. a.removeFromAllBuckets(ka)
  593. // It's officially old now.
  594. ka.BucketType = bucketTypeOld
  595. // Try to add it to its oldBucket destination.
  596. oldBucketIdx := a.calcOldBucket(ka.Addr)
  597. added := a.addToOldBucket(ka, oldBucketIdx)
  598. if !added {
  599. // No room; move the oldest to a new bucket
  600. oldest := a.pickOldest(bucketTypeOld, oldBucketIdx)
  601. a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx)
  602. newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src)
  603. a.addToNewBucket(oldest, newBucketIdx)
  604. // Finally, add our ka to old bucket again.
  605. added = a.addToOldBucket(ka, oldBucketIdx)
  606. if !added {
  607. a.Logger.Error(cmn.Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx))
  608. }
  609. }
  610. }
  611. //---------------------------------------------------------------------
  612. // calculate bucket placements
  613. // doublesha256( key + sourcegroup +
  614. // int64(doublesha256(key + group + sourcegroup))%bucket_per_group ) % num_new_buckets
  615. func (a *addrBook) calcNewBucket(addr, src *p2p.NetAddress) int {
  616. data1 := []byte{}
  617. data1 = append(data1, []byte(a.key)...)
  618. data1 = append(data1, []byte(a.groupKey(addr))...)
  619. data1 = append(data1, []byte(a.groupKey(src))...)
  620. hash1 := doubleSha256(data1)
  621. hash64 := binary.BigEndian.Uint64(hash1)
  622. hash64 %= newBucketsPerGroup
  623. var hashbuf [8]byte
  624. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  625. data2 := []byte{}
  626. data2 = append(data2, []byte(a.key)...)
  627. data2 = append(data2, a.groupKey(src)...)
  628. data2 = append(data2, hashbuf[:]...)
  629. hash2 := doubleSha256(data2)
  630. return int(binary.BigEndian.Uint64(hash2) % newBucketCount)
  631. }
  632. // doublesha256( key + group +
  633. // int64(doublesha256(key + addr))%buckets_per_group ) % num_old_buckets
  634. func (a *addrBook) calcOldBucket(addr *p2p.NetAddress) int {
  635. data1 := []byte{}
  636. data1 = append(data1, []byte(a.key)...)
  637. data1 = append(data1, []byte(addr.String())...)
  638. hash1 := doubleSha256(data1)
  639. hash64 := binary.BigEndian.Uint64(hash1)
  640. hash64 %= oldBucketsPerGroup
  641. var hashbuf [8]byte
  642. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  643. data2 := []byte{}
  644. data2 = append(data2, []byte(a.key)...)
  645. data2 = append(data2, a.groupKey(addr)...)
  646. data2 = append(data2, hashbuf[:]...)
  647. hash2 := doubleSha256(data2)
  648. return int(binary.BigEndian.Uint64(hash2) % oldBucketCount)
  649. }
  650. // Return a string representing the network group of this address.
  651. // This is the /16 for IPv4, the /32 (/36 for he.net) for IPv6, the string
  652. // "local" for a local address and the string "unroutable" for an unroutable
  653. // address.
  654. func (a *addrBook) groupKey(na *p2p.NetAddress) string {
  655. if a.routabilityStrict && na.Local() {
  656. return "local"
  657. }
  658. if a.routabilityStrict && !na.Routable() {
  659. return "unroutable"
  660. }
  661. if ipv4 := na.IP.To4(); ipv4 != nil {
  662. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String()
  663. }
  664. if na.RFC6145() || na.RFC6052() {
  665. // last four bytes are the ip address
  666. ip := net.IP(na.IP[12:16])
  667. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  668. }
  669. if na.RFC3964() {
  670. ip := net.IP(na.IP[2:7])
  671. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  672. }
  673. if na.RFC4380() {
  674. // teredo tunnels have the last 4 bytes as the v4 address XOR
  675. // 0xff.
  676. ip := net.IP(make([]byte, 4))
  677. for i, byte := range na.IP[12:16] {
  678. ip[i] = byte ^ 0xff
  679. }
  680. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  681. }
  682. // OK, so now we know ourselves to be a IPv6 address.
  683. // bitcoind uses /32 for everything, except for Hurricane Electric's
  684. // (he.net) IP range, which it uses /36 for.
  685. bits := 32
  686. heNet := &net.IPNet{IP: net.ParseIP("2001:470::"),
  687. Mask: net.CIDRMask(32, 128)}
  688. if heNet.Contains(na.IP) {
  689. bits = 36
  690. }
  691. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String()
  692. }
  693. // doubleSha256 calculates sha256(sha256(b)) and returns the resulting bytes.
  694. func doubleSha256(b []byte) []byte {
  695. hasher := sha256.New()
  696. hasher.Write(b) // nolint: errcheck, gas
  697. sum := hasher.Sum(nil)
  698. hasher.Reset()
  699. hasher.Write(sum) // nolint: errcheck, gas
  700. return hasher.Sum(nil)
  701. }