Example #1
0
        /**
         * Just for testing remove all peers and orderers and add them back.
         *
         * @param client
         * @param channel
         */
        public static void TestRemovingAddingPeersOrderers(HFClient client, Channel channel)
        {
            Dictionary <Peer, PeerOptions> perm = new Dictionary <Peer, PeerOptions>();

            Assert.IsTrue(channel.IsInitialized);
            Assert.IsFalse(channel.IsShutdown);
            Thread.Sleep(1500); // time needed let channel get config block

            channel.Peers.ToList().ForEach(peer =>
            {
                perm[peer] = channel.GetPeersOptions(peer);
                channel.RemovePeer(peer);
            });

            perm.Keys.ToList().ForEach(peer =>
            {
                PeerOptions value = perm[peer];
                Peer newPeer      = client.NewPeer(peer.Name, peer.Url, peer.Properties);
                channel.AddPeer(newPeer, value);
            });

            List <Orderer> removedOrders = new List <Orderer>();

            foreach (Orderer orderer in channel.Orderers.ToList())
            {
                channel.RemoveOrderer(orderer);
                removedOrders.Add(orderer);
            }

            removedOrders.ForEach(orderer =>
            {
                Orderer newOrderer = client.NewOrderer(orderer.Name, orderer.Url, orderer.Properties);
                channel.AddOrderer(newOrderer);
            });
        }
Example #2
0
    public RestApi(string key, string domain, string peerId, bool turn)
    {
        var peerParams = new PeerOptions();

        peerParams.key     = key;
        peerParams.domain  = domain;
        peerParams.peer_id = peerId;
        peerParams.turn    = turn;
        string peerParamsJson = JsonUtility.ToJson(peerParams);

        byte[] peerParamsBytes = Encoding.UTF8.GetBytes(peerParamsJson);
        //SkyWayサーバとの接続開始するためのAPIを叩く
        ObservableWWW.Post(entryPoint + "/peers", peerParamsBytes).Subscribe(x =>
        {
            //この時点ではSkyWay WebRTC GWが「このPeer IDで処理を開始する」という応答でしかなく、
            //SkyWayサーバで利用できるPeer IDとは限らない(重複で弾かれる等があり得るので)
            var response   = Json.Deserialize(x) as Dictionary <string, object>;
            var parameters = (IDictionary)response["params"];
            var peer_id    = (string)parameters["peer_id"];
            var token      = (string)parameters["token"];
            //SkyWayサーバとSkyWay WebRTC Gatewayが繋がって初めてPeer ID等が正式に決定するので、
            //イベントを監視する
            var url = string.Format("{0}/peers/{1}/events?token={2}", entryPoint, peer_id, token);
            ObservableWWW.Get(url).Repeat().Where(wx =>
            {
                //この時点ではOPENイベント以外はいらないので弾く
                var res = Json.Deserialize(wx) as Dictionary <string, object>;
                return(res.ContainsKey("event") && (string)res["event"] == "OPEN");
            }).First().Subscribe(sx =>             //ここでは最初の一回しか監視しない。着信等のイベントは後で別の場所で取ることにする
            {
                var response_j   = Json.Deserialize(sx) as Dictionary <string, object>;
                var parameters_s = (IDictionary)response_j["params"];
                //正式決定したpeer_idとtokenを記録しておく
                _peerId    = (string)parameters_s["peer_id"];
                _peerToken = (string)parameters_s["token"];
                //SkyWayサーバと繋がったときの処理を始める
                _OnOpen();
            }, ex =>
            {
                //ここが発火する場合は多分peer_idやtoken等が間違っている
                //もしくはSkyWay WebRTC GWとSkyWayサーバの間で通信ができてない
                Debug.LogError(ex);
            });
        }, ex =>
        {
            //ここが発火する場合はSkyWay WebRTC GWと通信できてないのでは。
            //そもそも起動してないとか
            //他には、前回ちゃんとClose処理をしなかったため前のセッションが残っている場合が考えられる。
            //その場合はWebRTC GWを再起動するか、別のPeer IDを利用する
            //時間が経てば勝手に開放されるのでそこまで気にしなくてもよい(気にしなくてもいいとは言ってない)
            Debug.LogError("error");
            Debug.LogError(ex);
        });
    }
