-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmsg_server_submit_proof_test.go
1285 lines (1133 loc) · 41.9 KB
/
msg_server_submit_proof_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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package keeper_test
import (
"context"
"fmt"
"os"
"strings"
"testing"
"cosmossdk.io/depinject"
ring_secp256k1 "github.com/athanorlabs/go-dleq/secp256k1"
ringtypes "github.com/athanorlabs/go-dleq/types"
cosmoscrypto "github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
cosmostypes "github.com/cosmos/cosmos-sdk/types"
signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/noot/ring-go"
"github.com/pokt-network/smt"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pokt-network/poktroll/pkg/crypto"
"github.com/pokt-network/poktroll/pkg/crypto/rings"
"github.com/pokt-network/poktroll/pkg/polylog/polyzero"
"github.com/pokt-network/poktroll/pkg/relayer"
"github.com/pokt-network/poktroll/pkg/relayer/protocol"
"github.com/pokt-network/poktroll/pkg/relayer/session"
keepertest "github.com/pokt-network/poktroll/testutil/keeper"
"github.com/pokt-network/poktroll/x/proof/keeper"
"github.com/pokt-network/poktroll/x/proof/types"
servicetypes "github.com/pokt-network/poktroll/x/service/types"
sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper"
sessiontypes "github.com/pokt-network/poktroll/x/session/types"
sharedtypes "github.com/pokt-network/poktroll/x/shared/types"
)
// TODO_TECHDEBT(@bryanchriswhite): Simplify this file; https://github.com/pokt-network/poktroll/pull/417#pullrequestreview-1958582600
const (
supplierUid = "supplier"
)
var (
blockHeaderHash []byte
expectedMerkleProofPath []byte
)
func init() {
// The CometBFT header hash is 32 bytes: https://docs.cometbft.com/main/spec/core/data_structures
blockHeaderHash = make([]byte, 32)
expectedMerkleProofPath = keeper.GetPathForProof(blockHeaderHash, "TODO_BLOCKER_session_id_currently_unused")
}
func TestMsgServer_SubmitProof_Success(t *testing.T) {
opts := []keepertest.ProofKeepersOpt{
// Set block hash so we can have a deterministic expected on-chain proof requested by the protocol.
keepertest.WithBlockHash(blockHeaderHash),
// Set block height to 1 so there is a valid session on-chain.
keepertest.WithBlockHeight(1),
}
keepers, ctx := keepertest.NewProofModuleKeepers(t, opts...)
// Ensure the minimum relay difficulty bits is set to zero so this test
// doesn't need to mine for valid relays.
err := keepers.Keeper.SetParams(ctx, types.NewParams(0))
require.NoError(t, err)
// Construct a keyring to hold the keypairs for the accounts used in the test.
keyRing := keyring.NewInMemory(keepers.Codec)
// Create accounts in the account keeper with corresponding keys in the keyring for the application and supplier.
supplierAddr := createAccount(ctx, t, supplierUid, keyRing, keepers).GetAddress().String()
appAddr := createAccount(ctx, t, "app", keyRing, keepers).GetAddress().String()
service := &sharedtypes.Service{Id: testServiceId}
// Add a supplier and application pair that are expected to be in the session.
keepers.AddServiceActors(ctx, t, service, supplierAddr, appAddr)
// Get the session for the application/supplier pair which is expected
// to be claimed and for which a valid proof would be accepted.
// Given the setup above, it is guaranteed that the supplier created
// will be part of the session.
sessionHeader := keepers.GetSessionHeader(ctx, t, appAddr, service, 1)
// Construct a proof message server from the proof keeper.
srv := keeper.NewMsgServerImpl(*keepers.Keeper)
// Prepare a ring client to sign & validate relays.
ringClient, err := rings.NewRingClient(depinject.Supply(
polyzero.NewLogger(),
types.NewAppKeeperQueryClient(keepers.ApplicationKeeper),
types.NewAccountKeeperQueryClient(keepers.AccountKeeper),
))
require.NoError(t, err)
// Submit the corresponding proof.
numRelays := uint(5)
sessionTree := newFilledSessionTree(
ctx, t,
numRelays,
supplierUid, supplierAddr,
sessionHeader, sessionHeader, sessionHeader,
keyRing,
ringClient,
)
// Create a valid claim.
createClaimAndStoreBlockHash(
ctx, t,
supplierAddr,
appAddr,
service,
sessionTree,
sessionHeader,
srv,
keepers,
)
proofMsg := newTestProofMsg(t,
supplierAddr,
sessionHeader,
sessionTree,
expectedMerkleProofPath,
)
submitProofRes, err := srv.SubmitProof(ctx, proofMsg)
require.NoError(t, err)
require.NotNil(t, submitProofRes)
proofRes, err := keepers.AllProofs(ctx, &types.QueryAllProofsRequest{})
require.NoError(t, err)
proofs := proofRes.GetProofs()
require.Lenf(t, proofs, 1, "expected 1 proof, got %d", len(proofs))
require.Equal(t, proofMsg.SessionHeader.SessionId, proofs[0].GetSessionHeader().GetSessionId())
require.Equal(t, proofMsg.SupplierAddress, proofs[0].GetSupplierAddress())
require.Equal(t, proofMsg.SessionHeader.GetSessionEndBlockHeight(), proofs[0].GetSessionHeader().GetSessionEndBlockHeight())
}
func TestMsgServer_SubmitProof_Error(t *testing.T) {
opts := []keepertest.ProofKeepersOpt{
// Set block hash such that on-chain closest merkle proof validation
// uses the expected path.
keepertest.WithBlockHash(expectedMerkleProofPath),
// Set block height to 1 so there is a valid session on-chain.
keepertest.WithBlockHeight(1),
}
keepers, ctx := keepertest.NewProofModuleKeepers(t, opts...)
// Ensure the minimum relay difficulty bits is set to zero so that test cases
// don't need to mine for valid relays.
err := keepers.Keeper.SetParams(ctx, types.NewParams(0))
require.NoError(t, err)
// Construct a keyring to hold the keypairs for the accounts used in the test.
keyRing := keyring.NewInMemory(keepers.Codec)
// Create accounts in the account keeper with corresponding keys in the keyring
// for the applications and suppliers used in the tests.
supplierAddr := createAccount(ctx, t, supplierUid, keyRing, keepers).GetAddress().String()
wrongSupplierAddr := createAccount(ctx, t, "wrong_supplier", keyRing, keepers).GetAddress().String()
appAddr := createAccount(ctx, t, "app", keyRing, keepers).GetAddress().String()
wrongAppAddr := createAccount(ctx, t, "wrong_app", keyRing, keepers).GetAddress().String()
service := &sharedtypes.Service{Id: testServiceId}
wrongService := &sharedtypes.Service{Id: "wrong_svc"}
// Add a supplier and application pair that are expected to be in the session.
keepers.AddServiceActors(ctx, t, service, supplierAddr, appAddr)
// Add a supplier and application pair that are *not* expected to be in the session.
keepers.AddServiceActors(ctx, t, wrongService, wrongSupplierAddr, wrongAppAddr)
// Get the session for the application/supplier pair which is expected
// to be claimed and for which a valid proof would be accepted.
validSessionHeader := keepers.GetSessionHeader(ctx, t, appAddr, service, 1)
// Get the session for the application/supplier pair which is
// *not* expected to be claimed.
unclaimedSessionHeader := keepers.GetSessionHeader(ctx, t, wrongAppAddr, wrongService, 1)
// Construct a session header with session ID that doesn't match the expected session ID.
wrongSessionIdHeader := *validSessionHeader
wrongSessionIdHeader.SessionId = "wrong session ID"
// Construct a session header with a session start height that doesn't match
// the expected session start height.
wrongSessionStartHeightHeader := *validSessionHeader
wrongSessionStartHeightHeader.SessionStartBlockHeight = 2
// Construct a session header with a session end height that doesn't match
// the expected session end height.
wrongSessionEndHeightHeader := *validSessionHeader
wrongSessionEndHeightHeader.SessionEndBlockHeight = 3
// TODO_TECHDEBT: add a test case such that we can distinguish between early
// & late session end block heights.
// Construct a proof message server from the proof keeper.
srv := keeper.NewMsgServerImpl(*keepers.Keeper)
// Construct a ringClient to get the application's ring & verify the relay
// request signature.
ringClient, err := rings.NewRingClient(depinject.Supply(
polyzero.NewLogger(),
types.NewAppKeeperQueryClient(keepers.ApplicationKeeper),
types.NewAccountKeeperQueryClient(keepers.AccountKeeper),
))
require.NoError(t, err)
// Construct a valid session tree with 5 relays.
numRelays := uint(5)
validSessionTree := newFilledSessionTree(
ctx, t,
numRelays,
supplierUid, supplierAddr,
validSessionHeader, validSessionHeader, validSessionHeader,
keyRing,
ringClient,
)
// Create a valid claim for the expected session and update the block hash
// store for the corresponding session.
createClaimAndStoreBlockHash(
ctx, t,
supplierAddr,
appAddr,
service,
validSessionTree,
validSessionHeader,
srv,
keepers,
)
// Compute the difficulty in bits of the closest relay from the valid session tree.
validClosestRelayDifficultyBits := getClosestRelayDifficultyBits(t, validSessionTree, expectedMerkleProofPath)
// Copy `emptyBlockHash` to `wrongClosestProofPath` to with a missing byte
// so the closest proof is invalid (i.e. unmarshalable).
invalidClosestProofBytes := make([]byte, len(expectedMerkleProofPath)-1)
// Store the expected error returned during deserialization of the invalid
// closest Merkle proof bytes.
sparseMerkleClosestProof := &smt.SparseMerkleClosestProof{}
expectedInvalidProofUnmarshalErr := sparseMerkleClosestProof.Unmarshal(invalidClosestProofBytes)
// Construct a relay to be mangled such that it fails to deserialize in order
// to set the error expectation for the relevant test case.
mangledRelay := newEmptyRelay(validSessionHeader, validSessionHeader)
// Ensure valid relay request and response signatures.
signRelayRequest(ctx, t, mangledRelay, appAddr, keyRing, ringClient)
signRelayResponse(ctx, t, mangledRelay, supplierUid, supplierAddr, keyRing)
// Serialize the relay so that it can be mangled.
mangledRelayBz, err := mangledRelay.Marshal()
require.NoError(t, err)
// Mangle the serialized relay to cause an error during deserialization.
// Mangling could involve any byte randomly being swapped to any value
// so unmarshaling fails, but we are setting the first byte to 0 for simplicity.
mangledRelayBz[0] = 0x00
// Declare an invalid signature byte slice to construct expected relay request
// and response errors and use in corresponding test cases.
invalidSignatureBz := []byte("invalid signature bytes")
// Prepare an invalid proof of the correct size.
wrongClosestProofPath := make([]byte, len(expectedMerkleProofPath))
copy(wrongClosestProofPath, expectedMerkleProofPath)
copy(wrongClosestProofPath, "wrong closest proof path")
tests := []struct {
desc string
newProofMsg func(t *testing.T) *types.MsgSubmitProof
expectedErr error
}{
{
desc: "proof service ID cannot be empty",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Set proof session ID to empty string.
emptySessionIdHeader := *validSessionHeader
emptySessionIdHeader.SessionId = ""
// Construct new proof message.
return newTestProofMsg(t,
supplierAddr,
&emptySessionIdHeader,
validSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.InvalidArgument,
types.ErrProofInvalidSessionId.Wrapf(
"session ID does not match on-chain session ID; expected %q, got %q",
validSessionHeader.GetSessionId(),
"",
).Error(),
),
},
{
desc: "merkle proof cannot be empty",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct new proof message.
proof := newTestProofMsg(t,
supplierAddr,
validSessionHeader,
validSessionTree,
expectedMerkleProofPath,
)
// Set merkle proof to an empty byte slice.
proof.Proof = []byte{}
return proof
},
expectedErr: status.Error(
codes.InvalidArgument,
types.ErrProofInvalidProof.Wrap(
"proof cannot be empty",
).Error(),
),
},
{
desc: "proof session ID must match on-chain session ID",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct new proof message using the wrong session ID.
return newTestProofMsg(t,
supplierAddr,
&wrongSessionIdHeader,
validSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.InvalidArgument,
types.ErrProofInvalidSessionId.Wrapf(
"session ID does not match on-chain session ID; expected %q, got %q",
validSessionHeader.GetSessionId(),
wrongSessionIdHeader.GetSessionId(),
).Error(),
),
},
{
desc: "proof supplier must be in on-chain session",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct a proof message with a supplier that does not belong in the session.
return newTestProofMsg(t,
wrongSupplierAddr,
validSessionHeader,
validSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.InvalidArgument,
types.ErrProofNotFound.Wrapf(
"supplier address %q not found in session ID %q",
wrongSupplierAddr,
validSessionHeader.GetSessionId(),
).Error(),
),
},
{
desc: "merkle proof must be deserializable",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct new proof message.
proof := newTestProofMsg(t,
supplierAddr,
validSessionHeader,
validSessionTree,
expectedMerkleProofPath,
)
// Set merkle proof to an incorrect byte slice.
proof.Proof = invalidClosestProofBytes
return proof
},
expectedErr: status.Error(
codes.InvalidArgument,
types.ErrProofInvalidProof.Wrapf(
"failed to unmarshal closest merkle proof: %s",
expectedInvalidProofUnmarshalErr,
).Error(),
),
},
{
desc: "relay must be deserializable",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct a session tree to which we'll add 1 unserializable relay.
mangledRelaySessionTree := newEmptySessionTree(t, validSessionHeader)
// Add the mangled relay to the session tree.
err = mangledRelaySessionTree.Update([]byte{1}, mangledRelayBz, 1)
require.NoError(t, err)
// Get the Merkle root for the session tree in order to construct a claim.
mangledRelayMerkleRootBz, err := mangledRelaySessionTree.Flush()
require.NoError(t, err)
// Create a claim with a merkle root derived from a session tree
// with an unserializable relay.
claimMsg := newTestClaimMsg(t,
validSessionHeader.GetSessionId(),
supplierAddr,
appAddr,
service,
mangledRelayMerkleRootBz,
)
_, err = srv.CreateClaim(ctx, claimMsg)
require.NoError(t, err)
// Construct new proof message derived from a session tree
// with an unserializable relay.
return newTestProofMsg(t,
supplierAddr,
validSessionHeader,
mangledRelaySessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.InvalidArgument,
types.ErrProofInvalidRelay.Wrapf(
"failed to unmarshal relay: %s",
keepers.Codec.Unmarshal(mangledRelayBz, &servicetypes.Relay{}),
).Error(),
),
},
{
// TODO_TEST(community): expand: test case to cover each session header field.
desc: "relay request session header must match proof session header",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct a session tree with 1 relay with a session header containing
// a session ID that doesn't match the proof session ID.
numRelays := uint(1)
wrongRequestSessionIdSessionTree := newFilledSessionTree(
ctx, t,
numRelays,
supplierUid, supplierAddr,
validSessionHeader, &wrongSessionIdHeader, validSessionHeader,
keyRing,
ringClient,
)
// Get the Merkle root for the session tree in order to construct a claim.
wrongRequestSessionIdMerkleRootBz, err := wrongRequestSessionIdSessionTree.Flush()
require.NoError(t, err)
// Create a claim with a merkle root derived from a relay
// request containing the wrong session ID.
claimMsg := newTestClaimMsg(t,
validSessionHeader.GetSessionId(),
supplierAddr,
appAddr,
service,
wrongRequestSessionIdMerkleRootBz,
)
_, err = srv.CreateClaim(ctx, claimMsg)
require.NoError(t, err)
// Construct new proof message using the valid session header,
// *not* the one used in the session tree's relay request.
return newTestProofMsg(t,
supplierAddr,
validSessionHeader,
wrongRequestSessionIdSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidRelay.Wrapf(
"session headers session IDs mismatch; expected: %q, got: %q",
validSessionHeader.GetSessionId(),
wrongSessionIdHeader.GetSessionId(),
).Error(),
),
},
{
// TODO_TEST(community): expand: test case to cover each session header field.
desc: "relay response session header must match proof session header",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct a session tree with 1 relay with a session header containing
// a session ID that doesn't match the expected session ID.
numRelays := uint(1)
wrongResponseSessionIdSessionTree := newFilledSessionTree(
ctx, t,
numRelays,
supplierUid, supplierAddr,
validSessionHeader, validSessionHeader, &wrongSessionIdHeader,
keyRing,
ringClient,
)
// Get the Merkle root for the session tree in order to construct a claim.
wrongResponseSessionIdMerkleRootBz, err := wrongResponseSessionIdSessionTree.Flush()
require.NoError(t, err)
// Create a claim with a merkle root derived from a relay
// response containing the wrong session ID.
claimMsg := newTestClaimMsg(t,
validSessionHeader.GetSessionId(),
supplierAddr,
appAddr,
service,
wrongResponseSessionIdMerkleRootBz,
)
_, err = srv.CreateClaim(ctx, claimMsg)
require.NoError(t, err)
// Construct new proof message using the valid session header,
// *not* the one used in the session tree's relay response.
return newTestProofMsg(t,
supplierAddr,
validSessionHeader,
wrongResponseSessionIdSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidRelay.Wrapf(
"session headers session IDs mismatch; expected: %q, got: %q",
validSessionHeader.GetSessionId(),
wrongSessionIdHeader.GetSessionId(),
).Error(),
),
},
{
desc: "relay request signature must be valid",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Set the relay request signature to an invalid byte slice.
invalidRequestSignatureRelay := newEmptyRelay(validSessionHeader, validSessionHeader)
invalidRequestSignatureRelay.Req.Meta.Signature = invalidSignatureBz
// Ensure a valid relay response signature.
signRelayResponse(ctx, t, invalidRequestSignatureRelay, supplierUid, supplierAddr, keyRing)
invalidRequestSignatureRelayBz, err := invalidRequestSignatureRelay.Marshal()
require.NoError(t, err)
// Construct a session tree with 1 relay with a session header containing
// a session ID that doesn't match the expected session ID.
invalidRequestSignatureSessionTree := newEmptySessionTree(t, validSessionHeader)
// Add the relay to the session tree.
err = invalidRequestSignatureSessionTree.Update([]byte{1}, invalidRequestSignatureRelayBz, 1)
require.NoError(t, err)
// Get the Merkle root for the session tree in order to construct a claim.
invalidRequestSignatureMerkleRootBz, err := invalidRequestSignatureSessionTree.Flush()
require.NoError(t, err)
// Create a claim with a merkle root derived from a session tree
// with an invalid relay request signature.
claimMsg := newTestClaimMsg(t,
validSessionHeader.GetSessionId(),
supplierAddr,
appAddr,
service,
invalidRequestSignatureMerkleRootBz,
)
_, err = srv.CreateClaim(ctx, claimMsg)
require.NoError(t, err)
// Construct new proof message derived from a session tree
// with an invalid relay request signature.
return newTestProofMsg(t,
supplierAddr,
validSessionHeader,
invalidRequestSignatureSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidRelayRequest.Wrapf(
"error deserializing ring signature: %s",
new(ring.RingSig).Deserialize(ring_secp256k1.NewCurve(), invalidSignatureBz),
).Error(),
),
},
{
desc: "relay request signature is valid but signed by an incorrect application",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
t.Skip("TODO_TECHDEBT(@bryanchriswhite): Implement this")
return nil
},
},
{
desc: "relay response signature must be valid",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Set the relay response signature to an invalid byte slice.
relay := newEmptyRelay(validSessionHeader, validSessionHeader)
relay.Res.Meta.SupplierSignature = invalidSignatureBz
// Ensure a valid relay request signature
signRelayRequest(ctx, t, relay, appAddr, keyRing, ringClient)
relayBz, err := relay.Marshal()
require.NoError(t, err)
// Construct a session tree with 1 relay with a session header containing
// a session ID that doesn't match the expected session ID.
invalidResponseSignatureSessionTree := newEmptySessionTree(t, validSessionHeader)
// Add the relay to the session tree.
err = invalidResponseSignatureSessionTree.Update([]byte{1}, relayBz, 1)
require.NoError(t, err)
// Get the Merkle root for the session tree in order to construct a claim.
invalidResponseSignatureMerkleRootBz, err := invalidResponseSignatureSessionTree.Flush()
require.NoError(t, err)
// Create a claim with a merkle root derived from a session tree
// with an invalid relay response signature.
claimMsg := newTestClaimMsg(t,
validSessionHeader.GetSessionId(),
supplierAddr,
appAddr,
service,
invalidResponseSignatureMerkleRootBz,
)
_, err = srv.CreateClaim(ctx, claimMsg)
require.NoError(t, err)
// Construct new proof message derived from a session tree
// with an invalid relay response signature.
return newTestProofMsg(t,
supplierAddr,
validSessionHeader,
invalidResponseSignatureSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
servicetypes.ErrServiceInvalidRelayResponse.Wrap("invalid signature").Error(),
),
},
{
desc: "relay response signature is valid but signed by an incorrect supplier",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
t.Skip("TODO_TECHDEBT(@bryanchriswhite): Implement this")
return nil
},
},
{
desc: "the merkle proof path provided does not match the one expected/enforced by the protocol",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct a new valid session tree for this test case because once the
// closest proof has already been generated, the path cannot be changed.
numRelays := uint(5)
wrongPathSessionTree := newFilledSessionTree(
ctx, t,
numRelays,
supplierUid, supplierAddr,
validSessionHeader, validSessionHeader, validSessionHeader,
keyRing,
ringClient,
)
wrongPathMerkleRootBz, err := wrongPathSessionTree.Flush()
require.NoError(t, err)
// Create a valid claim with the expected merkle root.
claimMsg := newTestClaimMsg(t,
validSessionHeader.GetSessionId(),
supplierAddr,
appAddr,
service,
wrongPathMerkleRootBz,
)
_, err = srv.CreateClaim(ctx, claimMsg)
require.NoError(t, err)
// Construct new proof message derived from a session tree
// with an invalid relay response signature.
return newTestProofMsg(t, supplierAddr, validSessionHeader, wrongPathSessionTree, wrongClosestProofPath)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidProof.Wrapf(
"the proof for the path provided (%x) does not match one expected by the on-chain protocol (%x)",
wrongClosestProofPath,
blockHeaderHash,
).Error(),
),
},
{
desc: "relay difficulty must be greater than or equal to minimum (zero difficulty)",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Set the minimum relay difficulty to a non-zero value such that the relays
// constructed by the test helpers have a negligable chance of being valid.
err := keepers.Keeper.SetParams(ctx, types.Params{
MinRelayDifficultyBits: 10,
})
require.NoError(t, err)
// Reset the minimum relay difficulty to zero after this test case.
t.Cleanup(func() {
err := keepers.Keeper.SetParams(ctx, types.DefaultParams())
require.NoError(t, err)
})
// Construct a proof message with a session tree containing
// a relay of insufficient difficulty.
return newTestProofMsg(t,
supplierAddr,
validSessionHeader,
validSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidRelay.Wrapf(
"relay difficulty %d is less than the minimum difficulty %d",
validClosestRelayDifficultyBits,
10,
).Error(),
),
},
{
desc: "relay difficulty must be greater than or equal to minimum (non-zero difficulty)",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
t.Skip("TODO_TECHDEBT(@bryanchriswhite): Implement this")
return nil
},
},
{ // group: claim must exist for proof message
desc: "claim must exist for proof message",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Construct a new session tree corresponding to the unclaimed session.
numRelays := uint(5)
unclaimedSessionTree := newFilledSessionTree(
ctx, t,
numRelays,
"wrong_supplier", wrongSupplierAddr,
unclaimedSessionHeader, unclaimedSessionHeader, unclaimedSessionHeader,
keyRing,
ringClient,
)
// Discard session tree Merkle root because no claim is being created.
// Session tree must be closed (flushed) to compute closest Merkle Proof.
_, err = unclaimedSessionTree.Flush()
require.NoError(t, err)
// Construct new proof message using the supplier & session header
// from the session which is *not* expected to be claimed.
return newTestProofMsg(t,
wrongSupplierAddr,
unclaimedSessionHeader,
unclaimedSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofClaimNotFound.Wrapf(
"no claim found for session ID %q and supplier %q",
unclaimedSessionHeader.GetSessionId(),
wrongSupplierAddr,
).Error(),
),
},
{
desc: "claim and proof session start heights must match",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Advance the block height to shift the session start height.
sdkCtx := cosmostypes.UnwrapSDKContext(ctx)
ctx = sdkCtx.WithBlockHeight(3)
t.Cleanup(resetBlockHeightFn(&ctx))
// Construct new proof message.
return newTestProofMsg(t,
supplierAddr,
&wrongSessionStartHeightHeader,
validSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidRelay.Wrapf(
"session headers session start heights mismatch; expected: %d, got: %d",
2,
1,
).Error(),
),
},
{
desc: "claim and proof session end heights must match",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
// Advance the block height such that no hydration errors can occur when
// getting a session with start height less than the current block height.
setBlockHeight(&ctx, 3)
// Reset the block height to zero after this test case.
t.Cleanup(resetBlockHeightFn(&ctx))
// Construct new proof message.
return newTestProofMsg(t,
supplierAddr,
&wrongSessionEndHeightHeader,
validSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidRelay.Wrapf(
"session headers session end heights mismatch; expected: %d, got: %d",
3,
4,
).Error(),
),
},
{
desc: "Valid proof cannot validate claim with an incorrect root",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
numRelays := uint(10)
wrongMerkleRootSessionTree := newFilledSessionTree(
ctx, t,
numRelays,
supplierUid, supplierAddr,
validSessionHeader, validSessionHeader, validSessionHeader,
keyRing,
ringClient,
)
wrongMerkleRootBz, err := wrongMerkleRootSessionTree.Flush()
require.NoError(t, err)
// Create a claim with the incorrect Merkle root.
wrongMerkleRootClaimMsg := newTestClaimMsg(t,
validSessionHeader.GetSessionId(),
supplierAddr,
appAddr,
service,
wrongMerkleRootBz,
)
_, err = srv.CreateClaim(ctx, wrongMerkleRootClaimMsg)
require.NoError(t, err)
return newTestProofMsg(t,
supplierAddr,
validSessionHeader,
validSessionTree,
expectedMerkleProofPath,
)
},
expectedErr: status.Error(
codes.FailedPrecondition,
types.ErrProofInvalidProof.Wrap("invalid closest merkle proof").Error(),
),
},
{
desc: "claim and proof application addresses must match",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
t.Skip("this test case reduces to either the 'claim must exist for proof message' or 'proof session ID must match on-chain session ID cases")
return nil
},
},
{
desc: "claim and proof service IDs must match",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
t.Skip("this test case reduces to either the 'claim must exist for proof message' or 'proof session ID must match on-chain session ID cases")
return nil
},
},
{
desc: "claim and proof supplier addresses must match",
newProofMsg: func(t *testing.T) *types.MsgSubmitProof {
t.Skip("this test case reduces to either the 'claim must exist for proof message' or 'proof session ID must match on-chain session ID cases")
return nil
},
},
}
// Submit the corresponding proof.
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
proofMsg := test.newProofMsg(t)
submitProofRes, err := srv.SubmitProof(ctx, proofMsg)
require.ErrorContains(t, err, test.expectedErr.Error())
require.Nil(t, submitProofRes)
proofRes, err := keepers.AllProofs(ctx, &types.QueryAllProofsRequest{})
require.NoError(t, err)
// Expect zero proofs to have been persisted as all test cases are error cases.
proofs := proofRes.GetProofs()
require.Lenf(t, proofs, 0, "expected 0 proofs, got %d", len(proofs))
})
}
}
// newFilledSessionTree creates a new session tree with numRelays of relays
// filled out using the request and response headers provided where every
// relay is signed by the supplier and application respectively.
func newFilledSessionTree(
ctx context.Context, t *testing.T,
numRelays uint,
supplierKeyUid, supplierAddr string,
sessionTreeHeader, reqHeader, resHeader *sessiontypes.SessionHeader,
keyRing keyring.Keyring,
ringClient crypto.RingClient,
) relayer.SessionTree {
t.Helper()
// Initialize an empty session tree with the given session header.
sessionTree := newEmptySessionTree(t, sessionTreeHeader)
// Add numRelays of relays to the session tree.
fillSessionTree(
ctx, t,
sessionTree, numRelays,
supplierKeyUid, supplierAddr,
reqHeader, resHeader,
keyRing,
ringClient,
)
return sessionTree
}
// newEmptySessionTree creates a new empty session tree with for given session.
func newEmptySessionTree(
t *testing.T,
sessionTreeHeader *sessiontypes.SessionHeader,
) relayer.SessionTree {
t.Helper()
// Create a temporary session tree store directory for persistence.
testSessionTreeStoreDir, err := os.MkdirTemp("", "session_tree_store_dir")
require.NoError(t, err)
// Delete the temporary session tree store directory after the test completes.
t.Cleanup(func() {
_ = os.RemoveAll(testSessionTreeStoreDir)
})
// Construct a session tree to add relays to and generate a proof from.
sessionTree, err := session.NewSessionTree(
sessionTreeHeader,
testSessionTreeStoreDir,
func(*sessiontypes.SessionHeader) {},
)
require.NoError(t, err)
return sessionTree
}
// fillSessionTree fills the session tree with valid signed relays.
// A total of numRelays relays are added to the session tree with
// increasing weights (relay 1 has weight 1, relay 2 has weight 2, etc.).
func fillSessionTree(
ctx context.Context, t *testing.T,
sessionTree relayer.SessionTree,
numRelays uint,
supplierKeyUid, supplierAddr string,
reqHeader, resHeader *sessiontypes.SessionHeader,
keyRing keyring.Keyring,
ringClient crypto.RingClient,
) {
t.Helper()
for i := 0; i < int(numRelays); i++ {
relay := newSignedEmptyRelay(
ctx, t,
supplierKeyUid, supplierAddr,
reqHeader, resHeader,
keyRing,
ringClient,
)
relayBz, err := relay.Marshal()
require.NoError(t, err)
relayKey, err := relay.GetHash()
require.NoError(t, err)
relayWeight := uint64(i)
err = sessionTree.Update(relayKey[:], relayBz, relayWeight)
require.NoError(t, err)
}
}
// newTestProofMsg creates a new submit proof message that can be submitted
// to be validated and stored on-chain.
func newTestProofMsg(
t *testing.T,