org.hyperledger.fabric.sdk.HFClient Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.HFClient. 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: FabricDeployContractUtil.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private static boolean checkChaincodeIfInstalled(HFClient client, FabricConfig fabricConfig) throws InvalidArgumentException, ProposalException {
    boolean isInstalled = false;
    String topicName = fabricConfig.getTopicName();
    String topicVersion = fabricConfig.getTopicVerison();
    String topicControllerName = fabricConfig.getTopicControllerName();
    String topicControllerVersion = fabricConfig.getTopicControllerVersion();

    List<Pair<String, String>> chaincodes = FabricSDKWrapper.queryInstalledChaincodes(client, FabricSDKWrapper.getPeer(client, fabricConfig));

    for (Pair<String, String> chaincode : chaincodes) {
        if (topicName.equals(chaincode.getKey()) && topicVersion.equals(chaincode.getValue())) {
            log.info("chaincode topic={}:{} already Installed.", topicName, topicVersion);
            isInstalled = true;
            break;
        }
        if (topicControllerName.equals(chaincode.getKey()) && topicControllerVersion.equals(chaincode.getValue())) {
            log.info("chaincode topicController={}:{} already Installed.", topicControllerName, topicControllerVersion);
            isInstalled = true;
            break;
        }
    }
    return isInstalled;
}
 
Example #2
Source File: End2endAndBackAgainIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private static boolean checkInstalledChaincode(HFClient client, Peer peer, String ccName, String ccPath, String ccVersion) throws InvalidArgumentException, ProposalException {

        out("Checking installed chaincode: %s, at version: %s, on peer: %s", ccName, ccVersion, peer.getName());
        List<ChaincodeInfo> ccinfoList = client.queryInstalledChaincodes(peer);

        boolean found = false;

        for (ChaincodeInfo ccifo : ccinfoList) {

            if (ccPath != null) {
                found = ccName.equals(ccifo.getName()) && ccPath.equals(ccifo.getPath()) && ccVersion.equals(ccifo.getVersion());
                if (found) {
                    break;
                }
            }

            found = ccName.equals(ccifo.getName()) && ccVersion.equals(ccifo.getVersion());
            if (found) {
                break;
            }

        }

        return found;
    }
 
Example #3
Source File: FabricStatementTest.java    From fabric-jdbc-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSchemaStar() throws Exception {
    PowerMockito.mockStatic(HFCAClient.class);
    when(HFCAClient.createNewInstance(anyString(), any())).thenReturn(mockCA);
    
    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);
    
    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);
    
    HyperUser mockuser = mock(HyperUser.class);
    when(mockuser.isEnrolled()).thenReturn(true);
    Store mockStore = mock(Store.class);
    PowerMockito.whenNew(Store.class).withAnyArguments().thenReturn(mockStore);
    
    String configPath = new File("src/test/resources/blockchain-query").getAbsolutePath();
    Class.forName("com.impetus.fabric.jdbc.FabricDriver");
    Connection conn = DriverManager.getConnection("jdbc:fabric://" + configPath + ":mychannel", 
            "admin", "adminpw");
    BlkchnStatement stat = (BlkchnStatement) conn.createStatement();
    String sql = "select * from transaction";
    ResultSetMetaData metadata = stat.getSchema(sql);
    int columnCount = metadata.getColumnCount();
    assertEquals(10, columnCount);
}
 
Example #4
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private static void deployChaincodeIfRequired() throws Exception {

        ////////////////////////////
        // Setup client
        HFClient client = getTheClient();

        Channel channel = constructChannel(client, FOO_CHANNEL_NAME);

        // Use any old peer...
        Peer peer = channel.getPeers().iterator().next();
        if (!checkInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION)) {

            // The chaincode we require does not exist, so deploy it...
            deployChaincode(client, channel, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION);
        }

    }
 
