org.hyperledger.fabric.sdk.Peer Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.Peer. 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: End2endAndBackAgainIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private static boolean checkInstantiatedChaincode(Channel channel, Peer peer, String ccName, String ccPath, String ccVersion) throws InvalidArgumentException, ProposalException {
    out("Checking instantiated chaincode: %s, at version: %s, on peer: %s", ccName, ccVersion, peer.getName());
    List<ChaincodeInfo> ccinfoList = channel.queryInstantiatedChaincodes(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 #2
Source File: FabricClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Deploy chain code.
 * 
 * @param chainCodeName
 * @param chaincodePath
 * @param codepath
 * @param language
 * @param version
 * @param peers
 * @return
 * @throws InvalidArgumentException
 * @throws IOException
 * @throws ProposalException
 */
public Collection<ProposalResponse> deployChainCode(String chainCodeName, String chaincodePath, String codepath,
		String language, String version, Collection<Peer> peers)
		throws InvalidArgumentException, IOException, ProposalException {
	InstallProposalRequest request = instance.newInstallProposalRequest();
	ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(chainCodeName).setVersion(version)
			.setPath(chaincodePath);
	ChaincodeID chaincodeID = chaincodeIDBuilder.build();
	Logger.getLogger(FabricClient.class.getName()).log(Level.INFO,
			"Deploying chaincode " + chainCodeName + " using Fabric client " + instance.getUserContext().getMspId()
					+ " " + instance.getUserContext().getName());
	request.setChaincodeID(chaincodeID);
	request.setUserContext(instance.getUserContext());
	request.setChaincodeSourceLocation(new File(codepath));
	request.setChaincodeVersion(version);
	Collection<ProposalResponse> responses = instance.sendInstallProposal(request, peers);
	return responses;
}
 
Example #3
Source File: End2endAndBackAgainIT.java    From fabric_sdk_java_study with Apache License 2.0 6 votes vote down vote up
private static boolean checkInstantiatedChaincode(Channel channel, Peer peer, String ccName, String ccPath, String ccVersion) throws InvalidArgumentException, ProposalException {
    out("Checking instantiated chaincode: %s, at version: %s, on peer: %s", ccName, ccVersion, peer.getName());
    List<ChaincodeInfo> ccinfoList = channel.queryInstantiatedChaincodes(peer);

    boolean found = false;

    for (ChaincodeInfo ccifo : ccinfoList) {
        found = ccName.equals(ccifo.getName()) && ccPath.equals(ccifo.getPath()) && ccVersion.equals(ccifo.getVersion());
        if (found) {
            break;
        }

    }

    return found;
}
 
Example #4
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 #5
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 #6
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 #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: 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 #9
Source File: NetworkConfigIT.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private static boolean checkInstantiatedChaincode(Channel channel, Peer peer, String ccName, String ccPath, String ccVersion) throws InvalidArgumentException, ProposalException {
    out("Checking instantiated chaincode: %s, at version: %s, on peer: %s", ccName, ccVersion, peer.getName());
    List<ChaincodeInfo> ccinfoList = channel.queryInstantiatedChaincodes(peer);

    boolean found = false;

    for (ChaincodeInfo ccifo : ccinfoList) {
        found = ccName.equals(ccifo.getName()) && ccPath.equals(ccifo.getPath()) && ccVersion.equals(ccifo.getVersion());
        if (found) {
            break;
        }

    }

    return found;
}
 
Example #10
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static ListPage<TbNode> queryNodeList(FabricConfig fabricConfig,
                                             Channel channel,
                                             Integer pageIndex,
                                             Integer pageSize) throws ProposalException, InvalidArgumentException {
    ListPage<TbNode> tbNodeListPage = new ListPage<>();
    List<TbNode> tbNodes = new ArrayList<>();
    BlockInfo blockInfo = getBlockInfo(fabricConfig, channel, null);

    Collection<Peer> peers = channel.getPeers();
    peers.forEach(peer -> {
        TbNode tbNode = new TbNode();
        tbNode.setBlockNumber(BigInteger.valueOf(blockInfo.getBlockNumber()));
        tbNode.setNodeId(peer.getUrl());
        tbNode.setNodeActive(1);
        tbNode.setNodeType(WeEventConstants.NODE_TYPE_SEALER);
        tbNodes.add(tbNode);
    });

    tbNodeListPage.setPageIndex(pageIndex);
    tbNodeListPage.setPageSize(pageSize);
    tbNodeListPage.setTotal(peers.size());
    tbNodeListPage.setPageData(tbNodes);
    return tbNodeListPage;
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: ChaincodeServiceImpl.java    From balance-transfer-java with Apache License 2.0 5 votes vote down vote up
/**
 * gives blockchain info
 * 
 */
public void blockchainInfo(Org sampleOrg, Channel channel) {

	try {
		checkConfig();

		String channelName = channel.getName();
		Set<Peer> peerSet = sampleOrg.getPeers();
		// Peer queryPeer = peerSet.iterator().next();
		// out("Using peer %s for channel queries", queryPeer.getName());

		BlockchainInfo channelInfo = channel.queryBlockchainInfo();
		logger.info("Channel info for : " + channelName);
		logger.info("Channel height: " + channelInfo.getHeight());

		String chainCurrentHash = Hex.encodeHexString(channelInfo.getCurrentBlockHash());
		String chainPreviousHash = Hex.encodeHexString(channelInfo.getPreviousBlockHash());
		logger.info("Chain current block hash: " + chainCurrentHash);
		logger.info("Chainl previous block hash: " + chainPreviousHash);

		// Query by block number. Should return latest block, i.e. block
		// number 2
		BlockInfo returnedBlock = channel.queryBlockByNumber(channelInfo.getHeight() - 1);
		String previousHash = Hex.encodeHexString(returnedBlock.getPreviousHash());
		logger.info("queryBlockByNumber returned correct block with blockNumber " + returnedBlock.getBlockNumber()
		+ " \n previous_hash " + previousHash);

		// Query by block hash. Using latest block's previous hash so should
		// return block number 1
		byte[] hashQuery = returnedBlock.getPreviousHash();
		returnedBlock = channel.queryBlockByHash(hashQuery);
		logger.info("queryBlockByHash returned block with blockNumber " + returnedBlock.getBlockNumber());

	} catch (Exception e) {
		logger.error("ChaincodeServiceImpl | blockchainInfo | "+ e.getMessage());
	}
}
 
Example #18
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Channel initializeChannel(HFClient client, String channelName, FabricConfig fabricConfig) throws InvalidArgumentException, TransactionException {
    Orderer orderer1 = getOrderer(client, fabricConfig);

    Peer peer0 = getPeer(client, fabricConfig);

    Channel channel = client.newChannel(channelName);
    channel.addOrderer(orderer1);
    channel.addPeer(peer0);
    channel.initialize();
    return channel;
}
 
Example #19
Source File: Fabric.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public List<String> listChannelName(FabricConfig fabricConfig) throws BrokerException {
    try {
        Peer peer = FabricSDKWrapper.getPeer(hfClient, fabricConfig);
        Set<String> channels = hfClient.queryChannels(peer);
        return new ArrayList<>(channels);
    } catch (Exception e) {
        log.error("get channel name list failed , e: ", e);
        throw new BrokerException(ErrorCode.TRANSACTION_EXECUTE_ERROR);
    }
}
 
Example #20
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Peer getPeer(HFClient client, FabricConfig fabricConfig) throws InvalidArgumentException {
    Properties peer0Prop = new Properties();
    peer0Prop.setProperty("pemFile", fabricConfig.getPeerTlsCaFile());
    peer0Prop.setProperty("sslProvider", "openSSL");
    peer0Prop.setProperty("negotiationType", "TLS");
    peer0Prop.setProperty("hostnameOverride", "peer0");
    peer0Prop.setProperty("trustServerCertificate", "true");
    peer0Prop.setProperty("allowAllHostNames", "true");
    return client.newPeer("peer0", fabricConfig.getPeerAddress(), peer0Prop);
}
 
Example #21
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static List<Pair<String, String>> queryInstalledChaincodes(HFClient client, Peer peer) throws ProposalException, InvalidArgumentException {
    List<Query.ChaincodeInfo> listChainCodeInfo = client.queryInstalledChaincodes(peer);
    List<Pair<String, String>> chainCodeList = new ArrayList<>();
    listChainCodeInfo.forEach(chaincodeInfo ->
            chainCodeList.add(new Pair<>(chaincodeInfo.getName(), chaincodeInfo.getVersion()))
    );
    return chainCodeList;
}
 
Example #22
Source File: ChannelClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Query a transaction by id.
 * 
 * @param txnId
 * @return
 * @throws ProposalException
 * @throws InvalidArgumentException
 */
public TransactionInfo queryByTransactionId(String txnId) throws ProposalException, InvalidArgumentException {
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Querying by trasaction id " + txnId + " on channel " + channel.getName());
	Collection<Peer> peers = channel.getPeers();
	for (Peer peer : peers) {
		TransactionInfo info = channel.queryTransactionByID(peer, txnId);
		return info;
	}
	return null;
}
 
Example #23
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 #24
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 #25
Source File: UpdateChannelIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private Channel reconstructChannel(final boolean isSystemChannel, String name, HFClient client, SampleOrg sampleOrg) throws Exception {

        client.setUserContext(isSystemChannel ? ordererAdmin : sampleOrg.getPeerAdmin());
        Channel newChannel = client.newChannel(name);

        for (String orderName : sampleOrg.getOrdererNames()) {
            newChannel.addOrderer(client.newOrderer(orderName, sampleOrg.getOrdererLocation(orderName),
                    testConfig.getOrdererProperties(orderName)));
        }

        if (isSystemChannel) { // done
            newChannel.initialize();
            return newChannel;

        }

        assertTrue(sampleOrg.getPeerNames().size() > 1); // need at least two for testing.

        int i = 0;
        for (String peerName : sampleOrg.getPeerNames()) {
            String peerLocation = sampleOrg.getPeerLocation(peerName);
            Peer peer = client.newPeer(peerName, peerLocation, testConfig.getPeerProperties(peerName));

            //Query the actual peer for which channels it belongs to and check it belongs to this channel
            Set<String> channels = client.queryChannels(peer);
            if (!channels.contains(name)) {
                throw new AssertionError(format("Peer %s does not appear to belong to channel %s", peerName, name));
            }
            Channel.PeerOptions peerOptions = createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.CHAINCODE_QUERY,
                    Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.EVENT_SOURCE));

            if (i % 2 == 0) {
                peerOptions.registerEventsForFilteredBlocks(); // we need a mix of each type for testing.
            } else {
                peerOptions.registerEventsForBlocks();
            }
            ++i;

            newChannel.addPeer(peer, peerOptions);
        }

        //For testing of blocks which are not transactions.
        newChannel.registerBlockListener(blockEvent -> {
            eventQueueCaputure.add(blockEvent); // used with the other queued to make sure same.
            // Note peer eventing will always start with sending the last block so this will get the last endorser block
            int transactions = 0;
            int nonTransactions = 0;
            for (BlockInfo.EnvelopeInfo envelopeInfo : blockEvent.getEnvelopeInfos()) {

                if (BlockInfo.EnvelopeType.TRANSACTION_ENVELOPE == envelopeInfo.getType()) {
                    ++transactions;
                } else {
                    assertEquals(BlockInfo.EnvelopeType.ENVELOPE, envelopeInfo.getType());
                    ++nonTransactions;
                }

            }
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions < 2); // non transaction blocks only have one envelope
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions + transactions > 0); // has to be one.
            assertFalse(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions > 0 && transactions > 0); // can't have both.

            if (nonTransactions > 0) { // this is an update block -- don't care about others here.

                if (blockEvent.isFiltered()) {
                    ++eventCountFilteredBlock; // make sure we're seeing non transaction events.
                } else {
                    ++eventCountBlock;
                }
                assertEquals(0, blockEvent.getTransactionCount());
                assertEquals(1, blockEvent.getEnvelopeCount());
                for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) {
                    fail("Got transaction event in a block update"); // only events for update should not have transactions.
                }
            }
        });

        // Register Queued block listeners just for testing use both ways.
        // Ideally an application would have it's own independent thread to monitor and take off elements as fast as they can.
        // This would wait forever however if event could not be put in the queue like if the capacity is at a maximum. For LinkedBlockingQueue so unlikely
        listenerHandler1 = newChannel.registerBlockListener(blockingQueue1);
        assertNotNull(listenerHandler1);
        // This is the same but put a timeout on it.  If its not queued in time like if the queue is full it would generate a log warning and ignore the event.
        listenerHandler2 = newChannel.registerBlockListener(blockingQueue2, 1L, TimeUnit.SECONDS);
        assertNotNull(listenerHandler2);

        newChannel.initialize();

        return newChannel;
    }
 
