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.

818 lines
20 KiB

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