-
Notifications
You must be signed in to change notification settings - Fork 467
/
Copy pathaddress.go
460 lines (394 loc) · 11.8 KB
/
address.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package cmd
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/howeyc/gopass"
cmds "github.com/ipfs/go-ipfs-cmds"
files "github.com/ipfs/go-libipfs/files"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/venus/app/node"
"github.com/filecoin-project/venus/cmd/tablewriter"
"github.com/filecoin-project/venus/pkg/wallet"
"github.com/filecoin-project/venus/pkg/wallet/key"
"github.com/filecoin-project/venus/venus-shared/types"
)
var (
errMissPassword = errors.New("the wallet is missing password, please use command `venus wallet set-password` to set password")
errWalletLocked = errors.New("the wallet is locked, please use command `venus wallet unlock` to unlock")
)
var walletCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Manage your filecoin wallets",
},
Subcommands: map[string]*cmds.Command{
"balance": balanceCmd,
"import": walletImportCmd,
"export": walletExportCmd,
"ls": addrsLsCmd,
"new": addrsNewCmd,
"default": defaultAddressCmd,
"delete": addrsDeleteCmd,
"set-default": setDefaultAddressCmd,
"lock": lockedCmd,
"unlock": unlockedCmd,
"set-password": setWalletPassword,
},
}
type AddressResult struct {
Address address.Address
}
// AddressLsResult is the result of running the address list command.
type AddressLsResult struct {
Addresses []address.Address
}
var addrsNewCmd = &cmds.Command{
Options: []cmds.Option{
cmds.StringOption("type", "The type of address to create: bls (default) or secp256k1 or delegated").WithDefault("bls"),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
protocolName := req.Options["type"].(string)
var protocol address.Protocol
switch protocolName {
case "secp256k1":
protocol = address.SECP256K1
case "bls":
protocol = address.BLS
case "delegated":
protocol = address.Delegated
default:
return fmt.Errorf("unrecognized address protocol %s", protocolName)
}
if !env.(*node.Env).WalletAPI.HasPassword(req.Context) {
return errMissPassword
}
if env.(*node.Env).WalletAPI.WalletState(req.Context) == wallet.Lock {
return errWalletLocked
}
addr, err := env.(*node.Env).WalletAPI.WalletNewAddress(req.Context, protocol)
if err != nil {
return err
}
return printOneString(re, addr.String())
},
}
var addrsDeleteCmd = &cmds.Command{
Arguments: []cmds.Argument{
cmds.StringArg("address", true, false, "wallet address"),
},
Options: []cmds.Option{
cmds.BoolOption("really-do-it", "Actually send transaction performing the action").WithDefault(false),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
if really := req.Options["really-do-it"].(bool); !really {
return fmt.Errorf("pass --really-do-it to actually execute this action")
}
addr, err := address.NewFromString(req.Arguments[0])
if err != nil {
return err
}
if !env.(*node.Env).WalletAPI.HasPassword(req.Context) {
return errMissPassword
}
if env.(*node.Env).WalletAPI.WalletState(req.Context) == wallet.Lock {
return errWalletLocked
}
err = env.(*node.Env).WalletAPI.WalletDelete(req.Context, addr)
if err != nil {
return err
}
return printOneString(re, "Delete successfully!")
},
}
var addrsLsCmd = &cmds.Command{
Options: []cmds.Option{
cmds.BoolOption("addr-only", "Only print addresses"),
cmds.BoolOption("id", "Output ID addresses"),
cmds.BoolOption("market", "Output market balances"),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
api := env.(*node.Env)
ctx := req.Context
addrs := api.WalletAPI.WalletAddresses(req.Context)
// Assume an error means no default key is set
def, _ := api.WalletAPI.WalletDefaultAddress(req.Context)
buf := new(bytes.Buffer)
tw := tablewriter.New(
tablewriter.Col("Address"),
tablewriter.Col("ID"),
tablewriter.Col("Balance"),
tablewriter.Col("Market(Avail)"),
tablewriter.Col("Market(Locked)"),
tablewriter.Col("Nonce"),
tablewriter.Col("Default"),
tablewriter.NewLineCol("Error"))
addrOnly := false
if _, ok := req.Options["addr-only"]; ok {
addrOnly = true
}
for _, addr := range addrs {
if addrOnly {
writer := NewSilentWriter(buf)
writer.WriteStringln(addr.String())
} else {
a, err := api.ChainAPI.StateGetActor(ctx, addr, types.EmptyTSK)
if err != nil {
if !strings.Contains(err.Error(), "actor not found") {
tw.Write(map[string]interface{}{
"Address": addr,
"Error": err,
})
continue
}
a = &types.Actor{
Balance: big.Zero(),
}
}
row := map[string]interface{}{
"Address": addr,
"Balance": types.FIL(a.Balance),
"Nonce": a.Nonce,
}
if addr == def {
row["Default"] = "X"
}
if _, ok := req.Options["id"]; ok {
id, err := api.ChainAPI.StateLookupID(ctx, addr, types.EmptyTSK)
if err != nil {
row["ID"] = "n/a"
} else {
row["ID"] = id
}
}
if _, ok := req.Options["market"]; ok {
mbal, err := api.ChainAPI.StateMarketBalance(ctx, addr, types.EmptyTSK)
if err == nil {
row["Market(Avail)"] = types.FIL(types.BigSub(mbal.Escrow, mbal.Locked))
row["Market(Locked)"] = types.FIL(mbal.Locked)
}
}
tw.Write(row)
}
}
if !addrOnly {
_ = tw.Flush(buf)
}
return re.Emit(buf)
},
}
var defaultAddressCmd = &cmds.Command{
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
addr, err := env.(*node.Env).WalletAPI.WalletDefaultAddress(req.Context)
if err != nil {
return err
}
return printOneString(re, addr.String())
},
}
var setDefaultAddressCmd = &cmds.Command{
Arguments: []cmds.Argument{
cmds.StringArg("address", true, false, "address to set default for"),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
if env.(*node.Env).WalletAPI.WalletState(req.Context) == wallet.Lock {
return errWalletLocked
}
addr, err := address.NewFromString(req.Arguments[0])
if err != nil {
return err
}
err = env.(*node.Env).WalletAPI.WalletSetDefault(context.TODO(), addr)
if err != nil {
return err
}
return printOneString(re, addr.String())
},
}
var balanceCmd = &cmds.Command{
Arguments: []cmds.Argument{
cmds.StringArg("address", true, false, "APIAddress to get balance for"),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
addr, err := address.NewFromString(req.Arguments[0])
if err != nil {
return err
}
balance, err := env.(*node.Env).WalletAPI.WalletBalance(req.Context, addr)
if err != nil {
return err
}
isDone, err := isSyncDone(req.Context, env)
if err != nil {
return err
}
var balanceStr string
if balance.Equals(big.NewInt(0)) && !isDone {
balanceStr = fmt.Sprintf("%s (warning: may display 0 if chain sync in progress)", types.FIL(balance))
} else {
balanceStr = (types.FIL)(balance).String()
}
return printOneString(re, balanceStr)
},
}
func isSyncDone(ctx context.Context, env cmds.Environment) (bool, error) {
head, err := getEnv(env).ChainAPI.ChainHead(ctx)
if err != nil {
return false, err
}
params, err := getEnv(env).ChainAPI.StateGetNetworkParams(ctx)
if err != nil {
return false, err
}
return time.Now().Unix()-int64(head.MinTimestamp()) < int64(params.BlockDelaySecs), nil
}
// WalletSerializeResult is the type wallet export and import return and expect.
type WalletSerializeResult struct {
KeyInfo []*key.KeyInfo
}
var walletImportCmd = &cmds.Command{
Arguments: []cmds.Argument{
cmds.FileArg("walletFile", true, false, "File containing wallet data to import").EnableStdin(),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
if !env.(*node.Env).WalletAPI.HasPassword(req.Context) {
return errMissPassword
}
if env.(*node.Env).WalletAPI.WalletState(req.Context) == wallet.Lock {
return errWalletLocked
}
iter := req.Files.Entries()
if !iter.Next() {
return fmt.Errorf("no file given: %s", iter.Err())
}
fi, ok := iter.Node().(files.File)
if !ok {
return fmt.Errorf("given file was not a files.File")
}
var key types.KeyInfo
err := json.NewDecoder(hex.NewDecoder(fi)).Decode(&key)
if err != nil {
return err
}
addr, err := env.(*node.Env).WalletAPI.WalletImport(req.Context, &key)
if err != nil {
return err
}
return printOneString(re, addr.String())
},
}
var walletExportCmd = &cmds.Command{
Arguments: []cmds.Argument{
cmds.StringArg("addr", true, true, "address of key to export"),
cmds.StringArg("password", false, false, "Password to be locked"),
},
PreRun: func(req *cmds.Request, env cmds.Environment) error {
// for testing, skip manual password entry
if len(req.Arguments) == 2 && len(req.Arguments[1]) != 0 {
return nil
}
pw, err := gopass.GetPasswdPrompt("Password:", true, os.Stdin, os.Stdout)
if err != nil {
return err
}
fmt.Println(req.Arguments)
req.Arguments = []string{req.Arguments[0], string(pw)}
return nil
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
if env.(*node.Env).WalletAPI.WalletState(req.Context) == wallet.Lock {
return errWalletLocked
}
if len(req.Arguments) != 2 {
return re.Emit("Two parameter is required.")
}
addr, err := address.NewFromString(req.Arguments[0])
if err != nil {
return err
}
pw := req.Arguments[1]
ki, err := env.(*node.Env).WalletAPI.WalletExport(req.Context, addr, pw)
if err != nil {
return err
}
kiBytes, err := json.Marshal(ki)
if err != nil {
return err
}
return printOneString(re, hex.EncodeToString(kiBytes))
},
}
var setWalletPassword = &cmds.Command{
Arguments: []cmds.Argument{
cmds.StringArg("password", false, false, "Password to be locked"),
},
PreRun: func(req *cmds.Request, env cmds.Environment) error {
pw, err := gopass.GetPasswdPrompt("Password:", true, os.Stdin, os.Stdout)
if err != nil {
return err
}
pw2, err := gopass.GetPasswdPrompt("Enter Password again:", true, os.Stdin, os.Stdout)
if err != nil {
return err
}
if !bytes.Equal(pw, pw2) {
return errors.New("the input passwords are inconsistent")
}
req.Arguments = []string{string(pw)}
return nil
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
if len(req.Arguments) != 1 {
return re.Emit("A parameter is required.")
}
pw := req.Arguments[0]
if len(pw) == 0 {
return re.Emit("Do not enter an empty string")
}
err := env.(*node.Env).WalletAPI.SetPassword(req.Context, []byte(pw))
if err != nil {
return err
}
return printOneString(re, "Password set successfully \n"+
"You must REMEMBER your password! Without the password, it's impossible to decrypt the key!")
},
}
var lockedCmd = &cmds.Command{
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
err := env.(*node.Env).WalletAPI.LockWallet(req.Context)
if err != nil {
return err
}
return re.Emit("locked success")
},
}
var unlockedCmd = &cmds.Command{
Arguments: []cmds.Argument{
cmds.StringArg("password", false, false, "Password to be locked"),
},
PreRun: func(req *cmds.Request, env cmds.Environment) error {
pw, err := gopass.GetPasswdPrompt("Password:", true, os.Stdin, os.Stdout)
if err != nil {
return err
}
req.Arguments = []string{string(pw)}
return nil
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
if len(req.Arguments) != 1 {
return re.Emit("A parameter is required.")
}
pw := req.Arguments[0]
err := env.(*node.Env).WalletAPI.UnLockWallet(req.Context, []byte(pw))
if err != nil {
return err
}
return re.Emit("unlocked success")
},
}