Java Code Examples for org.hyperledger.fabric.sdk.ProposalResponse#getStatus()

The following examples show how to use org.hyperledger.fabric.sdk.ProposalResponse#getStatus() . 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: FabricQueryResponse.java    From spring-fabric-gateway with MIT License 6 votes vote down vote up
public static <T> FabricQueryResponse<T> create(ProposalResponse res, Class<T> type) {
	Status status = res.getStatus();
	if (status != Status.SUCCESS) {
		return failure(res.getMessage());
	} else {
		if (type != null) {
			try {
				int chaincodeStatus = res.getChaincodeActionResponseStatus();
				if (chaincodeStatus != -1) {

					byte[] payload = res.getChaincodeActionResponsePayload();
					return create(payload, type);
				} else {
					return failure("Chaincode executed failure.");
				}
			} catch (InvalidArgumentException e) {
				return failure("Chaincode error: " + e.getMessage());
			}
		} else {
			return success(null);
		}
	}
}
 
Example 2
Source File: FabricQueryResponse.java    From spring-fabric-gateway with MIT License 6 votes vote down vote up
public static <T> FabricQueryResponse<List<T>> many(ProposalResponse res, Class<T> type) {
	Status status = res.getStatus();
	if (status != Status.SUCCESS) {
		return failure(res.getMessage());
	} else {
		if (type != null) {
			try {
				int chaincodeStatus = res.getChaincodeActionResponseStatus();
				if (chaincodeStatus != -1) {
					byte[] payload = res.getChaincodeActionResponsePayload();
					return parsePayloadMany(new String(payload, Charset.forName("utf-8")), type);
				} else {
					return failure("Chaincode executed failure.");
				}
			} catch (InvalidArgumentException e) {
				return failure("Chaincode error: " + e.getMessage());
			}
		} else {
			return success(null);
		}
	}
}
 
Example 3
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
void executeVerifyByQuery(HFClient client, Channel channel, String chaincodeName, String expect) throws ProposalException, InvalidArgumentException {
    out("Now query chaincode for the value of b.");
    QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
    queryByChaincodeRequest.setArgs("b");
    queryByChaincodeRequest.setFcn("query");
    queryByChaincodeRequest.setChaincodeName(chaincodeName);

    Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers());
    for (ProposalResponse proposalResponse : queryProposals) {
        if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
            fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                    ". Messages: " + proposalResponse.getMessage()
                    + ". Was verified : " + proposalResponse.isVerified());
        } else {
            String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
            out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
            assertEquals(expect, payload);
        }
    }

}
 
Example 4
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static BlockEvent.TransactionEvent sendTransaction(Channel channel, Collection<ProposalResponse> propResp, Long transactionTimeout) throws InvalidArgumentException, InterruptedException, ExecutionException, TimeoutException {
    List<ProposalResponse> successful = new LinkedList<>();
    List<ProposalResponse> failed = new LinkedList<>();
    for (ProposalResponse response : propResp) {
        if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
            String payload = new String(response.getChaincodeActionResponsePayload());
            log.debug("[√] Got success response from peer:{}, payload:{}", response.getPeer().getName(), payload);
            successful.add(response);
        } else {
            String status = response.getStatus().toString();
            String msg = response.getMessage();
            log.error("[×] Got failed response from peer:{}, status:{}, error message:{} ", response.getPeer().getName(), status, msg);
            failed.add(response);
        }
    }

    CompletableFuture<BlockEvent.TransactionEvent> carfuture = channel.sendTransaction(successful);
    return carfuture.get(transactionTimeout, TimeUnit.MILLISECONDS);
}
 
Example 5
Source File: End2endAndBackAgainIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void queryChaincodeForExpectedValue(HFClient client, Channel channel, final String expect, ChaincodeID chaincodeID) {

        out("Now query chaincode %s on channel %s for the value of b expecting to see: %s", chaincodeID, channel.getName(), expect);
        QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
        queryByChaincodeRequest.setArgs("b".getBytes(UTF_8)); // test using bytes as args. End2end uses Strings.
        queryByChaincodeRequest.setFcn("query");
        queryByChaincodeRequest.setChaincodeID(chaincodeID);

        Collection<ProposalResponse> queryProposals;

        try {
            queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
        } catch (Exception e) {
            throw new CompletionException(e);
        }

        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != Status.SUCCESS) {
                fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                        ". Messages: " + proposalResponse.getMessage()
                        + ". Was verified : " + proposalResponse.isVerified());
            } else {
                String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                assertEquals(format("Failed compare on channel %s chaincode id %s expected value:'%s', but got:'%s'",
                        channel.getName(), chaincodeID, expect, payload), expect, payload);
            }
        }
    }
 
