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

The following examples show how to use org.hyperledger.fabric.sdk.exception.TransactionException. 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: IntermediateChaincodeID.java    From fabric-net-server with Apache License 2.0 6 votes vote down vote up
/**
 * 安装智能合约
 *
 * @param org 中继组织对象
 */
JSONObject install(IntermediateOrg org) throws ProposalException, InvalidArgumentException, TransactionException {
    /// Send transaction proposal to all peers
    InstallProposalRequest installProposalRequest = org.getClient().newInstallProposalRequest();
    installProposalRequest.setChaincodeName(chaincodeName);
    installProposalRequest.setChaincodeVersion(chaincodeVersion);
    installProposalRequest.setChaincodeSourceLocation(new File(chaincodeSource));
    installProposalRequest.setChaincodePath(chaincodePath);
    installProposalRequest.setChaincodeLanguage(TransactionRequest.Type.GO_LANG);
    installProposalRequest.setProposalWaitTime(proposalWaitTime);

    long currentStart = System.currentTimeMillis();
    Collection<ProposalResponse> installProposalResponses = org.getClient().sendInstallProposal(installProposalRequest, org.getChannel().get().getPeers());
    log.info("chaincode install transaction proposal time = " + (System.currentTimeMillis() - currentStart));
    return toPeerResponse(installProposalResponses, false);
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: Orderer.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Send transaction to Order
 *
 * @param transaction transaction to be sent
 */

Ab.BroadcastResponse sendTransaction(Common.Envelope transaction) throws Exception {
    if (shutdown) {
        throw new TransactionException(format("Orderer %s was shutdown.", name));
    }

    logger.debug(format("Orderer.sendTransaction %s", toString()));

    OrdererClient localOrdererClient = getOrdererClient();

    try {
        return localOrdererClient.sendTransaction(transaction);
    } catch (Throwable t) {
        removeOrdererClient(true);
        throw t;

    }

}
 
Example #8
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 #9
Source File: PeerEventServiceClient.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void peerVent(TransactionContext transactionContext) throws TransactionException {
    logger.trace(toString() + "peerVent  transaction: " + transactionContext);
    if (shutdown) { // check aagin
        logger.debug("peerVent not starting, shutting down.");
        return;
    }

    final Envelope envelope;
    try {
        Ab.SeekPosition.Builder start = Ab.SeekPosition.newBuilder();
        if (null != peerOptions.getNewest()) {
            start.setNewest(Ab.SeekNewest.getDefaultInstance());
        } else if (peerOptions.getStartEvents() != null) {
            start.setSpecified(Ab.SeekSpecified.newBuilder().setNumber(peerOptions.getStartEvents()));
        } else {
            start.setNewest(Ab.SeekNewest.getDefaultInstance());
        }

        envelope = ProtoUtils.createSeekInfoEnvelope(transactionContext,
                start.build(),
                Ab.SeekPosition.newBuilder()
                        .setSpecified(Ab.SeekSpecified.newBuilder().setNumber(peerOptions.getStopEvents()).build())
                        .build(),
                SeekInfo.SeekBehavior.BLOCK_UNTIL_READY,

                clientTLSCertificateDigest);
        connectEnvelope(envelope);
    } catch (Exception e) {
        throw new TransactionException(toString() + " error message: " + e.getMessage(), e);
    }
}
 
Example #10
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 #11
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 #12
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 #13
Source File: IntermediateChannel.java    From fabric-net-server with Apache License 2.0 5 votes vote down vote up
/** 获取Fabric Channel */
Channel get() throws InvalidArgumentException, TransactionException {
    if (!channel.isInitialized()) {
        initChannel();
    }
    return channel;
}
 
Example #14
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;
}
 
Example #15
Source File: Peer.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
void initiateEventing(TransactionContext transactionContext, PeerOptions peersOptions) throws TransactionException {
    this.transactionContext = transactionContext.retryTransactionSameContext();

    if (peerEventingClient == null && !shutdown) {
        peerEventingClient = new PeerEventServiceClient(this, Endpoint.createEndpoint(url, properties), properties, peersOptions);
        peerEventingClient.connect(transactionContext);
    }
}
 
