-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathhandler.js
More file actions
2284 lines (1784 loc) · 99.7 KB
/
handler.js
File metadata and controls
2284 lines (1784 loc) · 99.7 KB
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
/*
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
*/
/* global */
/* eslint-disable no-useless-escape */
'use strict';
const sinon = require('sinon');
const chai = require('chai');
chai.use(require('chai-as-promised'));
const expect = chai.expect;
const rewire = require('rewire');
let Handler = rewire('../../../fabric-shim/lib/handler.js');
const Stub = require('../../../fabric-shim/lib/stub.js');
const MsgQueueHandler = Handler.__get__('MsgQueueHandler');
const QMsg = Handler.__get__('QMsg');
const {peer} = require('@hyperledger/fabric-protos');
const grpc = require('@grpc/grpc-js');
const fs = require('fs');
const path = require('path');
const {ChaincodeEvent} = require('@hyperledger/fabric-protos/lib/peer');
const sandbox = sinon.createSandbox();
const mockChaincodeImpl = {
Init: function() {},
Invoke: function() {}
};
function mapToChaincodeMessage(msg) {
const msgPb = new peer.ChaincodeMessage();
msgPb.setType(msg.type);
msgPb.setPayload(msg.payload);
msgPb.setTxid(msg.txid);
msgPb.setChannelId(msg.channel_id);
msgPb.setChaincodeEvent(msg.chaincode_event);
return msgPb;
}
function mapFromChaincodeMessage(msgPb) {
return {
type: msgPb.getType(),
payload: Buffer.from(msgPb.getPayload_asU8()),
txid: msgPb.getTxid(),
channel_id: msgPb.getChannelId(),
proposal: msgPb.getProposal(),
chaincode_event: msgPb.getChaincodeEvent()
};
}
const ca = fs.readFileSync(path.join(__dirname, 'test-ca.pem'), 'utf8');
const privatekey = fs.readFileSync(path.join(__dirname, 'test-key.base64'), 'utf8');
const cert = fs.readFileSync(path.join(__dirname, 'test-cert.base64'), 'utf8');
const mockOpts = {
pem: ca,
key: privatekey,
cert: cert
};
const mockPeerAddress = {
base: 'localhost:7051',
unsecure: 'grpc://localhost:7051',
secure: 'grpcs://localhost:7051'
};
describe('Handler', () => {
describe('QMsg', () => {
let resolve;
let reject;
let qMsg;
const msg = {
getChannelId: () => 'theChannelID',
getTxid: () => 'aTx'
};
beforeEach(() => {
resolve = sinon.stub();
reject = sinon.stub();
qMsg = new QMsg(msg, 'some method', resolve, reject);
});
it ('should set its variables with values passed in the constructor', () => {
expect(qMsg.msg).to.deep.equal(msg);
expect(qMsg.method).to.deep.equal('some method');
expect(qMsg.resolve).to.deep.equal(resolve);
expect(qMsg.reject).to.deep.equal(reject);
});
describe('getMsg', () => {
it ('should return the value of msg', () => {
expect(qMsg.getMsg()).to.deep.equal(msg);
});
});
describe('getMsgTxContextId', () => {
it ('should return the value of msg.channel_id concatenated with msg.txid', () => {
expect(qMsg.getMsgTxContextId()).to.deep.equal(msg.getChannelId() + msg.getTxid());
});
});
describe('getMethod', () => {
it ('should return the value of method', () => {
expect(qMsg.getMethod()).to.deep.equal('some method');
});
});
describe('success', () => {
it ('should call the resolve function', () => {
qMsg.success('response');
expect(resolve.calledOnce).to.be.true;
expect(resolve.firstCall.args).to.deep.equal(['response']);
});
});
describe('fail', () => {
it ('should call the reject function', () => {
qMsg.fail('err');
expect(reject.calledOnce).to.be.true;
expect(reject.firstCall.args).to.deep.equal(['err']);
});
});
});
describe('MsgQueueHandler', () => {
const txContextId = 'theChannelIDaTX';
let mockHandler;
let qHandler;
beforeEach(() => {
mockHandler = {_stream: {write: sinon.stub()}};
qHandler = new MsgQueueHandler(mockHandler);
});
it ('should setup its variables on construction', () => {
expect(qHandler.handler).to.deep.equal(mockHandler);
expect(qHandler.stream).to.deep.equal(mockHandler._stream);
expect(qHandler.txQueues).to.deep.equal({});
});
describe('queueMsg', () => {
const qMsg = {
getMsgTxContextId: () => {
return txContextId;
}
};
let mockSendMsg;
beforeEach(() => {
mockSendMsg = sinon.stub(qHandler, '_sendMsg');
});
it ('should add message to the queue and call sendMsg and handle when txContentId not in txQueues', () => {
qHandler.queueMsg(qMsg);
expect(mockSendMsg.calledOnce).to.be.true;
expect(mockSendMsg.firstCall.args).to.deep.equal([txContextId]);
expect(qHandler.txQueues[txContextId]).to.deep.equal([qMsg]);
});
it ('should add message to the queue and not call call sendMsg when txContentId in txQueues and is empty array', () => {
qHandler.txQueues[txContextId] = [];
qHandler.queueMsg(qMsg);
expect(mockSendMsg.calledOnce).to.be.true;
expect(mockSendMsg.firstCall.args).to.deep.equal([txContextId]);
expect(qHandler.txQueues[txContextId]).to.deep.equal([qMsg]);
});
it ('should add message to the queue and not call call sendMsg when txContentId in txQueues and already has value in array', () => {
qHandler.txQueues[txContextId] = ['some qMsg'];
qHandler.queueMsg(qMsg);
expect(mockSendMsg.notCalled).to.be.true;
expect(qHandler.txQueues[txContextId]).to.deep.equal(['some qMsg', qMsg]);
});
});
describe('handleMsgResponse', () => {
const saveParseResponse = Handler.__get__('parseResponse');
const response = {
channel_id: 'theChannelID',
txid: 'aTx'
};
let qMsg;
let mockGetCurrMsg;
let mockRemoveCurrentAndSendNextMsg;
beforeEach(() => {
qMsg = {
success: sinon.spy(),
fail: sinon.spy(),
getMethod: () => {
return 'some method';
}
};
mockGetCurrMsg = sinon.stub(qHandler, '_getCurrentMsg').returns(qMsg);
mockRemoveCurrentAndSendNextMsg = sinon.stub(qHandler, '_removeCurrentAndSendNextMsg');
});
afterEach(() => {
Handler.__set__('parseResponse', saveParseResponse);
mockGetCurrMsg.restore();
mockRemoveCurrentAndSendNextMsg.restore();
});
it ('should do nothing if qMsg does not exist for txContextId', () => {
const mockParseResponse = sinon.stub().returns('parsed response');
Handler.__set__('parseResponse', mockParseResponse);
mockGetCurrMsg.restore();
mockGetCurrMsg = sinon.stub(qHandler, '_getCurrentMsg').returns(null);
qHandler.handleMsgResponse(response);
expect(mockGetCurrMsg.calledOnce).to.be.true;
expect(mockGetCurrMsg.firstCall.args).to.deep.equal([response.channel_id + response.txid]);
expect(mockParseResponse.notCalled).to.be.true;
expect(qMsg.success.notCalled).to.be.true;
expect(qMsg.fail.notCalled).to.be.true;
expect(mockRemoveCurrentAndSendNextMsg.notCalled).to.be.true;
});
it ('should call qMsg success when parseResponse does not throw an error _removeCurrentAndSendNextMsg', () => {
const mockParseResponse = sinon.stub().returns('parsed response');
Handler.__set__('parseResponse', mockParseResponse);
qHandler.handleMsgResponse(response);
expect(mockGetCurrMsg.calledOnce).to.be.true;
expect(mockGetCurrMsg.firstCall.args).to.deep.equal([response.channel_id + response.txid]);
expect(mockParseResponse.calledOnce).to.be.true;
expect(mockParseResponse.firstCall.args).to.deep.equal([mockHandler, response, 'some method']);
expect(qMsg.success.calledOnce).to.be.true;
expect(qMsg.success.firstCall.args).to.deep.equal(['parsed response']);
expect(qMsg.fail.notCalled).to.be.true;
expect(mockRemoveCurrentAndSendNextMsg.calledOnce).to.be.true;
expect(mockRemoveCurrentAndSendNextMsg.firstCall.args).to.deep.equal([response.channel_id + response.txid]);
});
it ('should call qMsg fail when parseResponse does throw an error _removeCurrentAndSendNextMsg', () => {
const err = new Error('parse error');
const mockParseResponse = sinon.stub().throws(err);
Handler.__set__('parseResponse', mockParseResponse);
qHandler.handleMsgResponse(response);
expect(mockGetCurrMsg.calledOnce).to.be.true;
expect(mockGetCurrMsg.firstCall.args).to.deep.equal([response.channel_id + response.txid]);
expect(mockParseResponse.calledOnce).to.be.true;
expect(mockParseResponse.firstCall.args).to.deep.equal([mockHandler, response, 'some method']);
expect(qMsg.success.notCalled).to.be.true;
expect(qMsg.fail.calledOnce).to.be.true;
expect(qMsg.fail.firstCall.args).to.deep.equal([err]);
expect(mockRemoveCurrentAndSendNextMsg.calledOnce).to.be.true;
expect(mockRemoveCurrentAndSendNextMsg.firstCall.args).to.deep.equal([response.channel_id + response.txid]);
});
});
describe('_getCurrentMsg', () => {
it ('should get the message at the top of the queue for a txContextId', () => {
qHandler.txQueues[txContextId] = ['message1', 'message2'];
expect(qHandler._getCurrentMsg(txContextId)).to.deep.equal('message1');
});
it ('should return undefined when queue is empty for a txContextId', () => {
qHandler.txQueues[txContextId] = [];
expect(qHandler._getCurrentMsg(txContextId)).to.be.undefined;
});
it ('should return undefined when queue does not exist for a txContextId', () => {
qHandler.txQueues[txContextId] = null;
expect(qHandler._getCurrentMsg(txContextId)).to.be.undefined;
});
});
describe('_removeCurrentAndSendNextMsg', () => {
let sendMsg;
const alternateTxContextId = 'theChannelIDanotherTX';
beforeEach(() => {
sendMsg = sinon.stub(qHandler, '_sendMsg');
qHandler.txQueues[alternateTxContextId] = ['message3', 'message4'];
});
afterEach(() => {
sendMsg.restore();
});
it ('should delete the current message and send the next for a txContentId', () => {
qHandler.txQueues[txContextId] = ['message1', 'message2'];
qHandler._removeCurrentAndSendNextMsg(txContextId);
expect(sendMsg.calledOnce).to.be.true;
expect(qHandler.txQueues[txContextId]).to.deep.equal(['message2']);
expect(qHandler.txQueues[alternateTxContextId]).to.deep.equal(['message3', 'message4']);
});
it ('should delete the queue if no messages left after current is deleted for a txContentId', () => {
qHandler.txQueues[txContextId] = ['message1'];
qHandler._removeCurrentAndSendNextMsg(txContextId);
expect(sendMsg.notCalled).to.be.true;
expect(qHandler.txQueues[txContextId]).to.be.undefined;
expect(qHandler.txQueues[alternateTxContextId]).to.deep.equal(['message3', 'message4']);
});
it ('should do nothing if no queue is found for a txContentId', () => {
qHandler.txQueues[txContextId] = null;
qHandler._removeCurrentAndSendNextMsg(txContextId);
expect(sendMsg.notCalled).to.be.true;
expect(qHandler.txQueues[txContextId]).to.be.null;
expect(qHandler.txQueues[alternateTxContextId]).to.deep.equal(['message3', 'message4']);
});
});
describe('_sendMsg', () => {
const mockQMsg = {
getMsg: () => {
return 'some message';
},
fail: sinon.spy()
};
it ('should do nothing if no QMsg found for a txContextId', () => {
const getCurrStub = sinon.stub(qHandler, '_getCurrentMsg').returns(null);
qHandler._sendMsg(txContextId);
expect(getCurrStub.calledOnce).to.be.true;
expect(getCurrStub.firstCall.args).to.deep.equal([txContextId]);
expect(qHandler.stream.write.notCalled).to.be.true;
expect(mockQMsg.fail.notCalled).to.be.true;
});
it ('should write to the stream the current message', () => {
const getCurrStub = sinon.stub(qHandler, '_getCurrentMsg').returns(mockQMsg);
qHandler._sendMsg(txContextId);
expect(getCurrStub.calledOnce).to.be.true;
expect(getCurrStub.firstCall.args).to.deep.equal([txContextId]);
expect(qHandler.stream.write.calledOnce).to.be.true;
expect(qHandler.stream.write.firstCall.args).to.deep.equal(['some message']);
expect(mockQMsg.fail.notCalled).to.be.true;
});
it ('should call fail on the QMsg if stream write errors', () => {
const err = new Error('some error');
qHandler.stream.write = sinon.stub().throws(err);
const getCurrStub = sinon.stub(qHandler, '_getCurrentMsg').returns(mockQMsg);
qHandler._sendMsg(txContextId);
expect(getCurrStub.calledOnce).to.be.true;
expect(getCurrStub.firstCall.args).to.deep.equal([txContextId]);
expect(mockQMsg.fail.calledOnce).to.be.true;
expect(mockQMsg.fail.firstCall.args).to.deep.equal([err]);
});
});
});
describe('ChaincodeSupportClient', () => {
it ('should throw an error when chaincode not passed', () => {
expect(() => {
new Handler.ChaincodeSupportClient();
}).to.throw(/Missing required argument: chaincode/);
});
it ('should throw an error if argument does not match chaincode format', () => {
expect(() => {
new Handler.ChaincodeSupportClient({});
}).to.throw(/The chaincode argument must implement the mandatory "Init\(\)" method/);
});
it ('should throw an error if argument only part matches chaincode format', () => {
expect(() => {
new Handler.ChaincodeSupportClient({
Init: function() {}
});
}).to.throw(/The chaincode argument must implement the mandatory "Invoke\(\)" method/);
});
it ('should throw an error if argument missing URL argument', () => {
expect(() => {
new Handler.ChaincodeSupportClient(mockChaincodeImpl);
}).to.throw(/Invalid URL/);
});
it ('should throw an error if URL argument does not use grpc as protocol', () => {
expect(() => {
new Handler.ChaincodeSupportClient(mockChaincodeImpl, 'https://' + mockPeerAddress.base);
}).to.throw(/Invalid protocol: https. {2}URLs must begin with grpc:\/\/ or grpcs:\/\//);
});
it ('should set endpoint, client and default timeout', () => {
const credsSpy = sinon.spy(grpc.credentials, 'createInsecure');
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.unsecure);
expect(handler._request_timeout).to.deep.equal(30000);
expect(handler._endpoint.addr).to.deep.equal(mockPeerAddress.base);
expect(credsSpy.calledOnce).to.be.true;
expect(handler._endpoint.creds.constructor.name).to.deep.equal('InsecureChannelCredentialsImpl');
expect(handler._client.constructor.name).to.deep.equal('ServiceClientImpl');
credsSpy.restore();
});
it ('should override the default request timeout if value passed', () => {
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.unsecure, {
'request-timeout': 123456
});
expect(handler._request_timeout).to.deep.equal(123456);
});
it ('should store additional grpc options', () => {
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.unsecure, {
'grpc.max_send_message_length': 1,
'grpc.max_receive_message_length': 2,
'grpc.keepalive_time_ms': 3,
'grpc.http2.min_time_between_pings_ms': 5,
'grpc.keepalive_timeout_ms': 8,
'grpc.http2.max_pings_without_data': 13,
'grpc.keepalive_permit_without_calls': 21
});
expect(handler._options['grpc.max_send_message_length']).to.equal(1);
expect(handler._options['grpc.max_receive_message_length']).to.equal(2);
expect(handler._options['grpc.keepalive_time_ms']).to.equal(3);
expect(handler._options['grpc.http2.min_time_between_pings_ms']).to.equal(5);
expect(handler._options['grpc.keepalive_timeout_ms']).to.equal(8);
expect(handler._options['grpc.http2.max_pings_without_data']).to.equal(13);
expect(handler._options['grpc.keepalive_permit_without_calls']).to.equal(21);
});
it ('should preserve casing in handler addr', () => {
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, 'grpc://' + mockPeerAddress.base.toUpperCase());
expect(handler._endpoint.addr).to.deep.equal(mockPeerAddress.base.toUpperCase());
});
it ('should throw an error if connection secure and certificate not passed', () => {
expect(() => {
new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.secure);
}).to.throw(/PEM encoded certificate is required./);
});
it ('should throw an error if connection secure encoded private key not passed as opt', () => {
expect(() => {
new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.secure, {
pem: ca
});
}).to.throw(/encoded Private key is required./);
});
it ('should throw an error if connection secure encoded private key not passed as opt', () => {
expect(() => {
new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.secure, {
pem: ca,
key: privatekey
});
}).to.throw(/encoded client certificate is required./);
});
it ('should set endpoint, client and default timeout for a secure connection', () => {
const credsSpy = sinon.spy(grpc.credentials, 'createSsl');
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.secure, mockOpts);
expect(handler._options.cert).to.deep.equal(mockOpts.cert);
expect(handler._request_timeout).to.deep.equal(30000);
expect(handler._endpoint.addr).to.deep.equal(mockPeerAddress.base);
expect(credsSpy.calledOnce).to.be.true;
expect(credsSpy.calledWith(Buffer.from(mockOpts.pem), Buffer.from(mockOpts.key, 'base64'), Buffer.from(mockOpts.cert, 'base64'))).to.be.true;
expect(handler._endpoint.creds.constructor.name).to.deep.equal('SecureChannelCredentialsImpl');
expect(handler._client.constructor.name).to.deep.equal('ServiceClientImpl');
});
it ('should set grpc ssl options when ssl-target-name-override passed', () => {
const opts = Object.assign({}, mockOpts);
opts['ssl-target-name-override'] = 'dummy override';
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.secure, opts);
expect(handler._options['grpc.ssl_target_name_override']).to.deep.equal('dummy override');
expect(handler._options['grpc.default_authority']).to.deep.equal('dummy override');
});
describe('close', () => {
it ('should call end on the stream', () => {
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.unsecure);
handler._stream = {end: sinon.stub()};
handler.close();
expect(handler._stream.end.calledOnce).to.be.true;
});
});
describe('chat', () => {
afterEach(() => {
Handler = rewire('../../../fabric-shim/lib/handler.js');
});
it ('should create an instance of ChaincodeMessageHandler and pass the argument', () => {
const mockChaincodeMessageHandler = sinon.spy(() => {
return sinon.createStubInstance(Handler.ChaincodeMessageHandler);
});
Handler.__set__('ChaincodeMessageHandler', mockChaincodeMessageHandler);
const mockStream = {write: sinon.stub(), on: sinon.stub()};
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.unsecure);
handler._client.register = sinon.stub().returns(mockStream);
const fakeChatMessage = mapToChaincodeMessage({
type: peer.ChaincodeMessage.Type.GET_STATE,
payload: Buffer.from('starter message'),
channel_id: 'theChannelID',
txid: 'theTxID'
});
handler.chat(mapToChaincodeMessage(fakeChatMessage));
expect(handler._client.register.calledOnce).to.be.true;
expect(mockChaincodeMessageHandler.calledWithNew()).to.be.false;
expect(handler._stream).to.deep.equal(mockStream);
expect(handler._handler).to.deep.equal(new mockChaincodeMessageHandler(mockStream, mockChaincodeImpl));
expect(handler._handler.chat.calledOnce).to.be.true;
});
});
describe('toString', () => {
it ('should return ChaincodeSupportClient object as a string with the URL', () => {
const handler = new Handler.ChaincodeSupportClient(mockChaincodeImpl, mockPeerAddress.unsecure);
expect(handler.toString()).to.deep.equal(`ChaincodeSupportClient : {url:${mockPeerAddress.unsecure}}`);
});
});
});
describe('ChaincodeMessageHandler', () => {
describe('chat', () => {
afterEach(() => {
Handler = rewire('../../../fabric-shim/lib/handler.js');
});
it ('should create instance of MsgQueueHandler, register the client, setup listeners and write', () => {
const mockMsgQueueHandler = sinon.spy(() => {
return sinon.createStubInstance(MsgQueueHandler);
});
Handler.__set__('MsgQueueHandler', mockMsgQueueHandler);
const mockStream = {write: sinon.stub(), on: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
handler.chat('some starter message');
expect(mockMsgQueueHandler.calledWithNew()).to.be.false;
expect(handler._stream).to.deep.equal(mockStream);
expect(handler.msgQueueHandler).to.deep.equal(new mockMsgQueueHandler(handler));
expect(mockStream.write.calledOnce).to.be.true;
expect(mockStream.write.firstCall.args).to.deep.equal(['some starter message']);
expect(mockStream.on.callCount).to.deep.equal(3);
expect(mockStream.on.firstCall.args[0]).to.deep.equal('data');
expect(mockStream.on.secondCall.args[0]).to.deep.equal('end');
expect(mockStream.on.thirdCall.args[0]).to.deep.equal('error');
});
describe('stream.on.data', () => {
const MSG_TYPE = Handler.__get__('MSG_TYPE');
const registeredMsg = mapToChaincodeMessage({
type: MSG_TYPE.REGISTERED
});
const establishedMsg = mapToChaincodeMessage({
type: MSG_TYPE.READY
});
const eventReg = {};
const mockEventEmitter = (event, cb) => {
eventReg[event] = cb;
};
let mockStream;
let mockNewErrorMsg;
let handler;
let mockMsgQueueHandler;
let handleMsgResponseSpy;
let handleInitSpy;
let handleTransactionSpy;
beforeEach(() => {
handleMsgResponseSpy = sinon.spy();
mockMsgQueueHandler = sinon.spy(() => {
const mock = sinon.createStubInstance(MsgQueueHandler);
mock.handleMsgResponse = handleMsgResponseSpy;
return mock;
});
mockNewErrorMsg = sinon.stub().returns('some error');
Handler.__set__('MsgQueueHandler', mockMsgQueueHandler);
Handler.__set__('newErrorMsg', mockNewErrorMsg);
mockStream = {write: (sinon.stub()), on: mockEventEmitter, end: sinon.stub()};
handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
handler.chat('some starter message');
handleInitSpy = sinon.spy();
handleTransactionSpy = sinon.spy();
handler.handleInit = handleInitSpy;
handler.handleTransaction = handleTransactionSpy;
});
it ('should throw error when in state created and MSG_TYPE not REGISTERED', () => {
const badRegisteredMsg = mapToChaincodeMessage({
type: 'NOT REGISTERED'
});
eventReg.data(badRegisteredMsg);
expect(mockStream.write.calledTwice).to.be.true;
expect(mockNewErrorMsg.calledOnce).to.be.true;
expect(mockStream.write.secondCall.args).to.deep.equal(['some error']);
expect(mockNewErrorMsg.firstCall.args).to.deep.equal([mapFromChaincodeMessage(badRegisteredMsg), 'created']);
});
it ('should throw error when in state established and MSG_TYPE not READY', () => {
const badEstablishedMsg = mapToChaincodeMessage({
type: 'NOT REGISTERED'
});
eventReg.data(registeredMsg);
eventReg.data(badEstablishedMsg);
expect(mockStream.write.calledTwice).to.be.true;
expect(mockNewErrorMsg.calledOnce).to.be.true;
expect(mockStream.write.secondCall.args).to.deep.equal(['some error']);
expect(mockNewErrorMsg.firstCall.args).to.deep.equal([mapFromChaincodeMessage(badEstablishedMsg), 'established']);
});
it ('should do nothing when in state ready and MSG_TYPE equals REGISTERED', () => {
eventReg.data(registeredMsg);
eventReg.data(establishedMsg);
eventReg.data(registeredMsg);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockNewErrorMsg.notCalled).to.be.true;
expect(handleMsgResponseSpy.notCalled).to.be.true;
expect(handleInitSpy.notCalled).to.be.true;
expect(handleTransactionSpy.notCalled).to.be.true;
});
it ('should do nothing when in state ready and MSG_TYPE equals READY', () => {
eventReg.data(registeredMsg);
eventReg.data(establishedMsg);
eventReg.data(establishedMsg);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockNewErrorMsg.notCalled).to.be.true;
expect(handleMsgResponseSpy.notCalled).to.be.true;
expect(handleInitSpy.notCalled).to.be.true;
expect(handleTransactionSpy.notCalled).to.be.true;
});
it ('should call handleMsgResponse when in state ready and MSG_TYPE equals RESPONSE', () => {
eventReg.data(registeredMsg);
eventReg.data(establishedMsg);
const readyMsg = mapToChaincodeMessage({
type: MSG_TYPE.RESPONSE,
channel_id: 'some channel',
txid: 'some tx id'
});
eventReg.data(readyMsg);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockNewErrorMsg.notCalled).to.be.true;
expect(handleMsgResponseSpy.calledOnce).to.be.true;
expect(handleMsgResponseSpy.firstCall.args).to.deep.equal([mapFromChaincodeMessage(readyMsg)]);
expect(handleInitSpy.notCalled).to.be.true;
expect(handleTransactionSpy.notCalled).to.be.true;
});
it ('should call handleMsgResponse when in state ready and MSG_TYPE equals ERROR', () => {
eventReg.data(registeredMsg);
eventReg.data(establishedMsg);
const readyMsg = mapToChaincodeMessage({
type: MSG_TYPE.ERROR,
channel_id: 'some channel',
txid: 'some tx id'
});
eventReg.data(readyMsg);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockNewErrorMsg.notCalled).to.be.true;
expect(handleMsgResponseSpy.calledOnce).to.be.true;
expect(handleMsgResponseSpy.firstCall.args).to.deep.equal([mapFromChaincodeMessage(readyMsg)]);
expect(handleInitSpy.notCalled).to.be.true;
expect(handleTransactionSpy.notCalled).to.be.true;
});
it ('should call handleInit when in state ready and MSG_TYPE equals INIT', () => {
eventReg.data(registeredMsg);
eventReg.data(establishedMsg);
const readyMsg = mapToChaincodeMessage({
type: MSG_TYPE.INIT,
channel_id: 'some channel',
txid: 'some tx id'
});
eventReg.data(readyMsg);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockNewErrorMsg.notCalled).to.be.true;
expect(handleMsgResponseSpy.notCalled).to.be.true;
expect(handleInitSpy.calledOnce).to.be.true;
expect(handleInitSpy.firstCall.args).to.deep.equal([mapFromChaincodeMessage(readyMsg)]);
expect(handleTransactionSpy.notCalled).to.be.true;
});
it ('should call handleTransaction when in state ready and MSG_TYPE equals TRANSACTION', () => {
eventReg.data(registeredMsg);
eventReg.data(establishedMsg);
const readyMsg = mapToChaincodeMessage({
type: MSG_TYPE.TRANSACTION,
channel_id: 'some channel',
txid: 'some tx id'
});
eventReg.data(readyMsg);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockNewErrorMsg.notCalled).to.be.true;
expect(handleMsgResponseSpy.notCalled).to.be.true;
expect(handleInitSpy.notCalled).to.be.true;
expect(handleTransactionSpy.calledOnce).to.be.true;
expect(handleTransactionSpy.firstCall.args).to.deep.equal([mapFromChaincodeMessage(readyMsg)]);
});
it ('should end the process with value 1', () => {
const processStub = sinon.stub(process, 'exit');
eventReg.data(registeredMsg);
eventReg.data(establishedMsg);
const readyMsg = mapToChaincodeMessage({
type: 'something else',
channel_id: 'some channel',
txid: 'some tx id'
});
eventReg.data(readyMsg);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockNewErrorMsg.notCalled).to.be.true;
expect(handleMsgResponseSpy.notCalled).to.be.true;
expect(handleInitSpy.notCalled).to.be.true;
expect(handleTransactionSpy.notCalled).to.be.true;
expect(processStub.calledOnce).to.be.true;
expect(processStub.firstCall.args).to.deep.equal([1]);
processStub.restore();
});
});
describe('stream.on.end', () => {
it ('should cancel the stream', () => {
const eventReg = {};
const mockEventEmitter = (event, cb) => {
eventReg[event] = cb;
};
const mockStream = {write: sinon.stub(), on: mockEventEmitter, end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
handler.chat('some starter message');
eventReg.end();
expect(mockStream.write.calledOnce).to.be.true;
expect(mockStream.end.calledOnce).to.be.true;
});
});
describe('stream.on.error', () => {
it ('should end the stream', () => {
const eventReg = {};
const mockEventEmitter = (event, cb) => {
eventReg[event] = cb;
};
const mockStream = {write: sinon.stub(), on: mockEventEmitter, end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
handler.chat('some starter message');
eventReg.error({});
expect(mockStream.write.calledOnce).to.be.true;
expect(mockStream.end.calledOnce).to.be.true;
});
it ('should end the with error', () => {
const eventReg = {};
const mockEventEmitter = (event, cb) => {
eventReg[event] = cb;
};
const mockStream = {write: sinon.stub(), on: mockEventEmitter, end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
handler.chat('some starter message');
const error = new Error();
eventReg.error(error);
expect(mockStream.write.calledOnce).to.be.true;
expect(mockStream.end.calledOnce).to.be.true;
});
});
});
describe('handleInit', () => {
it ('should call handleMessage', () => {
const savedHandleMessage = Handler.__get__('handleMessage');
const handleMessage = sinon.spy();
Handler.__set__('handleMessage', handleMessage);
const mockStream = {write: sinon.stub(), end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
handler.handleInit('some message');
expect(handleMessage.calledOnce).to.be.true;
expect(handleMessage.firstCall.args).to.deep.equal(['some message', handler, 'init']);
Handler.__set__('handleMessage', savedHandleMessage);
});
});
describe('handleTransaction', () => {
it ('should call handleMessage', () => {
const savedHandleMessage = Handler.__get__('handleMessage');
const handleMessage = sinon.spy();
Handler.__set__('handleMessage', handleMessage);
const mockStream = {write: sinon.stub(), end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
handler.handleTransaction('some message');
expect(handleMessage.calledOnce).to.be.true;
expect(handleMessage.firstCall.args).to.deep.equal(['some message', handler, 'invoke']);
Handler.__set__('handleMessage', savedHandleMessage);
});
});
describe('handleGetMultipleStates', () => {
afterEach(() => {
sandbox.restore();
});
it('should send a GET_STATE_MULTIPLE message to the peer and return values', async () => {
const mockStream = {write: sinon.stub(), end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
const _askPeerAndListenStub = sandbox.stub(handler, '_askPeerAndListen').resolves({ payload: Buffer.alloc(0) });
const result = await handler.handleGetMultipleStates(['key1', 'key2'], 'theChannelID', 'theTxID');
expect(result).to.deep.equal([]);
expect(_askPeerAndListenStub.calledOnce).to.be.true;
expect(_askPeerAndListenStub.firstCall.args[1]).to.deep.equal('GET_STATE_MULTIPLE');
const sentMsg = _askPeerAndListenStub.firstCall.args[0];
expect(sentMsg.getType()).to.equal(peer.ChaincodeMessage.Type.GET_STATE_MULTIPLE);
const decodedPayload = peer.GetStateMultiple.deserializeBinary(sentMsg.getPayload_asU8());
expect(decodedPayload.getKeysList()).to.deep.equal(['key1', 'key2']);
expect(decodedPayload.getCollection()).to.equal('');
});
});
describe('handleGetMultiplePrivateData', () => {
afterEach(() => {
sandbox.restore();
});
it('should send a GET_STATE_MULTIPLE message with a collection to the peer and return values', async () => {
const mockStream = {write: sinon.stub(), end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
const _askPeerAndListenStub = sandbox.stub(handler, '_askPeerAndListen').resolves({ payload: Buffer.alloc(0) });
const result = await handler.handleGetMultiplePrivateData('collection1', ['key1', 'key2'], 'theChannelID', 'theTxID');
expect(result).to.deep.equal([]);
expect(_askPeerAndListenStub.calledOnce).to.be.true;
expect(_askPeerAndListenStub.firstCall.args[1]).to.deep.equal('GET_STATE_MULTIPLE');
const sentMsg = _askPeerAndListenStub.firstCall.args[0];
expect(sentMsg.getType()).to.equal(peer.ChaincodeMessage.Type.GET_STATE_MULTIPLE);
const decodedPayload = peer.GetStateMultiple.deserializeBinary(sentMsg.getPayload_asU8());
expect(decodedPayload.getKeysList()).to.deep.equal(['key1', 'key2']);
expect(decodedPayload.getCollection()).to.equal('collection1');
});
});
describe('handleGetState', () => {
const key = 'theKey';
const collection = '';
let expectedMsg;
before(() => {
const payloadPb = new peer.GetState();
payloadPb.setKey(key);
payloadPb.setCollection(collection);
expectedMsg = mapToChaincodeMessage({
type: peer.ChaincodeMessage.Type.GET_STATE,
payload: payloadPb.serializeBinary(),
channel_id: 'theChannelID',
txid: 'theTxID'
});
});
afterEach(() => {
Handler = rewire('../../../fabric-shim/lib/handler.js');
sandbox.restore();
});
it ('should resolve when _askPeerAndListen resolves', async () => {
const mockStream = {write: sinon.stub(), end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
const _askPeerAndListenStub = sandbox.stub(handler, '_askPeerAndListen').resolves('some response');
const result = await handler.handleGetState(collection, key, 'theChannelID', 'theTxID');
expect(result).to.deep.equal('some response');
expect(_askPeerAndListenStub.firstCall.args.length).to.deep.equal(2);
expect(_askPeerAndListenStub.firstCall.args[0]).to.deep.equal(expectedMsg);
expect(_askPeerAndListenStub.firstCall.args[1]).to.deep.equal('GetState');
});
it ('should reject when _askPeerAndListen resolves', async () => {
const mockStream = {write: sinon.stub(), end: sinon.stub()};
const handler = new Handler.ChaincodeMessageHandler(mockStream, mockChaincodeImpl);
const _askPeerAndListenStub = sandbox.stub(handler, '_askPeerAndListen').rejects();
const result = handler.handleGetState(collection, key, 'theChannelID', 'theTxID');
await expect(result).to.eventually.be.rejected;
expect(_askPeerAndListenStub.firstCall.args.length).to.deep.equal(2);
expect(_askPeerAndListenStub.firstCall.args[0]).to.deep.equal(expectedMsg);
expect(_askPeerAndListenStub.firstCall.args[1]).to.deep.equal('GetState');
});
});
describe('handlePutState', () => {
const key = 'theKey';