org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChannelClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Send transaction proposal.
 * 
 * @param request
 * @return
 * @throws ProposalException
 * @throws InvalidArgumentException
 */
public Collection<ProposalResponse> sendTransactionProposal(TransactionProposalRequest request)
		throws ProposalException, InvalidArgumentException {
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Sending transaction proposal on channel " + channel.getName());

	Collection<ProposalResponse> response = channel.sendTransactionProposal(request, channel.getPeers());
	for (ProposalResponse pres : response) {
		String stringResponse = new String(pres.getChaincodeActionResponsePayload());
		Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
				"Transaction proposal on channel " + channel.getName() + " " + pres.getMessage() + " "
						+ pres.getStatus() + " with transaction id:" + pres.getTransactionID());
		Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,stringResponse);
	}

	CompletableFuture<TransactionEvent> cf = channel.sendTransaction(response);
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,cf.toString());

	return response;
}
 
Example #2
Source File: FabricResponse.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
public static FabricResponse create(TransactionEvent event) {
	if (event == null) {
		return fail("Invalid transaction event");
	}
	FabricResponse res = new FabricResponse(SUCCESS, null);
	res.setTransactionId(event.getTransactionID());
	return res;
}
 
Example #3
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
CompletableFuture<TransactionEvent> lifecycleApproveChaincodeDefinitionForMyOrg(HFClient client, Channel channel,
                                                                                Collection<Peer> peers, long sequence,
                                                                                String chaincodeName, String chaincodeVersion, LifecycleChaincodeEndorsementPolicy chaincodeEndorsementPolicy, ChaincodeCollectionConfiguration chaincodeCollectionConfiguration, boolean initRequired, String org1ChaincodePackageID) throws InvalidArgumentException, ProposalException {

    LifecycleApproveChaincodeDefinitionForMyOrgRequest lifecycleApproveChaincodeDefinitionForMyOrgRequest = client.newLifecycleApproveChaincodeDefinitionForMyOrgRequest();
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setSequence(sequence);
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeName(chaincodeName);
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeVersion(chaincodeVersion);
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setInitRequired(initRequired);

    if (null != chaincodeCollectionConfiguration) {
        lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeCollectionConfiguration(chaincodeCollectionConfiguration);
    }

    if (null != chaincodeEndorsementPolicy) {
        lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
    }

    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setPackageId(org1ChaincodePackageID);

    Collection<LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse> lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse = channel.sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(lifecycleApproveChaincodeDefinitionForMyOrgRequest,
            peers);

    assertEquals(peers.size(), lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse.size());
    for (LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse response : lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse) {
        final Peer peer = response.getPeer();

        assertEquals(format("failure on %s  message is: %s", peer, response.getMessage()), ChaincodeResponse.Status.SUCCESS, response.getStatus());
        assertFalse(peer + " " + response.getMessage(), response.isInvalid());
        assertTrue(format("failure on %s", peer), response.isVerified());
    }

    return channel.sendTransaction(lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse);

}
 