Example #5
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static Collection<ProposalResponse> instantiateProposal(HFClient client, Channel channel, ChaincodeID chaincodeID,
                                                               TransactionRequest.Type chaincodeLang, Long proposalTimeout) throws InvalidArgumentException, ProposalException {
    InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
    instantiateProposalRequest.setProposalWaitTime(proposalTimeout);//time in milliseconds
    instantiateProposalRequest.setChaincodeID(chaincodeID);
    instantiateProposalRequest.setChaincodeLanguage(chaincodeLang);
    instantiateProposalRequest.setFcn("init");
    instantiateProposalRequest.setArgs(new String[]{});

    // I do not know the purpose of transient map works for.
    Map<String, byte[]> transientMap = new HashMap<>();
    transientMap.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
    transientMap.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
    instantiateProposalRequest.setTransientMap(transientMap);
    return channel.sendInstantiationProposal(instantiateProposalRequest, channel.getPeers());
}
 
Example #6
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
void executeVerifyByQuery(HFClient client, Channel channel, String chaincodeName, String expect) throws ProposalException, InvalidArgumentException {
    out("Now query chaincode for the value of b.");
    QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
    queryByChaincodeRequest.setArgs("b");
    queryByChaincodeRequest.setFcn("query");
    queryByChaincodeRequest.setChaincodeName(chaincodeName);

    Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers());
    for (ProposalResponse proposalResponse : queryProposals) {
        if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
            fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                    ". Messages: " + proposalResponse.getMessage()
                    + ". Was verified : " + proposalResponse.isVerified());
        } else {
            String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
            out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
            assertEquals(expect, payload);
        }
    }

}
 
Example #7
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private void verifyNoInstalledChaincodes(HFClient client, Collection<Peer> peers) throws ProposalException, InvalidArgumentException {

        Collection<LifecycleQueryInstalledChaincodesProposalResponse> results = client.sendLifecycleQueryInstalledChaincodes(client.newLifecycleQueryInstalledChaincodesRequest(), peers);
        assertNotNull(results);
        assertEquals(peers.size(), results.size());

        for (LifecycleQueryInstalledChaincodesProposalResponse result : results) {

            final String peerName = result.getPeer().getName();
            assertEquals(format("Peer returned back bad status %s", peerName), result.getStatus(), ChaincodeResponse.Status.SUCCESS);
            Collection<LifecycleQueryInstalledChaincodesResult> lifecycleQueryInstalledChaincodesResult = result.getLifecycleQueryInstalledChaincodesResult();
            assertNotNull(format("Peer %s returned back null result.", peerName), lifecycleQueryInstalledChaincodesResult);
            assertTrue(format("Peer %s returned back result with chaincode installed.", peerName), lifecycleQueryInstalledChaincodesResult.isEmpty());

        }

    }
 
Example #8
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private void verifyByCheckCommitReadinessStatus(HFClient client, Channel channel, long definitionSequence, String chaincodeName,
                                                String chaincodeVersion, LifecycleChaincodeEndorsementPolicy chaincodeEndorsementPolicy,
                                                ChaincodeCollectionConfiguration chaincodeCollectionConfiguration, boolean initRequired, Collection<Peer> org1MyPeers,
                                                Set<String> expectedApproved, Set<String> expectedUnApproved) throws InvalidArgumentException, ProposalException {
    LifecycleCheckCommitReadinessRequest lifecycleCheckCommitReadinessRequest = client.newLifecycleSimulateCommitChaincodeDefinitionRequest();
    lifecycleCheckCommitReadinessRequest.setSequence(definitionSequence);
    lifecycleCheckCommitReadinessRequest.setChaincodeName(chaincodeName);
    lifecycleCheckCommitReadinessRequest.setChaincodeVersion(chaincodeVersion);
    if (null != chaincodeEndorsementPolicy) {
        lifecycleCheckCommitReadinessRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
    }
    if (null != chaincodeCollectionConfiguration) {
        lifecycleCheckCommitReadinessRequest.setChaincodeCollectionConfiguration(chaincodeCollectionConfiguration);
    }
    lifecycleCheckCommitReadinessRequest.setInitRequired(initRequired);

    Collection<LifecycleCheckCommitReadinessProposalResponse> lifecycleSimulateCommitChaincodeDefinitionProposalResponse = channel.sendLifecycleCheckCommitReadinessRequest(lifecycleCheckCommitReadinessRequest, org1MyPeers);
    for (LifecycleCheckCommitReadinessProposalResponse resp : lifecycleSimulateCommitChaincodeDefinitionProposalResponse) {
        final Peer peer = resp.getPeer();
        assertEquals(ChaincodeResponse.Status.SUCCESS, resp.getStatus());
        assertEquals(format("Approved orgs failed on %s", peer), expectedApproved, resp.getApprovedOrgs());
        assertEquals(format("UnApproved orgs failed on %s", peer), expectedUnApproved, resp.getUnApprovedOrgs());
    }
}
 
