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.

820 lines
20 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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. w, err := os.Create(filePath)
  271. if err != nil {
  272. log.Error("Error opening file", "file", filePath, "error", err)
  273. return
  274. }
  275. defer w.Close()
  276. jsonBytes, err := json.MarshalIndent(aJSON, "", "\t")
  277. _, err = w.Write(jsonBytes)
  278. if err != nil {
  279. log.Error("Failed to save AddrBook to file", "file", filePath, "error", err)
  280. }
  281. }
  282. // Returns false if file does not exist.
  283. // Panics if file is corrupt.
  284. func (a *AddrBook) loadFromFile(filePath string) bool {
  285. // If doesn't exist, do nothing.
  286. _, err := os.Stat(filePath)
  287. if os.IsNotExist(err) {
  288. return false
  289. }
  290. // Load addrBookJSON{}
  291. r, err := os.Open(filePath)
  292. if err != nil {
  293. panic(Fmt("Error opening file %s: %v", filePath, err))
  294. }
  295. defer r.Close()
  296. aJSON := &addrBookJSON{}
  297. dec := json.NewDecoder(r)
  298. err = dec.Decode(aJSON)
  299. if err != nil {
  300. panic(Fmt("Error reading file %s: %v", filePath, err))
  301. }
  302. // Restore all the fields...
  303. // Restore the key
  304. a.key = aJSON.Key
  305. // Restore .addrNew & .addrOld
  306. for _, ka := range aJSON.Addrs {
  307. for _, bucketIndex := range ka.Buckets {
  308. bucket := a.getBucket(ka.BucketType, bucketIndex)
  309. bucket[ka.Addr.String()] = ka
  310. }
  311. a.addrLookup[ka.Addr.String()] = ka
  312. if ka.BucketType == bucketTypeNew {
  313. a.nNew++
  314. } else {
  315. a.nOld++
  316. }
  317. }
  318. return true
  319. }
  320. /* Private methods */
  321. func (a *AddrBook) saveRoutine() {
  322. dumpAddressTicker := time.NewTicker(dumpAddressInterval)
  323. out:
  324. for {
  325. select {
  326. case <-dumpAddressTicker.C:
  327. log.Debug("Saving AddrBook to file", "size", a.Size())
  328. a.saveToFile(a.filePath)
  329. case <-a.quit:
  330. break out
  331. }
  332. }
  333. dumpAddressTicker.Stop()
  334. a.saveToFile(a.filePath)
  335. a.wg.Done()
  336. log.Info("Address handler done")
  337. }
  338. func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress {
  339. switch bucketType {
  340. case bucketTypeNew:
  341. return a.addrNew[bucketIdx]
  342. case bucketTypeOld:
  343. return a.addrOld[bucketIdx]
  344. default:
  345. panic("Should not happen")
  346. }
  347. }
  348. // Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full.
  349. // NOTE: currently it always returns true.
  350. func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool {
  351. // Sanity check
  352. if ka.isOld() {
  353. log.Warn(Fmt("Cannot add address already in old bucket to a new bucket: %v", ka))
  354. return false
  355. }
  356. addrStr := ka.Addr.String()
  357. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  358. // Already exists?
  359. if _, ok := bucket[addrStr]; ok {
  360. return true
  361. }
  362. // Enforce max addresses.
  363. if len(bucket) > newBucketSize {
  364. log.Info("new bucket is full, expiring old ")
  365. a.expireNew(bucketIdx)
  366. }
  367. // Add to bucket.
  368. bucket[addrStr] = ka
  369. if ka.addBucketRef(bucketIdx) == 1 {
  370. a.nNew++
  371. }
  372. // Ensure in addrLookup
  373. a.addrLookup[addrStr] = ka
  374. return true
  375. }
  376. // Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full.
  377. func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool {
  378. // Sanity check
  379. if ka.isNew() {
  380. log.Warn(Fmt("Cannot add new address to old bucket: %v", ka))
  381. return false
  382. }
  383. if len(ka.Buckets) != 0 {
  384. log.Warn(Fmt("Cannot add already old address to another old bucket: %v", ka))
  385. return false
  386. }
  387. addrStr := ka.Addr.String()
  388. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  389. // Already exists?
  390. if _, ok := bucket[addrStr]; ok {
  391. return true
  392. }
  393. // Enforce max addresses.
  394. if len(bucket) > oldBucketSize {
  395. return false
  396. }
  397. // Add to bucket.
  398. bucket[addrStr] = ka
  399. if ka.addBucketRef(bucketIdx) == 1 {
  400. a.nOld++
  401. }
  402. // Ensure in addrLookup
  403. a.addrLookup[addrStr] = ka
  404. return true
  405. }
  406. func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) {
  407. if ka.BucketType != bucketType {
  408. log.Warn(Fmt("Bucket type mismatch: %v", ka))
  409. return
  410. }
  411. bucket := a.getBucket(bucketType, bucketIdx)
  412. delete(bucket, ka.Addr.String())
  413. if ka.removeBucketRef(bucketIdx) == 0 {
  414. if bucketType == bucketTypeNew {
  415. a.nNew--
  416. } else {
  417. a.nOld--
  418. }
  419. delete(a.addrLookup, ka.Addr.String())
  420. }
  421. }
  422. func (a *AddrBook) removeFromAllBuckets(ka *knownAddress) {
  423. for _, bucketIdx := range ka.Buckets {
  424. bucket := a.getBucket(ka.BucketType, bucketIdx)
  425. delete(bucket, ka.Addr.String())
  426. }
  427. ka.Buckets = nil
  428. if ka.BucketType == bucketTypeNew {
  429. a.nNew--
  430. } else {
  431. a.nOld--
  432. }
  433. delete(a.addrLookup, ka.Addr.String())
  434. }
  435. func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress {
  436. bucket := a.getBucket(bucketType, bucketIdx)
  437. var oldest *knownAddress
  438. for _, ka := range bucket {
  439. if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) {
  440. oldest = ka
  441. }
  442. }
  443. return oldest
  444. }
  445. func (a *AddrBook) addAddress(addr, src *NetAddress) {
  446. if !addr.Routable() {
  447. log.Warn(Fmt("Cannot add non-routable address %v", addr))
  448. return
  449. }
  450. if _, ok := a.ourAddrs[addr.String()]; ok {
  451. // Ignore our own listener address.
  452. return
  453. }
  454. ka := a.addrLookup[addr.String()]
  455. if ka != nil {
  456. // Already old.
  457. if ka.isOld() {
  458. return
  459. }
  460. // Already in max new buckets.
  461. if len(ka.Buckets) == maxNewBucketsPerAddress {
  462. return
  463. }
  464. // The more entries we have, the less likely we are to add more.
  465. factor := int32(2 * len(ka.Buckets))
  466. if a.rand.Int31n(factor) != 0 {
  467. return
  468. }
  469. } else {
  470. ka = newKnownAddress(addr, src)
  471. }
  472. bucket := a.calcNewBucket(addr, src)
  473. a.addToNewBucket(ka, bucket)
  474. log.Info("Added new address", "address", addr, "total", a.size())
  475. }
  476. // Make space in the new buckets by expiring the really bad entries.
  477. // If no bad entries are available we remove the oldest.
  478. func (a *AddrBook) expireNew(bucketIdx int) {
  479. for addrStr, ka := range a.addrNew[bucketIdx] {
  480. // If an entry is bad, throw it away
  481. if ka.isBad() {
  482. log.Info(Fmt("expiring bad address %v", addrStr))
  483. a.removeFromBucket(ka, bucketTypeNew, bucketIdx)
  484. return
  485. }
  486. }
  487. // If we haven't thrown out a bad entry, throw out the oldest entry
  488. oldest := a.pickOldest(bucketTypeNew, bucketIdx)
  489. a.removeFromBucket(oldest, bucketTypeNew, bucketIdx)
  490. }
  491. // Promotes an address from new to old.
  492. // TODO: Move to old probabilistically.
  493. // The better a node is, the less likely it should be evicted from an old bucket.
  494. func (a *AddrBook) moveToOld(ka *knownAddress) {
  495. // Sanity check
  496. if ka.isOld() {
  497. log.Warn(Fmt("Cannot promote address that is already old %v", ka))
  498. return
  499. }
  500. if len(ka.Buckets) == 0 {
  501. log.Warn(Fmt("Cannot promote address that isn't in any new buckets %v", ka))
  502. return
  503. }
  504. // Remember one of the buckets in which ka is in.
  505. freedBucket := ka.Buckets[0]
  506. // Remove from all (new) buckets.
  507. a.removeFromAllBuckets(ka)
  508. // It's officially old now.
  509. ka.BucketType = bucketTypeOld
  510. // Try to add it to its oldBucket destination.
  511. oldBucketIdx := a.calcOldBucket(ka.Addr)
  512. added := a.addToOldBucket(ka, oldBucketIdx)
  513. if !added {
  514. // No room, must evict something
  515. oldest := a.pickOldest(bucketTypeOld, oldBucketIdx)
  516. a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx)
  517. // Find new bucket to put oldest in
  518. newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src)
  519. added := a.addToNewBucket(oldest, newBucketIdx)
  520. // No space in newBucket either, just put it in freedBucket from above.
  521. if !added {
  522. added := a.addToNewBucket(oldest, freedBucket)
  523. if !added {
  524. log.Warn(Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket))
  525. }
  526. }
  527. // Finally, add to bucket again.
  528. added = a.addToOldBucket(ka, oldBucketIdx)
  529. if !added {
  530. log.Warn(Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx))
  531. }
  532. }
  533. }
  534. // doublesha256(key + sourcegroup +
  535. // int64(doublesha256(key + group + sourcegroup))%bucket_per_source_group) % num_new_buckes
  536. func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int {
  537. data1 := []byte{}
  538. data1 = append(data1, []byte(a.key)...)
  539. data1 = append(data1, []byte(groupKey(addr))...)
  540. data1 = append(data1, []byte(groupKey(src))...)
  541. hash1 := doubleSha256(data1)
  542. hash64 := binary.LittleEndian.Uint64(hash1)
  543. hash64 %= newBucketsPerGroup
  544. var hashbuf [8]byte
  545. binary.LittleEndian.PutUint64(hashbuf[:], hash64)
  546. data2 := []byte{}
  547. data2 = append(data2, []byte(a.key)...)
  548. data2 = append(data2, groupKey(src)...)
  549. data2 = append(data2, hashbuf[:]...)
  550. hash2 := doubleSha256(data2)
  551. return int(binary.LittleEndian.Uint64(hash2) % newBucketCount)
  552. }
  553. // doublesha256(key + group + truncate_to_64bits(doublesha256(key + addr))%buckets_per_group) % num_buckets
  554. func (a *AddrBook) calcOldBucket(addr *NetAddress) int {
  555. data1 := []byte{}
  556. data1 = append(data1, []byte(a.key)...)
  557. data1 = append(data1, []byte(addr.String())...)
  558. hash1 := doubleSha256(data1)
  559. hash64 := binary.LittleEndian.Uint64(hash1)
  560. hash64 %= oldBucketsPerGroup
  561. var hashbuf [8]byte
  562. binary.LittleEndian.PutUint64(hashbuf[:], hash64)
  563. data2 := []byte{}
  564. data2 = append(data2, []byte(a.key)...)
  565. data2 = append(data2, groupKey(addr)...)
  566. data2 = append(data2, hashbuf[:]...)
  567. hash2 := doubleSha256(data2)
  568. return int(binary.LittleEndian.Uint64(hash2) % oldBucketCount)
  569. }
  570. // Return a string representing the network group of this address.
  571. // This is the /16 for IPv6, the /32 (/36 for he.net) for IPv6, the string
  572. // "local" for a local address and the string "unroutable for an unroutable
  573. // address.
  574. func groupKey(na *NetAddress) string {
  575. if na.Local() {
  576. return "local"
  577. }
  578. if !na.Routable() {
  579. return "unroutable"
  580. }
  581. if ipv4 := na.IP.To4(); ipv4 != nil {
  582. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String()
  583. }
  584. if na.RFC6145() || na.RFC6052() {
  585. // last four bytes are the ip address
  586. ip := net.IP(na.IP[12:16])
  587. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  588. }
  589. if na.RFC3964() {
  590. ip := net.IP(na.IP[2:7])
  591. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  592. }
  593. if na.RFC4380() {
  594. // teredo tunnels have the last 4 bytes as the v4 address XOR
  595. // 0xff.
  596. ip := net.IP(make([]byte, 4))
  597. for i, byte := range na.IP[12:16] {
  598. ip[i] = byte ^ 0xff
  599. }
  600. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  601. }
  602. // OK, so now we know ourselves to be a IPv6 address.
  603. // bitcoind uses /32 for everything, except for Hurricane Electric's
  604. // (he.net) IP range, which it uses /36 for.
  605. bits := 32
  606. heNet := &net.IPNet{IP: net.ParseIP("2001:470::"),
  607. Mask: net.CIDRMask(32, 128)}
  608. if heNet.Contains(na.IP) {
  609. bits = 36
  610. }
  611. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String()
  612. }
  613. //-----------------------------------------------------------------------------
  614. /*
  615. knownAddress
  616. tracks information about a known network address that is used
  617. to determine how viable an address is.
  618. */
  619. type knownAddress struct {
  620. Addr *NetAddress
  621. Src *NetAddress
  622. Attempts uint32
  623. LastAttempt time.Time
  624. LastSuccess time.Time
  625. BucketType byte
  626. Buckets []int
  627. }
  628. func newKnownAddress(addr *NetAddress, src *NetAddress) *knownAddress {
  629. return &knownAddress{
  630. Addr: addr,
  631. Src: src,
  632. Attempts: 0,
  633. LastAttempt: time.Now(),
  634. BucketType: bucketTypeNew,
  635. Buckets: nil,
  636. }
  637. }
  638. func (ka *knownAddress) isOld() bool {
  639. return ka.BucketType == bucketTypeOld
  640. }
  641. func (ka *knownAddress) isNew() bool {
  642. return ka.BucketType == bucketTypeNew
  643. }
  644. func (ka *knownAddress) markAttempt() {
  645. now := time.Now()
  646. ka.LastAttempt = now
  647. ka.Attempts += 1
  648. }
  649. func (ka *knownAddress) markGood() {
  650. now := time.Now()
  651. ka.LastAttempt = now
  652. ka.Attempts = 0
  653. ka.LastSuccess = now
  654. }
  655. func (ka *knownAddress) addBucketRef(bucketIdx int) int {
  656. for _, bucket := range ka.Buckets {
  657. if bucket == bucketIdx {
  658. log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka))
  659. return -1
  660. }
  661. }
  662. ka.Buckets = append(ka.Buckets, bucketIdx)
  663. return len(ka.Buckets)
  664. }
  665. func (ka *knownAddress) removeBucketRef(bucketIdx int) int {
  666. buckets := []int{}
  667. for _, bucket := range ka.Buckets {
  668. if bucket != bucketIdx {
  669. buckets = append(buckets, bucket)
  670. }
  671. }
  672. if len(buckets) != len(ka.Buckets)-1 {
  673. log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka))
  674. return -1
  675. }
  676. ka.Buckets = buckets
  677. return len(ka.Buckets)
  678. }
  679. /*
  680. An address is bad if the address in question has not been tried in the last
  681. minute and meets one of the following criteria:
  682. 1) It claims to be from the future
  683. 2) It hasn't been seen in over a month
  684. 3) It has failed at least three times and never succeeded
  685. 4) It has failed ten times in the last week
  686. All addresses that meet these criteria are assumed to be worthless and not
  687. worth keeping hold of.
  688. */
  689. func (ka *knownAddress) isBad() bool {
  690. // Has been attempted in the last minute --> good
  691. if ka.LastAttempt.Before(time.Now().Add(-1 * time.Minute)) {
  692. return false
  693. }
  694. // Over a month old?
  695. if ka.LastAttempt.After(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) {
  696. return true
  697. }
  698. // Never succeeded?
  699. if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries {
  700. return true
  701. }
  702. // Hasn't succeeded in too long?
  703. if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) &&
  704. ka.Attempts >= maxFailures {
  705. return true
  706. }
  707. return false
  708. }