Example #4
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<TransactionEvent> commitChaincodeDefinitionRequest(HFClient client, Channel channel, long definitionSequence, String chaincodeName, String chaincodeVersion,
                                                                             LifecycleChaincodeEndorsementPolicy chaincodeEndorsementPolicy,
                                                                             ChaincodeCollectionConfiguration chaincodeCollectionConfiguration,
                                                                             boolean initRequired, Collection<Peer> endorsingPeers) throws ProposalException, InvalidArgumentException, InterruptedException, ExecutionException, TimeoutException {
    LifecycleCommitChaincodeDefinitionRequest lifecycleCommitChaincodeDefinitionRequest = client.newLifecycleCommitChaincodeDefinitionRequest();

    lifecycleCommitChaincodeDefinitionRequest.setSequence(definitionSequence);
    lifecycleCommitChaincodeDefinitionRequest.setChaincodeName(chaincodeName);
    lifecycleCommitChaincodeDefinitionRequest.setChaincodeVersion(chaincodeVersion);
    if (null != chaincodeEndorsementPolicy) {
        lifecycleCommitChaincodeDefinitionRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
    }
    if (null != chaincodeCollectionConfiguration) {
        lifecycleCommitChaincodeDefinitionRequest.setChaincodeCollectionConfiguration(chaincodeCollectionConfiguration);
    }
    lifecycleCommitChaincodeDefinitionRequest.setInitRequired(initRequired);

    Collection<LifecycleCommitChaincodeDefinitionProposalResponse> lifecycleCommitChaincodeDefinitionProposalResponses = channel.sendLifecycleCommitChaincodeDefinitionProposal(lifecycleCommitChaincodeDefinitionRequest,
            endorsingPeers);

    for (LifecycleCommitChaincodeDefinitionProposalResponse resp : lifecycleCommitChaincodeDefinitionProposalResponses) {

        final Peer peer = resp.getPeer();
        assertEquals(format("%s had unexpected status.", peer.toString()), ChaincodeResponse.Status.SUCCESS, resp.getStatus());
        assertTrue(format("%s not verified.", peer.toString()), resp.isVerified());
    }

    return channel.sendTransaction(lifecycleCommitChaincodeDefinitionProposalResponses);

}
 
Example #5
Source File: ChannelClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * Instantiate chaincode.
 * 
 * @param chaincodeName
 * @param version
 * @param chaincodePath
 * @param language
 * @param functionName
 * @param functionArgs
 * @param policyPath
 * @return
 * @throws InvalidArgumentException
 * @throws ProposalException
 * @throws ChaincodeEndorsementPolicyParseException
 * @throws IOException
 */
public Collection<ProposalResponse> instantiateChainCode(String chaincodeName, String version, String chaincodePath,
		String language, String functionName, String[] functionArgs, String policyPath)
		throws InvalidArgumentException, ProposalException, ChaincodeEndorsementPolicyParseException, IOException {
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Instantiate proposal request " + chaincodeName + " on channel " + channel.getName()
					+ " with Fabric client " + fabClient.getInstance().getUserContext().getMspId() + " "
					+ fabClient.getInstance().getUserContext().getName());
	InstantiateProposalRequest instantiateProposalRequest = fabClient.getInstance()
			.newInstantiationProposalRequest();
	instantiateProposalRequest.setProposalWaitTime(180000);
	ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(chaincodeName).setVersion(version)
			.setPath(chaincodePath);
	ChaincodeID ccid = chaincodeIDBuilder.build();
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Instantiating Chaincode ID " + chaincodeName + " on channel " + channel.getName());
	instantiateProposalRequest.setChaincodeID(ccid);
	if (language.equals(Type.GO_LANG.toString()))
		instantiateProposalRequest.setChaincodeLanguage(Type.GO_LANG);
	else
		instantiateProposalRequest.setChaincodeLanguage(Type.JAVA);

	instantiateProposalRequest.setFcn(functionName);
	instantiateProposalRequest.setArgs(functionArgs);
	Map<String, byte[]> tm = new HashMap<>();
	tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
	tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
	instantiateProposalRequest.setTransientMap(tm);

	if (policyPath != null) {
		ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
		chaincodeEndorsementPolicy.fromYamlFile(new File(policyPath));
		instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
	}

	Collection<ProposalResponse> responses = channel.sendInstantiationProposal(instantiateProposalRequest);
	CompletableFuture<TransactionEvent> cf = channel.sendTransaction(responses);
	
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Chaincode " + chaincodeName + " on channel " + channel.getName() + " instantiation " + cf);
	return responses;
}
 
Example #6
Source File: TransactionEventException.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * @return the transactionEvent that precipitated this exception
 */
public TransactionEvent getTransactionEvent() {
    return this.transactionEvent;
}
 
