org.hyperledger.fabric.sdk.exception.ProposalException Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.exception.ProposalException. 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: Fabric.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public boolean createTopic(String topicName) throws BrokerException {
    try {
        TransactionInfo transactionInfo = FabricSDKWrapper.executeTransaction(hfClient, channel, topicControllerChaincodeID, true, "addTopicInfo",
                fabricConfig.getTransactionTimeout(), topicName, fabricConfig.getTopicVerison());
        if (ErrorCode.SUCCESS.getCode() != transactionInfo.getCode()) {
            if (WeEventConstants.TOPIC_ALREADY_EXIST.equals(transactionInfo.getMessage())) {
                throw new BrokerException(ErrorCode.TOPIC_ALREADY_EXIST);
            }
            throw new BrokerException(transactionInfo.getCode(), transactionInfo.getMessage());
        }
        return true;
    } catch (InterruptedException | ProposalException | ExecutionException | InvalidArgumentException exception) {
        log.error("create topic :{} failed due to transaction execution error.{}", topicName, exception);
        throw new BrokerException(ErrorCode.TRANSACTION_EXECUTE_ERROR);
    } catch (TimeoutException timeout) {
        log.error("create topic :{} failed due to transaction execution timeout. {}", topicName, timeout);
        throw new BrokerException(ErrorCode.TRANSACTION_TIMEOUT);
    }
}
 
Example #2
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 #3
Source File: IntermediateChannel.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * Peer加入频道
 *
 * @param peer 中继节点信息
 */
JSONObject joinPeer(IntermediatePeer peer) throws InvalidArgumentException, ProposalException {
    Properties peerProperties = new Properties();
    if (org.openTLS()) {
        File peerCert = new File(org.getPeers().get(0).getServerCrtPath());
        if (!peerCert.exists()) {
            throw new RuntimeException(
                    String.format("Missing cert file for: %s. Could not find at location: %s", peer.getPeerName(), peerCert.getAbsolutePath()));
        }
        peerProperties.setProperty("pemFile", peerCert.getAbsolutePath());
    }
    // ret.setProperty("trustServerCertificate", "true"); //testing
    // environment only NOT FOR PRODUCTION!
    peerProperties.setProperty("hostnameOverride", peer.getPeerName());
    peerProperties.setProperty("sslProvider", "openSSL");
    peerProperties.setProperty("negotiationType", "TLS");
    // 在grpc的NettyChannelBuilder上设置特定选项
    peerProperties.put("grpc.ManagedChannelBuilderOption.maxInboundMessageSize", 9000000);
    // 如果未加入频道,该方法执行加入。如果已加入频道,则执行下一行方面新增Peer
    // channel.joinPeer(client.newPeer(peers.get().get(i).getPeerName(), fabricOrg.getPeerLocation(peers.get().get(i).getPeerName()), peerProperties));
    channel.joinPeer(org.getClient().newPeer(peer.getPeerName(), peer.getPeerLocation(), peerProperties));
    if (null != peer.getPeerEventHubLocation() && !peer.getPeerEventHubLocation().isEmpty()) {
        channel.addEventHub(org.getClient().newEventHub(peer.getPeerName(), peer.getPeerEventHubLocation(), peerProperties));
    }
    return getSuccessFromString();
}
 
Example #4
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 #5
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 #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: 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: 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 #10
Source File: IntermediateChaincodeID.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * 实例化智能合约
 *
 * @param org  中继组织对象
 * @param args 初始化参数数组
 */
JSONObject instantiate(IntermediateOrg org, String[] args) throws ProposalException, InvalidArgumentException, IOException, ChaincodeEndorsementPolicyParseException, TransactionException {
    /// Send transaction proposal to all peers
    InstantiateProposalRequest instantiateProposalRequest = org.getClient().newInstantiationProposalRequest();
    instantiateProposalRequest.setChaincodeID(chaincodeID);
    instantiateProposalRequest.setProposalWaitTime(proposalWaitTime);
    instantiateProposalRequest.setArgs(args);

    ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
    chaincodeEndorsementPolicy.fromYamlFile(new File(chaincodePolicy));
    instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);

    Map<String, byte[]> tm2 = new HashMap<>();
    tm2.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
    tm2.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
    tm2.put("result", ":)".getBytes(UTF_8));
    instantiateProposalRequest.setTransientMap(tm2);

    long currentStart = System.currentTimeMillis();
    Collection<ProposalResponse> instantiateProposalResponses = org.getChannel().get().sendInstantiationProposal(instantiateProposalRequest, org.getChannel().get().getPeers());
    log.info("chaincode instantiate transaction proposal time = " + (System.currentTimeMillis() - currentStart));
    return toOrdererResponse(instantiateProposalResponses, org);
}
 
