-
Notifications
You must be signed in to change notification settings - Fork 464
/
testing.go
363 lines (331 loc) · 9.91 KB
/
testing.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package internal
import (
"bytes"
"context"
"crypto/rand"
"fmt"
"testing"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/venus/pkg/constants"
"github.com/filecoin-project/venus/pkg/crypto"
)
// MockSigner implements the Signer interface
type MockSigner struct {
AddrKeyInfo map[address.Address]crypto.KeyInfo
Addresses []address.Address
PubKeys [][]byte
}
// NewMockSigner returns a new mock signer, capable of signing data with
// keys (addresses derived from) in keyinfo
func NewMockSigner(kis []crypto.KeyInfo) MockSigner {
var ms MockSigner
ms.AddrKeyInfo = make(map[address.Address]crypto.KeyInfo)
for _, k := range kis {
// extract public key
pub, err := k.PublicKey()
if err != nil {
panic(err)
}
var newAddr address.Address
if k.SigType == crypto.SigTypeSecp256k1 {
newAddr, err = address.NewSecp256k1Address(pub)
} else if k.SigType == crypto.SigTypeBLS {
newAddr, err = address.NewBLSAddress(pub)
}
if err != nil {
panic(err)
}
ms.Addresses = append(ms.Addresses, newAddr)
ms.AddrKeyInfo[newAddr] = k
ms.PubKeys = append(ms.PubKeys, pub)
}
return ms
}
// NewMockSignersAndKeyInfo is a convenience function to generate a mock
// signers with some keys.
func NewMockSignersAndKeyInfo(numSigners int) (MockSigner, []crypto.KeyInfo) {
ki := MustGenerateKeyInfo(numSigners, 42)
signer := NewMockSigner(ki)
return signer, ki
}
// MustGenerateMixedKeyInfo produces m bls keys and n secp keys.
// BLS and Secp will be interleaved. The keys will be valid, but not deterministic.
func MustGenerateMixedKeyInfo(m int, n int) []crypto.KeyInfo {
info := []crypto.KeyInfo{}
for m > 0 && n > 0 {
if m > 0 {
ki, err := crypto.NewBLSKeyFromSeed(rand.Reader)
if err != nil {
panic(err)
}
info = append(info, ki)
m--
}
if n > 0 {
ki, err := crypto.NewSecpKeyFromSeed(rand.Reader)
if err != nil {
panic(err)
}
info = append(info, ki)
n--
}
}
return info
}
// MustGenerateBLSKeyInfo produces n distinct BLS keyinfos.
func MustGenerateBLSKeyInfo(n int, seed byte) []crypto.KeyInfo {
token := bytes.Repeat([]byte{seed}, 512)
var keyinfos []crypto.KeyInfo
for i := 0; i < n; i++ {
token[0] = byte(i)
ki, err := crypto.NewBLSKeyFromSeed(bytes.NewReader(token))
if err != nil {
panic(err)
}
keyinfos = append(keyinfos, ki)
}
return keyinfos
}
// MustGenerateKeyInfo generates `n` distinct keyinfos using seed `seed`.
// The result is deterministic (for stable tests), don't use this for real keys!
func MustGenerateKeyInfo(n int, seed byte) []crypto.KeyInfo {
token := bytes.Repeat([]byte{seed}, 512)
var keyinfos []crypto.KeyInfo
for i := 0; i < n; i++ {
token[0] = byte(i)
ki, err := crypto.NewSecpKeyFromSeed(bytes.NewReader(token))
if err != nil {
panic(err)
}
keyinfos = append(keyinfos, ki)
}
return keyinfos
}
// SignBytes cryptographically signs `data` using the `addr`.
func (ms MockSigner) SignBytes(_ context.Context, data []byte, addr address.Address) (*crypto.Signature, error) {
ki, ok := ms.AddrKeyInfo[addr]
if !ok {
return nil, errors.New("unknown address")
}
var sig *crypto.Signature
err := ki.UsePrivateKey(func(privateKey []byte) error {
var err error
sig, err = crypto.Sign(data, privateKey, ki.SigType)
return err
})
return sig, err
}
// HasAddress returns whether the signer can sign with this address
func (ms MockSigner) HasAddress(_ context.Context, addr address.Address) (bool, error) {
return true, nil
}
// GetAddressForPubKey looks up a KeyInfo address associated with a given PublicKeyForSecpSecretKey for a MockSigner
func (ms MockSigner) GetAddressForPubKey(pk []byte) (address.Address, error) {
var addr address.Address
for _, ki := range ms.AddrKeyInfo {
testPk, err := ki.PublicKey()
if err != nil {
return address.Undef, err
}
if bytes.Equal(testPk, pk) {
addr, err := ki.Address()
if err != nil {
return addr, errors.New("could not fetch address")
}
return addr, nil
}
}
return addr, errors.New("public key not found in wallet")
}
// NewSignedMessageForTestGetter returns a closure that returns a SignedMessage unique to that invocation.
// The message is unique wrt the closure returned, not globally. You can use this function
// in tests instead of manually creating messages -- it both reduces duplication and gives us
// exactly one place to create valid messages for tests if messages require validation in the
// future.
// TODO support chosing from address
func NewSignedMessageForTestGetter(ms MockSigner) func(uint64) *SignedMessage {
i := 0
return func(nonce uint64) *SignedMessage {
s := fmt.Sprintf("smsg%d", i)
i++
newAddr, err := address.NewSecp256k1Address([]byte(s + "-to"))
if err != nil {
panic(err)
}
msg := NewMeteredMessage(
ms.Addresses[0], // from needs to be an address from the signer
newAddr,
nonce,
ZeroFIL,
0,
[]byte("params"),
ZeroFIL,
ZeroFIL,
0,
)
smsg, err := NewSignedMessage(context.TODO(), *msg, &ms)
if err != nil {
panic(err)
}
return smsg
}
}
// Type-related test helpers.
// CidFromString generates Cid from string input
func CidFromString(t *testing.T, input string) cid.Cid {
c, err := constants.DefaultCidBuilder.Sum([]byte(input))
require.NoError(t, err)
return c
}
// NewCidForTestGetter returns a closure that returns a Cid unique to that invocation.
// The Cid is unique wrt the closure returned, not globally. You can use this function
// in tests.
func NewCidForTestGetter() func() cid.Cid {
i := 31337
return func() cid.Cid {
obj, err := cbor.WrapObject([]int{i}, constants.DefaultHashFunction, -1)
if err != nil {
panic(err)
}
i++
return obj.Cid()
}
}
// NewMessageForTestGetter returns a closure that returns a message unique to that invocation.
// The message is unique wrt the closure returned, not globally. You can use this function
// in tests instead of manually creating messages -- it both reduces duplication and gives us
// exactly one place to create valid messages for tests if messages require validation in the
// future.
func NewMessageForTestGetter() func() *UnsignedMessage {
i := 0
return func() *UnsignedMessage {
s := fmt.Sprintf("msg%d", i)
i++
from, err := address.NewSecp256k1Address([]byte(s + "-from"))
if err != nil {
panic(err)
}
to, err := address.NewSecp256k1Address([]byte(s + "-to"))
if err != nil {
panic(err)
}
return NewUnsignedMessage(
from,
to,
0,
ZeroFIL,
abi.MethodNum(10000+i),
nil)
}
}
// NewMsgs returns n messages. The messages returned are unique to this invocation
// but are not unique globally (ie, a second call to NewMsgs will return the same
// set of messages).
func NewMsgs(n int) []*UnsignedMessage {
newMsg := NewMessageForTestGetter()
msgs := make([]*UnsignedMessage, n)
for i := 0; i < n; i++ {
msgs[i] = newMsg()
msgs[i].Nonce = uint64(i)
}
return msgs
}
// NewSignedMsgs returns n signed messages. The messages returned are unique to this invocation
// but are not unique globally (ie, a second call to NewSignedMsgs will return the same
// set of messages).
func NewSignedMsgs(n uint, ms MockSigner) []*SignedMessage {
var err error
newMsg := NewMessageForTestGetter()
smsgs := make([]*SignedMessage, n)
for i := uint(0); i < n; i++ {
msg := newMsg()
msg.From = ms.Addresses[0]
msg.Nonce = uint64(i)
msg.GasFeeCap = ZeroFIL
msg.GasPremium = ZeroFIL
msg.GasLimit = 0
smsgs[i], err = NewSignedMessage(context.TODO(), *msg, ms)
if err != nil {
panic(err)
}
}
return smsgs
}
// SignMsgs returns a slice of signed messages where the original messages
// are `msgs`, if signing one of the `msgs` fails an error is returned
func SignMsgs(ms MockSigner, msgs []*UnsignedMessage) ([]*SignedMessage, error) {
var smsgs []*SignedMessage
for _, m := range msgs {
s, err := NewSignedMessage(context.TODO(), *m, ms)
if err != nil {
return nil, err
}
smsgs = append(smsgs, s)
}
return smsgs, nil
}
// NewMsgsWithAddrs returns a slice of `n` messages who's `From` field's are pulled
// from `a`. This method should be used when the addresses returned are to be signed
// at a later point.
func NewMsgsWithAddrs(n int, a []address.Address) []*UnsignedMessage {
if n > len(a) {
panic("cannot create more messages than there are addresess for")
}
newMsg := NewMessageForTestGetter()
msgs := make([]*UnsignedMessage, n)
for i := 0; i < n; i++ {
msgs[i] = newMsg()
msgs[i].From = a[i]
}
return msgs
}
// HasCid allows two values with CIDs to be compared.
type HasCid interface {
Cid() cid.Cid
}
// AssertHaveSameCid asserts that two values have identical CIDs.
func AssertHaveSameCid(t *testing.T, m HasCid, n HasCid) {
if !m.Cid().Equals(n.Cid()) {
assert.Fail(t, "CIDs don't match", "not equal %v %v", m.Cid(), n.Cid())
}
}
// AssertCidsEqual asserts that two CIDS are identical.
func AssertCidsEqual(t *testing.T, m cid.Cid, n cid.Cid) {
if !m.Equals(n) {
assert.Fail(t, "CIDs don't match", "not equal %v %v", m, n)
}
}
func RequireIDAddress(t *testing.T, i int) address.Address {
a, err := address.NewIDAddress(uint64(i))
if err != nil {
t.Fatalf("failed to make address: %v", err)
}
return a
}
// NewForTestGetter returns a closure that returns an address unique to that invocation.
// The address is unique wrt the closure returned, not globally.
func NewForTestGetter() func() address.Address {
i := 0
return func() address.Address {
s := fmt.Sprintf("address%d", i)
i++
newAddr, err := address.NewSecp256k1Address([]byte(s))
if err != nil {
panic(err)
}
return newAddr
}
}
// RequireNewTipSet instantiates and returns a new tipset of the given blocks
// and requires that the setup validation succeed.
func RequireNewTipSet(t *testing.T, blks ...*BlockHeader) *TipSet {
ts, err := NewTipSet(blks...)
require.NoError(t, err)
return ts
}