Beispiel #1
0
        private void EnrollIdemixUser(SampleOrg sampleOrg, SampleUser user, SampleUser admin)
        {
            if (!user.IsRegistered)
            {
                // users need to be registered AND enrolled
                RegistrationRequest rr = new RegistrationRequest(user.Name, "org1.department1");
                user.EnrollmentSecret = sampleOrg.CAClient.Register(rr, admin);
            }

            if (!user.IsEnrolled)
            {
                user.Enrollment = sampleOrg.CAClient.Enroll(user.Name, user.EnrollmentSecret);
                user.MspId      = sampleOrg.MSPID;
            }
            // If running version 1.3, then get Idemix credential
            if (testConfig.IsFabricVersionAtOrAfter("1.3"))
            {
                string mspID = "idemixMSPID1";
                if (sampleOrg.Name.Contains("Org2"))
                {
                    mspID = "idemixMSPID2";
                }
                user.Enrollment = sampleOrg.CAClient.IdemixEnroll(user.Enrollment, sampleOrg.MSPID);
            }
        }
        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!");
        }
Beispiel #3
0
        internal override Channel ConstructChannel(string name, HFClient client, SampleOrg sampleOrg)
        {
            // override this method since we don't want to construct the channel that's been done.
            // Just get it out of the samplestore!

            client.UserContext = sampleOrg.PeerAdmin;
            return(sampleStore.GetChannel(client, name).Initialize());
        }
        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!");
        }
Beispiel #5
0
 public string GetClientPEMTLSCertificate(SampleOrg sampleOrg)
 {
     return(GetValue("clientPEMTLSCertificate." + sampleOrg.Name));
 }
Beispiel #6
0
 public void StoreClientPEMTLCertificate(SampleOrg sampleOrg, string certificate)
 {
     SetValue("clientPEMTLSCertificate." + sampleOrg.Name, certificate);
 }
Beispiel #7
0
 public string GetClientPEMTLSKey(SampleOrg sampleOrg)
 {
     return(GetValue("clientPEMTLSKey." + sampleOrg.Name));
 }
Beispiel #8
0
 public void StoreClientPEMTLSKey(SampleOrg sampleOrg, string key)
 {
     SetValue("clientPEMTLSKey." + sampleOrg.Name, key);
 }
