예제 #1
0
        public void TestLoadFromConfigFileYamlNOOverrides()
        {
            // Should be able to instantiate a new instance of "Client" with a valid path to the YAML configuration
            string        f      = TestUtils.TestUtils.RelocateFilePathsYAML("fixture/sdkintegration/network_configs/network-config.yaml".Locate());
            NetworkConfig config = NetworkConfig.FromYamlFile(f);

            //HFClient client = HFClient.loadFromConfig(f);
            Assert.IsNotNull(config);
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();
            client.UserContext = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);

            Channel channel = client.LoadChannelFromConfig("foo", config);

            Assert.IsNotNull(channel);

            Assert.IsTrue(channel.Peers.Count != 0);

            foreach (Peer peer in channel.Peers)
            {
                Properties properties = peer.Properties;

                Assert.IsNotNull(properties);
                //Assert.IsNull(properties.Get("grpc.keepalive_time_ms"));
                Assert.IsNull(properties.Get("grpc.keepalive_timeout_ms"));
                //Assert.IsNull(properties.Get("grpc.NettyChannelBuilderOption.keepAliveWithoutCalls"));
            }
        }
예제 #2
0
        public void TestLoadFromConfigFileYamlNOOverridesButSet()
        {
            // Should be able to instantiate a new instance of "Client" with a valid path to the YAML configuration
            string        f      = TestUtils.TestUtils.RelocateFilePathsYAML("fixture/sdkintegration/network_configs/network-config.yaml".Locate());
            NetworkConfig config = NetworkConfig.FromYamlFile(f);

            //HFClient client = HFClient.loadFromConfig(f);
            Assert.IsNotNull(config);

            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();
            client.UserContext = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);


            Channel channel = client.LoadChannelFromConfig("foo", config);

            Assert.IsNotNull(channel);

            Assert.IsTrue(channel.Orderers.Count != 0);

            foreach (Orderer orderer in channel.Orderers)
            {
                Properties properties = orderer.Properties;
                string     str        = properties.Get("grpc.keepalive_time_ms");
                Assert.AreEqual(long.Parse(str), 360000L);

                str = properties.Get("grpc.keepalive_timeout_ms");
                Assert.AreEqual(long.Parse(str), 180000L);
            }
        }
예제 #3
0
        public static HFClient Create()
        {
            HFClient hfclient = HFClient.Create();

            SetupClient(hfclient);
            return(hfclient);
        }
예제 #4
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;
        }
        public void RunFabricTest(SampleStore sStore)
        {
            ////////////////////////////
            // Setup client

            //Create instance of client.
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();

            ////////////////////////////
            //Reconstruct and run the channels
            SampleOrg sampleOrg  = testConfig.GetIntegrationTestsSampleOrg("peerOrg1");
            Channel   fooChannel = ReconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg);

            RunChannel(client, fooChannel, sampleOrg, 0);
            Assert.IsFalse(fooChannel.IsShutdown);
            Assert.IsTrue(fooChannel.IsInitialized);
            fooChannel.Shutdown(true); //clean up resources no longer needed.
            Assert.IsTrue(fooChannel.IsShutdown);
            Util.COut("\n");

            sampleOrg = testConfig.GetIntegrationTestsSampleOrg("peerOrg2");
            Channel barChannel = ReconstructChannel(BAR_CHANNEL_NAME, client, sampleOrg);

            RunChannel(client, barChannel, sampleOrg, 100); //run a newly constructed foo channel with different b value!
            Assert.IsFalse(barChannel.IsShutdown);
            Assert.IsTrue(barChannel.IsInitialized);

            if (!testConfig.IsRunningAgainstFabric10())
            {
                //Peer eventing service support started with v1.1

                // Now test replay feature of V1.1 peer eventing services.
                string json = barChannel.Serialize();
                barChannel.Shutdown(true);

                Channel replayChannel = client.DeSerializeChannel(json);

                Util.COut("doing testPeerServiceEventingReplay,0,-1,false");
                TestPeerServiceEventingReplay(client, replayChannel, 0L, -1L, false);

                replayChannel = client.DeSerializeChannel(json);
                Util.COut("doing testPeerServiceEventingReplay,0,-1,true"); // block 0 is import to test
                TestPeerServiceEventingReplay(client, replayChannel, 0L, -1L, true);

                //Now do it again starting at block 1
                replayChannel = client.DeSerializeChannel(json);
                Util.COut("doing testPeerServiceEventingReplay,1,-1,false");
                TestPeerServiceEventingReplay(client, replayChannel, 1L, -1L, false);

                //Now do it again starting at block 2 to 3
                replayChannel = client.DeSerializeChannel(json);
                Util.COut("doing testPeerServiceEventingReplay,2,3,false");
                TestPeerServiceEventingReplay(client, replayChannel, 2L, 3L, false);
            }

            Util.COut("That's all folks!");
        }
