From 421c273a7c085c1fe70673091779671b1c621749 Mon Sep 17 00:00:00 2001 From: kozlov-oleksandr Date: Tue, 14 Aug 2018 10:52:14 +0300 Subject: [PATCH] Change NodeID to ESSNodeID --- eth/handler.go | 2 +- eth/helper_test.go | 2 +- eth/sync.go | 2 +- eth/sync_test.go | 4 +- les/handler.go | 2 +- les/helper_test.go | 4 +- les/serverpool.go | 12 +-- p2p/dial.go | 26 +++--- p2p/dial_test.go | 20 ++--- p2p/discover/database.go | 38 ++++----- p2p/discover/database_test.go | 22 ++--- p2p/discover/node.go | 64 +++++++-------- p2p/discover/node_test.go | 30 +++---- p2p/discover/table.go | 20 ++--- p2p/discover/table_test.go | 48 +++++------ p2p/discover/udp.go | 40 ++++----- p2p/discover/udp_test.go | 14 ++-- p2p/discv5/database.go | 44 +++++----- p2p/discv5/database_test.go | 22 ++--- p2p/discv5/net.go | 12 +-- p2p/discv5/net_test.go | 16 ++-- p2p/discv5/node.go | 44 +++++----- p2p/discv5/node_test.go | 24 +++--- p2p/discv5/sim_test.go | 12 +-- p2p/discv5/table.go | 2 +- p2p/discv5/table_test.go | 26 +++--- p2p/discv5/udp.go | 12 +-- p2p/discv5/udp_test.go | 6 +- p2p/message.go | 4 +- p2p/peer.go | 8 +- p2p/protocol.go | 2 +- p2p/protocols/protocol_test.go | 8 +- p2p/rlpx.go | 12 +-- p2p/rlpx_test.go | 2 +- p2p/server.go | 22 ++--- p2p/server_test.go | 24 +++--- p2p/simulations/adapters/docker.go | 2 +- p2p/simulations/adapters/exec.go | 8 +- p2p/simulations/adapters/inproc.go | 12 +-- p2p/simulations/adapters/types.go | 6 +- p2p/simulations/examples/ping-pong.go | 4 +- p2p/simulations/http_test.go | 8 +- p2p/simulations/mocker.go | 6 +- p2p/simulations/mocker_test.go | 2 +- p2p/simulations/network.go | 56 ++++++------- p2p/simulations/network_test.go | 8 +- p2p/simulations/simulation.go | 12 +-- p2p/testing/peerpool.go | 10 +-- p2p/testing/protocolsession.go | 14 ++-- p2p/testing/protocoltester.go | 6 +- swarm/api/config.go | 4 +- swarm/network/discovery.go | 4 +- swarm/network/discovery_test.go | 2 +- swarm/network/hive.go | 8 +- swarm/network/hive_test.go | 4 +- swarm/network/networkid_test.go | 18 ++-- swarm/network/protocol.go | 30 +++---- swarm/network/protocol_test.go | 20 ++--- swarm/network/simulation/bucket.go | 18 ++-- swarm/network/simulation/connect.go | 40 ++++----- swarm/network/simulation/connect_test.go | 8 +- swarm/network/simulation/events.go | 24 +++--- swarm/network/simulation/events_test.go | 6 +- swarm/network/simulation/example_test.go | 14 ++-- swarm/network/simulation/kademlia.go | 8 +- swarm/network/simulation/kademlia_test.go | 2 +- swarm/network/simulation/node.go | 82 +++++++++---------- swarm/network/simulation/node_test.go | 28 +++---- swarm/network/simulation/service.go | 6 +- swarm/network/simulation/simulation.go | 8 +- .../simulations/discovery/discovery_test.go | 16 ++-- swarm/network/simulations/overlay.go | 6 +- swarm/network/simulations/overlay_test.go | 4 +- swarm/network/stream/common_test.go | 20 ++--- swarm/network/stream/delivery.go | 4 +- swarm/network/stream/delivery_test.go | 28 +++---- swarm/network/stream/intervals_test.go | 10 +-- .../network/stream/snapshot_retrieval_test.go | 34 ++++---- swarm/network/stream/snapshot_sync_test.go | 42 +++++----- swarm/network/stream/stream.go | 22 ++--- swarm/network/stream/syncer.go | 2 +- swarm/network/stream/syncer_test.go | 20 ++--- swarm/network/stream/testing/testing.go | 14 ++-- swarm/network_test.go | 14 ++-- swarm/pss/client/client_test.go | 8 +- swarm/pss/notify/notify_test.go | 8 +- swarm/pss/pss.go | 2 +- swarm/pss/pss_test.go | 34 ++++---- swarm/pss/writeup.md | 2 +- swarm/swarm.go | 2 +- vendor/bazil.org/fuse/fs/serve.go | 32 ++++---- vendor/bazil.org/fuse/fuse.go | 38 ++++----- vendor/github.com/pborman/uuid/node.go | 26 +++--- vendor/github.com/pborman/uuid/version1.go | 6 +- 94 files changed, 767 insertions(+), 767 deletions(-) diff --git a/eth/handler.go b/eth/handler.go index f2d2eaf1c7..e70598624e 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -147,7 +147,7 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne NodeInfo: func() interface{} { return manager.NodeInfo() }, - PeerInfo: func(id discover.NodeID) interface{} { + PeerInfo: func(id discover.ESSNodeID) interface{} { if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil { return p.Info() } diff --git a/eth/helper_test.go b/eth/helper_test.go index 3d2ab0aba1..87e4c5cede 100644 --- a/eth/helper_test.go +++ b/eth/helper_test.go @@ -148,7 +148,7 @@ func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*te app, net := p2p.MsgPipe() // Generate a random id and create the peer - var id discover.NodeID + var id discover.ESSNodeID rand.Read(id[:]) peer := pm.newPeer(version, p2p.NewPeer(id, name, nil), net) diff --git a/eth/sync.go b/eth/sync.go index e49e40087e..1d0b0ae38e 100644 --- a/eth/sync.go +++ b/eth/sync.go @@ -64,7 +64,7 @@ func (pm *ProtocolManager) syncTransactions(p *peer) { // the transactions in small packs to one peer at a time. func (pm *ProtocolManager) txsyncLoop() { var ( - pending = make(map[discover.NodeID]*txsync) + pending = make(map[discover.ESSNodeID]*txsync) sending = false // whether a send is active pack = new(txsync) // the pack that is being sent done = make(chan error, 1) // result of the send diff --git a/eth/sync_test.go b/eth/sync_test.go index 88c10c7f74..985ba7efc1 100644 --- a/eth/sync_test.go +++ b/eth/sync_test.go @@ -42,8 +42,8 @@ func TestFastSyncDisabling(t *testing.T) { // Sync up the two peers io1, io2 := p2p.MsgPipe() - go pmFull.handle(pmFull.newPeer(63, p2p.NewPeer(discover.NodeID{}, "empty", nil), io2)) - go pmEmpty.handle(pmEmpty.newPeer(63, p2p.NewPeer(discover.NodeID{}, "full", nil), io1)) + go pmFull.handle(pmFull.newPeer(63, p2p.NewPeer(discover.ESSNodeID{}, "empty", nil), io2)) + go pmEmpty.handle(pmEmpty.newPeer(63, p2p.NewPeer(discover.ESSNodeID{}, "full", nil), io1)) time.Sleep(250 * time.Millisecond) pmEmpty.synchronise(pmEmpty.peers.BestPeer()) diff --git a/les/handler.go b/les/handler.go index a1c16cb875..a2a0068dc1 100644 --- a/les/handler.go +++ b/les/handler.go @@ -189,7 +189,7 @@ func NewProtocolManager(chainConfig *params.ChainConfig, lightSync bool, protoco NodeInfo: func() interface{} { return manager.NodeInfo() }, - PeerInfo: func(id discover.NodeID) interface{} { + PeerInfo: func(id discover.ESSNodeID) interface{} { if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil { return p.Info() } diff --git a/les/helper_test.go b/les/helper_test.go index 8fd01a39e0..429d6e3d73 100644 --- a/les/helper_test.go +++ b/les/helper_test.go @@ -223,7 +223,7 @@ func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, sh app, net := p2p.MsgPipe() // Generate a random id and create the peer - var id discover.NodeID + var id discover.ESSNodeID rand.Read(id[:]) peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) @@ -260,7 +260,7 @@ func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, app, net := p2p.MsgPipe() // Generate a random id and create the peer - var id discover.NodeID + var id discover.ESSNodeID rand.Read(id[:]) peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) diff --git a/les/serverpool.go b/les/serverpool.go index 1a4c752293..21c452455b 100644 --- a/les/serverpool.go +++ b/les/serverpool.go @@ -125,7 +125,7 @@ type serverPool struct { discNodes chan *discv5.Node discLookups chan bool - entries map[discover.NodeID]*poolEntry + entries map[discover.ESSNodeID]*poolEntry timeout, enableRetry chan *poolEntry adjustStats chan poolStatAdjust @@ -145,7 +145,7 @@ func newServerPool(db ethdb.Database, quit chan struct{}, wg *sync.WaitGroup) *s db: db, quit: quit, wg: wg, - entries: make(map[discover.NodeID]*poolEntry), + entries: make(map[discover.ESSNodeID]*poolEntry), timeout: make(chan *poolEntry, 1), adjustStats: make(chan poolStatAdjust, 100), enableRetry: make(chan *poolEntry, 1), @@ -320,7 +320,7 @@ func (pool *serverPool) eventLoop() { } case node := <-pool.discNodes: - entry := pool.findOrNewNode(discover.NodeID(node.ID), node.IP, node.TCP) + entry := pool.findOrNewNode(discover.ESSNodeID(node.ID), node.IP, node.TCP) pool.updateCheckDial(entry) case conv := <-pool.discLookups: @@ -401,7 +401,7 @@ func (pool *serverPool) eventLoop() { } } -func (pool *serverPool) findOrNewNode(id discover.NodeID, ip net.IP, port uint16) *poolEntry { +func (pool *serverPool) findOrNewNode(id discover.ESSNodeID, ip net.IP, port uint16) *poolEntry { now := mclock.Now() entry := pool.entries[id] if entry == nil { @@ -602,7 +602,7 @@ const ( // poolEntry represents a server node and stores its current state and statistics. type poolEntry struct { peer *peer - id discover.NodeID + id discover.ESSNodeID addr map[string]*poolEntryAddress lastConnected, dialed *poolEntryAddress addrSelect weightedRandomSelect @@ -626,7 +626,7 @@ func (e *poolEntry) EncodeRLP(w io.Writer) error { func (e *poolEntry) DecodeRLP(s *rlp.Stream) error { var entry struct { - ID discover.NodeID + ID discover.ESSNodeID IP net.IP Port uint16 Fails uint diff --git a/p2p/dial.go b/p2p/dial.go index d8feceb9f3..7f8b94445a 100644 --- a/p2p/dial.go +++ b/p2p/dial.go @@ -74,10 +74,10 @@ type dialstate struct { netrestrict *netutil.Netlist lookupRunning bool - dialing map[discover.NodeID]connFlag + dialing map[discover.ESSNodeID]connFlag lookupBuf []*discover.Node // current discovery lookup results randomNodes []*discover.Node // filled from Table - static map[discover.NodeID]*dialTask + static map[discover.ESSNodeID]*dialTask hist *dialHistory start time.Time // time when the dialer was first used @@ -87,8 +87,8 @@ type dialstate struct { type discoverTable interface { Self() *discover.Node Close() - Resolve(target discover.NodeID) *discover.Node - Lookup(target discover.NodeID) []*discover.Node + Resolve(target discover.ESSNodeID) *discover.Node + Lookup(target discover.ESSNodeID) []*discover.Node ReadRandomNodes([]*discover.Node) int } @@ -97,7 +97,7 @@ type dialHistory []pastDial // pastDial is an entry in the dial history. type pastDial struct { - id discover.NodeID + id discover.ESSNodeID exp time.Time } @@ -132,8 +132,8 @@ func newDialState(static []*discover.Node, bootnodes []*discover.Node, ntab disc maxDynDials: maxdyn, ntab: ntab, netrestrict: netrestrict, - static: make(map[discover.NodeID]*dialTask), - dialing: make(map[discover.NodeID]connFlag), + static: make(map[discover.ESSNodeID]*dialTask), + dialing: make(map[discover.ESSNodeID]connFlag), bootnodes: make([]*discover.Node, len(bootnodes)), randomNodes: make([]*discover.Node, maxdyn/2), hist: new(dialHistory), @@ -159,7 +159,7 @@ func (s *dialstate) removeStatic(n *discover.Node) { s.hist.remove(n.ID) } -func (s *dialstate) newTasks(nRunning int, peers map[discover.NodeID]*Peer, now time.Time) []task { +func (s *dialstate) newTasks(nRunning int, peers map[discover.ESSNodeID]*Peer, now time.Time) []task { if s.start.IsZero() { s.start = now } @@ -260,7 +260,7 @@ var ( errNotWhitelisted = errors.New("not contained in netrestrict whitelist") ) -func (s *dialstate) checkDial(n *discover.Node, peers map[discover.NodeID]*Peer) error { +func (s *dialstate) checkDial(n *discover.Node, peers map[discover.ESSNodeID]*Peer) error { _, dialing := s.dialing[n.ID] switch { case dialing: @@ -367,7 +367,7 @@ func (t *discoverTask) Do(srv *Server) { time.Sleep(next.Sub(now)) } srv.lastLookup = time.Now() - var target discover.NodeID + var target discover.ESSNodeID rand.Read(target[:]) t.results = srv.ntab.Lookup(target) } @@ -391,11 +391,11 @@ func (t waitExpireTask) String() string { func (h dialHistory) min() pastDial { return h[0] } -func (h *dialHistory) add(id discover.NodeID, exp time.Time) { +func (h *dialHistory) add(id discover.ESSNodeID, exp time.Time) { heap.Push(h, pastDial{id, exp}) } -func (h *dialHistory) remove(id discover.NodeID) bool { +func (h *dialHistory) remove(id discover.ESSNodeID) bool { for i, v := range *h { if v.id == id { heap.Remove(h, i) @@ -404,7 +404,7 @@ func (h *dialHistory) remove(id discover.NodeID) bool { } return false } -func (h dialHistory) contains(id discover.NodeID) bool { +func (h dialHistory) contains(id discover.ESSNodeID) bool { for _, v := range h { if v.id == id { return true diff --git a/p2p/dial_test.go b/p2p/dial_test.go index 2a7941fc65..06e90ff168 100644 --- a/p2p/dial_test.go +++ b/p2p/dial_test.go @@ -48,8 +48,8 @@ func runDialTest(t *testing.T, test dialtest) { vtime time.Time running int ) - pm := func(ps []*Peer) map[discover.NodeID]*Peer { - m := make(map[discover.NodeID]*Peer) + pm := func(ps []*Peer) map[discover.ESSNodeID]*Peer { + m := make(map[discover.ESSNodeID]*Peer) for _, p := range ps { m[p.rw.id] = p } @@ -80,8 +80,8 @@ type fakeTable []*discover.Node func (t fakeTable) Self() *discover.Node { return new(discover.Node) } func (t fakeTable) Close() {} -func (t fakeTable) Lookup(discover.NodeID) []*discover.Node { return nil } -func (t fakeTable) Resolve(discover.NodeID) *discover.Node { return nil } +func (t fakeTable) Lookup(discover.ESSNodeID) []*discover.Node { return nil } +func (t fakeTable) Resolve(discover.ESSNodeID) *discover.Node { return nil } func (t fakeTable) ReadRandomNodes(buf []*discover.Node) int { return copy(buf, t) } // This test checks that dynamic dials are launched from discovery results. @@ -644,7 +644,7 @@ func TestDialResolve(t *testing.T) { config := Config{Dialer: TCPDialer{&net.Dialer{Deadline: time.Now().Add(-5 * time.Minute)}}} srv := &Server{ntab: table, Config: config} tasks[0].Do(srv) - if !reflect.DeepEqual(table.resolveCalls, []discover.NodeID{dest.ID}) { + if !reflect.DeepEqual(table.resolveCalls, []discover.ESSNodeID{dest.ID}) { t.Fatalf("wrong resolve calls, got %v", table.resolveCalls) } @@ -672,19 +672,19 @@ next: return true } -func uintID(i uint32) discover.NodeID { - var id discover.NodeID +func uintID(i uint32) discover.ESSNodeID { + var id discover.ESSNodeID binary.BigEndian.PutUint32(id[:], i) return id } // implements discoverTable for TestDialResolve type resolveMock struct { - resolveCalls []discover.NodeID + resolveCalls []discover.ESSNodeID answer *discover.Node } -func (t *resolveMock) Resolve(id discover.NodeID) *discover.Node { +func (t *resolveMock) Resolve(id discover.ESSNodeID) *discover.Node { t.resolveCalls = append(t.resolveCalls, id) return t.answer } @@ -692,5 +692,5 @@ func (t *resolveMock) Resolve(id discover.NodeID) *discover.Node { func (t *resolveMock) Self() *discover.Node { return new(discover.Node) } func (t *resolveMock) Close() {} func (t *resolveMock) Bootstrap([]*discover.Node) {} -func (t *resolveMock) Lookup(discover.NodeID) []*discover.Node { return nil } +func (t *resolveMock) Lookup(discover.ESSNodeID) []*discover.Node { return nil } func (t *resolveMock) ReadRandomNodes(buf []*discover.Node) int { return 0 } diff --git a/p2p/discover/database.go b/p2p/discover/database.go index 22554145f4..c0d470f816 100644 --- a/p2p/discover/database.go +++ b/p2p/discover/database.go @@ -39,7 +39,7 @@ import ( ) var ( - nodeDBNilNodeID = NodeID{} // Special node ID to use as a nil element. + nodeDBNilESSNodeID = ESSNodeID{} // Special node ID to use as a nil element. nodeDBNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped. nodeDBCleanupCycle = time.Hour // Time period for running the expiration task. nodeDBVersion = 5 @@ -48,7 +48,7 @@ var ( // nodeDB stores all nodes we know about. type nodeDB struct { lvl *leveldb.DB // Interface to the database itself - self NodeID // Own node id to prevent adding it into the database + self ESSNodeID // Own node id to prevent adding it into the database runner sync.Once // Ensures we can start at most one expirer quit chan struct{} // Channel to signal the expiring thread to stop } @@ -67,7 +67,7 @@ var ( // newNodeDB creates a new node database for storing and retrieving infos about // known peers in the network. If no path is given, an in-memory, temporary // database is constructed. -func newNodeDB(path string, version int, self NodeID) (*nodeDB, error) { +func newNodeDB(path string, version int, self ESSNodeID) (*nodeDB, error) { if path == "" { return newMemoryNodeDB(self) } @@ -76,7 +76,7 @@ func newNodeDB(path string, version int, self NodeID) (*nodeDB, error) { // newMemoryNodeDB creates a new in-memory node database without a persistent // backend. -func newMemoryNodeDB(self NodeID) (*nodeDB, error) { +func newMemoryNodeDB(self ESSNodeID) (*nodeDB, error) { db, err := leveldb.Open(storage.NewMemStorage(), nil) if err != nil { return nil, err @@ -90,7 +90,7 @@ func newMemoryNodeDB(self NodeID) (*nodeDB, error) { // newPersistentNodeDB creates/opens a leveldb backed persistent node database, // also flushing its contents in case of a version mismatch. -func newPersistentNodeDB(path string, version int, self NodeID) (*nodeDB, error) { +func newPersistentNodeDB(path string, version int, self ESSNodeID) (*nodeDB, error) { opts := &opt.Options{OpenFilesCacheCapacity: 5} db, err := leveldb.OpenFile(path, opts) if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted { @@ -132,18 +132,18 @@ func newPersistentNodeDB(path string, version int, self NodeID) (*nodeDB, error) // makeKey generates the leveldb key-blob from a node id and its particular // field of interest. -func makeKey(id NodeID, field string) []byte { - if bytes.Equal(id[:], nodeDBNilNodeID[:]) { +func makeKey(id ESSNodeID, field string) []byte { + if bytes.Equal(id[:], nodeDBNilESSNodeID[:]) { return []byte(field) } return append(nodeDBItemPrefix, append(id[:], field...)...) } // splitKey tries to split a database key into a node id and a field part. -func splitKey(key []byte) (id NodeID, field string) { +func splitKey(key []byte) (id ESSNodeID, field string) { // If the key is not of a node, return it plainly if !bytes.HasPrefix(key, nodeDBItemPrefix) { - return NodeID{}, string(key) + return ESSNodeID{}, string(key) } // Otherwise split the id and field item := key[len(nodeDBItemPrefix):] @@ -177,7 +177,7 @@ func (db *nodeDB) storeInt64(key []byte, n int64) error { } // node retrieves a node with a given id from the database. -func (db *nodeDB) node(id NodeID) *Node { +func (db *nodeDB) node(id ESSNodeID) *Node { blob, err := db.lvl.Get(makeKey(id, nodeDBDiscoverRoot), nil) if err != nil { return nil @@ -201,7 +201,7 @@ func (db *nodeDB) updateNode(node *Node) error { } // deleteNode deletes all information/keys associated with a node. -func (db *nodeDB) deleteNode(id NodeID) error { +func (db *nodeDB) deleteNode(id ESSNodeID) error { deleter := db.lvl.NewIterator(util.BytesPrefix(makeKey(id, "")), nil) for deleter.Next() { if err := db.lvl.Delete(deleter.Key(), nil); err != nil { @@ -269,37 +269,37 @@ func (db *nodeDB) expireNodes() error { } // lastPingReceived retrieves the time of the last ping packet sent by the remote node. -func (db *nodeDB) lastPingReceived(id NodeID) time.Time { +func (db *nodeDB) lastPingReceived(id ESSNodeID) time.Time { return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPing)), 0) } // updateLastPing updates the last time remote node pinged us. -func (db *nodeDB) updateLastPingReceived(id NodeID, instance time.Time) error { +func (db *nodeDB) updateLastPingReceived(id ESSNodeID, instance time.Time) error { return db.storeInt64(makeKey(id, nodeDBDiscoverPing), instance.Unix()) } // lastPongReceived retrieves the time of the last successful pong from remote node. -func (db *nodeDB) lastPongReceived(id NodeID) time.Time { +func (db *nodeDB) lastPongReceived(id ESSNodeID) time.Time { return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPong)), 0) } // hasBond reports whether the given node is considered bonded. -func (db *nodeDB) hasBond(id NodeID) bool { +func (db *nodeDB) hasBond(id ESSNodeID) bool { return time.Since(db.lastPongReceived(id)) < nodeDBNodeExpiration } // updateLastPongReceived updates the last pong time of a node. -func (db *nodeDB) updateLastPongReceived(id NodeID, instance time.Time) error { +func (db *nodeDB) updateLastPongReceived(id ESSNodeID, instance time.Time) error { return db.storeInt64(makeKey(id, nodeDBDiscoverPong), instance.Unix()) } // findFails retrieves the number of findnode failures since bonding. -func (db *nodeDB) findFails(id NodeID) int { +func (db *nodeDB) findFails(id ESSNodeID) int { return int(db.fetchInt64(makeKey(id, nodeDBDiscoverFindFails))) } // updateFindFails updates the number of findnode failures since bonding. -func (db *nodeDB) updateFindFails(id NodeID, fails int) error { +func (db *nodeDB) updateFindFails(id ESSNodeID, fails int) error { return db.storeInt64(makeKey(id, nodeDBDiscoverFindFails), int64(fails)) } @@ -310,7 +310,7 @@ func (db *nodeDB) querySeeds(n int, maxAge time.Duration) []*Node { now = time.Now() nodes = make([]*Node, 0, n) it = db.lvl.NewIterator(nil, nil) - id NodeID + id ESSNodeID ) defer it.Release() diff --git a/p2p/discover/database_test.go b/p2p/discover/database_test.go index 27974344e0..436093317d 100644 --- a/p2p/discover/database_test.go +++ b/p2p/discover/database_test.go @@ -28,12 +28,12 @@ import ( ) var nodeDBKeyTests = []struct { - id NodeID + id ESSNodeID field string key []byte }{ { - id: NodeID{}, + id: ESSNodeID{}, field: "version", key: []byte{0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e}, // field }, @@ -79,7 +79,7 @@ var nodeDBInt64Tests = []struct { } func TestNodeDBInt64(t *testing.T) { - db, _ := newNodeDB("", nodeDBVersion, NodeID{}) + db, _ := newNodeDB("", nodeDBVersion, ESSNodeID{}) defer db.close() tests := nodeDBInt64Tests @@ -111,7 +111,7 @@ func TestNodeDBFetchStore(t *testing.T) { inst := time.Now() num := 314 - db, _ := newNodeDB("", nodeDBVersion, NodeID{}) + db, _ := newNodeDB("", nodeDBVersion, ESSNodeID{}) defer db.close() // Check fetch/store operations on a node ping object @@ -231,11 +231,11 @@ func TestNodeDBSeedQuery(t *testing.T) { // Retrieve the entire batch and check for duplicates seeds := db.querySeeds(len(nodeDBSeedQueryNodes)*2, time.Hour) - have := make(map[NodeID]struct{}) + have := make(map[ESSNodeID]struct{}) for _, seed := range seeds { have[seed.ID] = struct{}{} } - want := make(map[NodeID]struct{}) + want := make(map[ESSNodeID]struct{}) for _, seed := range nodeDBSeedQueryNodes[2:] { want[seed.node.ID] = struct{}{} } @@ -267,7 +267,7 @@ func TestNodeDBPersistency(t *testing.T) { ) // Create a persistent database and store some values - db, err := newNodeDB(filepath.Join(root, "database"), nodeDBVersion, NodeID{}) + db, err := newNodeDB(filepath.Join(root, "database"), nodeDBVersion, ESSNodeID{}) if err != nil { t.Fatalf("failed to create persistent database: %v", err) } @@ -277,7 +277,7 @@ func TestNodeDBPersistency(t *testing.T) { db.close() // Reopen the database and check the value - db, err = newNodeDB(filepath.Join(root, "database"), nodeDBVersion, NodeID{}) + db, err = newNodeDB(filepath.Join(root, "database"), nodeDBVersion, ESSNodeID{}) if err != nil { t.Fatalf("failed to open persistent database: %v", err) } @@ -287,7 +287,7 @@ func TestNodeDBPersistency(t *testing.T) { db.close() // Change the database version and check flush - db, err = newNodeDB(filepath.Join(root, "database"), nodeDBVersion+1, NodeID{}) + db, err = newNodeDB(filepath.Join(root, "database"), nodeDBVersion+1, ESSNodeID{}) if err != nil { t.Fatalf("failed to open persistent database: %v", err) } @@ -324,7 +324,7 @@ var nodeDBExpirationNodes = []struct { } func TestNodeDBExpiration(t *testing.T) { - db, _ := newNodeDB("", nodeDBVersion, NodeID{}) + db, _ := newNodeDB("", nodeDBVersion, ESSNodeID{}) defer db.close() // Add all the test nodes and set their last pong time @@ -350,7 +350,7 @@ func TestNodeDBExpiration(t *testing.T) { func TestNodeDBSelfExpiration(t *testing.T) { // Find a node in the tests that shouldn't expire, and assign it as self - var self NodeID + var self ESSNodeID for _, node := range nodeDBExpirationNodes { if !node.exp { self = node.node.ID diff --git a/p2p/discover/node.go b/p2p/discover/node.go index 3b0c84115c..6c01c4034c 100644 --- a/p2p/discover/node.go +++ b/p2p/discover/node.go @@ -36,14 +36,14 @@ import ( "github.com/ethereum/go-ethereum/crypto/secp256k1" ) -const NodeIDBits = 512 +const ESSNodeIDBits = 512 // Node represents a host on the network. // The fields of Node may not be modified. type Node struct { IP net.IP // len 4 for IPv4 or 16 for IPv6 UDP, TCP uint16 // port numbers - ID NodeID // the node's public key + ID ESSNodeID // the node's public key // This is a cached copy of sha3(ID) which is used for node // distance calculations. This is part of Node in order to make it @@ -58,7 +58,7 @@ type Node struct { // NewNode creates a new node. It is mostly meant to be used for // testing purposes. -func NewNode(id NodeID, ip net.IP, udpPort, tcpPort uint16) *Node { +func NewNode(id ESSNodeID, ip net.IP, udpPort, tcpPort uint16) *Node { if ipv4 := ip.To4(); ipv4 != nil { ip = ipv4 } @@ -153,7 +153,7 @@ func ParseNode(rawurl string) (*Node, error) { func parseComplete(rawurl string) (*Node, error) { var ( - id NodeID + id ESSNodeID ip net.IP tcpPort, udpPort uint64 ) @@ -221,37 +221,37 @@ func (n *Node) UnmarshalText(text []byte) error { return err } -// NodeID is a unique identifier for each node. +// ESSNodeID is a unique identifier for each node. // The node identifier is a marshaled elliptic curve public key. -type NodeID [NodeIDBits / 8]byte +type ESSNodeID [ESSNodeIDBits / 8]byte -// Bytes returns a byte slice representation of the NodeID -func (n NodeID) Bytes() []byte { +// Bytes returns a byte slice representation of the ESSNodeID +func (n ESSNodeID) Bytes() []byte { return n[:] } -// NodeID prints as a long hexadecimal number. -func (n NodeID) String() string { +// ESSNodeID prints as a long hexadecimal number. +func (n ESSNodeID) String() string { return fmt.Sprintf("%x", n[:]) } -// The Go syntax representation of a NodeID is a call to HexID. -func (n NodeID) GoString() string { +// The Go syntax representation of a ESSNodeID is a call to HexID. +func (n ESSNodeID) GoString() string { return fmt.Sprintf("discover.HexID(\"%x\")", n[:]) } // TerminalString returns a shortened hex string for terminal logging. -func (n NodeID) TerminalString() string { +func (n ESSNodeID) TerminalString() string { return hex.EncodeToString(n[:8]) } // MarshalText implements the encoding.TextMarshaler interface. -func (n NodeID) MarshalText() ([]byte, error) { +func (n ESSNodeID) MarshalText() ([]byte, error) { return []byte(hex.EncodeToString(n[:])), nil } // UnmarshalText implements the encoding.TextUnmarshaler interface. -func (n *NodeID) UnmarshalText(text []byte) error { +func (n *ESSNodeID) UnmarshalText(text []byte) error { id, err := HexID(string(text)) if err != nil { return err @@ -260,9 +260,9 @@ func (n *NodeID) UnmarshalText(text []byte) error { return nil } -// BytesID converts a byte slice to a NodeID -func BytesID(b []byte) (NodeID, error) { - var id NodeID +// BytesID converts a byte slice to a ESSNodeID +func BytesID(b []byte) (ESSNodeID, error) { + var id ESSNodeID if len(b) != len(id) { return id, fmt.Errorf("wrong length, want %d bytes", len(id)) } @@ -270,9 +270,9 @@ func BytesID(b []byte) (NodeID, error) { return id, nil } -// MustBytesID converts a byte slice to a NodeID. -// It panics if the byte slice is not a valid NodeID. -func MustBytesID(b []byte) NodeID { +// MustBytesID converts a byte slice to a ESSNodeID. +// It panics if the byte slice is not a valid ESSNodeID. +func MustBytesID(b []byte) ESSNodeID { id, err := BytesID(b) if err != nil { panic(err) @@ -280,10 +280,10 @@ func MustBytesID(b []byte) NodeID { return id } -// HexID converts a hex string to a NodeID. +// HexID converts a hex string to a ESSNodeID. // The string may be prefixed with 0x. -func HexID(in string) (NodeID, error) { - var id NodeID +func HexID(in string) (ESSNodeID, error) { + var id ESSNodeID b, err := hex.DecodeString(strings.TrimPrefix(in, "0x")) if err != nil { return id, err @@ -294,9 +294,9 @@ func HexID(in string) (NodeID, error) { return id, nil } -// MustHexID converts a hex string to a NodeID. -// It panics if the string is not a valid NodeID. -func MustHexID(in string) NodeID { +// MustHexID converts a hex string to a ESSNodeID. +// It panics if the string is not a valid ESSNodeID. +func MustHexID(in string) ESSNodeID { id, err := HexID(in) if err != nil { panic(err) @@ -305,8 +305,8 @@ func MustHexID(in string) NodeID { } // PubkeyID returns a marshaled representation of the given public key. -func PubkeyID(pub *ecdsa.PublicKey) NodeID { - var id NodeID +func PubkeyID(pub *ecdsa.PublicKey) ESSNodeID { + var id ESSNodeID pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y) if len(pbytes)-1 != len(id) { panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes))) @@ -317,7 +317,7 @@ func PubkeyID(pub *ecdsa.PublicKey) NodeID { // Pubkey returns the public key represented by the node ID. // It returns an error if the ID is not a point on the curve. -func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) { +func (id ESSNodeID) Pubkey() (*ecdsa.PublicKey, error) { p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)} half := len(id) / 2 p.X.SetBytes(id[:half]) @@ -328,9 +328,9 @@ func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) { return p, nil } -// recoverNodeID computes the public key used to sign the +// recoverESSNodeID computes the public key used to sign the // given hash from the signature. -func recoverNodeID(hash, sig []byte) (id NodeID, err error) { +func recoverESSNodeID(hash, sig []byte) (id ESSNodeID, err error) { pubkey, err := secp256k1.RecoverPubkey(hash, sig) if err != nil { return id, err diff --git a/p2p/discover/node_test.go b/p2p/discover/node_test.go index ed8db4dc65..6372f0e6e5 100644 --- a/p2p/discover/node_test.go +++ b/p2p/discover/node_test.go @@ -181,7 +181,7 @@ func TestNodeString(t *testing.T) { } func TestHexID(t *testing.T) { - ref := NodeID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 106, 217, 182, 31, 165, 174, 1, 67, 7, 235, 220, 150, 66, 83, 173, 205, 159, 44, 10, 57, 42, 161, 26, 188} + ref := ESSNodeID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 106, 217, 182, 31, 165, 174, 1, 67, 7, 235, 220, 150, 66, 83, 173, 205, 159, 44, 10, 57, 42, 161, 26, 188} id1 := MustHexID("0x000000000000000000000000000000000000000000000000000000000000000000000000000000806ad9b61fa5ae014307ebdc964253adcd9f2c0a392aa11abc") id2 := MustHexID("000000000000000000000000000000000000000000000000000000000000000000000000000000806ad9b61fa5ae014307ebdc964253adcd9f2c0a392aa11abc") @@ -193,8 +193,8 @@ func TestHexID(t *testing.T) { } } -func TestNodeID_textEncoding(t *testing.T) { - ref := NodeID{ +func TestESSNodeID_textEncoding(t *testing.T) { + ref := ESSNodeID{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x30, @@ -213,7 +213,7 @@ func TestNodeID_textEncoding(t *testing.T) { t.Fatalf("text encoding did not match\nexpected: %s\ngot: %s", hex, text) } - id := new(NodeID) + id := new(ESSNodeID) if err := id.UnmarshalText(text); err != nil { t.Fatal(err) } @@ -222,7 +222,7 @@ func TestNodeID_textEncoding(t *testing.T) { } } -func TestNodeID_recover(t *testing.T) { +func TestESSNodeID_recover(t *testing.T) { prv := newkey() hash := make([]byte, 32) sig, err := crypto.Sign(hash, prv) @@ -231,7 +231,7 @@ func TestNodeID_recover(t *testing.T) { } pub := PubkeyID(&prv.PublicKey) - recpub, err := recoverNodeID(hash, sig) + recpub, err := recoverESSNodeID(hash, sig) if err != nil { t.Fatalf("recovery error: %v", err) } @@ -248,8 +248,8 @@ func TestNodeID_recover(t *testing.T) { } } -func TestNodeID_pubkeyBad(t *testing.T) { - ecdsa, err := NodeID{}.Pubkey() +func TestESSNodeID_pubkeyBad(t *testing.T) { + ecdsa, err := ESSNodeID{}.Pubkey() if err == nil { t.Error("expected error for zero ID") } @@ -258,7 +258,7 @@ func TestNodeID_pubkeyBad(t *testing.T) { } } -func TestNodeID_distcmp(t *testing.T) { +func TestESSNodeID_distcmp(t *testing.T) { distcmpBig := func(target, a, b common.Hash) int { tbig := new(big.Int).SetBytes(target[:]) abig := new(big.Int).SetBytes(a[:]) @@ -271,7 +271,7 @@ func TestNodeID_distcmp(t *testing.T) { } // the random tests is likely to miss the case where they're equal. -func TestNodeID_distcmpEqual(t *testing.T) { +func TestESSNodeID_distcmpEqual(t *testing.T) { base := common.Hash{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} x := common.Hash{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0} if distcmp(base, x, x) != 0 { @@ -279,7 +279,7 @@ func TestNodeID_distcmpEqual(t *testing.T) { } } -func TestNodeID_logdist(t *testing.T) { +func TestESSNodeID_logdist(t *testing.T) { logdistBig := func(a, b common.Hash) int { abig, bbig := new(big.Int).SetBytes(a[:]), new(big.Int).SetBytes(b[:]) return new(big.Int).Xor(abig, bbig).BitLen() @@ -290,14 +290,14 @@ func TestNodeID_logdist(t *testing.T) { } // the random tests is likely to miss the case where they're equal. -func TestNodeID_logdistEqual(t *testing.T) { +func TestESSNodeID_logdistEqual(t *testing.T) { x := common.Hash{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} if logdist(x, x) != 0 { t.Errorf("logdist(x, x) != 0") } } -func TestNodeID_hashAtDistance(t *testing.T) { +func TestESSNodeID_hashAtDistance(t *testing.T) { // we don't use quick.Check here because its output isn't // very helpful when the test fails. cfg := quickcfg() @@ -325,8 +325,8 @@ func quickcfg() *quick.Config { // TODO: The Generate method can be dropped when we require Go >= 1.5 // because testing/quick learned to generate arrays in 1.5. -func (NodeID) Generate(rand *rand.Rand, size int) reflect.Value { - var id NodeID +func (ESSNodeID) Generate(rand *rand.Rand, size int) reflect.Value { + var id ESSNodeID m := rand.Intn(len(id)) for i := len(id) - 1; i > m; i-- { id[i] = byte(rand.Uint32()) diff --git a/p2p/discover/table.go b/p2p/discover/table.go index 8803daa56e..3a9743363f 100644 --- a/p2p/discover/table.go +++ b/p2p/discover/table.go @@ -85,8 +85,8 @@ type Table struct { // it is an interface so we can test without opening lots of UDP // sockets and without generating a private key. type transport interface { - ping(NodeID, *net.UDPAddr) error - findnode(toid NodeID, addr *net.UDPAddr, target NodeID) ([]*Node, error) + ping(ESSNodeID, *net.UDPAddr) error + findnode(toid ESSNodeID, addr *net.UDPAddr, target ESSNodeID) ([]*Node, error) close() } @@ -98,7 +98,7 @@ type bucket struct { ips netutil.DistinctNetSet } -func newTable(t transport, ourID NodeID, ourAddr *net.UDPAddr, nodeDBPath string, bootnodes []*Node) (*Table, error) { +func newTable(t transport, ourID ESSNodeID, ourAddr *net.UDPAddr, nodeDBPath string, bootnodes []*Node) (*Table, error) { // If no node database was given, use an in-memory one db, err := newNodeDB(nodeDBPath, nodeDBVersion, ourID) if err != nil { @@ -231,7 +231,7 @@ func (tab *Table) isInitDone() bool { // Resolve searches for a specific node with the given ID. // It returns nil if the node could not be found. -func (tab *Table) Resolve(targetID NodeID) *Node { +func (tab *Table) Resolve(targetID ESSNodeID) *Node { // If the node is present in the local table, no // network interaction is required. hash := crypto.Keccak256Hash(targetID[:]) @@ -256,15 +256,15 @@ func (tab *Table) Resolve(targetID NodeID) *Node { // nodes that are closer to it on each iteration. // The given target does not need to be an actual node // identifier. -func (tab *Table) Lookup(targetID NodeID) []*Node { +func (tab *Table) Lookup(targetID ESSNodeID) []*Node { return tab.lookup(targetID, true) } -func (tab *Table) lookup(targetID NodeID, refreshIfEmpty bool) []*Node { +func (tab *Table) lookup(targetID ESSNodeID, refreshIfEmpty bool) []*Node { var ( target = crypto.Keccak256Hash(targetID[:]) - asked = make(map[NodeID]bool) - seen = make(map[NodeID]bool) + asked = make(map[ESSNodeID]bool) + seen = make(map[ESSNodeID]bool) reply = make(chan []*Node, alpha) pendingQueries = 0 result *nodesByDistance @@ -315,7 +315,7 @@ func (tab *Table) lookup(targetID NodeID, refreshIfEmpty bool) []*Node { return result.entries } -func (tab *Table) findnode(n *Node, targetID NodeID, reply chan<- []*Node) { +func (tab *Table) findnode(n *Node, targetID ESSNodeID, reply chan<- []*Node) { fails := tab.db.findFails(n.ID) r, err := tab.net.findnode(n.ID, n.addr(), targetID) if err != nil || len(r) == 0 { @@ -430,7 +430,7 @@ func (tab *Table) doRefresh(done chan struct{}) { // sha3 preimage that falls into a chosen bucket. // We perform a few lookups with a random target instead. for i := 0; i < 3; i++ { - var target NodeID + var target ESSNodeID crand.Read(target[:]) tab.lookup(target, false) } diff --git a/p2p/discover/table_test.go b/p2p/discover/table_test.go index ed55ebd9a9..2ceba9d063 100644 --- a/p2p/discover/table_test.go +++ b/p2p/discover/table_test.go @@ -49,7 +49,7 @@ func TestTable_pingReplace(t *testing.T) { func testPingReplace(t *testing.T, newNodeIsResponding, lastInBucketIsResponding bool) { transport := newPingRecorder() - tab, _ := newTable(transport, NodeID{}, &net.UDPAddr{}, "", nil) + tab, _ := newTable(transport, ESSNodeID{}, &net.UDPAddr{}, "", nil) defer tab.Close() <-tab.initDone @@ -134,7 +134,7 @@ func TestBucket_bumpNoDuplicates(t *testing.T) { // This checks that the table-wide IP limit is applied correctly. func TestTable_IPLimit(t *testing.T) { transport := newPingRecorder() - tab, _ := newTable(transport, NodeID{}, &net.UDPAddr{}, "", nil) + tab, _ := newTable(transport, ESSNodeID{}, &net.UDPAddr{}, "", nil) defer tab.Close() for i := 0; i < tableIPLimit+1; i++ { @@ -150,7 +150,7 @@ func TestTable_IPLimit(t *testing.T) { // This checks that the table-wide IP limit is applied correctly. func TestTable_BucketIPLimit(t *testing.T) { transport := newPingRecorder() - tab, _ := newTable(transport, NodeID{}, &net.UDPAddr{}, "", nil) + tab, _ := newTable(transport, ESSNodeID{}, &net.UDPAddr{}, "", nil) defer tab.Close() d := 3 @@ -188,21 +188,21 @@ func nodeAtDistance(base common.Hash, ld int) (n *Node) { type pingRecorder struct { mu sync.Mutex - dead, pinged map[NodeID]bool + dead, pinged map[ESSNodeID]bool } func newPingRecorder() *pingRecorder { return &pingRecorder{ - dead: make(map[NodeID]bool), - pinged: make(map[NodeID]bool), + dead: make(map[ESSNodeID]bool), + pinged: make(map[ESSNodeID]bool), } } -func (t *pingRecorder) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { +func (t *pingRecorder) findnode(toid ESSNodeID, toaddr *net.UDPAddr, target ESSNodeID) ([]*Node, error) { return nil, nil } -func (t *pingRecorder) ping(toid NodeID, toaddr *net.UDPAddr) error { +func (t *pingRecorder) ping(toid ESSNodeID, toaddr *net.UDPAddr) error { t.mu.Lock() defer t.mu.Unlock() @@ -282,7 +282,7 @@ func TestTable_ReadRandomNodesGetAll(t *testing.T) { } test := func(buf []*Node) bool { transport := newPingRecorder() - tab, _ := newTable(transport, NodeID{}, &net.UDPAddr{}, "", nil) + tab, _ := newTable(transport, ESSNodeID{}, &net.UDPAddr{}, "", nil) defer tab.Close() <-tab.initDone @@ -307,7 +307,7 @@ func TestTable_ReadRandomNodesGetAll(t *testing.T) { } type closeTest struct { - Self NodeID + Self ESSNodeID Target common.Hash All []*Node N int @@ -315,11 +315,11 @@ type closeTest struct { func (*closeTest) Generate(rand *rand.Rand, size int) reflect.Value { t := &closeTest{ - Self: gen(NodeID{}, rand).(NodeID), + Self: gen(ESSNodeID{}, rand).(ESSNodeID), Target: gen(common.Hash{}, rand).(common.Hash), N: rand.Intn(bucketSize), } - for _, id := range gen([]NodeID{}, rand).([]NodeID) { + for _, id := range gen([]ESSNodeID{}, rand).([]ESSNodeID) { t.All = append(t.All, &Node{ID: id}) } return reflect.ValueOf(t) @@ -356,11 +356,11 @@ func TestTable_Lookup(t *testing.T) { } // This is the test network for the Lookup test. -// The nodes were obtained by running testnet.mine with a random NodeID as target. +// The nodes were obtained by running testnet.mine with a random ESSNodeID as target. var lookupTestnet = &preminedTestnet{ target: MustHexID("166aea4f556532c6d34e8b740e5d314af7e9ac0ca79833bd751d6b665f12dfd38ec563c363b32f02aef4a80b44fd3def94612d497b99cb5f17fd24de454927ec"), targetSha: common.Hash{0x5c, 0x94, 0x4e, 0xe5, 0x1c, 0x5a, 0xe9, 0xf7, 0x2a, 0x95, 0xec, 0xcb, 0x8a, 0xed, 0x3, 0x74, 0xee, 0xcb, 0x51, 0x19, 0xd7, 0x20, 0xcb, 0xea, 0x68, 0x13, 0xe8, 0xe0, 0xd6, 0xad, 0x92, 0x61}, - dists: [257][]NodeID{ + dists: [257][]ESSNodeID{ 240: { MustHexID("2001ad5e3e80c71b952161bc0186731cf5ffe942d24a79230a0555802296238e57ea7a32f5b6f18564eadc1c65389448481f8c9338df0a3dbd18f708cbc2cbcb"), MustHexID("6ba3f4f57d084b6bf94cc4555b8c657e4a8ac7b7baf23c6874efc21dd1e4f56b7eb2721e07f5242d2f1d8381fc8cae535e860197c69236798ba1ad231b105794"), @@ -551,12 +551,12 @@ var lookupTestnet = &preminedTestnet{ } type preminedTestnet struct { - target NodeID + target ESSNodeID targetSha common.Hash // sha3(target) - dists [hashBits + 1][]NodeID + dists [hashBits + 1][]ESSNodeID } -func (tn *preminedTestnet) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { +func (tn *preminedTestnet) findnode(toid ESSNodeID, toaddr *net.UDPAddr, target ESSNodeID) ([]*Node, error) { // current log distance is encoded in port number // fmt.Println("findnode query at dist", toaddr.Port) if toaddr.Port == 0 { @@ -571,12 +571,12 @@ func (tn *preminedTestnet) findnode(toid NodeID, toaddr *net.UDPAddr, target Nod } func (*preminedTestnet) close() {} -func (*preminedTestnet) waitping(from NodeID) error { return nil } -func (*preminedTestnet) ping(toid NodeID, toaddr *net.UDPAddr) error { return nil } +func (*preminedTestnet) waitping(from ESSNodeID) error { return nil } +func (*preminedTestnet) ping(toid ESSNodeID, toaddr *net.UDPAddr) error { return nil } // mine generates a testnet struct literal with nodes at // various distances to the given target. -func (tn *preminedTestnet) mine(target NodeID) { +func (tn *preminedTestnet) mine(target ESSNodeID) { tn.target = target tn.targetSha = crypto.Keccak256Hash(tn.target[:]) found := 0 @@ -594,12 +594,12 @@ func (tn *preminedTestnet) mine(target NodeID) { fmt.Println("&preminedTestnet{") fmt.Printf(" target: %#v,\n", tn.target) fmt.Printf(" targetSha: %#v,\n", tn.targetSha) - fmt.Printf(" dists: [%d][]NodeID{\n", len(tn.dists)) + fmt.Printf(" dists: [%d][]ESSNodeID{\n", len(tn.dists)) for ld, ns := range tn.dists { if len(ns) == 0 { continue } - fmt.Printf(" %d: []NodeID{\n", ld) + fmt.Printf(" %d: []ESSNodeID{\n", ld) for _, n := range ns { fmt.Printf(" MustHexID(\"%x\"),\n", n[:]) } @@ -610,7 +610,7 @@ func (tn *preminedTestnet) mine(target NodeID) { } func hasDuplicates(slice []*Node) bool { - seen := make(map[NodeID]bool) + seen := make(map[ESSNodeID]bool) for i, e := range slice { if e == nil { panic(fmt.Sprintf("nil *Node at %d", i)) @@ -634,7 +634,7 @@ func sortedByDistanceTo(distbase common.Hash, slice []*Node) bool { return true } -func contains(ns []*Node, id NodeID) bool { +func contains(ns []*Node, id ESSNodeID) bool { for _, n := range ns { if n.ID == id { return true diff --git a/p2p/discover/udp.go b/p2p/discover/udp.go index 0ff47c5e46..7d79181e27 100644 --- a/p2p/discover/udp.go +++ b/p2p/discover/udp.go @@ -87,7 +87,7 @@ type ( // findnode is a query for nodes close to the given target. findnode struct { - Target NodeID // doesn't need to be an actual public key + Target ESSNodeID // doesn't need to be an actual public key Expiration uint64 // Ignore additional fields (for forward compatibility). Rest []rlp.RawValue `rlp:"tail"` @@ -105,7 +105,7 @@ type ( IP net.IP // len 4 for IPv4 or 16 for IPv6 UDP uint16 // for discovery protocol TCP uint16 // for RLPx protocol - ID NodeID + ID ESSNodeID } rpcEndpoint struct { @@ -143,7 +143,7 @@ func nodeToRPC(n *Node) rpcNode { } type packet interface { - handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error + handle(t *udp, from *net.UDPAddr, fromID ESSNodeID, mac []byte) error name() string } @@ -181,7 +181,7 @@ type udp struct { // to all the callback functions for that node. type pending struct { // these fields must match in the reply. - from NodeID + from ESSNodeID ptype byte // time when the request must complete @@ -199,7 +199,7 @@ type pending struct { } type reply struct { - from NodeID + from ESSNodeID ptype byte data interface{} // loop indicates whether there was @@ -269,13 +269,13 @@ func (t *udp) close() { } // ping sends a ping message to the given node and waits for a reply. -func (t *udp) ping(toid NodeID, toaddr *net.UDPAddr) error { +func (t *udp) ping(toid ESSNodeID, toaddr *net.UDPAddr) error { return <-t.sendPing(toid, toaddr, nil) } // sendPing sends a ping message to the given node and invokes the callback // when the reply arrives. -func (t *udp) sendPing(toid NodeID, toaddr *net.UDPAddr, callback func()) <-chan error { +func (t *udp) sendPing(toid ESSNodeID, toaddr *net.UDPAddr, callback func()) <-chan error { req := &ping{ Version: 4, From: t.ourEndpoint, @@ -299,13 +299,13 @@ func (t *udp) sendPing(toid NodeID, toaddr *net.UDPAddr, callback func()) <-chan return errc } -func (t *udp) waitping(from NodeID) error { +func (t *udp) waitping(from ESSNodeID) error { return <-t.pending(from, pingPacket, func(interface{}) bool { return true }) } // findnode sends a findnode request to the given node and waits until // the node has sent up to k neighbors. -func (t *udp) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { +func (t *udp) findnode(toid ESSNodeID, toaddr *net.UDPAddr, target ESSNodeID) ([]*Node, error) { // If we haven't seen a ping from the destination node for a while, it won't remember // our endpoint proof and reject findnode. Solicit a ping first. if time.Since(t.db.lastPingReceived(toid)) > nodeDBNodeExpiration { @@ -337,7 +337,7 @@ func (t *udp) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node // pending adds a reply callback to the pending reply queue. // see the documentation of type pending for a detailed explanation. -func (t *udp) pending(id NodeID, ptype byte, callback func(interface{}) bool) <-chan error { +func (t *udp) pending(id ESSNodeID, ptype byte, callback func(interface{}) bool) <-chan error { ch := make(chan error, 1) p := &pending{from: id, ptype: ptype, callback: callback, errc: ch} select { @@ -349,7 +349,7 @@ func (t *udp) pending(id NodeID, ptype byte, callback func(interface{}) bool) <- return ch } -func (t *udp) handleReply(from NodeID, ptype byte, req packet) bool { +func (t *udp) handleReply(from ESSNodeID, ptype byte, req packet) bool { matched := make(chan bool, 1) select { case t.gotreply <- reply{from, ptype, req, matched}: @@ -563,18 +563,18 @@ func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error { return err } -func decodePacket(buf []byte) (packet, NodeID, []byte, error) { +func decodePacket(buf []byte) (packet, ESSNodeID, []byte, error) { if len(buf) < headSize+1 { - return nil, NodeID{}, nil, errPacketTooSmall + return nil, ESSNodeID{}, nil, errPacketTooSmall } hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:] shouldhash := crypto.Keccak256(buf[macSize:]) if !bytes.Equal(hash, shouldhash) { - return nil, NodeID{}, nil, errBadHash + return nil, ESSNodeID{}, nil, errBadHash } - fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig) + fromID, err := recoverESSNodeID(crypto.Keccak256(buf[headSize:]), sig) if err != nil { - return nil, NodeID{}, hash, err + return nil, ESSNodeID{}, hash, err } var req packet switch ptype := sigdata[0]; ptype { @@ -594,7 +594,7 @@ func decodePacket(buf []byte) (packet, NodeID, []byte, error) { return req, fromID, hash, err } -func (req *ping) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { +func (req *ping) handle(t *udp, from *net.UDPAddr, fromID ESSNodeID, mac []byte) error { if expired(req.Expiration) { return errExpired } @@ -619,7 +619,7 @@ func (req *ping) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) er func (req *ping) name() string { return "PING/v4" } -func (req *pong) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { +func (req *pong) handle(t *udp, from *net.UDPAddr, fromID ESSNodeID, mac []byte) error { if expired(req.Expiration) { return errExpired } @@ -632,7 +632,7 @@ func (req *pong) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) er func (req *pong) name() string { return "PONG/v4" } -func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { +func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID ESSNodeID, mac []byte) error { if expired(req.Expiration) { return errExpired } @@ -672,7 +672,7 @@ func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte func (req *findnode) name() string { return "FINDNODE/v4" } -func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { +func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID ESSNodeID, mac []byte) error { if expired(req.Expiration) { return errExpired } diff --git a/p2p/discover/udp_test.go b/p2p/discover/udp_test.go index b4363a12b8..35a80970ed 100644 --- a/p2p/discover/udp_test.go +++ b/p2p/discover/udp_test.go @@ -46,7 +46,7 @@ func init() { // shared test variables var ( futureExp = uint64(time.Now().Add(10 * time.Hour).Unix()) - testTarget = NodeID{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1} + testTarget = ESSNodeID{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1} testRemote = rpcEndpoint{IP: net.ParseIP("1.1.1.1").To4(), UDP: 1, TCP: 2} testLocalAnnounced = rpcEndpoint{IP: net.ParseIP("2.2.2.2").To4(), UDP: 3, TCP: 4} testLocal = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6} @@ -136,7 +136,7 @@ func TestUDP_pingTimeout(t *testing.T) { defer test.table.Close() toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222} - toid := NodeID{1, 2, 3, 4} + toid := ESSNodeID{1, 2, 3, 4} if err := test.udp.ping(toid, toaddr); err != errTimeout { t.Error("expected timeout error, got", err) } @@ -220,8 +220,8 @@ func TestUDP_findnodeTimeout(t *testing.T) { defer test.table.Close() toaddr := &net.UDPAddr{IP: net.ParseIP("1.2.3.4"), Port: 2222} - toid := NodeID{1, 2, 3, 4} - target := NodeID{4, 5, 6, 7} + toid := ESSNodeID{1, 2, 3, 4} + target := ESSNodeID{4, 5, 6, 7} result, err := test.udp.findnode(toid, toaddr, target) if err != errTimeout { t.Error("expected timeout error, got", err) @@ -476,7 +476,7 @@ var testPackets = []struct { func TestForwardCompatibility(t *testing.T) { testkey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - wantNodeID := PubkeyID(&testkey.PublicKey) + wantESSNodeID := PubkeyID(&testkey.PublicKey) for _, test := range testPackets { input, err := hex.DecodeString(test.input) @@ -491,8 +491,8 @@ func TestForwardCompatibility(t *testing.T) { if !reflect.DeepEqual(packet, test.wantPacket) { t.Errorf("got %s\nwant %s", spew.Sdump(packet), spew.Sdump(test.wantPacket)) } - if nodeid != wantNodeID { - t.Errorf("got id %v\nwant id %v", nodeid, wantNodeID) + if nodeid != wantESSNodeID { + t.Errorf("got id %v\nwant id %v", nodeid, wantESSNodeID) } } } diff --git a/p2p/discv5/database.go b/p2p/discv5/database.go index 3c2d5744c3..fbe4cd9ca5 100644 --- a/p2p/discv5/database.go +++ b/p2p/discv5/database.go @@ -40,7 +40,7 @@ import ( ) var ( - nodeDBNilNodeID = NodeID{} // Special node ID to use as a nil element. + nodeDBNilESSNodeID = ESSNodeID{} // Special node ID to use as a nil element. nodeDBNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped. nodeDBCleanupCycle = time.Hour // Time period for running the expiration task. ) @@ -48,7 +48,7 @@ var ( // nodeDB stores all nodes we know about. type nodeDB struct { lvl *leveldb.DB // Interface to the database itself - self NodeID // Own node id to prevent adding it into the database + self ESSNodeID // Own node id to prevent adding it into the database runner sync.Once // Ensures we can start at most one expirer quit chan struct{} // Channel to signal the expiring thread to stop } @@ -69,7 +69,7 @@ var ( // newNodeDB creates a new node database for storing and retrieving infos about // known peers in the network. If no path is given, an in-memory, temporary // database is constructed. -func newNodeDB(path string, version int, self NodeID) (*nodeDB, error) { +func newNodeDB(path string, version int, self ESSNodeID) (*nodeDB, error) { if path == "" { return newMemoryNodeDB(self) } @@ -78,7 +78,7 @@ func newNodeDB(path string, version int, self NodeID) (*nodeDB, error) { // newMemoryNodeDB creates a new in-memory node database without a persistent // backend. -func newMemoryNodeDB(self NodeID) (*nodeDB, error) { +func newMemoryNodeDB(self ESSNodeID) (*nodeDB, error) { db, err := leveldb.Open(storage.NewMemStorage(), nil) if err != nil { return nil, err @@ -92,7 +92,7 @@ func newMemoryNodeDB(self NodeID) (*nodeDB, error) { // newPersistentNodeDB creates/opens a leveldb backed persistent node database, // also flushing its contents in case of a version mismatch. -func newPersistentNodeDB(path string, version int, self NodeID) (*nodeDB, error) { +func newPersistentNodeDB(path string, version int, self ESSNodeID) (*nodeDB, error) { opts := &opt.Options{OpenFilesCacheCapacity: 5} db, err := leveldb.OpenFile(path, opts) if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted { @@ -134,18 +134,18 @@ func newPersistentNodeDB(path string, version int, self NodeID) (*nodeDB, error) // makeKey generates the leveldb key-blob from a node id and its particular // field of interest. -func makeKey(id NodeID, field string) []byte { - if bytes.Equal(id[:], nodeDBNilNodeID[:]) { +func makeKey(id ESSNodeID, field string) []byte { + if bytes.Equal(id[:], nodeDBNilESSNodeID[:]) { return []byte(field) } return append(nodeDBItemPrefix, append(id[:], field...)...) } // splitKey tries to split a database key into a node id and a field part. -func splitKey(key []byte) (id NodeID, field string) { +func splitKey(key []byte) (id ESSNodeID, field string) { // If the key is not of a node, return it plainly if !bytes.HasPrefix(key, nodeDBItemPrefix) { - return NodeID{}, string(key) + return ESSNodeID{}, string(key) } // Otherwise split the id and field item := key[len(nodeDBItemPrefix):] @@ -198,7 +198,7 @@ func (db *nodeDB) fetchRLP(key []byte, val interface{}) error { } // node retrieves a node with a given id from the database. -func (db *nodeDB) node(id NodeID) *Node { +func (db *nodeDB) node(id ESSNodeID) *Node { var node Node if err := db.fetchRLP(makeKey(id, nodeDBDiscoverRoot), &node); err != nil { return nil @@ -213,7 +213,7 @@ func (db *nodeDB) updateNode(node *Node) error { } // deleteNode deletes all information/keys associated with a node. -func (db *nodeDB) deleteNode(id NodeID) error { +func (db *nodeDB) deleteNode(id ESSNodeID) error { deleter := db.lvl.NewIterator(util.BytesPrefix(makeKey(id, "")), nil) for deleter.Next() { if err := db.lvl.Delete(deleter.Key(), nil); err != nil { @@ -282,38 +282,38 @@ func (db *nodeDB) expireNodes() error { // lastPing retrieves the time of the last ping packet send to a remote node, // requesting binding. -func (db *nodeDB) lastPing(id NodeID) time.Time { +func (db *nodeDB) lastPing(id ESSNodeID) time.Time { return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPing)), 0) } // updateLastPing updates the last time we tried contacting a remote node. -func (db *nodeDB) updateLastPing(id NodeID, instance time.Time) error { +func (db *nodeDB) updateLastPing(id ESSNodeID, instance time.Time) error { return db.storeInt64(makeKey(id, nodeDBDiscoverPing), instance.Unix()) } // lastPong retrieves the time of the last successful contact from remote node. -func (db *nodeDB) lastPong(id NodeID) time.Time { +func (db *nodeDB) lastPong(id ESSNodeID) time.Time { return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPong)), 0) } // updateLastPong updates the last time a remote node successfully contacted. -func (db *nodeDB) updateLastPong(id NodeID, instance time.Time) error { +func (db *nodeDB) updateLastPong(id ESSNodeID, instance time.Time) error { return db.storeInt64(makeKey(id, nodeDBDiscoverPong), instance.Unix()) } // findFails retrieves the number of findnode failures since bonding. -func (db *nodeDB) findFails(id NodeID) int { +func (db *nodeDB) findFails(id ESSNodeID) int { return int(db.fetchInt64(makeKey(id, nodeDBDiscoverFindFails))) } // updateFindFails updates the number of findnode failures since bonding. -func (db *nodeDB) updateFindFails(id NodeID, fails int) error { +func (db *nodeDB) updateFindFails(id ESSNodeID, fails int) error { return db.storeInt64(makeKey(id, nodeDBDiscoverFindFails), int64(fails)) } // localEndpoint returns the last local endpoint communicated to the // given remote node. -func (db *nodeDB) localEndpoint(id NodeID) *rpcEndpoint { +func (db *nodeDB) localEndpoint(id ESSNodeID) *rpcEndpoint { var ep rpcEndpoint if err := db.fetchRLP(makeKey(id, nodeDBDiscoverLocalEndpoint), &ep); err != nil { return nil @@ -321,7 +321,7 @@ func (db *nodeDB) localEndpoint(id NodeID) *rpcEndpoint { return &ep } -func (db *nodeDB) updateLocalEndpoint(id NodeID, ep rpcEndpoint) error { +func (db *nodeDB) updateLocalEndpoint(id ESSNodeID, ep rpcEndpoint) error { return db.storeRLP(makeKey(id, nodeDBDiscoverLocalEndpoint), &ep) } @@ -332,7 +332,7 @@ func (db *nodeDB) querySeeds(n int, maxAge time.Duration) []*Node { now = time.Now() nodes = make([]*Node, 0, n) it = db.lvl.NewIterator(nil, nil) - id NodeID + id ESSNodeID ) defer it.Release() @@ -367,7 +367,7 @@ seek: return nodes } -func (db *nodeDB) fetchTopicRegTickets(id NodeID) (issued, used uint32) { +func (db *nodeDB) fetchTopicRegTickets(id ESSNodeID) (issued, used uint32) { key := makeKey(id, nodeDBTopicRegTickets) blob, _ := db.lvl.Get(key, nil) if len(blob) != 8 { @@ -378,7 +378,7 @@ func (db *nodeDB) fetchTopicRegTickets(id NodeID) (issued, used uint32) { return } -func (db *nodeDB) updateTopicRegTickets(id NodeID, issued, used uint32) error { +func (db *nodeDB) updateTopicRegTickets(id ESSNodeID, issued, used uint32) error { key := makeKey(id, nodeDBTopicRegTickets) blob := make([]byte, 8) binary.BigEndian.PutUint32(blob[0:4], issued) diff --git a/p2p/discv5/database_test.go b/p2p/discv5/database_test.go index a2ccb64671..ef8272356e 100644 --- a/p2p/discv5/database_test.go +++ b/p2p/discv5/database_test.go @@ -28,12 +28,12 @@ import ( ) var nodeDBKeyTests = []struct { - id NodeID + id ESSNodeID field string key []byte }{ { - id: NodeID{}, + id: ESSNodeID{}, field: "version", key: []byte{0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e}, // field }, @@ -79,7 +79,7 @@ var nodeDBInt64Tests = []struct { } func TestNodeDBInt64(t *testing.T) { - db, _ := newNodeDB("", Version, NodeID{}) + db, _ := newNodeDB("", Version, ESSNodeID{}) defer db.close() tests := nodeDBInt64Tests @@ -111,7 +111,7 @@ func TestNodeDBFetchStore(t *testing.T) { inst := time.Now() num := 314 - db, _ := newNodeDB("", Version, NodeID{}) + db, _ := newNodeDB("", Version, ESSNodeID{}) defer db.close() // Check fetch/store operations on a node ping object @@ -231,11 +231,11 @@ func TestNodeDBSeedQuery(t *testing.T) { // Retrieve the entire batch and check for duplicates seeds := db.querySeeds(len(nodeDBSeedQueryNodes)*2, time.Hour) - have := make(map[NodeID]struct{}) + have := make(map[ESSNodeID]struct{}) for _, seed := range seeds { have[seed.ID] = struct{}{} } - want := make(map[NodeID]struct{}) + want := make(map[ESSNodeID]struct{}) for _, seed := range nodeDBSeedQueryNodes[2:] { want[seed.node.ID] = struct{}{} } @@ -267,7 +267,7 @@ func TestNodeDBPersistency(t *testing.T) { ) // Create a persistent database and store some values - db, err := newNodeDB(filepath.Join(root, "database"), Version, NodeID{}) + db, err := newNodeDB(filepath.Join(root, "database"), Version, ESSNodeID{}) if err != nil { t.Fatalf("failed to create persistent database: %v", err) } @@ -277,7 +277,7 @@ func TestNodeDBPersistency(t *testing.T) { db.close() // Reopen the database and check the value - db, err = newNodeDB(filepath.Join(root, "database"), Version, NodeID{}) + db, err = newNodeDB(filepath.Join(root, "database"), Version, ESSNodeID{}) if err != nil { t.Fatalf("failed to open persistent database: %v", err) } @@ -287,7 +287,7 @@ func TestNodeDBPersistency(t *testing.T) { db.close() // Change the database version and check flush - db, err = newNodeDB(filepath.Join(root, "database"), Version+1, NodeID{}) + db, err = newNodeDB(filepath.Join(root, "database"), Version+1, ESSNodeID{}) if err != nil { t.Fatalf("failed to open persistent database: %v", err) } @@ -324,7 +324,7 @@ var nodeDBExpirationNodes = []struct { } func TestNodeDBExpiration(t *testing.T) { - db, _ := newNodeDB("", Version, NodeID{}) + db, _ := newNodeDB("", Version, ESSNodeID{}) defer db.close() // Add all the test nodes and set their last pong time @@ -350,7 +350,7 @@ func TestNodeDBExpiration(t *testing.T) { func TestNodeDBSelfExpiration(t *testing.T) { // Find a node in the tests that shouldn't expire, and assign it as self - var self NodeID + var self ESSNodeID for _, node := range nodeDBExpirationNodes { if !node.exp { self = node.node.ID diff --git a/p2p/discv5/net.go b/p2p/discv5/net.go index 9b0bd0c80a..9bcf4be482 100644 --- a/p2p/discv5/net.go +++ b/p2p/discv5/net.go @@ -75,7 +75,7 @@ type Network struct { topictab *topicTable ticketStore *ticketStore nursery []*Node - nodes map[NodeID]*Node // tracks active nodes with state != known + nodes map[ESSNodeID]*Node // tracks active nodes with state != known timeoutTimers map[timeoutEvent]*time.Timer // Revalidation queues. @@ -163,7 +163,7 @@ func newNetwork(conn transport, ourPubkey ecdsa.PublicKey, dbPath string, netres queryReq: make(chan *findnodeQuery), topicRegisterReq: make(chan topicRegisterReq), topicSearchReq: make(chan topicSearchReq), - nodes: make(map[NodeID]*Node), + nodes: make(map[ESSNodeID]*Node), } go net.loop() return net, nil @@ -214,7 +214,7 @@ func (net *Network) SetFallbackNodes(nodes []*Node) error { // Resolve searches for a specific node with the given ID. // It returns nil if the node could not be found. -func (net *Network) Resolve(targetID NodeID) *Node { +func (net *Network) Resolve(targetID ESSNodeID) *Node { result := net.lookup(crypto.Keccak256Hash(targetID[:]), true) for _, n := range result { if n.ID == targetID { @@ -231,14 +231,14 @@ func (net *Network) Resolve(targetID NodeID) *Node { // identifier. // // The local node may be included in the result. -func (net *Network) Lookup(targetID NodeID) []*Node { +func (net *Network) Lookup(targetID ESSNodeID) []*Node { return net.lookup(crypto.Keccak256Hash(targetID[:]), false) } func (net *Network) lookup(target common.Hash, stopOnMatch bool) []*Node { var ( - asked = make(map[NodeID]bool) - seen = make(map[NodeID]bool) + asked = make(map[ESSNodeID]bool) + seen = make(map[ESSNodeID]bool) reply = make(chan []*Node, alpha) result = nodesByDistance{target: target} pendingQueries = 0 diff --git a/p2p/discv5/net_test.go b/p2p/discv5/net_test.go index 001d193cc9..3f6d42f1be 100644 --- a/p2p/discv5/net_test.go +++ b/p2p/discv5/net_test.go @@ -64,11 +64,11 @@ func TestNetwork_Lookup(t *testing.T) { } // This is the test network for the Lookup test. -// The nodes were obtained by running testnet.mine with a random NodeID as target. +// The nodes were obtained by running testnet.mine with a random ESSNodeID as target. var lookupTestnet = &preminedTestnet{ target: MustHexID("166aea4f556532c6d34e8b740e5d314af7e9ac0ca79833bd751d6b665f12dfd38ec563c363b32f02aef4a80b44fd3def94612d497b99cb5f17fd24de454927ec"), targetSha: common.Hash{0x5c, 0x94, 0x4e, 0xe5, 0x1c, 0x5a, 0xe9, 0xf7, 0x2a, 0x95, 0xec, 0xcb, 0x8a, 0xed, 0x3, 0x74, 0xee, 0xcb, 0x51, 0x19, 0xd7, 0x20, 0xcb, 0xea, 0x68, 0x13, 0xe8, 0xe0, 0xd6, 0xad, 0x92, 0x61}, - dists: [257][]NodeID{ + dists: [257][]ESSNodeID{ 240: { MustHexID("2001ad5e3e80c71b952161bc0186731cf5ffe942d24a79230a0555802296238e57ea7a32f5b6f18564eadc1c65389448481f8c9338df0a3dbd18f708cbc2cbcb"), MustHexID("6ba3f4f57d084b6bf94cc4555b8c657e4a8ac7b7baf23c6874efc21dd1e4f56b7eb2721e07f5242d2f1d8381fc8cae535e860197c69236798ba1ad231b105794"), @@ -259,13 +259,13 @@ var lookupTestnet = &preminedTestnet{ } type preminedTestnet struct { - target NodeID + target ESSNodeID targetSha common.Hash // sha3(target) - dists [hashBits + 1][]NodeID + dists [hashBits + 1][]ESSNodeID net *Network } -func (tn *preminedTestnet) sendFindnode(to *Node, target NodeID) { +func (tn *preminedTestnet) sendFindnode(to *Node, target ESSNodeID) { panic("sendFindnode called") } @@ -336,7 +336,7 @@ func (*preminedTestnet) localAddr() *net.UDPAddr { // mine generates a testnet struct literal with nodes at // various distances to the given target. -func (tn *preminedTestnet) mine(target NodeID) { +func (tn *preminedTestnet) mine(target ESSNodeID) { tn.target = target tn.targetSha = crypto.Keccak256Hash(tn.target[:]) found := 0 @@ -354,12 +354,12 @@ func (tn *preminedTestnet) mine(target NodeID) { fmt.Println("&preminedTestnet{") fmt.Printf(" target: %#v,\n", tn.target) fmt.Printf(" targetSha: %#v,\n", tn.targetSha) - fmt.Printf(" dists: [%d][]NodeID{\n", len(tn.dists)) + fmt.Printf(" dists: [%d][]ESSNodeID{\n", len(tn.dists)) for ld, ns := range tn.dists { if len(ns) == 0 { continue } - fmt.Printf(" %d: []NodeID{\n", ld) + fmt.Printf(" %d: []ESSNodeID{\n", ld) for _, n := range ns { fmt.Printf(" MustHexID(\"%x\"),\n", n[:]) } diff --git a/p2p/discv5/node.go b/p2p/discv5/node.go index 3d47485122..593863dbea 100644 --- a/p2p/discv5/node.go +++ b/p2p/discv5/node.go @@ -39,7 +39,7 @@ import ( type Node struct { IP net.IP // len 4 for IPv4 or 16 for IPv6 UDP, TCP uint16 // port numbers - ID NodeID // the node's public key + ID ESSNodeID // the node's public key // Network-related fields are contained in nodeNetGuts. // These fields are not supposed to be used off the @@ -49,7 +49,7 @@ type Node struct { // NewNode creates a new node. It is mostly meant to be used for // testing purposes. -func NewNode(id NodeID, ip net.IP, udpPort, tcpPort uint16) *Node { +func NewNode(id ESSNodeID, ip net.IP, udpPort, tcpPort uint16) *Node { if ipv4 := ip.To4(); ipv4 != nil { ip = ipv4 } @@ -161,7 +161,7 @@ func ParseNode(rawurl string) (*Node, error) { func parseComplete(rawurl string) (*Node, error) { var ( - id NodeID + id ESSNodeID ip net.IP tcpPort, udpPort uint64 ) @@ -259,29 +259,29 @@ func (n *Node) UnmarshalText(text []byte) error { const nodeIDBits = 512 -// NodeID is a unique identifier for each node. +// ESSNodeID is a unique identifier for each node. // The node identifier is a marshaled elliptic curve public key. -type NodeID [nodeIDBits / 8]byte +type ESSNodeID [nodeIDBits / 8]byte -// NodeID prints as a long hexadecimal number. -func (n NodeID) String() string { +// ESSNodeID prints as a long hexadecimal number. +func (n ESSNodeID) String() string { return fmt.Sprintf("%x", n[:]) } -// The Go syntax representation of a NodeID is a call to HexID. -func (n NodeID) GoString() string { +// The Go syntax representation of a ESSNodeID is a call to HexID. +func (n ESSNodeID) GoString() string { return fmt.Sprintf("discover.HexID(\"%x\")", n[:]) } // TerminalString returns a shortened hex string for terminal logging. -func (n NodeID) TerminalString() string { +func (n ESSNodeID) TerminalString() string { return hex.EncodeToString(n[:8]) } -// HexID converts a hex string to a NodeID. +// HexID converts a hex string to a ESSNodeID. // The string may be prefixed with 0x. -func HexID(in string) (NodeID, error) { - var id NodeID +func HexID(in string) (ESSNodeID, error) { + var id ESSNodeID b, err := hex.DecodeString(strings.TrimPrefix(in, "0x")) if err != nil { return id, err @@ -292,9 +292,9 @@ func HexID(in string) (NodeID, error) { return id, nil } -// MustHexID converts a hex string to a NodeID. -// It panics if the string is not a valid NodeID. -func MustHexID(in string) NodeID { +// MustHexID converts a hex string to a ESSNodeID. +// It panics if the string is not a valid ESSNodeID. +func MustHexID(in string) ESSNodeID { id, err := HexID(in) if err != nil { panic(err) @@ -303,8 +303,8 @@ func MustHexID(in string) NodeID { } // PubkeyID returns a marshaled representation of the given public key. -func PubkeyID(pub *ecdsa.PublicKey) NodeID { - var id NodeID +func PubkeyID(pub *ecdsa.PublicKey) ESSNodeID { + var id ESSNodeID pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y) if len(pbytes)-1 != len(id) { panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes))) @@ -315,7 +315,7 @@ func PubkeyID(pub *ecdsa.PublicKey) NodeID { // Pubkey returns the public key represented by the node ID. // It returns an error if the ID is not a point on the curve. -func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) { +func (n ESSNodeID) Pubkey() (*ecdsa.PublicKey, error) { p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)} half := len(n) / 2 p.X.SetBytes(n[:half]) @@ -326,7 +326,7 @@ func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) { return p, nil } -func (id NodeID) mustPubkey() ecdsa.PublicKey { +func (id ESSNodeID) mustPubkey() ecdsa.PublicKey { pk, err := id.Pubkey() if err != nil { panic(err) @@ -334,9 +334,9 @@ func (id NodeID) mustPubkey() ecdsa.PublicKey { return *pk } -// recoverNodeID computes the public key used to sign the +// recoverESSNodeID computes the public key used to sign the // given hash from the signature. -func recoverNodeID(hash, sig []byte) (id NodeID, err error) { +func recoverESSNodeID(hash, sig []byte) (id ESSNodeID, err error) { pubkey, err := crypto.Ecrecover(hash, sig) if err != nil { return id, err diff --git a/p2p/discv5/node_test.go b/p2p/discv5/node_test.go index ce4ad9e4d4..a1af57fa26 100644 --- a/p2p/discv5/node_test.go +++ b/p2p/discv5/node_test.go @@ -180,7 +180,7 @@ func TestNodeString(t *testing.T) { } func TestHexID(t *testing.T) { - ref := NodeID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 106, 217, 182, 31, 165, 174, 1, 67, 7, 235, 220, 150, 66, 83, 173, 205, 159, 44, 10, 57, 42, 161, 26, 188} + ref := ESSNodeID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 106, 217, 182, 31, 165, 174, 1, 67, 7, 235, 220, 150, 66, 83, 173, 205, 159, 44, 10, 57, 42, 161, 26, 188} id1 := MustHexID("0x000000000000000000000000000000000000000000000000000000000000000000000000000000806ad9b61fa5ae014307ebdc964253adcd9f2c0a392aa11abc") id2 := MustHexID("000000000000000000000000000000000000000000000000000000000000000000000000000000806ad9b61fa5ae014307ebdc964253adcd9f2c0a392aa11abc") @@ -192,7 +192,7 @@ func TestHexID(t *testing.T) { } } -func TestNodeID_recover(t *testing.T) { +func TestESSNodeID_recover(t *testing.T) { prv := newkey() hash := make([]byte, 32) sig, err := crypto.Sign(hash, prv) @@ -201,7 +201,7 @@ func TestNodeID_recover(t *testing.T) { } pub := PubkeyID(&prv.PublicKey) - recpub, err := recoverNodeID(hash, sig) + recpub, err := recoverESSNodeID(hash, sig) if err != nil { t.Fatalf("recovery error: %v", err) } @@ -218,8 +218,8 @@ func TestNodeID_recover(t *testing.T) { } } -func TestNodeID_pubkeyBad(t *testing.T) { - ecdsa, err := NodeID{}.Pubkey() +func TestESSNodeID_pubkeyBad(t *testing.T) { + ecdsa, err := ESSNodeID{}.Pubkey() if err == nil { t.Error("expected error for zero ID") } @@ -228,7 +228,7 @@ func TestNodeID_pubkeyBad(t *testing.T) { } } -func TestNodeID_distcmp(t *testing.T) { +func TestESSNodeID_distcmp(t *testing.T) { distcmpBig := func(target, a, b common.Hash) int { tbig := new(big.Int).SetBytes(target[:]) abig := new(big.Int).SetBytes(a[:]) @@ -241,7 +241,7 @@ func TestNodeID_distcmp(t *testing.T) { } // the random tests is likely to miss the case where they're equal. -func TestNodeID_distcmpEqual(t *testing.T) { +func TestESSNodeID_distcmpEqual(t *testing.T) { base := common.Hash{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} x := common.Hash{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0} if distcmp(base, x, x) != 0 { @@ -249,7 +249,7 @@ func TestNodeID_distcmpEqual(t *testing.T) { } } -func TestNodeID_logdist(t *testing.T) { +func TestESSNodeID_logdist(t *testing.T) { logdistBig := func(a, b common.Hash) int { abig, bbig := new(big.Int).SetBytes(a[:]), new(big.Int).SetBytes(b[:]) return new(big.Int).Xor(abig, bbig).BitLen() @@ -260,14 +260,14 @@ func TestNodeID_logdist(t *testing.T) { } // the random tests is likely to miss the case where they're equal. -func TestNodeID_logdistEqual(t *testing.T) { +func TestESSNodeID_logdistEqual(t *testing.T) { x := common.Hash{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} if logdist(x, x) != 0 { t.Errorf("logdist(x, x) != 0") } } -func TestNodeID_hashAtDistance(t *testing.T) { +func TestESSNodeID_hashAtDistance(t *testing.T) { // we don't use quick.Check here because its output isn't // very helpful when the test fails. cfg := quickcfg() @@ -295,8 +295,8 @@ func quickcfg() *quick.Config { // TODO: The Generate method can be dropped when we require Go >= 1.5 // because testing/quick learned to generate arrays in 1.5. -func (NodeID) Generate(rand *rand.Rand, size int) reflect.Value { - var id NodeID +func (ESSNodeID) Generate(rand *rand.Rand, size int) reflect.Value { + var id ESSNodeID m := rand.Intn(len(id)) for i := len(id) - 1; i > m; i-- { id[i] = byte(rand.Uint32()) diff --git a/p2p/discv5/sim_test.go b/p2p/discv5/sim_test.go index 543faecd48..ad657a4105 100644 --- a/p2p/discv5/sim_test.go +++ b/p2p/discv5/sim_test.go @@ -190,7 +190,7 @@ func randomResolves(t *testing.T, s *simulation, net *Network) { randtime := func() time.Duration { return time.Duration(rand.Intn(50)+20) * time.Second } - lookup := func(target NodeID) bool { + lookup := func(target ESSNodeID) bool { result := net.Resolve(target) return result != nil && result.ID == target } @@ -212,12 +212,12 @@ func randomResolves(t *testing.T, s *simulation, net *Network) { type simulation struct { mu sync.RWMutex - nodes map[NodeID]*Network + nodes map[ESSNodeID]*Network nodectr uint32 } func newSimulation() *simulation { - return &simulation{nodes: make(map[NodeID]*Network)} + return &simulation{nodes: make(map[ESSNodeID]*Network)} } func (s *simulation) shutdown() { @@ -294,7 +294,7 @@ func (s *simulation) launchNode(log bool) *Network { return net } -func (s *simulation) dropNode(id NodeID) { +func (s *simulation) dropNode(id ESSNodeID) { s.mu.Lock() n := s.nodes[id] delete(s.nodes, id) @@ -305,7 +305,7 @@ func (s *simulation) dropNode(id NodeID) { type simTransport struct { joinTime time.Time - sender NodeID + sender ESSNodeID senderAddr *net.UDPAddr sim *simulation hashctr uint64 @@ -443,7 +443,7 @@ func (st *simTransport) nextHash() []byte { const packetLoss = 0 // 1/1000 -func (st *simTransport) sendPacket(remote NodeID, p ingressPacket) { +func (st *simTransport) sendPacket(remote ESSNodeID, p ingressPacket) { if rand.Int31n(1000) >= packetLoss { st.sim.mu.RLock() recipient := st.sim.nodes[remote] diff --git a/p2p/discv5/table.go b/p2p/discv5/table.go index c8d234b936..adce185650 100644 --- a/p2p/discv5/table.go +++ b/p2p/discv5/table.go @@ -55,7 +55,7 @@ type bucket struct { replacements []*Node } -func newTable(ourID NodeID, ourAddr *net.UDPAddr) *Table { +func newTable(ourID ESSNodeID, ourAddr *net.UDPAddr) *Table { self := NewNode(ourID, ourAddr.IP, uint16(ourAddr.Port), uint16(ourAddr.Port)) tab := &Table{self: self} for i := range tab.buckets { diff --git a/p2p/discv5/table_test.go b/p2p/discv5/table_test.go index a29943dab9..2dbbf33ed7 100644 --- a/p2p/discv5/table_test.go +++ b/p2p/discv5/table_test.go @@ -35,7 +35,7 @@ type nullTransport struct{} func (nullTransport) sendPing(remote *Node, remoteAddr *net.UDPAddr) []byte { return []byte{1} } func (nullTransport) sendPong(remote *Node, pingHash []byte) {} -func (nullTransport) sendFindnode(remote *Node, target NodeID) {} +func (nullTransport) sendFindnode(remote *Node, target ESSNodeID) {} func (nullTransport) sendNeighbours(remote *Node, nodes []*Node) {} func (nullTransport) localAddr() *net.UDPAddr { return new(net.UDPAddr) } func (nullTransport) Close() {} @@ -43,7 +43,7 @@ func (nullTransport) Close() {} // func TestTable_pingReplace(t *testing.T) { // doit := func(newNodeIsResponding, lastInBucketIsResponding bool) { // transport := newPingRecorder() -// tab, _ := newTable(transport, NodeID{}, &net.UDPAddr{}) +// tab, _ := newTable(transport, ESSNodeID{}, &net.UDPAddr{}) // defer tab.Close() // pingSender := NewNode(MustHexID("a502af0f59b2aab7746995408c79e9ca312d2793cc997e44fc55eda62f0150bbb8c59a6f9269ba3a081518b62699ee807c7c19c20125ddfccca872608af9e370"), net.IP{}, 99, 99) // @@ -159,20 +159,20 @@ func nodeAtDistance(base common.Hash, ld int) (n *Node) { return n } -type pingRecorder struct{ responding, pinged map[NodeID]bool } +type pingRecorder struct{ responding, pinged map[ESSNodeID]bool } func newPingRecorder() *pingRecorder { - return &pingRecorder{make(map[NodeID]bool), make(map[NodeID]bool)} + return &pingRecorder{make(map[ESSNodeID]bool), make(map[ESSNodeID]bool)} } -func (t *pingRecorder) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { +func (t *pingRecorder) findnode(toid ESSNodeID, toaddr *net.UDPAddr, target ESSNodeID) ([]*Node, error) { panic("findnode called on pingRecorder") } func (t *pingRecorder) close() {} -func (t *pingRecorder) waitping(from NodeID) error { +func (t *pingRecorder) waitping(from ESSNodeID) error { return nil // remote always pings } -func (t *pingRecorder) ping(toid NodeID, toaddr *net.UDPAddr) error { +func (t *pingRecorder) ping(toid ESSNodeID, toaddr *net.UDPAddr) error { t.pinged[toid] = true if t.responding[toid] { return nil @@ -244,7 +244,7 @@ func TestTable_ReadRandomNodesGetAll(t *testing.T) { }, } test := func(buf []*Node) bool { - tab := newTable(NodeID{}, &net.UDPAddr{}) + tab := newTable(ESSNodeID{}, &net.UDPAddr{}) for i := 0; i < len(buf); i++ { ld := cfg.Rand.Intn(len(tab.buckets)) tab.stuff([]*Node{nodeAtDistance(tab.self.sha, ld)}) @@ -266,7 +266,7 @@ func TestTable_ReadRandomNodesGetAll(t *testing.T) { } type closeTest struct { - Self NodeID + Self ESSNodeID Target common.Hash All []*Node N int @@ -274,18 +274,18 @@ type closeTest struct { func (*closeTest) Generate(rand *rand.Rand, size int) reflect.Value { t := &closeTest{ - Self: gen(NodeID{}, rand).(NodeID), + Self: gen(ESSNodeID{}, rand).(ESSNodeID), Target: gen(common.Hash{}, rand).(common.Hash), N: rand.Intn(bucketSize), } - for _, id := range gen([]NodeID{}, rand).([]NodeID) { + for _, id := range gen([]ESSNodeID{}, rand).([]ESSNodeID) { t.All = append(t.All, &Node{ID: id}) } return reflect.ValueOf(t) } func hasDuplicates(slice []*Node) bool { - seen := make(map[NodeID]bool) + seen := make(map[ESSNodeID]bool) for i, e := range slice { if e == nil { panic(fmt.Sprintf("nil *Node at %d", i)) @@ -309,7 +309,7 @@ func sortedByDistanceTo(distbase common.Hash, slice []*Node) bool { return true } -func contains(ns []*Node, id NodeID) bool { +func contains(ns []*Node, id ESSNodeID) bool { for _, n := range ns { if n.ID == id { return true diff --git a/p2p/discv5/udp.go b/p2p/discv5/udp.go index 49e1cb811a..f629d5a443 100644 --- a/p2p/discv5/udp.go +++ b/p2p/discv5/udp.go @@ -84,7 +84,7 @@ type ( // findnode is a query for nodes close to the given target. findnode struct { - Target NodeID // doesn't need to be an actual public key + Target ESSNodeID // doesn't need to be an actual public key Expiration uint64 // Ignore additional fields (for forward compatibility). Rest []rlp.RawValue `rlp:"tail"` @@ -127,7 +127,7 @@ type ( IP net.IP // len 4 for IPv4 or 16 for IPv6 UDP uint16 // for discovery protocol TCP uint16 // for RLPx protocol - ID NodeID + ID ESSNodeID } rpcEndpoint struct { @@ -205,7 +205,7 @@ func nodeToRPC(n *Node) rpcNode { } type ingressPacket struct { - remoteID NodeID + remoteID ESSNodeID remoteAddr *net.UDPAddr ev nodeEvent hash []byte @@ -273,7 +273,7 @@ func (t *udp) sendPing(remote *Node, toaddr *net.UDPAddr, topics []Topic) (hash return hash } -func (t *udp) sendFindnode(remote *Node, target NodeID) { +func (t *udp) sendFindnode(remote *Node, target ESSNodeID) { t.sendPacket(remote.ID, remote.addr(), byte(findnodePacket), findnode{ Target: target, Expiration: uint64(time.Now().Add(expiration).Unix()), @@ -326,7 +326,7 @@ func (t *udp) sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node) } } -func (t *udp) sendPacket(toid NodeID, toaddr *net.UDPAddr, ptype byte, req interface{}) (hash []byte, err error) { +func (t *udp) sendPacket(toid ESSNodeID, toaddr *net.UDPAddr, ptype byte, req interface{}) (hash []byte, err error) { //fmt.Println("sendPacket", nodeEvent(ptype), toaddr.String(), toid.String()) packet, hash, err := encodePacket(t.priv, ptype, req) if err != nil { @@ -411,7 +411,7 @@ func decodePacket(buffer []byte, pkt *ingressPacket) error { if !bytes.Equal(prefix, versionPrefix) { return errBadPrefix } - fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig) + fromID, err := recoverESSNodeID(crypto.Keccak256(buf[headSize:]), sig) if err != nil { return err } diff --git a/p2p/discv5/udp_test.go b/p2p/discv5/udp_test.go index 62184aa9d3..14427e800b 100644 --- a/p2p/discv5/udp_test.go +++ b/p2p/discv5/udp_test.go @@ -364,7 +364,7 @@ func TestForwardCompatibility(t *testing.T) { t.Skip("skipped while working on discovery v5") testkey, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - wantNodeID := PubkeyID(&testkey.PublicKey) + wantESSNodeID := PubkeyID(&testkey.PublicKey) for _, test := range testPackets { input, err := hex.DecodeString(test.input) @@ -379,8 +379,8 @@ func TestForwardCompatibility(t *testing.T) { if !reflect.DeepEqual(pkt.data, test.wantPacket) { t.Errorf("got %s\nwant %s", spew.Sdump(pkt.data), spew.Sdump(test.wantPacket)) } - if pkt.remoteID != wantNodeID { - t.Errorf("got id %v\nwant id %v", pkt.remoteID, wantNodeID) + if pkt.remoteID != wantESSNodeID { + t.Errorf("got id %v\nwant id %v", pkt.remoteID, wantESSNodeID) } } } diff --git a/p2p/message.go b/p2p/message.go index a4eac54d33..463494f3f9 100644 --- a/p2p/message.go +++ b/p2p/message.go @@ -253,13 +253,13 @@ type msgEventer struct { MsgReadWriter feed *event.Feed - peerID discover.NodeID + peerID discover.ESSNodeID Protocol string } // newMsgEventer returns a msgEventer which sends message events to the given // feed -func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID discover.NodeID, proto string) *msgEventer { +func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID discover.ESSNodeID, proto string) *msgEventer { return &msgEventer{ MsgReadWriter: rw, feed: feed, diff --git a/p2p/peer.go b/p2p/peer.go index e8d1f25404..9d083e2274 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -60,7 +60,7 @@ type protoHandshake struct { Name string Caps []Cap ListenPort uint64 - ID discover.NodeID + ID discover.ESSNodeID // Ignore additional fields (for forward compatibility). Rest []rlp.RawValue `rlp:"tail"` @@ -91,7 +91,7 @@ const ( // a p2p.Server or when a message is sent or received on a peer connection type PeerEvent struct { Type PeerEventType `json:"type"` - Peer discover.NodeID `json:"peer"` + Peer discover.ESSNodeID `json:"peer"` Error string `json:"error,omitempty"` Protocol string `json:"protocol,omitempty"` MsgCode *uint64 `json:"msg_code,omitempty"` @@ -115,7 +115,7 @@ type Peer struct { } // NewPeer returns a peer for testing purposes. -func NewPeer(id discover.NodeID, name string, caps []Cap) *Peer { +func NewPeer(id discover.ESSNodeID, name string, caps []Cap) *Peer { pipe, _ := net.Pipe() conn := &conn{fd: pipe, transport: nil, id: id, caps: caps, name: name} peer := newPeer(conn, nil) @@ -124,7 +124,7 @@ func NewPeer(id discover.NodeID, name string, caps []Cap) *Peer { } // ID returns the node's public key. -func (p *Peer) ID() discover.NodeID { +func (p *Peer) ID() discover.ESSNodeID { return p.rw.id } diff --git a/p2p/protocol.go b/p2p/protocol.go index ee747ba23d..efae039f44 100644 --- a/p2p/protocol.go +++ b/p2p/protocol.go @@ -51,7 +51,7 @@ type Protocol struct { // PeerInfo is an optional helper method to retrieve protocol specific metadata // about a certain peer in the network. If an info retrieval function is set, // but returns nil, it is assumed that the protocol handshake is still running. - PeerInfo func(id discover.NodeID) interface{} + PeerInfo func(id discover.ESSNodeID) interface{} } func (p Protocol) cap() Cap { diff --git a/p2p/protocols/protocol_test.go b/p2p/protocols/protocol_test.go index 11df8ff39e..95f66d404d 100644 --- a/p2p/protocols/protocol_test.go +++ b/p2p/protocols/protocol_test.go @@ -36,7 +36,7 @@ type hs0 struct { // message to kill/drop the peer with nodeID type kill struct { - C discover.NodeID + C discover.ESSNodeID } // message to drop connection @@ -144,7 +144,7 @@ func protocolTester(t *testing.T, pp *p2ptest.TestPeerPool) *p2ptest.ProtocolTes return p2ptest.NewProtocolTester(t, conf.ID, 2, newProtocol(pp)) } -func protoHandshakeExchange(id discover.NodeID, proto *protoHandshake) []p2ptest.Exchange { +func protoHandshakeExchange(id discover.ESSNodeID, proto *protoHandshake) []p2ptest.Exchange { return []p2ptest.Exchange{ { @@ -197,7 +197,7 @@ func TestProtoHandshakeSuccess(t *testing.T) { runProtoHandshake(t, &protoHandshake{42, "420"}) } -func moduleHandshakeExchange(id discover.NodeID, resp uint) []p2ptest.Exchange { +func moduleHandshakeExchange(id discover.ESSNodeID, resp uint) []p2ptest.Exchange { return []p2ptest.Exchange{ { @@ -249,7 +249,7 @@ func TestModuleHandshakeSuccess(t *testing.T) { } // testing complex interactions over multiple peers, relaying, dropping -func testMultiPeerSetup(a, b discover.NodeID) []p2ptest.Exchange { +func testMultiPeerSetup(a, b discover.ESSNodeID) []p2ptest.Exchange { return []p2ptest.Exchange{ { diff --git a/p2p/rlpx.go b/p2p/rlpx.go index 46b6668695..3c397b8d35 100644 --- a/p2p/rlpx.go +++ b/p2p/rlpx.go @@ -165,7 +165,7 @@ func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake, if err := msg.Decode(&hs); err != nil { return nil, err } - if (hs.ID == discover.NodeID{}) { + if (hs.ID == discover.ESSNodeID{}) { return nil, DiscInvalidIdentity } return &hs, nil @@ -175,7 +175,7 @@ func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake, // messages. the protocol handshake is the first authenticated message // and also verifies whether the encryption handshake 'worked' and the // remote side actually provided the right public key. -func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (discover.NodeID, error) { +func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (discover.ESSNodeID, error) { var ( sec secrets err error @@ -186,7 +186,7 @@ func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (disco sec, err = initiatorEncHandshake(t.fd, prv, dial.ID) } if err != nil { - return discover.NodeID{}, err + return discover.ESSNodeID{}, err } t.wmu.Lock() t.rw = newRLPXFrameRW(t.fd, sec) @@ -197,7 +197,7 @@ func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (disco // encHandshake contains the state of the encryption handshake. type encHandshake struct { initiator bool - remoteID discover.NodeID + remoteID discover.ESSNodeID remotePub *ecies.PublicKey // remote-pubk initNonce, respNonce []byte // nonce @@ -208,7 +208,7 @@ type encHandshake struct { // secrets represents the connection secrets // which are negotiated during the encryption handshake. type secrets struct { - RemoteID discover.NodeID + RemoteID discover.ESSNodeID AES, MAC []byte EgressMAC, IngressMAC hash.Hash Token []byte @@ -280,7 +280,7 @@ func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) // it should be called on the dialing side of the connection. // // prv is the local client's private key. -func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID) (s secrets, err error) { +func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.ESSNodeID) (s secrets, err error) { h := &encHandshake{initiator: true, remoteID: remoteID} authMsg, err := h.makeAuthMsg(prv) if err != nil { diff --git a/p2p/rlpx_test.go b/p2p/rlpx_test.go index 7ae8007740..ada54eaa7d 100644 --- a/p2p/rlpx_test.go +++ b/p2p/rlpx_test.go @@ -81,7 +81,7 @@ func TestEncHandshake(t *testing.T) { func testEncHandshake(token []byte) error { type result struct { side string - id discover.NodeID + id discover.ESSNodeID err error } var ( diff --git a/p2p/server.go b/p2p/server.go index cdb5b1926e..1a4db34b49 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -177,7 +177,7 @@ type Server struct { log log.Logger } -type peerOpFunc func(map[discover.NodeID]*Peer) +type peerOpFunc func(map[discover.ESSNodeID]*Peer) type peerDrop struct { *Peer @@ -201,14 +201,14 @@ type conn struct { transport flags connFlag cont chan error // The run loop uses cont to signal errors to SetupConn. - id discover.NodeID // valid after the encryption handshake + id discover.ESSNodeID // valid after the encryption handshake caps []Cap // valid after the protocol handshake name string // valid after the protocol handshake } type transport interface { // The two handshakes. - doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error) + doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.ESSNodeID, error) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) // The MsgReadWriter can only be used after the encryption // handshake has completed. The code uses conn.id to track this @@ -222,7 +222,7 @@ type transport interface { func (c *conn) String() string { s := c.flags.String() - if (c.id != discover.NodeID{}) { + if (c.id != discover.ESSNodeID{}) { s += " " + c.id.String() } s += " " + c.fd.RemoteAddr().String() @@ -260,7 +260,7 @@ func (srv *Server) Peers() []*Peer { // Note: We'd love to put this function into a variable but // that seems to cause a weird compiler error in some // environments. - case srv.peerOp <- func(peers map[discover.NodeID]*Peer) { + case srv.peerOp <- func(peers map[discover.ESSNodeID]*Peer) { for _, p := range peers { ps = append(ps, p) } @@ -275,7 +275,7 @@ func (srv *Server) Peers() []*Peer { func (srv *Server) PeerCount() int { var count int select { - case srv.peerOp <- func(ps map[discover.NodeID]*Peer) { count = len(ps) }: + case srv.peerOp <- func(ps map[discover.ESSNodeID]*Peer) { count = len(ps) }: <-srv.peerOpDone case <-srv.quit: } @@ -529,7 +529,7 @@ func (srv *Server) startListening() error { } type dialer interface { - newTasks(running int, peers map[discover.NodeID]*Peer, now time.Time) []task + newTasks(running int, peers map[discover.ESSNodeID]*Peer, now time.Time) []task taskDone(task, time.Time) addStatic(*discover.Node) removeStatic(*discover.Node) @@ -538,9 +538,9 @@ type dialer interface { func (srv *Server) run(dialstate dialer) { defer srv.loopWG.Done() var ( - peers = make(map[discover.NodeID]*Peer) + peers = make(map[discover.ESSNodeID]*Peer) inboundCount = 0 - trusted = make(map[discover.NodeID]bool, len(srv.TrustedNodes)) + trusted = make(map[discover.ESSNodeID]bool, len(srv.TrustedNodes)) taskdone = make(chan task, maxActiveDialTasks) runningTasks []task queuedTasks []task // tasks that can't run yet @@ -691,7 +691,7 @@ running: } } -func (srv *Server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, inboundCount int, c *conn) error { +func (srv *Server) protoHandshakeChecks(peers map[discover.ESSNodeID]*Peer, inboundCount int, c *conn) error { // Drop connections with no matching protocols. if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 { return DiscUselessPeer @@ -701,7 +701,7 @@ func (srv *Server) protoHandshakeChecks(peers map[discover.NodeID]*Peer, inbound return srv.encHandshakeChecks(peers, inboundCount, c) } -func (srv *Server) encHandshakeChecks(peers map[discover.NodeID]*Peer, inboundCount int, c *conn) error { +func (srv *Server) encHandshakeChecks(peers map[discover.ESSNodeID]*Peer, inboundCount int, c *conn) error { switch { case !c.is(trustedConn|staticDialedConn) && len(peers) >= srv.MaxPeers: return DiscTooManyPeers diff --git a/p2p/server_test.go b/p2p/server_test.go index 10c36528eb..0161692197 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -36,13 +36,13 @@ func init() { } type testTransport struct { - id discover.NodeID + id discover.ESSNodeID *rlpx closeErr error } -func newTestTransport(id discover.NodeID, fd net.Conn) transport { +func newTestTransport(id discover.ESSNodeID, fd net.Conn) transport { wrapped := newRLPX(fd).(*rlpx) wrapped.rw = newRLPXFrameRW(fd, secrets{ MAC: zero16, @@ -53,7 +53,7 @@ func newTestTransport(id discover.NodeID, fd net.Conn) transport { return &testTransport{id: id, rlpx: wrapped} } -func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error) { +func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.ESSNodeID, error) { return c.id, nil } @@ -66,7 +66,7 @@ func (c *testTransport) close(err error) { c.closeErr = err } -func startTestServer(t *testing.T, id discover.NodeID, pf func(*Peer)) *Server { +func startTestServer(t *testing.T, id discover.ESSNodeID, pf func(*Peer)) *Server { config := Config{ Name: "test", MaxPeers: 10, @@ -187,7 +187,7 @@ func TestServerTaskScheduling(t *testing.T) { quit, returned = make(chan struct{}), make(chan struct{}) tc = 0 tg = taskgen{ - newFunc: func(running int, peers map[discover.NodeID]*Peer) []task { + newFunc: func(running int, peers map[discover.ESSNodeID]*Peer) []task { tc++ return []task{&testTask{index: tc - 1}} }, @@ -260,7 +260,7 @@ func TestServerManyTasks(t *testing.T) { defer srv.Stop() srv.loopWG.Add(1) go srv.run(taskgen{ - newFunc: func(running int, peers map[discover.NodeID]*Peer) []task { + newFunc: func(running int, peers map[discover.ESSNodeID]*Peer) []task { start, end = end, end+maxActiveDialTasks+10 if end > len(alltasks) { end = len(alltasks) @@ -295,11 +295,11 @@ func TestServerManyTasks(t *testing.T) { } type taskgen struct { - newFunc func(running int, peers map[discover.NodeID]*Peer) []task + newFunc func(running int, peers map[discover.ESSNodeID]*Peer) []task doneFunc func(task) } -func (tg taskgen) newTasks(running int, peers map[discover.NodeID]*Peer, now time.Time) []task { +func (tg taskgen) newTasks(running int, peers map[discover.ESSNodeID]*Peer, now time.Time) []task { return tg.newFunc(running, peers) } func (tg taskgen) taskDone(t task, now time.Time) { @@ -337,7 +337,7 @@ func TestServerAtCap(t *testing.T) { } defer srv.Stop() - newconn := func(id discover.NodeID) *conn { + newconn := func(id discover.ESSNodeID) *conn { fd, _ := net.Pipe() tx := newTestTransport(id, fd) return &conn{fd: fd, transport: tx, flags: inboundConn, id: id, cont: make(chan error)} @@ -454,7 +454,7 @@ func TestServerSetupConn(t *testing.T) { } type setupTransport struct { - id discover.NodeID + id discover.ESSNodeID encHandshakeErr error phs *protoHandshake @@ -464,7 +464,7 @@ type setupTransport struct { closeErr error } -func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error) { +func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.ESSNodeID, error) { c.calls += "doEncHandshake," return c.id, c.encHandshakeErr } @@ -496,7 +496,7 @@ func newkey() *ecdsa.PrivateKey { return key } -func randomID() (id discover.NodeID) { +func randomID() (id discover.ESSNodeID) { for i := range id { id[i] = byte(rand.Intn(255)) } diff --git a/p2p/simulations/adapters/docker.go b/p2p/simulations/adapters/docker.go index d145c46b3a..d77294a0ee 100644 --- a/p2p/simulations/adapters/docker.go +++ b/p2p/simulations/adapters/docker.go @@ -64,7 +64,7 @@ func NewDockerAdapter() (*DockerAdapter, error) { return &DockerAdapter{ ExecAdapter{ - nodes: make(map[discover.NodeID]*ExecNode), + nodes: make(map[discover.ESSNodeID]*ExecNode), }, }, nil } diff --git a/p2p/simulations/adapters/exec.go b/p2p/simulations/adapters/exec.go index e64cebc2a7..842e412ed1 100644 --- a/p2p/simulations/adapters/exec.go +++ b/p2p/simulations/adapters/exec.go @@ -54,7 +54,7 @@ type ExecAdapter struct { // simulation node are created. BaseDir string - nodes map[discover.NodeID]*ExecNode + nodes map[discover.ESSNodeID]*ExecNode } // NewExecAdapter returns an ExecAdapter which stores node data in @@ -62,7 +62,7 @@ type ExecAdapter struct { func NewExecAdapter(baseDir string) *ExecAdapter { return &ExecAdapter{ BaseDir: baseDir, - nodes: make(map[discover.NodeID]*ExecNode), + nodes: make(map[discover.ESSNodeID]*ExecNode), } } @@ -122,7 +122,7 @@ func (e *ExecAdapter) NewNode(config *NodeConfig) (Node, error) { // ExecNode starts a simulation node by exec'ing the current binary and // running the configured services type ExecNode struct { - ID discover.NodeID + ID discover.ESSNodeID Dir string Config *execNodeConfig Cmd *exec.Cmd @@ -492,7 +492,7 @@ type wsRPCDialer struct { // DialRPC implements the RPCDialer interface by creating a WebSocket RPC // client of the given node -func (w *wsRPCDialer) DialRPC(id discover.NodeID) (*rpc.Client, error) { +func (w *wsRPCDialer) DialRPC(id discover.ESSNodeID) (*rpc.Client, error) { addr, ok := w.addrs[id.String()] if !ok { return nil, fmt.Errorf("unknown node: %s", id) diff --git a/p2p/simulations/adapters/inproc.go b/p2p/simulations/adapters/inproc.go index c1b032a0df..94124397f4 100644 --- a/p2p/simulations/adapters/inproc.go +++ b/p2p/simulations/adapters/inproc.go @@ -37,7 +37,7 @@ import ( type SimAdapter struct { pipe func() (net.Conn, net.Conn, error) mtx sync.RWMutex - nodes map[discover.NodeID]*SimNode + nodes map[discover.ESSNodeID]*SimNode services map[string]ServiceFunc } @@ -48,7 +48,7 @@ type SimAdapter struct { func NewSimAdapter(services map[string]ServiceFunc) *SimAdapter { return &SimAdapter{ pipe: pipes.NetPipe, - nodes: make(map[discover.NodeID]*SimNode), + nodes: make(map[discover.ESSNodeID]*SimNode), services: services, } } @@ -56,7 +56,7 @@ func NewSimAdapter(services map[string]ServiceFunc) *SimAdapter { func NewTCPAdapter(services map[string]ServiceFunc) *SimAdapter { return &SimAdapter{ pipe: pipes.TCPPipe, - nodes: make(map[discover.NodeID]*SimNode), + nodes: make(map[discover.ESSNodeID]*SimNode), services: services, } } @@ -138,7 +138,7 @@ func (s *SimAdapter) Dial(dest *discover.Node) (conn net.Conn, err error) { // DialRPC implements the RPCDialer interface by creating an in-memory RPC // client of the given node -func (s *SimAdapter) DialRPC(id discover.NodeID) (*rpc.Client, error) { +func (s *SimAdapter) DialRPC(id discover.ESSNodeID) (*rpc.Client, error) { node, ok := s.GetNode(id) if !ok { return nil, fmt.Errorf("unknown node: %s", id) @@ -151,7 +151,7 @@ func (s *SimAdapter) DialRPC(id discover.NodeID) (*rpc.Client, error) { } // GetNode returns the node with the given ID if it exists -func (s *SimAdapter) GetNode(id discover.NodeID) (*SimNode, bool) { +func (s *SimAdapter) GetNode(id discover.ESSNodeID) (*SimNode, bool) { s.mtx.RLock() defer s.mtx.RUnlock() node, ok := s.nodes[id] @@ -163,7 +163,7 @@ func (s *SimAdapter) GetNode(id discover.NodeID) (*SimNode, bool) { // pipe type SimNode struct { lock sync.RWMutex - ID discover.NodeID + ID discover.ESSNodeID config *NodeConfig adapter *SimAdapter node *node.Node diff --git a/p2p/simulations/adapters/types.go b/p2p/simulations/adapters/types.go index 2c4b9dd8f2..90cd8e3e6e 100644 --- a/p2p/simulations/adapters/types.go +++ b/p2p/simulations/adapters/types.go @@ -78,7 +78,7 @@ type NodeAdapter interface { type NodeConfig struct { // ID is the node's ID which is used to identify the node in the // simulation network - ID discover.NodeID + ID discover.ESSNodeID // PrivateKey is the node's private key which is used by the devp2p // stack to encrypt communications @@ -97,7 +97,7 @@ type NodeConfig struct { Services []string // function to sanction or prevent suggesting a peer - Reachable func(id discover.NodeID) bool + Reachable func(id discover.ESSNodeID) bool Port uint16 } @@ -218,7 +218,7 @@ type ServiceContext struct { // other nodes in the network (for example a simulated Swarm node which needs // to connect to a Geth node to resolve ENS names) type RPCDialer interface { - DialRPC(id discover.NodeID) (*rpc.Client, error) + DialRPC(id discover.ESSNodeID) (*rpc.Client, error) } // Services is a collection of services which can be run in a simulation diff --git a/p2p/simulations/examples/ping-pong.go b/p2p/simulations/examples/ping-pong.go index 6a0ead53a5..d277fe564e 100644 --- a/p2p/simulations/examples/ping-pong.go +++ b/p2p/simulations/examples/ping-pong.go @@ -96,12 +96,12 @@ func main() { // sends a ping to all its connected peers every 10s and receives a pong in // return type pingPongService struct { - id discover.NodeID + id discover.ESSNodeID log log.Logger received int64 } -func newPingPongService(id discover.NodeID) *pingPongService { +func newPingPongService(id discover.ESSNodeID) *pingPongService { return &pingPongService{ id: id, log: log.New("node.id", id), diff --git a/p2p/simulations/http_test.go b/p2p/simulations/http_test.go index 732d49f546..67842ee1ae 100644 --- a/p2p/simulations/http_test.go +++ b/p2p/simulations/http_test.go @@ -38,12 +38,12 @@ import ( // testService implements the node.Service interface and provides protocols // and APIs which are useful for testing nodes in a simulation network type testService struct { - id discover.NodeID + id discover.ESSNodeID // peerCount is incremented once a peer handshake has been performed peerCount int64 - peers map[discover.NodeID]*testPeer + peers map[discover.ESSNodeID]*testPeer peersMtx sync.Mutex // state stores []byte which is used to test creating and loading @@ -54,7 +54,7 @@ type testService struct { func newTestService(ctx *adapters.ServiceContext) (node.Service, error) { svc := &testService{ id: ctx.Config.ID, - peers: make(map[discover.NodeID]*testPeer), + peers: make(map[discover.ESSNodeID]*testPeer), } svc.state.Store(ctx.Snapshot) return svc, nil @@ -65,7 +65,7 @@ type testPeer struct { dumReady chan struct{} } -func (t *testService) peer(id discover.NodeID) *testPeer { +func (t *testService) peer(id discover.ESSNodeID) *testPeer { t.peersMtx.Lock() defer t.peersMtx.Unlock() if peer, ok := t.peers[id]; ok { diff --git a/p2p/simulations/mocker.go b/p2p/simulations/mocker.go index 389b1e3ec3..fa4e354580 100644 --- a/p2p/simulations/mocker.go +++ b/p2p/simulations/mocker.go @@ -154,7 +154,7 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) { wg.Done() continue } - go func(id discover.NodeID) { + go func(id discover.ESSNodeID) { time.Sleep(randWait) err := net.Start(id) if err != nil { @@ -169,8 +169,8 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) { } //connect nodeCount number of nodes in a ring -func connectNodesInRing(net *Network, nodeCount int) ([]discover.NodeID, error) { - ids := make([]discover.NodeID, nodeCount) +func connectNodesInRing(net *Network, nodeCount int) ([]discover.ESSNodeID, error) { + ids := make([]discover.ESSNodeID, nodeCount) for i := 0; i < nodeCount; i++ { conf := adapters.RandomNodeConfig() node, err := net.NewNodeWithConfig(conf) diff --git a/p2p/simulations/mocker_test.go b/p2p/simulations/mocker_test.go index de8ec0b337..d26343bdcf 100644 --- a/p2p/simulations/mocker_test.go +++ b/p2p/simulations/mocker_test.go @@ -82,7 +82,7 @@ func TestMocker(t *testing.T) { defer sub.Unsubscribe() //wait until all nodes are started and connected //store every node up event in a map (value is irrelevant, mimic Set datatype) - nodemap := make(map[discover.NodeID]bool) + nodemap := make(map[discover.ESSNodeID]bool) wg.Add(1) nodesComplete := false connCount := 0 diff --git a/p2p/simulations/network.go b/p2p/simulations/network.go index 0fb7485ad0..1f068375ff 100644 --- a/p2p/simulations/network.go +++ b/p2p/simulations/network.go @@ -51,7 +51,7 @@ type Network struct { NetworkConfig Nodes []*Node `json:"nodes"` - nodeMap map[discover.NodeID]int + nodeMap map[discover.ESSNodeID]int Conns []*Conn `json:"conns"` connMap map[string]int @@ -67,7 +67,7 @@ func NewNetwork(nodeAdapter adapters.NodeAdapter, conf *NetworkConfig) *Network return &Network{ NetworkConfig: *conf, nodeAdapter: nodeAdapter, - nodeMap: make(map[discover.NodeID]int), + nodeMap: make(map[discover.ESSNodeID]int), connMap: make(map[string]int), quitc: make(chan struct{}), } @@ -85,7 +85,7 @@ func (net *Network) NewNodeWithConfig(conf *adapters.NodeConfig) (*Node, error) defer net.lock.Unlock() if conf.Reachable == nil { - conf.Reachable = func(otherID discover.NodeID) bool { + conf.Reachable = func(otherID discover.ESSNodeID) bool { _, err := net.InitConn(conf.ID, otherID) if err != nil && bytes.Compare(conf.ID.Bytes(), otherID.Bytes()) < 0 { return false @@ -158,13 +158,13 @@ func (net *Network) StopAll() error { } // Start starts the node with the given ID -func (net *Network) Start(id discover.NodeID) error { +func (net *Network) Start(id discover.ESSNodeID) error { return net.startWithSnapshots(id, nil) } // startWithSnapshots starts the node with the given ID using the give // snapshots -func (net *Network) startWithSnapshots(id discover.NodeID, snapshots map[string][]byte) error { +func (net *Network) startWithSnapshots(id discover.ESSNodeID, snapshots map[string][]byte) error { net.lock.Lock() defer net.lock.Unlock() node := net.getNode(id) @@ -200,7 +200,7 @@ func (net *Network) startWithSnapshots(id discover.NodeID, snapshots map[string] // watchPeerEvents reads peer events from the given channel and emits // corresponding network events -func (net *Network) watchPeerEvents(id discover.NodeID, events chan *p2p.PeerEvent, sub event.Subscription) { +func (net *Network) watchPeerEvents(id discover.ESSNodeID, events chan *p2p.PeerEvent, sub event.Subscription) { defer func() { sub.Unsubscribe() @@ -248,7 +248,7 @@ func (net *Network) watchPeerEvents(id discover.NodeID, events chan *p2p.PeerEve } // Stop stops the node with the given ID -func (net *Network) Stop(id discover.NodeID) error { +func (net *Network) Stop(id discover.ESSNodeID) error { net.lock.Lock() defer net.lock.Unlock() node := net.getNode(id) @@ -270,7 +270,7 @@ func (net *Network) Stop(id discover.NodeID) error { // Connect connects two nodes together by calling the "admin_addPeer" RPC // method on the "one" node so that it connects to the "other" node -func (net *Network) Connect(oneID, otherID discover.NodeID) error { +func (net *Network) Connect(oneID, otherID discover.ESSNodeID) error { log.Debug(fmt.Sprintf("connecting %s to %s", oneID, otherID)) conn, err := net.InitConn(oneID, otherID) if err != nil { @@ -286,7 +286,7 @@ func (net *Network) Connect(oneID, otherID discover.NodeID) error { // Disconnect disconnects two nodes by calling the "admin_removePeer" RPC // method on the "one" node so that it disconnects from the "other" node -func (net *Network) Disconnect(oneID, otherID discover.NodeID) error { +func (net *Network) Disconnect(oneID, otherID discover.ESSNodeID) error { conn := net.GetConn(oneID, otherID) if conn == nil { return fmt.Errorf("connection between %v and %v does not exist", oneID, otherID) @@ -303,7 +303,7 @@ func (net *Network) Disconnect(oneID, otherID discover.NodeID) error { } // DidConnect tracks the fact that the "one" node connected to the "other" node -func (net *Network) DidConnect(one, other discover.NodeID) error { +func (net *Network) DidConnect(one, other discover.ESSNodeID) error { net.lock.Lock() defer net.lock.Unlock() conn, err := net.getOrCreateConn(one, other) @@ -320,7 +320,7 @@ func (net *Network) DidConnect(one, other discover.NodeID) error { // DidDisconnect tracks the fact that the "one" node disconnected from the // "other" node -func (net *Network) DidDisconnect(one, other discover.NodeID) error { +func (net *Network) DidDisconnect(one, other discover.ESSNodeID) error { net.lock.Lock() defer net.lock.Unlock() conn := net.getConn(one, other) @@ -337,7 +337,7 @@ func (net *Network) DidDisconnect(one, other discover.NodeID) error { } // DidSend tracks the fact that "sender" sent a message to "receiver" -func (net *Network) DidSend(sender, receiver discover.NodeID, proto string, code uint64) error { +func (net *Network) DidSend(sender, receiver discover.ESSNodeID, proto string, code uint64) error { msg := &Msg{ One: sender, Other: receiver, @@ -350,7 +350,7 @@ func (net *Network) DidSend(sender, receiver discover.NodeID, proto string, code } // DidReceive tracks the fact that "receiver" received a message from "sender" -func (net *Network) DidReceive(sender, receiver discover.NodeID, proto string, code uint64) error { +func (net *Network) DidReceive(sender, receiver discover.ESSNodeID, proto string, code uint64) error { msg := &Msg{ One: sender, Other: receiver, @@ -364,7 +364,7 @@ func (net *Network) DidReceive(sender, receiver discover.NodeID, proto string, c // GetNode gets the node with the given ID, returning nil if the node does not // exist -func (net *Network) GetNode(id discover.NodeID) *Node { +func (net *Network) GetNode(id discover.ESSNodeID) *Node { net.lock.Lock() defer net.lock.Unlock() return net.getNode(id) @@ -387,7 +387,7 @@ func (net *Network) GetNodes() (nodes []*Node) { return nodes } -func (net *Network) getNode(id discover.NodeID) *Node { +func (net *Network) getNode(id discover.ESSNodeID) *Node { i, found := net.nodeMap[id] if !found { return nil @@ -406,7 +406,7 @@ func (net *Network) getNodeByName(name string) *Node { // GetConn returns the connection which exists between "one" and "other" // regardless of which node initiated the connection -func (net *Network) GetConn(oneID, otherID discover.NodeID) *Conn { +func (net *Network) GetConn(oneID, otherID discover.ESSNodeID) *Conn { net.lock.Lock() defer net.lock.Unlock() return net.getConn(oneID, otherID) @@ -414,13 +414,13 @@ func (net *Network) GetConn(oneID, otherID discover.NodeID) *Conn { // GetOrCreateConn is like GetConn but creates the connection if it doesn't // already exist -func (net *Network) GetOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) { +func (net *Network) GetOrCreateConn(oneID, otherID discover.ESSNodeID) (*Conn, error) { net.lock.Lock() defer net.lock.Unlock() return net.getOrCreateConn(oneID, otherID) } -func (net *Network) getOrCreateConn(oneID, otherID discover.NodeID) (*Conn, error) { +func (net *Network) getOrCreateConn(oneID, otherID discover.ESSNodeID) (*Conn, error) { if conn := net.getConn(oneID, otherID); conn != nil { return conn, nil } @@ -445,7 +445,7 @@ func (net *Network) getOrCreateConn(oneID, otherID discover.NodeID) (*Conn, erro return conn, nil } -func (net *Network) getConn(oneID, otherID discover.NodeID) *Conn { +func (net *Network) getConn(oneID, otherID discover.ESSNodeID) *Conn { label := ConnLabel(oneID, otherID) i, found := net.connMap[label] if !found { @@ -462,7 +462,7 @@ func (net *Network) getConn(oneID, otherID discover.NodeID) *Conn { // it also checks whether there has been recent attempt to connect the peers // this is cheating as the simulation is used as an oracle and know about // remote peers attempt to connect to a node which will then not initiate the connection -func (net *Network) InitConn(oneID, otherID discover.NodeID) (*Conn, error) { +func (net *Network) InitConn(oneID, otherID discover.ESSNodeID) (*Conn, error) { net.lock.Lock() defer net.lock.Unlock() if oneID == otherID { @@ -508,7 +508,7 @@ func (net *Network) Reset() { //re-initialize the maps net.connMap = make(map[string]int) - net.nodeMap = make(map[discover.NodeID]int) + net.nodeMap = make(map[discover.ESSNodeID]int) net.Nodes = nil net.Conns = nil @@ -527,7 +527,7 @@ type Node struct { } // ID returns the ID of the node -func (n *Node) ID() discover.NodeID { +func (n *Node) ID() discover.ESSNodeID { return n.Config.ID } @@ -564,10 +564,10 @@ func (n *Node) MarshalJSON() ([]byte, error) { // Conn represents a connection between two nodes in the network type Conn struct { // One is the node which initiated the connection - One discover.NodeID `json:"one"` + One discover.ESSNodeID `json:"one"` // Other is the node which the connection was made to - Other discover.NodeID `json:"other"` + Other discover.ESSNodeID `json:"other"` // Up tracks whether or not the connection is active Up bool `json:"up"` @@ -596,8 +596,8 @@ func (c *Conn) String() string { // Msg represents a p2p message sent between two nodes in the network type Msg struct { - One discover.NodeID `json:"one"` - Other discover.NodeID `json:"other"` + One discover.ESSNodeID `json:"one"` + Other discover.ESSNodeID `json:"other"` Protocol string `json:"protocol"` Code uint64 `json:"code"` Received bool `json:"received"` @@ -611,8 +611,8 @@ func (m *Msg) String() string { // ConnLabel generates a deterministic string which represents a connection // between two nodes, used to compare if two connections are between the same // nodes -func ConnLabel(source, target discover.NodeID) string { - var first, second discover.NodeID +func ConnLabel(source, target discover.ESSNodeID) string { + var first, second discover.ESSNodeID if bytes.Compare(source.Bytes(), target.Bytes()) > 0 { first = target second = source diff --git a/p2p/simulations/network_test.go b/p2p/simulations/network_test.go index f178bac502..18c3c1db77 100644 --- a/p2p/simulations/network_test.go +++ b/p2p/simulations/network_test.go @@ -39,7 +39,7 @@ func TestNetworkSimulation(t *testing.T) { }) defer network.Shutdown() nodeCount := 20 - ids := make([]discover.NodeID, nodeCount) + ids := make([]discover.ESSNodeID, nodeCount) for i := 0; i < nodeCount; i++ { conf := adapters.RandomNodeConfig() node, err := network.NewNodeWithConfig(conf) @@ -64,7 +64,7 @@ func TestNetworkSimulation(t *testing.T) { } return nil } - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { // check we haven't run out of time select { case <-ctx.Done(): @@ -102,7 +102,7 @@ func TestNetworkSimulation(t *testing.T) { defer cancel() // trigger a check every 100ms - trigger := make(chan discover.NodeID) + trigger := make(chan discover.ESSNodeID) go triggerChecks(ctx, ids, trigger, 100*time.Millisecond) result := NewSimulation(network).Run(ctx, &Step{ @@ -140,7 +140,7 @@ func TestNetworkSimulation(t *testing.T) { } } -func triggerChecks(ctx context.Context, ids []discover.NodeID, trigger chan discover.NodeID, interval time.Duration) { +func triggerChecks(ctx context.Context, ids []discover.ESSNodeID, trigger chan discover.ESSNodeID, interval time.Duration) { tick := time.NewTicker(interval) defer tick.Stop() for { diff --git a/p2p/simulations/simulation.go b/p2p/simulations/simulation.go index 28886e924a..486962b3b5 100644 --- a/p2p/simulations/simulation.go +++ b/p2p/simulations/simulation.go @@ -55,7 +55,7 @@ func (s *Simulation) Run(ctx context.Context, step *Step) (result *StepResult) { } // wait for all node expectations to either pass, error or timeout - nodes := make(map[discover.NodeID]struct{}, len(step.Expect.Nodes)) + nodes := make(map[discover.ESSNodeID]struct{}, len(step.Expect.Nodes)) for _, id := range step.Expect.Nodes { nodes[id] = struct{}{} } @@ -119,7 +119,7 @@ type Step struct { // Trigger is a channel which receives node ids and triggers an // expectation check for that node - Trigger chan discover.NodeID + Trigger chan discover.ESSNodeID // Expect is the expectation to wait for when performing this step Expect *Expectation @@ -127,15 +127,15 @@ type Step struct { type Expectation struct { // Nodes is a list of nodes to check - Nodes []discover.NodeID + Nodes []discover.ESSNodeID // Check checks whether a given node meets the expectation - Check func(context.Context, discover.NodeID) (bool, error) + Check func(context.Context, discover.ESSNodeID) (bool, error) } func newStepResult() *StepResult { return &StepResult{ - Passes: make(map[discover.NodeID]time.Time), + Passes: make(map[discover.ESSNodeID]time.Time), } } @@ -150,7 +150,7 @@ type StepResult struct { FinishedAt time.Time // Passes are the timestamps of the successful node expectations - Passes map[discover.NodeID]time.Time + Passes map[discover.ESSNodeID]time.Time // NetworkEvents are the network events which occurred during the step NetworkEvents []*Event diff --git a/p2p/testing/peerpool.go b/p2p/testing/peerpool.go index ed00396e23..465fe8d10e 100644 --- a/p2p/testing/peerpool.go +++ b/p2p/testing/peerpool.go @@ -25,18 +25,18 @@ import ( ) type TestPeer interface { - ID() discover.NodeID + ID() discover.ESSNodeID Drop(error) } // TestPeerPool is an example peerPool to demonstrate registration of peer connections type TestPeerPool struct { lock sync.Mutex - peers map[discover.NodeID]TestPeer + peers map[discover.ESSNodeID]TestPeer } func NewTestPeerPool() *TestPeerPool { - return &TestPeerPool{peers: make(map[discover.NodeID]TestPeer)} + return &TestPeerPool{peers: make(map[discover.ESSNodeID]TestPeer)} } func (p *TestPeerPool) Add(peer TestPeer) { @@ -53,14 +53,14 @@ func (p *TestPeerPool) Remove(peer TestPeer) { delete(p.peers, peer.ID()) } -func (p *TestPeerPool) Has(id discover.NodeID) bool { +func (p *TestPeerPool) Has(id discover.ESSNodeID) bool { p.lock.Lock() defer p.lock.Unlock() _, ok := p.peers[id] return ok } -func (p *TestPeerPool) Get(id discover.NodeID) TestPeer { +func (p *TestPeerPool) Get(id discover.ESSNodeID) TestPeer { p.lock.Lock() defer p.lock.Unlock() return p.peers[id] diff --git a/p2p/testing/protocolsession.go b/p2p/testing/protocolsession.go index e3ec41ad67..4e87212cc2 100644 --- a/p2p/testing/protocolsession.go +++ b/p2p/testing/protocolsession.go @@ -35,7 +35,7 @@ var errTimedOut = errors.New("timed out") // receive (expect) messages type ProtocolSession struct { Server *p2p.Server - IDs []discover.NodeID + IDs []discover.ESSNodeID adapter *adapters.SimAdapter events chan *p2p.PeerEvent } @@ -58,7 +58,7 @@ type Exchange struct { type Trigger struct { Msg interface{} // type of message to be sent Code uint64 // code of message is given - Peer discover.NodeID // the peer to send the message to + Peer discover.ESSNodeID // the peer to send the message to Timeout time.Duration // timeout duration for the sending } @@ -67,13 +67,13 @@ type Trigger struct { type Expect struct { Msg interface{} // type of message to expect Code uint64 // code of message is now given - Peer discover.NodeID // the peer that expects the message + Peer discover.ESSNodeID // the peer that expects the message Timeout time.Duration // timeout duration for receiving } // Disconnect represents a disconnect event, used and checked by TestDisconnected type Disconnect struct { - Peer discover.NodeID // discconnected peer + Peer discover.ESSNodeID // discconnected peer Error error // disconnect reason } @@ -111,7 +111,7 @@ func (s *ProtocolSession) trigger(trig Trigger) error { // expect checks an expectation of a message sent out by the pivot node func (s *ProtocolSession) expect(exps []Expect) error { // construct a map of expectations for each node - peerExpects := make(map[discover.NodeID][]Expect) + peerExpects := make(map[discover.ESSNodeID][]Expect) for _, exp := range exps { if exp.Msg == nil { return errors.New("no message to expect") @@ -120,7 +120,7 @@ func (s *ProtocolSession) expect(exps []Expect) error { } // construct a map of mockNodes for each node - mockNodes := make(map[discover.NodeID]*mockNode) + mockNodes := make(map[discover.ESSNodeID]*mockNode) for nodeID := range peerExpects { simNode, ok := s.adapter.GetNode(nodeID) if !ok { @@ -253,7 +253,7 @@ func (s *ProtocolSession) testExchange(e Exchange) error { // TestDisconnected tests the disconnections given as arguments // the disconnect structs describe what disconnect error is expected on which peer func (s *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error { - expects := make(map[discover.NodeID]error) + expects := make(map[discover.ESSNodeID]error) for _, disconnect := range disconnects { expects[disconnect.Peer] = disconnect.Error } diff --git a/p2p/testing/protocoltester.go b/p2p/testing/protocoltester.go index c99578fe0b..43978e9a70 100644 --- a/p2p/testing/protocoltester.go +++ b/p2p/testing/protocoltester.go @@ -52,7 +52,7 @@ type ProtocolTester struct { // NewProtocolTester constructs a new ProtocolTester // it takes as argument the pivot node id, the number of dummy peers and the // protocol run function called on a peer connection by the p2p server -func NewProtocolTester(t *testing.T, id discover.NodeID, n int, run func(*p2p.Peer, p2p.MsgReadWriter) error) *ProtocolTester { +func NewProtocolTester(t *testing.T, id discover.ESSNodeID, n int, run func(*p2p.Peer, p2p.MsgReadWriter) error) *ProtocolTester { services := adapters.Services{ "test": func(ctx *adapters.ServiceContext) (node.Service, error) { return &testNode{run}, nil @@ -76,7 +76,7 @@ func NewProtocolTester(t *testing.T, id discover.NodeID, n int, run func(*p2p.Pe node := net.GetNode(id).Node.(*adapters.SimNode) peers := make([]*adapters.NodeConfig, n) - peerIDs := make([]discover.NodeID, n) + peerIDs := make([]discover.ESSNodeID, n) for i := 0; i < n; i++ { peers[i] = adapters.RandomNodeConfig() peers[i].Services = []string{"mock"} @@ -108,7 +108,7 @@ func (t *ProtocolTester) Stop() error { // Connect brings up the remote peer node and connects it using the // p2p/simulations network connection with the in memory network adapter -func (t *ProtocolTester) Connect(selfID discover.NodeID, peers ...*adapters.NodeConfig) { +func (t *ProtocolTester) Connect(selfID discover.ESSNodeID, peers ...*adapters.NodeConfig) { for _, peer := range peers { log.Trace(fmt.Sprintf("start node %v", peer.ID)) if _, err := t.network.NewNodeWithConfig(peer); err != nil { diff --git a/swarm/api/config.go b/swarm/api/config.go index 939285e09c..f2b607e3c2 100644 --- a/swarm/api/config.go +++ b/swarm/api/config.go @@ -58,7 +58,7 @@ type Config struct { Port string PublicKey string BzzKey string - NodeID string + ESSNodeID string NetworkID uint64 SwapEnabled bool SyncEnabled bool @@ -116,7 +116,7 @@ func (c *Config) Init(prvKey *ecdsa.PrivateKey) { c.PublicKey = pubkeyhex c.BzzKey = keyhex - c.NodeID = discover.PubkeyID(&prvKey.PublicKey).String() + c.ESSNodeID = discover.PubkeyID(&prvKey.PublicKey).String() if c.SwapEnabled { c.Swap.Init(c.Contract, prvKey) diff --git a/swarm/network/discovery.go b/swarm/network/discovery.go index 55bf7c0332..9568ef58f7 100644 --- a/swarm/network/discovery.go +++ b/swarm/network/discovery.go @@ -115,8 +115,8 @@ peersMsg is the message to pass peer information It is always a response to a peersRequestMsg The encoding of a peer address is identical the devp2p base protocol peers -messages: [IP, Port, NodeID], -Note that a node's FileStore address is not the NodeID but the hash of the NodeID. +messages: [IP, Port, ESSNodeID], +Note that a node's FileStore address is not the ESSNodeID but the hash of the ESSNodeID. TODO: To mitigate against spurious peers messages, requests should be remembered diff --git a/swarm/network/discovery_test.go b/swarm/network/discovery_test.go index 0427d81cad..cd0fc64b5e 100644 --- a/swarm/network/discovery_test.go +++ b/swarm/network/discovery_test.go @@ -32,7 +32,7 @@ func TestDiscovery(t *testing.T) { s, pp := newHiveTester(t, params, 1, nil) id := s.IDs[0] - raddr := NewAddrFromNodeID(id) + raddr := NewAddrFromESSNodeID(id) pp.Register([]OverlayAddr{OverlayAddr(raddr)}) // start the hive and wait for the connection diff --git a/swarm/network/hive.go b/swarm/network/hive.go index a54a17d29d..f7ce642735 100644 --- a/swarm/network/hive.go +++ b/swarm/network/hive.go @@ -99,7 +99,7 @@ func NewHive(params *HiveParams, overlay Overlay, store state.Store) *Hive { } // Start stars the hive, receives p2p.Server only at startup -// server is used to connect to a peer based on its NodeID or enode URL +// server is used to connect to a peer based on its ESSNodeID or enode URL // these are called on the p2p.Server which runs on the node func (h *Hive) Start(server *p2p.Server) error { log.Info(fmt.Sprintf("%08x hive starting", h.BaseAddr()[:4])) @@ -194,9 +194,9 @@ func (h *Hive) NodeInfo() interface{} { } // PeerInfo function is used by the p2p.server RPC interface to display -// protocol specific information any connected peer referred to by their NodeID -func (h *Hive) PeerInfo(id discover.NodeID) interface{} { - addr := NewAddrFromNodeID(id) +// protocol specific information any connected peer referred to by their ESSNodeID +func (h *Hive) PeerInfo(id discover.ESSNodeID) interface{} { + addr := NewAddrFromESSNodeID(id) return struct { OAddr hexutil.Bytes UAddr hexutil.Bytes diff --git a/swarm/network/hive_test.go b/swarm/network/hive_test.go index c2abfb2aad..e1acda375e 100644 --- a/swarm/network/hive_test.go +++ b/swarm/network/hive_test.go @@ -40,7 +40,7 @@ func TestRegisterAndConnect(t *testing.T) { s, pp := newHiveTester(t, params, 1, nil) id := s.IDs[0] - raddr := NewAddrFromNodeID(id) + raddr := NewAddrFromESSNodeID(id) pp.Register([]OverlayAddr{OverlayAddr(raddr)}) // start the hive and wait for the connection @@ -76,7 +76,7 @@ func TestHiveStatePersistance(t *testing.T) { peers := make(map[string]bool) for _, id := range s.IDs { - raddr := NewAddrFromNodeID(id) + raddr := NewAddrFromESSNodeID(id) pp.Register([]OverlayAddr{OverlayAddr(raddr)}) peers[raddr.String()] = true } diff --git a/swarm/network/networkid_test.go b/swarm/network/networkid_test.go index 05134b083b..67d3d9eb41 100644 --- a/swarm/network/networkid_test.go +++ b/swarm/network/networkid_test.go @@ -38,8 +38,8 @@ import ( var ( currentNetworkID int cnt int - nodeMap map[int][]discover.NodeID - kademlias map[discover.NodeID]*Kademlia + nodeMap map[int][]discover.ESSNodeID + kademlias map[discover.ESSNodeID]*Kademlia ) const ( @@ -70,7 +70,7 @@ func TestNetworkID(t *testing.T) { //arbitrarily set the number of nodes. It could be any number numNodes := 24 //the nodeMap maps all nodes (slice value) with the same network ID (key) - nodeMap = make(map[int][]discover.NodeID) + nodeMap = make(map[int][]discover.ESSNodeID) //set up the network and connect nodes net, err := setupNetwork(numNodes) if err != nil { @@ -183,12 +183,12 @@ func setupNetwork(numnodes int) (net *simulations.Network, err error) { } func newServices() adapters.Services { - kademlias = make(map[discover.NodeID]*Kademlia) - kademlia := func(id discover.NodeID) *Kademlia { + kademlias = make(map[discover.ESSNodeID]*Kademlia) + kademlia := func(id discover.ESSNodeID) *Kademlia { if k, ok := kademlias[id]; ok { return k } - addr := NewAddrFromNodeID(id) + addr := NewAddrFromESSNodeID(id) params := NewKadParams() params.MinProxBinSize = 2 params.MaxBinSize = 3 @@ -201,14 +201,14 @@ func newServices() adapters.Services { } return adapters.Services{ "bzz": func(ctx *adapters.ServiceContext) (node.Service, error) { - addr := NewAddrFromNodeID(ctx.Config.ID) + addr := NewAddrFromESSNodeID(ctx.Config.ID) hp := NewHiveParams() hp.Discovery = false cnt++ //assign the network ID currentNetworkID = cnt % NumberOfNets if ok := nodeMap[currentNetworkID]; ok == nil { - nodeMap[currentNetworkID] = make([]discover.NodeID, 0) + nodeMap[currentNetworkID] = make([]discover.ESSNodeID, 0) } //add this node to the group sharing the same network ID nodeMap[currentNetworkID] = append(nodeMap[currentNetworkID], ctx.Config.ID) @@ -224,7 +224,7 @@ func newServices() adapters.Services { } } -func watchSubscriptionEvents(ctx context.Context, id discover.NodeID, client *rpc.Client, errc chan error, quitC chan struct{}) { +func watchSubscriptionEvents(ctx context.Context, id discover.ESSNodeID, client *rpc.Client, errc chan error, quitC chan struct{}) { events := make(chan *p2p.PeerEvent) sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents") if err != nil { diff --git a/swarm/network/protocol.go b/swarm/network/protocol.go index 49ae5a15bf..0863017dc7 100644 --- a/swarm/network/protocol.go +++ b/swarm/network/protocol.go @@ -80,7 +80,7 @@ type Peer interface { // Conn interface represents an live peer connection type Conn interface { - ID() discover.NodeID // the key that uniquely identifies the Node for the peerPool + ID() discover.ESSNodeID // the key that uniquely identifies the Node for the peerPool Handshake(context.Context, interface{}, func(interface{}) error) (interface{}, error) // can send messages Send(context.Context, interface{}) error // can send messages Drop(error) // disconnect this peer @@ -102,7 +102,7 @@ type Bzz struct { NetworkID uint64 localAddr *BzzAddr mtx sync.Mutex - handshakes map[discover.NodeID]*HandshakeMsg + handshakes map[discover.ESSNodeID]*HandshakeMsg streamerSpec *protocols.Spec streamerRun func(*BzzPeer) error } @@ -117,7 +117,7 @@ func NewBzz(config *BzzConfig, kad Overlay, store state.Store, streamerSpec *pro Hive: NewHive(config.HiveParams, kad, store), NetworkID: config.NetworkID, localAddr: &BzzAddr{config.OverlayAddr, config.UnderlayAddr}, - handshakes: make(map[discover.NodeID]*HandshakeMsg), + handshakes: make(map[discover.ESSNodeID]*HandshakeMsg), streamerRun: streamerRun, streamerSpec: streamerSpec, } @@ -269,7 +269,7 @@ func NewBzzTestPeer(p *protocols.Peer, addr *BzzAddr) *BzzPeer { return &BzzPeer{ Peer: p, localAddr: addr, - BzzAddr: NewAddrFromNodeID(p.ID()), + BzzAddr: NewAddrFromESSNodeID(p.ID()), } } @@ -322,14 +322,14 @@ func (b *Bzz) checkHandshake(hs interface{}) error { // removeHandshake removes handshake for peer with peerID // from the bzz handshake store -func (b *Bzz) removeHandshake(peerID discover.NodeID) { +func (b *Bzz) removeHandshake(peerID discover.ESSNodeID) { b.mtx.Lock() defer b.mtx.Unlock() delete(b.handshakes, peerID) } // GetHandshake returns the bzz handhake that the remote peer with peerID sent -func (b *Bzz) GetHandshake(peerID discover.NodeID) (*HandshakeMsg, bool) { +func (b *Bzz) GetHandshake(peerID discover.ESSNodeID) (*HandshakeMsg, bool) { b.mtx.Lock() defer b.mtx.Unlock() handshake, found := b.handshakes[peerID] @@ -372,7 +372,7 @@ func (a *BzzAddr) Under() []byte { } // ID returns the nodeID from the underlay enode address -func (a *BzzAddr) ID() discover.NodeID { +func (a *BzzAddr) ID() discover.ESSNodeID { return discover.MustParseNode(string(a.UAddr)).ID } @@ -393,30 +393,30 @@ func RandomAddr() *BzzAddr { panic("unable to generate key") } pubkey := crypto.FromECDSAPub(&key.PublicKey) - var id discover.NodeID + var id discover.ESSNodeID copy(id[:], pubkey[1:]) - return NewAddrFromNodeID(id) + return NewAddrFromESSNodeID(id) } -// NewNodeIDFromAddr transforms the underlay address to an adapters.NodeID -func NewNodeIDFromAddr(addr Addr) discover.NodeID { +// NewESSNodeIDFromAddr transforms the underlay address to an adapters.ESSNodeID +func NewESSNodeIDFromAddr(addr Addr) discover.ESSNodeID { log.Info(fmt.Sprintf("uaddr=%s", string(addr.Under()))) node := discover.MustParseNode(string(addr.Under())) return node.ID } -// NewAddrFromNodeID constucts a BzzAddr from a discover.NodeID +// NewAddrFromESSNodeID constucts a BzzAddr from a discover.ESSNodeID // the overlay address is derived as the hash of the nodeID -func NewAddrFromNodeID(id discover.NodeID) *BzzAddr { +func NewAddrFromESSNodeID(id discover.ESSNodeID) *BzzAddr { return &BzzAddr{ OAddr: ToOverlayAddr(id.Bytes()), UAddr: []byte(discover.NewNode(id, net.IP{127, 0, 0, 1}, 30303, 30303).String()), } } -// NewAddrFromNodeIDAndPort constucts a BzzAddr from a discover.NodeID and port uint16 +// NewAddrFromESSNodeIDAndPort constucts a BzzAddr from a discover.ESSNodeID and port uint16 // the overlay address is derived as the hash of the nodeID -func NewAddrFromNodeIDAndPort(id discover.NodeID, host net.IP, port uint16) *BzzAddr { +func NewAddrFromESSNodeIDAndPort(id discover.ESSNodeID, host net.IP, port uint16) *BzzAddr { return &BzzAddr{ OAddr: ToOverlayAddr(id.Bytes()), UAddr: []byte(discover.NewNode(id, host, port, port).String()), diff --git a/swarm/network/protocol_test.go b/swarm/network/protocol_test.go index 63faf31088..fb562b32dc 100644 --- a/swarm/network/protocol_test.go +++ b/swarm/network/protocol_test.go @@ -66,7 +66,7 @@ func (t *testStore) Save(key string, v []byte) error { return nil } -func HandshakeMsgExchange(lhs, rhs *HandshakeMsg, id discover.NodeID) []p2ptest.Exchange { +func HandshakeMsgExchange(lhs, rhs *HandshakeMsg, id discover.ESSNodeID) []p2ptest.Exchange { return []p2ptest.Exchange{ { @@ -106,11 +106,11 @@ func newBzzBaseTester(t *testing.T, n int, addr *BzzAddr, spec *protocols.Spec, return srv(&BzzPeer{ Peer: protocols.NewPeer(p, rw, spec), localAddr: addr, - BzzAddr: NewAddrFromNodeID(p.ID()), + BzzAddr: NewAddrFromESSNodeID(p.ID()), }) } - s := p2ptest.NewProtocolTester(t, NewNodeIDFromAddr(addr), n, protocol) + s := p2ptest.NewProtocolTester(t, NewESSNodeIDFromAddr(addr), n, protocol) for _, id := range s.IDs { cs[id.String()] = make(chan bool) @@ -139,7 +139,7 @@ func newBzzHandshakeTester(t *testing.T, n int, addr *BzzAddr) *bzzTester { kad := NewKademlia(addr.OAddr, NewKadParams()) bzz := NewBzz(config, kad, nil, nil, nil) - s := p2ptest.NewProtocolTester(t, NewNodeIDFromAddr(addr), 1, bzz.runBzz) + s := p2ptest.NewProtocolTester(t, NewESSNodeIDFromAddr(addr), 1, bzz.runBzz) return &bzzTester{ addr: addr, @@ -149,14 +149,14 @@ func newBzzHandshakeTester(t *testing.T, n int, addr *BzzAddr) *bzzTester { // should test handshakes in one exchange? parallelisation func (s *bzzTester) testHandshake(lhs, rhs *HandshakeMsg, disconnects ...*p2ptest.Disconnect) error { - var peers []discover.NodeID - id := NewNodeIDFromAddr(rhs.Addr) + var peers []discover.ESSNodeID + id := NewESSNodeIDFromAddr(rhs.Addr) if len(disconnects) > 0 { for _, d := range disconnects { peers = append(peers, d.Peer) } } else { - peers = []discover.NodeID{id} + peers = []discover.ESSNodeID{id} } if err := s.TestExchanges(HandshakeMsgExchange(lhs, rhs, id)...); err != nil { @@ -199,7 +199,7 @@ func TestBzzHandshakeNetworkIDMismatch(t *testing.T) { err := s.testHandshake( correctBzzHandshake(addr), - &HandshakeMsg{Version: 5, NetworkID: 321, Addr: NewAddrFromNodeID(id)}, + &HandshakeMsg{Version: 5, NetworkID: 321, Addr: NewAddrFromESSNodeID(id)}, &p2ptest.Disconnect{Peer: id, Error: fmt.Errorf("Handshake error: Message handler error: (msg code 0): network id mismatch 321 (!= 3)")}, ) @@ -215,7 +215,7 @@ func TestBzzHandshakeVersionMismatch(t *testing.T) { err := s.testHandshake( correctBzzHandshake(addr), - &HandshakeMsg{Version: 0, NetworkID: 3, Addr: NewAddrFromNodeID(id)}, + &HandshakeMsg{Version: 0, NetworkID: 3, Addr: NewAddrFromESSNodeID(id)}, &p2ptest.Disconnect{Peer: id, Error: fmt.Errorf("Handshake error: Message handler error: (msg code 0): version mismatch 0 (!= 5)")}, ) @@ -231,7 +231,7 @@ func TestBzzHandshakeSuccess(t *testing.T) { err := s.testHandshake( correctBzzHandshake(addr), - &HandshakeMsg{Version: 5, NetworkID: 3, Addr: NewAddrFromNodeID(id)}, + &HandshakeMsg{Version: 5, NetworkID: 3, Addr: NewAddrFromESSNodeID(id)}, ) if err != nil { diff --git a/swarm/network/simulation/bucket.go b/swarm/network/simulation/bucket.go index b37afaaa45..8a7b03ff63 100644 --- a/swarm/network/simulation/bucket.go +++ b/swarm/network/simulation/bucket.go @@ -24,7 +24,7 @@ import ( type BucketKey string // NodeItem returns an item set in ServiceFunc function for a particualar node. -func (s *Simulation) NodeItem(id discover.NodeID, key interface{}) (value interface{}, ok bool) { +func (s *Simulation) NodeItem(id discover.ESSNodeID, key interface{}) (value interface{}, ok bool) { s.mu.Lock() defer s.mu.Unlock() @@ -34,9 +34,9 @@ func (s *Simulation) NodeItem(id discover.NodeID, key interface{}) (value interf return s.buckets[id].Load(key) } -// SetNodeItem sets a new item associated with the node with provided NodeID. +// SetNodeItem sets a new item associated with the node with provided ESSNodeID. // Buckets should be used to avoid managing separate simulation global state. -func (s *Simulation) SetNodeItem(id discover.NodeID, key interface{}, value interface{}) { +func (s *Simulation) SetNodeItem(id discover.ESSNodeID, key interface{}, value interface{}) { s.mu.Lock() defer s.mu.Unlock() @@ -45,12 +45,12 @@ func (s *Simulation) SetNodeItem(id discover.NodeID, key interface{}, value inte // NodeItems returns a map of items from all nodes that are all set under the // same BucketKey. -func (s *Simulation) NodesItems(key interface{}) (values map[discover.NodeID]interface{}) { +func (s *Simulation) NodesItems(key interface{}) (values map[discover.ESSNodeID]interface{}) { s.mu.RLock() defer s.mu.RUnlock() - ids := s.NodeIDs() - values = make(map[discover.NodeID]interface{}, len(ids)) + ids := s.ESSNodeIDs() + values = make(map[discover.ESSNodeID]interface{}, len(ids)) for _, id := range ids { if _, ok := s.buckets[id]; !ok { continue @@ -63,12 +63,12 @@ func (s *Simulation) NodesItems(key interface{}) (values map[discover.NodeID]int } // UpNodesItems returns a map of items with the same BucketKey from all nodes that are up. -func (s *Simulation) UpNodesItems(key interface{}) (values map[discover.NodeID]interface{}) { +func (s *Simulation) UpNodesItems(key interface{}) (values map[discover.ESSNodeID]interface{}) { s.mu.RLock() defer s.mu.RUnlock() - ids := s.UpNodeIDs() - values = make(map[discover.NodeID]interface{}) + ids := s.UpESSNodeIDs() + values = make(map[discover.ESSNodeID]interface{}) for _, id := range ids { if _, ok := s.buckets[id]; !ok { continue diff --git a/swarm/network/simulation/connect.go b/swarm/network/simulation/connect.go index 3fe82052b5..92bcef1fb1 100644 --- a/swarm/network/simulation/connect.go +++ b/swarm/network/simulation/connect.go @@ -22,24 +22,24 @@ import ( "github.com/ethereum/go-ethereum/p2p/discover" ) -// ConnectToPivotNode connects the node with provided NodeID +// ConnectToPivotNode connects the node with provided ESSNodeID // to the pivot node, already set by Simulation.SetPivotNode method. // It is useful when constructing a star network topology // when simulation adds and removes nodes dynamically. -func (s *Simulation) ConnectToPivotNode(id discover.NodeID) (err error) { - pid := s.PivotNodeID() +func (s *Simulation) ConnectToPivotNode(id discover.ESSNodeID) (err error) { + pid := s.PivotESSNodeID() if pid == nil { return ErrNoPivotNode } return s.connect(*pid, id) } -// ConnectToLastNode connects the node with provided NodeID +// ConnectToLastNode connects the node with provided ESSNodeID // to the last node that is up, and avoiding connection to self. // It is useful when constructing a chain network topology // when simulation adds and removes nodes dynamically. -func (s *Simulation) ConnectToLastNode(id discover.NodeID) (err error) { - ids := s.UpNodeIDs() +func (s *Simulation) ConnectToLastNode(id discover.ESSNodeID) (err error) { + ids := s.UpESSNodeIDs() l := len(ids) if l < 2 { return nil @@ -51,9 +51,9 @@ func (s *Simulation) ConnectToLastNode(id discover.NodeID) (err error) { return s.connect(lid, id) } -// ConnectToRandomNode connects the node with provieded NodeID +// ConnectToRandomNode connects the node with provieded ESSNodeID // to a random node that is up. -func (s *Simulation) ConnectToRandomNode(id discover.NodeID) (err error) { +func (s *Simulation) ConnectToRandomNode(id discover.ESSNodeID) (err error) { n := s.randomUpNode(id) if n == nil { return ErrNodeNotFound @@ -64,9 +64,9 @@ func (s *Simulation) ConnectToRandomNode(id discover.NodeID) (err error) { // ConnectNodesFull connects all nodes one to another. // It provides a complete connectivity in the network // which should be rarely needed. -func (s *Simulation) ConnectNodesFull(ids []discover.NodeID) (err error) { +func (s *Simulation) ConnectNodesFull(ids []discover.ESSNodeID) (err error) { if ids == nil { - ids = s.UpNodeIDs() + ids = s.UpESSNodeIDs() } l := len(ids) for i := 0; i < l; i++ { @@ -82,9 +82,9 @@ func (s *Simulation) ConnectNodesFull(ids []discover.NodeID) (err error) { // ConnectNodesChain connects all nodes in a chain topology. // If ids argument is nil, all nodes that are up will be connected. -func (s *Simulation) ConnectNodesChain(ids []discover.NodeID) (err error) { +func (s *Simulation) ConnectNodesChain(ids []discover.ESSNodeID) (err error) { if ids == nil { - ids = s.UpNodeIDs() + ids = s.UpESSNodeIDs() } l := len(ids) for i := 0; i < l-1; i++ { @@ -98,9 +98,9 @@ func (s *Simulation) ConnectNodesChain(ids []discover.NodeID) (err error) { // ConnectNodesRing connects all nodes in a ring topology. // If ids argument is nil, all nodes that are up will be connected. -func (s *Simulation) ConnectNodesRing(ids []discover.NodeID) (err error) { +func (s *Simulation) ConnectNodesRing(ids []discover.ESSNodeID) (err error) { if ids == nil { - ids = s.UpNodeIDs() + ids = s.UpESSNodeIDs() } l := len(ids) if l < 2 { @@ -116,11 +116,11 @@ func (s *Simulation) ConnectNodesRing(ids []discover.NodeID) (err error) { } // ConnectNodesStar connects all nodes in a star topology -// with the center at provided NodeID. +// with the center at provided ESSNodeID. // If ids argument is nil, all nodes that are up will be connected. -func (s *Simulation) ConnectNodesStar(id discover.NodeID, ids []discover.NodeID) (err error) { +func (s *Simulation) ConnectNodesStar(id discover.ESSNodeID, ids []discover.ESSNodeID) (err error) { if ids == nil { - ids = s.UpNodeIDs() + ids = s.UpESSNodeIDs() } l := len(ids) for i := 0; i < l; i++ { @@ -138,8 +138,8 @@ func (s *Simulation) ConnectNodesStar(id discover.NodeID, ids []discover.NodeID) // ConnectNodesStar connects all nodes in a star topology // with the center at already set pivot node. // If ids argument is nil, all nodes that are up will be connected. -func (s *Simulation) ConnectNodesStarPivot(ids []discover.NodeID) (err error) { - id := s.PivotNodeID() +func (s *Simulation) ConnectNodesStarPivot(ids []discover.ESSNodeID) (err error) { + id := s.PivotESSNodeID() if id == nil { return ErrNoPivotNode } @@ -147,7 +147,7 @@ func (s *Simulation) ConnectNodesStarPivot(ids []discover.NodeID) (err error) { } // connect connects two nodes but ignores already connected error. -func (s *Simulation) connect(oneID, otherID discover.NodeID) error { +func (s *Simulation) connect(oneID, otherID discover.ESSNodeID) error { return ignoreAlreadyConnectedErr(s.Net.Connect(oneID, otherID)) } diff --git a/swarm/network/simulation/connect_test.go b/swarm/network/simulation/connect_test.go index 10d73e4a1c..9c19848d2b 100644 --- a/swarm/network/simulation/connect_test.go +++ b/swarm/network/simulation/connect_test.go @@ -143,7 +143,7 @@ func TestConnectNodesFull(t *testing.T) { testFull(t, sim, ids) } -func testFull(t *testing.T, sim *Simulation, ids []discover.NodeID) { +func testFull(t *testing.T, sim *Simulation, ids []discover.ESSNodeID) { n := len(ids) var cc int for i := 0; i < n; i++ { @@ -182,7 +182,7 @@ func TestConnectNodesChain(t *testing.T) { testChain(t, sim, ids) } -func testChain(t *testing.T, sim *Simulation, ids []discover.NodeID) { +func testChain(t *testing.T, sim *Simulation, ids []discover.ESSNodeID) { n := len(ids) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { @@ -221,7 +221,7 @@ func TestConnectNodesRing(t *testing.T) { testRing(t, sim, ids) } -func testRing(t *testing.T, sim *Simulation, ids []discover.NodeID) { +func testRing(t *testing.T, sim *Simulation, ids []discover.ESSNodeID) { n := len(ids) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { @@ -262,7 +262,7 @@ func TestConnectToNodesStar(t *testing.T) { testStar(t, sim, ids, centerIndex) } -func testStar(t *testing.T, sim *Simulation, ids []discover.NodeID, centerIndex int) { +func testStar(t *testing.T, sim *Simulation, ids []discover.ESSNodeID, centerIndex int) { n := len(ids) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { diff --git a/swarm/network/simulation/events.go b/swarm/network/simulation/events.go index f9cfadb73e..a67a313e6f 100644 --- a/swarm/network/simulation/events.go +++ b/swarm/network/simulation/events.go @@ -26,8 +26,8 @@ import ( // PeerEvent is the type of the channel returned by Simulation.PeerEvents. type PeerEvent struct { - // NodeID is the ID of node that the event is caught on. - NodeID discover.NodeID + // ESSNodeID is the ID of node that the event is caught on. + ESSNodeID discover.ESSNodeID // Event is the event that is caught. Event *p2p.PeerEvent // Error is the error that may have happened during event watching. @@ -66,25 +66,25 @@ func (f *PeerEventsFilter) MsgCode(c uint64) *PeerEventsFilter { } // PeerEvents returns a channel of events that are captured by admin peerEvents -// subscription nodes with provided NodeIDs. Additional filters can be set to ignore +// subscription nodes with provided ESSNodeIDs. Additional filters can be set to ignore // events that are not relevant. -func (s *Simulation) PeerEvents(ctx context.Context, ids []discover.NodeID, filters ...*PeerEventsFilter) <-chan PeerEvent { +func (s *Simulation) PeerEvents(ctx context.Context, ids []discover.ESSNodeID, filters ...*PeerEventsFilter) <-chan PeerEvent { eventC := make(chan PeerEvent) for _, id := range ids { s.shutdownWG.Add(1) - go func(id discover.NodeID) { + go func(id discover.ESSNodeID) { defer s.shutdownWG.Done() client, err := s.Net.GetNode(id).Client() if err != nil { - eventC <- PeerEvent{NodeID: id, Error: err} + eventC <- PeerEvent{ESSNodeID: id, Error: err} return } events := make(chan *p2p.PeerEvent) sub, err := client.Subscribe(ctx, "admin", events, "peerEvents") if err != nil { - eventC <- PeerEvent{NodeID: id, Error: err} + eventC <- PeerEvent{ESSNodeID: id, Error: err} return } defer sub.Unsubscribe() @@ -94,7 +94,7 @@ func (s *Simulation) PeerEvents(ctx context.Context, ids []discover.NodeID, filt case <-ctx.Done(): if err := ctx.Err(); err != nil { select { - case eventC <- PeerEvent{NodeID: id, Error: err}: + case eventC <- PeerEvent{ESSNodeID: id, Error: err}: case <-s.Done(): } } @@ -119,11 +119,11 @@ func (s *Simulation) PeerEvents(ctx context.Context, ids []discover.NodeID, filt } if match { select { - case eventC <- PeerEvent{NodeID: id, Event: e}: + case eventC <- PeerEvent{ESSNodeID: id, Event: e}: case <-ctx.Done(): if err := ctx.Err(); err != nil { select { - case eventC <- PeerEvent{NodeID: id, Error: err}: + case eventC <- PeerEvent{ESSNodeID: id, Error: err}: case <-s.Done(): } } @@ -135,11 +135,11 @@ func (s *Simulation) PeerEvents(ctx context.Context, ids []discover.NodeID, filt case err := <-sub.Err(): if err != nil { select { - case eventC <- PeerEvent{NodeID: id, Error: err}: + case eventC <- PeerEvent{ESSNodeID: id, Error: err}: case <-ctx.Done(): if err := ctx.Err(); err != nil { select { - case eventC <- PeerEvent{NodeID: id, Error: err}: + case eventC <- PeerEvent{ESSNodeID: id, Error: err}: case <-s.Done(): } } diff --git a/swarm/network/simulation/events_test.go b/swarm/network/simulation/events_test.go index 0c185d9774..16bfab060f 100644 --- a/swarm/network/simulation/events_test.go +++ b/swarm/network/simulation/events_test.go @@ -38,7 +38,7 @@ func TestPeerEvents(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - events := sim.PeerEvents(ctx, sim.NodeIDs()) + events := sim.PeerEvents(ctx, sim.ESSNodeIDs()) // two nodes -> two connection events expectedEventCount := 2 @@ -59,7 +59,7 @@ func TestPeerEvents(t *testing.T) { } }() - err = sim.ConnectNodesChain(sim.NodeIDs()) + err = sim.ConnectNodesChain(sim.ESSNodeIDs()) if err != nil { t.Fatal(err) } @@ -78,7 +78,7 @@ func TestPeerEventsTimeout(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() - events := sim.PeerEvents(ctx, sim.NodeIDs()) + events := sim.PeerEvents(ctx, sim.ESSNodeIDs()) done := make(chan struct{}) go func() { diff --git a/swarm/network/simulation/example_test.go b/swarm/network/simulation/example_test.go index 2a8116921a..4166e8d40b 100644 --- a/swarm/network/simulation/example_test.go +++ b/swarm/network/simulation/example_test.go @@ -36,7 +36,7 @@ import ( func ExampleSimulation_WaitTillHealthy() { sim := simulation.New(map[string]simulation.ServiceFunc{ "bzz": func(ctx *adapters.ServiceContext, b *sync.Map) (node.Service, func(), error) { - addr := network.NewAddrFromNodeID(ctx.Config.ID) + addr := network.NewAddrFromESSNodeID(ctx.Config.ID) hp := network.NewHiveParams() hp.Discovery = false config := &network.BzzConfig{ @@ -79,7 +79,7 @@ func ExampleSimulation_PeerEvents() { sim := simulation.New(nil) defer sim.Close() - events := sim.PeerEvents(context.Background(), sim.NodeIDs()) + events := sim.PeerEvents(context.Background(), sim.ESSNodeIDs()) go func() { for e := range events { @@ -87,7 +87,7 @@ func ExampleSimulation_PeerEvents() { log.Error("peer event", "err", e.Error) continue } - log.Info("peer event", "node", e.NodeID, "peer", e.Event.Peer, "msgcode", e.Event.MsgCode) + log.Info("peer event", "node", e.ESSNodeID, "peer", e.Event.Peer, "msgcode", e.Event.MsgCode) } }() } @@ -99,7 +99,7 @@ func ExampleSimulation_PeerEvents_disconnections() { disconnections := sim.PeerEvents( context.Background(), - sim.NodeIDs(), + sim.ESSNodeIDs(), simulation.NewPeerEventsFilter().Type(p2p.PeerEventTypeDrop), ) @@ -109,7 +109,7 @@ func ExampleSimulation_PeerEvents_disconnections() { log.Error("peer drop", "err", d.Error) continue } - log.Warn("peer drop", "node", d.NodeID, "peer", d.Event.Peer) + log.Warn("peer drop", "node", d.ESSNodeID, "peer", d.Event.Peer) } }() } @@ -122,7 +122,7 @@ func ExampleSimulation_PeerEvents_multipleFilters() { msgs := sim.PeerEvents( context.Background(), - sim.NodeIDs(), + sim.ESSNodeIDs(), // Watch when bzz messages 1 and 4 are received. simulation.NewPeerEventsFilter().Type(p2p.PeerEventTypeMsgRecv).Protocol("bzz").MsgCode(1), simulation.NewPeerEventsFilter().Type(p2p.PeerEventTypeMsgRecv).Protocol("bzz").MsgCode(4), @@ -134,7 +134,7 @@ func ExampleSimulation_PeerEvents_multipleFilters() { log.Error("bzz message", "err", m.Error) continue } - log.Info("bzz message", "node", m.NodeID, "peer", m.Event.Peer) + log.Info("bzz message", "node", m.ESSNodeID, "peer", m.Event.Peer) } }() } diff --git a/swarm/network/simulation/kademlia.go b/swarm/network/simulation/kademlia.go index 3e45cb0ce1..513efd1410 100644 --- a/swarm/network/simulation/kademlia.go +++ b/swarm/network/simulation/kademlia.go @@ -34,7 +34,7 @@ var BucketKeyKademlia BucketKey = "kademlia" // WaitTillHealthy is blocking until the health of all kademlias is true. // If error is not nil, a map of kademlia that was found not healthy is returned. -func (s *Simulation) WaitTillHealthy(ctx context.Context, kadMinProxSize int) (ill map[discover.NodeID]*network.Kademlia, err error) { +func (s *Simulation) WaitTillHealthy(ctx context.Context, kadMinProxSize int) (ill map[discover.ESSNodeID]*network.Kademlia, err error) { // Prepare PeerPot map for checking Kademlia health var ppmap map[string]*network.PeerPot kademlias := s.kademlias() @@ -48,7 +48,7 @@ func (s *Simulation) WaitTillHealthy(ctx context.Context, kadMinProxSize int) (i ticker := time.NewTicker(200 * time.Millisecond) defer ticker.Stop() - ill = make(map[discover.NodeID]*network.Kademlia) + ill = make(map[discover.ESSNodeID]*network.Kademlia) for { select { case <-ctx.Done(): @@ -82,9 +82,9 @@ func (s *Simulation) WaitTillHealthy(ctx context.Context, kadMinProxSize int) (i // kademlias returns all Kademlia instances that are set // in simulation bucket. -func (s *Simulation) kademlias() (ks map[discover.NodeID]*network.Kademlia) { +func (s *Simulation) kademlias() (ks map[discover.ESSNodeID]*network.Kademlia) { items := s.UpNodesItems(BucketKeyKademlia) - ks = make(map[discover.NodeID]*network.Kademlia, len(items)) + ks = make(map[discover.ESSNodeID]*network.Kademlia, len(items)) for id, v := range items { k, ok := v.(*network.Kademlia) if !ok { diff --git a/swarm/network/simulation/kademlia_test.go b/swarm/network/simulation/kademlia_test.go index d11fe7e41f..4ee7b2c86d 100644 --- a/swarm/network/simulation/kademlia_test.go +++ b/swarm/network/simulation/kademlia_test.go @@ -30,7 +30,7 @@ import ( func TestWaitTillHealthy(t *testing.T) { sim := New(map[string]ServiceFunc{ "bzz": func(ctx *adapters.ServiceContext, b *sync.Map) (node.Service, func(), error) { - addr := network.NewAddrFromNodeID(ctx.Config.ID) + addr := network.NewAddrFromESSNodeID(ctx.Config.ID) hp := network.NewHiveParams() hp.Discovery = false config := &network.BzzConfig{ diff --git a/swarm/network/simulation/node.go b/swarm/network/simulation/node.go index bc433cfd83..9f318ab22d 100644 --- a/swarm/network/simulation/node.go +++ b/swarm/network/simulation/node.go @@ -30,18 +30,18 @@ import ( "github.com/ethereum/go-ethereum/p2p/simulations/adapters" ) -// NodeIDs returns NodeIDs for all nodes in the network. -func (s *Simulation) NodeIDs() (ids []discover.NodeID) { +// ESSNodeIDs returns ESSNodeIDs for all nodes in the network. +func (s *Simulation) ESSNodeIDs() (ids []discover.ESSNodeID) { nodes := s.Net.GetNodes() - ids = make([]discover.NodeID, len(nodes)) + ids = make([]discover.ESSNodeID, len(nodes)) for i, node := range nodes { ids[i] = node.ID() } return ids } -// UpNodeIDs returns NodeIDs for nodes that are up in the network. -func (s *Simulation) UpNodeIDs() (ids []discover.NodeID) { +// UpESSNodeIDs returns ESSNodeIDs for nodes that are up in the network. +func (s *Simulation) UpESSNodeIDs() (ids []discover.ESSNodeID) { nodes := s.Net.GetNodes() for _, node := range nodes { if node.Up { @@ -51,8 +51,8 @@ func (s *Simulation) UpNodeIDs() (ids []discover.NodeID) { return ids } -// DownNodeIDs returns NodeIDs for nodes that are stopped in the network. -func (s *Simulation) DownNodeIDs() (ids []discover.NodeID) { +// DownESSNodeIDs returns ESSNodeIDs for nodes that are stopped in the network. +func (s *Simulation) DownESSNodeIDs() (ids []discover.ESSNodeID) { nodes := s.Net.GetNodes() for _, node := range nodes { if !node.Up { @@ -88,7 +88,7 @@ func AddNodeWithService(serviceName string) AddNodeOption { // applies provided options to the config and adds the node to network. // By default all services will be started on a node. If one or more // AddNodeWithService option are provided, only specified services will be started. -func (s *Simulation) AddNode(opts ...AddNodeOption) (id discover.NodeID, err error) { +func (s *Simulation) AddNode(opts ...AddNodeOption) (id discover.ESSNodeID, err error) { conf := adapters.RandomNodeConfig() for _, o := range opts { o(conf) @@ -105,8 +105,8 @@ func (s *Simulation) AddNode(opts ...AddNodeOption) (id discover.NodeID, err err // AddNodes creates new nodes with random configurations, // applies provided options to the config and adds nodes to network. -func (s *Simulation) AddNodes(count int, opts ...AddNodeOption) (ids []discover.NodeID, err error) { - ids = make([]discover.NodeID, 0, count) +func (s *Simulation) AddNodes(count int, opts ...AddNodeOption) (ids []discover.ESSNodeID, err error) { + ids = make([]discover.ESSNodeID, 0, count) for i := 0; i < count; i++ { id, err := s.AddNode(opts...) if err != nil { @@ -119,7 +119,7 @@ func (s *Simulation) AddNodes(count int, opts ...AddNodeOption) (ids []discover. // AddNodesAndConnectFull is a helpper method that combines // AddNodes and ConnectNodesFull. Only new nodes will be connected. -func (s *Simulation) AddNodesAndConnectFull(count int, opts ...AddNodeOption) (ids []discover.NodeID, err error) { +func (s *Simulation) AddNodesAndConnectFull(count int, opts ...AddNodeOption) (ids []discover.ESSNodeID, err error) { if count < 2 { return nil, errors.New("count of nodes must be at least 2") } @@ -137,7 +137,7 @@ func (s *Simulation) AddNodesAndConnectFull(count int, opts ...AddNodeOption) (i // AddNodesAndConnectChain is a helpper method that combines // AddNodes and ConnectNodesChain. The chain will be continued from the last // added node, if there is one in simulation using ConnectToLastNode method. -func (s *Simulation) AddNodesAndConnectChain(count int, opts ...AddNodeOption) (ids []discover.NodeID, err error) { +func (s *Simulation) AddNodesAndConnectChain(count int, opts ...AddNodeOption) (ids []discover.ESSNodeID, err error) { if count < 2 { return nil, errors.New("count of nodes must be at least 2") } @@ -153,7 +153,7 @@ func (s *Simulation) AddNodesAndConnectChain(count int, opts ...AddNodeOption) ( if err != nil { return nil, err } - ids = append([]discover.NodeID{id}, ids...) + ids = append([]discover.ESSNodeID{id}, ids...) err = s.ConnectNodesChain(ids) if err != nil { return nil, err @@ -163,7 +163,7 @@ func (s *Simulation) AddNodesAndConnectChain(count int, opts ...AddNodeOption) ( // AddNodesAndConnectRing is a helpper method that combines // AddNodes and ConnectNodesRing. -func (s *Simulation) AddNodesAndConnectRing(count int, opts ...AddNodeOption) (ids []discover.NodeID, err error) { +func (s *Simulation) AddNodesAndConnectRing(count int, opts ...AddNodeOption) (ids []discover.ESSNodeID, err error) { if count < 2 { return nil, errors.New("count of nodes must be at least 2") } @@ -180,7 +180,7 @@ func (s *Simulation) AddNodesAndConnectRing(count int, opts ...AddNodeOption) (i // AddNodesAndConnectStar is a helpper method that combines // AddNodes and ConnectNodesStar. -func (s *Simulation) AddNodesAndConnectStar(count int, opts ...AddNodeOption) (ids []discover.NodeID, err error) { +func (s *Simulation) AddNodesAndConnectStar(count int, opts ...AddNodeOption) (ids []discover.ESSNodeID, err error) { if count < 2 { return nil, errors.New("count of nodes must be at least 2") } @@ -236,32 +236,32 @@ func (s *Simulation) UploadSnapshot(snapshotFile string, opts ...AddNodeOption) return nil } -// SetPivotNode sets the NodeID of the network's pivot node. +// SetPivotNode sets the ESSNodeID of the network's pivot node. // Pivot node is just a specific node that should be treated // differently then other nodes in test. SetPivotNode and -// PivotNodeID are just a convenient functions to set and +// PivotESSNodeID are just a convenient functions to set and // retrieve it. -func (s *Simulation) SetPivotNode(id discover.NodeID) { +func (s *Simulation) SetPivotNode(id discover.ESSNodeID) { s.mu.Lock() defer s.mu.Unlock() - s.pivotNodeID = &id + s.pivotESSNodeID = &id } -// PivotNodeID returns NodeID of the pivot node set by +// PivotESSNodeID returns ESSNodeID of the pivot node set by // Simulation.SetPivotNode method. -func (s *Simulation) PivotNodeID() (id *discover.NodeID) { +func (s *Simulation) PivotESSNodeID() (id *discover.ESSNodeID) { s.mu.Lock() defer s.mu.Unlock() - return s.pivotNodeID + return s.pivotESSNodeID } -// StartNode starts a node by NodeID. -func (s *Simulation) StartNode(id discover.NodeID) (err error) { +// StartNode starts a node by ESSNodeID. +func (s *Simulation) StartNode(id discover.ESSNodeID) (err error) { return s.Net.Start(id) } // StartRandomNode starts a random node. -func (s *Simulation) StartRandomNode() (id discover.NodeID, err error) { +func (s *Simulation) StartRandomNode() (id discover.ESSNodeID, err error) { n := s.randomDownNode() if n == nil { return id, ErrNodeNotFound @@ -270,9 +270,9 @@ func (s *Simulation) StartRandomNode() (id discover.NodeID, err error) { } // StartRandomNodes starts random nodes. -func (s *Simulation) StartRandomNodes(count int) (ids []discover.NodeID, err error) { - ids = make([]discover.NodeID, 0, count) - downIDs := s.DownNodeIDs() +func (s *Simulation) StartRandomNodes(count int) (ids []discover.ESSNodeID, err error) { + ids = make([]discover.ESSNodeID, 0, count) + downIDs := s.DownESSNodeIDs() for i := 0; i < count; i++ { n := s.randomNode(downIDs, ids...) if n == nil { @@ -287,13 +287,13 @@ func (s *Simulation) StartRandomNodes(count int) (ids []discover.NodeID, err err return ids, nil } -// StopNode stops a node by NodeID. -func (s *Simulation) StopNode(id discover.NodeID) (err error) { +// StopNode stops a node by ESSNodeID. +func (s *Simulation) StopNode(id discover.ESSNodeID) (err error) { return s.Net.Stop(id) } // StopRandomNode stops a random node. -func (s *Simulation) StopRandomNode() (id discover.NodeID, err error) { +func (s *Simulation) StopRandomNode() (id discover.ESSNodeID, err error) { n := s.randomUpNode() if n == nil { return id, ErrNodeNotFound @@ -302,9 +302,9 @@ func (s *Simulation) StopRandomNode() (id discover.NodeID, err error) { } // StopRandomNodes stops random nodes. -func (s *Simulation) StopRandomNodes(count int) (ids []discover.NodeID, err error) { - ids = make([]discover.NodeID, 0, count) - upIDs := s.UpNodeIDs() +func (s *Simulation) StopRandomNodes(count int) (ids []discover.ESSNodeID, err error) { + ids = make([]discover.ESSNodeID, 0, count) + upIDs := s.UpESSNodeIDs() for i := 0; i < count; i++ { n := s.randomNode(upIDs, ids...) if n == nil { @@ -325,18 +325,18 @@ func init() { } // randomUpNode returns a random SimNode that is up. -// Arguments are NodeIDs for nodes that should not be returned. -func (s *Simulation) randomUpNode(exclude ...discover.NodeID) *adapters.SimNode { - return s.randomNode(s.UpNodeIDs(), exclude...) +// Arguments are ESSNodeIDs for nodes that should not be returned. +func (s *Simulation) randomUpNode(exclude ...discover.ESSNodeID) *adapters.SimNode { + return s.randomNode(s.UpESSNodeIDs(), exclude...) } // randomUpNode returns a random SimNode that is not up. -func (s *Simulation) randomDownNode(exclude ...discover.NodeID) *adapters.SimNode { - return s.randomNode(s.DownNodeIDs(), exclude...) +func (s *Simulation) randomDownNode(exclude ...discover.ESSNodeID) *adapters.SimNode { + return s.randomNode(s.DownESSNodeIDs(), exclude...) } -// randomUpNode returns a random SimNode from the slice of NodeIDs. -func (s *Simulation) randomNode(ids []discover.NodeID, exclude ...discover.NodeID) *adapters.SimNode { +// randomUpNode returns a random SimNode from the slice of ESSNodeIDs. +func (s *Simulation) randomNode(ids []discover.ESSNodeID, exclude ...discover.ESSNodeID) *adapters.SimNode { for _, e := range exclude { var i int for _, id := range ids { diff --git a/swarm/network/simulation/node_test.go b/swarm/network/simulation/node_test.go index 94f0b4fac0..0044468ae7 100644 --- a/swarm/network/simulation/node_test.go +++ b/swarm/network/simulation/node_test.go @@ -30,7 +30,7 @@ import ( "github.com/ethereum/go-ethereum/swarm/network" ) -func TestUpDownNodeIDs(t *testing.T) { +func TestUpDownESSNodeIDs(t *testing.T) { sim := New(noopServiceFuncMap) defer sim.Close() @@ -39,9 +39,9 @@ func TestUpDownNodeIDs(t *testing.T) { t.Fatal(err) } - gotIDs := sim.NodeIDs() + gotIDs := sim.ESSNodeIDs() - if !equalNodeIDs(ids, gotIDs) { + if !equalESSNodeIDs(ids, gotIDs) { t.Error("returned nodes are not equal to added ones") } @@ -50,7 +50,7 @@ func TestUpDownNodeIDs(t *testing.T) { t.Fatal(err) } - gotIDs = sim.UpNodeIDs() + gotIDs = sim.UpESSNodeIDs() for _, id := range gotIDs { if !sim.Net.GetNode(id).Up { @@ -58,11 +58,11 @@ func TestUpDownNodeIDs(t *testing.T) { } } - if !equalNodeIDs(ids, append(gotIDs, stoppedIDs...)) { + if !equalESSNodeIDs(ids, append(gotIDs, stoppedIDs...)) { t.Error("returned nodes are not equal to added ones") } - gotIDs = sim.DownNodeIDs() + gotIDs = sim.DownESSNodeIDs() for _, id := range gotIDs { if sim.Net.GetNode(id).Up { @@ -70,12 +70,12 @@ func TestUpDownNodeIDs(t *testing.T) { } } - if !equalNodeIDs(stoppedIDs, gotIDs) { + if !equalESSNodeIDs(stoppedIDs, gotIDs) { t.Error("returned nodes are not equal to the stopped ones") } } -func equalNodeIDs(one, other []discover.NodeID) bool { +func equalESSNodeIDs(one, other []discover.ESSNodeID) bool { if len(one) != len(other) { return false } @@ -212,7 +212,7 @@ func TestAddNodesAndConnectChain(t *testing.T) { t.Fatal(err) } - testChain(t, sim, sim.UpNodeIDs()) + testChain(t, sim, sim.UpESSNodeIDs()) } func TestAddNodesAndConnectRing(t *testing.T) { @@ -244,7 +244,7 @@ func TestUploadSnapshot(t *testing.T) { log.Debug("Creating simulation") s := New(map[string]ServiceFunc{ "bzz": func(ctx *adapters.ServiceContext, b *sync.Map) (node.Service, func(), error) { - addr := network.NewAddrFromNodeID(ctx.Config.ID) + addr := network.NewAddrFromESSNodeID(ctx.Config.ID) hp := network.NewHiveParams() hp.Discovery = false config := &network.BzzConfig{ @@ -269,7 +269,7 @@ func TestUploadSnapshot(t *testing.T) { log.Debug("Starting simulation...") s.Run(ctx, func(ctx context.Context, sim *Simulation) error { log.Debug("Checking") - nodes := sim.UpNodeIDs() + nodes := sim.UpESSNodeIDs() if len(nodes) != nodeCount { t.Fatal("Simulation network node number doesn't match snapshot node number") } @@ -292,13 +292,13 @@ func TestPivotNode(t *testing.T) { t.Fatal(err) } - if sim.PivotNodeID() != nil { + if sim.PivotESSNodeID() != nil { t.Error("expected no pivot node") } sim.SetPivotNode(id) - pid := sim.PivotNodeID() + pid := sim.PivotESSNodeID() if pid == nil { t.Error("pivot node not set") @@ -308,7 +308,7 @@ func TestPivotNode(t *testing.T) { sim.SetPivotNode(id2) - pid = sim.PivotNodeID() + pid = sim.PivotESSNodeID() if pid == nil { t.Error("pivot node not set") diff --git a/swarm/network/simulation/service.go b/swarm/network/simulation/service.go index d1cbf1f8b3..9c1e5fb980 100644 --- a/swarm/network/simulation/service.go +++ b/swarm/network/simulation/service.go @@ -24,7 +24,7 @@ import ( // Service returns a single Service by name on a particular node // with provided id. -func (s *Simulation) Service(name string, id discover.NodeID) node.Service { +func (s *Simulation) Service(name string, id discover.ESSNodeID) node.Service { simNode, ok := s.Net.GetNode(id).Node.(*adapters.SimNode) if !ok { return nil @@ -48,9 +48,9 @@ func (s *Simulation) RandomService(name string) node.Service { // Services returns all services with a provided name // from nodes that are up. -func (s *Simulation) Services(name string) (services map[discover.NodeID]node.Service) { +func (s *Simulation) Services(name string) (services map[discover.ESSNodeID]node.Service) { nodes := s.Net.GetNodes() - services = make(map[discover.NodeID]node.Service) + services = make(map[discover.ESSNodeID]node.Service) for _, node := range nodes { if !node.Up { continue diff --git a/swarm/network/simulation/simulation.go b/swarm/network/simulation/simulation.go index 2241dfca21..4e3a36212f 100644 --- a/swarm/network/simulation/simulation.go +++ b/swarm/network/simulation/simulation.go @@ -45,8 +45,8 @@ type Simulation struct { serviceNames []string cleanupFuncs []func() - buckets map[discover.NodeID]*sync.Map - pivotNodeID *discover.NodeID + buckets map[discover.ESSNodeID]*sync.Map + pivotESSNodeID *discover.ESSNodeID shutdownWG sync.WaitGroup done chan struct{} mu sync.RWMutex @@ -58,7 +58,7 @@ type Simulation struct { // ServiceFunc is used in New to declare new service constructor. // The first argument provides ServiceContext from the adapters package -// giving for example the access to NodeID. Second argument is the sync.Map +// giving for example the access to ESSNodeID. Second argument is the sync.Map // where all "global" state related to the service should be kept. // All cleanups needed for constructed service and any other constructed // objects should ne provided in a single returned cleanup function. @@ -68,7 +68,7 @@ type ServiceFunc func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Se // simulations.Network initialized with provided services. func New(services map[string]ServiceFunc) (s *Simulation) { s = &Simulation{ - buckets: make(map[discover.NodeID]*sync.Map), + buckets: make(map[discover.ESSNodeID]*sync.Map), done: make(chan struct{}), } diff --git a/swarm/network/simulations/discovery/discovery_test.go b/swarm/network/simulations/discovery/discovery_test.go index acf3479e52..bbf00d9ff7 100644 --- a/swarm/network/simulations/discovery/discovery_test.go +++ b/swarm/network/simulations/discovery/discovery_test.go @@ -237,8 +237,8 @@ func discoverySimulation(nodes, conns int, adapter adapters.NodeAdapter) (*simul DefaultService: serviceName, }) defer net.Shutdown() - trigger := make(chan discover.NodeID) - ids := make([]discover.NodeID, nodes) + trigger := make(chan discover.ESSNodeID) + ids := make([]discover.ESSNodeID, nodes) for i := 0; i < nodes; i++ { conf := adapters.RandomNodeConfig() node, err := net.NewNodeWithConfig(conf) @@ -282,7 +282,7 @@ func discoverySimulation(nodes, conns int, adapter adapters.NodeAdapter) (*simul log.Debug(fmt.Sprintf("nodes: %v", len(addrs))) // construct the peer pot, so that kademlia health can be checked ppmap := network.NewPeerPotMap(testMinProxBinSize, addrs) - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { select { case <-ctx.Done(): return false, ctx.Err() @@ -351,8 +351,8 @@ func discoveryPersistenceSimulation(nodes, conns int, adapter adapters.NodeAdapt DefaultService: serviceName, }) defer net.Shutdown() - trigger := make(chan discover.NodeID) - ids := make([]discover.NodeID, nodes) + trigger := make(chan discover.ESSNodeID) + ids := make([]discover.ESSNodeID, nodes) var addrs [][]byte for i := 0; i < nodes; i++ { @@ -462,7 +462,7 @@ func discoveryPersistenceSimulation(nodes, conns int, adapter adapters.NodeAdapt wg.Wait() log.Debug(fmt.Sprintf("nodes: %v", len(addrs))) // construct the peer pot, so that kademlia health can be checked - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { select { case <-ctx.Done(): return false, ctx.Err() @@ -510,7 +510,7 @@ func discoveryPersistenceSimulation(nodes, conns int, adapter adapters.NodeAdapt // triggerChecks triggers a simulation step check whenever a peer is added or // removed from the given node, and also every second to avoid a race between // peer events and kademlia becoming healthy -func triggerChecks(trigger chan discover.NodeID, net *simulations.Network, id discover.NodeID) error { +func triggerChecks(trigger chan discover.ESSNodeID, net *simulations.Network, id discover.ESSNodeID) error { node := net.GetNode(id) if node == nil { return fmt.Errorf("unknown node: %s", id) @@ -550,7 +550,7 @@ func triggerChecks(trigger chan discover.NodeID, net *simulations.Network, id di func newService(ctx *adapters.ServiceContext) (node.Service, error) { host := adapters.ExternalIP() - addr := network.NewAddrFromNodeIDAndPort(ctx.Config.ID, host, ctx.Config.Port) + addr := network.NewAddrFromESSNodeIDAndPort(ctx.Config.ID, host, ctx.Config.Port) kp := network.NewKadParams() kp.MinProxBinSize = testMinProxBinSize diff --git a/swarm/network/simulations/overlay.go b/swarm/network/simulations/overlay.go index 9419de0c6f..cb4598a8b0 100644 --- a/swarm/network/simulations/overlay.go +++ b/swarm/network/simulations/overlay.go @@ -64,12 +64,12 @@ func init() { type Simulation struct { mtx sync.Mutex - stores map[discover.NodeID]*state.InmemoryStore + stores map[discover.ESSNodeID]*state.InmemoryStore } func NewSimulation() *Simulation { return &Simulation{ - stores: make(map[discover.NodeID]*state.InmemoryStore), + stores: make(map[discover.ESSNodeID]*state.InmemoryStore), } } @@ -83,7 +83,7 @@ func (s *Simulation) NewService(ctx *adapters.ServiceContext) (node.Service, err } s.mtx.Unlock() - addr := network.NewAddrFromNodeID(id) + addr := network.NewAddrFromESSNodeID(id) kp := network.NewKadParams() kp.MinProxBinSize = 2 diff --git a/swarm/network/simulations/overlay_test.go b/swarm/network/simulations/overlay_test.go index 4d4eb6c371..5b96b704ad 100644 --- a/swarm/network/simulations/overlay_test.go +++ b/swarm/network/simulations/overlay_test.go @@ -86,7 +86,7 @@ func TestOverlaySim(t *testing.T) { //variables needed to wait for nodes being up var upCount int - trigger := make(chan discover.NodeID) + trigger := make(chan discover.ESSNodeID) //wait for all nodes to be up ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -169,7 +169,7 @@ LOOP: } //watch for events so we know when all nodes are up -func watchSimEvents(net *simulations.Network, ctx context.Context, trigger chan discover.NodeID) { +func watchSimEvents(net *simulations.Network, ctx context.Context, trigger chan discover.ESSNodeID) { events := make(chan *simulations.Event) sub := net.Events().Subscribe(events) defer sub.Unsubscribe() diff --git a/swarm/network/stream/common_test.go b/swarm/network/stream/common_test.go index 4d55c6ee38..922b75a8f4 100644 --- a/swarm/network/stream/common_test.go +++ b/swarm/network/stream/common_test.go @@ -46,10 +46,10 @@ import ( ) var ( - deliveries map[discover.NodeID]*Delivery - stores map[discover.NodeID]storage.ChunkStore - toAddr func(discover.NodeID) *network.BzzAddr - peerCount func(discover.NodeID) int + deliveries map[discover.ESSNodeID]*Delivery + stores map[discover.ESSNodeID]storage.ChunkStore + toAddr func(discover.ESSNodeID) *network.BzzAddr + peerCount func(discover.ESSNodeID) int adapter = flag.String("adapter", "sim", "type of simulation: sim|exec|docker") loglevel = flag.Int("loglevel", 2, "verbosity of logs") nodes = flag.Int("nodes", 0, "number of nodes") @@ -61,8 +61,8 @@ var ( defaultSkipCheck bool waitPeerErrC chan error chunkSize = 4096 - registries map[discover.NodeID]*TestRegistry - createStoreFunc func(id discover.NodeID, addr *network.BzzAddr) (storage.ChunkStore, error) + registries map[discover.ESSNodeID]*TestRegistry + createStoreFunc func(id discover.ESSNodeID, addr *network.BzzAddr) (storage.ChunkStore, error) getRetrieveFunc = defaultRetrieveFunc subscriptionCount = 0 globalStore mock.GlobalStorer @@ -126,7 +126,7 @@ func NewStreamerService(ctx *adapters.ServiceContext) (node.Service, error) { return testRegistry, nil } -func defaultRetrieveFunc(id discover.NodeID) func(ctx context.Context, chunk *storage.Chunk) error { +func defaultRetrieveFunc(id discover.ESSNodeID) func(ctx context.Context, chunk *storage.Chunk) error { return nil } @@ -181,7 +181,7 @@ func newStreamerTester(t *testing.T) (*p2ptest.ProtocolTester, *Registry, *stora streamer.Close() removeDataDir() } - protocolTester := p2ptest.NewProtocolTester(t, network.NewNodeIDFromAddr(addr), 1, streamer.runProtocol) + protocolTester := p2ptest.NewProtocolTester(t, network.NewESSNodeIDFromAddr(addr), 1, streamer.runProtocol) err = waitForPeers(streamer, 1*time.Second, 1) if err != nil { @@ -292,7 +292,7 @@ func (r *TestExternalRegistry) APIs() []rpc.API { return a } -func (r *TestExternalRegistry) GetHashes(ctx context.Context, peerId discover.NodeID, s Stream) (*rpc.Subscription, error) { +func (r *TestExternalRegistry) GetHashes(ctx context.Context, peerId discover.ESSNodeID, s Stream) (*rpc.Subscription, error) { peer := r.getPeer(peerId) client, err := peer.getClient(ctx, s) @@ -336,7 +336,7 @@ func (r *TestExternalRegistry) GetHashes(ctx context.Context, peerId discover.No return sub, nil } -func (r *TestExternalRegistry) EnableNotifications(peerId discover.NodeID, s Stream) error { +func (r *TestExternalRegistry) EnableNotifications(peerId discover.ESSNodeID, s Stream) error { peer := r.getPeer(peerId) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/swarm/network/stream/delivery.go b/swarm/network/stream/delivery.go index fa210e3007..807514588b 100644 --- a/swarm/network/stream/delivery.go +++ b/swarm/network/stream/delivery.go @@ -48,7 +48,7 @@ type Delivery struct { db *storage.DBAPI overlay network.Overlay receiveC chan *ChunkDeliveryMsg - getPeer func(discover.NodeID) *Peer + getPeer func(discover.ESSNodeID) *Peer } func NewDelivery(overlay network.Overlay, db *storage.DBAPI) *Delivery { @@ -257,7 +257,7 @@ R: } // RequestFromPeers sends a chunk retrieve request to -func (d *Delivery) RequestFromPeers(ctx context.Context, hash []byte, skipCheck bool, peersToSkip ...discover.NodeID) error { +func (d *Delivery) RequestFromPeers(ctx context.Context, hash []byte, skipCheck bool, peersToSkip ...discover.ESSNodeID) error { var success bool var err error requestFromPeersCount.Inc(1) diff --git a/swarm/network/stream/delivery_test.go b/swarm/network/stream/delivery_test.go index f3da893a2f..c0170ed584 100644 --- a/swarm/network/stream/delivery_test.go +++ b/swarm/network/stream/delivery_test.go @@ -309,7 +309,7 @@ func TestDeliveryFromNodes(t *testing.T) { func testDeliveryFromNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck bool) { defaultSkipCheck = skipCheck - toAddr = network.NewAddrFromNodeID + toAddr = network.NewAddrFromESSNodeID createStoreFunc = createTestLocalStorageFromSim conf := &streamTesting.RunConfig{ Adapter: *adapter, @@ -329,13 +329,13 @@ func testDeliveryFromNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck if err != nil { t.Fatal(err.Error()) } - stores = make(map[discover.NodeID]storage.ChunkStore) + stores = make(map[discover.ESSNodeID]storage.ChunkStore) for i, id := range sim.IDs { stores[id] = sim.Stores[i] } - registries = make(map[discover.NodeID]*TestRegistry) - deliveries = make(map[discover.NodeID]*Delivery) - peerCount = func(id discover.NodeID) int { + registries = make(map[discover.ESSNodeID]*TestRegistry) + deliveries = make(map[discover.ESSNodeID]*Delivery) + peerCount = func(id discover.ESSNodeID) int { if sim.IDs[0] == id || sim.IDs[nodes-1] == id { return 1 } @@ -418,7 +418,7 @@ func testDeliveryFromNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck }() return nil } - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { select { case err := <-errc: return false, err @@ -491,9 +491,9 @@ func BenchmarkDeliveryFromNodesWithCheck(b *testing.B) { func benchmarkDeliveryFromNodes(b *testing.B, nodes, conns, chunkCount int, skipCheck bool) { defaultSkipCheck = skipCheck - toAddr = network.NewAddrFromNodeID + toAddr = network.NewAddrFromESSNodeID createStoreFunc = createTestLocalStorageFromSim - registries = make(map[discover.NodeID]*TestRegistry) + registries = make(map[discover.ESSNodeID]*TestRegistry) timeout := 300 * time.Second ctx, cancel := context.WithTimeout(context.Background(), timeout) @@ -517,12 +517,12 @@ func benchmarkDeliveryFromNodes(b *testing.B, nodes, conns, chunkCount int, skip b.Fatal(err.Error()) } - stores = make(map[discover.NodeID]storage.ChunkStore) - deliveries = make(map[discover.NodeID]*Delivery) + stores = make(map[discover.ESSNodeID]storage.ChunkStore) + deliveries = make(map[discover.ESSNodeID]*Delivery) for i, id := range sim.IDs { stores[id] = sim.Stores[i] } - peerCount = func(id discover.NodeID) int { + peerCount = func(id discover.ESSNodeID) int { if sim.IDs[0] == id || sim.IDs[nodes-1] == id { return 1 } @@ -585,8 +585,8 @@ func benchmarkDeliveryFromNodes(b *testing.B, nodes, conns, chunkCount int, skip } // the check function is only triggered when the benchmark finishes - trigger := make(chan discover.NodeID) - check := func(ctx context.Context, id discover.NodeID) (_ bool, err error) { + trigger := make(chan discover.ESSNodeID) + check := func(ctx context.Context, id discover.ESSNodeID) (_ bool, err error) { return true, nil } @@ -702,6 +702,6 @@ Loop: } } -func createTestLocalStorageFromSim(id discover.NodeID, addr *network.BzzAddr) (storage.ChunkStore, error) { +func createTestLocalStorageFromSim(id discover.ESSNodeID, addr *network.BzzAddr) (storage.ChunkStore, error) { return stores[id], nil } diff --git a/swarm/network/stream/intervals_test.go b/swarm/network/stream/intervals_test.go index d996cdc7e5..084bdbfd8d 100644 --- a/swarm/network/stream/intervals_test.go +++ b/swarm/network/stream/intervals_test.go @@ -85,7 +85,7 @@ func testIntervals(t *testing.T, live bool, history *Range, skipCheck bool) { defer setDefaultSkipCheck(defaultSkipCheck) defaultSkipCheck = skipCheck - toAddr = network.NewAddrFromNodeID + toAddr = network.NewAddrFromESSNodeID conf := &streamTesting.RunConfig{ Adapter: *adapter, NodeCount: nodes, @@ -105,13 +105,13 @@ func testIntervals(t *testing.T, live bool, history *Range, skipCheck bool) { t.Fatal(err) } - stores = make(map[discover.NodeID]storage.ChunkStore) - deliveries = make(map[discover.NodeID]*Delivery) + stores = make(map[discover.ESSNodeID]storage.ChunkStore) + deliveries = make(map[discover.ESSNodeID]*Delivery) for i, id := range sim.IDs { stores[id] = sim.Stores[i] } - peerCount = func(id discover.NodeID) int { + peerCount = func(id discover.ESSNodeID) int { return 1 } @@ -282,7 +282,7 @@ func testIntervals(t *testing.T, live bool, history *Range, skipCheck bool) { }) return err } - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { select { case err := <-errc: return false, err diff --git a/swarm/network/stream/snapshot_retrieval_test.go b/swarm/network/stream/snapshot_retrieval_test.go index 9961a0bc7f..4d20d69ebe 100644 --- a/swarm/network/stream/snapshot_retrieval_test.go +++ b/swarm/network/stream/snapshot_retrieval_test.go @@ -42,31 +42,31 @@ const ( func initRetrievalTest() { //global func to get overlay address from discover ID - toAddr = func(id discover.NodeID) *network.BzzAddr { - addr := network.NewAddrFromNodeID(id) + toAddr = func(id discover.ESSNodeID) *network.BzzAddr { + addr := network.NewAddrFromESSNodeID(id) return addr } //global func to create local store createStoreFunc = createTestLocalStorageForId //local stores - stores = make(map[discover.NodeID]storage.ChunkStore) + stores = make(map[discover.ESSNodeID]storage.ChunkStore) //data directories for each node and store - datadirs = make(map[discover.NodeID]string) + datadirs = make(map[discover.ESSNodeID]string) //deliveries for each node - deliveries = make(map[discover.NodeID]*Delivery) + deliveries = make(map[discover.ESSNodeID]*Delivery) //global retrieve func - getRetrieveFunc = func(id discover.NodeID) func(ctx context.Context, chunk *storage.Chunk) error { + getRetrieveFunc = func(id discover.ESSNodeID) func(ctx context.Context, chunk *storage.Chunk) error { return func(ctx context.Context, chunk *storage.Chunk) error { skipCheck := true return deliveries[id].RequestFromPeers(ctx, chunk.Addr[:], skipCheck) } } - //registries, map of discover.NodeID to its streamer - registries = make(map[discover.NodeID]*TestRegistry) + //registries, map of discover.ESSNodeID to its streamer + registries = make(map[discover.ESSNodeID]*TestRegistry) //not needed for this test but required from common_test for NewStreamService waitPeerErrC = make(chan error) //also not needed for this test but required for NewStreamService - peerCount = func(id discover.NodeID) int { + peerCount = func(id discover.ESSNodeID) int { if ids[0] == id || ids[len(ids)-1] == id { return 1 } @@ -202,7 +202,7 @@ func runFileRetrievalTest(nodeCount int) error { //for every run (live, history), int the variables initRetrievalTest() //the ids of the snapshot nodes, initiate only now as we need nodeCount - ids = make([]discover.NodeID, nodeCount) + ids = make([]discover.ESSNodeID, nodeCount) //channel to check for disconnection errors disconnectC := make(chan error) //channel to close disconnection watcher routine @@ -210,7 +210,7 @@ func runFileRetrievalTest(nodeCount int) error { //the test conf (using same as in `snapshot_sync_test` conf = &synctestConfig{} //map of overlay address to discover ID - conf.addrToIdMap = make(map[string]discover.NodeID) + conf.addrToIdMap = make(map[string]discover.ESSNodeID) //array where the generated chunk hashes will be stored conf.hashes = make([]storage.Address, 0) //load nodes from the snapshot file @@ -248,7 +248,7 @@ func runFileRetrievalTest(nodeCount int) error { //channel to signal when the upload has finished uploadFinished := make(chan struct{}) //channel to trigger new node checks - trigger := make(chan discover.NodeID) + trigger := make(chan discover.ESSNodeID) //simulation action action := func(ctx context.Context) error { //first run the health check on all nodes, @@ -392,7 +392,7 @@ func runFileRetrievalTest(nodeCount int) error { } //check defines what will be checked during the test - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { select { case <-ctx.Done(): @@ -485,7 +485,7 @@ func runRetrievalTest(chunkCount int, nodeCount int) error { //for every run (live, history), int the variables initRetrievalTest() //the ids of the snapshot nodes, initiate only now as we need nodeCount - ids = make([]discover.NodeID, nodeCount) + ids = make([]discover.ESSNodeID, nodeCount) //channel to check for disconnection errors disconnectC := make(chan error) //channel to close disconnection watcher routine @@ -493,7 +493,7 @@ func runRetrievalTest(chunkCount int, nodeCount int) error { //the test conf (using same as in `snapshot_sync_test` conf = &synctestConfig{} //map of overlay address to discover ID - conf.addrToIdMap = make(map[string]discover.NodeID) + conf.addrToIdMap = make(map[string]discover.ESSNodeID) //array where the generated chunk hashes will be stored conf.hashes = make([]storage.Address, 0) //load nodes from the snapshot file @@ -531,7 +531,7 @@ func runRetrievalTest(chunkCount int, nodeCount int) error { //needed for healthy call ppmap = network.NewPeerPotMap(testMinProxBinSize, conf.addrs) - trigger := make(chan discover.NodeID) + trigger := make(chan discover.ESSNodeID) //simulation action action := func(ctx context.Context) error { //first run the health check on all nodes, @@ -674,7 +674,7 @@ func runRetrievalTest(chunkCount int, nodeCount int) error { chunkSize := storage.DefaultChunkSize //check defines what will be checked during the test - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { //don't check the uploader node if id == uploadNode.ID() { diff --git a/swarm/network/stream/snapshot_sync_test.go b/swarm/network/stream/snapshot_sync_test.go index 0b5257c603..621a99c1c0 100644 --- a/swarm/network/stream/snapshot_sync_test.go +++ b/swarm/network/stream/snapshot_sync_test.go @@ -49,8 +49,8 @@ var ( pof = pot.DefaultPof(256) conf *synctestConfig - ids []discover.NodeID - datadirs map[discover.NodeID]string + ids []discover.ESSNodeID + datadirs map[discover.ESSNodeID]string ppmap map[string]*network.PeerPot live bool @@ -62,9 +62,9 @@ var ( type synctestConfig struct { addrs [][]byte hashes []storage.Address - idToChunksMap map[discover.NodeID][]int + idToChunksMap map[discover.ESSNodeID][]int chunksToNodesMap map[string][]int - addrToIdMap map[string]discover.NodeID + addrToIdMap map[string]discover.ESSNodeID } func init() { @@ -77,8 +77,8 @@ func init() { //we thus need to initialize first as init() as well. func initSyncTest() { //assign the toAddr func so NewStreamerService can build the addr - toAddr = func(id discover.NodeID) *network.BzzAddr { - addr := network.NewAddrFromNodeID(id) + toAddr = func(id discover.ESSNodeID) *network.BzzAddr { + addr := network.NewAddrFromESSNodeID(id) return addr } //global func to create local store @@ -88,17 +88,17 @@ func initSyncTest() { createStoreFunc = createTestLocalStorageForId } //local stores - stores = make(map[discover.NodeID]storage.ChunkStore) + stores = make(map[discover.ESSNodeID]storage.ChunkStore) //data directories for each node and store - datadirs = make(map[discover.NodeID]string) + datadirs = make(map[discover.ESSNodeID]string) //deliveries for each node - deliveries = make(map[discover.NodeID]*Delivery) - //registries, map of discover.NodeID to its streamer - registries = make(map[discover.NodeID]*TestRegistry) + deliveries = make(map[discover.ESSNodeID]*Delivery) + //registries, map of discover.ESSNodeID to its streamer + registries = make(map[discover.ESSNodeID]*TestRegistry) //not needed for this test but required from common_test for NewStreamService waitPeerErrC = make(chan error) //also not needed for this test but required for NewStreamService - peerCount = func(id discover.NodeID) int { + peerCount = func(id discover.ESSNodeID) int { if ids[0] == id || ids[len(ids)-1] == id { return 1 } @@ -202,17 +202,17 @@ For every test run, a series of three tests will be executed: func runSyncTest(chunkCount int, nodeCount int, live bool, history bool) error { initSyncTest() //the ids of the snapshot nodes, initiate only now as we need nodeCount - ids = make([]discover.NodeID, nodeCount) + ids = make([]discover.ESSNodeID, nodeCount) //initialize the test struct conf = &synctestConfig{} //map of discover ID to indexes of chunks expected at that ID - conf.idToChunksMap = make(map[discover.NodeID][]int) + conf.idToChunksMap = make(map[discover.ESSNodeID][]int) //map of overlay address to discover ID - conf.addrToIdMap = make(map[string]discover.NodeID) + conf.addrToIdMap = make(map[string]discover.ESSNodeID) //array where the generated chunk hashes will be stored conf.hashes = make([]storage.Address, 0) //channel to trigger node checks in the simulation - trigger := make(chan discover.NodeID) + trigger := make(chan discover.ESSNodeID) //channel to check for disconnection errors disconnectC := make(chan error) //channel to close disconnection watcher routine @@ -256,7 +256,7 @@ func runSyncTest(chunkCount int, nodeCount int, live bool, history bool) error { //append it to the array of all overlay addresses conf.addrs = append(conf.addrs, a) //the proximity calculation is on overlay addr, - //the p2p/simulations check func triggers on discover.NodeID, + //the p2p/simulations check func triggers on discover.ESSNodeID, //so we need to know which overlay addr maps to which nodeID conf.addrToIdMap[string(a)] = ids[c] } @@ -404,7 +404,7 @@ func runSyncTest(chunkCount int, nodeCount int, live bool, history bool) error { } //check defines what will be checked during the test - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { select { case <-ctx.Done(): return false, ctx.Err() @@ -574,7 +574,7 @@ func mapKeysToNodes(conf *synctestConfig) { } //upload a file(chunks) to a single local node store -func uploadFileToSingleNodeStore(id discover.NodeID, chunkCount int) ([]storage.Address, error) { +func uploadFileToSingleNodeStore(id discover.ESSNodeID, chunkCount int) ([]storage.Address, error) { log.Debug(fmt.Sprintf("Uploading to node id: %s", id)) lstore := stores[id] size := chunkSize @@ -656,7 +656,7 @@ func initNetWithSnapshot(nodeCount int) (*simulations.Network, error) { //we want to wait for subscriptions to be established before uploading to test //that live syncing is working correctly -func watchSubscriptionEvents(ctx context.Context, id discover.NodeID, client *rpc.Client, errc chan error, quitC chan struct{}) (doneC <-chan struct{}) { +func watchSubscriptionEvents(ctx context.Context, id discover.ESSNodeID, client *rpc.Client, errc chan error, quitC chan struct{}) (doneC <-chan struct{}) { events := make(chan *p2p.PeerEvent) sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents") if err != nil { @@ -703,7 +703,7 @@ func watchSubscriptionEvents(ctx context.Context, id discover.NodeID, client *rp } //create a local store for the given node -func createTestLocalStorageForId(id discover.NodeID, addr *network.BzzAddr) (storage.ChunkStore, error) { +func createTestLocalStorageForId(id discover.ESSNodeID, addr *network.BzzAddr) (storage.ChunkStore, error) { var datadir string var err error datadir, err = ioutil.TempDir("", fmt.Sprintf("syncer-test-%s", id.TerminalString())) diff --git a/swarm/network/stream/stream.go b/swarm/network/stream/stream.go index cd0580a0c0..416f163942 100644 --- a/swarm/network/stream/stream.go +++ b/swarm/network/stream/stream.go @@ -58,7 +58,7 @@ type Registry struct { peersMu sync.RWMutex serverFuncs map[string]func(*Peer, string, bool) (Server, error) clientFuncs map[string]func(*Peer, string, bool) (Client, error) - peers map[discover.NodeID]*Peer + peers map[discover.ESSNodeID]*Peer delivery *Delivery intervalsStore state.Store doRetrieve bool @@ -85,7 +85,7 @@ func NewRegistry(addr *network.BzzAddr, delivery *Delivery, db *storage.DBAPI, i skipCheck: options.SkipCheck, serverFuncs: make(map[string]func(*Peer, string, bool) (Server, error)), clientFuncs: make(map[string]func(*Peer, string, bool) (Client, error)), - peers: make(map[discover.NodeID]*Peer), + peers: make(map[discover.ESSNodeID]*Peer), delivery: delivery, intervalsStore: intervalsStore, doRetrieve: options.DoRetrieve, @@ -222,7 +222,7 @@ func (r *Registry) GetServerFunc(stream string) (func(*Peer, string, bool) (Serv return f, nil } -func (r *Registry) RequestSubscription(peerId discover.NodeID, s Stream, h *Range, prio uint8) error { +func (r *Registry) RequestSubscription(peerId discover.ESSNodeID, s Stream, h *Range, prio uint8) error { // check if the stream is registered if _, err := r.GetServerFunc(s.Name); err != nil { return err @@ -250,7 +250,7 @@ func (r *Registry) RequestSubscription(peerId discover.NodeID, s Stream, h *Rang } // Subscribe initiates the streamer -func (r *Registry) Subscribe(peerId discover.NodeID, s Stream, h *Range, priority uint8) error { +func (r *Registry) Subscribe(peerId discover.ESSNodeID, s Stream, h *Range, priority uint8) error { // check if the stream is registered if _, err := r.GetClientFunc(s.Name); err != nil { return err @@ -290,7 +290,7 @@ func (r *Registry) Subscribe(peerId discover.NodeID, s Stream, h *Range, priorit return peer.SendPriority(context.TODO(), msg, priority) } -func (r *Registry) Unsubscribe(peerId discover.NodeID, s Stream) error { +func (r *Registry) Unsubscribe(peerId discover.ESSNodeID, s Stream) error { peer := r.getPeer(peerId) if peer == nil { return fmt.Errorf("peer not found %v", peerId) @@ -309,7 +309,7 @@ func (r *Registry) Unsubscribe(peerId discover.NodeID, s Stream) error { // Quit sends the QuitMsg to the peer to remove the // stream peer client and terminate the streaming. -func (r *Registry) Quit(peerId discover.NodeID, s Stream) error { +func (r *Registry) Quit(peerId discover.ESSNodeID, s Stream) error { peer := r.getPeer(peerId) if peer == nil { log.Debug("stream quit: peer not found", "peer", peerId, "stream", s) @@ -339,7 +339,7 @@ func (r *Registry) NodeInfo() interface{} { return nil } -func (r *Registry) PeerInfo(id discover.NodeID) interface{} { +func (r *Registry) PeerInfo(id discover.ESSNodeID) interface{} { return nil } @@ -347,7 +347,7 @@ func (r *Registry) Close() error { return r.intervalsStore.Close() } -func (r *Registry) getPeer(peerId discover.NodeID) *Peer { +func (r *Registry) getPeer(peerId discover.ESSNodeID) *Peer { r.peersMu.RLock() defer r.peersMu.RUnlock() @@ -404,7 +404,7 @@ func (r *Registry) updateSyncing() { // map of all SYNC streams for all peers // used at the and of the function to remove servers // that are not needed anymore - subs := make(map[discover.NodeID]map[Stream]struct{}) + subs := make(map[discover.ESSNodeID]map[Stream]struct{}) r.peersMu.RLock() for id, peer := range r.peers { peer.serverMu.RLock() @@ -738,10 +738,10 @@ func NewAPI(r *Registry) *API { } } -func (api *API) SubscribeStream(peerId discover.NodeID, s Stream, history *Range, priority uint8) error { +func (api *API) SubscribeStream(peerId discover.ESSNodeID, s Stream, history *Range, priority uint8) error { return api.streamer.Subscribe(peerId, s, history, priority) } -func (api *API) UnsubscribeStream(peerId discover.NodeID, s Stream) error { +func (api *API) UnsubscribeStream(peerId discover.ESSNodeID, s Stream) error { return api.streamer.Unsubscribe(peerId, s) } diff --git a/swarm/network/stream/syncer.go b/swarm/network/stream/syncer.go index d7febe4a3e..f475426cc8 100644 --- a/swarm/network/stream/syncer.go +++ b/swarm/network/stream/syncer.go @@ -190,7 +190,7 @@ func NewSwarmSyncerClient(p *Peer, db *storage.DBAPI, ignoreExistingRequest bool // // StartSyncing is called on the Peer to start the syncing process // // the idea is that it is called only after kademlia is close to healthy -// func StartSyncing(s *Streamer, peerId discover.NodeID, po uint8, nn bool) { +// func StartSyncing(s *Streamer, peerId discover.ESSNodeID, po uint8, nn bool) { // lastPO := po // if nn { // lastPO = maxPO diff --git a/swarm/network/stream/syncer_test.go b/swarm/network/stream/syncer_test.go index a3d53e6488..56dc318b4d 100644 --- a/swarm/network/stream/syncer_test.go +++ b/swarm/network/stream/syncer_test.go @@ -46,7 +46,7 @@ func TestSyncerSimulation(t *testing.T) { testSyncBetweenNodes(t, 16, 1, dataChunkCount, true, 1) } -func createMockStore(id discover.NodeID, addr *network.BzzAddr) (storage.ChunkStore, error) { +func createMockStore(id discover.ESSNodeID, addr *network.BzzAddr) (storage.ChunkStore, error) { var err error address := common.BytesToAddress(id.Bytes()) mockStore := globalStore.NewNodeStore(address) @@ -65,7 +65,7 @@ func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck defer setDefaultSkipCheck(defaultSkipCheck) defaultSkipCheck = skipCheck //data directories for each node and store - datadirs = make(map[discover.NodeID]string) + datadirs = make(map[discover.ESSNodeID]string) if *useMockStore { createStoreFunc = createMockStore createGlobalStore() @@ -74,9 +74,9 @@ func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck } defer datadirsCleanup() - registries = make(map[discover.NodeID]*TestRegistry) - toAddr = func(id discover.NodeID) *network.BzzAddr { - addr := network.NewAddrFromNodeID(id) + registries = make(map[discover.ESSNodeID]*TestRegistry) + toAddr = func(id discover.ESSNodeID) *network.BzzAddr { + addr := network.NewAddrFromESSNodeID(id) //hack to put addresses in same space addr.OAddr[0] = byte(0) return addr @@ -93,8 +93,8 @@ func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck // the service constructor function // TODO: will this work with exec/docker adapter? // localstore of nodes made available for action and check calls - stores = make(map[discover.NodeID]storage.ChunkStore) - deliveries = make(map[discover.NodeID]*Delivery) + stores = make(map[discover.ESSNodeID]storage.ChunkStore) + deliveries = make(map[discover.ESSNodeID]*Delivery) // create context for simulation run timeout := 30 * time.Second ctx, cancel := context.WithTimeout(context.Background(), timeout) @@ -112,7 +112,7 @@ func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck t.Fatal(err.Error()) } - nodeIndex := make(map[discover.NodeID]int) + nodeIndex := make(map[discover.ESSNodeID]int) for i, id := range sim.IDs { nodeIndex[id] = i if !*useMockStore { @@ -123,7 +123,7 @@ func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck // peerCount function gives the number of peer connections for a nodeID // this is needed for the service run function to wait until // each protocol instance runs and the streamer peers are available - peerCount = func(id discover.NodeID) int { + peerCount = func(id discover.ESSNodeID) int { if sim.IDs[0] == id || sim.IDs[nodes-1] == id { return 1 } @@ -216,7 +216,7 @@ func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck } // this makes sure check is not called before the previous call finishes - check := func(ctx context.Context, id discover.NodeID) (bool, error) { + check := func(ctx context.Context, id discover.ESSNodeID) (bool, error) { select { case err := <-errc: return false, err diff --git a/swarm/network/stream/testing/testing.go b/swarm/network/stream/testing/testing.go index d584ec3974..be5ccfc6bd 100644 --- a/swarm/network/stream/testing/testing.go +++ b/swarm/network/stream/testing/testing.go @@ -41,7 +41,7 @@ type Simulation struct { Net *simulations.Network Stores []storage.ChunkStore Addrs []network.Addr - IDs []discover.NodeID + IDs []discover.ESSNodeID } func SetStores(addrs ...network.Addr) ([]storage.ChunkStore, func(), error) { @@ -122,7 +122,7 @@ type RunConfig struct { Step *simulations.Step NodeCount int ConnLevel int - ToAddr func(discover.NodeID) *network.BzzAddr + ToAddr func(discover.ESSNodeID) *network.BzzAddr Services adapters.Services DefaultService string EnableMsgEvents bool @@ -147,7 +147,7 @@ func NewSimulation(conf *RunConfig) (*Simulation, func(), error) { adapterTeardown() net.Shutdown() } - ids := make([]discover.NodeID, nodes) + ids := make([]discover.ESSNodeID, nodes) addrs := make([]network.Addr, nodes) // start nodes for i := 0; i < nodes; i++ { @@ -221,7 +221,7 @@ func (s *Simulation) Run(ctx context.Context, conf *RunConfig) (*simulations.Ste // errors to the errc channel. Channel quitC signals the termination of the event loop. // Returned doneC will be closed after the rpc subscription is unsubscribed, // signaling that simulations network is safe to shutdown. -func WatchDisconnections(id discover.NodeID, client *rpc.Client, errc chan error, quitC chan struct{}) (doneC <-chan struct{}, err error) { +func WatchDisconnections(id discover.ESSNodeID, client *rpc.Client, errc chan error, quitC chan struct{}) (doneC <-chan struct{}, err error) { events := make(chan *p2p.PeerEvent) sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents") if err != nil { @@ -260,8 +260,8 @@ func WatchDisconnections(id discover.NodeID, client *rpc.Client, errc chan error return c, nil } -func Trigger(d time.Duration, quitC chan struct{}, ids ...discover.NodeID) chan discover.NodeID { - trigger := make(chan discover.NodeID) +func Trigger(d time.Duration, quitC chan struct{}, ids ...discover.ESSNodeID) chan discover.ESSNodeID { + trigger := make(chan discover.ESSNodeID) go func() { defer close(trigger) ticker := time.NewTicker(d) @@ -280,7 +280,7 @@ func Trigger(d time.Duration, quitC chan struct{}, ids ...discover.NodeID) chan return trigger } -func (sim *Simulation) CallClient(id discover.NodeID, f func(*rpc.Client) error) error { +func (sim *Simulation) CallClient(id discover.ESSNodeID, f func(*rpc.Client) error) error { node := sim.Net.GetNode(id) if node == nil { return fmt.Errorf("unknown node: %s", id) diff --git a/swarm/network_test.go b/swarm/network_test.go index d2a0309338..ce08e338a7 100644 --- a/swarm/network_test.go +++ b/swarm/network_test.go @@ -235,14 +235,14 @@ type testSwarmNetworkStep struct { type file struct { addr storage.Address data string - nodeID discover.NodeID + nodeID discover.ESSNodeID } // check represents a reference to a file that is retrieved // from a particular node. type check struct { key string - nodeID discover.NodeID + nodeID discover.ESSNodeID } // testSwarmNetworkOptions contains optional parameters for running @@ -312,7 +312,7 @@ func testSwarmNetwork(t *testing.T, o *testSwarmNetworkOptions, steps ...testSwa for i, step := range steps { log.Debug("test sync step", "n", i+1, "nodes", step.nodeCount) - change := step.nodeCount - len(sim.UpNodeIDs()) + change := step.nodeCount - len(sim.UpESSNodeIDs()) if change > 0 { _, err := sim.AddNodesAndConnectChain(change) @@ -334,7 +334,7 @@ func testSwarmNetwork(t *testing.T, o *testSwarmNetworkOptions, steps ...testSwa var totalFoundCount uint64 result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) error { - nodeIDs := sim.UpNodeIDs() + nodeIDs := sim.UpESSNodeIDs() shuffle(len(nodeIDs), func(i, j int) { nodeIDs[i], nodeIDs[j] = nodeIDs[j], nodeIDs[i] }) @@ -411,7 +411,7 @@ func retrieve( var totalWg sync.WaitGroup errc := make(chan error) - nodeIDs := sim.UpNodeIDs() + nodeIDs := sim.UpESSNodeIDs() totalCheckCount := len(nodeIDs) * len(files) @@ -440,7 +440,7 @@ func retrieve( checkCount++ wg.Add(1) - go func(f file, id discover.NodeID) { + go func(f file, id discover.ESSNodeID) { defer wg.Done() log.Debug("api get: check file", "node", id.String(), "key", f.addr.String(), "total files found", atomic.LoadUint64(totalFoundCount)) @@ -466,7 +466,7 @@ func retrieve( }(f, id) } - go func(id discover.NodeID) { + go func(id discover.ESSNodeID) { defer totalWg.Done() wg.Wait() diff --git a/swarm/pss/client/client_test.go b/swarm/pss/client/client_test.go index f360698778..838f9ae7c9 100644 --- a/swarm/pss/client/client_test.go +++ b/swarm/pss/client/client_test.go @@ -232,12 +232,12 @@ func setupNetwork(numnodes int) (clients []*rpc.Client, err error) { func newServices() adapters.Services { stateStore := state.NewInmemoryStore() - kademlias := make(map[discover.NodeID]*network.Kademlia) - kademlia := func(id discover.NodeID) *network.Kademlia { + kademlias := make(map[discover.ESSNodeID]*network.Kademlia) + kademlia := func(id discover.ESSNodeID) *network.Kademlia { if k, ok := kademlias[id]; ok { return k } - addr := network.NewAddrFromNodeID(id) + addr := network.NewAddrFromESSNodeID(id) params := network.NewKadParams() params.MinProxBinSize = 2 params.MaxBinSize = 3 @@ -269,7 +269,7 @@ func newServices() adapters.Services { return ps, nil }, "bzz": func(ctx *adapters.ServiceContext) (node.Service, error) { - addr := network.NewAddrFromNodeID(ctx.Config.ID) + addr := network.NewAddrFromESSNodeID(ctx.Config.ID) hp := network.NewHiveParams() hp.Discovery = false config := &network.BzzConfig{ diff --git a/swarm/pss/notify/notify_test.go b/swarm/pss/notify/notify_test.go index 3c655f215c..c92a033bc0 100644 --- a/swarm/pss/notify/notify_test.go +++ b/swarm/pss/notify/notify_test.go @@ -203,12 +203,12 @@ func TestStart(t *testing.T) { func newServices(allowRaw bool) adapters.Services { stateStore := state.NewInmemoryStore() - kademlias := make(map[discover.NodeID]*network.Kademlia) - kademlia := func(id discover.NodeID) *network.Kademlia { + kademlias := make(map[discover.ESSNodeID]*network.Kademlia) + kademlia := func(id discover.ESSNodeID) *network.Kademlia { if k, ok := kademlias[id]; ok { return k } - addr := network.NewAddrFromNodeID(id) + addr := network.NewAddrFromESSNodeID(id) params := network.NewKadParams() params.MinProxBinSize = 2 params.MaxBinSize = 3 @@ -238,7 +238,7 @@ func newServices(allowRaw bool) adapters.Services { return ps, nil }, "bzz": func(ctx *adapters.ServiceContext) (node.Service, error) { - addr := network.NewAddrFromNodeID(ctx.Config.ID) + addr := network.NewAddrFromESSNodeID(ctx.Config.ID) hp := network.NewHiveParams() hp.Discovery = false config := &network.BzzConfig{ diff --git a/swarm/pss/pss.go b/swarm/pss/pss.go index 5c060b2486..eec7b1d32a 100644 --- a/swarm/pss/pss.go +++ b/swarm/pss/pss.go @@ -70,7 +70,7 @@ type pssCacheEntry struct { // abstraction to enable access to p2p.protocols.Peer.Send type senderPeer interface { Info() *p2p.PeerInfo - ID() discover.NodeID + ID() discover.ESSNodeID Address() []byte Send(context.Context, interface{}) error } diff --git a/swarm/pss/pss_test.go b/swarm/pss/pss_test.go index 41b03db286..e6ba9f4510 100644 --- a/swarm/pss/pss_test.go +++ b/swarm/pss/pss_test.go @@ -940,11 +940,11 @@ func testSendAsym(t *testing.T) { type Job struct { Msg []byte - SendNode discover.NodeID - RecvNode discover.NodeID + SendNode discover.ESSNodeID + RecvNode discover.ESSNodeID } -func worker(id int, jobs <-chan Job, rpcs map[discover.NodeID]*rpc.Client, pubkeys map[discover.NodeID]string, topic string) { +func worker(id int, jobs <-chan Job, rpcs map[discover.ESSNodeID]*rpc.Client, pubkeys map[discover.ESSNodeID]string, topic string) { for j := range jobs { rpcs[j.SendNode].Call(nil, "pss_sendAsym", pubkeys[j.RecvNode], topic, hexutil.Encode(j.Msg)) } @@ -994,7 +994,7 @@ func TestNetwork10000(t *testing.T) { func testNetwork(t *testing.T) { type msgnotifyC struct { - id discover.NodeID + id discover.ESSNodeID msgIdx int } @@ -1006,16 +1006,16 @@ func testNetwork(t *testing.T) { log.Info("network test", "nodecount", nodecount, "msgcount", msgcount, "addrhintsize", addrsize) - nodes := make([]discover.NodeID, nodecount) - bzzaddrs := make(map[discover.NodeID]string, nodecount) - rpcs := make(map[discover.NodeID]*rpc.Client, nodecount) - pubkeys := make(map[discover.NodeID]string, nodecount) + nodes := make([]discover.ESSNodeID, nodecount) + bzzaddrs := make(map[discover.ESSNodeID]string, nodecount) + rpcs := make(map[discover.ESSNodeID]*rpc.Client, nodecount) + pubkeys := make(map[discover.ESSNodeID]string, nodecount) sentmsgs := make([][]byte, msgcount) recvmsgs := make([]bool, msgcount) - nodemsgcount := make(map[discover.NodeID]int, nodecount) + nodemsgcount := make(map[discover.ESSNodeID]int, nodecount) - trigger := make(chan discover.NodeID) + trigger := make(chan discover.ESSNodeID) var a adapters.NodeAdapter if adapter == "exec" { @@ -1055,7 +1055,7 @@ func testNetwork(t *testing.T) { time.Sleep(1 * time.Second) - triggerChecks := func(trigger chan discover.NodeID, id discover.NodeID, rpcclient *rpc.Client, topic string) error { + triggerChecks := func(trigger chan discover.ESSNodeID, id discover.ESSNodeID, rpcclient *rpc.Client, topic string) error { msgC := make(chan APIMsg) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -1559,12 +1559,12 @@ func setupNetwork(numnodes int, allowRaw bool) (clients []*rpc.Client, err error func newServices(allowRaw bool) adapters.Services { stateStore := state.NewInmemoryStore() - kademlias := make(map[discover.NodeID]*network.Kademlia) - kademlia := func(id discover.NodeID) *network.Kademlia { + kademlias := make(map[discover.ESSNodeID]*network.Kademlia) + kademlia := func(id discover.ESSNodeID) *network.Kademlia { if k, ok := kademlias[id]; ok { return k } - addr := network.NewAddrFromNodeID(id) + addr := network.NewAddrFromESSNodeID(id) params := network.NewKadParams() params.MinProxBinSize = 2 params.MaxBinSize = 3 @@ -1623,7 +1623,7 @@ func newServices(allowRaw bool) adapters.Services { return ps, nil }, "bzz": func(ctx *adapters.ServiceContext) (node.Service, error) { - addr := network.NewAddrFromNodeID(ctx.Config.ID) + addr := network.NewAddrFromESSNodeID(ctx.Config.ID) hp := network.NewHiveParams() hp.Discovery = false config := &network.BzzConfig{ @@ -1638,9 +1638,9 @@ func newServices(allowRaw bool) adapters.Services { func newTestPss(privkey *ecdsa.PrivateKey, overlay network.Overlay, ppextra *PssParams) *Pss { - var nid discover.NodeID + var nid discover.ESSNodeID copy(nid[:], crypto.FromECDSAPub(&privkey.PublicKey)) - addr := network.NewAddrFromNodeID(nid) + addr := network.NewAddrFromESSNodeID(nid) // set up routing if kademlia is not passed to us if overlay == nil { diff --git a/swarm/pss/writeup.md b/swarm/pss/writeup.md index a0506ffa43..8aff0d1bfc 100644 --- a/swarm/pss/writeup.md +++ b/swarm/pss/writeup.md @@ -65,7 +65,7 @@ The validation phase of the TestNetwork test is done using an RPC subscription: ``` ... - triggerChecks := func(trigger chan discover.NodeID, id discover.NodeID, rpcclient *rpc.Client) error { + triggerChecks := func(trigger chan discover.ESSNodeID, id discover.ESSNodeID, rpcclient *rpc.Client) error { msgC := make(chan APIMsg) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() diff --git a/swarm/swarm.go b/swarm/swarm.go index db7d2dfedc..4644d334ce 100644 --- a/swarm/swarm.go +++ b/swarm/swarm.go @@ -129,7 +129,7 @@ func NewSwarm(config *api.Config, mockStore *mock.NodeStore) (self *Swarm, err e log.Debug(fmt.Sprintf("-> swarm net store shared access layer to Swarm Chunk Store")) - nodeID, err := discover.HexID(config.NodeID) + nodeID, err := discover.HexID(config.ESSNodeID) if err != nil { return nil, err } diff --git a/vendor/bazil.org/fuse/fs/serve.go b/vendor/bazil.org/fuse/fs/serve.go index e9fc56590f..e7b7a202f7 100644 --- a/vendor/bazil.org/fuse/fs/serve.go +++ b/vendor/bazil.org/fuse/fs/serve.go @@ -86,7 +86,7 @@ type FSInodeGenerator interface { // // Methods returning Node should take care to return the same Node // when the result is logically the same instance. Without this, each -// Node will get a new NodeID, causing spurious cache invalidations, +// Node will get a new ESSNodeID, causing spurious cache invalidations, // extra lookups and aliasing anomalies. This may not matter for a // simple, read-only filesystem. type Node interface { @@ -347,7 +347,7 @@ func New(conn *fuse.Conn, config *Config) *Server { s := &Server{ conn: conn, req: map[fuse.RequestID]*serveRequest{}, - nodeRef: map[Node]fuse.NodeID{}, + nodeRef: map[Node]fuse.ESSNodeID{}, dynamicInode: GenerateDynamicInode, } if config != nil { @@ -374,9 +374,9 @@ type Server struct { meta sync.Mutex req map[fuse.RequestID]*serveRequest node []*serveNode - nodeRef map[Node]fuse.NodeID + nodeRef map[Node]fuse.ESSNodeID handle []*serveHandle - freeNode []fuse.NodeID + freeNode []fuse.ESSNodeID freeHandle []fuse.HandleID nodeGen uint64 @@ -448,8 +448,8 @@ type serveNode struct { node Node refs uint64 - // Delay freeing the NodeID until waitgroup is done. This allows - // using the NodeID for short periods of time without holding the + // Delay freeing the ESSNodeID until waitgroup is done. This allows + // using the ESSNodeID for short periods of time without holding the // Server.meta lock. // // Rules: @@ -470,7 +470,7 @@ func (sn *serveNode) attr(ctx context.Context, attr *fuse.Attr) error { type serveHandle struct { handle Handle readData []byte - nodeID fuse.NodeID + nodeID fuse.ESSNodeID } // NodeRef is deprecated. It remains here to decrease code churn on @@ -479,7 +479,7 @@ type serveHandle struct { // without needing NodeRef. type NodeRef struct{} -func (c *Server) saveNode(inode uint64, node Node) (id fuse.NodeID, gen uint64) { +func (c *Server) saveNode(inode uint64, node Node) (id fuse.ESSNodeID, gen uint64) { c.meta.Lock() defer c.meta.Unlock() @@ -496,7 +496,7 @@ func (c *Server) saveNode(inode uint64, node Node) (id fuse.NodeID, gen uint64) c.node[id] = sn c.nodeGen++ } else { - id = fuse.NodeID(len(c.node)) + id = fuse.ESSNodeID(len(c.node)) c.node = append(c.node, sn) } sn.generation = c.nodeGen @@ -504,7 +504,7 @@ func (c *Server) saveNode(inode uint64, node Node) (id fuse.NodeID, gen uint64) return id, sn.generation } -func (c *Server) saveHandle(handle Handle, nodeID fuse.NodeID) (id fuse.HandleID) { +func (c *Server) saveHandle(handle Handle, nodeID fuse.ESSNodeID) (id fuse.HandleID) { c.meta.Lock() shandle := &serveHandle{handle: handle, nodeID: nodeID} if n := len(c.freeHandle); n > 0 { @@ -522,14 +522,14 @@ func (c *Server) saveHandle(handle Handle, nodeID fuse.NodeID) (id fuse.HandleID type nodeRefcountDropBug struct { N uint64 Refs uint64 - Node fuse.NodeID + Node fuse.ESSNodeID } func (n *nodeRefcountDropBug) String() string { return fmt.Sprintf("bug: trying to drop %d of %d references to %v", n.N, n.Refs, n.Node) } -func (c *Server) dropNode(id fuse.NodeID, n uint64) (forget bool) { +func (c *Server) dropNode(id fuse.ESSNodeID, n uint64) (forget bool) { c.meta.Lock() defer c.meta.Unlock() snode := c.node[id] @@ -653,7 +653,7 @@ func (r response) String() string { type notification struct { Op string - Node fuse.NodeID + Node fuse.ESSNodeID Out interface{} `json:",omitempty"` Err string `json:",omitempty"` } @@ -679,7 +679,7 @@ func (n notification) String() string { } type logMissingNode struct { - MaxNode fuse.NodeID + MaxNode fuse.ESSNodeID } func opName(req fuse.Request) string { @@ -786,7 +786,7 @@ func (c *Server) serve(r fuse.Request) { c.meta.Lock() hdr := r.Hdr() if id := hdr.Node; id != 0 { - if id < fuse.NodeID(len(c.node)) { + if id < fuse.ESSNodeID(len(c.node)) { snode = c.node[uint(id)] } if snode == nil { @@ -799,7 +799,7 @@ func (c *Server) serve(r fuse.Request) { // Out; not sure if i want to do that; might get rid // of len(c.node) things altogether Out: logMissingNode{ - MaxNode: fuse.NodeID(len(c.node)), + MaxNode: fuse.ESSNodeID(len(c.node)), }, }) r.RespondError(fuse.ESTALE) diff --git a/vendor/bazil.org/fuse/fuse.go b/vendor/bazil.org/fuse/fuse.go index 6db0ef2935..8fe959e9aa 100644 --- a/vendor/bazil.org/fuse/fuse.go +++ b/vendor/bazil.org/fuse/fuse.go @@ -262,12 +262,12 @@ func (r RequestID) String() string { return fmt.Sprintf("%#x", uint64(r)) } -// A NodeID is a number identifying a directory or file. +// A ESSNodeID is a number identifying a directory or file. // It must be unique among IDs returned in LookupResponses // that have not yet been forgotten by ForgetRequests. -type NodeID uint64 +type ESSNodeID uint64 -func (n NodeID) String() string { +func (n ESSNodeID) String() string { return fmt.Sprintf("%#x", uint64(n)) } @@ -280,13 +280,13 @@ func (h HandleID) String() string { } // The RootID identifies the root directory of a FUSE file system. -const RootID NodeID = rootID +const RootID ESSNodeID = rootID // A Header describes the basic information sent in every request. type Header struct { Conn *Conn `json:"-"` // connection this request was received on ID RequestID // unique ID for request - Node NodeID // file or directory the request is about + Node ESSNodeID // file or directory the request is about Uid uint32 // user ID of process making request Gid uint32 // group ID of process making request Pid uint32 // process ID of process making request @@ -468,7 +468,7 @@ func (m *message) Header() Header { return Header{ Conn: m.conn, ID: RequestID(h.Unique), - Node: NodeID(h.Nodeid), + Node: ESSNodeID(h.Nodeid), Uid: h.Uid, Gid: h.Gid, Pid: h.Pid, @@ -696,7 +696,7 @@ loop: newName = newName[:len(newName)-1] req = &LinkRequest{ Header: m.Header(), - OldNode: NodeID(in.Oldnodeid), + OldNode: ESSNodeID(in.Oldnodeid), NewName: string(newName), } @@ -763,7 +763,7 @@ loop: if m.len() < unsafe.Sizeof(*in) { goto corrupt } - newDirNodeID := NodeID(in.Newdir) + newDirESSNodeID := ESSNodeID(in.Newdir) oldNew := m.bytes()[unsafe.Sizeof(*in):] // oldNew should be "old\x00new\x00" if len(oldNew) < 4 { @@ -779,7 +779,7 @@ loop: oldName, newName := string(oldNew[:i]), string(oldNew[i+1:len(oldNew)-1]) req = &RenameRequest{ Header: m.Header(), - NewDir: newDirNodeID, + NewDir: newDirESSNodeID, OldName: oldName, NewName: newName, } @@ -1021,8 +1021,8 @@ loop: if m.len() < unsafe.Sizeof(*in) { goto corrupt } - oldDirNodeID := NodeID(in.Olddir) - newDirNodeID := NodeID(in.Newdir) + oldDirESSNodeID := ESSNodeID(in.Olddir) + newDirESSNodeID := ESSNodeID(in.Newdir) oldNew := m.bytes()[unsafe.Sizeof(*in):] // oldNew should be "oldname\x00newname\x00" if len(oldNew) < 4 { @@ -1038,8 +1038,8 @@ loop: oldName, newName := string(oldNew[:i]), string(oldNew[i+1:len(oldNew)-1]) req = &ExchangeDataRequest{ Header: m.Header(), - OldDir: oldDirNodeID, - NewDir: newDirNodeID, + OldDir: oldDirESSNodeID, + NewDir: newDirESSNodeID, OldName: oldName, NewName: newName, // TODO options @@ -1153,7 +1153,7 @@ func (c *Conn) sendInvalidate(msg []byte) error { // // Returns ErrNotCached if the kernel is not currently caching the // node. -func (c *Conn) InvalidateNode(nodeID NodeID, off int64, size int64) error { +func (c *Conn) InvalidateNode(nodeID ESSNodeID, off int64, size int64) error { buf := newBuffer(unsafe.Sizeof(notifyInvalInodeOut{})) h := (*outHeader)(unsafe.Pointer(&buf[0])) // h.Unique is 0 @@ -1175,7 +1175,7 @@ func (c *Conn) InvalidateNode(nodeID NodeID, off int64, size int64) error { // // Returns ErrNotCached if the kernel is not currently caching the // node. -func (c *Conn) InvalidateEntry(parent NodeID, name string) error { +func (c *Conn) InvalidateEntry(parent ESSNodeID, name string) error { const maxUint32 = ^uint32(0) if uint64(len(name)) > uint64(maxUint32) { // very unlikely, but we don't want to silently truncate @@ -1602,7 +1602,7 @@ func (r *LookupRequest) Respond(resp *LookupResponse) { // A LookupResponse is the response to a LookupRequest. type LookupResponse struct { - Node NodeID + Node ESSNodeID Generation uint64 EntryValid time.Duration Attr Attr @@ -2167,7 +2167,7 @@ func (r *ReadlinkRequest) Respond(target string) { // A LinkRequest is a request to create a hard link. type LinkRequest struct { Header `json:"-"` - OldNode NodeID + OldNode ESSNodeID NewName string } @@ -2194,7 +2194,7 @@ func (r *LinkRequest) Respond(resp *LookupResponse) { // A RenameRequest is a request to rename a file. type RenameRequest struct { Header `json:"-"` - NewDir NodeID + NewDir ESSNodeID OldName, NewName string } @@ -2285,7 +2285,7 @@ func (r *InterruptRequest) String() string { // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html type ExchangeDataRequest struct { Header `json:"-"` - OldDir, NewDir NodeID + OldDir, NewDir ESSNodeID OldName, NewName string // TODO options } diff --git a/vendor/github.com/pborman/uuid/node.go b/vendor/github.com/pborman/uuid/node.go index 42d60da8f1..d946d9b334 100644 --- a/vendor/github.com/pborman/uuid/node.go +++ b/vendor/github.com/pborman/uuid/node.go @@ -16,9 +16,9 @@ var ( nodeID []byte // hardware for version 1 UUIDs ) -// NodeInterface returns the name of the interface from which the NodeID was -// derived. The interface "user" is returned if the NodeID was set by -// SetNodeID. +// NodeInterface returns the name of the interface from which the ESSNodeID was +// derived. The interface "user" is returned if the ESSNodeID was set by +// SetESSNodeID. func NodeInterface() string { defer nodeMu.Unlock() nodeMu.Lock() @@ -48,7 +48,7 @@ func setNodeInterface(name string) bool { for _, ifs := range interfaces { if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { - if setNodeID(ifs.HardwareAddr) { + if setESSNodeID(ifs.HardwareAddr) { ifname = ifs.Name return true } @@ -68,9 +68,9 @@ func setNodeInterface(name string) bool { return false } -// NodeID returns a slice of a copy of the current Node ID, setting the Node ID +// ESSNodeID returns a slice of a copy of the current Node ID, setting the Node ID // if not already set. -func NodeID() []byte { +func ESSNodeID() []byte { defer nodeMu.Unlock() nodeMu.Lock() if nodeID == nil { @@ -81,20 +81,20 @@ func NodeID() []byte { return nid } -// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes +// SetESSNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes // of id are used. If id is less than 6 bytes then false is returned and the // Node ID is not set. -func SetNodeID(id []byte) bool { +func SetESSNodeID(id []byte) bool { defer nodeMu.Unlock() nodeMu.Lock() - if setNodeID(id) { + if setESSNodeID(id) { ifname = "user" return true } return false } -func setNodeID(id []byte) bool { +func setESSNodeID(id []byte) bool { if len(id) < 6 { return false } @@ -105,9 +105,9 @@ func setNodeID(id []byte) bool { return true } -// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is -// not valid. The NodeID is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) NodeID() []byte { +// ESSNodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is +// not valid. The ESSNodeID is only well defined for version 1 and 2 UUIDs. +func (uuid UUID) ESSNodeID() []byte { if len(uuid) != 16 { return nil } diff --git a/vendor/github.com/pborman/uuid/version1.go b/vendor/github.com/pborman/uuid/version1.go index 0127eacfab..5e0f366721 100644 --- a/vendor/github.com/pborman/uuid/version1.go +++ b/vendor/github.com/pborman/uuid/version1.go @@ -8,9 +8,9 @@ import ( "encoding/binary" ) -// NewUUID returns a Version 1 UUID based on the current NodeID and clock -// sequence, and the current time. If the NodeID has not been set by SetNodeID -// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// NewUUID returns a Version 1 UUID based on the current ESSNodeID and clock +// sequence, and the current time. If the ESSNodeID has not been set by SetESSNodeID +// or SetNodeInterface then it will be set automatically. If the ESSNodeID cannot // be set NewUUID returns nil. If clock sequence has not been set by // SetClockSequence then it will be set automatically. If GetTime fails to // return the current NewUUID returns nil.