Example #9
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
public ChaincodeManager(String username, FabricConfig fabricConfig)
		throws CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, TransactionException {
	this.config = fabricConfig;

	orderers = this.config.getOrderers();
	peers = this.config.getPeers();
	chaincode = this.config.getChaincode();

	client = HFClient.createNewInstance();
	log.debug("Create instance of HFClient");
	client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
	log.debug("Set Crypto Suite of HFClient");

	fabricOrg = getFabricOrg(username, config.openCATLS());
	channel = getChannel();
	chaincodeID = getChaincodeID();

	client.setUserContext(fabricOrg.getPeerAdmin());
}
 
Example #10
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private void verifyByQueryInstalledChaincode(HFClient client, Collection<Peer> peers, String packageId, String expectedLabel) throws ProposalException, InvalidArgumentException {

        final LifecycleQueryInstalledChaincodeRequest lifecycleQueryInstalledChaincodeRequest = client.newLifecycleQueryInstalledChaincodeRequest();
        lifecycleQueryInstalledChaincodeRequest.setPackageID(packageId);

        Collection<LifecycleQueryInstalledChaincodeProposalResponse> responses = client.sendLifecycleQueryInstalledChaincode(lifecycleQueryInstalledChaincodeRequest, peers);
        assertNotNull(responses);
        assertEquals("responses not same as peers", peers.size(), responses.size());

        for (LifecycleQueryInstalledChaincodeProposalResponse response : responses) {
            assertEquals(ChaincodeResponse.Status.SUCCESS, response.getStatus());
            String peerName = response.getPeer().getName();
            assertEquals(format("Peer %s returned back bad status code", peerName), ChaincodeResponse.Status.SUCCESS, response.getStatus());
            assertEquals(format("Peer %s returned back different label", peerName), expectedLabel, response.getLabel());

        }
    }
 
Example #11
Source File: FabricStatementTest.java    From fabric-jdbc-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayElementType() throws Exception {
    PowerMockito.mockStatic(HFCAClient.class);
    when(HFCAClient.createNewInstance(anyString(), any())).thenReturn(mockCA);
    
    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);
    
    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);
    
    HyperUser mockuser = mock(HyperUser.class);
    when(mockuser.isEnrolled()).thenReturn(true);
    Store mockStore = mock(Store.class);
    PowerMockito.whenNew(Store.class).withAnyArguments().thenReturn(mockStore);
    
    String configPath = new File("src/test/resources/blockchain-query").getAbsolutePath();
    Class.forName("com.impetus.fabric.jdbc.FabricDriver");
    Connection conn = DriverManager.getConnection("jdbc:fabric://" + configPath + ":mychannel", 
            "admin", "adminpw");
    BlkchnStatement stat = (BlkchnStatement) conn.createStatement();
    int arrayElementType = stat.getArrayElementType("transaction_action", "chaincode_args");
    assertEquals(Types.VARCHAR, arrayElementType);
}
 
Example #12
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private void verifyByQueryChaincodeDefinitions(HFClient client, Channel channel, Collection<Peer> peers, String expectChaincodeName) throws InvalidArgumentException, ProposalException {

        final LifecycleQueryChaincodeDefinitionsRequest request = client.newLifecycleQueryChaincodeDefinitionsRequest();

        Collection<LifecycleQueryChaincodeDefinitionsProposalResponse> proposalResponses = channel.lifecycleQueryChaincodeDefinitions(request, peers);
        for (LifecycleQueryChaincodeDefinitionsProposalResponse proposalResponse : proposalResponses) {
            Peer peer = proposalResponse.getPeer();

            assertEquals(ChaincodeResponse.Status.SUCCESS, proposalResponse.getStatus());
            Collection<LifecycleQueryChaincodeDefinitionsResult> chaincodeDefinitions = proposalResponse.getLifecycleQueryChaincodeDefinitionsResult();

            Optional<String> matchingName = chaincodeDefinitions.stream()
                    .map(LifecycleQueryChaincodeDefinitionsResult::getName)
                    .filter(Predicate.isEqual(expectChaincodeName))
                    .findAny();
            assertTrue(format("On peer %s return namespace for chaincode %s", peer, expectChaincodeName), matchingName.isPresent());
        }
    }
 
