org.hyperledger.fabric.sdk.ProposalResponse Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.ProposalResponse. 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: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static Collection<ProposalResponse> instantiateProposal(HFClient client, Channel channel, ChaincodeID chaincodeID,
                                                               TransactionRequest.Type chaincodeLang, Long proposalTimeout) throws InvalidArgumentException, ProposalException {
    InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
    instantiateProposalRequest.setProposalWaitTime(proposalTimeout);//time in milliseconds
    instantiateProposalRequest.setChaincodeID(chaincodeID);
    instantiateProposalRequest.setChaincodeLanguage(chaincodeLang);
    instantiateProposalRequest.setFcn("init");
    instantiateProposalRequest.setArgs(new String[]{});

    // I do not know the purpose of transient map works for.
    Map<String, byte[]> transientMap = new HashMap<>();
    transientMap.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
    transientMap.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
    instantiateProposalRequest.setTransientMap(transientMap);
    return channel.sendInstantiationProposal(instantiateProposalRequest, channel.getPeers());
}
 
Example #2
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 #3
Source File: FabricClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Deploy chain code.
 * 
 * @param chainCodeName
 * @param chaincodePath
 * @param codepath
 * @param language
 * @param version
 * @param peers
 * @return
 * @throws InvalidArgumentException
 * @throws IOException
 * @throws ProposalException
 */
public Collection<ProposalResponse> deployChainCode(String chainCodeName, String chaincodePath, String codepath,
		String language, String version, Collection<Peer> peers)
		throws InvalidArgumentException, IOException, ProposalException {
	InstallProposalRequest request = instance.newInstallProposalRequest();
	ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(chainCodeName).setVersion(version)
			.setPath(chaincodePath);
	ChaincodeID chaincodeID = chaincodeIDBuilder.build();
	Logger.getLogger(FabricClient.class.getName()).log(Level.INFO,
			"Deploying chaincode " + chainCodeName + " using Fabric client " + instance.getUserContext().getMspId()
					+ " " + instance.getUserContext().getName());
	request.setChaincodeID(chaincodeID);
	request.setUserContext(instance.getUserContext());
	request.setChaincodeSourceLocation(new File(codepath));
	request.setChaincodeVersion(version);
	Collection<ProposalResponse> responses = instance.sendInstallProposal(request, peers);
	return responses;
}
 
Example #4
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 #5
Source File: ChannelClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Query by chaincode.
 * 
 * @param chaincodeName
 * @param functionName
 * @param args
 * @return
 * @throws InvalidArgumentException
 * @throws ProposalException
 */
public Collection<ProposalResponse> queryByChainCode(String chaincodeName, String functionName, String[] args)
		throws InvalidArgumentException, ProposalException {
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Querying " + functionName + " on channel " + channel.getName());
	QueryByChaincodeRequest request = fabClient.getInstance().newQueryProposalRequest();
	ChaincodeID ccid = ChaincodeID.newBuilder().setName(chaincodeName).build();
	request.setChaincodeID(ccid);
	request.setFcn(functionName);
	if (args != null)
		request.setArgs(args);

	Collection<ProposalResponse> response = channel.queryByChaincode(request);

	return response;
}
 