Example #11
Source File: IntermediateChaincodeID.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * 执行智能合约
 *
 * @param org  中继组织对象
 * @param fcn  方法名
 * @param args 参数数组
 */
JSONObject invoke(IntermediateOrg org, String fcn, String[] args) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
    /// Send transaction proposal to all peers
    TransactionProposalRequest transactionProposalRequest = org.getClient().newTransactionProposalRequest();
    transactionProposalRequest.setChaincodeID(chaincodeID);
    transactionProposalRequest.setFcn(fcn);
    transactionProposalRequest.setArgs(args);
    transactionProposalRequest.setProposalWaitTime(proposalWaitTime);

    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));
    transactionProposalRequest.setTransientMap(tm2);

    long currentStart = System.currentTimeMillis();
    Collection<ProposalResponse> transactionProposalResponses = org.getChannel().get().sendTransactionProposal(transactionProposalRequest, org.getChannel().get().getPeers());
    log.info("chaincode invoke transaction proposal time = " + (System.currentTimeMillis() - currentStart));
    return toOrdererResponse(transactionProposalResponses, org);
}
 
Example #12
Source File: IntermediateChaincodeID.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * 查询智能合约
 *
 * @param org     中继组织对象
 * @param fcn     方法名
 * @param args    参数数组
 */
JSONObject query(IntermediateOrg org, String fcn, String[] args) throws InvalidArgumentException, ProposalException, TransactionException {
    QueryByChaincodeRequest queryByChaincodeRequest = org.getClient().newQueryProposalRequest();
    queryByChaincodeRequest.setArgs(args);
    queryByChaincodeRequest.setFcn(fcn);
    queryByChaincodeRequest.setChaincodeID(chaincodeID);
    queryByChaincodeRequest.setProposalWaitTime(proposalWaitTime);

    Map<String, byte[]> tm2 = new HashMap<>();
    tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
    tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
    queryByChaincodeRequest.setTransientMap(tm2);

    long currentStart = System.currentTimeMillis();
    Collection<ProposalResponse> queryProposalResponses = org.getChannel().get().queryByChaincode(queryByChaincodeRequest, org.getChannel().get().getPeers());
    log.info("chaincode query transaction proposal time = " + (System.currentTimeMillis() - currentStart));
    return toPeerResponse(queryProposalResponses, true);
}
 
Example #13
Source File: LifecycleQueryChaincodeDefinitionsProposalResponse.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private Lifecycle.QueryChaincodeDefinitionsResult getPayload() throws ProposalException {
    if (null == queryChaincodeDefinitionsResult) {
        if (getStatus() != Status.SUCCESS) {
            throw new ProposalException(format("Fabric response failed on peer %s  %s", getPeer(), getMessage()));
        }

        ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse();
        if (null == fabricResponse) {
            throw new ProposalException(format("Proposal has no Fabric response. %s", getPeer()));
        }

        ByteString responsePayload = fabricResponse.getResponse().getPayload();
        if (responsePayload == null) {
            throw new ProposalException(format("Fabric response has no payload  %s", getPeer()));
        }

        try {
            queryChaincodeDefinitionsResult = Lifecycle.QueryChaincodeDefinitionsResult.parseFrom(responsePayload);
        } catch (Exception e) {
            throw new ProposalException(format("Failure on peer %s %s", getPeer(), e.getMessage()), e);
        }
    }

    return queryChaincodeDefinitionsResult;
}
 
Example #14
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 #15
Source File: InstallProposalBuilderTest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildInvalidSource() throws Exception {

    // A mock InputStream that throws an IOException
    class MockInputStream extends InputStream {
        @Override
        public int read() throws IOException {
            throw new IOException("Cannot read!");
        }
    }

    thrown.expect(ProposalException.class);
    thrown.expectMessage("IO Error");

    InstallProposalBuilder builder = createTestBuilder();

    builder.setChaincodeLanguage(TransactionRequest.Type.JAVA);
    builder.setChaincodeInputStream(new MockInputStream());

    builder.build();
}
 
