Skip to content

Commit

Permalink
[FABN-1153] Add BasicProverHandler
Browse files Browse the repository at this point in the history
- Implement BasicProverHandler
- Add unit and e2e tests

Change-Id: I14ede2d6fe426b292a5511bbdad5e516e3c4b082
Signed-off-by: Wenjian Qiao <[email protected]>
  • Loading branch information
wenjianqiao committed Mar 19, 2019
1 parent 81d32ad commit 1dcaf55
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 9 deletions.
40 changes: 40 additions & 0 deletions docs/tutorials/handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ a custom handler to be used. This handler is used in the
{@linkcode Channel#sendTransaction sendTransaction()} method
to determine the orderers and how to send the transaction to be committed.
(default 'fabric-client/lib/impl/BasicCommitHandler.js')
* `prover-handler` - string - The path to the prover handler. Allows for a
custom handler to be used. This handler is used in the
{@linkcode Channel#sendTokenCommand sendTokenCommand()}
method to determine the target peers and how to send the token command.
(default 'fabric-client/lib/impl/BasicProverHandler.js')

### new Endorsement Handler
The sending of a proposal to be endorsed may be done using custom code. The
Expand Down Expand Up @@ -122,3 +127,38 @@ channel is initialized, the channel will read the path setting and create an
instance of the handler for use by the new channel instance.

<a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>.

### new Prover Handler
The sending of a token command to a prover peer may be done using custom code. The
fabric-client will use by default the file called `BasicProverHandler`.
The default handler was designed to be used without discovery.
The default handler will only send to the peers as defined in the targets parameter
or the peers with the 'proverPeer' role assigned to the channel instance.
A different prover handler may be used by changing the configuration setting
"prover-handler" with the `setConfigSetting()` or placing a new line
in configuration JSON file that the application has applied to the fabric-client
configuration. This will instantiate a handler located at the path provided
in the `prover-handler` attribute for all channels initialized after the call.
The handler may also be changed using the `proverHandler` attribute on the
`channel.initialize()` request call parameter. This will instantiate a handler
located at the path provide in the attribute just for this channel instance.
```
// set value in memory
Client.setConfigSetting('prover-handler', '/path/to/the/handler.js');
--or--
// the path to an additional config file
Client.addConfigFile('/path/to/config.json');
// the json file contains the following line
// "prover-handler": "/path/to/the/handler.js"
--or--
const request = {
...
proverHandler: "/path/to/the/handler.js",
...
}
// initialize must be run to use handlers.
channel.initialize(request);
```
A prover handler should extend the {@link ProverHandler}. When the
channel is initialized, the channel will read the path setting and create an
instance of the handler for use by the new channel instance.
3 changes: 2 additions & 1 deletion fabric-client/config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,6 @@
"discovery-cache-life": 300000,
"override-discovery-protocol": null,
"endorsement-handler": "fabric-client/lib/impl/DiscoveryEndorsementHandler.js",
"commit-handler": "fabric-client/lib/impl/BasicCommitHandler.js"
"commit-handler": "fabric-client/lib/impl/BasicCommitHandler.js",
"prover-handler": "fabric-client/lib/impl/BasicProverHandler.js"
}
8 changes: 3 additions & 5 deletions fabric-client/lib/Channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -3369,11 +3369,6 @@ const Channel = class {
throw new Error(util.format('Missing required "tokenCommand" in request on the %s call', method));
}

// convert any names into peer objects or if empty find all
// prover peers added to this channel
const targetPeers = this._getTargets(request.targets, Constants.NetworkConfig.PROVER_PEER_ROLE);
logger.debug('sendTokenCommand, number targetPeers=%d', targetPeers.length);

if (this._prover_handler) {
logger.debug('%s - running with prover handler', method);
const signedCommand = Channel._buildSignedTokenCommand(request, this._name, this._clientContext);
Expand All @@ -3387,6 +3382,9 @@ const Channel = class {
const response = await this._prover_handler.processCommand(params);
return response;
} else {
// convert any names into peer objects or if empty find all
// prover peers added to this channel
const targetPeers = this._getTargets(request.targets, Constants.NetworkConfig.PROVER_PEER_ROLE);
return Channel.sendTokenCommand(request, targetPeers, this._name, this._clientContext, timeout);
}
}
Expand Down
74 changes: 74 additions & 0 deletions fabric-client/lib/ProverHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/**
* Base class for prover handling
* @class
*/
class ProverHandler {

/**
* @typedef {Object} ProverHandlerParameters
* @property {Object} request - {@link ChaincodeInvokeRequest}
* @property {Object} signed_proposal - the encoded protobuf "SignedProposal"
* created by the sendTransactionProposal method before calling the
* handler. Will be the object to be proved by the target peers.
* @property {Number} timeout - the timeout setting passed on sendTransactionProposal
* method.
*/

/**
* This method will process the request object to calculate the target peers.
* Once the targets have been determined, use the channel to send the token
* transaction to the targets one at a time. After a target peer returns a response,
* this method will skip the rest of targets and return the response to the caller.
*
* @param {ProverHandlerParameters} params - A {@link ProverHandlerParameters}
* that contains enough information to determine the targets and contains
* a {@link ChaincodeInvokeRequest} to be sent using the included channel
* with the {@link Channel} 'sendTransactionProposal' method.
* @returns {Promise} A Promise for the {@link ProposalResponseObject}, the
* same results as calling the {@link Channel#sendTransactionProposal}
* method directly.
*/
processCommand(params) {
if (params) {
throw new Error('The "processCommand" method must be implemented');
}
throw new Error('The "processCommand" method must be implemented');
}

/**
* This method will be called by the channel when the channel is initialized.
*/
initialize() {
throw new Error('The "initialize" method must be implemented');
}

/**
* This static method will be called by the channel to create an instance of
* this handler. It will be passed the channel object this handler is working
* with.
*/
static create(channel) {
if (channel) {
throw new Error('The "create" method must be implemented');
}
throw new Error('The "create" method must be implemented');
}
}

module.exports = ProverHandler;
102 changes: 102 additions & 0 deletions fabric-client/lib/impl/BasicProverHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
Copyright 2019 IBM All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/

'use strict';

const token_utils = require('../token-utils');
const utils = require('../utils');
const Constants = require('../Constants.js');
const ProverHandler = require('../ProverHandler');
const logger = utils.getLogger('BasicProverHandler');


/**
* This is an implementation of the [ProverHandler]{@link ProverHandler} API.
* It will send a token request to a Prover peer one at a time from a provided
* list or a list currently assigned to the channel.
*
* @class
* @extends ProverHandler
*/
class BasicProverHandler extends ProverHandler {

/**
* constructor
*
* @param {Channel} channel - The channel for this handler.
*/
constructor(channel) {
super();
this._channel = channel;
}

/**
* Factory method to create an instance of a Proverter handler.
*
* @param {Channel} channel - the channel instance that this Prover
* handler will be servicing.
* @returns {BasicProverHandler} The instance of the handler
*/
static create(channel) {
return new BasicProverHandler(channel);
}

initialize() {
logger.debug('initialize - start');
}

async processCommand(params) {
const method = 'processCommand';
logger.debug('%s - start', method);


let errorMsg = null;
if (!params) {
errorMsg = 'Missing all required input parameters';
} else if (!params.request) {
errorMsg = 'Missing "request" input parameter';
} else if (!params.signed_command) {
errorMsg = 'Missing "signed_command" input parameter';
}

if (!params.request.txId) {
errorMsg = 'Missing "txId" parameter in the token request';
}

if (errorMsg) {
logger.error('Prover Handler error:' + errorMsg);
throw new Error(errorMsg);
}

let timeout = utils.getConfigSetting('request-timeout');
if (params.timeout) {
timeout = params.timeout;
}

// Prover peers are not integrated with discovery service yet,
// so this handler uses request.targets or gets all prover peers if not defined.

let targetPeers;

if (!params.request.targets) {
logger.debug('%s - running prover handler without provided targets', method);
// find all prover peers added to this channel
targetPeers = this._channel._getTargets(undefined, Constants.NetworkConfig.PROVER_PEER_ROLE);
} else {
logger.debug('%s - running prover handler with provided targets', method);
// convert any names into peer objects
targetPeers = this._channel._getTargets(params.request.targets, Constants.NetworkConfig.PROVER_PEER_ROLE);
}

// send to one of the peers; if failed, send to next peer
const responses = await token_utils.sendTokenCommandToPeer(targetPeers, params.signed_command, timeout);
return responses;

}
}

module.exports = BasicProverHandler;
71 changes: 71 additions & 0 deletions fabric-client/test/ProverHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

const ProverHandler = require('../lib/ProverHandler');

const chai = require('chai');
chai.should();

describe('ProverHandler', () => {
let providerHandler;

beforeEach(() => {
providerHandler = new ProverHandler();
});

describe('#processCommand', () => {

it('should throw', () => {
(() => {
providerHandler.initialize();
}).should.throw('The "initialize" method must be implemented');
});

it('should throw when params are given', () => {
(() => {
providerHandler.processCommand('params');
}).should.throw('The "processCommand" method must be implemented');
});

it('should throw when params are not given', () => {
(() => {
providerHandler.processCommand();
}).should.throw('The "processCommand" method must be implemented');
});
});

describe('#initialize', () => {
it('should throw', () => {
(() => {
providerHandler.initialize();
}).should.throw('The "initialize" method must be implemented');
});
});

describe('create', () => {
it('should throw when params are given', () => {
(() => {
ProverHandler.create('channel');
}).should.throw('The "create" method must be implemented');
});

it('should throw when params are not given', () => {
(() => {
ProverHandler.create();
}).should.throw('The "create" method must be implemented');
});
});
});
10 changes: 7 additions & 3 deletions test/integration/e2e/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,20 +235,24 @@ test('\n\n***** Token end-to-end flow: non owner transfer fails *****\n\n', asyn
let transferToken;

try {
// create TokenClient for user1 (admin user in org1)
// create TokenClient for user1 (admin user in org1)
const user1ClientObj = await e2eUtils.createTokenClient('org1', channel_name, 'localhost:7051', t);
const user1TokenClient = user1ClientObj.tokenClient;
const user1Identity = user1ClientObj.user.getIdentity();

// create TokenClient for user2 (admin user in org2)
const user2ClientObj = await e2eUtils.createTokenClient('org2', channel_name, 'localhost:8051', t);
// create TokenClient for user2 (admin user in org2), no target peer provided
const user2ClientObj = await e2eUtils.createTokenClient('org2', channel_name, undefined, t);
const user2TokenClient = user2ClientObj.tokenClient;
const user2Identity = user2ClientObj.user.getIdentity();

await resetTokens(user1TokenClient, 'user1', t);
await resetTokens(user2TokenClient, 'user2', t);

// use BasicProverHandler for this test
const req = {proverHandler : 'fabric-client/lib/impl/BasicProverHandler.js'};
user1TokenClient.getChannel().initialize(req);
user2TokenClient.getChannel().initialize(req);

const eventhub = user1TokenClient._channel.getChannelEventHub('localhost:7051');

// build request for user2 to issue a token to user1
Expand Down

0 comments on commit 1dcaf55

Please sign in to comment.