예제 #6
0
        public void TestBadUserContextNull()
        {
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();

            client.UserContext = null;
        }
예제 #7
0
        public void TestBadUserNameNull()
        {
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();

            TestUtils.TestUtils.MockUser mockUser = TestUtils.TestUtils.GetMockUser(null, USER_MSP_ID);

            client.UserContext = mockUser;
        }
예제 #8
0
        public void TestGoodMockUser()
        {
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();
            client.UserContext = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);
            Orderer orderer = hfclient.NewOrderer("justMockme", "grpc://localhost:99"); // test mock should work.

            Assert.IsNotNull(orderer);
        }
예제 #9
0
        public void TestBadUserMSPIDNull()
        {
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();


            TestUtils.TestUtils.MockUser mockUser = TestUtils.TestUtils.GetMockUser(USER_NAME, null);

            client.UserContext = mockUser;
        }
예제 #10
0
        public void TestBadEnrollmentNull()
        {
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();


            TestUtils.TestUtils.MockUser mockUser = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);
            mockUser.Enrollment = null;
            client.UserContext  = mockUser;
        }
예제 #11
0
        // Returns a new client instance
        private static HFClient GetTheClient()
        {
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();

            IUser peerAdmin = GetAdminUser(TEST_ORG);

            client.UserContext = peerAdmin;

            return(client);
        }
예제 #12
0
        public void TestBadEnrollmentBadKey()
        {
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();



            TestUtils.TestUtils.MockUser mockUser = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);

            IEnrollment mockEnrollment = TestUtils.TestUtils.GetMockEnrollment(null, "mockCert");

            mockUser.Enrollment = mockEnrollment;
            client.UserContext  = mockUser;
        }
예제 #13
0
        public void TestNewChannel()
        {
            // Should be able to instantiate a new instance of "Channel" with the definition in the network configuration'
            JObject jsonConfig = GetJsonConfig(1, 0, 1);

            NetworkConfig config = NetworkConfig.FromJsonObject(jsonConfig);

            HFClient client = HFClient.Create();

            TestHFClient.SetupClient(client);

            Channel channel = client.LoadChannelFromConfig(CHANNEL_NAME, config);

            Assert.IsNotNull(channel);
            Assert.AreEqual(CHANNEL_NAME, channel.Name);
            Assert.AreEqual(channel.GetPeers(PeerRole.SERVICE_DISCOVERY).Count, 1);
        }
예제 #14
0
        public void TestGetChannelNotExists()
        {
            // Should be able to instantiate a new instance of "Client" with a valid path to the YAML configuration
            string        f      = TestUtils.TestUtils.RelocateFilePathsYAML("fixture/sdkintegration/network_configs/network-config.yaml".Locate());
            NetworkConfig config = NetworkConfig.FromYamlFile(f);

            //HFClient client = HFClient.loadFromConfig(f);
            Assert.IsNotNull(config);


            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();
            client.UserContext = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);

            client.LoadChannelFromConfig("MissingChannel", config);
        }