Example #3
0
        public virtual async Task <Peer> AddAsync(Properties config, CancellationToken token = default(CancellationToken))
        {
            Properties properties     = new Properties();
            string     protocol       = this.FindClientProp(config, "protocol", "grpcs:");
            string     clientCertFile = this.FindClientProp(config, "clientCertFile", null);
            Peer       peer           = EndpointMap.GetOrNull(Endpoint); // maybe there already.

            if (null != peer)
            {
                return(peer);
            }
            if (null != clientCertFile)
            {
                properties.Set("clientCertFile", clientCertFile);
            }
            string clientKeyFile = this.FindClientProp(config, "clientKeyFile", null);

            if (null != clientKeyFile)
            {
                properties.Set("clientKeyFile", clientKeyFile);
            }
            string clientCertBytes = this.FindClientProp(config, "clientCertBytes", null);

            if (null != clientCertBytes)
            {
                properties.Set("clientCertBytes", clientCertBytes);
            }
            string clientKeyBytes = this.FindClientProp(config, "clientKeyBytes", null);

            if (null != clientKeyBytes)
            {
                properties.Set("clientKeyBytes", clientKeyBytes);
            }
            string hostnameOverride = this.FindClientProp(config, "hostnameOverride", null);

            if (null != hostnameOverride)
            {
                properties.Set("hostnameOverride", hostnameOverride);
            }
            byte[] pemBytes = this.GetAllTLSCerts();
            if (pemBytes?.Length > 0)
            {
                properties.Set("pemBytes", pemBytes);
            }
            peer = Client.NewPeer(Endpoint, protocol + "//" + Endpoint, properties);
            PeerOptions opts = PeerOptions.CreatePeerOptions();

            opts.SetPeerRoles(PeerRole.ENDORSING_PEER, PeerRole.EVENT_SOURCE, PeerRole.LEDGER_QUERY, PeerRole.CHAINCODE_QUERY);
            await Channel.AddPeerAsync(peer, opts, token).ConfigureAwait(false);

            return(peer);
        }
Example #4
0
        public void TestChannelInitialize()
        {
            //test may not be doable once initialize is done


            Channel testChannel = new MockChannel(CHANNEL_NAME, hfclient);
            Peer    peer        = hfclient.NewPeer("peer_", "grpc://localhost:7051");

            testChannel.AddPeer(peer, PeerOptions.CreatePeerOptions().SetPeerRoles(PeerRole.ENDORSING_PEER));
            Assert.IsFalse(testChannel.IsInitialized);
            testChannel.Initialize();
            Assert.IsTrue(testChannel.IsInitialized);
        }
Example #5
0
        // ReSharper disable once UnusedParameter.Local
        private static void SetPeerRole(PeerOptions peerOptions, JToken jsonPeer, PeerRole role)
        {
            string propName = RoleNameRemap(role);
            JToken val      = jsonPeer[propName];

            if (val != null)
            {
                bool isSet = val.Value <bool>();

                /*if (isSet == null) {
                 *  // This is an invalid boolean value
                 *  throw new NetworkConfigurationException(format("Error constructing channel %s. Role %s has invalid boolean value: %s", channelName, propName, val.toString()));
                 * }*/
                if (isSet)
                {
                    peerOptions.AddPeerRole(role);
                }
            }
        }
        /**
         * Construct client for accessing Peer eventing service using the existing managedChannel.
         */
        public PeerEventServiceClient(Peer peer, Endpoint endpoint, Properties properties, PeerOptions peerOptions)
        {
            channelBuilder             = endpoint;
            filterBlock                = peerOptions.IsRegisterEventsForFilteredBlocks;
            this.peer                  = peer;
            name                       = peer.Name;
            url                        = peer.Url;
            channelName                = peer.Channel.Name;
            toString                   = $"PeerEventServiceClient{{id: {Config.Instance.GetNextID()}, channel: {channelName}, peerName: {name}, url: {url}}}";
            this.peerOptions           = peerOptions;
            clientTLSCertificateDigest = endpoint.GetClientTLSCertificateDigest();

            channelEventQue = peer.Channel.ChannelEventQueue;

            if (null == properties)
            {
                peerEventRegistrationWaitTimeMilliSecs = PEER_EVENT_REGISTRATION_WAIT_TIME;
            }
            else
            {
                peerEventRegistrationWaitTimeMilliSecs = properties.GetLongProperty("peerEventRegistrationWaitTime", PEER_EVENT_REGISTRATION_WAIT_TIME);
            }
        }
        [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!");
        }
