aboutsummaryrefslogtreecommitdiffstats
path: root/dex/nodetable.go
blob: 9fe1d6b71b621692625584ce8de2b9b3324b3899 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package dex

import (
    "net"
    "sync"

    "github.com/dexon-foundation/dexon/common"
    "github.com/dexon-foundation/dexon/crypto/sha3"
    "github.com/dexon-foundation/dexon/event"
    "github.com/dexon-foundation/dexon/log"
    "github.com/dexon-foundation/dexon/p2p/enode"
    "github.com/dexon-foundation/dexon/rlp"
)

type NodeMeta struct {
    ID        enode.ID
    IP        net.IP
    UDP       uint
    TCP       uint
    Timestamp uint64
    Sig       []byte
}

func (n *NodeMeta) Hash() (h common.Hash) {
    hw := sha3.NewKeccak256()
    rlp.Encode(hw, n)
    hw.Sum(h[:0])
    return h
}

type newMetasEvent struct{ Metas []*NodeMeta }

type nodeTable struct {
    mu    sync.RWMutex
    entry map[enode.ID]*NodeMeta
    feed  event.Feed
}

func newNodeTable() *nodeTable {
    return &nodeTable{
        entry: make(map[enode.ID]*NodeMeta),
    }
}

func (t *nodeTable) Get(id enode.ID) *NodeMeta {
    t.mu.RLock()
    defer t.mu.RUnlock()
    return t.entry[id]
}

func (t *nodeTable) Add(metas []*NodeMeta) {
    t.mu.Lock()
    defer t.mu.Unlock()

    var newMetas []*NodeMeta
    for _, meta := range metas {
        // TODO: validate the meta
        if e, ok := t.entry[meta.ID]; ok && e.Timestamp > meta.Timestamp {
            continue
        }
        t.entry[meta.ID] = meta
        newMetas = append(newMetas, meta)
        log.Trace("add new node meta", "id", meta.ID[:8],
            "ip", meta.IP, "udp", meta.UDP, "tcp", meta.TCP)
    }
    t.feed.Send(newMetasEvent{newMetas})
}

func (t *nodeTable) Metas() []*NodeMeta {
    t.mu.RLock()
    defer t.mu.RUnlock()
    metas := make([]*NodeMeta, 0, len(t.entry))
    for _, meta := range t.entry {
        metas = append(metas, meta)
    }
    return metas
}

func (t *nodeTable) SubscribeNewMetasEvent(
    ch chan<- newMetasEvent) event.Subscription {
    return t.feed.Subscribe(ch)
}