forked from nknorg/nkn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nknd.go
350 lines (301 loc) · 7.56 KB
/
nknd.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"os/signal"
"runtime"
"strings"
"time"
"github.com/nknorg/nkn/api/httpjson"
"github.com/nknorg/nkn/api/httpjson/client"
"github.com/nknorg/nkn/api/websocket"
"github.com/nknorg/nkn/consensus/ising"
"github.com/nknorg/nkn/core/ledger"
"github.com/nknorg/nkn/core/transaction"
"github.com/nknorg/nkn/crypto"
"github.com/nknorg/nkn/db"
"github.com/nknorg/nkn/gateway/httpproxy"
"github.com/nknorg/nkn/net/node"
"github.com/nknorg/nkn/net/protocol"
"github.com/nknorg/nkn/por"
"github.com/nknorg/nkn/util/config"
"github.com/nknorg/nkn/util/log"
"github.com/nknorg/nkn/util/password"
"github.com/nknorg/nkn/vault"
"github.com/nknorg/nnet"
nnetnode "github.com/nknorg/nnet/node"
"github.com/nknorg/nnet/overlay"
"github.com/nknorg/nnet/overlay/chord"
"github.com/urfave/cli"
)
const (
TestNetVersionNum = 3
)
var (
createMode bool
seedStr string
)
func init() {
log.Init(log.Path, log.Stdout)
runtime.GOMAXPROCS(runtime.NumCPU())
rand.Seed(time.Now().UnixNano())
crypto.SetAlg(config.Parameters.EncryptAlg)
}
func InitLedger(account *vault.Account) error {
var err error
store, err := db.NewLedgerStore()
if err != nil {
return err
}
blockChain, err := ledger.NewBlockchainWithGenesisBlock(store)
if err != nil {
return err
}
ledger.DefaultLedger = &ledger.Ledger{
Blockchain: blockChain,
Store: store,
}
transaction.Store = ledger.DefaultLedger.Store
por.Store = ledger.DefaultLedger.Store
vault.Store = ledger.DefaultLedger.Store
return nil
}
func StartConsensus(wallet vault.Wallet, node protocol.Noder) {
log.Info("ising consensus starting ...")
account, _ := wallet.GetDefaultAccount()
go ising.NewProposerService(account, node).Start()
}
func JoinNet(nn *nnet.NNet) error {
seeds := config.Parameters.SeedList
rand.Shuffle(len(seeds), func(i int, j int) {
seeds[i], seeds[j] = seeds[j], seeds[i]
})
for _, seed := range seeds {
succAddrs, err := client.FindSuccessorAddrs(seed, nn.GetLocalNode().Id)
if err != nil {
log.Warningf("Can't get successor address from [%s]", seed)
continue
}
success := false
for _, succAddr := range succAddrs {
if succAddr == nn.GetLocalNode().Addr {
log.Warning("Skipping self...")
continue
}
err = nn.Join(succAddr)
if err != nil {
log.Error(err)
continue
}
success = true
}
if success {
return nil
}
}
return errors.New("Failed to join the network.")
}
func nknMain(c *cli.Context) error {
log.Info("Node version: ", config.Version)
signalChan := make(chan os.Signal, 1)
err := config.Init()
if err != nil {
return err
}
log.Log.SetDebugLevel(config.Parameters.LogLevel) // Update LogLevel after config.json loaded
// Get local account
wallet := vault.GetWallet()
if wallet == nil {
return errors.New("open local wallet error")
}
account, err := wallet.GetDefaultAccount()
if err != nil {
return errors.New("load local account error")
}
conf := &nnet.Config{
Transport: config.Parameters.Transport,
Hostname: config.Parameters.Hostname,
Port: config.Parameters.NodePort,
NodeIDBytes: 32,
MinNumSuccessors: config.MinNumSuccessors,
}
err = nnet.SetLogger(log.Log)
if err != nil {
return err
}
id := node.GenChordID(fmt.Sprintf("%s:%d", config.Parameters.Hostname, config.Parameters.NodePort))
nn, err := nnet.NewNNet(id, conf)
if err != nil {
return err
}
nn.MustApplyMiddleware(overlay.NetworkStopped(func(network overlay.Network) bool {
select {
case signalChan <- os.Interrupt:
default:
}
return true
}))
if len(seedStr) > 0 {
// Support input mutil seeds which split by ","
config.Parameters.SeedList = strings.Split(seedStr, ",")
}
// initialize ledger
err = InitLedger(account)
if err != nil {
return fmt.Errorf("ledger initialization error: %v", err)
}
// if InitLedger return err, ledger.DefaultLedger is uninitialized.
defer ledger.DefaultLedger.Store.Close()
err = por.InitPorServer(account, id)
if err != nil {
return errors.New("PorServer initialization error")
}
node, err := node.InitNode(account.PublicKey, nn)
if err != nil {
return err
}
// start relay service
node.StartRelayer(wallet)
//start JsonRPC
rpcServer := httpjson.NewServer(node, wallet)
// start websocket server
ws := websocket.NewServer(node, wallet)
// start http proxy
hp := httpproxy.NewServer()
nn.MustApplyMiddleware(chord.SuccessorAdded(func(remoteNode *nnetnode.RemoteNode, index int) bool {
if index == 0 {
ws.NotifyWrongClients()
}
return true
}))
err = nn.Start(createMode)
if err != nil {
return err
}
if !createMode {
err = JoinNet(nn)
if err != nil {
return err
}
go func() {
for {
time.Sleep(time.Minute)
if node.GetConnectionCnt() == 0 {
log.Error("Node has no neighbors and is too lonely to run")
panic("Node has no neighbors and is too lonely to run")
}
}
}()
}
defer nn.Stop(nil)
go rpcServer.Start()
go ws.Start()
go hp.Start()
// start consensus
StartConsensus(wallet, node)
go func() {
for {
time.Sleep(config.ConsensusTime)
if log.CheckIfNeedNewFile() {
log.ClosePrintLog()
log.Init(log.Path, os.Stdout)
}
}
}()
signal.Notify(signalChan, os.Interrupt)
for _ = range signalChan {
fmt.Println("\nReceived an interrupt, stopping services...\n")
return nil
}
return nil
}
type testNetVer struct {
Ver int `json:"version"`
}
func GetRemoteVersionNum() (int, error) {
var myClient = &http.Client{Timeout: 10 * time.Second}
r, err := myClient.Get("http://testnet.nkn.org/nkn.runtime.version")
if err != nil {
return 0, err
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return 0, err
}
res := testNetVer{}
json.Unmarshal(body, &res)
return res.Ver, err
}
func TestNetVersion(timer *time.Timer) {
for {
select {
case <-timer.C:
verNum, err := GetRemoteVersionNum()
if err != nil {
log.Warning("Get the remote version number error")
timer.Reset(30 * time.Minute)
break
}
if verNum > TestNetVersionNum {
log.Error("Your current nknd is deprecated, Please download the latest NKN software from https://github.com/nknorg/nkn/releases")
panic("Your current nknd is deprecated, Please download the latest NKN software from https://github.com/nknorg/nkn/releases")
}
timer.Reset(30 * time.Minute)
}
}
}
func main() {
// Detect the remote nknd version, only used for testnet for debugging purposes
timer := time.NewTimer(1 * time.Second)
go TestNetVersion(timer)
app := cli.NewApp()
app.Name = "nknd"
app.Version = config.Version
app.HelpName = "nknd"
app.Usage = "full node of NKN blockchain"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "create, c",
Usage: "Create Mode",
Hidden: false,
Destination: &createMode,
},
cli.StringFlag{
Name: "seed",
Usage: "Seed List to join",
Value: "",
Destination: &seedStr,
},
cli.StringFlag{
Name: "passwd, p",
Usage: "Password of Your wallet private Key",
Value: "",
Hidden: true,
Destination: &password.Passwd,
},
cli.BoolFlag{
Name: "no-check-port",
Usage: "Skip checking port opening",
Hidden: true,
Destination: &config.SkipCheckPort,
},
cli.BoolFlag{
Name: "no-nat",
Usage: "Skip NAT traversal for UPnP and NAT-PMP",
Hidden: false,
Destination: &config.SkipNAT,
},
}
app.Action = nknMain
// app.Run will shutdown graceful.
if err := app.Run(os.Args); err != nil {
log.Errorf("%v", err)
os.Exit(1)
}
}