Java Code Examples for org.hyperledger.fabric.sdk.HFClient#newChannel()

The following examples show how to use org.hyperledger.fabric.sdk.HFClient#newChannel() . 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: 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 2
Source File: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
public Channel reconstructChannel(List<Peer> peers, HFClient client) {
    checkConfig();
    try {
        org.apache.log4j.Level setTo = null;
        setTo = org.apache.log4j.Level.DEBUG;
        org.apache.log4j.Logger.getLogger("org.hyperledger.fabric").setLevel(setTo);

        Channel newChannel = null;

        client.setUserContext(user);
        newChannel = client.newChannel(channelName);
        for (String orderName : userOrg.getOrdererNames()) {
            newChannel.addOrderer(client.newOrderer(orderName, userOrg.getOrdererLocation(orderName),
                    conf.getOrdererProperties(orderName)));
        }
        
        for (Peer peer : peers) {
            logger.debug(peer.getName());

            newChannel.addPeer(peer);
            userOrg.addPeer(peer);
        }
        newChannel.initialize();
        return newChannel;

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

}
 
Example 3
Source File: FabricUtils.java    From fabric-java-block with GNU General Public License v3.0 5 votes vote down vote up
public static Channel initChannel(HFClient client, BlockChainOrgUserDTO userDTO, BlockChainOrgDTO currentOrgDTO,
                                  BlockChainChannelDTO channelDTO, BaasRouteDTO routeDTO, List<BlockChainOrdererDTO> ordererList) throws Exception {
    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

    // 实例化用户需要先在控制台-证书管理中申请客户端证书,申请的企业名称需要与当前登录账户实名认证的企业名称相同
    FabricUser user = new FabricUser(userDTO.getOrgUserName(), new FabricEnrollment(userDTO.getOrgUserKey(), userDTO.getOrgUserCert()),
            currentOrgDTO.getMspId());

    client.setUserContext(user);

    Channel chain = client.newChannel(channelDTO.getChannelKey());

    for(BlockChainOrdererDTO ordererDTO: ordererList) {
        chain.addOrderer(client.newOrderer(ordererDTO.getOrdererKey(), routeDTO.getEndPoint(),
                FabricConfig.getOrderProperties(routeDTO.getSecretId(),routeDTO.getSecretKey(),ordererDTO.getOrdererKey())));
    }

    for(BlockChainOrgNodeDTO nodeDTO : currentOrgDTO.getNodeList()){
        chain.addPeer(client.newPeer(nodeDTO.getNodeKey(), routeDTO.getEndPoint(), FabricConfig.getPeerProperties(routeDTO.getSecretId(),
                routeDTO.getSecretKey(),nodeDTO.getNodeKey())),
                createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER,
                        Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE)));
        //registerEventsForFilteredBlocks()
    }


    chain.initialize();

    return chain;
}
 
Example 4
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 5
Source File: UpdateChannelIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private Channel reconstructChannel(final boolean isSystemChannel, String name, HFClient client, SampleOrg sampleOrg) throws Exception {

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

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

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

        }

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

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

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

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

            newChannel.addPeer(peer, peerOptions);
        }

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

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

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

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

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

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

        newChannel.initialize();

        return newChannel;
    }