Example #26
Source File: FabricTransaction.java    From spring-fabric-gateway with MIT License 4 votes vote down vote up
@Override
public Transaction setEndorsingPeers(Collection<Peer> peers) {
	endorsingPeers = peers;
	delegate.setEndorsingPeers(peers);
	return this;
}
 
Example #27
Source File: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
public Channel reconstructChannel()
{
    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 (String peerName : userOrg.getPeerNames()) {
            logger.debug(peerName);
            String peerLocation = userOrg.getPeerLocation(peerName);
            Peer peer = client.newPeer(peerName, peerLocation, conf.getPeerProperties(peerName));

            Set<String> channels = client.queryChannels(peer);
            if (!channels.contains(channelName)) {
                logger.info(String.format("Peer %s does not appear to belong to channel %s", peerName, channelName));
            }
            newChannel.addPeer(peer);
            userOrg.addPeer(peer);
        }

        for (String eventHubName : userOrg.getEventHubNames()) {
            EventHub eventHub = client.newEventHub(eventHubName, userOrg.getEventHubLocation(eventHubName),
                    conf.getEventHubProperties(eventHubName));
            newChannel.addEventHub(eventHub);
        }
        newChannel.initialize();
        return newChannel;

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

}
 
Example #28
Source File: Org.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
public Set<Peer> getPeers() {
    return Collections.unmodifiableSet(peers);
}
 
Example #29
Source File: Org.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
public void addPeer(Peer peer) {
    peers.add(peer);
}
 
Example #30
Source File: InvokeChaincode.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 4 votes vote down vote up
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();
	}
}