use of org.hyperledger.fabric.sdk.Peer in project fabric-sdk-java by hyperledger.
the class End2endAndBackAgainIT method runChannel.
// Disable MethodLength as this method is for instructional purposes and hence
// we don't want to split it into smaller pieces
// CHECKSTYLE:OFF: MethodLength
void runChannel(HFClient client, Channel channel, SampleOrg sampleOrg, final int delta) {
final String channelName = channel.getName();
try {
client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
// final boolean changeContext = false; // BAR_CHANNEL_NAME.equals(channel.getName()) ? true : false;
final boolean changeContext = BAR_CHANNEL_NAME.equals(channel.getName());
out("Running Channel %s with a delta %d", channelName, delta);
out("ChaincodeID: ", chaincodeID);
// //////////////////////////
// Send Query Proposal to all peers see if it's what we expect from end of End2endIT
//
queryChaincodeForExpectedValue(client, channel, "" + (300 + delta), chaincodeID);
// Set user context on client but use explicit user contest on each call.
if (changeContext) {
client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
}
// exercise v1 of chaincode
moveAmount(client, channel, chaincodeID, "25", changeContext ? sampleOrg.getPeerAdmin() : null).thenApply((BlockEvent.TransactionEvent transactionEvent) -> {
try {
waitOnFabric();
client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
queryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);
// ////////////////
// Start of upgrade first must install it.
client.setUserContext(sampleOrg.getPeerAdmin());
// /////////////
// //
InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
installProposalRequest.setChaincodeID(chaincodeID);
// //For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
installProposalRequest.setChaincodeSourceLocation(Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile());
installProposalRequest.setChaincodeVersion(CHAIN_CODE_VERSION_11);
installProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
installProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
if (changeContext) {
installProposalRequest.setUserContext(sampleOrg.getPeerAdmin());
}
out("Sending install proposal for channel: %s", channel.getName());
// //////////////////////////
// only a client from the same org as the peer can issue an install request
int numInstallProposal = 0;
Collection<ProposalResponse> responses;
final Collection<ProposalResponse> successful = new LinkedList<>();
final Collection<ProposalResponse> failed = new LinkedList<>();
Collection<Peer> peersFromOrg = channel.getPeers();
numInstallProposal = numInstallProposal + peersFromOrg.size();
responses = client.sendInstallProposal(installProposalRequest, peersFromOrg);
for (ProposalResponse response : responses) {
if (response.getStatus() == Status.SUCCESS) {
out("Successful install proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
successful.add(response);
} else {
failed.add(response);
}
}
out("Received %d install proposal responses. Successful+verified: %d . Failed: %d", numInstallProposal, successful.size(), failed.size());
if (failed.size() > 0) {
ProposalResponse first = failed.iterator().next();
fail("Not enough endorsers for install :" + successful.size() + ". " + first.getMessage());
}
if (changeContext) {
installProposalRequest.setUserContext(sampleOrg.getPeerAdmin());
}
UpgradeProposalRequest upgradeProposalRequest = client.newUpgradeProposalRequest();
upgradeProposalRequest.setChaincodeID(chaincodeID_11);
upgradeProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
upgradeProposalRequest.setFcn("init");
// no arguments don't change the ledger see chaincode.
upgradeProposalRequest.setArgs(new String[] {});
ChaincodeEndorsementPolicy chaincodeEndorsementPolicy;
chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
chaincodeEndorsementPolicy.fromYamlFile(new File(TEST_FIXTURES_PATH + "/sdkintegration/chaincodeendorsementpolicy.yaml"));
upgradeProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
Map<String, byte[]> tmap = new HashMap<>();
tmap.put("test", "data".getBytes());
upgradeProposalRequest.setTransientMap(tmap);
if (changeContext) {
upgradeProposalRequest.setUserContext(sampleOrg.getPeerAdmin());
}
out("Sending upgrade proposal");
Collection<ProposalResponse> responses2;
responses2 = channel.sendUpgradeProposal(upgradeProposalRequest);
successful.clear();
failed.clear();
for (ProposalResponse response : responses2) {
if (response.getStatus() == Status.SUCCESS) {
out("Successful upgrade proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
successful.add(response);
} else {
failed.add(response);
}
}
out("Received %d upgrade proposal responses. Successful+verified: %d . Failed: %d", channel.getPeers().size(), successful.size(), failed.size());
if (failed.size() > 0) {
ProposalResponse first = failed.iterator().next();
throw new AssertionError("Not enough endorsers for upgrade :" + successful.size() + ". " + first.getMessage());
}
if (changeContext) {
return channel.sendTransaction(successful, sampleOrg.getPeerAdmin()).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
} else {
return channel.sendTransaction(successful).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
}
} catch (CompletionException e) {
throw e;
} catch (Exception e) {
throw new CompletionException(e);
}
}).thenApply(transactionEvent -> {
try {
waitOnFabric(10000);
out("Chaincode has been upgraded to version %s", CHAIN_CODE_VERSION_11);
// Check to see if peers have new chaincode and old chaincode is gone.
client.setUserContext(sampleOrg.getPeerAdmin());
for (Peer peer : channel.getPeers()) {
if (!checkInstalledChaincode(client, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11)) {
throw new AssertionError(format("Peer %s is missing chaincode name:%s, path:%s, version: %s", peer.getName(), CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_PATH));
}
// should be instantiated too..
if (!checkInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11)) {
throw new AssertionError(format("Peer %s is missing instantiated chaincode name:%s, path:%s, version: %s", peer.getName(), CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_PATH));
}
if (checkInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION)) {
throw new AssertionError(format("Peer %s still has old instantiated chaincode name:%s, path:%s, version: %s", peer.getName(), CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_PATH));
}
}
client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
// /Check if we still get the same value on the ledger
out("delta is %s", delta);
queryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);
// Now lets run the new chaincode which should *double* the results we asked to move.
return moveAmount(client, channel, chaincodeID_11, "50", changeContext ? sampleOrg.getPeerAdmin() : null).get(testConfig.getTransactionWaitTime(), // really move 100
TimeUnit.SECONDS);
} catch (CompletionException e) {
throw e;
} catch (Exception e) {
throw new CompletionException(e);
}
}).thenApply(transactionEvent -> {
waitOnFabric(10000);
queryChaincodeForExpectedValue(client, channel, "" + (425 + delta), chaincodeID_11);
return null;
}).exceptionally(e -> {
if (e instanceof CompletionException && e.getCause() != null) {
e = e.getCause();
}
if (e instanceof TransactionEventException) {
BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent();
if (te != null) {
e.printStackTrace(System.err);
fail(format("Transaction with txid %s failed. %s", te.getTransactionID(), e.getMessage()));
}
}
e.printStackTrace(System.err);
fail(format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()));
return null;
}).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
} catch (Exception e) {
throw new RuntimeException(e);
}
out("Running for Channel %s done", channelName);
}
use of org.hyperledger.fabric.sdk.Peer in project fabric-sdk-java by hyperledger.
the class End2endAndBackAgainIT method testPeerServiceEventingReplay.
/**
* This code test the replay feature of the new peer event services.
* Instead of the default of starting the eventing peer to retrieve the newest block it sets it
* retrieve starting from the start parameter. Also checks with block and filterblock replays.
* Depends on end2end and end2endAndBackagain of have fully run to have the blocks need to work with.
*
* @param client
* @param replayTestChannel
* @param start
* @param stop
* @param useFilteredBlocks
* @throws InvalidArgumentException
*/
private void testPeerServiceEventingReplay(HFClient client, Channel replayTestChannel, final long start, final long stop, final boolean useFilteredBlocks) throws InvalidArgumentException {
if (testConfig.isRunningAgainstFabric10()) {
// not supported for v1.0
return;
}
// not yet initialized
assertFalse(replayTestChannel.isInitialized());
// not yet shutdown.
assertFalse(replayTestChannel.isShutdown());
// Remove all peers just have one ledger peer and one eventing peer.
List<Peer> savedPeers = new ArrayList<>(replayTestChannel.getPeers());
for (Peer peer : savedPeers) {
replayTestChannel.removePeer(peer);
}
// need at least two
assertTrue(savedPeers.size() > 1);
final Peer eventingPeer = savedPeers.remove(0);
Peer ledgerPeer = savedPeers.remove(0);
// no more peers.
assertTrue(replayTestChannel.getPeers().isEmpty());
// just checking :)
assertTrue(replayTestChannel.getPeers(EnumSet.of(PeerRole.CHAINCODE_QUERY, PeerRole.ENDORSING_PEER)).isEmpty());
// just checking
assertTrue(replayTestChannel.getPeers(EnumSet.of(PeerRole.LEDGER_QUERY)).isEmpty());
// should be known by client.
assertNotNull(client.getChannel(replayTestChannel.getName()));
final PeerOptions eventingPeerOptions = createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.EVENT_SOURCE));
if (useFilteredBlocks) {
eventingPeerOptions.registerEventsForFilteredBlocks();
}
if (-1L == stop) {
// the height of the blockchain
// Eventing peer start getting blocks from block 0
replayTestChannel.addPeer(eventingPeer, eventingPeerOptions.startEvents(start));
} else {
replayTestChannel.addPeer(eventingPeer, eventingPeerOptions.startEvents(start).stopEvents(// Eventing peer start getting blocks from block 0
stop));
}
// add a ledger peer
replayTestChannel.addPeer(ledgerPeer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.LEDGER_QUERY)));
// future to set when done.
CompletableFuture<Long> done = new CompletableFuture<>();
// some variable used by the block listener being set up.
final AtomicLong bcount = new AtomicLong(0);
final AtomicLong stopValue = new AtomicLong(stop == -1L ? Long.MAX_VALUE : stop);
final Channel finalChannel = replayTestChannel;
final Map<Long, BlockEvent> blockEvents = Collections.synchronizedMap(new HashMap<>(100));
final String blockListenerHandle = replayTestChannel.registerBlockListener(blockEvent -> {
try {
final long blockNumber = blockEvent.getBlockNumber();
BlockEvent seen = blockEvents.put(blockNumber, blockEvent);
assertNull(format("Block number %d seen twice", blockNumber), seen);
assertTrue(format("Wrong type of block seen block number %d. expected filtered block %b but got %b", blockNumber, useFilteredBlocks, blockEvent.isFiltered()), useFilteredBlocks ? blockEvent.isFiltered() : !blockEvent.isFiltered());
// count starts with 0 not 1 !
final long count = bcount.getAndIncrement();
if (count == 0 && stop == -1L) {
final BlockchainInfo blockchainInfo = finalChannel.queryBlockchainInfo();
long lh = blockchainInfo.getHeight();
// blocks 0L 9L are on chain height 10 .. stop on 9
stopValue.set(lh - 1L);
// out("height: %d", lh);
if (bcount.get() + start > stopValue.longValue()) {
// test with latest count.
// report back latest count.
done.complete(bcount.get());
}
} else {
if (bcount.longValue() + start > stopValue.longValue()) {
done.complete(count);
}
}
} catch (AssertionError | Exception e) {
e.printStackTrace();
done.completeExceptionally(e);
}
});
try {
// start it all up.
replayTestChannel.initialize();
// give a timeout here.
done.get(30, TimeUnit.SECONDS);
// sleep a little to see if more blocks trickle in .. they should not
Thread.sleep(1000);
replayTestChannel.unregisterBlockListener(blockListenerHandle);
// Start 2 and stop is 3 expect 2
final long expectNumber = stopValue.longValue() - start + 1L;
assertEquals(format("Didn't get number we expected %d but got %d block events. Start: %d, end: %d, height: %d", expectNumber, blockEvents.size(), start, stop, stopValue.longValue()), expectNumber, blockEvents.size());
for (long i = stopValue.longValue(); i >= start; i--) {
// make sure all are there.
final BlockEvent blockEvent = blockEvents.get(i);
assertNotNull(format("Missing block event for block number %d. Start= %d", i, start), blockEvent);
}
// light weight test just see if we get reasonable values for traversing the block. Test just whats common between
// Block and FilteredBlock.
int transactionEventCounts = 0;
int chaincodeEventsCounts = 0;
for (long i = stopValue.longValue(); i >= start; i--) {
final BlockEvent blockEvent = blockEvents.get(i);
// out("blockwalker %b, start: %d, stop: %d, i: %d, block %d", useFilteredBlocks, start, stopValue.longValue(), i, blockEvent.getBlockNumber());
// check again
assertEquals(useFilteredBlocks, blockEvent.isFiltered());
if (useFilteredBlocks) {
// should not have raw block event.
assertNull(blockEvent.getBlock());
// should have raw filtered block.
assertNotNull(blockEvent.getFilteredBlock());
} else {
// should not have raw block event.
assertNotNull(blockEvent.getBlock());
// should have raw filtered block.
assertNull(blockEvent.getFilteredBlock());
}
assertEquals(replayTestChannel.getName(), blockEvent.getChannelId());
for (BlockInfo.EnvelopeInfo envelopeInfo : blockEvent.getEnvelopeInfos()) {
if (envelopeInfo.getType() == TRANSACTION_ENVELOPE) {
BlockInfo.TransactionEnvelopeInfo transactionEnvelopeInfo = (BlockInfo.TransactionEnvelopeInfo) envelopeInfo;
// only have valid blocks.
assertTrue(envelopeInfo.isValid());
assertEquals(envelopeInfo.getValidationCode(), 0);
++transactionEventCounts;
for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo ta : transactionEnvelopeInfo.getTransactionActionInfos()) {
// out("\nTA:", ta + "\n\n");
ChaincodeEvent event = ta.getEvent();
if (event != null) {
assertNotNull(event.getChaincodeId());
assertNotNull(event.getEventName());
chaincodeEventsCounts++;
}
}
} else {
assertEquals("Only non transaction block should be block 0.", blockEvent.getBlockNumber(), 0);
}
}
}
assertTrue(transactionEventCounts > 0);
if (expectNumber > 4) {
// this should be enough blocks with CC events.
assertTrue(chaincodeEventsCounts > 0);
}
// all done.
replayTestChannel.shutdown(true);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
use of org.hyperledger.fabric.sdk.Peer in project fabric-sdk-java by hyperledger.
the class NetworkConfigIT method deployChaincodeIfRequired.
// Determines whether or not the chaincode has been deployed and deploys it if necessary
private static void deployChaincodeIfRequired() throws Exception {
// //////////////////////////
// Setup client
HFClient client = getTheClient();
Channel channel = constructChannel(client, FOO_CHANNEL_NAME);
// Use any old peer...
Peer peer = channel.getPeers().iterator().next();
if (!checkInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION)) {
// The chaincode we require does not exist, so deploy it...
deployChaincode(client, channel, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION);
}
}
Aggregations