Example #13
Source File: CommonService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public Channel initChannel(HFClient client, BaseRequest baseRequest){
    Channel currentChannel;
    try {
        currentChannel = FabricUtils.initChannel(client,baseRequest.getCurrentBlockChainOrgUserDTO(),baseRequest.getCurrentBlockChainOrgDTO(),
                baseRequest.getBlockChainChannelDTO(),baseRequest.getBaasRouteDTO(),baseRequest.getBlockChainOrdererDTOs());
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServiceException(ResponseCodeEnum.CHANNEL_INVOKE_ERROR,"初始化区块链配置失败");
    }
    return currentChannel;
}
 
Example #14
Source File: FabricService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
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 #15
Source File: FabricEventService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public void unRegisterContractListener(ContractEventListenerRequest contractEventListenerRequest) throws InvalidArgumentException {

        String channelName = contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetCode() +
                contractEventListenerRequest.getBlockChainChannelDTO().getChannelCode() +
                contractEventListenerRequest.getLeagueCode();

        ChannelBean channelBean = ChannelContext.getChannelContext(channelName);
        if(channelBean == null){
            HFClient client = HFClient.createNewInstance();
            Channel currentChannel = super.initChannel(client, contractEventListenerRequest);
            channelBean = new ChannelBean();
            channelBean.setChannel(currentChannel);
            ChannelContext.addChannelContext(channelName,channelBean);
        }

        for(BlockChainContractFunDTO funDTO : contractEventListenerRequest.getFunList()) {
            for (BlockChainContractFunEventDTO eventDTO : funDTO.getEventDTOList()) {

                String channelContractName = contractEventListenerRequest.getBlockChainNetDTO().getBlockChainNetCode() +
                        contractEventListenerRequest.getBlockChainChannelDTO().getChannelCode() +
                        contractEventListenerRequest.getLeagueCode() +
                        contractEventListenerRequest.getBlockChainContractDTO().getContractCode() +
                        funDTO.getFunCode() +
                        eventDTO.getEventCode();

                String eventListenerHandle = ChannelContext.getChainCodeEventHandlerContext
                        (channelContractName);

                channelBean.getChannel().unregisterBlockListener(eventListenerHandle);
                ChannelContext.removeChainCodeEventHandlerContext(channelContractName);

            }
            channelBean.setContractEventCount(channelBean.getContractEventCount() - 1);
            if (channelBean.getContractEventCount() == 0) {
                ChannelContext.removeChannelContext(channelName);
            }
        }
    }
 
Example #16
Source File: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
public Channel reconstructChannel(List<Peer> peers, HFClient client) {
    checkConfig();
    try {
        org.apache.log4j.Level setTo = null;
        setTo = org.apache.log4j.Level.DEBUG;
        org.apache.log4j.Logger.getLogger("org.hyperledger.fabric").setLevel(setTo);

        Channel newChannel = null;

        client.setUserContext(user);
        newChannel = client.newChannel(channelName);
        for (String orderName : userOrg.getOrdererNames()) {
            newChannel.addOrderer(client.newOrderer(orderName, userOrg.getOrdererLocation(orderName),
                    conf.getOrdererProperties(orderName)));
        }
        
        for (Peer peer : peers) {
            logger.debug(peer.getName());

            newChannel.addPeer(peer);
            userOrg.addPeer(peer);
        }
        newChannel.initialize();
        return newChannel;

    } catch (Exception e) {
        String errMsg = "QueryBlock | reconstructChannel " + e;
        logger.error(errMsg);
        throw new BlkchnException(errMsg, e);
    }

}
 
