org.hyperledger.fabric.sdk.Channel Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.Channel. 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: FabricContext.java    From spring-fabric-gateway with MIT License 6 votes vote down vote up
public FabricQueryResponse<FabricLedger> queryBlockchainInfo() {
	try {
		if (network == null) {
			getContract();
		}
		Channel channel = network.getChannel();
		BlockchainInfo info = channel.queryBlockchainInfo();

		FabricLedger ledger = new FabricLedger();
		ledger.setChannel(channel.getName());
		ledger.setHeight(info.getHeight());
		ledger.setCurrentHash(Hex.encodeHexString(info.getCurrentBlockHash()));
		ledger.setPreviousHash(Hex.encodeHexString(info.getPreviousBlockHash()));
		ledger.setName(properties.getName());
		ledger.setOrgs(properties.getOrganizations());
		ledger.setChaincode(properties.getChaincode().getIdentify());
		ledger.setChaincodeName(properties.getChaincode().getName());
		ledger.setPeers(properties.getPeers());
		return FabricQueryResponse.success(ledger);
	} catch (Exception e) {
		e.printStackTrace();
		return FabricQueryResponse.failure(e.getLocalizedMessage());
	}
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static List<WeEvent> getBlockChainInfo(Channel channel, Long blockNumber) throws ProposalException, InvalidArgumentException, BrokerException {
    List<WeEvent> weEventList = new ArrayList<>();
    BlockInfo returnedBlock = channel.queryBlockByNumber(blockNumber);
    for (BlockInfo.EnvelopeInfo envelopeInfo : returnedBlock.getEnvelopeInfos()) {
        if (envelopeInfo.getType() == TRANSACTION_ENVELOPE) {
            BlockInfo.TransactionEnvelopeInfo transactionEnvelopeInfo = (BlockInfo.TransactionEnvelopeInfo) envelopeInfo;
            for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo transactionActionInfo : transactionEnvelopeInfo.getTransactionActionInfos()) {
                log.debug("chaincode input arguments count:{}", transactionActionInfo.getChaincodeInputArgsCount());
                if (transactionActionInfo.getChaincodeInputArgsCount() == WeEventConstants.DEFAULT_CHAINCODE_PARAM_COUNT && "publish".equals(new String(transactionActionInfo.getChaincodeInputArgs(0)))) {
                    WeEvent weEvent = new WeEvent();
                    weEvent.setTopic(new String(transactionActionInfo.getChaincodeInputArgs(1), UTF_8));
                    weEvent.setContent(transactionActionInfo.getChaincodeInputArgs(2));
                    weEvent.setExtensions(JsonHelper.json2Object(new String(transactionActionInfo.getChaincodeInputArgs(3)), new TypeReference<Map<String, String>>() {
                    }));
                    weEvent.setEventId(DataTypeUtils.encodeEventId(weEvent.getTopic(),
                            blockNumber.intValue(),
                            Integer.parseInt(new String(transactionActionInfo.getProposalResponsePayload()))));
                    weEventList.add(weEvent);
                    log.debug("weevent:{}", weEvent);
                }
            }
        }
    }
    return weEventList;
}
 
Example #7
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 #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: 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 #10
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 #11
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 #12
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 #13
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 #14
Source File: FabricUpdateContractUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    FabricConfig fabricConfig = new FabricConfig();
    fabricConfig.load("");

    HFClient client = FabricSDKWrapper.initializeClient(fabricConfig);
    Channel channel = FabricSDKWrapper.initializeChannel(client, fabricConfig.getChannelName(), fabricConfig);
    ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(fabricConfig.getTopicControllerName()).setVersion(fabricConfig.getTopicControllerVersion()).build();
    switch (args[0]) {
        case "add":
            FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, true, "addTopicContractName", fabricConfig.getTransactionTimeout(), fabricConfig.getTopicName(), fabricConfig.getTopicVerison());
            String topicContractNameAdd = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractName", fabricConfig.getTransactionTimeout()).getPayLoad();
            String topicContractVersionAdd = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractVersion", fabricConfig.getTransactionTimeout()).getPayLoad();
            if (fabricConfig.getTopicName().equals(topicContractNameAdd) && fabricConfig.getTopicVerison().equals(topicContractVersionAdd)) {
                log.debug("add TopicContract success");
            } else {
                log.error("add TopicContrct error");
                systemExit(1);
            }
            break;
        case "update":
            FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, true, "updateTopicContractName", fabricConfig.getTransactionTimeout(), fabricConfig.getTopicName(), fabricConfig.getTopicVerison());
            String topicContractNameUpdate = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractName", fabricConfig.getTransactionTimeout()).getPayLoad();
            String topicContractVersionUpdate = FabricSDKWrapper.executeTransaction(client, channel, chaincodeID, false, "getTopicContractVersion", fabricConfig.getTransactionTimeout()).getPayLoad();
            if (fabricConfig.getTopicName().equals(topicContractNameUpdate) && fabricConfig.getTopicVerison().equals(topicContractVersionUpdate)) {
                log.debug("update TopicContract success");
            } else {
                log.error("update TopicContrct error");
                systemExit(1);
            }
            break;
        default:
            log.error("update TopicContract, error command action");
            systemExit(1);
            break;
    }
}
 
