-
Notifications
You must be signed in to change notification settings - Fork 0
/
commonutils_test.go
471 lines (403 loc) · 13.7 KB
/
commonutils_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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package protoutil
import (
"bytes"
"errors"
"testing"
"github.com/davidkhala/protoutil/common/crypto"
"github.com/davidkhala/protoutil/fakes"
"github.com/hyperledger/fabric-protos-go-apiv2/common"
"github.com/hyperledger/fabric-protos-go-apiv2/peer"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
func TestNonceRandomness(t *testing.T) {
n1, err := CreateNonce()
if err != nil {
t.Fatal(err)
}
n2, err := CreateNonce()
if err != nil {
t.Fatal(err)
}
if bytes.Equal(n1, n2) {
t.Fatalf("Expected nonces to be different, got %x and %x", n1, n2)
}
}
func TestNonceLength(t *testing.T) {
n, err := CreateNonce()
if err != nil {
t.Fatal(err)
}
actual := len(n)
expected := crypto.NonceSize
if actual != expected {
t.Fatalf("Expected nonce to be of size %d, got %d instead", expected, actual)
}
}
func TestUnmarshalPayload(t *testing.T) {
var payload *common.Payload
good, _ := proto.Marshal(&common.Payload{
Data: []byte("payload"),
})
payload, err := UnmarshalPayload(good)
require.NoError(t, err, "Unexpected error unmarshalling payload")
require.NotNil(t, payload, "Payload should not be nil")
payload = UnmarshalPayloadOrPanic(good)
require.NotNil(t, payload, "Payload should not be nil")
bad := []byte("bad payload")
require.Panics(t, func() {
_ = UnmarshalPayloadOrPanic(bad)
}, "Expected panic unmarshalling malformed payload")
}
func TestUnmarshalSignatureHeader(t *testing.T) {
t.Run("invalid header", func(t *testing.T) {
sighdrBytes := []byte("invalid signature header")
_, err := UnmarshalSignatureHeader(sighdrBytes)
require.Error(t, err, "Expected unmarshalling error")
})
t.Run("valid empty header", func(t *testing.T) {
sighdr := &common.SignatureHeader{}
sighdrBytes := MarshalOrPanic(sighdr)
sighdr, err := UnmarshalSignatureHeader(sighdrBytes)
require.NoError(t, err, "Unexpected error unmarshalling signature header")
require.Nil(t, sighdr.Creator)
require.Nil(t, sighdr.Nonce)
})
t.Run("valid header", func(t *testing.T) {
sighdr := &common.SignatureHeader{
Creator: []byte("creator"),
Nonce: []byte("nonce"),
}
sighdrBytes := MarshalOrPanic(sighdr)
sighdr, err := UnmarshalSignatureHeader(sighdrBytes)
require.NoError(t, err, "Unexpected error unmarshalling signature header")
require.Equal(t, []byte("creator"), sighdr.Creator)
require.Equal(t, []byte("nonce"), sighdr.Nonce)
})
}
func TestUnmarshalSignatureHeaderOrPanic(t *testing.T) {
t.Run("panic due to invalid header", func(t *testing.T) {
sighdrBytes := []byte("invalid signature header")
require.Panics(t, func() {
UnmarshalSignatureHeaderOrPanic(sighdrBytes)
}, "Expected panic with invalid header")
})
t.Run("no panic as the header is valid", func(t *testing.T) {
sighdr := &common.SignatureHeader{}
sighdrBytes := MarshalOrPanic(sighdr)
sighdr = UnmarshalSignatureHeaderOrPanic(sighdrBytes)
require.Nil(t, sighdr.Creator)
require.Nil(t, sighdr.Nonce)
})
}
func TestUnmarshalEnvelope(t *testing.T) {
var env *common.Envelope
good, _ := proto.Marshal(&common.Envelope{})
env, err := UnmarshalEnvelope(good)
require.NoError(t, err, "Unexpected error unmarshalling envelope")
require.NotNil(t, env, "Envelope should not be nil")
env = UnmarshalEnvelopeOrPanic(good)
require.NotNil(t, env, "Envelope should not be nil")
bad := []byte("bad envelope")
require.Panics(t, func() {
_ = UnmarshalEnvelopeOrPanic(bad)
}, "Expected panic unmarshalling malformed envelope")
}
func TestUnmarshalBlock(t *testing.T) {
var env *common.Block
good, _ := proto.Marshal(&common.Block{})
env, err := UnmarshalBlock(good)
require.NoError(t, err, "Unexpected error unmarshalling block")
require.NotNil(t, env, "Block should not be nil")
env = UnmarshalBlockOrPanic(good)
require.NotNil(t, env, "Block should not be nil")
bad := []byte("bad block")
require.Panics(t, func() {
_ = UnmarshalBlockOrPanic(bad)
}, "Expected panic unmarshalling malformed block")
}
func TestUnmarshalEnvelopeOfType(t *testing.T) {
env := &common.Envelope{}
env.Payload = []byte("bad payload")
_, err := UnmarshalEnvelopeOfType(env, common.HeaderType_CONFIG, nil)
require.Error(t, err, "Expected error unmarshalling malformed envelope")
payload, _ := proto.Marshal(&common.Payload{
Header: nil,
})
env.Payload = payload
_, err = UnmarshalEnvelopeOfType(env, common.HeaderType_CONFIG, nil)
require.Error(t, err, "Expected error with missing payload header")
payload, _ = proto.Marshal(&common.Payload{
Header: &common.Header{
ChannelHeader: []byte("bad header"),
},
})
env.Payload = payload
_, err = UnmarshalEnvelopeOfType(env, common.HeaderType_CONFIG, nil)
require.Error(t, err, "Expected error for malformed channel header")
chdr, _ := proto.Marshal(&common.ChannelHeader{
Type: int32(common.HeaderType_CHAINCODE_PACKAGE),
})
payload, _ = proto.Marshal(&common.Payload{
Header: &common.Header{
ChannelHeader: chdr,
},
})
env.Payload = payload
_, err = UnmarshalEnvelopeOfType(env, common.HeaderType_CONFIG, nil)
require.Error(t, err, "Expected error for wrong channel header type")
chdr, _ = proto.Marshal(&common.ChannelHeader{
Type: int32(common.HeaderType_CONFIG),
})
payload, _ = proto.Marshal(&common.Payload{
Header: &common.Header{
ChannelHeader: chdr,
},
Data: []byte("bad data"),
})
env.Payload = payload
_, err = UnmarshalEnvelopeOfType(env, common.HeaderType_CONFIG, &common.ConfigEnvelope{})
require.Error(t, err, "Expected error for malformed payload data")
chdr, _ = proto.Marshal(&common.ChannelHeader{
Type: int32(common.HeaderType_CONFIG),
})
configEnv, _ := proto.Marshal(&common.ConfigEnvelope{})
payload, _ = proto.Marshal(&common.Payload{
Header: &common.Header{
ChannelHeader: chdr,
},
Data: configEnv,
})
env.Payload = payload
_, err = UnmarshalEnvelopeOfType(env, common.HeaderType_CONFIG, &common.ConfigEnvelope{})
require.NoError(t, err, "Unexpected error unmarshalling envelope")
}
func TestExtractEnvelopeNilData(t *testing.T) {
block := &common.Block{}
_, err := ExtractEnvelope(block, 0)
require.Error(t, err, "Nil data")
}
func TestExtractEnvelopeWrongIndex(t *testing.T) {
block := testBlock()
if _, err := ExtractEnvelope(block, len(block.GetData().Data)); err == nil {
t.Fatal("Expected envelope extraction to fail (wrong index)")
}
}
func TestExtractEnvelopeWrongIndexOrPanic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Fatal("Expected envelope extraction to panic (wrong index)")
}
}()
block := testBlock()
ExtractEnvelopeOrPanic(block, len(block.GetData().Data))
}
func TestExtractEnvelope(t *testing.T) {
if envelope, err := ExtractEnvelope(testBlock(), 0); err != nil {
t.Fatalf("Expected envelop extraction to succeed: %s", err)
} else if !proto.Equal(envelope, testEnvelope()) {
t.Fatal("Expected extracted envelope to match test envelope")
}
}
func TestExtractEnvelopeOrPanic(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatal("Expected envelope extraction to succeed")
}
}()
if !proto.Equal(ExtractEnvelopeOrPanic(testBlock(), 0), testEnvelope()) {
t.Fatal("Expected extracted envelope to match test envelope")
}
}
func TestExtractPayload(t *testing.T) {
if payload, err := UnmarshalPayload(testEnvelope().Payload); err != nil {
t.Fatalf("Expected payload extraction to succeed: %s", err)
} else if !proto.Equal(payload, testPayload()) {
t.Fatal("Expected extracted payload to match test payload")
}
}
func TestExtractPayloadOrPanic(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatal("Expected payload extraction to succeed")
}
}()
if !proto.Equal(UnmarshalPayloadOrPanic(testEnvelope().Payload), testPayload()) {
t.Fatal("Expected extracted payload to match test payload")
}
}
func TestUnmarshalChaincodeID(t *testing.T) {
ccname := "mychaincode"
ccversion := "myversion"
ccidbytes, _ := proto.Marshal(&peer.ChaincodeID{
Name: ccname,
Version: ccversion,
})
ccid, err := UnmarshalChaincodeID(ccidbytes)
require.NoError(t, err)
require.Equal(t, ccname, ccid.Name, "Expected ccid names to match")
require.Equal(t, ccversion, ccid.Version, "Expected ccid versions to match")
_, err = UnmarshalChaincodeID([]byte("bad chaincodeID"))
require.Error(t, err, "Expected error marshaling malformed chaincode ID")
}
func TestNewSignatureHeaderOrPanic(t *testing.T) {
var sigHeader *common.SignatureHeader
id := &fakes.SignerSerializer{}
id.SerializeReturnsOnCall(0, []byte("serialized"), nil)
id.SerializeReturnsOnCall(1, nil, errors.New("serialize failed"))
sigHeader = NewSignatureHeaderOrPanic(id)
require.NotNil(t, sigHeader, "Signature header should not be nil")
require.Panics(t, func() {
_ = NewSignatureHeaderOrPanic(nil)
}, "Expected panic with nil signer")
require.Panics(t, func() {
_ = NewSignatureHeaderOrPanic(id)
}, "Expected panic with signature header error")
}
func TestSignOrPanic(t *testing.T) {
msg := []byte("sign me")
signer := &fakes.SignerSerializer{}
signer.SignReturnsOnCall(0, msg, nil)
signer.SignReturnsOnCall(1, nil, errors.New("bad signature"))
sig := SignOrPanic(signer, msg)
// mock signer returns message to be signed
require.Equal(t, msg, sig, "Signature does not match expected value")
require.Panics(t, func() {
_ = SignOrPanic(nil, []byte("sign me"))
}, "Expected panic with nil signer")
require.Panics(t, func() {
_ = SignOrPanic(signer, []byte("sign me"))
}, "Expected panic with sign error")
}
// Helper functions
func testPayload() *common.Payload {
return &common.Payload{
Header: MakePayloadHeader(
MakeChannelHeader(common.HeaderType_MESSAGE, int32(1), "test", 0),
MakeSignatureHeader([]byte("creator"), []byte("nonce"))),
Data: []byte("test"),
}
}
func testEnvelope() *common.Envelope {
// No need to set the signature
return &common.Envelope{Payload: MarshalOrPanic(testPayload())}
}
func testBlock() *common.Block {
// No need to set the block's Header, or Metadata
return &common.Block{
Data: &common.BlockData{
Data: [][]byte{MarshalOrPanic(testEnvelope())},
},
}
}
func TestChannelHeader(t *testing.T) {
makeEnvelope := func(payload *common.Payload) *common.Envelope {
return &common.Envelope{
Payload: MarshalOrPanic(payload),
}
}
_, err := ChannelHeader(makeEnvelope(&common.Payload{
Header: &common.Header{
ChannelHeader: MarshalOrPanic(&common.ChannelHeader{
ChannelId: "foo",
}),
},
}))
require.NoError(t, err, "Channel header was present")
_, err = ChannelHeader(makeEnvelope(&common.Payload{
Header: &common.Header{},
}))
require.Error(t, err, "ChannelHeader was missing")
_, err = ChannelHeader(makeEnvelope(&common.Payload{}))
require.Error(t, err, "Header was missing")
_, err = ChannelHeader(&common.Envelope{})
require.Error(t, err, "Payload was missing")
}
func TestIsConfigBlock(t *testing.T) {
newBlock := func(env *common.Envelope) *common.Block {
return &common.Block{
Data: &common.BlockData{
Data: [][]byte{MarshalOrPanic(env)},
},
}
}
newConfigEnv := func(envType int32) *common.Envelope {
return &common.Envelope{
Payload: MarshalOrPanic(&common.Payload{
Header: &common.Header{
ChannelHeader: MarshalOrPanic(&common.ChannelHeader{
Type: envType,
ChannelId: "test-chain",
}),
},
Data: []byte("test bytes"),
}), // common.Payload
} // LastUpdate
}
// scenario 1: CONFIG envelope
envType := int32(common.HeaderType_CONFIG)
env := newConfigEnv(envType)
block := newBlock(env)
result := IsConfigBlock(block)
require.True(t, result, "IsConfigBlock returns true for blocks with CONFIG envelope")
// scenario 2: ORDERER_TRANSACTION envelope
envType = int32(common.HeaderType_ORDERER_TRANSACTION)
env = newConfigEnv(envType)
block = newBlock(env)
result = IsConfigBlock(block)
require.False(t, result, "IsConfigBlock returns false for blocks with ORDERER_TRANSACTION envelope since it is no longer supported")
// scenario 3: MESSAGE envelope
envType = int32(common.HeaderType_MESSAGE)
env = newConfigEnv(envType)
block = newBlock(env)
result = IsConfigBlock(block)
require.False(t, result, "IsConfigBlock returns false for blocks with MESSAGE envelope")
// scenario 4: Data with more than one tx
result = IsConfigBlock(&common.Block{
Header: nil,
Data: &common.BlockData{Data: [][]byte{{1, 2, 3, 4}, {1, 2, 3, 4}}},
Metadata: nil,
})
require.False(t, result, "IsConfigBlock returns false for blocks with more than one transaction")
// scenario 5: nil data
result = IsConfigBlock(&common.Block{
Header: nil,
Data: nil,
Metadata: nil,
})
require.False(t, result, "IsConfigBlock returns false for blocks with no data")
}
func TestEnvelopeToConfigUpdate(t *testing.T) {
makeEnv := func(data []byte) *common.Envelope {
return &common.Envelope{
Payload: MarshalOrPanic(&common.Payload{
Header: &common.Header{
ChannelHeader: MarshalOrPanic(&common.ChannelHeader{
Type: int32(common.HeaderType_CONFIG_UPDATE),
ChannelId: "test-chain",
}),
},
Data: data,
}), // common.Payload
} // LastUpdate
}
// scenario 1: for valid envelopes
configUpdateEnv := &common.ConfigUpdateEnvelope{}
env := makeEnv(MarshalOrPanic(configUpdateEnv))
result, err := EnvelopeToConfigUpdate(env)
require.NoError(t, err, "EnvelopeToConfigUpdate runs without error for valid CONFIG_UPDATE envelope")
require.Equal(t, configUpdateEnv, result, "Correct configUpdateEnvelope returned")
// scenario 2: for invalid envelopes
env = makeEnv([]byte("test bytes"))
_, err = EnvelopeToConfigUpdate(env)
require.Error(t, err, "EnvelopeToConfigUpdate fails with error for invalid CONFIG_UPDATE envelope")
}
func TestGetRandomNonce(t *testing.T) {
key1, err := getRandomNonce()
require.NoErrorf(t, err, "error getting random bytes")
require.Len(t, key1, crypto.NonceSize)
}