Java Code Examples for org.hyperledger.fabric.sdk.BlockEvent#TransactionEvent

The following examples show how to use org.hyperledger.fabric.sdk.BlockEvent#TransactionEvent . 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 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 vote down vote up
@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 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 4
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 5
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 6
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);

        }

    }