Example #17
Source File: FabricUtils.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public static Channel initChannel(HFClient client, BlockChainOrgUserDTO userDTO, BlockChainOrgDTO currentOrgDTO,
                                  BlockChainChannelDTO channelDTO, BaasRouteDTO routeDTO, List<BlockChainOrdererDTO> ordererList) throws Exception {
    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

    // 实例化用户需要先在控制台-证书管理中申请客户端证书,申请的企业名称需要与当前登录账户实名认证的企业名称相同
    FabricUser user = new FabricUser(userDTO.getOrgUserName(), new FabricEnrollment(userDTO.getOrgUserKey(), userDTO.getOrgUserCert()),
            currentOrgDTO.getMspId());

    client.setUserContext(user);

    Channel chain = client.newChannel(channelDTO.getChannelKey());

    for(BlockChainOrdererDTO ordererDTO: ordererList) {
        chain.addOrderer(client.newOrderer(ordererDTO.getOrdererKey(), routeDTO.getEndPoint(),
                FabricConfig.getOrderProperties(routeDTO.getSecretId(),routeDTO.getSecretKey(),ordererDTO.getOrdererKey())));
    }

    for(BlockChainOrgNodeDTO nodeDTO : currentOrgDTO.getNodeList()){
        chain.addPeer(client.newPeer(nodeDTO.getNodeKey(), routeDTO.getEndPoint(), FabricConfig.getPeerProperties(routeDTO.getSecretId(),
                routeDTO.getSecretKey(),nodeDTO.getNodeKey())),
                createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER,
                        Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE)));
        //registerEventsForFilteredBlocks()
    }


    chain.initialize();

    return chain;
}
 
Example #18
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static Orderer getOrderer(HFClient client, FabricConfig fabricConfig) throws InvalidArgumentException {
    Properties orderer1Prop = new Properties();
    orderer1Prop.setProperty("pemFile", fabricConfig.getOrdererTlsCaFile());
    orderer1Prop.setProperty("sslProvider", "openSSL");
    orderer1Prop.setProperty("negotiationType", "TLS");
    orderer1Prop.setProperty("ordererWaitTimeMilliSecs", "300000");
    orderer1Prop.setProperty("hostnameOverride", "orderer");
    orderer1Prop.setProperty("trustServerCertificate", "true");
    orderer1Prop.setProperty("allowAllHostNames", "true");
    return client.newOrderer("orderer", fabricConfig.getOrdererAddress(), orderer1Prop);
}
 
Example #19
Source File: OrgManager.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
public FabricManager use(String cc, String username) throws Exception {
        IntermediateOrg org = orgMap.get(cc);
//        org.init(fabricStore);
        org.setUsername(username);
        org.setClient(HFClient.createNewInstance());
        org.getChannel().init(org);
        return new FabricManager(org);
    }
 
Example #20
Source File: FabricService.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public InvokeAsyncQueryResult asyncQueryResult(InvokeAsyncQueryRequest invokeAsyncQueryRequest)  {
    HFClient client = HFClient.createNewInstance();
    Channel currentChannel = super.initChannel(client, invokeAsyncQueryRequest);

    FabricTemplate fabricTemplate = new FabricTemplate();
    FabricTemplate.setClient(client);

    InvokeAsyncQueryResult result = fabricTemplate.asyncQueryResult(currentChannel,invokeAsyncQueryRequest.getTxId());

    result.setOrderNo(invokeAsyncQueryRequest.getOrderNo());
    result.setRequestContext(JSONUtil.toJsonStr(invokeAsyncQueryRequest));
    result.setReturnNo(invokeAsyncQueryRequest.getTxId());
    result.setResponseContext(JSONUtil.toJsonStr(result));
    return result;
}
 
Example #21
Source File: PrivateDataIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public void runFabricTest(final SampleStore sampleStore) throws Exception {
    ////////////////////////////
    // Setup client

    //Create instance of client.
    HFClient client = HFClient.createNewInstance();

    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
    client.setUserContext(sampleStore.getMember(TEST_ADMIN_NAME, "peerOrg2"));

    SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg2");

    Channel barChannel = sampleStore.getChannel(client, BAR_CHANNEL_NAME);

    barChannel.initialize();
    runChannel(client, barChannel, sampleOrg, 10);
    assertFalse(barChannel.isShutdown());
    assertTrue(barChannel.isInitialized());

    if (testConfig.isFabricVersionAtOrAfter("1.3")) {
        Set<String> expect = new HashSet<>(Arrays.asList("COLLECTION_FOR_A", "COLLECTION_FOR_B"));
        Set<String> got = new HashSet<>();

        CollectionConfigPackage queryCollectionsConfig = barChannel.queryCollectionsConfig(CHAIN_CODE_NAME, barChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin());
        for (CollectionConfigPackage.CollectionConfig collectionConfig : queryCollectionsConfig.getCollectionConfigs()) {
            got.add(collectionConfig.getName());

        }
        assertEquals(expect, got);
    }

    out("That's all folks!");
}
 
