Пример #1
0
        public void TestSetDuplicateChannnel()
        {
            Channel channel = hfclient.NewChannel(DEFAULT_CHANNEL_NAME);

            orderer.Channel = channel;
            Channel channel2 = hfclient.NewChannel("channel2");

            orderer.Channel = channel2;
            orderer.Channel = channel2;
        }
Пример #2
0
 public void TestNewChannel()
 {
     try
     {
         Channel testChannel = hfclient.NewChannel(CHANNEL_NAME);
         Assert.IsTrue(testChannel != null && CHANNEL_NAME.Equals(testChannel.Name, StringComparison.InvariantCultureIgnoreCase));
     }
     catch (System.Exception e)
     {
         Assert.Fail($"Unexpected Exception {e.Message}");
     }
 }
Пример #3
0
        public UserManager()
        {
            keyStorePath  = @"D:\Projetos\Hyperledger\fabcar\hfc-key-store\";
            admin         = SampleUser.Load("admin", keyStorePath);
            fabric_client = HFClient.Create();
            var crypto = new Hyperledger.Fabric.SDK.Security.CryptoPrimitives();

            crypto.Init();
            crypto.Store.AddCertificate(admin.Enrollment.Cert);

            fabric_client.CryptoSuite = crypto;

            fabric_client.UserContext = admin;

            channel = fabric_client.NewChannel("mychannel");
            var peer = fabric_client.NewPeer("p1", $"grpc://{Startup.HyperleaderServer}:7051");

            channel.AddPeer(peer);

            var ordered = fabric_client.NewOrderer("o1", $"grpc://{Startup.HyperleaderServer}:7050");

            channel.AddOrderer(ordered);

            channel.Initialize();

            fabric_ca_client             = new Hyperledger.Fabric_CA.SDK.HFCAClient("", $"http://{Startup.HyperleaderServer}:7054", new Hyperledger.Fabric.SDK.Helper.Properties());
            fabric_ca_client.CryptoSuite = crypto;
        }
Пример #4
0
        public void TestDuplicateChannel()
        {
            Channel duplicate = hfclient.NewChannel("duplicate");

            peer.Channel = duplicate;
            peer.Channel = duplicate;
        }
