Java Code Examples for org.hyperledger.fabric.sdk.Channel#addOrderer()

The following examples show how to use org.hyperledger.fabric.sdk.Channel#addOrderer() . 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: QueryBlock.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
public Channel reconstructChannel()
{
    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 (String peerName : userOrg.getPeerNames()) {
            logger.debug(peerName);
            String peerLocation = userOrg.getPeerLocation(peerName);
            Peer peer = client.newPeer(peerName, peerLocation, conf.getPeerProperties(peerName));

            Set<String> channels = client.queryChannels(peer);
            if (!channels.contains(channelName)) {
                logger.info(String.format("Peer %s does not appear to belong to channel %s", peerName, channelName));
            }
            newChannel.addPeer(peer);
            userOrg.addPeer(peer);
        }

        for (String eventHubName : userOrg.getEventHubNames()) {
            EventHub eventHub = client.newEventHub(eventHubName, userOrg.getEventHubLocation(eventHubName),
                    conf.getEventHubProperties(eventHubName));
            newChannel.addEventHub(eventHub);
        }
        newChannel.initialize();
        return newChannel;

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

}
 
Example 6
Source File: CreateChannel.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	try {
		CryptoSuite.Factory.getCryptoSuite();
		Util.cleanUp();
		// Construct Channel
		UserContext org1Admin = new UserContext();
		File pkFolder1 = new File(Config.ORG1_USR_ADMIN_PK);
		File[] pkFiles1 = pkFolder1.listFiles();
		File certFolder1 = new File(Config.ORG1_USR_ADMIN_CERT);
		File[] certFiles1 = certFolder1.listFiles();
		Enrollment enrollOrg1Admin = Util.getEnrollment(Config.ORG1_USR_ADMIN_PK, pkFiles1[0].getName(),
				Config.ORG1_USR_ADMIN_CERT, certFiles1[0].getName());
		org1Admin.setEnrollment(enrollOrg1Admin);
		org1Admin.setMspId(Config.ORG1_MSP);
		org1Admin.setName(Config.ADMIN);

		UserContext org2Admin = new UserContext();
		File pkFolder2 = new File(Config.ORG2_USR_ADMIN_PK);
		File[] pkFiles2 = pkFolder2.listFiles();
		File certFolder2 = new File(Config.ORG2_USR_ADMIN_CERT);
		File[] certFiles2 = certFolder2.listFiles();
		Enrollment enrollOrg2Admin = Util.getEnrollment(Config.ORG2_USR_ADMIN_PK, pkFiles2[0].getName(),
				Config.ORG2_USR_ADMIN_CERT, certFiles2[0].getName());
		org2Admin.setEnrollment(enrollOrg2Admin);
		org2Admin.setMspId(Config.ORG2_MSP);
		org2Admin.setName(Config.ADMIN);

		FabricClient fabClient = new FabricClient(org1Admin);

		// Create a new channel
		Orderer orderer = fabClient.getInstance().newOrderer(Config.ORDERER_NAME, Config.ORDERER_URL);
		ChannelConfiguration channelConfiguration = new ChannelConfiguration(new File(Config.CHANNEL_CONFIG_PATH));

		byte[] channelConfigurationSignatures = fabClient.getInstance()
				.getChannelConfigurationSignature(channelConfiguration, org1Admin);

		Channel mychannel = fabClient.getInstance().newChannel(Config.CHANNEL_NAME, orderer, channelConfiguration,
				channelConfigurationSignatures);

		Peer peer0_org1 = fabClient.getInstance().newPeer(Config.ORG1_PEER_0, Config.ORG1_PEER_0_URL);
		Peer peer1_org1 = fabClient.getInstance().newPeer(Config.ORG1_PEER_1, Config.ORG1_PEER_1_URL);
		Peer peer0_org2 = fabClient.getInstance().newPeer(Config.ORG2_PEER_0, Config.ORG2_PEER_0_URL);
		Peer peer1_org2 = fabClient.getInstance().newPeer(Config.ORG2_PEER_1, Config.ORG2_PEER_1_URL);

		mychannel.joinPeer(peer0_org1);
		mychannel.joinPeer(peer1_org1);
		
		mychannel.addOrderer(orderer);

		mychannel.initialize();
		
		fabClient.getInstance().setUserContext(org2Admin);
		mychannel = fabClient.getInstance().getChannel("mychannel");
		mychannel.joinPeer(peer0_org2);
		mychannel.joinPeer(peer1_org2);
		
		Logger.getLogger(CreateChannel.class.getName()).log(Level.INFO, "Channel created "+mychannel.getName());
           Collection peers = mychannel.getPeers();
           Iterator peerIter = peers.iterator();
           while (peerIter.hasNext())
           {
           	  Peer pr = (Peer) peerIter.next();
           	  Logger.getLogger(CreateChannel.class.getName()).log(Level.INFO,pr.getName()+ " at " + pr.getUrl());
           }
           
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 7
Source File: InvokeChaincode.java    From blockchain-application-using-fabric-java-sdk with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {
	try {
           Util.cleanUp();
		String caUrl = Config.CA_ORG1_URL;
		CAClient caClient = new CAClient(caUrl, null);
		// Enroll Admin to Org1MSP
		UserContext adminUserContext = new UserContext();
		adminUserContext.setName(Config.ADMIN);
		adminUserContext.setAffiliation(Config.ORG1);
		adminUserContext.setMspId(Config.ORG1_MSP);
		caClient.setAdminUserContext(adminUserContext);
		adminUserContext = caClient.enrollAdminUser(Config.ADMIN, Config.ADMIN_PASSWORD);
		
		FabricClient fabClient = new FabricClient(adminUserContext);
		
		ChannelClient channelClient = fabClient.createChannelClient(Config.CHANNEL_NAME);
		Channel channel = channelClient.getChannel();
		Peer peer = fabClient.getInstance().newPeer(Config.ORG1_PEER_0, Config.ORG1_PEER_0_URL);
		EventHub eventHub = fabClient.getInstance().newEventHub("eventhub01", "grpc://localhost:7053");
		Orderer orderer = fabClient.getInstance().newOrderer(Config.ORDERER_NAME, Config.ORDERER_URL);
		channel.addPeer(peer);
		channel.addEventHub(eventHub);
		channel.addOrderer(orderer);
		channel.initialize();

		TransactionProposalRequest request = fabClient.getInstance().newTransactionProposalRequest();
		ChaincodeID ccid = ChaincodeID.newBuilder().setName(Config.CHAINCODE_1_NAME).build();
		request.setChaincodeID(ccid);
		request.setFcn("createCar");
		String[] arguments = { "CAR1", "Chevy", "Volt", "Red", "Nick" };
		request.setArgs(arguments);
		request.setProposalWaitTime(1000);

		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));
		tm2.put(EXPECTED_EVENT_NAME, EXPECTED_EVENT_DATA); 
		request.setTransientMap(tm2);
		Collection<ProposalResponse> responses = channelClient.sendTransactionProposal(request);
		for (ProposalResponse res: responses) {
			Status status = res.getStatus();
			Logger.getLogger(InvokeChaincode.class.getName()).log(Level.INFO,"Invoked createCar on "+Config.CHAINCODE_1_NAME + ". Status - " + status);
		}
								
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 8
Source File: ChaincodeServiceImpl.java    From balance-transfer-java with Apache License 2.0 4 votes vote down vote up
/**
 * Reconstruct the channel returns channel that has been reconstructed
 */
public Channel reconstructChannel()  {

	checkConfig();
	try
	{
		Org sampleOrg = Conf.getSampleOrg("peerOrg1");

		client.setUserContext(sampleOrg.getPeerAdmin());
		Channel newChannel = client.newChannel(channelName);

		for (String orderName : sampleOrg.getOrdererNames()) {

			newChannel.addOrderer(client.newOrderer(orderName, sampleOrg.getOrdererLocation(orderName),
					Conf.getOrdererProperties(orderName)));
		}

		for (String peerName : sampleOrg.getPeerNames()) {
			logger.debug(peerName);
			String peerLocation = sampleOrg.getPeerLocation(peerName);
			Peer peer = client.newPeer(peerName, peerLocation, Conf.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(channelName)) {
				logger.info("Peer %s does not appear to belong to channel %s", peerName, channelName);
			}

			newChannel.addPeer(peer);
			sampleOrg.addPeer(peer);
		}

		for (String eventHubName : sampleOrg.getEventHubNames()) {
			EventHub eventHub = client.newEventHub(eventHubName, sampleOrg.getEventHubLocation(eventHubName),
					Conf.getEventHubProperties(eventHubName));
			newChannel.addEventHub(eventHub);
		}

		newChannel.initialize();

		return newChannel;
	}
	catch (Exception e)
	{
		logger.error("ChaincodeServiceImpl | reconstructChannel ");
		return null;
	}
}
 
Example 9
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;
    }