-
Notifications
You must be signed in to change notification settings - Fork 157
/
node.go
123 lines (99 loc) · 2.18 KB
/
node.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// ln: abbr. of local node
package node
import (
"encoding/hex"
"encoding/json"
"net/url"
"sync"
"time"
"github.com/golang/protobuf/jsonpb"
"github.com/nknorg/nkn/v2/crypto"
"github.com/nknorg/nkn/v2/pb"
"github.com/nknorg/nkn/v2/util"
nnetpb "github.com/nknorg/nnet/protobuf"
)
type Node struct {
*nnetpb.Node
*pb.NodeData
publicKey []byte
StartTime time.Time
sync.RWMutex
syncState pb.SyncState
minVerifiableHeight uint32
}
func (n *Node) MarshalJSON() ([]byte, error) {
var out map[string]interface{}
marshaler := &jsonpb.Marshaler{}
s, err := marshaler.MarshalToString(n.Node)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(s), &out)
if err != nil {
return nil, err
}
delete(out, "data")
out["id"] = hex.EncodeToString(n.Node.Id)
s, err = marshaler.MarshalToString(n.NodeData)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(s), &out)
if err != nil {
return nil, err
}
out["publicKey"] = hex.EncodeToString(n.GetPublicKey())
out["syncState"] = n.GetSyncState().String()
return json.Marshal(out)
}
func NewNode(nnetNode *nnetpb.Node, nodeData *pb.NodeData) (*Node, error) {
err := crypto.CheckPublicKey(nodeData.PublicKey)
if err != nil {
return nil, err
}
node := &Node{
Node: nnetNode,
NodeData: nodeData,
publicKey: nodeData.PublicKey,
StartTime: time.Now(),
syncState: pb.SyncState_WAIT_FOR_SYNCING,
}
return node, nil
}
func (n *Node) GetChordID() []byte {
return n.Id
}
func (n *Node) GetID() string {
return util.ChordIDToNodeID(n.GetChordID())
}
func (n *Node) GetPubKey() []byte {
return n.publicKey
}
func (n *Node) GetHostname() string {
address, _ := url.Parse(n.GetAddr())
return address.Hostname()
}
func (n *Node) GetSyncState() pb.SyncState {
n.RLock()
defer n.RUnlock()
return n.syncState
}
func (n *Node) SetSyncState(s pb.SyncState) bool {
n.Lock()
defer n.Unlock()
if n.syncState == s {
return false
}
n.syncState = s
return true
}
func (n *Node) GetMinVerifiableHeight() uint32 {
n.RLock()
defer n.RUnlock()
return n.minVerifiableHeight
}
func (n *Node) SetMinVerifiableHeight(height uint32) {
n.Lock()
defer n.Unlock()
n.minVerifiableHeight = height
}