예제 #15
0
        public void TestCryptoFactory()
        {
            TestUtils.TestUtils.ResetConfig();
            Assert.IsNotNull(Config.Instance.GetDefaultCryptoSuiteFactory());

            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();


            TestUtils.TestUtils.MockUser mockUser = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);

            IEnrollment mockEnrollment = TestUtils.TestUtils.GetMockEnrollment(null, "mockCert");

            mockUser.Enrollment = mockEnrollment;
            client.UserContext  = mockUser;
        }
예제 #16
0
        public void TestGetChannelNoPeers()
        {
            // Should not be able to instantiate a new instance of "Channel" with no peers configured
            JObject jsonConfig = GetJsonConfig(1, 1, 0);

            NetworkConfig config = NetworkConfig.FromJsonObject(jsonConfig);

            HFClient client = HFClient.Create();

            TestHFClient.SetupClient(client);

            client.LoadChannelFromConfig(CHANNEL_NAME, config);

            //HFClient client = HFClient.loadFromConfig(jsonConfig);
            //TestHFClient.setupClient(client);

            //client.getChannel(CHANNEL_NAME);
        }
예제 #17
0
        public void TestLoadFromConfigFileJson()
        {
            // Should be able to instantiate a new instance of "Client" with a valid path to the JSON configuration
            string        f      = TestUtils.TestUtils.RelocateFilePathsJSON("fixture/sdkintegration/network_configs/network-config.json".Locate());
            NetworkConfig config = NetworkConfig.FromJsonFile(f);

            Assert.IsNotNull(config);

            //HFClient client = HFClient.loadFromConfig(f);
            //Assert.Assert.IsNotNull(client);

            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();
            client.UserContext = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);

            Channel channel = client.LoadChannelFromConfig("mychannel", config);

            Assert.IsNotNull(channel);
        }
예제 #18
0
        public void TestGetChannel()
        {
            // Should be able to instantiate a new instance of "Channel" with orderer, org and peer defined in the network configuration
            JObject jsonConfig = GetJsonConfig(4, 1, 1);

            NetworkConfig config = NetworkConfig.FromJsonObject(jsonConfig);

            HFClient client = HFClient.Create();

            TestHFClient.SetupClient(client);

            Channel channel = client.LoadChannelFromConfig(CHANNEL_NAME, config);

            //HFClient client = HFClient.loadFromConfig(jsonConfig);
            //TestHFClient.setupClient(client);

            //Channel channel = client.getChannel(CHANNEL_NAME);
            Assert.IsNotNull(channel);
            Assert.AreEqual(CHANNEL_NAME, channel.Name);

            IReadOnlyList <Orderer> orderers = channel.Orderers;

            Assert.IsNotNull(orderers);
            Assert.AreEqual(1, orderers.Count);

            Orderer orderer = orderers.First();

            Assert.AreEqual("orderer1.example.com", orderer.Name);

            IReadOnlyList <Peer> peers = channel.Peers;

            Assert.IsNotNull(peers);
            Assert.AreEqual(1, peers.Count);

            Peer peer = peers.First();

            Assert.AreEqual("peer0.org1.example.com", peer.Name);
        }