Example #6
Source File: FabricTransaction.java    From spring-fabric-gateway with MIT License 6 votes vote down vote up
private Collection<ProposalResponse> validatePeerResponses(Collection<ProposalResponse> proposalResponses)
		throws ContractException {
	final Collection<ProposalResponse> validResponses = new ArrayList<>();
	final Collection<String> invalidResponseMsgs = new ArrayList<>();
	proposalResponses.forEach(response -> {
		String peerUrl = response.getPeer() != null ? response.getPeer().getUrl() : "<unknown>";
		if (response.getStatus().equals(ChaincodeResponse.Status.SUCCESS)) {
			log.debug(String.format("validatePeerResponses: valid response from peer %s", peerUrl));
			validResponses.add(response);
		} else {
			logger.warn(String.format("validatePeerResponses: invalid response from peer %s, message %s", peerUrl,
					response.getMessage()));
			invalidResponseMsgs.add(response.getMessage());
		}
	});

	if (validResponses.size() < 1) {
		String msg = String.format("No valid proposal responses received. %d peer error responses: %s",
				invalidResponseMsgs.size(), String.join("; ", invalidResponseMsgs));
		logger.error(msg);
		throw new ContractException(msg);
	}

	return validResponses;
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Collection<ProposalResponse> installProposal(HFClient client, Channel channel, ChaincodeID chaincodeID,
                                                           TransactionRequest.Type chaincodeLang,         // Type.GO_LANG
                                                           String chaincodeVer,        // "v1"
                                                           String chaincodeSourceLoc,  // "/opt/gopath"
                                                           String chaincodePath        // "github.com/hyperledger/fabric/peer/chaincode/go/chaincode_example02
) throws InvalidArgumentException, ProposalException {
    InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
    installProposalRequest.setChaincodeID(chaincodeID);
    installProposalRequest.setChaincodeVersion(chaincodeVer);
    installProposalRequest.setChaincodeLanguage(chaincodeLang);
    installProposalRequest.setChaincodeSourceLocation(new File(chaincodeSourceLoc));
    installProposalRequest.setChaincodePath(chaincodePath);
    return client.sendInstallProposal(installProposalRequest, channel.getPeers());
}
 
Example #13
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 #14
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 #15
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 #16
Source File: FabricTransaction.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
private Collection<ProposalResponse> sendTransactionProposal(TransactionProposalRequest request)
		throws InvalidArgumentException, ServiceDiscoveryException, ProposalException {
	if (endorsingPeers != null) {
		return channel.sendTransactionProposal(request, endorsingPeers);
	} else if (network.getGateway().isDiscoveryEnabled()) {
		Channel.DiscoveryOptions discoveryOptions = createDiscoveryOptions()
				.setEndorsementSelector(ServiceDiscovery.EndorsementSelector.ENDORSEMENT_SELECTION_RANDOM)
				.setForceDiscovery(true);
		return channel.sendTransactionProposalToEndorsers(request, discoveryOptions);
	} else {
		return channel.sendTransactionProposal(request);
	}
}
 
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;
}
 
Example #19
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 #20
Source File: QueryBlockTest.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInvokeNoPeerInfo() throws ClassNotFoundException, SQLException, InvalidArgumentException, ProposalException {
    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);

    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);
    when(mockClient.newPeer(anyString(), anyString(), any())).thenCallRealMethod();


    InstantiateProposalRequest mockInstantiateProposalRequest = mock(InstantiateProposalRequest.class);
    when(mockClient.newInstantiationProposalRequest()).thenReturn(mockInstantiateProposalRequest);

    TransactionProposalRequest mockTransactionProposalRequest = mock(TransactionProposalRequest.class);
    when(mockClient.newTransactionProposalRequest()).thenReturn(mockTransactionProposalRequest);

    Collection<ProposalResponse> mockProposalResponsesList = new ArrayList<ProposalResponse>();
    ProposalResponse mockProposalResponses = mock(ProposalResponse.class);
    when(mockProposalResponses.getStatus()).thenReturn(ProposalResponse.Status.SUCCESS);
    Peer mkpeer = mock(Peer.class);
    when(mockProposalResponses.getPeer()).thenReturn(mkpeer);
    mockProposalResponsesList.add(mockProposalResponses);
    mockProposalResponsesList.add(mockProposalResponses);

    when(mockChannel.sendTransactionProposal(any(TransactionProposalRequest.class),anyCollectionOf(Peer.class))).thenReturn(mockProposalResponsesList);


    PowerMockito.mockStatic(SDKUtils.class);

    String configPath = "src/test/resources/blockchain-query";
    Class.forName("com.impetus.fabric.jdbc.FabricDriver");
    QueryBlock qb = new QueryBlock(configPath,"mychannel", null, null);
    qb.setChannel();
    String chaincodeName ="chncodefuncNoPeerInfo";

    when(SDKUtils.getProposalConsistencySets(anyCollection())).thenReturn(new ArrayList<>());

    CompletableFuture<BlockEvent.TransactionEvent> mockCompletableFutureTEvent = new CompletableFuture<BlockEvent.TransactionEvent>();//{mockTranEvent};
    when(mockChannel.sendTransaction(any(ArrayList.class))).thenReturn(mockCompletableFutureTEvent);// .thenReturn(mockCompletableFutureTEvent);

    DataFrame df = qb.invokeChaincode(chaincodeName, "testFunction", new String[]{"a", "b", "5", "10"});
    assertEquals(df.getData().size(), 1);
    List<Object> row = df.getData().get(0);
    assertEquals(false, Boolean.parseBoolean(row.get(1).toString()));
    assertEquals("Endorsing peer information not provided for chaincode chncodefuncNoPeerInfo", row.get(3).toString());
}
 