Example #7
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
CompletableFuture<TransactionEvent> executeChaincode(HFClient client, User userContext, Channel channel, String fcn, Boolean doInit, String chaincodeName, Type chaincodeType, String... args) throws InvalidArgumentException, ProposalException {

        final ExecutionException[] executionExceptions = new ExecutionException[1];

        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();

        TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
        transactionProposalRequest.setChaincodeName(chaincodeName);
        transactionProposalRequest.setChaincodeLanguage(chaincodeType);
        transactionProposalRequest.setUserContext(userContext);

        transactionProposalRequest.setFcn(fcn);
        transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
        transactionProposalRequest.setArgs(args);
        if (null != doInit) {
            transactionProposalRequest.setInit(doInit);
        }

        //  Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposalToEndorsers(transactionProposalRequest);
        Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());
        for (ProposalResponse response : transactionPropResp) {
            if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                out("Successful transaction proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
                successful.add(response);
            } else {
                failed.add(response);
            }
        }

        out("Received %d transaction proposal responses. Successful+verified: %d . Failed: %d",
                transactionPropResp.size(), successful.size(), failed.size());
        if (failed.size() > 0) {
            ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
            fail("Not enough endorsers for executeChaincode(move a,b,100):" + failed.size() + " endorser error: " +
                    firstTransactionProposalResponse.getMessage() +
                    ". Was verified: " + firstTransactionProposalResponse.isVerified());
        }
        out("Successfully received transaction proposal responses.");

        //  System.exit(10);

        ////////////////////////////
        // Send Transaction Transaction to orderer
        out("Sending chaincode transaction(move a,b,100) to orderer.");
        return channel.sendTransaction(successful);

    }
 