예제 #19
0
        public void RunFabricTest(SampleStore sStore)
        {
            ////////////////////////////
            // Setup client

            //Create instance of client.
            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.GetCryptoSuite();
            client.UserContext = sStore.GetMember(TEST_ADMIN_NAME, "peerOrg2");

            SampleOrg sampleOrg = testConfig.GetIntegrationTestsSampleOrg("peerOrg2");

            Channel barChannel = sStore.GetChannel(client, BAR_CHANNEL_NAME);

            barChannel.Initialize();
            RunChannel(client, barChannel, sampleOrg, 10);
            Assert.IsFalse(barChannel.IsShutdown);
            Assert.IsTrue(barChannel.IsInitialized);

            if (testConfig.IsFabricVersionAtOrAfter("1.3"))
            {
                HashSet <string> expect = new HashSet <string>(new [] { "COLLECTION_FOR_A", "COLLECTION_FOR_B" });
                HashSet <string> got    = new HashSet <string>();

                CollectionConfigPackage queryCollectionsConfig = barChannel.QueryCollectionsConfig(CHAIN_CODE_NAME, barChannel.Peers.First(), sampleOrg.PeerAdmin);
                foreach (CollectionConfig collectionConfig in queryCollectionsConfig.CollectionConfigs)
                {
                    got.Add(collectionConfig.Name);
                }
                CollectionAssert.AreEqual(expect.ToList(), got.ToList());
            }


            Util.COut("That's all folks!");
        }
예제 #20
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!");
        }