Example #16
Source File: ChannelTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClient() {
    try {
        hfclient = TestHFClient.newInstance();

        shutdownChannel = new Channel("shutdown", hfclient);
        shutdownChannel.addOrderer(hfclient.newOrderer("shutdow_orderer", "grpc://localhost:99"));

        setField(shutdownChannel, "shutdown", true);

        throwOrderer = new Orderer("foo", "grpc://localhost:8", null) {
            @Override
            Ab.BroadcastResponse sendTransaction(Common.Envelope transaction) throws Exception {
                throw new Exception(BAD_STUFF);
            }

            @Override
            Ab.DeliverResponse[] sendDeliver(Common.Envelope transaction) throws TransactionException {
                throw new TransactionException(BAD_STUFF);
            }
        };

        throwChannel = new Channel("throw", hfclient);
        throwChannel.addOrderer(throwOrderer);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Unexpected Exception " + e.getMessage());
    }
}
 
Example #17
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Channel initializeChannel(HFClient client, String channelName, FabricConfig fabricConfig) throws InvalidArgumentException, TransactionException {
    Orderer orderer1 = getOrderer(client, fabricConfig);

    Peer peer0 = getPeer(client, fabricConfig);

    Channel channel = client.newChannel(channelName);
    channel.addOrderer(orderer1);
    channel.addPeer(peer0);
    channel.initialize();
    return channel;
}
 
Example #18
Source File: Fabric.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
public ChaincodeManager getChaincodeManager()
		throws CryptoException, InvalidArgumentException, NoSuchAlgorithmException, NoSuchProviderException,
		InvalidKeySpecException, TransactionException, IOException {
	return new ChaincodeManager(!username.equals("") ? username : "Admin", getFabricConfig());
}
 
Example #19
Source File: PeerEventServiceClient.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
void connect(TransactionContext transactionContext) throws TransactionException {
    if (shutdown) {
        return;
    }
    peerVent(transactionContext);
}
 
Example #20
Source File: Orderer.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
DeliverResponse[] sendDeliver(Common.Envelope transaction) throws TransactionException {

        if (shutdown) {
            throw new TransactionException(format("Orderer %s was shutdown.", name));
        }

        OrdererClient localOrdererClient = getOrdererClient();

        logger.debug(format("%s Orderer.sendDeliver", toString()));

        try {

            return localOrdererClient.sendDeliver(transaction);
        } catch (Throwable t) {
            logger.error(format("%s removing %s due to %s", this.toString(), localOrdererClient, t.getMessage()));
            removeOrdererClient(true);
            throw t;

        }

    }
 
Example #21
Source File: IntermediateChaincodeID.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
/**
     * 获取实例化合约、升级合约以及invoke合约的返回结果集合
     *
     * @param proposalResponses 请求返回集合
     * @param org               中继组织对象
     */
    private JSONObject toOrdererResponse(Collection<ProposalResponse> proposalResponses, IntermediateOrg org) throws InvalidArgumentException, UnsupportedEncodingException, TransactionException {
        JSONObject jsonObject = new JSONObject();
        ProposalResponse first = null;
        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();
        for (ProposalResponse response : proposalResponses) {
            if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                successful.add(response);
            } else {
                failed.add(response);
            }
        }

        Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(proposalResponses);
        if (proposalConsistencySets.size() != 1) {
            log.error("Expected only one set of consistent proposal responses but got " + proposalConsistencySets.size());
        }
        if (failed.size() > 0) {
            for (ProposalResponse fail : failed) {
                log.error("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + fail.getMessage() + ", on peer" + fail.getPeer());
            }
            first = failed.iterator().next();
            log.error("Not enough endorsers for inspect:" + failed.size() + " endorser error: " + first.getMessage() + ". Was verified: "
                    + first.isVerified());
        }
        if (successful.size() > 0) {
            log.info("Successfully received transaction proposal responses.");
            ProposalResponse resp = proposalResponses.iterator().next();
            log.debug("TransactionID: " + resp.getTransactionID());
            byte[] x = resp.getChaincodeActionResponsePayload();
            String resultAsString = null;
            if (x != null) {
                resultAsString = new String(x, "UTF-8");
            }
            log.info("resultAsString = " + resultAsString);
            // org.getChannel().get().sendTransaction(successful).get(transactionWaitTime, TimeUnit.SECONDS);
            org.getChannel().get().sendTransaction(successful);
            jsonObject = parseResult(resultAsString);
            jsonObject.put("code", BlockListener.SUCCESS);
            jsonObject.put("txid", resp.getTransactionID());
            return jsonObject;
        } else {
            jsonObject.put("code", BlockListener.ERROR);
            jsonObject.put("error", null != first ? first.getMessage() : "error unknown");
            return jsonObject;
        }
//        channel.sendTransaction(successful).thenApply(transactionEvent -> {
//            if (transactionEvent.isValid()) {
//                log.info("Successfully send transaction proposal to orderer. Transaction ID: " + transactionEvent.getTransactionID());
//            } else {
//                log.info("Failed to send transaction proposal to orderer");
//            }
//            // chain.shutdown(true);
//            return transactionEvent.getTransactionID();
//        }).get(chaincode.getInvokeWatiTime(), TimeUnit.SECONDS);
    }
 