Example #22
Source File: PrivateDataIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void queryChaincodeForExpectedValue(HFClient client, Channel channel, final String expect, ChaincodeID chaincodeID) {

        out("Now query chaincode %s on channel %s for the value of b expecting to see: %s", chaincodeID, channel.getName(), expect);
        Collection<ProposalResponse> queryProposals;
        try {
            QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
            queryByChaincodeRequest.setFcn("query");
            queryByChaincodeRequest.setChaincodeID(chaincodeID);

            Map<String, byte[]> tmap = new HashMap<>();
            tmap.put("B", "b".getBytes(UTF_8)); // test using bytes as args. End2end uses Strings.
            queryByChaincodeRequest.setTransientMap(tmap);

            queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
        } catch (Exception e) {
            throw new CompletionException(e);
        }

        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != Status.SUCCESS) {
                fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                        ". Messages: " + proposalResponse.getMessage()
                        + ". Was verified : " + proposalResponse.isVerified());
            } else {
                String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                assertEquals(format("Failed compare on channel %s chaincode id %s expected value:'%s', but got:'%s'",
                        channel.getName(), chaincodeID, expect, payload), expect, payload);
            }
        }
    }
 
Example #23
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
CompletableFuture<TransactionEvent> lifecycleApproveChaincodeDefinitionForMyOrg(HFClient client, Channel channel,
                                                                                Collection<Peer> peers, long sequence,
                                                                                String chaincodeName, String chaincodeVersion, LifecycleChaincodeEndorsementPolicy chaincodeEndorsementPolicy, ChaincodeCollectionConfiguration chaincodeCollectionConfiguration, boolean initRequired, String org1ChaincodePackageID) throws InvalidArgumentException, ProposalException {

    LifecycleApproveChaincodeDefinitionForMyOrgRequest lifecycleApproveChaincodeDefinitionForMyOrgRequest = client.newLifecycleApproveChaincodeDefinitionForMyOrgRequest();
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setSequence(sequence);
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeName(chaincodeName);
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeVersion(chaincodeVersion);
    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setInitRequired(initRequired);

    if (null != chaincodeCollectionConfiguration) {
        lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeCollectionConfiguration(chaincodeCollectionConfiguration);
    }

    if (null != chaincodeEndorsementPolicy) {
        lifecycleApproveChaincodeDefinitionForMyOrgRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
    }

    lifecycleApproveChaincodeDefinitionForMyOrgRequest.setPackageId(org1ChaincodePackageID);

    Collection<LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse> lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse = channel.sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(lifecycleApproveChaincodeDefinitionForMyOrgRequest,
            peers);

    assertEquals(peers.size(), lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse.size());
    for (LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse response : lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse) {
        final Peer peer = response.getPeer();

        assertEquals(format("failure on %s  message is: %s", peer, response.getMessage()), ChaincodeResponse.Status.SUCCESS, response.getStatus());
        assertFalse(peer + " " + response.getMessage(), response.isInvalid());
        assertTrue(format("failure on %s", peer), response.isVerified());
    }

    return channel.sendTransaction(lifecycleApproveChaincodeDefinitionForMyOrgProposalResponse);

}
 
