forked from thetatoken/theta-protocol-ledger
/
start.go
260 lines (227 loc) · 8.02 KB
/
start.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
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"path"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/thetatoken/theta/cmd/thetacli/cmd/utils"
"github.com/thetatoken/theta/common"
"github.com/thetatoken/theta/core"
"github.com/thetatoken/theta/crypto"
"github.com/thetatoken/theta/node"
"github.com/thetatoken/theta/p2p/messenger"
"github.com/thetatoken/theta/snapshot"
"github.com/thetatoken/theta/store/database/backend"
"github.com/thetatoken/theta/version"
ks "github.com/thetatoken/theta/wallet/softwallet/keystore"
)
// startCmd represents the start command
var startCmd = &cobra.Command{
Use: "start",
Short: "Start Theta node.",
Run: runStart,
}
func init() {
RootCmd.AddCommand(startCmd)
}
func runStart(cmd *cobra.Command, args []string) {
port := viper.GetInt(common.CfgP2PPort)
// Parse seeds and filter out empty item.
f := func(c rune) bool {
return c == ','
}
peerSeeds := strings.FieldsFunc(viper.GetString(common.CfgP2PSeeds), f)
privKey, err := loadOrCreateKey()
if err != nil {
log.Fatalf("Failed to load or create key: %v", err)
}
network := newMessenger(privKey, peerSeeds, port)
mainDBPath := path.Join(cfgPath, "db", "main")
refDBPath := path.Join(cfgPath, "db", "ref")
db, err := backend.NewLDBDatabase(mainDBPath, refDBPath, 256, 0)
if err != nil {
log.Fatalf("Failed to connect to the db. main: %v, ref: %v, err: %v",
mainDBPath, refDBPath, err)
}
if len(snapshotPath) == 0 {
snapshotPath = path.Join(cfgPath, "snapshot")
}
snapshotBlockHeader, err := snapshot.ValidateSnapshot(snapshotPath, chainImportDirPath, chainCorrectionPath)
if err != nil {
log.Fatalf("Snapshot validation failed, err: %v", err)
}
root := &core.Block{BlockHeader: snapshotBlockHeader}
viper.Set(common.CfgGenesisChainID, root.ChainID)
params := &node.Params{
ChainID: root.ChainID,
PrivateKey: privKey,
Root: root,
Network: network,
DB: db,
SnapshotPath: snapshotPath,
ChainImportDirPath: chainImportDirPath,
ChainCorrectionPath: chainCorrectionPath,
}
n := node.NewNode(params)
// trap Ctrl+C and call cancel on the context
ctx, cancel := context.WithCancel(context.Background())
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
done := make(chan struct{})
go func() {
<-c
signal.Stop(c)
cancel()
// Wait at most 5 seconds before forcefully shutting down.
<-time.After(time.Duration(5) * time.Second)
close(done)
}()
n.Start(ctx)
go func() {
n.Wait()
close(done)
}()
<-done
log.Infof("")
log.Infof("Graceful exit.")
printExitBanner()
}
func loadOrCreateKey() (*crypto.PrivateKey, error) {
keysDir := path.Join(cfgPath, "key")
keystore, err := ks.NewKeystoreEncrypted(keysDir, ks.StandardScryptN, ks.StandardScryptP)
if err != nil {
log.Fatalf("Failed to create key store: %v", err)
}
addresses, err := keystore.ListKeyAddresses()
if err != nil {
log.Fatalf("Failed to get key address: %v", err)
}
numAddrs := len(addresses)
if numAddrs > 1 {
return nil, fmt.Errorf("Multiple encrypted keys detected under %v. Please keep only one key.", path.Join(keysDir, "encrypted"))
}
printWelcomeBanner()
var password string
var nodeAddrss common.Address
if numAddrs == 0 {
if len(nodePassword) != 0 {
password = nodePassword
} else {
fmt.Println("")
fmt.Println("You are launching the Theta Node for the first time. Welcome and please follow the instructions to setup the node.")
fmt.Println("")
firstPrompt := fmt.Sprintf("Please choose your password for the Theta Node: ")
firstPassword, err := utils.GetPassword(firstPrompt)
if err != nil {
return nil, fmt.Errorf("Failed to get password: %v", err)
}
secondPrompt := fmt.Sprintf("Please enter your password again: ")
secondPassword, err := utils.GetPassword(secondPrompt)
if err != nil {
return nil, fmt.Errorf("Failed to get password: %v", err)
}
if firstPassword != secondPassword {
return nil, fmt.Errorf("Passwords do not match")
}
fmt.Println("")
fmt.Println("-----------------------------------------------------------------------------------------------------")
fmt.Println("IMPORTANT: Please store your password securely. You will need it each time you launch the Theta node.")
fmt.Println("-----------------------------------------------------------------------------------------------------")
fmt.Println("")
// fmt.Println("Please press enter to continue..")
// utils.GetConfirmation()
password = firstPassword
}
privKey, _, err := crypto.GenerateKeyPair()
if err != nil {
return nil, err
}
key := ks.NewKey(privKey)
err = keystore.StoreKey(key, password)
if err != nil {
return nil, err
}
nodeAddrss = key.Address
printCountdown()
} else {
prompt := fmt.Sprintf("Please enter the password to launch the Theta node: ")
if len(nodePassword) != 0 {
password = nodePassword
} else {
password, err = utils.GetPassword(prompt)
}
if err != nil {
return nil, fmt.Errorf("Failed to get password: %v", err)
}
nodeAddrss = addresses[0]
}
nodeKey, err := keystore.GetKey(nodeAddrss, password)
if err != nil {
return nil, err
}
nodePrivKey := nodeKey.PrivateKey
return nodePrivKey, nil
}
func newMessenger(privKey *crypto.PrivateKey, seedPeerNetAddresses []string, port int) *messenger.Messenger {
log.WithFields(log.Fields{
"pubKey": fmt.Sprintf("%v", privKey.PublicKey().ToBytes()),
"address": fmt.Sprintf("%v", privKey.PublicKey().Address()),
}).Info("Using key")
msgrConfig := messenger.GetDefaultMessengerConfig()
msgrConfig.SetAddressBookFilePath(path.Join(cfgPath, "addrbook.json"))
messenger, err := messenger.CreateMessenger(privKey, seedPeerNetAddresses, port, msgrConfig)
if err != nil {
log.WithFields(log.Fields{"err": err}).Fatal("Failed to create PeerDiscoveryManager instance")
}
return messenger
}
func printCountdown() {
for i := 10; i >= 0; i-- {
fmt.Printf("\rLaunching Theta to da moon: %d...", i)
time.Sleep(1 * time.Second)
}
fmt.Printf("\n\n")
}
func printWelcomeBanner() {
fmt.Println("")
fmt.Println("")
fmt.Println(" ######################################################### ")
fmt.Println("# #")
fmt.Println("# _ _ _ _ _______ _ _ #")
fmt.Println("# | | | | | | | |__ __| | | | #")
fmt.Println("# | |__| | ___| | | ___ | | | |__ ___| |_ __ _ #")
fmt.Println("# | __ |/ _ \\ | |/ _ \\ | | | '_ \\ / _ \\ __/ _` | #")
fmt.Println("# | | | | __/ | | (_) | | | | | | | __/ || (_| | #")
fmt.Println("# |_| |_|\\___|_|_|\\___/ |_| |_| |_|\\___|\\__\\__,_| #")
fmt.Println("# #")
fmt.Println("# #")
fmt.Println(" ######################################################### ")
fmt.Println("")
fmt.Println("")
fmt.Printf("Version %v, GitHash %s\nBuilt at %s\n", version.Version, version.GitHash, version.Timestamp)
fmt.Println("")
}
func printExitBanner() {
fmt.Println("")
fmt.Println("")
fmt.Println(" #################################################### ")
fmt.Println("# #")
fmt.Println("# ____ _______ _ _ #")
fmt.Println("# | _ \\ |__ __| | | | #")
fmt.Println("# | |_) |_ _ ___ | | | |__ ___| |_ __ _ #")
fmt.Println("# | _ <| | | |/ _ \\ | | | '_ \\ / _ \\ __/ _` | #")
fmt.Println("# | |_) | |_| | __/ | | | | | | __/ || (_| | #")
fmt.Println("# |____/ \\__, |\\___| |_| |_| |_|\\___|\\__\\__,_| #")
fmt.Println("# __/ | #")
fmt.Println("# |___/ #")
fmt.Println("# #")
fmt.Println(" #################################################### ")
fmt.Println("")
fmt.Println("")
}