org.hyperledger.fabric.sdk.ChaincodeID Java Examples
The following examples show how to use
org.hyperledger.fabric.sdk.ChaincodeID.
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 |
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: FabricClient.java From blockchain-application-using-fabric-java-sdk with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: ChannelClient.java From blockchain-application-using-fabric-java-sdk with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: QueryBlock.java From fabric-jdbc-connector with Apache License 2.0 | 6 votes |
private UpgradeProposalRequest getUpgradeProposalRequest(String chaincodeName, String chainCodeVersion, String chainCodePath, String chaincodeFunction, String[] chaincodeArgs, Endorsers endorsers) throws InvalidArgumentException { client.setUserContext(userOrg.getPeerAdmin()); ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(chaincodeName).setVersion(chainCodeVersion) .setPath(chainCodePath).build(); UpgradeProposalRequest upgradeProposalRequest = client.newUpgradeProposalRequest(); upgradeProposalRequest.setProposalWaitTime(conf.getProposalWaitTime()); upgradeProposalRequest.setChaincodeID(chaincodeID); upgradeProposalRequest.setFcn(chaincodeFunction); upgradeProposalRequest.setArgs(chaincodeArgs); if(endorsers != null) { ChaincodeEndorsementPolicy policy = getChaincodeEndorsementPolicy(endorsers); upgradeProposalRequest.setChaincodeEndorsementPolicy(policy); } return upgradeProposalRequest; }
Example #5
Source File: QueryBlock.java From fabric-jdbc-connector with Apache License 2.0 | 6 votes |
private InstantiateProposalRequest getInstantiateProposalRequest(String chaincodeName, String chainCodeVersion, String chainCodePath, String chaincodeFunction, String[] chaincodeArgs, Endorsers endorsers) throws InvalidArgumentException { client.setUserContext(userOrg.getPeerAdmin()); ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(chaincodeName).setVersion(chainCodeVersion) .setPath(chainCodePath).build(); InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest(); instantiateProposalRequest.setProposalWaitTime(conf.getProposalWaitTime()); instantiateProposalRequest.setChaincodeID(chaincodeID); instantiateProposalRequest.setFcn(chaincodeFunction); instantiateProposalRequest.setArgs(chaincodeArgs); if(endorsers != null) { ChaincodeEndorsementPolicy policy = getChaincodeEndorsementPolicy(endorsers); instantiateProposalRequest.setChaincodeEndorsementPolicy(policy); } return instantiateProposalRequest; }
Example #6
Source File: End2endAndBackAgainIT.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
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 #7
Source File: FabricUpdateContractUtil.java From WeEvent with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { FabricConfig fabricConfig = new FabricConfig(); fabricConfig.load(""); HFClient client = FabricSDKWrapper.initializeClient(fabricConfig); Channel channel = FabricSDKWrapper.initializeChannel(client, fabricConfig.getChannelName(), fabricConfig); ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(fabricConfig.getTopicControllerName()).setVersion(fabricConfig.getTopicControllerVersion()).build(); switch (args[0]) { case "add": FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, true, "addTopicContractName", fabricConfig.getTransactionTimeout(), fabricConfig.getTopicName(), fabricConfig.getTopicVerison()); String topicContractNameAdd = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractName", fabricConfig.getTransactionTimeout()).getPayLoad(); String topicContractVersionAdd = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractVersion", fabricConfig.getTransactionTimeout()).getPayLoad(); if (fabricConfig.getTopicName().equals(topicContractNameAdd) && fabricConfig.getTopicVerison().equals(topicContractVersionAdd)) { log.debug("add TopicContract success"); } else { log.error("add TopicContrct error"); systemExit(1); } break; case "update": FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, true, "updateTopicContractName", fabricConfig.getTransactionTimeout(), fabricConfig.getTopicName(), fabricConfig.getTopicVerison()); String topicContractNameUpdate = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractName", fabricConfig.getTransactionTimeout()).getPayLoad(); String topicContractVersionUpdate = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractVersion", fabricConfig.getTransactionTimeout()).getPayLoad(); if (fabricConfig.getTopicName().equals(topicContractNameUpdate) && fabricConfig.getTopicVerison().equals(topicContractVersionUpdate)) { log.debug("update TopicContract success"); } else { log.error("update TopicContrct error"); systemExit(1); } break; default: log.error("update TopicContract, error command action"); systemExit(1); break; } }
Example #8
Source File: NetworkConfigIT.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
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 #9
Source File: PrivateDataIT.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
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 #10
Source File: FabricService.java From fabric-java-block with GNU General Public License v3.0 | 5 votes |
public QueryResult query(QueryRequest queryRequest) { HFClient client = HFClient.createNewInstance(); QueryResult queryResult = null; try { Channel currentChannel = super.initChannel(client, queryRequest); FabricTemplate fabricTemplate = new FabricTemplate(); FabricTemplate.setClient(client); List<String> peers = FabricUtils.converPeerNodeKey(queryRequest.getStrategyOrgList()); ChaincodeID chainCodeId = ChaincodeID.newBuilder() .setName(queryRequest.getBlockChainContractDTO().getContractKey()) .setVersion(queryRequest.getBlockChainContractDTO().getVersion()) .setPath("").build(); queryResult = fabricTemplate.query(currentChannel, queryRequest.getBlockChainContractFunDTO().getFunKey(), queryRequest.getArgs(), chainCodeId, peers); queryResult.setOrderNo(queryRequest.getOrderNo()); queryResult.setRequestId(IdUtil.fastUUID()); queryResult.setRequestContext(JSONUtil.toJsonStr(queryRequest)); queryResult.setStatus(ResponseCodeEnum.SUCCESS.getCode()); queryResult.setResponseContext(JSONUtil.toJsonStr(queryResult)); }catch(Exception e){ log.error("Fabric SDK query 出错: " + e.getMessage()); e.printStackTrace(); queryResult = new QueryResult(); queryResult.setOrderNo(queryRequest.getOrderNo()); queryResult.setRequestId(IdUtil.fastUUID()); queryResult.setRequestContext(JSONUtil.toJsonStr(queryRequest)); queryResult.setStatus(ResponseCodeEnum.PROCESS_ERROR.getCode()); queryResult.setErrorMsg(e.getMessage()); } return queryResult; }
Example #11
Source File: End2endAndBackAgainIT.java From fabric_sdk_java_study with Apache License 2.0 | 5 votes |
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 #12
Source File: QueryBlock.java From fabric-jdbc-connector with Apache License 2.0 | 5 votes |
private InstallProposalRequest getInstallProposalRequest(String chaincodeName, String version, String goPath, String chainCodePath, Org sampleOrg) throws InvalidArgumentException { ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(chaincodeName).setVersion(version) .setPath(chainCodePath).build(); final String channelName = channel.getName(); logger.info(String.format("Running channel %s", channelName)); client.setUserContext(sampleOrg.getPeerAdmin()); logger.info("Creating install proposal"); InstallProposalRequest installProposalRequest = client.newInstallProposalRequest(); installProposalRequest.setChaincodeID(chaincodeID); installProposalRequest.setChaincodeSourceLocation(new File(goPath)); installProposalRequest.setChaincodeVersion(version); return installProposalRequest; }
Example #13
Source File: FabricSDKWrapper.java From WeEvent with Apache License 2.0 | 5 votes |
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 #14
Source File: QueryBlock.java From fabric-jdbc-connector with Apache License 2.0 | 4 votes |
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 #15
Source File: ChaincodeManager.java From fabric-net-server with Apache License 2.0 | 4 votes |
private ChaincodeID getChaincodeID() { return ChaincodeID.newBuilder().setName(chaincode.getChaincodeName()).setVersion(chaincode.getChaincodeVersion()).setPath(chaincode.getChaincodePath()).build(); }
Example #16
Source File: ChannelClient.java From blockchain-application-using-fabric-java-sdk with Apache License 2.0 | 4 votes |
/** * * 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 #17
Source File: FabricTransaction.java From spring-fabric-gateway with MIT License | 4 votes |
private ChaincodeID getChaincodeId() { return ChaincodeID.newBuilder().setName(contract.getChaincodeId()).build(); }
Example #18
Source File: InvokeChaincode.java From blockchain-application-using-fabric-java-sdk with Apache License 2.0 | 4 votes |
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 #19
Source File: FabricSDKWrapper.java From WeEvent with Apache License 2.0 | 4 votes |
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 #20
Source File: FabricService.java From fabric-java-block with GNU General Public License v3.0 | 4 votes |
public InvokeResult invoke(InvokeRequest invokeRequest) { HFClient client = HFClient.createNewInstance(); InvokeResult invokeResult = null; try { Channel currentChannel = super.initChannel(client, invokeRequest); FabricTemplate fabricTemplate = new FabricTemplate(); FabricTemplate.setClient(client); List<String> peers = FabricUtils.converPeerNodeKey(invokeRequest.getStrategyOrgList()); ChaincodeID chainCodeId = ChaincodeID.newBuilder() .setName(invokeRequest.getBlockChainContractDTO().getContractKey()) .setVersion(invokeRequest.getBlockChainContractDTO().getVersion()) .setPath("").build(); invokeResult = fabricTemplate.transaction (currentChannel, invokeRequest.getBlockChainContractFunDTO().getFunKey(), invokeRequest.getArgs(), chainCodeId, peers, invokeRequest.getBlockChainContractFunDTO().getAsyncFlag()); invokeResult.setOrderNo(invokeRequest.getOrderNo()); invokeResult.setRequestId(IdUtil.fastUUID()); invokeResult.setRequestContext(JSONUtil.toJsonStr(invokeRequest)); invokeResult.setReturnNo(invokeResult.getTxId()); if (AsyncInvokeTypeEnum.ASYNC.getCode().equals(invokeRequest.getBlockChainContractFunDTO().getAsyncFlag())) { invokeResult.setStatus(ResponseCodeEnum.PROCESSING.getCode()); } else { invokeResult.setStatus(ResponseCodeEnum.SUCCESS.getCode()); } invokeResult.setResponseContext(JSONUtil.toJsonStr(invokeResult)); }catch (Exception e){ log.error("Fabric SDK invoke 出错: " + e.getMessage()); e.printStackTrace(); invokeResult = new InvokeResult(); invokeResult.setOrderNo(invokeRequest.getOrderNo()); invokeResult.setRequestId(IdUtil.fastUUID()); invokeResult.setRequestContext(JSONUtil.toJsonStr(invokeRequest)); invokeResult.setStatus(ResponseCodeEnum.PROCESS_ERROR.getCode()); invokeResult.setErrorMsg(e.getMessage()); } return invokeResult; }
Example #21
Source File: FabricSDKWrapper.java From WeEvent with Apache License 2.0 | 4 votes |
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 #22
Source File: PrivateDataIT.java From fabric-sdk-java with Apache License 2.0 | 4 votes |
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 #23
Source File: NetworkConfigIT.java From fabric-sdk-java with Apache License 2.0 | 4 votes |
@Test public void testUpdate1() throws Exception { // Setup client and channel instances HFClient client = getTheClient(); Channel channel = constructChannel(client, FOO_CHANNEL_NAME); final ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME) .setVersion(CHAIN_CODE_VERSION) .setPath(CHAIN_CODE_PATH).build(); final String channelName = channel.getName(); out("Running testUpdate1 - Channel %s", channelName); final Collection<String> peersOrganizationMSPIDs = channel.getPeersOrganizationMSPIDs(); assertNotNull(peersOrganizationMSPIDs); assertEquals(1, peersOrganizationMSPIDs.size()); assertEquals("Org1MSP", peersOrganizationMSPIDs.iterator().next()); int moveAmount = 5; String originalVal = queryChaincodeForCurrentValue(client, channel, chaincodeID); String newVal = "" + (Integer.parseInt(originalVal) + moveAmount); out("Original value = %s", originalVal); //user registered user client.setUserContext(orgRegisteredUsers.get("Org1")); // only using org1 // Move some assets moveAmount(client, channel, chaincodeID, "a", "b", "" + moveAmount, null).thenApply(transactionEvent -> { // Check that they were moved queryChaincodeForExpectedValue(client, channel, newVal, chaincodeID); return null; }).thenApply(transactionEvent -> { // Move them back try { return moveAmount(client, channel, chaincodeID, "b", "a", "" + moveAmount, null).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS); } catch (Exception e) { throw new RuntimeException(e); } }).thenApply(transactionEvent -> { // Check that they were moved back queryChaincodeForExpectedValue(client, channel, originalVal, chaincodeID); return null; }).exceptionally(e -> { if (e instanceof CompletionException && e.getCause() != null) { e = e.getCause(); } if (e instanceof TransactionEventException) { BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent(); if (te != null) { e.printStackTrace(System.err); fail(format("Transaction with txid %s failed. %s", te.getTransactionID(), e.getMessage())); } } e.printStackTrace(System.err); fail(format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage())); return null; }).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS); channel.shutdown(true); // Force channel to shutdown clean up resources. out("testUpdate1 - done"); out("That's all folks!"); }
Example #24
Source File: FabricSDKWrapper.java From WeEvent with Apache License 2.0 | 4 votes |
public static ChaincodeID getChainCodeID(String chaincodeName, String chaincodeVersion) { return ChaincodeID.newBuilder().setName(chaincodeName).setVersion(chaincodeVersion).build(); }
Example #25
Source File: Fabric.java From WeEvent with Apache License 2.0 | 4 votes |
private static ChaincodeID getTopicChaincodeID(FabricConfig fabricConfig, ChaincodeID topicControllerChaincodeID) throws InvalidArgumentException, ProposalException, InterruptedException, ExecutionException, TimeoutException { String topicContractName = FabricSDKWrapper.executeTransaction(hfClient, channel, topicControllerChaincodeID, false, "getTopicContractName", fabricConfig.getTransactionTimeout()).getPayLoad(); String topicContractVersion = FabricSDKWrapper.executeTransaction(hfClient, channel, topicControllerChaincodeID, false, "getTopicContractVersion", fabricConfig.getTransactionTimeout()).getPayLoad(); return FabricSDKWrapper.getChainCodeID(topicContractName, topicContractVersion); }
Example #26
Source File: NetworkConfigIT.java From fabric-sdk-java with Apache License 2.0 | 3 votes |
private static 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); String value = queryChaincodeForCurrentValue(client, channel, chaincodeID); assertEquals(expect, value); }
Example #27
Source File: ChaincodeServiceImpl.java From balance-transfer-java with Apache License 2.0 | 2 votes |
/** * takes input as chaincode name and returns chaincode id * * @param chaincodename * @return ChaincodeID */ public ChaincodeID getChaincodeId(String name) { chaincodeID = ChaincodeID.newBuilder().setName(name).setVersion(chainCodeVersion).setPath(chainCodePath) .build(); return chaincodeID; }