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

The following examples show how to use org.hyperledger.fabric.sdk.exception.InvalidArgumentException. 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: ChannelClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Send transaction proposal.
 * 
 * @param request
 * @return
 * @throws ProposalException
 * @throws InvalidArgumentException
 */
public Collection<ProposalResponse> sendTransactionProposal(TransactionProposalRequest request)
		throws ProposalException, InvalidArgumentException {
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Sending transaction proposal on channel " + channel.getName());

	Collection<ProposalResponse> response = channel.sendTransactionProposal(request, channel.getPeers());
	for (ProposalResponse pres : response) {
		String stringResponse = new String(pres.getChaincodeActionResponsePayload());
		Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
				"Transaction proposal on channel " + channel.getName() + " " + pres.getMessage() + " "
						+ pres.getStatus() + " with transaction id:" + pres.getTransactionID());
		Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,stringResponse);
	}

	CompletableFuture<TransactionEvent> cf = channel.sendTransaction(response);
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,cf.toString());

	return response;
}
 
Example #2
Source File: Fabric.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<SendResult> publishEvent(String topicName, String eventContent, String extensions) throws BrokerException {
    if (!isTopicExist(topicName)) {
        throw new BrokerException(ErrorCode.TOPIC_NOT_EXIST);
    }

    SendResult sendResult = new SendResult();
    sendResult.setTopic(topicName);
    try {
        return FabricSDKWrapper.executeTransactionAsync(hfClient,
                channel,
                topicChaincodeID,
                true,
                "publish",
                topicName,
                eventContent,
                extensions).thenApply(transactionInfo -> {
            sendResult.setStatus(SendResult.SendResultStatus.SUCCESS);
            sendResult.setEventId(DataTypeUtils.encodeEventId(topicName, transactionInfo.getBlockNumber().intValue(), Integer.parseInt(transactionInfo.getPayLoad())));
            sendResult.setTopic(topicName);
            return sendResult;
        });
    } catch (ProposalException | InvalidArgumentException exception) {
        log.error("publish event failed due to transaction execution error.", exception);
        throw new BrokerException(ErrorCode.TRANSACTION_EXECUTE_ERROR);
    }
}
 
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: 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 #5
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 #6
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static ListPage<TbTransHash> queryTransList(FabricConfig fabricConfig,
                                                   Channel channel,
                                                   BigInteger blockNumber,
                                                   String blockHash, Integer pageIndex,
                                                   Integer pageSize) throws ProposalException, InvalidArgumentException, BrokerException, DecoderException {
    ListPage<TbTransHash> tbTransHashListPage = new ListPage<>();
    List<TbTransHash> tbTransHashes = new ArrayList<>();

    BlockInfo blockInfo;
    if (!StringUtils.isBlank(blockHash)) {
        blockInfo = channel.queryBlockByHash(Hex.decodeHex(blockHash.toCharArray()));
    } else {
        blockInfo = getBlockInfo(fabricConfig, channel, blockNumber);
    }

    if (blockInfo == null) {
        log.error("query block by blockHash failed, block is empty.");
        throw new BrokerException("query block by blockHash failed, block is empty.");
    }
    generateTbTransHashListPage(pageIndex, pageSize, tbTransHashListPage, tbTransHashes, blockInfo);

    tbTransHashListPage.setPageData(tbTransHashes);
    return tbTransHashListPage;
}
 
Example #7
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 #8
Source File: FabricQueryResponse.java    From spring-fabric-gateway with MIT License 6 votes vote down vote up
public static <T> FabricQueryResponse<T> create(ProposalResponse res, Class<T> type) {
	Status status = res.getStatus();
	if (status != Status.SUCCESS) {
		return failure(res.getMessage());
	} else {
		if (type != null) {
			try {
				int chaincodeStatus = res.getChaincodeActionResponseStatus();
				if (chaincodeStatus != -1) {

					byte[] payload = res.getChaincodeActionResponsePayload();
					return create(payload, type);
				} else {
					return failure("Chaincode executed failure.");
				}
			} catch (InvalidArgumentException e) {
				return failure("Chaincode error: " + e.getMessage());
			}
		} else {
			return success(null);
		}
	}
}
 
Example #9
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
public ChaincodeManager(String username, FabricConfig fabricConfig)
		throws CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, TransactionException {
	this.config = fabricConfig;

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

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

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

	client.setUserContext(fabricOrg.getPeerAdmin());
}
 
Example #10
Source File: 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 #11
Source File: IntermediateChannel.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * 解析区块信息对象
 *
 * @param blockInfo 区块信息对象
 */
