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