forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
secp256k1_test.go
326 lines (292 loc) · 8.18 KB
/
secp256k1_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package secp256k1_test
import (
"crypto/ecdsa"
"encoding/base64"
"encoding/hex"
"math/big"
"testing"
btcSecp256k1 "github.com/btcsuite/btcd/btcec/v2"
btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/cosmos/btcutil/base58"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto"
tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
)
type keyData struct {
priv string
pub string
addr string
}
var secpDataTable = []keyData{
{
priv: "a96e62ed3955e65be32703f12d87b6b5cf26039ecfa948dc5107a495418e5330",
pub: "02950e1cdfcb133d6024109fd489f734eeb4502418e538c28481f22bce276f248c",
addr: "1CKZ9Nx4zgds8tU7nJHotKSDr4a9bYJCa3",
},
}
func TestPubKeySecp256k1Address(t *testing.T) {
for _, d := range secpDataTable {
privB, _ := hex.DecodeString(d.priv)
pubB, _ := hex.DecodeString(d.pub)
addrBbz, _, _ := base58.CheckDecode(d.addr)
addrB := crypto.Address(addrBbz)
priv := secp256k1.PrivKey{Key: privB}
pubKey := priv.PubKey()
pubT, _ := pubKey.(*secp256k1.PubKey)
addr := pubKey.Address()
assert.Equal(t, pubT, &secp256k1.PubKey{Key: pubB}, "Expected pub keys to match")
assert.Equal(t, addr, addrB, "Expected addresses to match")
}
}
func TestSignAndValidateSecp256k1(t *testing.T) {
privKey := secp256k1.GenPrivKey()
pubKey := privKey.PubKey()
msg := crypto.CRandBytes(1000)
sig, err := privKey.Sign(msg)
require.Nil(t, err)
assert.True(t, pubKey.VerifySignature(msg, sig))
// ----
// Test cross packages verification
msgHash := crypto.Sha256(msg)
btcPrivKey, btcPubKey := btcSecp256k1.PrivKeyFromBytes(privKey.Key)
// This fails: malformed signature: no header magic
// btcSig, err := secp256k1.ParseSignature(sig, secp256k1.S256())
// require.NoError(t, err)
// assert.True(t, btcSig.Verify(msgHash, btcPubKey))
// So we do a hacky way:
r := new(big.Int)
s := new(big.Int)
r.SetBytes(sig[:32])
s.SetBytes(sig[32:])
ok := ecdsa.Verify(btcPubKey.ToECDSA(), msgHash, r, s)
require.True(t, ok)
sig2, err := btcecdsa.SignCompact(btcPrivKey, msgHash, false)
// Chop off compactSigRecoveryCode.
sig2 = sig2[1:]
require.NoError(t, err)
pubKey.VerifySignature(msg, sig2)
// ----
// Mutate the signature, just one bit.
sig[3] ^= byte(0x01)
assert.False(t, pubKey.VerifySignature(msg, sig))
}
// This test is intended to justify the removal of calls to the underlying library
// in creating the privkey.
func TestSecp256k1LoadPrivkeyAndSerializeIsIdentity(t *testing.T) {
numberOfTests := 256
for i := 0; i < numberOfTests; i++ {
// Seed the test case with some random bytes
privKeyBytes := [32]byte{}
copy(privKeyBytes[:], crypto.CRandBytes(32))
// This function creates a private and public key in the underlying libraries format.
// The private key is basically calling new(big.Int).SetBytes(pk), which removes leading zero bytes
priv, _ := btcSecp256k1.PrivKeyFromBytes(privKeyBytes[:])
// this takes the bytes returned by `(big int).Bytes()`, and if the length is less than 32 bytes,
// pads the bytes from the left with zero bytes. Therefore these two functions composed
// result in the identity function on privKeyBytes, hence the following equality check
// always returning true.
serializedBytes := priv.Serialize()
require.Equal(t, privKeyBytes[:], serializedBytes)
}
}
func TestGenPrivKeyFromSecret(t *testing.T) {
// curve oder N
N := btcSecp256k1.S256().N
tests := []struct {
name string
secret []byte
}{
{"empty secret", []byte{}},
{
"some long secret",
[]byte("We live in a society exquisitely dependent on science and technology, " +
"in which hardly anyone knows anything about science and technology."),
},
{"another seed used in cosmos tests #1", []byte{0}},
{"another seed used in cosmos tests #2", []byte("mySecret")},
{"another seed used in cosmos tests #3", []byte("")},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
gotPrivKey := secp256k1.GenPrivKeyFromSecret(tt.secret)
require.NotNil(t, gotPrivKey)
// interpret as a big.Int and make sure it is a valid field element:
fe := new(big.Int).SetBytes(gotPrivKey.Key[:])
require.True(t, fe.Cmp(N) < 0)
require.True(t, fe.Sign() > 0)
})
}
}
func TestPubKeyEquals(t *testing.T) {
secp256K1PubKey := secp256k1.GenPrivKey().PubKey().(*secp256k1.PubKey)
testCases := []struct {
msg string
pubKey cryptotypes.PubKey
other cryptotypes.PubKey
expectEq bool
}{
{
"different bytes",
secp256K1PubKey,
secp256k1.GenPrivKey().PubKey(),
false,
},
{
"equals",
secp256K1PubKey,
&secp256k1.PubKey{
Key: secp256K1PubKey.Key,
},
true,
},
{
"different types",
secp256K1PubKey,
ed25519.GenPrivKey().PubKey(),
false,
},
}
for _, tc := range testCases {
t.Run(tc.msg, func(t *testing.T) {
eq := tc.pubKey.Equals(tc.other)
require.Equal(t, eq, tc.expectEq)
})
}
}
func TestPrivKeyEquals(t *testing.T) {
secp256K1PrivKey := secp256k1.GenPrivKey()
testCases := []struct {
msg string
privKey cryptotypes.PrivKey
other cryptotypes.PrivKey
expectEq bool
}{
{
"different bytes",
secp256K1PrivKey,
secp256k1.GenPrivKey(),
false,
},
{
"equals",
secp256K1PrivKey,
&secp256k1.PrivKey{
Key: secp256K1PrivKey.Key,
},
true,
},
{
"different types",
secp256K1PrivKey,
ed25519.GenPrivKey(),
false,
},
}
for _, tc := range testCases {
t.Run(tc.msg, func(t *testing.T) {
eq := tc.privKey.Equals(tc.other)
require.Equal(t, eq, tc.expectEq)
})
}
}
func TestMarshalAmino(t *testing.T) {
aminoCdc := codec.NewLegacyAmino()
privKey := secp256k1.GenPrivKey()
pubKey := privKey.PubKey().(*secp256k1.PubKey)
testCases := []struct {
desc string
msg codec.AminoMarshaler
typ interface{}
expBinary []byte
expJSON string
}{
{
"secp256k1 private key",
privKey,
&secp256k1.PrivKey{},
append([]byte{32}, privKey.Bytes()...), // Length-prefixed.
"\"" + base64.StdEncoding.EncodeToString(privKey.Bytes()) + "\"",
},
{
"secp256k1 public key",
pubKey,
&secp256k1.PubKey{},
append([]byte{33}, pubKey.Bytes()...), // Length-prefixed.
"\"" + base64.StdEncoding.EncodeToString(pubKey.Bytes()) + "\"",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Do a round trip of encoding/decoding binary.
bz, err := aminoCdc.Marshal(tc.msg)
require.NoError(t, err)
require.Equal(t, tc.expBinary, bz)
err = aminoCdc.Unmarshal(bz, tc.typ)
require.NoError(t, err)
require.Equal(t, tc.msg, tc.typ)
// Do a round trip of encoding/decoding JSON.
bz, err = aminoCdc.MarshalJSON(tc.msg)
require.NoError(t, err)
require.Equal(t, tc.expJSON, string(bz))
err = aminoCdc.UnmarshalJSON(bz, tc.typ)
require.NoError(t, err)
require.Equal(t, tc.msg, tc.typ)
})
}
}
func TestMarshalAmino_BackwardsCompatibility(t *testing.T) {
aminoCdc := codec.NewLegacyAmino()
// Create Tendermint keys.
tmPrivKey := tmsecp256k1.GenPrivKey()
tmPubKey := tmPrivKey.PubKey()
// Create our own keys, with the same private key as Tendermint's.
privKey := &secp256k1.PrivKey{Key: []byte(tmPrivKey)}
pubKey := privKey.PubKey().(*secp256k1.PubKey)
testCases := []struct {
desc string
tmKey interface{}
ourKey interface{}
marshalFn func(o interface{}) ([]byte, error)
}{
{
"secp256k1 private key, binary",
tmPrivKey,
privKey,
aminoCdc.Marshal,
},
{
"secp256k1 private key, JSON",
tmPrivKey,
privKey,
aminoCdc.MarshalJSON,
},
{
"secp256k1 public key, binary",
tmPubKey,
pubKey,
aminoCdc.Marshal,
},
{
"secp256k1 public key, JSON",
tmPubKey,
pubKey,
aminoCdc.MarshalJSON,
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
// Make sure Amino encoding override is not breaking backwards compatibility.
bz1, err := tc.marshalFn(tc.tmKey)
require.NoError(t, err)
bz2, err := tc.marshalFn(tc.ourKey)
require.NoError(t, err)
require.Equal(t, bz1, bz2)
})
}
}