private JSONObject execBlockInfo(BlockInfo blockInfo) throws IOException, InvalidArgumentException {
    final long blockNumber = blockInfo.getBlockNumber();
    JSONObject blockJson = new JSONObject();
    blockJson.put("blockNumber", blockNumber);
    blockJson.put("dataHash", Hex.encodeHexString(blockInfo.getDataHash()));
    blockJson.put("previousHashID", Hex.encodeHexString(blockInfo.getPreviousHash()));
    blockJson.put("calculatedBlockHash", Hex.encodeHexString(SDKUtils.calculateBlockHash(org.getClient(), blockNumber, blockInfo.getPreviousHash(), blockInfo.getDataHash())));
    blockJson.put("envelopeCount", blockInfo.getEnvelopeCount());

    log.debug("blockNumber = " + blockNumber);
    log.debug("data hash: " + Hex.encodeHexString(blockInfo.getDataHash()));
    log.debug("previous hash id: " + Hex.encodeHexString(blockInfo.getPreviousHash()));
    log.debug("calculated block hash is " + Hex.encodeHexString(SDKUtils.calculateBlockHash(org.getClient(), blockNumber, blockInfo.getPreviousHash(), blockInfo.getDataHash())));
    log.debug("block number " + blockNumber + " has " + blockInfo.getEnvelopeCount() + " envelope count:");

    blockJson.put("envelopes", getEnvelopeJsonArray(blockInfo, blockNumber));
    return getSuccess(blockJson);
}
 
Example #12
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 #13
Source File: IntermediateChaincodeID.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * 升级智能合约
 *
 * @param org  中继组织对象
 * @param args 初始化参数数组
 */
JSONObject upgrade(IntermediateOrg org, String[] args) throws ProposalException, InvalidArgumentException, IOException, ChaincodeEndorsementPolicyParseException, TransactionException {
    /// Send transaction proposal to all peers
    UpgradeProposalRequest upgradeProposalRequest = org.getClient().newUpgradeProposalRequest();
    upgradeProposalRequest.setChaincodeID(chaincodeID);
    upgradeProposalRequest.setProposalWaitTime(proposalWaitTime);
    upgradeProposalRequest.setArgs(args);

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

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

    long currentStart = System.currentTimeMillis();
    Collection<ProposalResponse> upgradeProposalResponses = org.getChannel().get().sendUpgradeProposal(upgradeProposalRequest, org.getChannel().get().getPeers());
    log.info("chaincode instantiate transaction proposal time = " + (System.currentTimeMillis() - currentStart));
    return toOrdererResponse(upgradeProposalResponses, org);
}
 
Example #14
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 #15
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 #16
Source File: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 6 votes vote down vote up
private InstantiateProposalRequest getInstantiateProposalRequest(String chaincodeName, String chainCodeVersion,
        String chainCodePath, String chaincodeFunction, String[] chaincodeArgs, Endorsers endorsers) throws InvalidArgumentException {
    client.setUserContext(userOrg.getPeerAdmin());
    ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(chaincodeName).setVersion(chainCodeVersion)
            .setPath(chainCodePath).build();
    InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
    instantiateProposalRequest.setProposalWaitTime(conf.getProposalWaitTime());
    instantiateProposalRequest.setChaincodeID(chaincodeID);
    instantiateProposalRequest.setFcn(chaincodeFunction);
    instantiateProposalRequest.setArgs(chaincodeArgs);
    if(endorsers != null) {
        ChaincodeEndorsementPolicy policy = getChaincodeEndorsementPolicy(endorsers);
        instantiateProposalRequest.setChaincodeEndorsementPolicy(policy);
    }
    return instantiateProposalRequest;
}
 
Example #17
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 #18
Source File: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 6 votes vote down vote up
private UpgradeProposalRequest getUpgradeProposalRequest(String chaincodeName, String chainCodeVersion,
        String chainCodePath, String chaincodeFunction, String[] chaincodeArgs, Endorsers endorsers) throws InvalidArgumentException {
    client.setUserContext(userOrg.getPeerAdmin());
    ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(chaincodeName).setVersion(chainCodeVersion)
            .setPath(chainCodePath).build();
    UpgradeProposalRequest upgradeProposalRequest = client.newUpgradeProposalRequest();
    upgradeProposalRequest.setProposalWaitTime(conf.getProposalWaitTime());
    upgradeProposalRequest.setChaincodeID(chaincodeID);
    upgradeProposalRequest.setFcn(chaincodeFunction);
    upgradeProposalRequest.setArgs(chaincodeArgs);
    if(endorsers != null) {
        ChaincodeEndorsementPolicy policy = getChaincodeEndorsementPolicy(endorsers);
        upgradeProposalRequest.setChaincodeEndorsementPolicy(policy);
    }
    return upgradeProposalRequest;
}
 
Example #19
Source File: ChannelClient.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Query by chaincode.
 * 
 * @param chaincodeName
 * @param functionName
 * @param args
 * @return
 * @throws InvalidArgumentException
 * @throws ProposalException
 */