Example 6
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private static String queryChaincodeForCurrentValue(HFClient client, Channel channel, ChaincodeID chaincodeID) {

        out("Now query chaincode on channel %s for the current value of b", channel.getName());

        QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
        queryByChaincodeRequest.setArgs("b");
        queryByChaincodeRequest.setFcn("query");
        queryByChaincodeRequest.setChaincodeID(chaincodeID);

        Collection<ProposalResponse> queryProposals;

        try {
            queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
        } catch (Exception e) {
            throw new CompletionException(e);
        }

        String expect = null;
        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != Status.SUCCESS) {
                fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                        ". Messages: " + proposalResponse.getMessage()
                        + ". Was verified : " + proposalResponse.isVerified());
            } else {
                String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                if (expect != null) {
                    assertEquals(expect, payload);
                } else {
                    expect = payload;
                }
            }
        }
        return expect;
    }
 
Example 7
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
/**
 * 查询智能合约
 * 
 * @param fcn
 *            方法名
 * @param args
 *            参数数组
 * @return
 * @throws InvalidArgumentException
 * @throws ProposalException
 * @throws IOException 
 * @throws TransactionException 
 * @throws CryptoException 
 * @throws InvalidKeySpecException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 */
public Map<String, String> query(String fcn, String[] args) throws InvalidArgumentException, ProposalException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException {
	Map<String, String> resultMap = new HashMap<>();
	String payload = "";
	QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
	queryByChaincodeRequest.setArgs(args);
	queryByChaincodeRequest.setFcn(fcn);
	queryByChaincodeRequest.setChaincodeID(chaincodeID);

	Map<String, byte[]> tm2 = new HashMap<>();
	tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
	tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
	queryByChaincodeRequest.setTransientMap(tm2);

	Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers());
	for (ProposalResponse proposalResponse : queryProposals) {
		if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
			log.debug("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: "
					+ proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified());
			resultMap.put("code", "error");
			resultMap.put("data", "Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: "
					+ proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified());
		} else {
			payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
			log.debug("Query payload from peer: " + proposalResponse.getPeer().getName());
			log.debug("TransactionID: " + proposalResponse.getTransactionID());
			log.debug("" + payload);
			resultMap.put("code", "success");
			resultMap.put("data", payload);
			resultMap.put("txid", proposalResponse.getTransactionID());
		}
	}
	return resultMap;
}
 
Example 8
Source File: PrivateDataIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void queryChaincodeForExpectedValue(HFClient client, Channel channel, final String expect, ChaincodeID chaincodeID) {

        out("Now query chaincode %s on channel %s for the value of b expecting to see: %s", chaincodeID, channel.getName(), expect);
        Collection<ProposalResponse> queryProposals;
        try {
            QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
            queryByChaincodeRequest.setFcn("query");
            queryByChaincodeRequest.setChaincodeID(chaincodeID);

            Map<String, byte[]> tmap = new HashMap<>();
            tmap.put("B", "b".getBytes(UTF_8)); // test using bytes as args. End2end uses Strings.
            queryByChaincodeRequest.setTransientMap(tmap);

            queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
        } catch (Exception e) {
            throw new CompletionException(e);
        }

        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != Status.SUCCESS) {
                fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                        ". Messages: " + proposalResponse.getMessage()
                        + ". Was verified : " + proposalResponse.isVerified());
            } else {
                String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                assertEquals(format("Failed compare on channel %s chaincode id %s expected value:'%s', but got:'%s'",
                        channel.getName(), chaincodeID, expect, payload), expect, payload);
            }
        }
    }
 
Example 9
Source File: End2endAndBackAgainIT.java    From fabric_sdk_java_study with Apache License 2.0 5 votes vote down vote up
private void queryChaincodeForExpectedValue(HFClient client, Channel channel, final String expect, ChaincodeID chaincodeID) {

        out("Now query chaincode on channel %s for the value of b expecting to see: %s", channel.getName(), expect);
        QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
        queryByChaincodeRequest.setArgs(new String[] {"query", "b"});
        queryByChaincodeRequest.setFcn("invoke");
        queryByChaincodeRequest.setChaincodeID(chaincodeID);

        Collection<ProposalResponse> queryProposals;

        try {
            queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
        } catch (Exception e) {
            throw new CompletionException(e);
        }

        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != Status.SUCCESS) {
                fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                        ". Messages: " + proposalResponse.getMessage()
                        + ". Was verified : " + proposalResponse.isVerified());
            } else {
                String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                assertEquals(payload, expect);
            }
        }
    }
 