Example #8
0
 public LoginParameters(string peerId)
 {
     this.options_ = new PeerOptions(peerId);
 }
Example #9
0
        // Reconstructs an existing channel
        private async Task <Channel> ReconstructChannelAsync(HFClient client, string channelName, JToken jsonChannel, CancellationToken token = default(CancellationToken))
        {
            Channel channel;


            channel = client.NewChannel(channelName);

            // orderers is an array of orderer name strings
            JArray ordererNames = jsonChannel["orderers"] as JArray;

            //out("Orderer names: " + (ordererNames == null ? "null" : ordererNames.toString()));
            if (ordererNames != null)
            {
                foreach (JToken jsonVal in ordererNames)
                {
                    string  ordererName = jsonVal.Value <string>();
                    Orderer orderer     = GetOrderer(client, ordererName);
                    if (orderer == null)
                    {
                        throw new NetworkConfigurationException($"Error constructing channel {channelName}. Orderer {ordererName} not defined in configuration");
                    }

                    channel.AddOrderer(orderer);
                }
            }

            // peers is an object containing a nested object for each peer
            JToken jsonPeers = jsonChannel["peers"];
            bool   foundPeer = false;

            //out("Peers: " + (peers == null ? "null" : peers.toString()));
            if (jsonPeers != null)
            {
                foreach (JProperty prop in jsonPeers.Children <JProperty>())
                {
                    string peerName = prop.Name;

                    if (logger.IsTraceEnabled())
                    {
                        logger.Trace($"NetworkConfig.reconstructChannel: Processing peer {peerName}");
                    }

                    JToken jsonPeer = prop.Value;
                    if (jsonPeer == null)
                    {
                        throw new NetworkConfigurationException($"Error constructing channel {channelName}. Invalid peer entry: {peerName}");
                    }

                    Peer peer = GetPeer(client, peerName);
                    if (peer == null)
                    {
                        throw new NetworkConfigurationException($"Error constructing channel {channelName}. Peer {peerName} not defined in configuration");
                    }

                    // Set the various roles
                    PeerOptions peerOptions = PeerOptions.CreatePeerOptions();
                    foreach (PeerRole peerRole in Enum.GetValues(typeof(PeerRole)))
                    {
                        SetPeerRole(peerOptions, jsonPeer, peerRole);
                    }

                    foundPeer = true;

                    // Add the event hub associated with this peer
                    EventHub eventHub = GetEventHub(client, peerName);
                    if (eventHub != null)
                    {
                        await channel.AddEventHubAsync(eventHub, token).ConfigureAwait(false);

                        if (!peerOptions.HasPeerRoles())
                        {
                            // means no roles were found but there is an event hub so define all roles but eventing.
                            peerOptions.SetPeerRoles(new List <PeerRole> {
                                PeerRole.ENDORSING_PEER, PeerRole.CHAINCODE_QUERY, PeerRole.LEDGER_QUERY
                            });
                        }
                    }

                    await channel.AddPeerAsync(peer, peerOptions, token).ConfigureAwait(false);
                }
            }

            if (!foundPeer)
            {
                // peers is a required field
                throw new NetworkConfigurationException($"Error constructing channel {channelName}. At least one peer must be specified");
            }

            return(channel);
        }
        private void TestPeerServiceEventingReplay(HFClient client, Channel replayTestChannel, long start, long stop, bool useFilteredBlocks)
        {
            if (testConfig.IsRunningAgainstFabric10())
            {
                return; // not supported for v1.0
            }

            Assert.IsFalse(replayTestChannel.IsInitialized); //not yet initialized
            Assert.IsFalse(replayTestChannel.IsShutdown);    // not yet shutdown.

            //Remove all peers just have one ledger peer and one eventing peer.
            List <Peer> savedPeers = new List <Peer>(replayTestChannel.Peers);

            foreach (Peer peer in savedPeers)
            {
                replayTestChannel.RemovePeer(peer);
            }

            Assert.IsTrue(savedPeers.Count > 1); //need at least two
            Peer eventingPeer = savedPeers[0];

            eventingPeer = client.NewPeer(eventingPeer.Name, eventingPeer.Url, eventingPeer.Properties);
            Peer ledgerPeer = savedPeers[1];

            ledgerPeer = client.NewPeer(ledgerPeer.Name, ledgerPeer.Url, ledgerPeer.Properties);

            savedPeers.RemoveAt(0);
            savedPeers.RemoveAt(0);

            Assert.IsTrue(replayTestChannel.Peers.Count == 0);                                                                 // no more peers.
            Assert.IsTrue(replayTestChannel.GetPeers(new[] { PeerRole.CHAINCODE_QUERY, PeerRole.ENDORSING_PEER }).Count == 0); // just checking :)
            Assert.IsTrue(replayTestChannel.GetPeers(new[] { PeerRole.LEDGER_QUERY }).Count == 0);                             // just checking

            Assert.IsNotNull(client.GetChannel(replayTestChannel.Name));                                                       // should be known by client.

            PeerOptions eventingPeerOptions = PeerOptions.CreatePeerOptions().SetPeerRoles(new List <PeerRole> {
                PeerRole.EVENT_SOURCE
            });

            if (useFilteredBlocks)
            {
                eventingPeerOptions.RegisterEventsForFilteredBlocks();
            }

            if (-1L == stop)
            {
                //the height of the blockchain

                replayTestChannel.AddPeer(eventingPeer, eventingPeerOptions.StartEvents(start)); // Eventing peer start getting blocks from block 0
            }
            else
            {
                replayTestChannel.AddPeer(eventingPeer, eventingPeerOptions.StartEvents(start).StopEvents(stop)); // Eventing peer start getting blocks from block 0
            }

            //add a ledger peer
            replayTestChannel.AddPeer(ledgerPeer, PeerOptions.CreatePeerOptions().SetPeerRoles(new List <PeerRole> {
                PeerRole.LEDGER_QUERY
            }));

            TaskCompletionSource <long> done = new TaskCompletionSource <long>(); // future to set when done.
            // some variable used by the block listener being set up.

            long    bcount       = 0;
            long    stopValue    = stop == -1L ? long.MaxValue : stop;
            Channel finalChannel = replayTestChannel;
            ConcurrentDictionary <long, BlockEvent> blockEvents = new ConcurrentDictionary <long, BlockEvent>();

            string blockListenerHandle = replayTestChannel.RegisterBlockListener((blockEvent) =>
            {
                try
                {
                    long blockNumber = blockEvent.BlockNumber;
                    if (blockEvents.ContainsKey(blockNumber))
                    {
                        Assert.Fail($"Block number {blockNumber} seen twice");
                    }
                    blockEvents[blockNumber] = blockEvent;


                    Assert.IsTrue(useFilteredBlocks ? blockEvent.IsFiltered : !blockEvent.IsFiltered, $"Wrong type of block seen block number {blockNumber}. expected filtered block {useFilteredBlocks} but got {blockEvent.IsFiltered}");
                    long count = Interlocked.Increment(ref bcount) - 1;


                    //out("Block count: %d, block number: %d  received from peer: %s", count, blockNumber, blockEvent.getPeer().getName());

                    if (count == 0 && stop == -1L)
                    {
                        BlockchainInfo blockchainInfo = finalChannel.QueryBlockchainInfo();

                        long lh   = blockchainInfo.Height;
                        stopValue = lh - 1L; // blocks 0L 9L are on chain height 10 .. stop on 9
                        //  out("height: %d", lh);
                        if (Interlocked.Read(ref bcount) + start > stopValue)
                        {
                            // test with latest count.

                            done.SetResult(Interlocked.Read(ref bcount));
                        }
                    }
                    else
                    {
                        if (Interlocked.Read(ref bcount) + start > stopValue)
                        {
                            done.SetResult(count);
                        }
                    }
                }
                catch (System.Exception e)
                {
                    done.SetException(e);
                }
            });


            try
            {
                replayTestChannel.Initialize(); // start it all up.
                done.Task.Wait(30 * 1000);
                Thread.Sleep(1000);             // sleep a little to see if more blocks trickle in .. they should not
                replayTestChannel.UnregisterBlockListener(blockListenerHandle);

                long expectNumber = stopValue - start + 1L; // Start 2 and stop is 3  expect 2

                Assert.AreEqual(expectNumber, blockEvents.Count, $"Didn't get number we expected {expectNumber} but got {blockEvents.Count} block events. Start: {start}, end: {stop}, height: {stopValue}");

                for (long i = stopValue; i >= start; i--)
                {
                    //make sure all are there.
                    BlockEvent blockEvent = blockEvents[i];
                    Assert.IsNotNull(blockEvent, $"Missing block event for block number {i}. Start= {start}", blockEvent);
                }

                //light weight test just see if we get reasonable values for traversing the block. Test just whats common between
                // Block and FilteredBlock.

                int transactionEventCounts = 0;
                int chaincodeEventsCounts  = 0;

                for (long i = stopValue; i >= start; i--)
                {
                    BlockEvent blockEvent = blockEvents[i];
//                out("blockwalker %b, start: %d, stop: %d, i: %d, block %d", useFilteredBlocks, start, stopValue.longValue(), i, blockEvent.getBlockNumber());
                    Assert.AreEqual(useFilteredBlocks, blockEvent.IsFiltered); // check again

                    if (useFilteredBlocks)
                    {
                        Assert.IsNull(blockEvent.Block);            // should not have raw block event.
                        Assert.IsNotNull(blockEvent.FilteredBlock); // should have raw filtered block.
                    }
                    else
                    {
                        Assert.IsNotNull(blockEvent.Block);      // should not have raw block event.
                        Assert.IsNull(blockEvent.FilteredBlock); // should have raw filtered block.
                    }

                    Assert.AreEqual(replayTestChannel.Name, blockEvent.ChannelId);

                    foreach (EnvelopeInfo envelopeInfo in blockEvent.EnvelopeInfos)
                    {
                        if (envelopeInfo.EnvelopeType == EnvelopeType.TRANSACTION_ENVELOPE)
                        {
                            TransactionEnvelopeInfo transactionEnvelopeInfo = (TransactionEnvelopeInfo)envelopeInfo;
                            Assert.IsTrue(envelopeInfo.IsValid); // only have valid blocks.
                            Assert.AreEqual(envelopeInfo.ValidationCode, 0);

                            ++transactionEventCounts;
                            foreach (TransactionActionInfo ta in transactionEnvelopeInfo.TransactionActionInfos)
                            {
                                //    out("\nTA:", ta + "\n\n");
                                ChaincodeEventDeserializer evnt = ta.Event;
                                if (evnt != null)
                                {
                                    Assert.IsNotNull(evnt.ChaincodeId);
                                    Assert.IsNotNull(evnt.EventName);
                                    chaincodeEventsCounts++;
                                }
                            }
                        }
                        else
                        {
                            Assert.AreEqual(blockEvent.BlockNumber, 0, "Only non transaction block should be block 0.");
                        }
                    }
                }

                Assert.IsTrue(transactionEventCounts > 0);

                if (expectNumber > 4)
                {
                    // this should be enough blocks with CC events.

                    Assert.IsTrue(chaincodeEventsCounts > 0);
                }

                replayTestChannel.Shutdown(true); //all done.
            }
            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);
        }