Example #16
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 #17
Source File: LifecycleQueryChaincodeDefinitionBuilder.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException {

    List<ByteString> argList = new ArrayList<>();
    argList.add(ByteString.copyFromUtf8("QueryChaincodeDefinition"));
    argList.add(Lifecycle.QueryChaincodeDefinitionArgs.newBuilder().setName(chaincodeName).build().toByteString());
    args(argList);
    return super.build();
}
 
Example #18
Source File: LifecycleQueryChaincodeDefinitionProposalResponse.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private Lifecycle.QueryChaincodeDefinitionResult parsePayload() throws ProposalException {
    if (null == queryChaincodeDefinitionResult) {
        if (getStatus() != Status.SUCCESS) {
            throw new ProposalException(format("Fabric response failed on peer %s  %s", getPeer(), getMessage()));
        }

        ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse();
        if (null == fabricResponse) {
            throw new ProposalException("Proposal has no Fabric response.");
        }

        ByteString payload = fabricResponse.getPayload();
        if (payload == null) {
            throw new ProposalException("Fabric response has no payload");
        }

        try {
            byte[] chaincodeActionResponsePayload = getChaincodeActionResponsePayload();
            if (null == chaincodeActionResponsePayload) {
                throw new ProposalException("Fabric chaincode action response payload is null.");
            }
            queryChaincodeDefinitionResult = Lifecycle.QueryChaincodeDefinitionResult.parseFrom(getChaincodeActionResponsePayload());
        } catch (Exception e) {
            throw new ProposalException(format("Failure on peer %s %s", getPeer(), e.getMessage()), e);
        }
    }

    return queryChaincodeDefinitionResult;
}
 
Example #19
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static void generateTbBlock(Channel channel, BigInteger blockNumber, BlockInfo lastestblockInfo, BlockInfo blockInfo, TbBlock tbBlock) throws InvalidArgumentException, ProposalException, InvalidProtocolBufferException {
    if (blockNumber.longValue() != lastestblockInfo.getBlockNumber()) {
        BlockInfo nextBlockInfo = channel.queryBlockByNumber(blockNumber.longValue() + 1);
        tbBlock.setPkHash(Hex.encodeHexString(nextBlockInfo.getPreviousHash()));
    } else {
        BlockchainInfo blockchainInfo = channel.queryBlockchainInfo();
        tbBlock.setPkHash(Hex.encodeHexString(blockchainInfo.getCurrentBlockHash()));
    }
    if (blockInfo.getEnvelopeCount() > 0) {
        tbBlock.setBlockTimestamp(DataTypeUtils.getTimestamp(blockInfo.getEnvelopeInfo(0).getTimestamp()));
    }
    tbBlock.setTransCount(blockInfo.getEnvelopeCount());
    tbBlock.setBlockNumber(blockNumber);
}
 
Example #20
Source File: ChannelTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testChannelShutdownJoinPeer() throws Exception {
    thrown.expect(ProposalException.class);
    thrown.expectMessage("Channel shutdown has been shutdown.");

    Assert.assertTrue(shutdownChannel.isShutdown());
    shutdownChannel.joinPeer(hfclient.newPeer("name", "grpc://myurl:90"));
}
 
Example #21
Source File: LifecycleCheckCommitReadinessProposalResponse.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * The set of organizations that have not approved this chaincode definition.
 *
 * @return
 * @throws ProposalException
 */
public Set<String> getUnApprovedOrgs() throws ProposalException {
    return getApprovalsMap().entrySet().stream()
            .filter(entry -> !entry.getValue())
            .map(Map.Entry::getKey)
            .collect(Collectors.toSet());
}
 
Example #22
Source File: IntermediateChannel.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
/** 查询当前频道的链信息,包括链长度、当前最新区块hash以及当前最新区块的上一区块hash */
JSONObject queryBlockChainInfo() throws InvalidArgumentException, ProposalException, TransactionException {
    if (!channel.isInitialized()) {
        initChannel();
    }
    JSONObject blockchainInfo = new JSONObject();
    blockchainInfo.put("height", channel.queryBlockchainInfo().getHeight());
    blockchainInfo.put("currentBlockHash", Hex.encodeHexString(channel.queryBlockchainInfo().getCurrentBlockHash()));
    blockchainInfo.put("previousBlockHash", Hex.encodeHexString(channel.queryBlockchainInfo().getPreviousBlockHash()));
    return getSuccess(blockchainInfo);
}
 