Example #15
Source File: FabricStatementTest.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSchema() 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 block_no, previous_hash from block";
    ResultSetMetaData metadata = stat.getSchema(sql);
    int columnCount = metadata.getColumnCount();
    assertEquals(2, columnCount);
    assertEquals(metadata.getColumnName(1), "block_no");
    assertEquals(metadata.getColumnName(2), "previous_hash");
    assertEquals(metadata.getColumnType(1), Types.BIGINT);
    assertEquals(metadata.getColumnType(2), Types.VARCHAR);
}
 
Example #16
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 #17
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 #18
Source File: QueryBlockTest.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInstallChainCode() throws ClassNotFoundException, SQLException, InvalidArgumentException{

    PowerMockito.mockStatic(SDKUtils.class);

    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);

    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);

    InstallProposalRequest mockInstallProposalRequest = mock(InstallProposalRequest.class);
    when(mockClient.newInstallProposalRequest()).thenReturn(mockInstallProposalRequest);


    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 chaincodePath = "hyperledger/fabric/examples/chaincode/go/chaincode_example02";


    when(SDKUtils.getProposalConsistencySets(anyCollection())).thenReturn(new ArrayList<>());
    String result = qb.installChaincode(chaincodeName, version, qb.getConf().getConfigPath(), chaincodePath);
    assert(result.equals("Chaincode installed successfully"));

}
 
Example #19
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static BlockInfo getBlockInfo(FabricConfig fabricConfig, Channel channel, BigInteger blockNumber) throws ProposalException, InvalidArgumentException {
    BlockInfo blockInfo;
    if (blockNumber == null) {
        long currentBlockNum = channel.queryBlockchainInfo(new FabricUser(fabricConfig)).getHeight() - 1;
        blockInfo = channel.queryBlockByNumber(currentBlockNum);
    } else {
        blockInfo = channel.queryBlockByNumber(blockNumber.longValue());
    }
    return blockInfo;
}
 
Example #20
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 #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: 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 #23
Source File: ChaincodeController.java    From balance-transfer-java with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * Return the channel that has been recreated , it takes the JWT token of
 * the user that is constructing it.
 * 
 * @param Authorization
 * @returns the channel that has been recreated
 */
@RequestMapping(value = "/api/reconstruct", method = RequestMethod.PUT)
public ResponseEntity<String> recreateChannel(@RequestHeader String Authorization) throws Exception {

	String uname = JwtFilter.uname;
	if(uname!=null)
	{

	String result = chaincodeService.enrollAndRegister(uname);
	if (result != "Failed to enroll user") {
		Channel ch =chaincodeService.reconstructChannel();
		if(ch==null)
		{
			return ResponseEntity
					.status(HttpStatus.FORBIDDEN)
					.body("Channel recreation failed");
		}
		return ResponseEntity
				.status(HttpStatus.OK)
				.body("Channel recreated successfully");
	} else {
		return ResponseEntity
				.status(HttpStatus.FORBIDDEN)
				.body("Something went wrong");
	}
	}		
	else
	{
		return ResponseEntity
				.status(HttpStatus.FORBIDDEN)
				.body("Invalid JWT Token");
		
	}
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
Source File: End2endAndBackAgainIT.java    From fabric_sdk_java_study 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 on channel %s for the value of b expecting to see: %s", channel.getName(), expect);
        QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
        queryByChaincodeRequest.setArgs(new String[] {"query", "b"});
        queryByChaincodeRequest.setFcn("invoke");
        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(payload, expect);
            }
        }
    }
 
Example #29
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 #30
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;
}