public Collection<ProposalResponse> queryByChainCode(String chaincodeName, String functionName, String[] args)
		throws InvalidArgumentException, ProposalException {
	Logger.getLogger(ChannelClient.class.getName()).log(Level.INFO,
			"Querying " + functionName + " on channel " + channel.getName());
	QueryByChaincodeRequest request = fabClient.getInstance().newQueryProposalRequest();
	ChaincodeID ccid = ChaincodeID.newBuilder().setName(chaincodeName).build();
	request.setChaincodeID(ccid);
	request.setFcn(functionName);
	if (args != null)
		request.setArgs(args);

	Collection<ProposalResponse> response = channel.queryByChaincode(request);

	return response;
}
 
Example #20
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 #21
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 #22
Source File: Fabric.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public ListPage<TbBlock> queryBlockList(BigInteger blockNumber, String blockHash, Integer pageIndex, Integer pageSize) throws BrokerException {

        try {
            return FabricSDKWrapper.queryBlockList(fabricConfig, channel, blockNumber, blockHash, pageIndex, pageSize);
        } catch (InvalidArgumentException | ProposalException | ExecutionException | InterruptedException | DecoderException | InvalidProtocolBufferException e) {
            log.error("query block list by transHash and blockNum error", e);
            throw new BrokerException(ErrorCode.FABRICSDK_GETBLOCKINFO_ERROR);
        }
    }
 
Example #23
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 #24
Source File: FabricManager.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
public void setUser(String leagueName, String orgName, String peerName, String username, String skPath, String certificatePath) throws InvalidArgumentException {
    if (StringUtils.equals(username, org.getUsername())) {
        return;
    }
    User user = org.getUser(username);
    if (null == user) {
        IntermediateUser intermediateUser = new IntermediateUser(leagueName, orgName, peerName, username, skPath, certificatePath);
        org.setUsername(username);
        org.addUser(leagueName, orgName, peerName, intermediateUser, org.getFabricStore());
    }
    org.getClient().setUserContext(org.getUser(username));
}
 
Example #25
Source File: Fabric.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public ListPage<TbNode> queryNodeList(Integer pageIndex, Integer pageSize) throws BrokerException {

        try {
            return FabricSDKWrapper.queryNodeList(fabricConfig, channel, pageIndex, pageSize);
        } catch (InvalidArgumentException | ProposalException e) {
            log.error("query node list by transHash and blockNum error", e);
            throw new BrokerException(ErrorCode.FABRICSDK_GETBLOCKINFO_ERROR);
        }
    }
 
Example #26
Source File: IntermediateChannel.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
/**
 * 在指定频道内根据区块高度查询区块
 *
 * @param blockNumber 区块高度
 */
JSONObject queryBlockByNumber(long blockNumber) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
    if (!channel.isInitialized()) {
        initChannel();
    }
    return execBlockInfo(channel.queryBlockByNumber(blockNumber));
}
 
Example #27
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 #28
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 #29
Source File: IntermediateChannel.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
/**
 * 在指定频道内根据hash查询区块
 *
 * @param blockHash hash
 */
JSONObject queryBlockByHash(byte[] blockHash) throws InvalidArgumentException, ProposalException, IOException, TransactionException {
    if (!channel.isInitialized()) {
        initChannel();
    }
    return execBlockInfo(channel.queryBlockByHash(blockHash));
}
 
Example #30
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
/**
 * 查询智能合约
 * 
 * @param fcn
 *            方法名
 * @param args
 *            参数数组
 * @return
 * @throws InvalidArgumentException
 * @throws ProposalException
 * @throws IOException 
 * @throws TransactionException 
 * @throws CryptoException 
 * @throws InvalidKeySpecException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 */
public Map<String, String> query(String fcn, String[] args) throws InvalidArgumentException, ProposalException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException {
	Map<String, String> resultMap = new HashMap<>();
	String payload = "";
	QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
	queryByChaincodeRequest.setArgs(args);
	queryByChaincodeRequest.setFcn(fcn);
	queryByChaincodeRequest.setChaincodeID(chaincodeID);

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

	Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers());
	for (ProposalResponse proposalResponse : queryProposals) {
		if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
			log.debug("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: "
					+ proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified());
			resultMap.put("code", "error");
			resultMap.put("data", "Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: "
					+ proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified());
		} else {
			payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
			log.debug("Query payload from peer: " + proposalResponse.getPeer().getName());
			log.debug("TransactionID: " + proposalResponse.getTransactionID());
			log.debug("" + payload);
			resultMap.put("code", "success");
			resultMap.put("data", payload);
			resultMap.put("txid", proposalResponse.getTransactionID());
		}
	}
	return resultMap;
}