Example #23
Source File: IntermediateChannel.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
/**
 * 在指定频道内根据transactionID查询区块
 *
 * @param txID transactionID
 */
JSONObject queryBlockByTransactionID(String txID) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
    if (!channel.isInitialized()) {
        initChannel();
    }
    return execBlockInfo(channel.queryBlockByTransactionID(txID));
}
 
Example #24
Source File: LifecycleQueryChaincodeDefinitionProposalResponse.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * The validation parameter bytes that were set when the chaincode was defined.
 *
 * @return validation parameter.
 * @throws ProposalException
 */
public byte[] getValidationParameter() throws ProposalException {
    ByteString payloadBytes = parsePayload().getValidationParameter();
    if (null == payloadBytes) {
        return null;
    }
    return payloadBytes.toByteArray();
}
 
Example #25
Source File: ChannelTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryInstalledChaincodesThrowTimeoutException() throws Exception {
    thrown.expect(ProposalException.class);
    thrown.expectMessage("What time is it?");

    final Channel channel = createRunningChannel(null);
    Peer peer = channel.getPeers().iterator().next();

    setField(peer, "endorserClent", new MockEndorserClient(new PeerException("What time is it?")));

    hfclient.queryChannels(peer);
}
 
Example #26
Source File: LifecycleCheckCommitReadinessBuilder.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public ProposalPackage.Proposal build() throws ProposalException, InvalidArgumentException {
    List<ByteString> argList = new ArrayList<>();
    argList.add(ByteString.copyFromUtf8("CheckCommitReadiness"));
    argList.add(builder.build().toByteString());
    args(argList);
    return super.build();
}
 
Example #27
Source File: LifecycleQueryInstalledChaincodeProposalResponse.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * The lable used by this chaincode. This is defined by the installed chaincode. See label parameter in {@link LifecycleChaincodePackage#fromSource(String, Path, TransactionRequest.Type, String, Path)}
 * @return the label
 * @throws ProposalException
 */
public String getLabel() throws ProposalException {
    Lifecycle.QueryInstalledChaincodeResult queryInstalledChaincodeResult = parsePayload();

    if (queryInstalledChaincodeResult == null) {
        return null;
    }
    return queryInstalledChaincodeResult.getLabel();
}
 
Example #28
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 #29
Source File: FabricTemplate.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public BlockchainInfo getBlockInfo(Channel chain) throws InvalidArgumentException, ProposalException {
    client.queryChannels((Peer) chain.getPeers().toArray()[0]);//通道总数
    client.queryInstalledChaincodes((Peer) chain.getPeers().toArray()[0]);//安装的合约数
    chain.queryInstantiatedChaincodes((Peer) chain.getPeers().toArray()[0]);//当前组织安装合约数
    chain.getDiscoveredChaincodeNames();//
    chain.getPeersOrganizationMSPIDs();//
    chain.getPeers();//peer总数
    chain.getOrderers();//排序总数
    chain.getOrderersOrganizationMSPIDs();//组织总数
    BlockchainInfo blockchainInfo = chain.queryBlockchainInfo();
    blockchainInfo.getHeight();//当前通道区块高度
    return null;
}
 
Example #30
Source File: LifecycleQueryInstalledChaincodesProposalResponse.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private Lifecycle.QueryInstalledChaincodesResult parsePayload() throws ProposalException {
    if (null == queryChaincodeDefinitionResult) {
        if (getStatus() != Status.SUCCESS) {
            throw new ProposalException(format("Fabric response failed on peer %s  %s", getPeer(), getMessage()));
        }

        ProposalResponsePackage.ProposalResponse fabricResponse = getProposalResponse();

        if (null == fabricResponse) {
            throw new ProposalException(format("Proposal has no Fabric response. %s", getPeer()));
        }

        ByteString payload = fabricResponse.getResponse().getPayload();

        if (payload == null) {
            throw new ProposalException(format("Fabric response has no payload  %s", getPeer()));
        }

        try {
            queryChaincodeDefinitionResult = Lifecycle.QueryInstalledChaincodesResult.parseFrom(payload);
        } catch (Exception e) {
            throw new ProposalException(format("Failure on peer %s %s", getPeer(), e.getMessage()), e);
        }
    }

    return queryChaincodeDefinitionResult;
}