nodeset.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "fmt"
  21. "io/ioutil"
  22. "sort"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/p2p/enode"
  25. )
  26. const jsonIndent = " "
  27. // nodeSet is the nodes.json file format. It holds a set of node records
  28. // as a JSON object.
  29. type nodeSet map[enode.ID]nodeJSON
  30. type nodeJSON struct {
  31. Seq uint64 `json:"seq"`
  32. N *enode.Node `json:"record"`
  33. }
  34. func loadNodesJSON(file string) nodeSet {
  35. var nodes nodeSet
  36. if err := common.LoadJSON(file, &nodes); err != nil {
  37. exit(err)
  38. }
  39. return nodes
  40. }
  41. func writeNodesJSON(file string, nodes nodeSet) {
  42. nodesJSON, err := json.MarshalIndent(nodes, "", jsonIndent)
  43. if err != nil {
  44. exit(err)
  45. }
  46. if err := ioutil.WriteFile(file, nodesJSON, 0644); err != nil {
  47. exit(err)
  48. }
  49. }
  50. func (ns nodeSet) nodes() []*enode.Node {
  51. result := make([]*enode.Node, 0, len(ns))
  52. for _, n := range ns {
  53. result = append(result, n.N)
  54. }
  55. // Sort by ID.
  56. sort.Slice(result, func(i, j int) bool {
  57. return bytes.Compare(result[i].ID().Bytes(), result[j].ID().Bytes()) < 0
  58. })
  59. return result
  60. }
  61. func (ns nodeSet) add(nodes ...*enode.Node) {
  62. for _, n := range nodes {
  63. ns[n.ID()] = nodeJSON{Seq: n.Seq(), N: n}
  64. }
  65. }
  66. func (ns nodeSet) verify() error {
  67. for id, n := range ns {
  68. if n.N.ID() != id {
  69. return fmt.Errorf("invalid node %v: ID does not match ID %v in record", id, n.N.ID())
  70. }
  71. if n.N.Seq() != n.Seq {
  72. return fmt.Errorf("invalid node %v: 'seq' does not match seq %d from record", id, n.N.Seq())
  73. }
  74. }
  75. return nil
  76. }