Example 10
Source File: ChaincodeServiceImpl.java    From balance-transfer-java with Apache License 2.0 4 votes vote down vote up
/**
 * installs the chaincode takes as input chaincode name returns status as
 * string
 */
public String installChaincode(String chaincodeName) {

	try {
		checkConfig();

		chaincodeID = getChaincodeId(chaincodeName);
		Org sampleOrg = Conf.getSampleOrg("peerOrg1");
		Channel channel = reconstructChannel();
		final String channelName = channel.getName();
		boolean isFooChain = channelName.equals(channelName);
		logger.info("Running channel %s", channelName);
		Collection<Peer> channelPeers = channel.getPeers();
		Collection<Orderer> orderers = channel.getOrderers();

		client.setUserContext(sampleOrg.getPeerAdmin());
		logger.info("Creating install proposal");
		InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
		installProposalRequest.setChaincodeID(chaincodeID);
		installProposalRequest.setChaincodeSourceLocation(new File(PATH + "/artifacts/"));
		installProposalRequest.setChaincodeVersion(chainCodeVersion);
		logger.info("Sending install proposal");
		int numInstallProposal = 0;

		Set<Peer> peersFromOrg = sampleOrg.getPeers();
		numInstallProposal = numInstallProposal + peersFromOrg.size();
		responses = client.sendInstallProposal(installProposalRequest, peersFromOrg);
		for (ProposalResponse response : responses) {
			if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
				out("Successful install proposal response Txid: %s from peer %s", response.getTransactionID(),
						response.getPeer().getName());
				successful.add(response);
			} else {
				failed.add(response);
			}
		}
		SDKUtils.getProposalConsistencySets(responses);
		// }
		logger.info("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());
			return "Not enough endorsers for install :" + successful.size() + ".  " + first.getMessage();
		}

		return "Chaincode installed successfully";

	} catch (Exception e) {
		logger.error("ChaincodeServiceImpl | installChaincode | " +e.getMessage());
		return "Chaincode installation failed";
	}

}
 
Example 11
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 12
Source File: PrivateDataIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
CompletableFuture<BlockEvent.TransactionEvent> setAmount(HFClient client, Channel channel, ChaincodeID chaincodeID, int delta, User user) {

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

            ///////////////
            /// Send transaction proposal to all peers
            TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
            transactionProposalRequest.setChaincodeID(chaincodeID);
            transactionProposalRequest.setFcn("set");

            Map<String, byte[]> transientMap = new HashMap<>();
            transientMap.put("A", "a".getBytes(UTF_8));   // test using bytes as args. End2end uses Strings.
            transientMap.put("AVal", "500".getBytes(UTF_8));
            transientMap.put("B", "b".getBytes(UTF_8));
            String arg3 = "" + (200 + delta);
            transientMap.put("BVal", arg3.getBytes(UTF_8));
            transactionProposalRequest.setTransientMap(transientMap);

            transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
            if (user != null) { // specific user use that
                transactionProposalRequest.setUserContext(user);
            }

            Collection<ProposalResponse> invokePropResp = channel.sendTransactionProposal(transactionProposalRequest);
            for (ProposalResponse response : invokePropResp) {
                if (response.getStatus() == 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 for setAmount. Successful+verified: %d . Failed: %d",
                    invokePropResp.size(), successful.size(), failed.size());
            if (failed.size() > 0) {
                ProposalResponse firstTransactionProposalResponse = failed.iterator().next();

                throw new ProposalException(format("Not enough endorsers for set(move a,b,%s):%d endorser error:%s. Was verified:%b",
                        0, firstTransactionProposalResponse.getStatus().getStatus(), firstTransactionProposalResponse.getMessage(), firstTransactionProposalResponse.isVerified()));

            }
            out("Successfully received transaction proposal responses for setAmount. Now sending to orderer.");

            ////////////////////////////
            // Send transaction to orderer

            if (user != null) {
                return channel.sendTransaction(successful, user);
            }
            return channel.sendTransaction(successful);
        } catch (Exception e) {

            throw new CompletionException(e);

        }

    }
 