Beispiel #9
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);
            }
        }
        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);
        }
        // Disable MethodLength as this method is for instructional purposes and hence
        // we don't want to split it into smaller pieces
        // CHECKSTYLE:OFF: MethodLength
        private void RunChannel(HFClient client, Channel channel, SampleOrg sampleOrg, int delta)
        {
            string channelName = channel.Name;

            try
            {
                client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

                //This is for testing only and can be ignored.
                TestUtils.TestUtils.TestRemovingAddingPeersOrderers(client, channel);

                //            final boolean changeContext = false; // BAR_CHANNEL_NAME.equals(channel.getName()) ? true : false;
                bool changeContext = BAR_CHANNEL_NAME.Equals(channel.Name);

                Util.COut("Running Channel {0} with a delta {1}", channelName, delta);

                Util.COut("ChaincodeID: {0}", chaincodeID);
                ////////////////////////////
                // Send Query Proposal to all peers see if it's what we expect from end of End2endIT
                //
                QueryChaincodeForExpectedValue(client, channel, "" + (300 + delta), chaincodeID);

                //Set user context on client but use explicit user contest on each call.
                if (changeContext)
                {
                    client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);
                }

                // exercise v1 of chaincode

                MoveAmount(client, channel, chaincodeID, "25", changeContext ? sampleOrg.PeerAdmin : null);


                WaitOnFabric();
                client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

                QueryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);

                //////////////////
                // Start of upgrade first must install it.

                client.UserContext = sampleOrg.PeerAdmin;
                ///////////////
                ////
                InstallProposalRequest installProposalRequest = client.NewInstallProposalRequest();
                installProposalRequest.ChaincodeID = chaincodeID;
                ////For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
                installProposalRequest.ChaincodeSourceLocation = Path.Combine(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).Locate();

                installProposalRequest.ChaincodeVersion  = CHAIN_CODE_VERSION_11;
                installProposalRequest.ProposalWaitTime  = DEPLOYWAITTIME;
                installProposalRequest.ChaincodeLanguage = CHAIN_CODE_LANG;

                if (changeContext)
                {
                    installProposalRequest.UserContext = sampleOrg.PeerAdmin;
                }

                Util.COut("Sending install proposal for channel: {0}", channel.Name);

                ////////////////////////////
                // only a client from the same org as the peer can issue an install request
                int numInstallProposal = 0;

                List <ProposalResponse> responses;
                List <ProposalResponse> successful   = new List <ProposalResponse>();
                List <ProposalResponse> failed       = new List <ProposalResponse>();
                IReadOnlyList <Peer>    peersFromOrg = channel.Peers;
                numInstallProposal = numInstallProposal + peersFromOrg.Count;

                responses = client.SendInstallProposal(installProposalRequest, peersFromOrg);

                foreach (ProposalResponse response in responses)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful install proposal response Txid: {0} from peer {1}", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received {0} install proposal responses. Successful+verified: {1} . Failed: {2}", numInstallProposal, successful.Count, failed.Count);

                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail($"Not enough endorsers for install : {successful.Count}.  {first.Message}");
                }

                //////////////////
                // Upgrade chaincode to ***double*** our move results.

                if (changeContext)
                {
                    installProposalRequest.UserContext = sampleOrg.PeerAdmin;
                }

                UpgradeProposalRequest upgradeProposalRequest = client.NewUpgradeProposalRequest();
                upgradeProposalRequest.ChaincodeID      = chaincodeID_11;
                upgradeProposalRequest.ProposalWaitTime = testConfig.GetProposalWaitTime();
                upgradeProposalRequest.Fcn  = "init";
                upgradeProposalRequest.Args = new List <string>(); // no arguments don't change the ledger see chaincode.

                ChaincodeEndorsementPolicy chaincodeEndorsementPolicy;

                chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
                chaincodeEndorsementPolicy.FromYamlFile(Path.Combine(TEST_FIXTURES_PATH, "sdkintegration/chaincodeendorsementpolicy.yaml").Locate());

                upgradeProposalRequest.ChaincodeEndorsementPolicy = chaincodeEndorsementPolicy;
                Dictionary <string, byte[]> tmap = new Dictionary <string, byte[]>();
                tmap.Add("test", "data".ToBytes());
                upgradeProposalRequest.SetTransientMap(tmap);

                if (changeContext)
                {
                    upgradeProposalRequest.UserContext = sampleOrg.PeerAdmin;
                }

                Util.COut("Sending upgrade proposal");

                List <ProposalResponse> responses2;

                responses2 = channel.SendUpgradeProposal(upgradeProposalRequest);

                successful.Clear();
                failed.Clear();
                foreach (ProposalResponse response in responses2)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful upgrade proposal response Txid: {0} from peer {1}", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received {0} upgrade proposal responses. Successful+verified: {1} . Failed: {2}", channel.Peers.Count, successful.Count, failed.Count);

                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail($"Not enough endorsers for upgrade : {successful.Count}.  {first.Message}");
                }

                if (changeContext)
                {
                    channel.SendTransaction(successful, sampleOrg.PeerAdmin, testConfig.GetTransactionWaitTime() * 1000);
                }
                else
                {
                    channel.SendTransaction(successful, testConfig.GetTransactionWaitTime() * 1000);
                }

                WaitOnFabric(10000);

                Util.COut("Chaincode has been upgraded to version {0}", CHAIN_CODE_VERSION_11);

                //Check to see if peers have new chaincode and old chaincode is gone.

                client.UserContext = sampleOrg.PeerAdmin;
                foreach (Peer peer in channel.Peers)
                {
                    if (!CheckInstalledChaincode(client, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11))
                    {
                        Assert.Fail($"Peer {peer.Name} is missing chaincode name:{CHAIN_CODE_NAME}, path:{CHAIN_CODE_PATH}, version: {CHAIN_CODE_VERSION_11}");
                    }

                    //should be instantiated too..
                    if (!CheckInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11))
                    {
                        Assert.Fail($"Peer {peer.Name} is missing instantiated chaincode name:{CHAIN_CODE_NAME}, path:{CHAIN_CODE_PATH}, version: {CHAIN_CODE_VERSION_11}");
                    }

                    if (CheckInstantiatedChaincode(channel, 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);

                //Check if we still get the same value on the ledger
                Util.COut("delta is {0}", delta);
                QueryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);

                MoveAmount(client, channel, chaincodeID_11, "50", changeContext ? sampleOrg.PeerAdmin : null); // really move 100
            }
            catch (TransactionEventException t)
            {
                TransactionEvent te = t.TransactionEvent;
                if (te != null)
                {
                    Assert.Fail($"Transaction with txid {te.TransactionID} failed. {t.Message}");
                }
            }
            catch (System.Exception e)
            {
                Assert.Fail($"Test failed with {e.GetType().Name} exception {e.Message}");
            }

            WaitOnFabric(10000);
            QueryChaincodeForExpectedValue(client, channel, "" + (425 + delta), chaincodeID_11);
            Util.COut("Running for Channel {0} done", channelName);
        }
        // Disable MethodLength as this method is for instructional purposes and hence
        // we don't want to split it into smaller pieces
        // CHECKSTYLE:OFF: MethodLength
        private void RunChannel(HFClient client, Channel channel, SampleOrg sampleOrg, int delta)
        {
            string channelName = channel.Name;

            try
            {
                client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

                Util.COut("Running Channel %s with a delta %d", channelName, delta);

                Util.COut("ChaincodeID: ", chaincodeID);

                client.UserContext = sampleOrg.PeerAdmin;
                ///////////////
                ////
                InstallProposalRequest installProposalRequest = client.NewInstallProposalRequest();
                installProposalRequest.SetChaincodeID(chaincodeID);
                ////For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
                installProposalRequest.SetChaincodeSourceLocation(Path.Combine(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).Locate());
                installProposalRequest.SetChaincodeVersion(CHAIN_CODE_VERSION);
                installProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
                installProposalRequest.SetChaincodeLanguage(CHAIN_CODE_LANG);

                Util.COut("Sending install proposal for channel: %s", channel.Name);

                ////////////////////////////
                // only a client from the same org as the peer can issue an install request
                int numInstallProposal = 0;

                List <ProposalResponse> responses;
                List <ProposalResponse> successful   = new List <ProposalResponse>();
                List <ProposalResponse> failed       = new List <ProposalResponse>();
                List <Peer>             peersFromOrg = channel.Peers.ToList();
                numInstallProposal = numInstallProposal + peersFromOrg.Count;

                responses = client.SendInstallProposal(installProposalRequest, peersFromOrg);

                foreach (ProposalResponse response in responses)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful install proposal response Txid: %s from peer %s", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received %d install proposal responses. Successful+verified: %d . Failed: %d", numInstallProposal, successful.Count, failed.Count);

                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail("Not enough endorsers for install :" + successful.Count + ".  " + first.Message);
                }

                InstantiateProposalRequest instantiateProposalRequest = client.NewInstantiationProposalRequest();
                instantiateProposalRequest.SetChaincodeID(chaincodeID);
                instantiateProposalRequest.SetProposalWaitTime(DEPLOYWAITTIME);
                instantiateProposalRequest.SetFcn("init");
                instantiateProposalRequest.SetArgs(new string[] { });
                instantiateProposalRequest.SetChaincodeCollectionConfiguration(ChaincodeCollectionConfiguration.FromYamlFile("fixture/collectionProperties/PrivateDataIT.yaml".Locate()));

                Util.COut("Sending instantiate proposal");

                List <ProposalResponse> responses2;

                responses2 = channel.SendInstantiationProposal(instantiateProposalRequest);

                successful.Clear();
                failed.Clear();
                foreach (ProposalResponse response in responses2)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful upgrade proposal response Txid: %s from peer %s", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received %d upgrade proposal responses. Successful+verified: %d . Failed: %d", channel.Peers.Count, successful.Count, failed.Count);

                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail("Not enough endorsers for upgrade :" + successful.Count + ".  " + first.Message);
                }

                Util.COut("Sending instantiate proposal to orderer.");
                channel.SendTransaction(successful, sampleOrg.PeerAdmin);
                Util.COut("instantiate proposal completed.");

                //Now lets run the new chaincode which should *double* the results we asked to move.
                // return setAmount(client, channel, chaincodeID, "50", null).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
                SetAmount(client, channel, chaincodeID, 50, null);
                Util.COut("Got back acknowledgement from setAmount from all peers.");
                WaitOnFabric(10000);

                Util.COut("delta is %s", delta);
                QueryChaincodeForExpectedValue(client, channel, "" + 250, chaincodeID);
                //Now lets run the new chaincode which should *double* the results we asked to move.
                MoveAmount(client, channel, chaincodeID, "50", null);
            }
            catch (TransactionEventException e)
            {
                TransactionEvent te = e.TransactionEvent;
                Assert.Fail($"Transaction with txid %s failed. %s", te.TransactionID, e.Message);
            }

            catch (System.Exception e)
            {
                Assert.Fail($"Test failed with {e.Message} exception {e}");
            }

            QueryChaincodeForExpectedValue(client, channel, "" + 300, chaincodeID);

            Util.COut("Running for Channel %s done", channelName);
        }