-
Notifications
You must be signed in to change notification settings - Fork 142
/
handler.js
783 lines (688 loc) · 28.1 KB
/
handler.js
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
/*
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
*/
'use strict';
/* eslint-disable no-useless-escape */
process.env.GRPC_SSL_CIPHER_SUITES = 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384';
const protoLoader = require('@grpc/proto-loader');
const grpc = require('@grpc/grpc-js');
const fabprotos = require('../bundle');
const path = require('path');
const {URL} = require('url');
const util = require('util');
const StateQueryIterator = require('./iterators').StateQueryIterator;
const HistoryQueryIterator = require('./iterators').HistoryQueryIterator;
const logger = require('./logger').getLogger('lib/handler.js');
const Stub = require('./stub.js');
const utils = require('./utils/utils');
const STATES = {
Created: 'created',
Established: 'established',
Ready: 'ready'
};
// message types
const MSG_TYPE = {
REGISTERED: 'REGISTERED', // _serviceProto.ChaincodeMessage.Type.REGISTERED
READY: 'READY', // _serviceProto.ChaincodeMessage.Type.READY
RESPONSE: 'RESPONSE', // _serviceProto.ChaincodeMessage.Type.RESPONSE
ERROR: 'ERROR', // _serviceProto.ChaincodeMessage.Type.ERROR
INIT: 'INIT', // _serviceProto.ChaincodeMessage.Type.INIT
TRANSACTION: 'TRANSACTION', // _serviceProto.ChaincodeMessage.Type.TRANSACTION
COMPLETED: 'COMPLETED', // _serviceProto.ChaincodeMessage.Type.COMPLETED
};
const PROTO_PATH = path.resolve(__dirname, '..', 'protos', 'peer', 'chaincode_shim.proto');
const packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs: [
path.resolve(__dirname, '..', 'google-protos'),
path.resolve(__dirname, '..', 'protos')
]
}
);
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
/*
* Simple class to represent a message to be queued with the associated
* promise methods to be driven around this message
*/
class QMsg {
constructor(msg, method, resolve, reject) {
this.msg = msg;
this.method = method;
this.resolve = resolve;
this.reject = reject;
}
getMsg() {
return this.msg;
}
getMsgTxContextId() {
return this.msg.channel_id + this.msg.txid;
}
getMethod() {
return this.method;
}
success(response) {
this.resolve(response);
}
fail(err) {
this.reject(err);
}
}
/*
* This class handles queuing messages to be sent to the peer based on transaction id
* The peer can access requests coming from different transactions concurrently but
* cannot handle concurrent requests for the same transaction. Given the nature of asynchronouse
* programming this could present a problem so this implementation provides a way to allow
* code to perform concurrent request by serialising the calls to the peer.
*/
class MsgQueueHandler {
constructor(handler) {
this.handler = handler;
this.stream = handler._stream;
this.txQueues = {};
}
/*
* Queue a message to be sent to the peer. If it is the first
* message on the queue then send the message to the peer
*
* @param {QMsg} qMsg the message to queue
*/
queueMsg(qMsg) {
const txContextId = qMsg.getMsgTxContextId();
let msgQueue = this.txQueues[txContextId];
if (!msgQueue) {
msgQueue = this.txQueues[txContextId] = [];
}
msgQueue.push(qMsg);
if (msgQueue.length === 1) {
this._sendMsg(txContextId);
}
}
/*
* Handle a response to a message. this looks at the top of
* the queue for the specific txn id to get the message this
* response is associated with so it can drive the promise waiting
* on this message response. it then removes that message from the
* queue and sends the next message on the queue if there is one.
*
* @param {any} response the received response
*/
handleMsgResponse(response) {
const txId = response.txid;
const channel_id = response.channel_id;
const txContextId = channel_id + txId;
const qMsg = this._getCurrentMsg(txContextId);
if (qMsg) {
try {
const parsedResponse = parseResponse(this.handler, response, qMsg.getMethod());
qMsg.success(parsedResponse);
} catch (err) {
qMsg.fail(err);
}
this._removeCurrentAndSendNextMsg(txContextId);
}
}
/**
* Get the current message.
* this returns the message at the top of the queue for the particular transaction.
*
* @param {string} txContextId - the transaction context id
* @returns {QMsg} the message at the top of the queue
*/
_getCurrentMsg(txContextId) {
const msgQueue = this.txQueues[txContextId];
if (msgQueue) {
return msgQueue[0];
}
const errMsg = util.format('Failed to find a message for transaction context id %s', txContextId);
logger.error(errMsg);
// Throwing an error here will terminate the container and potentially lose logs
// This may be an error, but I don't know if this should abend the container or
// should just keep going.
// throw new Error(errMsg);
}
/**
* Remove the current message and send the next message in the queue if there is one.
* delete the queue if there are no more messages.
*
* @param {any} txContextId - the transaction context id
*/
_removeCurrentAndSendNextMsg(txContextId) {
const msgQueue = this.txQueues[txContextId];
if (msgQueue && msgQueue.length > 0) {
msgQueue.shift();
if (msgQueue.length === 0) {
delete this.txQueues[txContextId];
} else {
this._sendMsg(txContextId);
}
}
}
/**
* send the current message to the peer.
*
* @param {any} txContextId the transaction context id
*/
_sendMsg(txContextId) {
const qMsg = this._getCurrentMsg(txContextId);
if (qMsg) {
try {
this.stream.write(qMsg.getMsg());
} catch (err) {
qMsg.fail(err);
}
}
}
}
/*
* The ChaincodeSupportClient class represents a chaincode gRPC client to the peer.
*/
class ChaincodeSupportClient {
/*
* Constructs an object with the endpoint configuration settings.
*
* @param {Object} chaincode The user-supplied object to handle chaincode interface calls Init() and Invoke()
* @param {string} url The peer URL with format of 'grpc(s)://host:port'
* @param {Object} opts An Object that may contain options to pass to grpcs calls
* <br>- pem {string} The certificate file, in PEM format,
* to use with the gRPC protocol (that is, with TransportCredentials).
* Required when using the grpcs protocol.
* <br>- ssl-target-name-override {string} Used in test environment only, when the server certificate's
* hostname (in the 'CN' field) does not match the actual host endpoint that the server process runs
* at, the application can work around the client TLS verify failure by setting this property to the
* value of the server certificate's hostname
* <br>- any other standard grpc call options will be passed to the grpc service calls directly
*/
constructor(chaincode, url, opts) {
if (typeof chaincode !== 'object') {
throw new Error('Missing required argument: chaincode');
}
if (typeof chaincode.Init !== 'function') {
throw new Error('The chaincode argument must implement the mandatory "Init()" method');
}
if (typeof chaincode.Invoke !== 'function') {
throw new Error('The chaincode argument must implement the mandatory "Invoke()" method');
}
this.chaincode = chaincode;
// connection options
this._options = {};
if (opts && opts['ssl-target-name-override'] && opts['ssl-target-name-override'] !== '') {
this._options['grpc.ssl_target_name_override'] = opts['ssl-target-name-override'];
this._options['grpc.default_authority'] = opts['ssl-target-name-override'];
}
for (const key in opts ? opts : {}) {
if (key !== 'pem' && key !== 'ssl-target-name-override') {
this._options[key] = opts[key];
}
}
// service connection
this._url = url;
this._endpoint = new Endpoint(url, opts);
// node.js based timeout
this._request_timeout = 30000;
if (opts && opts['request-timeout']) {
this._request_timeout = opts['request-timeout'];
}
this._client = new protoDescriptor.protos.ChaincodeSupport(this._endpoint.addr, this._endpoint.creds, this._options);
}
close() {
this._stream.end();
}
chat(convStarterMsg) {
this._stream = this._client.register();
this._handler = new ChaincodeMessageHandler(this._stream, this.chaincode);
this._handler.chat(convStarterMsg);
}
/*
return a printable representation of this object
*/
toString() {
return 'ChaincodeSupportClient : {' +
'url:' +
this._url +
'}';
}
}
/**
* The ChaincodeMessageHandler class handles messages between peer and chaincode both in the chaincode server and client model.
*/
class ChaincodeMessageHandler {
constructor (stream, chaincode) {
this._stream = stream;
this.chaincode = chaincode;
}
// this is a long-running method that does not return until
// the conversation b/w the chaincode program and the target
// peer has been completed
chat(convStarterMsg) {
this.msgQueueHandler = new MsgQueueHandler(this);
const stream = this._stream;
const self = this;
// the conversation is supposed to follow a certain protocol,
// if either side spoke out of turn, then we error out and
// reject that response. The initial state is "created"
let state = 'created';
stream.on('data', function (msg) {
logger.debug('Received chat message from peer: %s, state: %s', msg.txid, state);
if (state === STATES.Ready) {
const type = msg.type;
if (type !== MSG_TYPE.REGISTERED && type !== MSG_TYPE.READY) {
const loggerPrefix = utils.generateLoggingPrefix(msg.channel_id, msg.txid);
if (type === MSG_TYPE.RESPONSE || type === MSG_TYPE.ERROR) {
logger.debug('%s Received %s, handling good or error response', loggerPrefix, msg.type);
self.msgQueueHandler.handleMsgResponse(msg);
} else if (type === MSG_TYPE.INIT) {
logger.debug('%s Received %s, initializing chaincode', loggerPrefix, msg.type);
self.handleInit(msg);
} else if (type === MSG_TYPE.TRANSACTION) {
logger.debug('%s Received %s, invoking transaction on chaincode(state:%s)', loggerPrefix, msg.type, state);
self.handleTransaction(msg);
} else {
logger.error('Received unknown message from the peer. Exiting.');
// TODO: Should we really do this ?
process.exit(1);
}
}
}
if (state === STATES.Established) {
if (msg.type === MSG_TYPE.READY) {
logger.info('Successfully established communication with peer node. State transferred to "ready"');
state = STATES.Ready;
} else {
// can not process any message other than "ready"
// from the peer when in "established" state
// send an error message telling the peer about this
logger.error(util.format('Chaincode is in "ready" state, can only ' +
'process messages of type "established", but received "%s"', msg.type));
const errMsg = newErrorMsg(msg, state);
stream.write(errMsg);
}
}
if (state === STATES.Created) {
if (msg.type === MSG_TYPE.REGISTERED) {
logger.info('Successfully registered with peer node. State transferred to "established"');
state = STATES.Established;
} else {
// can not process any message other than "registered"
// from the peer when in "created" state
// send an error message telling the peer about this
logger.error(util.format('Chaincode is in "created" state, can only ' +
'process messages of type "registered", but received "%s"', msg.type));
const errMsg = newErrorMsg(msg, state);
stream.write(errMsg);
}
}
});
stream.on('end', function () {
logger.debug('Chat stream ending');
stream.cancel();
});
stream.on('error', function (err) {
logger.error('Chat stream with peer - on error: %j', err.stack ? err.stack : err);
stream.end();
});
// now let's kick off the conversation already!
logger.debug('Sending chat message: %j', convStarterMsg);
stream.write(convStarterMsg);
}
handleInit(msg) {
handleMessage(msg, this, 'init');
}
handleTransaction(msg) {
handleMessage(msg, this, 'invoke');
}
async handleGetState(collection, key, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.GET_STATE,
payload: fabprotos.protos.GetState.encode({key, collection}).finish(),
txid: txId,
channel_id: channel_id
};
logger.debug('handleGetState - with key:', key);
return await this._askPeerAndListen(msg, 'GetState');
}
async handlePutState(collection, key, value, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.PUT_STATE,
payload: fabprotos.protos.PutState.encode({key, value, collection}).finish(),
txid: txId,
channel_id: channel_id
};
return await this._askPeerAndListen(msg, 'PutState');
}
async handleDeleteState(collection, key, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.DEL_STATE,
payload: fabprotos.protos.DelState.encode({key, collection}).finish(),
txid: txId,
channel_id: channel_id
};
return await this._askPeerAndListen(msg, 'DeleteState');
}
async handlePutStateMetadata(collection, key, metakey, ep, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.PUT_STATE_METADATA,
payload: fabprotos.protos.PutStateMetadata.encode({
key,
collection,
metadata: {
metakey,
value: ep
}
}).finish(),
txid: txId,
channel_id: channel_id
};
return this._askPeerAndListen(msg, 'PutStateMetadata');
}
async handleGetPrivateDataHash(collection, key, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.GET_PRIVATE_DATA_HASH,
payload: fabprotos.protos.GetState.encode({key, collection}).finish(),
txid: txId,
channel_id: channel_id
};
return await this._askPeerAndListen(msg, 'GetPrivateDataHash');
}
async handleGetStateMetadata(collection, key, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.GET_STATE_METADATA,
payload: fabprotos.protos.GetStateMetadata.encode({key, collection}).finish(),
txid: txId,
channel_id: channel_id
};
return this._askPeerAndListen(msg, 'GetStateMetadata');
}
async handleGetStateByRange(collection, startKey, endKey, channel_id, txId, metadata) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.GET_STATE_BY_RANGE,
payload: fabprotos.protos.GetStateByRange.encode({startKey, endKey, collection, metadata}).finish(),
txid: txId,
channel_id: channel_id
};
return await this._askPeerAndListen(msg, 'GetStateByRange');
}
async handleQueryStateNext(id, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.QUERY_STATE_NEXT,
payload: fabprotos.protos.QueryStateNext.encode({id}).finish(),
txid: txId,
channel_id
};
return await this._askPeerAndListen(msg, 'QueryStateNext');
}
async handleQueryStateClose(id, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.QUERY_STATE_CLOSE,
payload: fabprotos.protos.QueryStateClose.encode({id}).finish(),
txid: txId,
channel_id: channel_id
};
return await this._askPeerAndListen(msg, 'QueryStateClose');
}
async handleGetQueryResult(collection, query, metadata, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.GET_QUERY_RESULT,
payload: fabprotos.protos.GetQueryResult.encode({query, collection, metadata}).finish(),
txid: txId,
channel_id: channel_id
};
return await this._askPeerAndListen(msg, 'GetQueryResult');
}
async handleGetHistoryForKey(key, channel_id, txId) {
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.GET_HISTORY_FOR_KEY,
payload: fabprotos.protos.GetHistoryForKey.encode({key}).finish(),
txid: txId,
channel_id: channel_id
};
return await this._askPeerAndListen(msg, 'GetHistoryForKey');
}
async handleInvokeChaincode(chaincodeName, args, channel_id, txId) {
const argsAsBuffers = args.map((arg) => Buffer.from(arg, 'utf8'));
const msg = {
type: fabprotos.protos.ChaincodeMessage.Type.INVOKE_CHAINCODE,
payload: fabprotos.protos.ChaincodeSpec.encode({
chaincodeId: {
name: chaincodeName
},
input: {
args: argsAsBuffers
}
}).finish(),
txid: txId,
channel_id: channel_id
};
const message = await this._askPeerAndListen(msg, 'InvokeChaincode');
// here the message type comes back as an enumeration value rather than a string
// so need to use the enumerated value
if (message.type === fabprotos.protos.ChaincodeMessage.Type.COMPLETED) {
return fabprotos.protos.Response.decode(message.payload);
}
// Catch the transaction and rethrow the data
if (message.type === fabprotos.protos.ChaincodeMessage.Type.ERROR) {
const errorData = message.payload.toString('utf8');
throw new Error(errorData);
}
}
/*
* send a message to the peer which returns a promise of the
* response.
*
* @param {string} msg the message to send to the peer
* @param {string} method the name of the method being called
* @returns {promise} returns a promise which is resolved with the response
* or is rejected otherwise
*/
_askPeerAndListen(msg, method) {
return new Promise((resolve, reject) => {
const qMsg = new QMsg(msg, method, resolve, reject);
this.msgQueueHandler.queueMsg(qMsg);
});
}
/*
return a printable representation of this object
*/
toString() {
return 'ChaincodeMessageHandler : {}';
}
}
async function handleMessage(msg, client, action) {
const loggerPrefix = utils.generateLoggingPrefix(msg.channel_id, msg.txid);
let nextStateMsg, input;
try {
input = fabprotos.protos.ChaincodeInput.decode(msg.payload);
} catch (err) {
logger.error('%s Incorrect payload format. Sending ERROR message back to peer', loggerPrefix);
nextStateMsg = {
type: fabprotos.protos.ChaincodeMessage.Type.ERROR,
payload: msg.payload,
txid: msg.txid,
channel_id : msg.channel_id
};
}
if (input) {
let stub;
try {
stub = createStub(client, msg.channel_id, msg.txid, input, msg.proposal);
} catch (err) {
logger.error(util.format('Failed to construct a chaincode stub instance from the INIT message: %s', err));
nextStateMsg = {
type: fabprotos.protos.ChaincodeMessage.Type.ERROR,
payload: Buffer.from(err.toString()),
txid: msg.txid,
channel_id : msg.channel_id
};
client._stream.write(nextStateMsg);
}
if (stub) {
let resp, method;
if (action === 'init') {
resp = await client.chaincode.Init(stub);
method = 'Init';
} else {
resp = await client.chaincode.Invoke(stub);
method = 'Invoke';
}
// check that a response object has been returned otherwise assume an error.
if (!resp || !resp.status) {
const errMsg = util.format('%s Calling chaincode %s() has not called success or error.',
loggerPrefix, method);
logger.error(errMsg);
resp = {
status: Stub.RESPONSE_CODE.ERROR,
message: errMsg
};
}
logger.debug(util.format(
'%s Calling chaincode %s(), response status: %s',
loggerPrefix,
method,
resp.status));
if (resp.status >= Stub.RESPONSE_CODE.ERROR) {
const errMsg = util.format('%s Calling chaincode %s() returned error response [%s]. Sending COMPLETED message back to peer',
loggerPrefix, method, resp.message);
logger.error(errMsg);
nextStateMsg = {
type: fabprotos.protos.ChaincodeMessage.Type.COMPLETED,
payload: fabprotos.protos.Response.encode(resp).finish(),
txid: msg.txid,
channel_id: msg.channel_id
};
} else {
logger.info(util.format('%s Calling chaincode %s() succeeded. Sending COMPLETED message back to peer',
loggerPrefix, method));
nextStateMsg = {
type: fabprotos.protos.ChaincodeMessage.Type.COMPLETED,
payload: fabprotos.protos.Response.encode(resp).finish(),
txid: msg.txid,
channel_id: msg.channel_id,
chaincode_event: stub.chaincodeEvent
};
}
client._stream.write(nextStateMsg);
}
} else {
client._stream.write(nextStateMsg);
}
}
/*
* function to create a new Stub, this is done to facilitate unit testing
*
* @param {Handler} client an instance of the Handler class
* @param {string} channel_id channel id
* @param {string} txid transaction id
* @param {any} input decoded message from peer
* @param {any} proposal the proposal
* @returns a new Stub instance
*/
function createStub(client, channel_id, txid, input, proposal) {
return new Stub(client, channel_id, txid, input, proposal);
}
function newErrorMsg(msg, state) {
const errStr = util.format('[%s-%s] Chaincode handler FSM cannot handle message (%s) with payload size (%d) while in state: %s',
msg.channel_id, msg.txid, msg.type, msg.payload.length, state);
return {
type: MSG_TYPE.ERROR,
payload: Buffer.from(errStr),
txid: msg.txid,
channel_id: msg.channel_id
};
}
function handleGetQueryResult(handler, res, method) {
const payload = fabprotos.protos.QueryResponse.decode(res.payload);
const iterator = new StateQueryIterator(handler, res.channel_id, res.txid, payload);
const result = {iterator};
if (payload.metadata) {
logger.debug(util.format('Received metadata for method: %s', method));
const metadata = fabprotos.protos.QueryResponseMetadata.decode(payload.metadata);
result.metadata = metadata;
logger.debug(util.format('metadata: %j', result.metadata));
}
return result;
}
function handleGetStateMetadata(payload) {
const method = 'handleGetStateMetadata';
logger.debug('%s - get response from peer.', method);
const decoded = fabprotos.protos.StateMetadataResult.decode(payload);
logger.debug('%s - decoded response:%j', method, decoded);
const entries = decoded.entries;
const metadata = {};
entries.forEach(entry => {
metadata[entry.metakey] = entry.value;
});
logger.debug('%s - metadata: %j', method, metadata);
return metadata;
}
function parseResponse(handler, res, method) {
const loggerPrefix = utils.generateLoggingPrefix(res.channel_id, res.txid);
if (res.type === MSG_TYPE.RESPONSE) {
logger.debug(util.format('%s Received %s() successful response', loggerPrefix, method));
// some methods have complex responses, decode the protobuf structure
// before returning to the client code
switch (method) {
case 'GetStateByRange':
case 'GetQueryResult':
return handleGetQueryResult(handler, res, method);
case 'GetHistoryForKey':
return new HistoryQueryIterator(handler, res.channel_id, res.txid, fabprotos.protos.QueryResponse.decode(res.payload));
case 'QueryStateNext':
case 'QueryStateClose':
return fabprotos.protos.QueryResponse.decode(res.payload);
case 'InvokeChaincode':
return fabprotos.protos.ChaincodeMessage.decode(res.payload);
case 'GetStateMetadata':
return handleGetStateMetadata(res.payload);
}
return res.payload;
} else if (res.type === MSG_TYPE.ERROR) {
logger.debug(util.format('%s Received %s() error response', loggerPrefix, method));
throw new Error(res.payload.toString());
} else {
const errMsg = util.format(
'%s Received incorrect chaincode in response to the %s() call: type="%s", expecting "RESPONSE"',
loggerPrefix, method, res.type);
logger.debug(errMsg);
throw new Error(errMsg);
}
}
module.exports = {
ChaincodeSupportClient,
ChaincodeMessageHandler
};
//
// The Endpoint class represents a remote grpc or grpcs target
//
class Endpoint {
constructor(url /* string*/, opts) {
const purl = new URL(url);
if (purl.protocol === 'grpc:') {
this.addr = purl.host;
this.creds = grpc.credentials.createInsecure();
} else if (purl.protocol === 'grpcs:') {
if (!opts || !opts.pem || !(typeof opts.pem === 'string')) {
throw new Error('PEM encoded certificate is required.');
}
if (!opts.key || !(typeof opts.key === 'string')) {
throw new Error('encoded Private key is required.');
}
if (!opts.cert || !(typeof opts.cert === 'string')) {
throw new Error('encoded client certificate is required.');
}
this.addr = purl.host;
this.creds = grpc.credentials.createSsl(Buffer.from(opts.pem), Buffer.from(opts.key, 'base64'), Buffer.from(opts.cert, 'base64'));
} else {
const error = new Error();
error.name = 'InvalidProtocol';
error.message = 'Invalid protocol: ' + purl.protocol + ' URLs must begin with grpc:// or grpcs://';
throw error;
}
}
}