"ipfs key list": add option to also list the hash of the key
License: MIT Signed-off-by: Kevin Atkinson <k@kevina.org>
Kevin Atkinson committed
Jan 10, 2017 at 19:13 UTC
4dbb084e8cbc8ac205ca36d046fe31cd9e280304
1 file changed
+55
-3
core/commands/keystore.go
+55
-3
@@ -1,11 +1,14 @@
1
package commands
2
3
import (
4
+ "bytes"
5
"crypto/rand"
6
+ "errors"
7
"fmt"
8
"io"
9
"sort"
10
"strings"
11
+ "text/tabwriter"
12
13
cmds "github.com/ipfs/go-ipfs/commands"
14
@@ -28,6 +31,10 @@ type KeyOutput struct {
31
Id string
32
}
33
34
+type KeyOutputList struct {
35
+ Keys []KeyOutput
36
+}
37
+
38
var KeyGenCmd = &cmds.Command{
39
Helptext: cmds.HelpText{
40
Tagline: "Create a new keypair",
@@ -135,6 +142,9 @@ var KeyListCmd = &cmds.Command{
142
Helptext: cmds.HelpText{
143
Tagline: "List all local keypairs",
144
},
145
+ Options: []cmds.Option{
146
+ cmds.BoolOption("show-ids", "l", "also show key ids"),
147
+ },
148
Run: func(req cmds.Request, res cmds.Response) {
149
n, err := req.InvocContext().GetNode()
150
if err != nil {
@@ -149,10 +159,52 @@ var KeyListCmd = &cmds.Command{
159
}
160
161
sort.Strings(keys)
152
- res.SetOutput(&stringList{keys})
162
+
163
+ list := make([]KeyOutput, 0, len(keys))
164
+
165
+ for _, key := range keys {
166
+ privKey, err := n.Repo.Keystore().Get(key)
167
+ if err != nil {
168
+ res.SetError(err, cmds.ErrNormal)
169
+ return
170
+ }
171
+
172
+ pubKey := privKey.GetPublic()
173
+
174
+ pid, err := peer.IDFromPublicKey(pubKey)
175
+ if err != nil {
176
+ res.SetError(err, cmds.ErrNormal)
177
+ return
178
+ }
179
+
180
+ list = append(list, KeyOutput{Name: key, Id: pid.Pretty()})
181
+ }
182
+
183
+ res.SetOutput(&KeyOutputList{list})
184
},
185
Marshalers: cmds.MarshalerMap{
155
- cmds.Text: stringListMarshaler,
186
+ cmds.Text: keyOutputListMarshaler,
187
},
157
- Type: stringList{},
188
+ Type: KeyOutputList{},
189
+}
190
+
191
+func keyOutputListMarshaler(res cmds.Response) (io.Reader, error) {
192
+ withId, _, _ := res.Request().Option("show-ids").Bool()
193
+
194
+ list, ok := res.Output().(*KeyOutputList)
195
+ if !ok {
196
+ return nil, errors.New("failed to cast []KeyOutput")
197
+ }
198
+
199
+ buf := new(bytes.Buffer)
200
+ w := tabwriter.NewWriter(buf, 1, 2, 1, ' ', 0)
201
+ for _, s := range list.Keys {
202
+ if withId {
203
+ fmt.Fprintf(w, "%s\t%s\t\n", s.Id, s.Name)
204
+ } else {
205
+ fmt.Fprintf(w, "%s\n", s.Name)
206
+ }
207
+ }
208
+ w.Flush()
209
+ return buf, nil
210
}