org.hyperledger.fabric.sdk.BlockEvent Java Examples
The following examples show how to use
org.hyperledger.fabric.sdk.BlockEvent.
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 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 #2
Source File: QueryBlockTest.java From fabric-jdbc-connector with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testInstantiateChaincode() throws ClassNotFoundException, SQLException, InvalidArgumentException{ PowerMockito.mockStatic(HFClient.class); when(HFClient.createNewInstance()).thenReturn(mockClient); Channel mockChannel = mock(Channel.class); when(mockClient.newChannel(anyString())).thenReturn(mockChannel); InstantiateProposalRequest mockInstantiateProposalRequest = mock(InstantiateProposalRequest.class); when(mockClient.newInstantiationProposalRequest()).thenReturn(mockInstantiateProposalRequest); 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"; String version = "1.0"; String goPath = "/home/impetus/IdeaProjects/fabric-jdbc-driver/src/test/resources/blockchain-query/"; CompletableFuture<BlockEvent.TransactionEvent> mockCompletableFutureTEvent = new CompletableFuture<BlockEvent.TransactionEvent>(); when(mockChannel.sendTransaction(any(ArrayList.class),anyCollection())).thenReturn(mockCompletableFutureTEvent);// .thenReturn(mockCompletableFutureTEvent); try { qb.instantiateChaincode(chaincodeName,version,goPath,"testFunction",new String[] {"a","b","5","10"}, null); } catch(BlkchnException blkEx){ //Do Nothing for Java Concurrent Error if(!blkEx.getMessage().contains("java.util.concurrent.TimeoutException")) { assert(false); } } assert(true); }
Example #3
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 #4
Source File: ChaincodeManager.java From fabric-net-server with Apache License 2.0 | 4 votes |
private Channel getChannel(FabricOrg fabricOrg, HFClient client) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, CryptoException, InvalidArgumentException, TransactionException { Channel channel = client.newChannel(chaincode.getChannelName()); log.debug("Get Chain " + chaincode.getChannelName()); channel.setTransactionWaitTime(chaincode.getTransactionWaitTime()); channel.setDeployWaitTime(chaincode.getDeployWaitTime()); for (int i = 0; i < peers.get().size(); i++) { File peerCert = Paths.get(config.getCryptoConfigPath(), "/peerOrganizations", peers.getOrgDomainName(), "peers", peers.get().get(i).getPeerName(), "tls/server.crt") .toFile(); if (!peerCert.exists()) { throw new RuntimeException( String.format("Missing cert file for: %s. Could not find at location: %s", peers.get().get(i).getPeerName(), peerCert.getAbsolutePath())); } Properties peerProperties = new Properties(); peerProperties.setProperty("pemFile", peerCert.getAbsolutePath()); // ret.setProperty("trustServerCertificate", "true"); //testing // environment only NOT FOR PRODUCTION! peerProperties.setProperty("hostnameOverride", peers.getOrgDomainName()); peerProperties.setProperty("sslProvider", "openSSL"); peerProperties.setProperty("negotiationType", "TLS"); // 在grpc的NettyChannelBuilder上设置特定选项 peerProperties.put("grpc.ManagedChannelBuilderOption.maxInboundMessageSize", 9000000); channel.addPeer(client.newPeer(peers.get().get(i).getPeerName(), fabricOrg.getPeerLocation(peers.get().get(i).getPeerName()), peerProperties)); if (peers.get().get(i).isAddEventHub()) { channel.addEventHub( client.newEventHub(peers.get().get(i).getPeerEventHubName(), fabricOrg.getEventHubLocation(peers.get().get(i).getPeerEventHubName()), peerProperties)); } } for (int i = 0; i < orderers.get().size(); i++) { File ordererCert = Paths.get(config.getCryptoConfigPath(), "/ordererOrganizations", orderers.getOrdererDomainName(), "orderers", orderers.get().get(i).getOrdererName(), "tls/server.crt").toFile(); if (!ordererCert.exists()) { throw new RuntimeException( String.format("Missing cert file for: %s. Could not find at location: %s", orderers.get().get(i).getOrdererName(), ordererCert.getAbsolutePath())); } Properties ordererProperties = new Properties(); ordererProperties.setProperty("pemFile", ordererCert.getAbsolutePath()); ordererProperties.setProperty("hostnameOverride", orderers.getOrdererDomainName()); ordererProperties.setProperty("sslProvider", "openSSL"); ordererProperties.setProperty("negotiationType", "TLS"); ordererProperties.put("grpc.ManagedChannelBuilderOption.maxInboundMessageSize", 9000000); ordererProperties.setProperty("ordererWaitTimeMilliSecs", "300000"); channel.addOrderer( client.newOrderer(orderers.get().get(i).getOrdererName(), fabricOrg.getOrdererLocation(orderers.get().get(i).getOrdererName()), ordererProperties)); } log.debug("channel.isInitialized() = " + channel.isInitialized()); if (!channel.isInitialized()) { channel.initialize(); } if (config.isRegisterEvent()) { log.debug("========================Event事件监听注册========================"); channel.registerBlockListener(new BlockListener() { @Override public void received(BlockEvent event) { // TODO log.debug("========================Event事件监听开始========================"); try { log.debug("event.getChannelId() = " + event.getChannelId()); log.debug("event.getEvent().getChaincodeEvent().getPayload().toStringUtf8() = " + event.getEvent().getChaincodeEvent().getPayload().toStringUtf8()); log.debug("event.getBlock().getData().getDataList().size() = " + event.getBlock().getData().getDataList().size()); ByteString byteString = event.getBlock().getData().getData(0); String result = byteString.toStringUtf8(); log.debug("byteString.toStringUtf8() = " + result); String r1[] = result.split("END CERTIFICATE"); String rr = r1[2]; log.debug("rr = " + rr); } catch (InvalidProtocolBufferException e) { // TODO e.printStackTrace(); } log.debug("========================Event事件监听结束========================"); } }); } return channel; }
Example #5
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 #6
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 #7
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 #8
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!"); }