-
Notifications
You must be signed in to change notification settings - Fork 6
/
chaincmd.go
299 lines (269 loc) · 8.42 KB
/
chaincmd.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
// Copyright 2015 The go-ethereum Authors
// Copyright 2018 Ngin project
// This file is part of Ngin.
//
// Ngin is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Ngin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Ngin. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"bufio"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/NginProject/ngind/common"
"github.com/NginProject/ngind/core"
"github.com/NginProject/ngind/core/state"
"github.com/NginProject/ngind/core/types"
"github.com/NginProject/ngind/logger/glog"
"gopkg.in/urfave/cli.v1"
)
var (
importCommand = cli.Command{
Action: importChain,
Name: "import",
Usage: `Import a blockchain file`,
}
exportCommand = cli.Command{
Action: exportChain,
Name: "export",
Usage: `Export blockchain into file`,
Description: `
Requires a first argument of the file to write to.
Optional second and third arguments control the first and
last block to write. In this mode, the file will be appended
if already existing.
`,
}
upgradedbCommand = cli.Command{
Action: upgradeDB,
Name: "upgrade-db",
Aliases: []string{"upgradedb"},
Usage: "Upgrade chainblock database",
}
dumpCommand = cli.Command{
Action: dump,
Name: "dump",
Usage: `Dump a specific block from storage`,
Description: `
The arguments are interpreted as block numbers or hashes.
Use "$ ngind dump 0" to dump the genesis block.
`,
}
dumpChainConfigCommand = cli.Command{
Action: dumpChainConfig,
Name: "dump-chain-config",
Aliases: []string{"dumpchainconfig"},
Usage: "Dump current chain configuration to JSON file [REQUIRED argument: filepath.json]",
Description: `
The dump external configuration command writes a JSON file containing pertinent configuration data for
the configuration of a chain database. It includes genesis block data as well as chain fork settings.
`,
}
rollbackCommand = cli.Command{
Action: rollback,
Name: "rollback",
Aliases: []string{"roll-back", "set-head", "sethead"},
Usage: "Set current head for blockchain, purging antecedent blocks",
Description: `
Rollback set the current head block for block chain already in the database.
This is a destructive action, purging any block more recent than the index specified.
Syncing will require downloading contemporary block information from the index onwards.
`,
}
statusCommand = cli.Command{
Action: status,
Name: "status",
Usage: "Display the status of the current node",
Description: `
Show the status of the current configuration.
`,
}
resetCommand = cli.Command{
Action: resetChaindata,
Name: "reset",
Usage: "Reset (remove) the chain database",
Description: `
Reset does a hard reset of the entire chain database.
This is a drastic and irreversible command, and should be used with caution.
The command will require user confirmation before any action is taken.
`,
}
recoverCommand = cli.Command{
Action: recoverChaindata,
Name: "recover",
Usage: "Attempt blockchain data recovery in case of data corruption",
Description: `
Recover scans and health-checks all available blockchain data in order
to recover all consistent and healthy block data. It will remove invalid or
corrupt block data that may have been caused by hard killing, system failure,
space limitations, or attack.
`,
}
)
func importChain(ctx *cli.Context) error {
if len(ctx.Args()) != 1 {
log.Fatal("This command requires an argument.")
}
chain, chainDb := MakeChain(ctx)
start := time.Now()
err := ImportChain(chain, ctx.Args().First())
chainDb.Close()
if err != nil {
log.Fatal("Import error: ", err)
}
fmt.Printf("Import done in %v", time.Since(start))
return nil
}
func exportChain(ctx *cli.Context) error {
if len(ctx.Args()) < 1 {
log.Fatal("This command requires an argument.")
}
chain, _ := MakeChain(ctx)
start := time.Now()
fp := ctx.Args().First()
if len(ctx.Args()) < 3 {
if err := ExportChain(chain, fp); err != nil {
log.Fatal(err)
}
} else {
// This can be improved to allow for numbers larger than 9223372036854775807
first, err := strconv.ParseUint(ctx.Args().Get(1), 10, 64)
if err != nil {
log.Fatal("export paramater: ", err)
}
last, err := strconv.ParseUint(ctx.Args().Get(2), 10, 64)
if err != nil {
log.Fatal("export paramater: ", err)
}
if err = ExportAppendChain(chain, fp, first, last); err != nil {
log.Fatal(err)
}
}
fmt.Printf("Export done in %v", time.Since(start))
return nil
}
func upgradeDB(ctx *cli.Context) error {
glog.Infoln("Upgrading blockchain database")
chain, chainDb := MakeChain(ctx)
bcVersion := core.GetBlockChainVersion(chainDb)
if bcVersion == 0 {
bcVersion = core.BlockChainVersion
}
// Export the current chain.
filename := fmt.Sprintf("blockchain_%d_%s.chain", bcVersion, time.Now().Format("20060102_150405"))
exportFile := filepath.Join(ctx.GlobalString(DataDirFlag.Name), filename)
if err := ExportChain(chain, exportFile); err != nil {
log.Fatal("Unable to export chain for reimport ", err)
}
chainDb.Close()
os.RemoveAll(filepath.Join(ctx.GlobalString(DataDirFlag.Name), "chaindata"))
// Import the chain file.
chain, chainDb = MakeChain(ctx)
core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
err := ImportChain(chain, exportFile)
chainDb.Close()
if err != nil {
log.Fatalf("Import error %v (a backup is made in %s, use the import command to import it)", err, exportFile)
} else {
os.Remove(exportFile)
glog.Infoln("Import finished")
}
return nil
}
// Original use allows n hashes|ints as space-separated arguments, dumping entire state for each block n[x].
// $ ngind dump [hash|num] [hash|num] ... [hash|num]
// $ ngind dump 0x234234234234233 42 43 0xlksdf234r23r234223
//
// Revised use allows n hashes|ints as comma-separated first argument and n addresses as comma-separated second argument,
// dumping only state information for given addresses if they're present.
// revised use: $ ngind dump [hash|num],[hash|num],...,[hash|num] [address],[address],...,[address]
//
// Added unsorted/sorted dumping algorithms.
// unsorted dump is used by default.
// revised use: $ ngind dump [sorted] [hash|num],[hash|num],...,[hash|num] [address],[address],...,[address]
func dump(ctx *cli.Context) error {
if ctx.NArg() == 0 {
return fmt.Errorf("%v: use: $ ngind dump [blockHash|blockNum],[blockHash|blockNum] [[addressHex|addressPrefixedHex],[addressHex|addressPrefixedHex]]", ErrInvalidFlag)
}
firstArg := 0
sorted := ctx.Args()[0] == "sorted"
if sorted {
firstArg = 1
}
blocks := strings.Split(ctx.Args()[firstArg], ",")
addresses := []common.Address{}
argaddress := ""
if ctx.NArg() > firstArg+1 {
argaddress = ctx.Args()[firstArg+1]
}
if argaddress != "" {
argaddresses := strings.Split(argaddress, ",")
for _, a := range argaddresses {
addresses = append(addresses, common.HexToAddress(strings.TrimSpace(a)))
}
}
chain, chainDb := MakeChain(ctx)
defer chainDb.Close()
prefix := ""
indent := " "
out := bufio.NewWriter(os.Stdout)
if len(blocks) > 1 {
prefix = indent
out.WriteString("[\n")
}
for n, b := range blocks {
b = strings.TrimSpace(b)
var block *types.Block
if hashish(b) {
block = chain.GetBlock(common.HexToHash(b))
} else {
num, _ := strconv.Atoi(b)
block = chain.GetBlockByNumber(uint64(num))
}
if block == nil {
out.WriteString("{}\n")
log.Fatal("block not found")
} else {
state, err := state.New(block.Root(), state.NewDatabase(chainDb))
if err != nil {
return fmt.Errorf("could not create new state: %v", err)
}
if n != 0 {
out.WriteString(",\n")
}
if sorted {
err = state.SortedDump(addresses, prefix, indent, out)
} else {
err = state.UnsortedDump(addresses, prefix, indent, out)
}
if err != nil {
return err
}
}
}
if len(blocks) > 1 {
out.WriteString("\n]")
}
out.WriteString("\n")
out.Flush()
return nil
}
// hashish returns true for strings that look like hashes.
func hashish(x string) bool {
_, err := strconv.Atoi(x)
return err != nil
}