Example #22
Source File: Peer.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
void reconnectPeerEventServiceClient(final PeerEventServiceClient failedPeerEventServiceClient,
                                     final Throwable throwable) {
    if (shutdown) {
        logger.debug(toString() + "not reconnecting PeerEventServiceClient shutdown ");
        return;

    }
    PeerEventingServiceDisconnected ldisconnectedHandler = disconnectedHandler;
    if (null == ldisconnectedHandler) {

        return; // just wont reconnect.

    }
    TransactionContext ltransactionContext = transactionContext;
    if (ltransactionContext == null) {

        logger.warn(toString() + " not reconnecting PeerEventServiceClient no transaction available ");
        return;
    }

    final TransactionContext fltransactionContext = ltransactionContext.retryTransactionSameContext();

    final ExecutorService executorService = getExecutorService();
    final PeerOptions peerOptions = null != failedPeerEventServiceClient.getPeerOptions() ? failedPeerEventServiceClient.getPeerOptions() :
            PeerOptions.createPeerOptions();
    if (!shutdown && executorService != null && !executorService.isShutdown() && !executorService.isTerminated()) {

        executorService.execute(() -> ldisconnectedHandler.disconnected(new PeerEventingServiceDisconnectEvent() {
            @Override
            public BlockEvent getLatestBLockReceived() {
                return lastBlockEvent;
            }

            @Override
            public long getLastConnectTime() {
                return lastConnectTime;
            }

            @Override
            public long getReconnectCount() {
                return reconnectCount.longValue();
            }

            @Override
            public Throwable getExceptionThrown() {
                return throwable;
            }

            @Override
            public void reconnect(Long startBLockNumber) throws TransactionException {
                logger.trace(format("%s reconnecting. Starting block number: %s", Peer.this.toString(), startBLockNumber == null ? "newest" : startBLockNumber));
                reconnectCount.getAndIncrement();

                if (startBLockNumber == null) {
                    peerOptions.startEventsNewest();
                } else {
                    peerOptions.startEvents(startBLockNumber);
                }

                if (!shutdown) {
                    PeerEventServiceClient lpeerEventingClient = new PeerEventServiceClient(Peer.this,
                            Endpoint.createEndpoint(url, properties), properties, peerOptions);
                    lpeerEventingClient.connect(fltransactionContext);
                    peerEventingClient = lpeerEventingClient;
                }
            }
        }));
    }
}
 
Example #23
Source File: FabricManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
/** 查询当前频道的链信息,包括链长度、当前最新区块hash以及当前最新区块的上一区块hash */
public JSONObject queryBlockChainInfo() throws ProposalException, InvalidArgumentException, TransactionException {
    return org.getChannel().queryBlockChainInfo();
}
 
Example #24
Source File: FabricManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
/** 安装智能合约 */
public JSONObject install() throws ProposalException, InvalidArgumentException, TransactionException {
    return org.getChainCode().install(org);
}
 