Example 13
Source File: ChaincodeServiceImpl.java    From balance-transfer-java with Apache License 2.0 4 votes vote down vote up
/**
 * queries the chaincode takes input chaincode name, function and args
 * returns payload from blockchain as string
 */
public String queryChaincode(String name, String chaincodeFunction, String[] chaincodeArgs) {
	try {
		checkConfig();

		chaincodeID = getChaincodeId(name);
		Channel channel = reconstructChannel();
		logger.debug("Now query chaincode for the value of b.");
		logger.debug(chaincodeFunction);
		QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();


		queryByChaincodeRequest.setArgs(chaincodeArgs);
		queryByChaincodeRequest.setFcn(chaincodeFunction);
		queryByChaincodeRequest.setChaincodeID(chaincodeID);

		Map<String, byte[]> tm2 = new HashMap<>();
		tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
		tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
		queryByChaincodeRequest.setTransientMap(tm2);


		Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest,
				channel.getPeers());


		for (ProposalResponse proposalResponse : queryProposals) {
			if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
				logger.debug("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: "
						+ proposalResponse.getStatus() + ". Messages: " + proposalResponse.getMessage()
						+ ". Was verified : " + proposalResponse.isVerified());
			} else {

				String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();

				return payload;
			}

		}

	} catch (Exception e) {
		logger.error("ChaincodeServiceImpl | queryChaincode | " +e.getMessage());
	}
	return "Caught an exception while quering chaincode"; 
}
 
Example 14
Source File: InvokeChaincode.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {
	try {
           Util.cleanUp();
		String caUrl = Config.CA_ORG1_URL;
		CAClient caClient = new CAClient(caUrl, null);
		// Enroll Admin to Org1MSP
		UserContext adminUserContext = new UserContext();
		adminUserContext.setName(Config.ADMIN);
		adminUserContext.setAffiliation(Config.ORG1);
		adminUserContext.setMspId(Config.ORG1_MSP);
		caClient.setAdminUserContext(adminUserContext);
		adminUserContext = caClient.enrollAdminUser(Config.ADMIN, Config.ADMIN_PASSWORD);
		
		FabricClient fabClient = new FabricClient(adminUserContext);
		
		ChannelClient channelClient = fabClient.createChannelClient(Config.CHANNEL_NAME);
		Channel channel = channelClient.getChannel();
		Peer peer = fabClient.getInstance().newPeer(Config.ORG1_PEER_0, Config.ORG1_PEER_0_URL);
		EventHub eventHub = fabClient.getInstance().newEventHub("eventhub01", "grpc://localhost:7053");
		Orderer orderer = fabClient.getInstance().newOrderer(Config.ORDERER_NAME, Config.ORDERER_URL);
		channel.addPeer(peer);
		channel.addEventHub(eventHub);
		channel.addOrderer(orderer);
		channel.initialize();

		TransactionProposalRequest request = fabClient.getInstance().newTransactionProposalRequest();
		ChaincodeID ccid = ChaincodeID.newBuilder().setName(Config.CHAINCODE_1_NAME).build();
		request.setChaincodeID(ccid);
		request.setFcn("createCar");
		String[] arguments = { "CAR1", "Chevy", "Volt", "Red", "Nick" };
		request.setArgs(arguments);
		request.setProposalWaitTime(1000);

		Map<String, byte[]> tm2 = new HashMap<>();
		tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8)); 																								
		tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8)); 
		tm2.put("result", ":)".getBytes(UTF_8));
		tm2.put(EXPECTED_EVENT_NAME, EXPECTED_EVENT_DATA); 
		request.setTransientMap(tm2);
		Collection<ProposalResponse> responses = channelClient.sendTransactionProposal(request);
		for (ProposalResponse res: responses) {
			Status status = res.getStatus();
			Logger.getLogger(InvokeChaincode.class.getName()).log(Level.INFO,"Invoked createCar on "+Config.CHAINCODE_1_NAME + ". Status - " + status);
		}
								
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 15
Source File: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
public String queryChaincode(String chaincodename, String chaincodeFunction, String[] chaincodeArgs) {
    try {
        checkConfig();

        ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(chaincodename).build();
        logger.info("Channel Name is " + channel.getName());
        logger.debug(String.format("Querying chaincode %s and function %s with arguments %s", chaincodename,
                chaincodeFunction, Arrays.asList(chaincodeArgs).toString()));

        QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
        queryByChaincodeRequest.setArgs(chaincodeArgs);
        queryByChaincodeRequest.setFcn(chaincodeFunction);
        queryByChaincodeRequest.setChaincodeID(chaincodeID);

        Map<String, byte[]> tm2 = new HashMap<>();
        tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
        tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
        queryByChaincodeRequest.setTransientMap(tm2);
        logger.debug("Chaincode request args:- " + queryByChaincodeRequest.getArgs().toString());
        Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest,
                channel.getPeers());

        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
                String errorMsg = "Failed query proposal from peer " + proposalResponse.getPeer().getName()
                        + " status: " + proposalResponse.getStatus() + ". Messages: "
                        + proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified();
                logger.debug(errorMsg);
                throw new BlkchnException(errorMsg);
            } else {
                return proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
            }

        }

    } catch (Exception e) {
        logger.error("QueryBlock | queryChaincode | " + e.getMessage());
        throw new BlkchnException(e);
    }
    throw new BlkchnException("Caught an exception while quering chaincode");
}
 