Example #21
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 #22
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 #23
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 #24
Source File: QueryBlockTest.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInvokeChaincode() throws ClassNotFoundException, SQLException, InvalidArgumentException, ProposalException{

    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);

    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);
    when(mockClient.newPeer(anyString(), anyString(), any())).thenCallRealMethod();


    InstantiateProposalRequest mockInstantiateProposalRequest = mock(InstantiateProposalRequest.class);
    when(mockClient.newInstantiationProposalRequest()).thenReturn(mockInstantiateProposalRequest);

    TransactionProposalRequest mockTransactionProposalRequest = mock(TransactionProposalRequest.class);
    when(mockClient.newTransactionProposalRequest()).thenReturn(mockTransactionProposalRequest);

    Collection<ProposalResponse> mockProposalResponsesList = new ArrayList<ProposalResponse>();
    ProposalResponse mockProposalResponses = mock(ProposalResponse.class);
    when(mockProposalResponses.getStatus()).thenReturn(ProposalResponse.Status.SUCCESS);
    Peer mkpeer = mock(Peer.class);
    when(mockProposalResponses.getPeer()).thenReturn(mkpeer);
    mockProposalResponsesList.add(mockProposalResponses);
    mockProposalResponsesList.add(mockProposalResponses);

    when(mockChannel.sendTransactionProposal(any(TransactionProposalRequest.class),anyCollectionOf(Peer.class))).thenReturn(mockProposalResponsesList);


    PowerMockito.mockStatic(SDKUtils.class);

    String configPath = "src/test/resources/blockchain-query";
    Class.forName("com.impetus.fabric.jdbc.FabricDriver");
    QueryBlock qb = new QueryBlock(configPath,"mychannel", null, null);
    qb.setChannel();
    String chaincodeName ="chncodefunc";

    when(SDKUtils.getProposalConsistencySets(anyCollection())).thenReturn(new ArrayList<>());

    CompletableFuture<BlockEvent.TransactionEvent> mockCompletableFutureTEvent = new CompletableFuture<BlockEvent.TransactionEvent>();//{mockTranEvent};
    when(mockChannel.sendTransaction(any(ArrayList.class))).thenReturn(mockCompletableFutureTEvent);// .thenReturn(mockCompletableFutureTEvent);

    try {
        qb.invokeChaincode(chaincodeName, "testFunction", new String[]{"a", "b", "5", "10"});

    }catch(BlkchnException blkEx){
        //Do Nothing for Java concurrent Error
        if(!(blkEx.getMessage().contains("java.util.concurrent.TimeoutException"))) {
            assert(false);
        }
    }
    assert(true);

}
 
Example #25
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 #26
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 #27
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private String lifecycleInstallChaincode(HFClient client, Collection<Peer> peers, LifecycleChaincodePackage lifecycleChaincodePackage) throws InvalidArgumentException, ProposalException, InvalidProtocolBufferException {

        int numInstallProposal = 0;

        numInstallProposal = numInstallProposal + peers.size();

        LifecycleInstallChaincodeRequest installProposalRequest = client.newLifecycleInstallChaincodeRequest();
        installProposalRequest.setLifecycleChaincodePackage(lifecycleChaincodePackage);
        installProposalRequest.setProposalWaitTime(DEPLOYWAITTIME);

        Collection<LifecycleInstallChaincodeProposalResponse> responses = client.sendLifecycleInstallChaincodeRequest(installProposalRequest, peers);
        assertNotNull(responses);

        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();
        String packageID = null;
        for (LifecycleInstallChaincodeProposalResponse 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);
                if (packageID == null) {
                    packageID = response.getPackageId();
                    assertNotNull(format("Hashcode came back as null from peer: %s ", response.getPeer()), packageID);
                } else {
                    assertEquals("Miss match on what the peers returned back as the packageID", packageID, response.getPackageId());
                }
            } 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());
        }

        assertNotNull(packageID);
        assertFalse(packageID.isEmpty());

        return packageID;

    }
 
Example #28
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 #29
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);
	}