Skip to content

Commit 807b97e

Browse files
fix(crypto/secp256k1): UnmarshalText (#4419)
1 parent 82df3ce commit 807b97e

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

utils/crypto/secp256k1/secp256k1.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -262,11 +262,19 @@ func (k *PrivateKey) UnmarshalJSON(b []byte) error {
262262
}
263263

264264
strNoQuotes := str[1:lastIndex]
265-
if !strings.HasPrefix(strNoQuotes, PrivateKeyPrefix) {
265+
return k.unmarshalText(strNoQuotes)
266+
}
267+
268+
func (k *PrivateKey) UnmarshalText(text []byte) error {
269+
return k.unmarshalText(string(text))
270+
}
271+
272+
func (k *PrivateKey) unmarshalText(text string) error {
273+
if !strings.HasPrefix(text, PrivateKeyPrefix) {
266274
return errMissingKeyPrefix
267275
}
268276

269-
strNoPrefix := strNoQuotes[len(PrivateKeyPrefix):]
277+
strNoPrefix := text[len(PrivateKeyPrefix):]
270278
keyBytes, err := cb58.Decode(strNoPrefix)
271279
if err != nil {
272280
return err
@@ -282,10 +290,6 @@ func (k *PrivateKey) UnmarshalJSON(b []byte) error {
282290
return nil
283291
}
284292

285-
func (k *PrivateKey) UnmarshalText(text []byte) error {
286-
return k.UnmarshalJSON(text)
287-
}
288-
289293
// raw sig has format [v || r || s] whereas the sig has format [r || s || v]
290294
func rawSigToSig(sig []byte) ([]byte, error) {
291295
if len(sig) != SignatureLen {

utils/crypto/secp256k1/secp256k1_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,20 @@ func TestPrivateKeySECP256K1RUnmarshalJSONError(t *testing.T) {
173173
}
174174
}
175175

176+
func TestPrivateKeySECP256K1RUnmarshalText(t *testing.T) {
177+
require := require.New(t)
178+
179+
key, err := NewPrivateKey()
180+
require.NoError(err)
181+
182+
keyText, err := key.MarshalText()
183+
require.NoError(err)
184+
185+
key2 := PrivateKey{}
186+
require.NoError(key2.UnmarshalText(keyText))
187+
require.Equal(key.PublicKey(), key2.PublicKey())
188+
}
189+
176190
func TestSigning(t *testing.T) {
177191
tests := []struct {
178192
msg []byte

0 commit comments

Comments
 (0)