Example #25
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
/**
	 * 执行智能合约
	 * 
	 * @param fcn
	 *            方法名
	 * @param args
	 *            参数数组
	 * @return
	 * @throws InvalidArgumentException
	 * @throws ProposalException
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws TimeoutException
	 * @throws IOException 
	 * @throws TransactionException 
	 * @throws CryptoException 
	 * @throws InvalidKeySpecException 
	 * @throws NoSuchProviderException 
	 * @throws NoSuchAlgorithmException 
	 */
	public Map<String, String> invoke(String fcn, String[] args)
			throws InvalidArgumentException, ProposalException, InterruptedException, ExecutionException, TimeoutException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException {
		Map<String, String> resultMap = new HashMap<>();

		Collection<ProposalResponse> successful = new LinkedList<>();
		Collection<ProposalResponse> failed = new LinkedList<>();

		/// Send transaction proposal to all peers
		TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
		transactionProposalRequest.setChaincodeID(chaincodeID);
		transactionProposalRequest.setFcn(fcn);
		transactionProposalRequest.setArgs(args);

		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> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());
		for (ProposalResponse response : transactionPropResp) {
			if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
				successful.add(response);
			} else {
				failed.add(response);
			}
		}
		log.info("channel send transaction proposal time = " + ( System.currentTimeMillis() - currentStart));

		Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(transactionPropResp);
		if (proposalConsistencySets.size() != 1) {
			log.error("Expected only one set of consistent proposal responses but got " + proposalConsistencySets.size());
		}

		if (failed.size() > 0) {
			ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
			log.error("Not enough endorsers for inspect:" + failed.size() + " endorser error: " + firstTransactionProposalResponse.getMessage() + ". Was verified: "
					+ firstTransactionProposalResponse.isVerified());
			resultMap.put("code", "error");
			resultMap.put("data", firstTransactionProposalResponse.getMessage());
			return resultMap;
		} else {
			log.info("Successfully received transaction proposal responses.");
			ProposalResponse resp = transactionPropResp.iterator().next();
			log.debug("TransactionID: " + resp.getTransactionID());
			byte[] x = resp.getChaincodeActionResponsePayload();
			String resultAsString = null;
			if (x != null) {
				resultAsString = new String(x, "UTF-8");
			}
			log.info("resultAsString = " + resultAsString);
			channel.sendTransaction(successful);
			resultMap.put("code", "success");
			resultMap.put("data", resultAsString);
			resultMap.put("txid", resp.getTransactionID());
			return resultMap;
		}

//		channel.sendTransaction(successful).thenApply(transactionEvent -> {
//			if (transactionEvent.isValid()) {
//				log.info("Successfully send transaction proposal to orderer. Transaction ID: " + transactionEvent.getTransactionID());
//			} else {
//				log.info("Failed to send transaction proposal to orderer");
//			}
//			// chain.shutdown(true);
//			return transactionEvent.getTransactionID();
//		}).get(chaincode.getInvokeWatiTime(), TimeUnit.SECONDS);
	}
 