Example 16
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
/**
	 * 执行智能合约
	 * 
	 * @param fcn
	 *            方法名
	 * @param args
	 *            参数数组
	 * @return
	 * @throws InvalidArgumentException
	 * @throws ProposalException
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws TimeoutException
	 * @throws IOException 
	 * @throws TransactionException 
	 * @throws CryptoException 
	 * @throws InvalidKeySpecException 
	 * @throws NoSuchProviderException 
	 * @throws NoSuchAlgorithmException 
	 */
	public Map<String, String> invoke(String fcn, String[] args)
			throws InvalidArgumentException, ProposalException, InterruptedException, ExecutionException, TimeoutException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException {
		Map<String, String> resultMap = new HashMap<>();

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

		/// Send transaction proposal to all peers
		TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
		transactionProposalRequest.setChaincodeID(chaincodeID);
		transactionProposalRequest.setFcn(fcn);
		transactionProposalRequest.setArgs(args);

		Map<String, byte[]> tm2 = new HashMap<>();
		tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8));
		tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8));
		tm2.put("result", ":)".getBytes(UTF_8));
		transactionProposalRequest.setTransientMap(tm2);

		long currentStart = System.currentTimeMillis();
		Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());
		for (ProposalResponse response : transactionPropResp) {
			if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
				successful.add(response);
			} else {
				failed.add(response);
			}
		}
		log.info("channel send transaction proposal time = " + ( System.currentTimeMillis() - currentStart));

		Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(transactionPropResp);
		if (proposalConsistencySets.size() != 1) {
			log.error("Expected only one set of consistent proposal responses but got " + proposalConsistencySets.size());
		}

		if (failed.size() > 0) {
			ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
			log.error("Not enough endorsers for inspect:" + failed.size() + " endorser error: " + firstTransactionProposalResponse.getMessage() + ". Was verified: "
					+ firstTransactionProposalResponse.isVerified());
			resultMap.put("code", "error");
			resultMap.put("data", firstTransactionProposalResponse.getMessage());
			return resultMap;
		} else {
			log.info("Successfully received transaction proposal responses.");
			ProposalResponse resp = transactionPropResp.iterator().next();
			log.debug("TransactionID: " + resp.getTransactionID());
			byte[] x = resp.getChaincodeActionResponsePayload();
			String resultAsString = null;
			if (x != null) {
				resultAsString = new String(x, "UTF-8");
			}
			log.info("resultAsString = " + resultAsString);
			channel.sendTransaction(successful);
			resultMap.put("code", "success");
			resultMap.put("data", resultAsString);
			resultMap.put("txid", resp.getTransactionID());
			return resultMap;
		}

//		channel.sendTransaction(successful).thenApply(transactionEvent -> {
//			if (transactionEvent.isValid()) {
//				log.info("Successfully send transaction proposal to orderer. Transaction ID: " + transactionEvent.getTransactionID());
//			} else {
//				log.info("Failed to send transaction proposal to orderer");
//			}
//			// chain.shutdown(true);
//			return transactionEvent.getTransactionID();
//		}).get(chaincode.getInvokeWatiTime(), TimeUnit.SECONDS);
	}
 
