org.hyperledger.fabric.sdk.TransactionProposalRequest Java Examples
The following examples show how to use
org.hyperledger.fabric.sdk.TransactionProposalRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChannelClient.java From blockchain-application-using-fabric-java-sdk with Apache License 2.0 | 6 votes |
/** * Send transaction proposal. * * @param request * @return * @throws ProposalException * @throws InvalidArgumentException */ public Collection<ProposalResponse> sendTransactionProposal(TransactionProposalRequest request) throws ProposalException, InvalidArgumentException { Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO, "Sending transaction proposal on channel " + channel.getName()); Collection<ProposalResponse> response = channel.sendTransactionProposal(request, channel.getPeers()); for (ProposalResponse pres : response) { String stringResponse = new String(pres.getChaincodeActionResponsePayload()); Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO, "Transaction proposal on channel " + channel.getName() + " " + pres.getMessage() + " " + pres.getStatus() + " with transaction id:" + pres.getTransactionID()); Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,stringResponse); } CompletableFuture<TransactionEvent> cf = channel.sendTransaction(response); Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,cf.toString()); return response; }
Example #2
Source File: FabricTransaction.java From spring-fabric-gateway with MIT License | 5 votes |
private TransactionProposalRequest newProposalRequest(String[] args) { TransactionProposalRequest request = network.getGateway().getClient().newTransactionProposalRequest(); configureRequest(request, args); if (transientData != null) { try { request.setTransientMap(transientData); } catch (InvalidArgumentException e) { // Only happens if transientData is null throw new IllegalStateException(e); } } return request; }
Example #3
Source File: FabricTransaction.java From spring-fabric-gateway with MIT License | 5 votes |
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 #4
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 #5
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 #6
Source File: ChaincodeManager.java From fabric-net-server with Apache License 2.0 | 4 votes |
/** * 执行智能合约 * * @param fcn * 方法名 * @param args * 参数数组 * @return * @throws InvalidArgumentException * @throws ProposalException * @throws InterruptedException * @throws ExecutionException * @throws TimeoutException * @throws IOException * @throws TransactionException * @throws CryptoException * @throws InvalidKeySpecException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException */ public Map<String, String> invoke(String fcn, String[] args) throws InvalidArgumentException, ProposalException, InterruptedException, ExecutionException, TimeoutException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException { Map<String, String> resultMap = new HashMap<>(); Collection<ProposalResponse> successful = new LinkedList<>(); Collection<ProposalResponse> failed = new LinkedList<>(); /// Send transaction proposal to all peers TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest(); transactionProposalRequest.setChaincodeID(chaincodeID); transactionProposalRequest.setFcn(fcn); transactionProposalRequest.setArgs(args); Map<String, byte[]> tm2 = new HashMap<>(); tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8)); tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8)); tm2.put("result", ":)".getBytes(UTF_8)); transactionProposalRequest.setTransientMap(tm2); long currentStart = System.currentTimeMillis(); Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers()); for (ProposalResponse response : transactionPropResp) { if (response.getStatus() == ProposalResponse.Status.SUCCESS) { successful.add(response); } else { failed.add(response); } } log.info("channel send transaction proposal time = " + ( System.currentTimeMillis() - currentStart)); Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(transactionPropResp); if (proposalConsistencySets.size() != 1) { log.error("Expected only one set of consistent proposal responses but got " + proposalConsistencySets.size()); } if (failed.size() > 0) { ProposalResponse firstTransactionProposalResponse = failed.iterator().next(); log.error("Not enough endorsers for inspect:" + failed.size() + " endorser error: " + firstTransactionProposalResponse.getMessage() + ". Was verified: " + firstTransactionProposalResponse.isVerified()); resultMap.put("code", "error"); resultMap.put("data", firstTransactionProposalResponse.getMessage()); return resultMap; } else { log.info("Successfully received transaction proposal responses."); ProposalResponse resp = transactionPropResp.iterator().next(); log.debug("TransactionID: " + resp.getTransactionID()); byte[] x = resp.getChaincodeActionResponsePayload(); String resultAsString = null; if (x != null) { resultAsString = new String(x, "UTF-8"); } log.info("resultAsString = " + resultAsString); channel.sendTransaction(successful); resultMap.put("code", "success"); resultMap.put("data", resultAsString); resultMap.put("txid", resp.getTransactionID()); return resultMap; } // channel.sendTransaction(successful).thenApply(transactionEvent -> { // if (transactionEvent.isValid()) { // log.info("Successfully send transaction proposal to orderer. Transaction ID: " + transactionEvent.getTransactionID()); // } else { // log.info("Failed to send transaction proposal to orderer"); // } // // chain.shutdown(true); // return transactionEvent.getTransactionID(); // }).get(chaincode.getInvokeWatiTime(), TimeUnit.SECONDS); }
Example #7
Source File: QueryBlockTest.java From fabric-jdbc-connector with Apache License 2.0 | 4 votes |
@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 #8
Source File: QueryBlockTest.java From fabric-jdbc-connector with Apache License 2.0 | 4 votes |
@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 #9
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 #10
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 #11
Source File: End2endLifecycleIT.java From fabric-sdk-java with Apache License 2.0 | 4 votes |
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); }