提交 3a68d639 作者: Łukasz Magiera

key cmd: refactor to use coreapi

License: MIT
Signed-off-by: 's avatarŁukasz Magiera <magik6k@gmail.com>
上级 c616b7ce
package commands package commands
import ( import (
"bytes"
"crypto/rand"
"fmt" "fmt"
"io" "io"
"sort"
"strings"
"text/tabwriter" "text/tabwriter"
cmds "github.com/ipfs/go-ipfs/commands" "github.com/ipfs/go-ipfs/core/commands/e"
e "github.com/ipfs/go-ipfs/core/commands/e" "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
"gx/ipfs/QmNueRyPRQiV7PUEpnP4GgGLuK1rKQLaRW7sfPvUetYig1/go-ipfs-cmds"
"gx/ipfs/QmdE4gMduCKCGAcczM2F5ioYDfdeKuPix138wrES1YSr7f/go-ipfs-cmdkit" "gx/ipfs/QmdE4gMduCKCGAcczM2F5ioYDfdeKuPix138wrES1YSr7f/go-ipfs-cmdkit"
peer "gx/ipfs/QmdVrMn1LhB4ybb8hMVaMLXnA8XRSewMnK6YqXKXoTcRvN/go-libp2p-peer"
ci "gx/ipfs/Qme1knMqwt1hKZbc1BmQFmnm9f36nyQGwXxPGVpVJ9rMK5/go-libp2p-crypto"
) )
var KeyCmd = &cmds.Command{ var KeyCmd = &cmds.Command{
...@@ -70,99 +65,54 @@ var keyGenCmd = &cmds.Command{ ...@@ -70,99 +65,54 @@ var keyGenCmd = &cmds.Command{
Arguments: []cmdkit.Argument{ Arguments: []cmdkit.Argument{
cmdkit.StringArg("name", true, false, "name of key to create"), cmdkit.StringArg("name", true, false, "name of key to create"),
}, },
Run: func(req cmds.Request, res cmds.Response) { Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := req.InvocContext().GetNode() api, err := GetApi(env)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
typ, f, err := req.Option("type").String()
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
typ, f := req.Options["type"].(string)
if !f { if !f {
res.SetError(fmt.Errorf("please specify a key type with --type"), cmdkit.ErrNormal) res.SetError(fmt.Errorf("please specify a key type with --type"), cmdkit.ErrNormal)
return return
} }
size, sizefound, err := req.Option("size").Int() name := req.Arguments[0]
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
name := req.Arguments()[0]
if name == "self" { if name == "self" {
res.SetError(fmt.Errorf("cannot create key with name 'self'"), cmdkit.ErrNormal) res.SetError(fmt.Errorf("cannot create key with name 'self'"), cmdkit.ErrNormal)
return return
} }
var sk ci.PrivKey opts := []options.KeyGenerateOption{options.Key.Type(typ)}
var pk ci.PubKey
switch typ {
case "rsa":
if !sizefound {
res.SetError(fmt.Errorf("please specify a key size with --size"), cmdkit.ErrNormal)
return
}
priv, pub, err := ci.GenerateKeyPairWithReader(ci.RSA, size, rand.Reader)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
sk = priv size, sizefound := req.Options["size"].(int)
pk = pub if sizefound {
case "ed25519": opts = append(opts, options.Key.Size(size))
priv, pub, err := ci.GenerateEd25519Key(rand.Reader)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
sk = priv
pk = pub
default:
res.SetError(fmt.Errorf("unrecognized key type: %s", typ), cmdkit.ErrNormal)
return
} }
err = n.Repo.Keystore().Put(name, sk) key, err := api.Key().Generate(req.Context, name, opts...)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
pid, err := peer.IDFromPublicKey(pk)
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
res.SetOutput(&KeyOutput{ cmds.EmitOnce(res, &KeyOutput{
Name: name, Name: name,
Id: pid.Pretty(), Id: key.Id().Pretty(),
}) })
}, },
Marshalers: cmds.MarshalerMap{ Encoders: cmds.EncoderMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) { cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
k, ok := v.(*KeyOutput) k, ok := v.(*KeyOutput)
if !ok { if !ok {
return nil, e.TypeErr(k, v) return e.TypeErr(k, v)
} }
return strings.NewReader(k.Id + "\n"), nil _, err := w.Write([]byte(k.Id + "\n"))
}, return err
}),
}, },
Type: KeyOutput{}, Type: KeyOutput{},
} }
...@@ -174,47 +124,29 @@ var keyListCmd = &cmds.Command{ ...@@ -174,47 +124,29 @@ var keyListCmd = &cmds.Command{
Options: []cmdkit.Option{ Options: []cmdkit.Option{
cmdkit.BoolOption("l", "Show extra information about keys."), cmdkit.BoolOption("l", "Show extra information about keys."),
}, },
Run: func(req cmds.Request, res cmds.Response) { Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := req.InvocContext().GetNode() api, err := GetApi(env)
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
keys, err := n.Repo.Keystore().List() keys, err := api.Key().List(req.Context)
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
sort.Strings(keys) list := make([]KeyOutput, 0, len(keys))
list := make([]KeyOutput, 0, len(keys)+1)
list = append(list, KeyOutput{Name: "self", Id: n.Identity.Pretty()})
for _, key := range keys { for _, key := range keys {
privKey, err := n.Repo.Keystore().Get(key) list = append(list, KeyOutput{Name: key.Name(), Id: key.Id().Pretty()})
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
pubKey := privKey.GetPublic()
pid, err := peer.IDFromPublicKey(pubKey)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
} }
list = append(list, KeyOutput{Name: key, Id: pid.Pretty()}) cmds.EmitOnce(res, &KeyOutputList{list})
}
res.SetOutput(&KeyOutputList{list})
}, },
Marshalers: cmds.MarshalerMap{ Encoders: cmds.EncoderMap{
cmds.Text: keyOutputListMarshaler, cmds.Text: keyOutputListMarshaler(),
}, },
Type: KeyOutputList{}, Type: KeyOutputList{},
} }
...@@ -230,100 +162,44 @@ var keyRenameCmd = &cmds.Command{ ...@@ -230,100 +162,44 @@ var keyRenameCmd = &cmds.Command{
Options: []cmdkit.Option{ Options: []cmdkit.Option{
cmdkit.BoolOption("force", "f", "Allow to overwrite an existing key."), cmdkit.BoolOption("force", "f", "Allow to overwrite an existing key."),
}, },
Run: func(req cmds.Request, res cmds.Response) { Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := req.InvocContext().GetNode() api, err := GetApi(env)
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
ks := n.Repo.Keystore() name := req.Arguments[0]
newName := req.Arguments[1]
name := req.Arguments()[0] force := req.Options["force"].(bool)
newName := req.Arguments()[1]
if name == "self" { key, overwritten, err := api.Key().Rename(req.Context, name, newName, options.Key.Force(force))
res.SetError(fmt.Errorf("cannot rename key with name 'self'"), cmdkit.ErrNormal)
return
}
if newName == "self" {
res.SetError(fmt.Errorf("cannot overwrite key with name 'self'"), cmdkit.ErrNormal)
return
}
oldKey, err := ks.Get(name)
if err != nil {
res.SetError(fmt.Errorf("no key named %s was found", name), cmdkit.ErrNormal)
return
}
pubKey := oldKey.GetPublic()
pid, err := peer.IDFromPublicKey(pubKey)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
overwrite := false
force, _, _ := res.Request().Option("f").Bool()
if force {
exist, err := ks.Has(newName)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
if exist {
overwrite = true
err := ks.Delete(newName)
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
}
}
err = ks.Put(newName, oldKey) cmds.EmitOnce(res, &KeyRenameOutput{
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
err = ks.Delete(name)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
res.SetOutput(&KeyRenameOutput{
Was: name, Was: name,
Now: newName, Now: newName,
Id: pid.Pretty(), Id: key.Id().Pretty(),
Overwrite: overwrite, Overwrite: overwritten,
}) })
}, },
Marshalers: cmds.MarshalerMap{ Encoders: cmds.EncoderMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) { cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
k, ok := v.(*KeyRenameOutput) k, ok := v.(*KeyRenameOutput)
if !ok { if !ok {
return nil, fmt.Errorf("expected a KeyRenameOutput as command result") return fmt.Errorf("expected a KeyRenameOutput as command result")
} }
buf := new(bytes.Buffer)
if k.Overwrite { if k.Overwrite {
fmt.Fprintf(buf, "Key %s renamed to %s with overwriting\n", k.Id, k.Now) fmt.Fprintf(w, "Key %s renamed to %s with overwriting\n", k.Id, k.Now)
} else { } else {
fmt.Fprintf(buf, "Key %s renamed to %s\n", k.Id, k.Now) fmt.Fprintf(w, "Key %s renamed to %s\n", k.Id, k.Now)
} }
return buf, nil return nil
}, }),
}, },
Type: KeyRenameOutput{}, Type: KeyRenameOutput{},
} }
...@@ -338,76 +214,52 @@ var keyRmCmd = &cmds.Command{ ...@@ -338,76 +214,52 @@ var keyRmCmd = &cmds.Command{
Options: []cmdkit.Option{ Options: []cmdkit.Option{
cmdkit.BoolOption("l", "Show extra information about keys."), cmdkit.BoolOption("l", "Show extra information about keys."),
}, },
Run: func(req cmds.Request, res cmds.Response) { Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) {
n, err := req.InvocContext().GetNode() api, err := GetApi(env)
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
names := req.Arguments() names := req.Arguments
list := make([]KeyOutput, 0, len(names)) list := make([]KeyOutput, 0, len(names))
for _, name := range names { for _, name := range names {
if name == "self" { key, err := api.Key().Remove(req.Context, name)
res.SetError(fmt.Errorf("cannot remove key with name 'self'"), cmdkit.ErrNormal)
return
}
removed, err := n.Repo.Keystore().Get(name)
if err != nil {
res.SetError(fmt.Errorf("no key named %s was found", name), cmdkit.ErrNormal)
return
}
pubKey := removed.GetPublic()
pid, err := peer.IDFromPublicKey(pubKey)
if err != nil { if err != nil {
res.SetError(err, cmdkit.ErrNormal) res.SetError(err, cmdkit.ErrNormal)
return return
} }
list = append(list, KeyOutput{Name: name, Id: pid.Pretty()}) list = append(list, KeyOutput{Name: name, Id: key.Id().Pretty()})
}
for _, name := range names {
err = n.Repo.Keystore().Delete(name)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
} }
res.SetOutput(&KeyOutputList{list}) cmds.EmitOnce(res, &KeyOutputList{list})
}, },
Marshalers: cmds.MarshalerMap{ Encoders: cmds.EncoderMap{
cmds.Text: keyOutputListMarshaler, cmds.Text: keyOutputListMarshaler(),
}, },
Type: KeyOutputList{}, Type: KeyOutputList{},
} }
func keyOutputListMarshaler(res cmds.Response) (io.Reader, error) { func keyOutputListMarshaler() cmds.EncoderFunc {
withId, _, _ := res.Request().Option("l").Bool() return cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
withId, _ := req.Options["l"].(bool)
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
list, ok := v.(*KeyOutputList) list, ok := v.(*KeyOutputList)
if !ok { if !ok {
return nil, e.TypeErr(list, v) return e.TypeErr(list, v)
} }
buf := new(bytes.Buffer) tw := tabwriter.NewWriter(w, 1, 2, 1, ' ', 0)
w := tabwriter.NewWriter(buf, 1, 2, 1, ' ', 0)
for _, s := range list.Keys { for _, s := range list.Keys {
if withId { if withId {
fmt.Fprintf(w, "%s\t%s\t\n", s.Id, s.Name) fmt.Fprintf(tw, "%s\t%s\t\n", s.Id, s.Name)
} else { } else {
fmt.Fprintf(w, "%s\n", s.Name) fmt.Fprintf(tw, "%s\n", s.Name)
} }
} }
w.Flush() tw.Flush()
return buf, nil return nil
})
} }
...@@ -121,7 +121,7 @@ var rootSubcommands = map[string]*cmds.Command{ ...@@ -121,7 +121,7 @@ var rootSubcommands = map[string]*cmds.Command{
"diag": lgc.NewCommand(DiagCmd), "diag": lgc.NewCommand(DiagCmd),
"dns": lgc.NewCommand(DNSCmd), "dns": lgc.NewCommand(DNSCmd),
"id": lgc.NewCommand(IDCmd), "id": lgc.NewCommand(IDCmd),
"key": lgc.NewCommand(KeyCmd), "key": KeyCmd,
"log": lgc.NewCommand(LogCmd), "log": lgc.NewCommand(LogCmd),
"ls": lgc.NewCommand(LsCmd), "ls": lgc.NewCommand(LsCmd),
"mount": lgc.NewCommand(MountCmd), "mount": lgc.NewCommand(MountCmd),
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论