Skip to content

Commit f08cd94

Browse files
authored
cmd/ethkey: fix formatting, review nits (#15807)
This commit: - Adds a --msgfile option to read the message to sign from a file instead of command line argument. - Adds a unit test for signing subcommands. - Removes some weird whitespace in the code.
1 parent 216e584 commit f08cd94

7 files changed

Lines changed: 231 additions & 95 deletions

File tree

‎cmd/ethkey/generate.go‎

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,23 @@
1+
// Copyright 2017 The go-ethereum Authors
2+
// This file is part of go-ethereum.
3+
//
4+
// go-ethereum is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// go-ethereum is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU General Public License
15+
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
16+
117
package main
218

319
import (
420
"crypto/ecdsa"
5-
"crypto/rand"
621
"fmt"
722
"io/ioutil"
823
"os"
@@ -26,16 +41,16 @@ var commandGenerate = cli.Command{
2641
ArgsUsage: "[ <keyfile> ]",
2742
Description: `
2843
Generate a new keyfile.
29-
If you want to use an existing private key to use in the keyfile, it can be
30-
specified by setting --privatekey with the location of the file containing the
31-
private key.`,
44+
45+
If you want to encrypt an existing private key, it can be specified by setting
46+
--privatekey with the location of the file containing the private key.
47+
`,
3248
Flags: []cli.Flag{
3349
passphraseFlag,
3450
jsonFlag,
3551
cli.StringFlag{
36-
Name: "privatekey",
37-
Usage: "the file from where to read the private key to " +
38-
"generate a keyfile for",
52+
Name: "privatekey",
53+
Usage: "file containing a raw private key to encrypt",
3954
},
4055
},
4156
Action: func(ctx *cli.Context) error {
@@ -51,32 +66,19 @@ private key.`,
5166
}
5267

5368
var privateKey *ecdsa.PrivateKey
54-
55-
// First check if a private key file is provided.
56-
privateKeyFile := ctx.String("privatekey")
57-
if privateKeyFile != "" {
58-
privateKeyBytes, err := ioutil.ReadFile(privateKeyFile)
69+
var err error
70+
if file := ctx.String("privatekey"); file != "" {
71+
// Load private key from file.
72+
privateKey, err = crypto.LoadECDSA(file)
5973
if err != nil {
60-
utils.Fatalf("Failed to read the private key file '%s': %v",
61-
privateKeyFile, err)
74+
utils.Fatalf("Can't load private key: %v", err)
6275
}
63-
64-
pk, err := crypto.HexToECDSA(string(privateKeyBytes))
65-
if err != nil {
66-
utils.Fatalf(
67-
"Could not construct ECDSA private key from file content: %v",
68-
err)
69-
}
70-
privateKey = pk
71-
}
72-
73-
// If not loaded, generate random.
74-
if privateKey == nil {
75-
pk, err := ecdsa.GenerateKey(crypto.S256(), rand.Reader)
76+
} else {
77+
// If not loaded, generate random.
78+
privateKey, err = crypto.GenerateKey()
7679
if err != nil {
7780
utils.Fatalf("Failed to generate random private key: %v", err)
7881
}
79-
privateKey = pk
8082
}
8183

8284
// Create the keyfile object with a random UUID.
@@ -89,8 +91,7 @@ private key.`,
8991

9092
// Encrypt key with passphrase.
9193
passphrase := getPassPhrase(ctx, true)
92-
keyjson, err := keystore.EncryptKey(key, passphrase,
93-
keystore.StandardScryptN, keystore.StandardScryptP)
94+
keyjson, err := keystore.EncryptKey(key, passphrase, keystore.StandardScryptN, keystore.StandardScryptP)
9495
if err != nil {
9596
utils.Fatalf("Error encrypting key: %v", err)
9697
}
@@ -110,7 +111,7 @@ private key.`,
110111
if ctx.Bool(jsonFlag.Name) {
111112
mustPrintJSON(out)
112113
} else {
113-
fmt.Println("Address: ", out.Address)
114+
fmt.Println("Address:", out.Address)
114115
}
115116
return nil
116117
},

‎cmd/ethkey/inspect.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ var commandInspect = cli.Command{
2323
ArgsUsage: "<keyfile>",
2424
Description: `
2525
Print various information about the keyfile.
26+
2627
Private key information can be printed by using the --private flag;
2728
make sure to use this feature with great caution!`,
2829
Flags: []cli.Flag{

‎cmd/ethkey/main.go‎

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,40 +28,37 @@ const (
2828
defaultKeyfileName = "keyfile.json"
2929
)
3030

31-
var (
32-
gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
31+
// Git SHA1 commit hash of the release (set via linker flags)
32+
var gitCommit = ""
3333

34-
app *cli.App // the main app instance
35-
)
34+
var app *cli.App
3635

37-
var ( // Commonly used command line flags.
36+
func init() {
37+
app = utils.NewApp(gitCommit, "an Ethereum key manager")
38+
app.Commands = []cli.Command{
39+
commandGenerate,
40+
commandInspect,
41+
commandSignMessage,
42+
commandVerifyMessage,
43+
}
44+
}
45+
46+
// Commonly used command line flags.
47+
var (
3848
passphraseFlag = cli.StringFlag{
3949
Name: "passwordfile",
4050
Usage: "the file that contains the passphrase for the keyfile",
4151
}
42-
4352
jsonFlag = cli.BoolFlag{
4453
Name: "json",
4554
Usage: "output JSON instead of human-readable format",
4655
}
47-
4856
messageFlag = cli.StringFlag{
4957
Name: "message",
5058
Usage: "the file that contains the message to sign/verify",
5159
}
5260
)
5361

54-
// Configure the app instance.
55-
func init() {
56-
app = utils.NewApp(gitCommit, "an Ethereum key manager")
57-
app.Commands = []cli.Command{
58-
commandGenerate,
59-
commandInspect,
60-
commandSignMessage,
61-
commandVerifyMessage,
62-
}
63-
}
64-
6562
func main() {
6663
if err := app.Run(os.Args); err != nil {
6764
fmt.Fprintln(os.Stderr, err)

‎cmd/ethkey/message.go‎

Lines changed: 54 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,25 @@
1+
// Copyright 2017 The go-ethereum Authors
2+
// This file is part of go-ethereum.
3+
//
4+
// go-ethereum is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// go-ethereum is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU General Public License
15+
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
16+
117
package main
218

319
import (
420
"encoding/hex"
521
"fmt"
622
"io/ioutil"
7-
"os"
8-
"strings"
923

1024
"github.com/ethereum/go-ethereum/accounts/keystore"
1125
"github.com/ethereum/go-ethereum/cmd/utils"
@@ -18,26 +32,33 @@ type outputSign struct {
1832
Signature string
1933
}
2034

35+
var msgfileFlag = cli.StringFlag{
36+
Name: "msgfile",
37+
Usage: "file containing the message to sign/verify",
38+
}
39+
2140
var commandSignMessage = cli.Command{
2241
Name: "signmessage",
2342
Usage: "sign a message",
24-
ArgsUsage: "<keyfile> <message/file>",
43+
ArgsUsage: "<keyfile> <message>",
2544
Description: `
2645
Sign the message with a keyfile.
27-
It is possible to refer to a file containing the message.`,
46+
47+
To sign a message contained in a file, use the --msgfile flag.
48+
`,
2849
Flags: []cli.Flag{
2950
passphraseFlag,
3051
jsonFlag,
52+
msgfileFlag,
3153
},
3254
Action: func(ctx *cli.Context) error {
33-
keyfilepath := ctx.Args().First()
34-
message := []byte(ctx.Args().Get(1))
55+
message := getMessage(ctx, 1)
3556

3657
// Load the keyfile.
58+
keyfilepath := ctx.Args().First()
3759
keyjson, err := ioutil.ReadFile(keyfilepath)
3860
if err != nil {
39-
utils.Fatalf("Failed to read the keyfile at '%s': %v",
40-
keyfilepath, err)
61+
utils.Fatalf("Failed to read the keyfile at '%s': %v", keyfilepath, err)
4162
}
4263

4364
// Decrypt key with passphrase.
@@ -47,29 +68,15 @@ It is possible to refer to a file containing the message.`,
4768
utils.Fatalf("Error decrypting key: %v", err)
4869
}
4970

50-
if len(message) == 0 {
51-
utils.Fatalf("A message must be provided")
52-
}
53-
// Read message if file.
54-
if _, err := os.Stat(string(message)); err == nil {
55-
message, err = ioutil.ReadFile(string(message))
56-
if err != nil {
57-
utils.Fatalf("Failed to read the message file: %v", err)
58-
}
59-
}
60-
6171
signature, err := crypto.Sign(signHash(message), key.PrivateKey)
6272
if err != nil {
6373
utils.Fatalf("Failed to sign message: %v", err)
6474
}
65-
66-
out := outputSign{
67-
Signature: hex.EncodeToString(signature),
68-
}
75+
out := outputSign{Signature: hex.EncodeToString(signature)}
6976
if ctx.Bool(jsonFlag.Name) {
7077
mustPrintJSON(out)
7178
} else {
72-
fmt.Println("Signature: ", out.Signature)
79+
fmt.Println("Signature:", out.Signature)
7380
}
7481
return nil
7582
},
@@ -84,53 +91,40 @@ type outputVerify struct {
8491
var commandVerifyMessage = cli.Command{
8592
Name: "verifymessage",
8693
Usage: "verify the signature of a signed message",
87-
ArgsUsage: "<address> <signature> <message/file>",
94+
ArgsUsage: "<address> <signature> <message>",
8895
Description: `
8996
Verify the signature of the message.
9097
It is possible to refer to a file containing the message.`,
9198
Flags: []cli.Flag{
9299
jsonFlag,
100+
msgfileFlag,
93101
},
94102
Action: func(ctx *cli.Context) error {
95103
addressStr := ctx.Args().First()
96104
signatureHex := ctx.Args().Get(1)
97-
message := []byte(ctx.Args().Get(2))
105+
message := getMessage(ctx, 2)
98106

99-
// Determine whether it is a keyfile, public key or address.
100107
if !common.IsHexAddress(addressStr) {
101108
utils.Fatalf("Invalid address: %s", addressStr)
102109
}
103110
address := common.HexToAddress(addressStr)
104-
105111
signature, err := hex.DecodeString(signatureHex)
106112
if err != nil {
107113
utils.Fatalf("Signature encoding is not hexadecimal: %v", err)
108114
}
109115

110-
if len(message) == 0 {
111-
utils.Fatalf("A message must be provided")
112-
}
113-
// Read message if file.
114-
if _, err := os.Stat(string(message)); err == nil {
115-
message, err = ioutil.ReadFile(string(message))
116-
if err != nil {
117-
utils.Fatalf("Failed to read the message file: %v", err)
118-
}
119-
}
120-
121116
recoveredPubkey, err := crypto.SigToPub(signHash(message), signature)
122117
if err != nil || recoveredPubkey == nil {
123118
utils.Fatalf("Signature verification failed: %v", err)
124119
}
125120
recoveredPubkeyBytes := crypto.FromECDSAPub(recoveredPubkey)
126121
recoveredAddress := crypto.PubkeyToAddress(*recoveredPubkey)
127-
128122
success := address == recoveredAddress
129123

130124
out := outputVerify{
131125
Success: success,
132126
RecoveredPublicKey: hex.EncodeToString(recoveredPubkeyBytes),
133-
RecoveredAddress: strings.ToLower(recoveredAddress.Hex()),
127+
RecoveredAddress: recoveredAddress.Hex(),
134128
}
135129
if ctx.Bool(jsonFlag.Name) {
136130
mustPrintJSON(out)
@@ -140,9 +134,26 @@ It is possible to refer to a file containing the message.`,
140134
} else {
141135
fmt.Println("Signature verification failed!")
142136
}
143-
fmt.Println("Recovered public key: ", out.RecoveredPublicKey)
144-
fmt.Println("Recovered address: ", out.RecoveredAddress)
137+
fmt.Println("Recovered public key:", out.RecoveredPublicKey)
138+
fmt.Println("Recovered address:", out.RecoveredAddress)
145139
}
146140
return nil
147141
},
148142
}
143+
144+
func getMessage(ctx *cli.Context, msgarg int) []byte {
145+
if file := ctx.String("msgfile"); file != "" {
146+
if len(ctx.Args()) > msgarg {
147+
utils.Fatalf("Can't use --msgfile and message argument at the same time.")
148+
}
149+
msg, err := ioutil.ReadFile(file)
150+
if err != nil {
151+
utils.Fatalf("Can't read message file: %v", err)
152+
}
153+
return msg
154+
} else if len(ctx.Args()) == msgarg+1 {
155+
return []byte(ctx.Args().Get(msgarg))
156+
}
157+
utils.Fatalf("Invalid number of arguments: want %d, got %d", msgarg+1, len(ctx.Args()))
158+
return nil
159+
}

0 commit comments

Comments
 (0)