Example 17
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
public static CompletableFuture<TransactionInfo> executeTransactionAsync(HFClient client, Channel channel, ChaincodeID chaincodeID, boolean invoke, String func,
                                                                         String... args) throws InvalidArgumentException, ProposalException {
    TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
    transactionProposalRequest.setChaincodeID(chaincodeID);
    transactionProposalRequest.setChaincodeLanguage(TransactionRequest.Type.GO_LANG);

    transactionProposalRequest.setFcn(func);
    transactionProposalRequest.setArgs(args);
    transactionProposalRequest.setProposalWaitTime(120000);

    List<ProposalResponse> successful = new LinkedList<>();
    List<ProposalResponse> failed = new LinkedList<>();
    // there is no need to retry. If not, you should re-send the transaction proposal.
    Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest);
    TransactionInfo transactionInfo = new TransactionInfo();
    boolean result = true;
    for (ProposalResponse response : transactionPropResp) {
        if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
            transactionInfo.setCode(ErrorCode.SUCCESS.getCode());
            transactionInfo.setPayLoad(new String(response.getChaincodeActionResponsePayload()));
            log.info("[√] Got success response from peer:{} , payload:{}", response.getPeer().getName(), transactionInfo.getPayLoad());
            successful.add(response);
        } else {
            result = false;
            transactionInfo.setCode(ErrorCode.FABRICSDK_CHAINCODE_INVOKE_FAILED.getCode());
            transactionInfo.setMessage(response.getMessage());
            String status = response.getStatus().toString();
            log.error("[×] Got failed response from peer:{}, status:{}, error message:{}", response.getPeer().getName(), status, transactionInfo.getMessage());
            failed.add(response);
        }
    }

    if (invoke && result) {
        log.info("Sending transaction to orders...");
        return channel.sendTransaction(successful).thenApply(
                (transactionEvent) -> {
                    log.info("Wait event return: {} {} {} {}",
                            transactionEvent.getChannelId(),
                            transactionEvent.getTransactionID(),
                            transactionEvent.getType(),
                            transactionEvent.getValidationCode());
                    transactionInfo.setBlockNumber(transactionEvent.getBlockEvent().getBlockNumber());
                    return transactionInfo;
                });
    }

    CompletableFuture<TransactionInfo> completableFuture = new CompletableFuture<>();
    completableFuture.complete(transactionInfo);
    return completableFuture;
}
 
Example 18
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
public static TransactionInfo executeTransaction(HFClient client, Channel channel, ChaincodeID chaincodeID, boolean invoke, String func,
                                                 Long transactionTimeout, String... args) throws InvalidArgumentException, ProposalException, InterruptedException, ExecutionException, TimeoutException {
    TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
    transactionProposalRequest.setChaincodeID(chaincodeID);
    transactionProposalRequest.setChaincodeLanguage(TransactionRequest.Type.GO_LANG);

    transactionProposalRequest.setFcn(func);
    transactionProposalRequest.setArgs(args);
    transactionProposalRequest.setProposalWaitTime(120000);

    List<ProposalResponse> successful = new LinkedList<>();
    List<ProposalResponse> failed = new LinkedList<>();
    // there is no need to retry. If not, you should re-send the transaction proposal.
    Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest);
    TransactionInfo transactionInfo = new TransactionInfo();
    boolean result = true;
    for (ProposalResponse response : transactionPropResp) {
        if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
            transactionInfo.setCode(ErrorCode.SUCCESS.getCode());
            transactionInfo.setPayLoad(new String(response.getChaincodeActionResponsePayload()));
            log.info("[√] Got success response from peer:{} , payload:{}", response.getPeer().getName(), transactionInfo.getPayLoad());
            successful.add(response);
        } else {
            result = false;
            transactionInfo.setCode(ErrorCode.FABRICSDK_CHAINCODE_INVOKE_FAILED.getCode());
            transactionInfo.setMessage(response.getMessage());
            String status = response.getStatus().toString();
            log.error("[×] Got failed response from peer:{}, status:{}, error message:{}", response.getPeer().getName(), status, transactionInfo.getMessage());
            failed.add(response);
        }
    }

    if (invoke && result) {
        log.info("Sending transaction to orderers...");
        CompletableFuture<BlockEvent.TransactionEvent> carfuture = channel.sendTransaction(successful);
        BlockEvent.TransactionEvent transactionEvent = carfuture.get(transactionTimeout, TimeUnit.MILLISECONDS);
        transactionInfo.setBlockNumber(transactionEvent.getBlockEvent().getBlockNumber());
        log.info("Wait event return: " + transactionEvent.getChannelId() + " " + transactionEvent.getTransactionID() + " " + transactionEvent.getType() + " " + transactionEvent.getValidationCode());
    }
    return transactionInfo;
}