Example #24
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<TransactionEvent> commitChaincodeDefinitionRequest(HFClient client, Channel channel, long definitionSequence, String chaincodeName, String chaincodeVersion,
                                                                             LifecycleChaincodeEndorsementPolicy chaincodeEndorsementPolicy,
                                                                             ChaincodeCollectionConfiguration chaincodeCollectionConfiguration,
                                                                             boolean initRequired, Collection<Peer> endorsingPeers) throws ProposalException, InvalidArgumentException, InterruptedException, ExecutionException, TimeoutException {
    LifecycleCommitChaincodeDefinitionRequest lifecycleCommitChaincodeDefinitionRequest = client.newLifecycleCommitChaincodeDefinitionRequest();

    lifecycleCommitChaincodeDefinitionRequest.setSequence(definitionSequence);
    lifecycleCommitChaincodeDefinitionRequest.setChaincodeName(chaincodeName);
    lifecycleCommitChaincodeDefinitionRequest.setChaincodeVersion(chaincodeVersion);
    if (null != chaincodeEndorsementPolicy) {
        lifecycleCommitChaincodeDefinitionRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
    }
    if (null != chaincodeCollectionConfiguration) {
        lifecycleCommitChaincodeDefinitionRequest.setChaincodeCollectionConfiguration(chaincodeCollectionConfiguration);
    }
    lifecycleCommitChaincodeDefinitionRequest.setInitRequired(initRequired);

    Collection<LifecycleCommitChaincodeDefinitionProposalResponse> lifecycleCommitChaincodeDefinitionProposalResponses = channel.sendLifecycleCommitChaincodeDefinitionProposal(lifecycleCommitChaincodeDefinitionRequest,
            endorsingPeers);

    for (LifecycleCommitChaincodeDefinitionProposalResponse resp : lifecycleCommitChaincodeDefinitionProposalResponses) {

        final Peer peer = resp.getPeer();
        assertEquals(format("%s had unexpected status.", peer.toString()), ChaincodeResponse.Status.SUCCESS, resp.getStatus());
        assertTrue(format("%s not verified.", peer.toString()), resp.isVerified());
    }

    return channel.sendTransaction(lifecycleCommitChaincodeDefinitionProposalResponses);

}
 
Example #25
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void verifyByQueryChaincodeDefinition(HFClient client, Channel channel, String chaincodeName, Collection<Peer> peers, long expectedSequence, boolean expectedInitRequired, byte[] expectedValidationParameter,
                                            ChaincodeCollectionConfiguration expectedChaincodeCollectionConfiguration) throws ProposalException, InvalidArgumentException, ChaincodeCollectionConfigurationException {

    final QueryLifecycleQueryChaincodeDefinitionRequest queryLifecycleQueryChaincodeDefinitionRequest = client.newQueryLifecycleQueryChaincodeDefinitionRequest();
    queryLifecycleQueryChaincodeDefinitionRequest.setChaincodeName(chaincodeName);

    Collection<LifecycleQueryChaincodeDefinitionProposalResponse> queryChaincodeDefinitionProposalResponses = channel.lifecycleQueryChaincodeDefinition(queryLifecycleQueryChaincodeDefinitionRequest, peers);

    assertNotNull(queryChaincodeDefinitionProposalResponses);
    assertEquals(peers.size(), queryChaincodeDefinitionProposalResponses.size());
    for (LifecycleQueryChaincodeDefinitionProposalResponse response : queryChaincodeDefinitionProposalResponses) {
        assertEquals(ChaincodeResponse.Status.SUCCESS, response.getStatus());
        assertEquals(expectedSequence, response.getSequence());
        if (expectedValidationParameter != null) {
            byte[] validationParameter = response.getValidationParameter();
            assertNotNull(validationParameter);
            assertArrayEquals(expectedValidationParameter, validationParameter);
        }

        if (null != expectedChaincodeCollectionConfiguration) {
            final ChaincodeCollectionConfiguration chaincodeCollectionConfiguration = response.getChaincodeCollectionConfiguration();
            assertNotNull(chaincodeCollectionConfiguration);
            assertArrayEquals(expectedChaincodeCollectionConfiguration.getAsBytes(), chaincodeCollectionConfiguration.getAsBytes());
        }

        ChaincodeCollectionConfiguration collections = response.getChaincodeCollectionConfiguration();
        assertEquals(expectedInitRequired, response.getInitRequired());
        assertEquals(DEFAULT_ENDORSMENT_PLUGIN, response.getEndorsementPlugin());
        assertEquals(DEFAULT_VALDITATION_PLUGIN, response.getValidationPlugin());
    }
}
 