예제 #21
0
        public void Setup()
        {
            try
            {
                ////////////////////////////
                // Setup client

                //Create instance of client.
                HFClient client = HFClient.Create();

                client.CryptoSuite = Factory.Instance.GetCryptoSuite();

                ////////////////////////////
                //Set up USERS

                //Persistence is not part of SDK. Sample file store is for demonstration purposes only!
                //   MUST be replaced with more robust application implementation  (Database, LDAP)
                string sampleStoreFile = Path.Combine(Path.GetTempPath(), "HFCSampletest.properties");

                SampleStore sampleStore = new SampleStore(sampleStoreFile);

                //SampleUser can be any implementation that implements org.hyperledger.fabric.sdk.User Interface

                ////////////////////////////
                // get users for all orgs

                foreach (SampleOrg sampleOrgs in testSampleOrgs)
                {
                    string orgName = sampleOrgs.Name;
                    sampleOrgs.PeerAdmin = sampleStore.GetMember(orgName + "Admin", orgName);
                }

                ////////////////////////////
                //Reconstruct and run the channels
                SampleOrg sampleOrg  = testConfig.GetIntegrationTestsSampleOrg("peerOrg1");
                Channel   fooChannel = ReconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg);

                // Getting foo channels current configuration bytes.
                byte[] channelConfigurationBytes = fooChannel.GetChannelConfigurationBytes();

                string responseAsString = ConfigTxlatorDecode(channelConfigurationBytes);


                //responseAsString is JSON but use just string operations for this test.

                if (!responseAsString.Contains(ORIGINAL_BATCH_TIMEOUT))
                {
                    Assert.Fail($"Did not find expected batch timeout '{ORIGINAL_BATCH_TIMEOUT}', in:{responseAsString}");
                }

                //Now modify the batch timeout
                string updateString = responseAsString.Replace(ORIGINAL_BATCH_TIMEOUT, UPDATED_BATCH_TIMEOUT);
                (int statuscode, byte[] data) = HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/encode/common.Config", updateString.ToBytes());
                Util.COut("Got {0} status for encoding the new desired channel config bytes", statuscode);
                Assert.AreEqual(200, statuscode);
                byte[] newConfigBytes = data;

                // Now send to configtxlator multipart form post with original config bytes, updated config bytes and channel name.
                List <(string Name, byte[] Body, string Mime, string FName)> parts = new List <(string Name, byte[] Body, string Mime, string FName)>();
                parts.Add(("original", channelConfigurationBytes, "application/octet-stream", "originalFakeFilename"));
                parts.Add(("updated", newConfigBytes, "application/octet-stream", "updatedFakeFilename"));
                parts.Add(("channel", fooChannel.Name.ToBytes(), null, null));
                (statuscode, data) = HttpPostMultiPart(CONFIGTXLATOR_LOCATION + "/configtxlator/compute/update-from-configs", parts);
                Util.COut("Got {0} status for updated config bytes needed for updateChannelConfiguration ", statuscode);
                Assert.AreEqual(200, statuscode);
                byte[] updateBytes = data;

                UpdateChannelConfiguration updateChannelConfiguration = new UpdateChannelConfiguration(updateBytes);

                //To change the channel we need to sign with orderer admin certs which crypto gen stores:

                // private key: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/[email protected]/msp/keystore/f1a9a940f57419a18a83a852884790d59b378281347dd3d4a88c2b820a0f70c9_sk
                //certificate:  src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/[email protected]/msp/signcerts/[email protected]

                string     sampleOrgName = sampleOrg.Name;
                SampleUser ordererAdmin  = sampleStore.GetMember(sampleOrgName + "OrderAdmin", sampleOrgName, "OrdererMSP", Util.FindFileSk("fixture/sdkintegration/e2e-2Orgs/" + TestConfig.Instance.FAB_CONFIG_GEN_VERS + "/crypto-config/ordererOrganizations/example.com/users/[email protected]/msp/keystore/"), ("fixture/sdkintegration/e2e-2Orgs/" + TestConfig.Instance.FAB_CONFIG_GEN_VERS + "/crypto-config/ordererOrganizations/example.com/users/[email protected]/msp/signcerts/[email protected]").Locate());

                client.UserContext = ordererAdmin;

                //Ok now do actual channel update.
                fooChannel.UpdateChannelConfiguration(updateChannelConfiguration, client.GetUpdateChannelConfigurationSignature(updateChannelConfiguration, ordererAdmin));

                Thread.Sleep(3000); // give time for events to happen

                //Let's add some additional verification...

                client.UserContext = sampleOrg.PeerAdmin;

                byte[] modChannelBytes = fooChannel.GetChannelConfigurationBytes();

                //Now decode the new channel config bytes to json...
                responseAsString = ConfigTxlatorDecode(modChannelBytes);


                if (!responseAsString.Contains(UPDATED_BATCH_TIMEOUT))
                {
                    //If it doesn't have the updated time out it failed.
                    Assert.Fail($"Did not find updated expected batch timeout '{UPDATED_BATCH_TIMEOUT}', in:{responseAsString}");
                }

                if (responseAsString.Contains(ORIGINAL_BATCH_TIMEOUT))
                {
                    //Should not have been there anymore!

                    Assert.Fail($"Found original batch timeout '{ORIGINAL_BATCH_TIMEOUT}', when it was not expected in:{responseAsString}");
                }


                Assert.IsTrue(eventCountFilteredBlock > 0); // make sure we got blockevent that were tested.
                Assert.IsTrue(eventCountBlock > 0);         // make sure we got blockevent that were tested.

                //Should be no anchor peers defined.
                Assert.IsFalse(new Regex(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM).Match(responseAsString).Success);
                Assert.IsFalse(new Regex(REGX_S_ANCHOR_PEERS).Match(responseAsString).Success);

                // Get config update for adding an anchor peer.
                Channel.AnchorPeersConfigUpdateResult configUpdateAnchorPeers = fooChannel.GetConfigUpdateAnchorPeers(fooChannel.Peers.First(), sampleOrg.PeerAdmin, new List <string> {
                    PEER_0_ORG_1_EXAMPLE_COM_7051
                }, null);

                Assert.IsNotNull(configUpdateAnchorPeers.UpdateChannelConfiguration);
                Assert.IsTrue(configUpdateAnchorPeers.PeersAdded.Contains(PEER_0_ORG_1_EXAMPLE_COM_7051));

                //Now add anchor peer to channel configuration.
                fooChannel.UpdateChannelConfiguration(configUpdateAnchorPeers.UpdateChannelConfiguration, client.GetUpdateChannelConfigurationSignature(configUpdateAnchorPeers.UpdateChannelConfiguration, sampleOrg.PeerAdmin));

                Thread.Sleep(3000); // give time for events to happen

                // Getting foo channels current configuration bytes to check with configtxlator
                channelConfigurationBytes = fooChannel.GetChannelConfigurationBytes();
                responseAsString          = ConfigTxlatorDecode(channelConfigurationBytes);

                // Check is anchor peer in config block?
                Assert.IsTrue(new Regex(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM).Match(responseAsString).Success);
                Assert.IsTrue(new Regex(REGX_S_ANCHOR_PEERS).Match(responseAsString).Success);

                //Should see what's there.
                configUpdateAnchorPeers = fooChannel.GetConfigUpdateAnchorPeers(fooChannel.Peers.First(), sampleOrg.PeerAdmin, null, null);

                Assert.IsNull(configUpdateAnchorPeers.UpdateChannelConfiguration);                           // not updating anything.
                Assert.IsTrue(configUpdateAnchorPeers.CurrentPeers.Contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should   be there.
                Assert.IsTrue(configUpdateAnchorPeers.PeersRemoved.Count == 0);                              // not removing any
                Assert.IsTrue(configUpdateAnchorPeers.PeersAdded.Count == 0);                                // not adding anything.
                Assert.IsTrue(configUpdateAnchorPeers.UpdatedPeers.Count == 0);                              // not updating anyting.

                //Now remove the anchor peer -- get the config update block.
                configUpdateAnchorPeers = fooChannel.GetConfigUpdateAnchorPeers(fooChannel.Peers.First(), sampleOrg.PeerAdmin, null, new List <string> {
                    PEER_0_ORG_1_EXAMPLE_COM_7051
                });

                Assert.IsNotNull(configUpdateAnchorPeers.UpdateChannelConfiguration);
                Assert.IsTrue(configUpdateAnchorPeers.CurrentPeers.Contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should still be there.
                Assert.IsTrue(configUpdateAnchorPeers.PeersRemoved.Contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer to remove.
                Assert.IsTrue(configUpdateAnchorPeers.PeersAdded.Count == 0);                                // not adding anything.
                Assert.IsTrue(configUpdateAnchorPeers.UpdatedPeers.Count == 0);                              // no peers should be left.

                // Now do the actual update.
                fooChannel.UpdateChannelConfiguration(configUpdateAnchorPeers.UpdateChannelConfiguration, client.GetUpdateChannelConfigurationSignature(configUpdateAnchorPeers.UpdateChannelConfiguration, sampleOrg.PeerAdmin));
                Thread.Sleep(3000); // give time for events to happen
                // Getting foo channels current configuration bytes to check with configtxlator.
                channelConfigurationBytes = fooChannel.GetChannelConfigurationBytes();
                responseAsString          = ConfigTxlatorDecode(channelConfigurationBytes);

                Assert.IsFalse(new Regex(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM).Match(responseAsString).Success); // should be gone!
                Assert.IsTrue(new Regex(REGX_S_ANCHOR_PEERS).Match(responseAsString).Success);                   //ODDLY we still want this even if it's empty!

                //Should see what's there.
                configUpdateAnchorPeers = fooChannel.GetConfigUpdateAnchorPeers(fooChannel.Peers.First(), sampleOrg.PeerAdmin, null, null);

                Assert.IsNull(configUpdateAnchorPeers.UpdateChannelConfiguration); // not updating anything.
                Assert.IsTrue(configUpdateAnchorPeers.CurrentPeers.Count == 0);    // peer should be now gone.
                Assert.IsTrue(configUpdateAnchorPeers.PeersRemoved.Count == 0);    // not removing any
                Assert.IsTrue(configUpdateAnchorPeers.PeersAdded.Count == 0);      // not adding anything.
                Assert.IsTrue(configUpdateAnchorPeers.UpdatedPeers.Count == 0);    // no peers should be left


                Util.COut("That's all folks!");
            }
            catch (System.Exception e)
            {
                Assert.Fail(e.Message);
            }
        }
예제 #22
0
        public void TestLoadFromConfigFileYamlOverrides()
        {
            // Should be able to instantiate a new instance of "Client" with a valid path to the YAML configuration
            string        f      = TestUtils.TestUtils.RelocateFilePathsYAML("fixture/sdkintegration/network_configs/network-config.yaml".Locate());
            NetworkConfig config = NetworkConfig.FromYamlFile(f);

            foreach (string peerName in config.PeerNames)
            {
                Properties peerProperties = config.GetPeerProperties(peerName);

                //example of setting keepAlive to avoid timeouts on inactive http2 connections.
                // Under 5 minutes would require changes to server side to accept faster ping rates.
                peerProperties.Set("grpc.keepalive_time_ms", 5 * 60 * 1000);
                peerProperties.Set("grpc.keepalive_timeout_ms", 8 * 1000);
//            peerProperties.Set("grpc.NettyChannelBuilderOption.keepAliveWithoutCalls", "true");
                config.SetPeerProperties(peerName, peerProperties);
            }

            foreach (string orderName in config.OrdererNames)
            {
                Properties ordererProperties = config.GetOrdererProperties(orderName);
                ordererProperties.Set("grpc.max_receive_message_length", 9000000);
                //ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveWithoutCalls", new Object[] {false});
                config.SetOrdererProperties(orderName, ordererProperties);
            }

            //HFClient client = HFClient.loadFromConfig(f);
            Assert.IsNotNull(config);

            HFClient client = HFClient.Create();

            client.CryptoSuite = Factory.Instance.GetCryptoSuite();
            client.UserContext = TestUtils.TestUtils.GetMockUser(USER_NAME, USER_MSP_ID);

            Channel channel = client.LoadChannelFromConfig("foo", config);

            Assert.IsNotNull(channel);

            Assert.IsTrue(channel.Peers.Count > 0);

            foreach (Peer peer in channel.Peers)
            {
                Properties properties = peer.Properties;

                Assert.IsNotNull(properties);
                Assert.IsNotNull(properties.Get("grpc.keepalive_time_ms"));
                Assert.IsNotNull(properties.Get("grpc.keepalive_timeout_ms"));
                //Assert.IsNotNull(properties.get("grpc.NettyChannelBuilderOption.keepAliveWithoutCalls"));

                Endpoint      ep               = new Endpoint(peer.Url, properties);
                ChannelOption keepalive        = ep.ChannelOptions.FirstOrDefault(a => a.Name == "grpc.keepalive_time_ms");
                ChannelOption keepalivetimeout = ep.ChannelOptions.FirstOrDefault(a => a.Name == "grpc.keepalive_timeout_ms");
                Assert.IsNotNull(keepalive);
                Assert.IsNotNull(keepalivetimeout);
                Assert.AreEqual(5 * 60 * 1000, keepalive.IntValue);
                Assert.AreEqual(8 * 1000, keepalivetimeout.IntValue);
            }

            foreach (Orderer orderer in channel.Orderers)
            {
                Properties properties = orderer.Properties;

                Assert.IsNotNull(properties);
                Assert.IsNotNull(properties.Get("grpc.max_receive_message_length"));
                //Assert.IsNotNull(properties.get("grpc.NettyChannelBuilderOption.keepAliveWithoutCalls"));

                Endpoint      ep    = new Endpoint(orderer.Url, properties);
                ChannelOption msize = ep.ChannelOptions.FirstOrDefault(a => a.Name == "grpc.max_receive_message_length");
                Assert.IsNotNull(msize);
                Assert.AreEqual(9000000, msize.IntValue);
            }
        }
예제 #23
0
 public void SetupClient()
 {
     hfclient   = HFClient.Create();
     mockstream = new MemoryStream();
 }
예제 #24
0
 public void TestBadCryptoSuite()
 {
     HFClient.Create().NewOrderer("xx", "xxxxxx");
     Assert.Fail("Orderer allowed setting no cryptoSuite");
 }