Пример #5
0
        public FabCar(string username)
        {
            var user = SampleUser.Load(username, @"D:\Projetos\Hyperledger\fabcar\hfc-key-store\");

            client = Hyperledger.Fabric.SDK.HFClient.Create();
            var crypto = new Hyperledger.Fabric.SDK.Security.CryptoPrimitives();

            crypto.Store.AddCertificate(user.Enrollment.Cert);
            crypto.Init();
            client.CryptoSuite = crypto;

            client.UserContext = user;

            channel = client.NewChannel("mychannel");
            var peer = client.NewPeer("p1", $"grpc://{Program.ServerIP}:7051");

            channel.AddPeer(peer);

            var ordered = client.NewOrderer("o1", $"grpc://{Program.ServerIP}:7050");

            channel.AddOrderer(ordered);

            channel.Initialize();
        }
Пример #6
0
        [Ignore] //Hostnames reported by service discovery won't work unless you edit hostfile
        public void Setup()
        {
            //Persistence is not part of SDK. Sample file store is for demonstration purposes only!
            //   MUST be replaced with more robust application implementation  (Database, LDAP)
            Util.COut("\n\n\nRUNNING: %s.\n", "ServiceDiscoveryIT");

            SampleStore sampleStore = new SampleStore(sampleStoreFile);

            //  SampleUser peerAdmin = sampleStore.getMember("admin", "peerOrg1");
            SampleUser user1  = sampleStore.GetMember("user1", "peerOrg1");
            HFClient   client = HFClient.Create();

            testConfig.GetIntegrationTestsSampleOrg("peerOrg1");
            client.CryptoSuite = Factory.GetCryptoSuite();
            client.UserContext = user1;
            Properties properties = testConfig.GetPeerProperties("peer0.org1.example.com");

            string protocol = testConfig.IsRunningFabricTLS() ? "grpcs:" : "grpc:";

            Properties sdprops = new Properties();

            //Create initial discovery peer.

            Peer    discoveryPeer = client.NewPeer("peer0.org1.example.com", protocol + "//localhost:7051", properties);
            Channel foo           = client.NewChannel("foo"); //create channel that will be discovered.

            foo.AddPeer(discoveryPeer, PeerOptions.CreatePeerOptions().SetPeerRoles(PeerRole.SERVICE_DISCOVERY, PeerRole.LEDGER_QUERY, PeerRole.EVENT_SOURCE, PeerRole.CHAINCODE_QUERY));

            // Need to provide client TLS certificate and key files when running mutual tls.
            if (testConfig.IsRunningFabricTLS())
            {
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.default.clientCertFile", "fixture/sdkintegration/e2e-2Orgs/v1.2/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/tls/client.crt".Locate());
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.default.clientKeyFile", "fixture/sdkintegration/e2e-2Orgs/v1.2/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/tls/client.key".Locate());

                // Need to do host name override for true tls in testing environment
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.endpoint.hostnameOverride.localhost:7050", "orderer.example.com");
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.endpoint.hostnameOverride.localhost:7051", "peer0.org1.example.com");
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.endpoint.hostnameOverride.localhost:7056", "peer1.org1.example.com");
            }
            else
            {
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.default.protocol", "grpc:");
            }

            foo.ServiceDiscoveryProperties = sdprops;

            string channel = foo.Serialize();

            // Next 3 lines are for testing purposes only!
            foo.Shutdown(false);
            foo = client.DeSerializeChannel(channel);
            foo.Initialize(); // initialize the channel.
            List <string> expect = new List <string>()
            {
                protocol + "//orderer.example.com:7050"
            };                                                                                  //discovered orderer

            foreach (Orderer orderer in foo.Orderers)
            {
                expect.Remove(orderer.Url);
            }

            Assert.IsTrue(expect.Count == 0);

            List <string> discoveredChaincodeNames = foo.GetDiscoveredChaincodeNames();

            Assert.IsTrue(discoveredChaincodeNames.Contains(CHAIN_CODE_NAME));

            ChaincodeID chaincodeID = new ChaincodeID();

            chaincodeID.Name = CHAIN_CODE_NAME;


            ///////////////
            // Send transaction proposal to all peers
            TransactionProposalRequest transactionProposalRequest = client.NewTransactionProposalRequest();

            transactionProposalRequest.SetChaincodeID(chaincodeID);
            transactionProposalRequest.SetChaincodeLanguage(CHAIN_CODE_LANG);
            transactionProposalRequest.SetFcn("move");
            transactionProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
            transactionProposalRequest.SetArgs("a", "b", "1");

            //Send proposal request discovering the what endorsers (peers) are needed.

            List <ProposalResponse> transactionPropResp = foo.SendTransactionProposalToEndorsers(transactionProposalRequest, DiscoveryOptions.CreateDiscoveryOptions().SetEndorsementSelector(ServiceDiscovery.ENDORSEMENT_SELECTION_RANDOM).SetForceDiscovery(true));

            Assert.IsFalse(transactionPropResp.Count == 0);

            transactionProposalRequest = client.NewTransactionProposalRequest();
            transactionProposalRequest.SetChaincodeID(chaincodeID);
            transactionProposalRequest.SetChaincodeLanguage(CHAIN_CODE_LANG);
            transactionProposalRequest.SetFcn("move");
            transactionProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
            transactionProposalRequest.SetArgs("a", "b", "1");

            //Send proposal request discovering the what endorsers (peers) are needed.
            transactionPropResp = foo.SendTransactionProposalToEndorsers(transactionProposalRequest, DiscoveryOptions.CreateDiscoveryOptions().IgnoreEndpoints("blah.blah.blah.com:90", "blah.com:80",
                                                                         // aka peer0.org1.example.com our discovery peer. Lets ignore it in endorsers selection and see if other discovered peer endorses.
                                                                                                                                                               "peer0.org1.example.com:7051")
                                                                         // if chaincode makes additional chaincode calls or uses collections you should add them with setServiceDiscoveryChaincodeInterests
                                                                         //         .setServiceDiscoveryChaincodeInterests(Channel.ServiceDiscoveryChaincodeCalls.createServiceDiscoveryChaincodeCalls("someOtherChaincodeName").addCollections("collection1", "collection2"))
                                                                         );
            Assert.AreEqual(transactionPropResp.Count, 1);
            ProposalResponse proposalResponse = transactionPropResp.First();
            Peer             peer             = proposalResponse.Peer;

            Assert.AreEqual(protocol + "//peer1.org1.example.com:7056", peer.Url); // not our discovery peer but the discovered one.

            string expectedTransactionId = null;

            StringBuilder evenTransactionId = new StringBuilder();

            foreach (ProposalResponse response in transactionPropResp)
            {
                expectedTransactionId = response.TransactionID;
                if (response.Status != ChaincodeResponse.ChaincodeResponseStatus.SUCCESS || !response.IsVerified)
                {
                    Assert.Fail("Failed status bad endorsement");
                }
            }

            //Send it to the orderer that was discovered.
            try
            {
                TransactionEvent transactionEvent = foo.SendTransaction(transactionPropResp);

                evenTransactionId.Length = 0;

                evenTransactionId.Append(transactionEvent.TransactionID);
            }
            catch (TransactionEventException e)
            {
                TransactionEvent te = e.TransactionEvent;
                if (te != null)
                {
                    throw new System.Exception($"Transaction with txid {te.TransactionID} failed. {e.Message}");
                }
            }
            catch (System.Exception e)
            {
                throw new System.Exception($"Test failed with {e.Message} exception {e}");
            }


            Assert.AreEqual(expectedTransactionId, evenTransactionId.ToString());
            Util.COut("That's all folks!");
        }
        private Channel ReconstructChannel(string name, HFClient client, SampleOrg sampleOrg)
        {
            Util.COut("Reconstructing {0} channel", name);

            client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

            Channel newChannel;

            if (BAR_CHANNEL_NAME.Equals(name))
            {
                // bar channel was stored in samplestore in End2endIT testcase.

                /**
                 *  sampleStore.getChannel uses {@link HFClient#deSerializeChannel(byte[])}
                 */
                newChannel = sampleStore.GetChannel(client, name);

                if (!IS_FABRIC_V10)
                {
                    // Make sure there is one of each type peer at the very least. see End2end for how peers were constructed.
                    Assert.IsFalse(newChannel.GetPeers(new[] { PeerRole.EVENT_SOURCE }).Count == 0);
                    Assert.IsFalse(newChannel.GetPeers(new[] { PeerRole.EVENT_SOURCE }).Count == 0);
                }

                Assert.AreEqual(testConfig.IsFabricVersionAtOrAfter("1.3") ? 0 : 2, newChannel.EventHubs.Count);
                Util.COut("Retrieved channel {0} from sample store.", name);
            }
            else
            {
                newChannel = client.NewChannel(name);

                foreach (string ordererName in sampleOrg.GetOrdererNames())
                {
                    newChannel.AddOrderer(client.NewOrderer(ordererName, sampleOrg.GetOrdererLocation(ordererName), testConfig.GetOrdererProperties(ordererName)));
                }

                bool everyOther = false;

                foreach (string peerName in sampleOrg.GetPeerNames())
                {
                    string      peerLocation        = sampleOrg.GetPeerLocation(peerName);
                    Properties  peerProperties      = testConfig.GetPeerProperties(peerName);
                    Peer        peer                = client.NewPeer(peerName, peerLocation, peerProperties);
                    PeerOptions peerEventingOptions = // we have two peers on one use block on other use filtered
                                                      everyOther ? PeerOptions.CreatePeerOptions().RegisterEventsForBlocks().SetPeerRoles(PeerRole.ENDORSING_PEER, PeerRole.LEDGER_QUERY, PeerRole.CHAINCODE_QUERY, PeerRole.EVENT_SOURCE) : PeerOptions.CreatePeerOptions().RegisterEventsForFilteredBlocks().SetPeerRoles(PeerRole.ENDORSING_PEER, PeerRole.LEDGER_QUERY, PeerRole.CHAINCODE_QUERY, PeerRole.EVENT_SOURCE);

                    newChannel.AddPeer(peer, IS_FABRIC_V10 ? PeerOptions.CreatePeerOptions().SetPeerRoles(PeerRole.ENDORSING_PEER, PeerRole.LEDGER_QUERY, PeerRole.CHAINCODE_QUERY) : peerEventingOptions);

                    everyOther = !everyOther;
                }

                //For testing mix it up. For v1.1 use just peer eventing service for foo channel.
                if (IS_FABRIC_V10)
                {
                    //Should have no peers with event sources.
                    Assert.IsTrue(newChannel.GetPeers(new[] { PeerRole.EVENT_SOURCE }).Count == 0);
                    //Should have two peers with all roles but event source.
                    Assert.AreEqual(2, newChannel.Peers.Count);
                    foreach (string eventHubName in sampleOrg.GetEventHubNames())
                    {
                        EventHub eventHub = client.NewEventHub(eventHubName, sampleOrg.GetEventHubLocation(eventHubName), testConfig.GetEventHubProperties(eventHubName));
                        newChannel.AddEventHub(eventHub);
                    }
                }
                else
                {
                    //Peers should have all roles. Do some sanity checks that they do.

                    //Should have two peers with event sources.
                    Assert.AreEqual(2, newChannel.GetPeers(new[] { PeerRole.EVENT_SOURCE }).Count);
                    //Check some other roles too..
                    Assert.AreEqual(2, newChannel.GetPeers(new[] { PeerRole.CHAINCODE_QUERY, PeerRole.LEDGER_QUERY }).Count);
                    Assert.AreEqual(2, newChannel.GetPeers(PeerRoleExtensions.All()).Count); //really same as newChannel.getPeers()
                }

                Assert.AreEqual(IS_FABRIC_V10 ? sampleOrg.GetEventHubNames().Count : 0, newChannel.EventHubs.Count);
            }

            //Just some sanity check tests
            Assert.IsTrue(newChannel == client.GetChannel(name));
            Assert.IsTrue(client == newChannel.client);
            Assert.AreEqual(name, newChannel.Name);
            Assert.AreEqual(2, newChannel.Peers.Count);
            Assert.AreEqual(1, newChannel.Orderers.Count);
            Assert.IsFalse(newChannel.IsShutdown);
            Assert.IsFalse(newChannel.IsInitialized);
            string serializedChannelBytes = newChannel.Serialize();

            //Just checks if channel can be serialized and deserialized .. otherwise this is just a waste :)
            // Get channel back.

            newChannel.Shutdown(true);
            newChannel = client.DeSerializeChannel(serializedChannelBytes);

            Assert.AreEqual(2, newChannel.Peers.Count);

            Assert.AreEqual(1, newChannel.Orderers.Count);
            Assert.IsNotNull(client.GetChannel(name));
            Assert.AreEqual(newChannel, client.GetChannel(name));
            Assert.IsFalse(newChannel.IsInitialized);
            Assert.IsFalse(newChannel.IsShutdown);
            Assert.AreEqual(TESTUSER_1_NAME, client.UserContext.Name);
            newChannel.Initialize();
            Assert.IsTrue(newChannel.IsInitialized);
            Assert.IsFalse(newChannel.IsShutdown);

            //Begin tests with de-serialized channel.

            //Query the actual peer for which channels it belongs to and check it belongs to this channel
            foreach (Peer peer in newChannel.Peers)
            {
                HashSet <string> channels = client.QueryChannels(peer);
                if (!channels.Contains(name))
                {
                    Assert.Fail($"Peer {peer.Name} does not appear to belong to channel {name}");
                }
            }

            //Just see if we can get channelConfiguration. Not required for the rest of scenario but should work.
            byte[] channelConfigurationBytes = newChannel.GetChannelConfigurationBytes();
            Config channelConfig             = Config.Parser.ParseFrom(channelConfigurationBytes);

            Assert.IsNotNull(channelConfig);

            ConfigGroup channelGroup = channelConfig.ChannelGroup;

            Assert.IsNotNull(channelGroup);

            Dictionary <string, ConfigGroup> groupsMap = channelGroup.Groups.ToDictionary(a => a.Key, a => a.Value);

            Assert.IsNotNull(groupsMap.GetOrNull("Orderer"));

            Assert.IsNotNull(groupsMap.GetOrNull("Application"));

            //Before return lets see if we have the chaincode on the peers that we expect from End2endIT
            //And if they were instantiated too. this requires peer admin user

            client.UserContext = sampleOrg.PeerAdmin;

            foreach (Peer peer in newChannel.Peers)
            {
                if (!CheckInstalledChaincode(client, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION))
                {
                    Assert.Fail($"Peer {peer.Name} is missing chaincode name: {CHAIN_CODE_NAME}, path:{CHAIN_CODE_PATH}, version: {CHAIN_CODE_VERSION}");
                }

                if (!CheckInstantiatedChaincode(newChannel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION))
                {
                    Assert.Fail($"Peer {peer.Name} is missing instantiated chaincode name: {CHAIN_CODE_NAME}, path:{CHAIN_CODE_PATH}, version: {CHAIN_CODE_VERSION}");
                }
            }

            client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

            Assert.IsTrue(newChannel.IsInitialized);
            Assert.IsFalse(newChannel.IsShutdown);

            Util.COut("Finished reconstructing channel {0}.", name);

            return(newChannel);
        }