Example #26
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
private Channel getChannel(FabricOrg fabricOrg, HFClient client)
		throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, CryptoException, InvalidArgumentException, TransactionException {
	Channel channel = client.newChannel(chaincode.getChannelName());
	log.debug("Get Chain " + chaincode.getChannelName());

	channel.setTransactionWaitTime(chaincode.getTransactionWaitTime());
	channel.setDeployWaitTime(chaincode.getDeployWaitTime());

	for (int i = 0; i < peers.get().size(); i++) {
		File peerCert = Paths.get(config.getCryptoConfigPath(), "/peerOrganizations", peers.getOrgDomainName(), "peers", peers.get().get(i).getPeerName(), "tls/server.crt")
				.toFile();
		if (!peerCert.exists()) {
			throw new RuntimeException(
					String.format("Missing cert file for: %s. Could not find at location: %s", peers.get().get(i).getPeerName(), peerCert.getAbsolutePath()));
		}
		Properties peerProperties = new Properties();
		peerProperties.setProperty("pemFile", peerCert.getAbsolutePath());
		// ret.setProperty("trustServerCertificate", "true"); //testing
		// environment only NOT FOR PRODUCTION!
		peerProperties.setProperty("hostnameOverride", peers.getOrgDomainName());
		peerProperties.setProperty("sslProvider", "openSSL");
		peerProperties.setProperty("negotiationType", "TLS");
		// 在grpc的NettyChannelBuilder上设置特定选项
		peerProperties.put("grpc.ManagedChannelBuilderOption.maxInboundMessageSize", 9000000);
		channel.addPeer(client.newPeer(peers.get().get(i).getPeerName(), fabricOrg.getPeerLocation(peers.get().get(i).getPeerName()), peerProperties));
		if (peers.get().get(i).isAddEventHub()) {
			channel.addEventHub(
					client.newEventHub(peers.get().get(i).getPeerEventHubName(), fabricOrg.getEventHubLocation(peers.get().get(i).getPeerEventHubName()), peerProperties));
		}
	}

	for (int i = 0; i < orderers.get().size(); i++) {
		File ordererCert = Paths.get(config.getCryptoConfigPath(), "/ordererOrganizations", orderers.getOrdererDomainName(), "orderers", orderers.get().get(i).getOrdererName(),
				"tls/server.crt").toFile();
		if (!ordererCert.exists()) {
			throw new RuntimeException(
					String.format("Missing cert file for: %s. Could not find at location: %s", orderers.get().get(i).getOrdererName(), ordererCert.getAbsolutePath()));
		}
		Properties ordererProperties = new Properties();
		ordererProperties.setProperty("pemFile", ordererCert.getAbsolutePath());
		ordererProperties.setProperty("hostnameOverride", orderers.getOrdererDomainName());
		ordererProperties.setProperty("sslProvider", "openSSL");
		ordererProperties.setProperty("negotiationType", "TLS");
		ordererProperties.put("grpc.ManagedChannelBuilderOption.maxInboundMessageSize", 9000000);
		ordererProperties.setProperty("ordererWaitTimeMilliSecs", "300000");
		channel.addOrderer(
				client.newOrderer(orderers.get().get(i).getOrdererName(), fabricOrg.getOrdererLocation(orderers.get().get(i).getOrdererName()), ordererProperties));
	}

	log.debug("channel.isInitialized() = " + channel.isInitialized());
	if (!channel.isInitialized()) {
		channel.initialize();
	}
	if (config.isRegisterEvent()) {
		log.debug("========================Event事件监听注册========================");
		channel.registerBlockListener(new BlockListener() {

			@Override
			public void received(BlockEvent event) {
				// TODO
				log.debug("========================Event事件监听开始========================");
				try {
					log.debug("event.getChannelId() = " + event.getChannelId());
					log.debug("event.getEvent().getChaincodeEvent().getPayload().toStringUtf8() = " + event.getEvent().getChaincodeEvent().getPayload().toStringUtf8());
					log.debug("event.getBlock().getData().getDataList().size() = " + event.getBlock().getData().getDataList().size());
					ByteString byteString = event.getBlock().getData().getData(0);
					String result = byteString.toStringUtf8();
					log.debug("byteString.toStringUtf8() = " + result);

					String r1[] = result.split("END CERTIFICATE");
					String rr = r1[2];
					log.debug("rr = " + rr);
				} catch (InvalidProtocolBufferException e) {
					// TODO
					e.printStackTrace();
				}
				log.debug("========================Event事件监听结束========================");
			}
		});
	}
	return channel;
}
 
Example #27
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
private Channel getChannel()
		throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException, CryptoException, InvalidArgumentException, TransactionException {
	client.setUserContext(fabricOrg.getPeerAdmin());
	return getChannel(fabricOrg, client);
}
 
Example #28
Source File: FabricManager.java    From fabric-net-server with Apache License 2.0 2 votes vote down vote up
/**
 * 在指定频道内根据区块高度查询区块
 *
 * @param blockNumber 区块高度
 */
public JSONObject queryBlockByNumber(long blockNumber) throws ProposalException, IOException, InvalidArgumentException, TransactionException {
    return org.getChannel().queryBlockByNumber(blockNumber);
}
 
Example #29
Source File: FabricManager.java    From fabric-net-server with Apache License 2.0 2 votes vote down vote up
/**
 * 在指定频道内根据hash查询区块
 *
 * @param blockHash hash
 */
public JSONObject queryBlockByHash(byte[] blockHash) throws ProposalException, IOException, InvalidArgumentException, TransactionException {
    return org.getChannel().queryBlockByHash(blockHash);
}
 
Example #30
Source File: FabricManager.java    From fabric-net-server with Apache License 2.0 2 votes vote down vote up
/**
 * 在指定频道内根据transactionID查询区块
 *
 * @param txID transactionID
 */
public JSONObject queryBlockByTransactionID(String txID) throws ProposalException, IOException, InvalidArgumentException, TransactionException {
    return org.getChannel().queryBlockByTransactionID(txID);
}