Example #8
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdate1() throws Exception {

    // Setup client and channel instances
    HFClient client = getTheClient();
    Channel channel = constructChannel(client, FOO_CHANNEL_NAME);

    final ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME)
            .setVersion(CHAIN_CODE_VERSION)
            .setPath(CHAIN_CODE_PATH).build();

    final String channelName = channel.getName();

    out("Running testUpdate1 - Channel %s", channelName);

    final Collection<String> peersOrganizationMSPIDs = channel.getPeersOrganizationMSPIDs();
    assertNotNull(peersOrganizationMSPIDs);
    assertEquals(1, peersOrganizationMSPIDs.size());
    assertEquals("Org1MSP", peersOrganizationMSPIDs.iterator().next());

    int moveAmount = 5;
    String originalVal = queryChaincodeForCurrentValue(client, channel, chaincodeID);
    String newVal = "" + (Integer.parseInt(originalVal) + moveAmount);

    out("Original value = %s", originalVal);

    //user registered user
    client.setUserContext(orgRegisteredUsers.get("Org1")); // only using org1

    // Move some assets
    moveAmount(client, channel, chaincodeID, "a", "b", "" + moveAmount, null).thenApply(transactionEvent -> {
        // Check that they were moved
        queryChaincodeForExpectedValue(client, channel, newVal, chaincodeID);
        return null;

    }).thenApply(transactionEvent -> {
        // Move them back
        try {
            return moveAmount(client, channel, chaincodeID, "b", "a", "" + moveAmount, null).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }).thenApply(transactionEvent -> {
        // Check that they were moved back
        queryChaincodeForExpectedValue(client, channel, originalVal, chaincodeID);
        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);

    channel.shutdown(true); // Force channel to shutdown clean up resources.

    out("testUpdate1 - done");
    out("That's all folks!");
}
 
Example #9
Source File: UpdateChannelIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private Channel reconstructChannel(final boolean isSystemChannel, String name, HFClient client, SampleOrg sampleOrg) throws Exception {

        client.setUserContext(isSystemChannel ? ordererAdmin : sampleOrg.getPeerAdmin());
        Channel newChannel = client.newChannel(name);

        for (String orderName : sampleOrg.getOrdererNames()) {
            newChannel.addOrderer(client.newOrderer(orderName, sampleOrg.getOrdererLocation(orderName),
                    testConfig.getOrdererProperties(orderName)));
        }

        if (isSystemChannel) { // done
            newChannel.initialize();
            return newChannel;

        }

        assertTrue(sampleOrg.getPeerNames().size() > 1); // need at least two for testing.

        int i = 0;
        for (String peerName : sampleOrg.getPeerNames()) {
            String peerLocation = sampleOrg.getPeerLocation(peerName);
            Peer peer = client.newPeer(peerName, peerLocation, testConfig.getPeerProperties(peerName));

            //Query the actual peer for which channels it belongs to and check it belongs to this channel
            Set<String> channels = client.queryChannels(peer);
            if (!channels.contains(name)) {
                throw new AssertionError(format("Peer %s does not appear to belong to channel %s", peerName, name));
            }
            Channel.PeerOptions peerOptions = createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.CHAINCODE_QUERY,
                    Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.EVENT_SOURCE));

            if (i % 2 == 0) {
                peerOptions.registerEventsForFilteredBlocks(); // we need a mix of each type for testing.
            } else {
                peerOptions.registerEventsForBlocks();
            }
            ++i;

            newChannel.addPeer(peer, peerOptions);
        }

        //For testing of blocks which are not transactions.
        newChannel.registerBlockListener(blockEvent -> {
            eventQueueCaputure.add(blockEvent); // used with the other queued to make sure same.
            // Note peer eventing will always start with sending the last block so this will get the last endorser block
            int transactions = 0;
            int nonTransactions = 0;
            for (BlockInfo.EnvelopeInfo envelopeInfo : blockEvent.getEnvelopeInfos()) {

                if (BlockInfo.EnvelopeType.TRANSACTION_ENVELOPE == envelopeInfo.getType()) {
                    ++transactions;
                } else {
                    assertEquals(BlockInfo.EnvelopeType.ENVELOPE, envelopeInfo.getType());
                    ++nonTransactions;
                }

            }
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions < 2); // non transaction blocks only have one envelope
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions + transactions > 0); // has to be one.
            assertFalse(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions > 0 && transactions > 0); // can't have both.

            if (nonTransactions > 0) { // this is an update block -- don't care about others here.

                if (blockEvent.isFiltered()) {
                    ++eventCountFilteredBlock; // make sure we're seeing non transaction events.
                } else {
                    ++eventCountBlock;
                }
                assertEquals(0, blockEvent.getTransactionCount());
                assertEquals(1, blockEvent.getEnvelopeCount());
                for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) {
                    fail("Got transaction event in a block update"); // only events for update should not have transactions.
                }
            }
        });

        // Register Queued block listeners just for testing use both ways.
        // Ideally an application would have it's own independent thread to monitor and take off elements as fast as they can.
        // This would wait forever however if event could not be put in the queue like if the capacity is at a maximum. For LinkedBlockingQueue so unlikely
        listenerHandler1 = newChannel.registerBlockListener(blockingQueue1);
        assertNotNull(listenerHandler1);
        // This is the same but put a timeout on it.  If its not queued in time like if the queue is full it would generate a log warning and ignore the event.
        listenerHandler2 = newChannel.registerBlockListener(blockingQueue2, 1L, TimeUnit.SECONDS);
        assertNotNull(listenerHandler2);

        newChannel.initialize();

        return newChannel;
    }
 
Example #10
Source File: TransactionEventException.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * save the TransactionEvent in the exception so that caller can use for debugging
 *
 * @param message
 * @param transactionEvent
 */
public TransactionEventException(String message, TransactionEvent transactionEvent) {
    super(message);
    this.transactionEvent = transactionEvent;
}
 
Example #11
Source File: TransactionEventException.java    From fabric-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * save the TransactionEvent in the exception so that caller can use for debugging
 *
 * @param message
 * @param transactionEvent
 * @param throwable
 */
public TransactionEventException(String message, TransactionEvent transactionEvent, Throwable throwable) {
    super(message, throwable);
    this.transactionEvent = transactionEvent;
}