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.

84 lines
1.8 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package pex
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. cmn "github.com/tendermint/tendermint/libs/common"
  7. )
  8. /* Loading & Saving */
  9. type addrBookJSON struct {
  10. Key string `json:"key"`
  11. Addrs []*knownAddress `json:"addrs"`
  12. }
  13. func (a *addrBook) saveToFile(filePath string) {
  14. a.Logger.Info("Saving AddrBook to file", "size", a.Size())
  15. a.mtx.Lock()
  16. defer a.mtx.Unlock()
  17. // Compile Addrs
  18. addrs := []*knownAddress{}
  19. for _, ka := range a.addrLookup {
  20. addrs = append(addrs, ka)
  21. }
  22. aJSON := &addrBookJSON{
  23. Key: a.key,
  24. Addrs: addrs,
  25. }
  26. jsonBytes, err := json.MarshalIndent(aJSON, "", "\t")
  27. if err != nil {
  28. a.Logger.Error("Failed to save AddrBook to file", "err", err)
  29. return
  30. }
  31. err = cmn.WriteFileAtomic(filePath, jsonBytes, 0644)
  32. if err != nil {
  33. a.Logger.Error("Failed to save AddrBook to file", "file", filePath, "err", err)
  34. }
  35. }
  36. // Returns false if file does not exist.
  37. // cmn.Panics if file is corrupt.
  38. func (a *addrBook) loadFromFile(filePath string) bool {
  39. // If doesn't exist, do nothing.
  40. _, err := os.Stat(filePath)
  41. if os.IsNotExist(err) {
  42. return false
  43. }
  44. // Load addrBookJSON{}
  45. r, err := os.Open(filePath)
  46. if err != nil {
  47. cmn.PanicCrisis(fmt.Sprintf("Error opening file %s: %v", filePath, err))
  48. }
  49. defer r.Close() // nolint: errcheck
  50. aJSON := &addrBookJSON{}
  51. dec := json.NewDecoder(r)
  52. err = dec.Decode(aJSON)
  53. if err != nil {
  54. cmn.PanicCrisis(fmt.Sprintf("Error reading file %s: %v", filePath, err))
  55. }
  56. // Restore all the fields...
  57. // Restore the key
  58. a.key = aJSON.Key
  59. // Restore .bucketsNew & .bucketsOld
  60. for _, ka := range aJSON.Addrs {
  61. for _, bucketIndex := range ka.Buckets {
  62. bucket := a.getBucket(ka.BucketType, bucketIndex)
  63. bucket[ka.Addr.String()] = ka
  64. }
  65. a.addrLookup[ka.ID()] = ka
  66. if ka.BucketType == bucketTypeNew {
  67. a.nNew++
  68. } else {
  69. a.nOld++
  70. }
  71. }
  72. return true
  73. }