Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto: improve error messages in LoadECDSA #20718

Merged
merged 12 commits into from
Apr 8, 2020
44 changes: 44 additions & 0 deletions cmd/geth/accountcmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,50 @@ Path of the secret key file: .*UTC--.+--[0-9a-f]{40}
`)
}

func hexadecimal(count int) string {
chars := "0123456789abcdef"
var sb strings.Builder
for i := 0; i < count; i++ {
c := string(chars[i%len(chars)])
sb.WriteString(c)
}
return sb.String()
}

func TestAccountImport(t *testing.T) {
dir := tmpdir(t)
keyfile := filepath.Join(dir, "key.prv")
key := hexadecimal(64)
if err := ioutil.WriteFile(keyfile, []byte(key), 0644); err != nil {
t.Error(err)
}
geth := runGeth(t, "account", "import", keyfile)
defer geth.ExpectExit()
geth.Expect(`
Your new account is locked with a password. Please give a password. Do not forget this password.
!! Unsupported terminal, password will be echoed.
Password: {{.InputLine "foobar"}}
Repeat password: {{.InputLine "foobar"}}
`)
geth.ExpectRegexp(`
Address: {[0-9a-f]{40}}
`)
}

func TestAccountImportTooShort(t *testing.T) {
dir := tmpdir(t)
keyfile := filepath.Join(dir, "key.prv")
key := hexadecimal(40)
if err := ioutil.WriteFile(keyfile, []byte(key), 0644); err != nil {
t.Error(err)
}
geth := runGeth(t, "account", "import", keyfile)
defer geth.ExpectExit()
geth.Expect(`
Fatal: Failed to load the private key: expected 64 hexa characters, got 40
`)
}

func TestAccountNewBadRepeat(t *testing.T) {
geth := runGeth(t, "account", "new", "--lightkdf")
defer geth.ExpectExit()
Expand Down
10 changes: 3 additions & 7 deletions crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@ import (
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"math/big"
"os"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
Expand Down Expand Up @@ -166,14 +164,12 @@ func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {

// LoadECDSA loads a secp256k1 private key from the given file.
func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
buf := make([]byte, 64)
fd, err := os.Open(file)
buf, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
defer fd.Close()
if _, err := io.ReadFull(fd, buf); err != nil {
return nil, err
if len(buf) != 64 {
return nil, fmt.Errorf("expected 64 hexa characters, got %v", len(buf))
}

key, err := hex.DecodeString(string(buf))
Expand Down