Example #26
Source File: End2endLifecycleIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void verifyByQueryInstalledChaincodes(HFClient client, Collection<Peer> peers, String excpectedChaincodeLabel, String excpectedPackageId) throws ProposalException, InvalidArgumentException {

        Collection<LifecycleQueryInstalledChaincodesProposalResponse> results = client.sendLifecycleQueryInstalledChaincodes(client.newLifecycleQueryInstalledChaincodesRequest(), peers);
        assertNotNull(results);
        assertEquals(peers.size(), results.size());

        for (LifecycleQueryInstalledChaincodesProposalResponse peerResults : results) {
            boolean found = false;
            final String peerName = peerResults.getPeer().getName();

            assertEquals(format("Peer returned back bad status %s", peerName), peerResults.getStatus(), ChaincodeResponse.Status.SUCCESS);

            for (LifecycleQueryInstalledChaincodesResult lifecycleQueryInstalledChaincodesResult : peerResults.getLifecycleQueryInstalledChaincodesResult()) {

                if (excpectedPackageId.equals(lifecycleQueryInstalledChaincodesResult.getPackageId())) {
                    assertEquals(format("Peer %s had chaincode lable mismatch", peerName), excpectedChaincodeLabel, lifecycleQueryInstalledChaincodesResult.getLabel());
                    found = true;
                    break;
                }

            }
            assertTrue(format("Chaincode label %s, packageId %s not found on peer %s ", excpectedChaincodeLabel, excpectedPackageId, peerName), found);

        }
        return;

    }
 
Example #27
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private static String queryChaincodeForCurrentValue(HFClient client, Channel channel, ChaincodeID chaincodeID) {

        out("Now query chaincode on channel %s for the current value of b", channel.getName());

        QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
        queryByChaincodeRequest.setArgs("b");
        queryByChaincodeRequest.setFcn("query");
        queryByChaincodeRequest.setChaincodeID(chaincodeID);

        Collection<ProposalResponse> queryProposals;

        try {
            queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
        } catch (Exception e) {
            throw new CompletionException(e);
        }

        String expect = null;
        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != Status.SUCCESS) {
                fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                        ". Messages: " + proposalResponse.getMessage()
                        + ". Was verified : " + proposalResponse.isVerified());
            } else {
                String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                if (expect != null) {
                    assertEquals(expect, payload);
                } else {
                    expect = payload;
                }
            }
        }
        return expect;
    }
 
Example #28
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private static Channel constructChannel(HFClient client, String channelName) throws Exception {

        //Channel newChannel = client.getChannel(channelName);
        Channel newChannel = client.loadChannelFromConfig(channelName, networkConfig);
        if (newChannel == null) {
            throw new RuntimeException("Channel " + channelName + " is not defined in the config file!");
        }

        return newChannel.initialize();
    }
 
Example #29
Source File: SampleStore.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
Channel getChannel(HFClient client, String name) throws IOException, ClassNotFoundException, InvalidArgumentException {
    Channel ret = null;

    String channelHex = getValue("channel." + name);
    if (channelHex != null) {

        ret = client.deSerializeChannel(Hex.decode(channelHex));

    }
    return ret;
}
 
Example #30
Source File: End2endAndBackAgainIT.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void queryChaincodeForExpectedValue(HFClient client, Channel channel, final String expect, ChaincodeID chaincodeID) {

        out("Now query chaincode %s on channel %s for the value of b expecting to see: %s", chaincodeID, channel.getName(), expect);
        QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
        queryByChaincodeRequest.setArgs("b".getBytes(UTF_8)); // test using bytes as args. End2end uses Strings.
        queryByChaincodeRequest.setFcn("query");
        queryByChaincodeRequest.setChaincodeID(chaincodeID);

        Collection<ProposalResponse> queryProposals;

        try {
            queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
        } catch (Exception e) {
            throw new CompletionException(e);
        }

        for (ProposalResponse proposalResponse : queryProposals) {
            if (!proposalResponse.isVerified() || proposalResponse.getStatus() != Status.SUCCESS) {
                fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
                        ". Messages: " + proposalResponse.getMessage()
                        + ". Was verified : " + proposalResponse.isVerified());
            } else {
                String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                assertEquals(format("Failed compare on channel %s chaincode id %s expected value:'%s', but got:'%s'",
                        channel.getName(), chaincodeID, expect, payload), expect, payload);
            }
        }
    }