示例#1
0
        /*Broadcasts the script to all other peers*/
        public static void BroadcastTransaction(string[] script)
        {
            RestRequest   request = new RestRequest("api/client/getclientlist/");
            IRestResponse resp    = RestClient.Get(request);

            if (resp.IsSuccessful)
            {
                List <Client> clients = JsonConvert.DeserializeObject <List <Client> >(resp.Content);

                foreach (Client c in clients)
                {
                    if (c.port != me.port)                    //Don't broadcast it to me i already have it
                    {
                        ChannelFactory <PeerServerInterface> channelFactory;
                        NetTcpBinding tcp = new NetTcpBinding();
                        tcp.MaxReceivedMessageSize = 2147483647;
                        string clientURL = String.Format("net.tcp://{0}:{1}/DataService", c.ipaddress, c.port);
                        channelFactory = new ChannelFactory <PeerServerInterface>(tcp, clientURL);
                        PeerServerInterface channel = channelFactory.CreateChannel();
                        channel.GetNewScript(script);
                    }
                }
                logger.LogFunc("SUCCESS:Broadcasted script to all clients");
            }
            else
            {
                logger.LogFunc("ERROR:Could not broadcast script to all clients");
            }
        }
示例#2
0
        /*Called when the users enters and submits code*/
        public void SubmitCode_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ChannelFactory <PeerServerInterface> channelFactory;
                NetTcpBinding tcp = new NetTcpBinding();
                tcp.MaxReceivedMessageSize = 2147483647;
                string clientURL = String.Format("net.tcp://{0}:{1}/DataService", me.ipaddress, me.port);
                channelFactory = new ChannelFactory <PeerServerInterface>(tcp, clientURL);
                PeerServerInterface channel = channelFactory.CreateChannel();
                //Channel to the peer server has been created

                string   scriptStr  = CodeBox.Text;
                string   encodedStr = EncodeString(scriptStr);
                string[] codeStr    = new string[2] {
                    encodedStr, ""
                };                                                                  //Converting the ans to a string if it isn't already
                Job j = new Job(codeStr[0], codeStr[1], jobId);
                myJobs.Add(j);
                jobId++;                //incremented for the next job this client creates

                RestRequest   request = new RestRequest("api/client/getclientlist/");
                IRestResponse resp    = RestClient.Get(request);

                if (resp.IsSuccessful)                //Checking if the client list was available to get
                {
                    List <Client> clients = JsonConvert.DeserializeObject <List <Client> >(resp.Content);

                    foreach (Client c in clients)                    //Give this to every client including myself
                    {
                        tcp = new NetTcpBinding();
                        tcp.MaxReceivedMessageSize = 2147483647;
                        clientURL      = String.Format("net.tcp://{0}:{1}/DataService", c.ipaddress, c.port);
                        channelFactory = new ChannelFactory <PeerServerInterface>(tcp, clientURL);
                        channel        = channelFactory.CreateChannel();
                        channel.GetNewScript(codeStr);                        //Adding it to every clients script queue
                    }
                    UpdateJobList();
                }
                else
                {
                    logger.LogFunc("ERROR: Could not retrieve the list of clients");
                }
            }
            catch (FormatException ex)
            {
                logger.LogFunc("ERROR: The user input was incorrect");
                MessageBox.Show("Please input python script correctly");
            }
        }
示例#3
0
        public static void GetMostPopular(APIClasses.Block block)
        {
            bool          isPopular = false;
            RestRequest   request   = new RestRequest("api/client/getclientlist/");
            IRestResponse resp      = RestClient.Get(request);

            List <Client> clients = JsonConvert.DeserializeObject <List <Client> >(resp.Content);

            Dictionary <string, List <Client> > clientMap = new Dictionary <string, List <Client> >(); //<hash, <list<ports who have that hash>>

            Client mostPopular = new Client();                                                         //This is the client's whose block chain we will take
            int    popularity  = 0;
            string popularHash = block.hash;

            foreach (Client c in clients)
            {
                ChannelFactory <PeerServerInterface> channelFactory;
                NetTcpBinding tcp = new NetTcpBinding();
                tcp.MaxReceivedMessageSize = 2147483647;
                string clientURL = String.Format("net.tcp://{0}:{1}/DataService", c.ipaddress, c.port);
                channelFactory = new ChannelFactory <PeerServerInterface>(tcp, clientURL);
                PeerServerInterface channel = channelFactory.CreateChannel();
                APIClasses.Block    b       = channel.GetCurrentBlock();

                //Hash is the key and then if someone else has that key increase the value at that key
                if (clientMap.ContainsKey(b.hash))
                {
                    clientMap[b.hash].Add(c);
                }
                else
                {
                    List <Client> ports = new List <Client>();
                    ports.Add(c);
                    clientMap.Add(b.hash, ports);
                }
            }

            foreach (KeyValuePair <string, List <Client> > entry in clientMap)
            {
                if (entry.Value.Count > popularity)
                {
                    mostPopular = entry.Value.ElementAt(0);
                    popularHash = entry.Key;
                    popularity  = entry.Value.Count;
                }
            }
            if (!popularHash.Equals(block.hash))   //If my hash is not the most popular
            {
                Thread.Sleep(1000);                //Sleep long enough so you can get the updated version of the others
                ChannelFactory <PeerServerInterface> channelFactory;
                NetTcpBinding tcp = new NetTcpBinding();
                tcp.MaxReceivedMessageSize = 2147483647;
                string clientURL = String.Format("net.tcp://{0}:{1}/DataService", mostPopular.ipaddress, mostPopular.port);
                channelFactory = new ChannelFactory <PeerServerInterface>(tcp, clientURL);
                PeerServerInterface channel = channelFactory.CreateChannel();
                Messenger.blockChain = channel.GetBlockChain();
            }
            else
            {
                //you've got the best chain
            }
        }
示例#4
0
        /*-------------------------------------Network Thread------------------------------------------*/

        /* ---------------------------------------WARNING----------------------------------------------*/

        /* The code you are about to witness is a brainwave and if given more time it would be seperated
         * out into different functions and made more clear but I didn't have enough time				*/
        public async Task NetworkThread()
        {
            await Task.Run(() =>
            {
                try
                {
                    while (true)
                    {
                        RestRequest request = new RestRequest("api/client/getclientlist");
                        IRestResponse resp  = RestClient.Get(request);

                        clientList = JsonConvert.DeserializeObject <List <Client> >(resp.Content);
                        //Used to make the swarm more fair, start from the begginning and then start from the end
                        if (fairSwarm)
                        {
                            fairSwarm = false;
                            foreach (Client client in clientList)
                            {
                                if (me.port != client.port)
                                {
                                    ChannelFactory <PeerServerInterface> channelFactory;
                                    NetTcpBinding tcp          = new NetTcpBinding();
                                    tcp.MaxReceivedMessageSize = 2147483647;
                                    string clientURL           = String.Format("net.tcp://{0}:{1}/DataService", client.ipaddress, client.port);
                                    channelFactory             = new ChannelFactory <PeerServerInterface>(tcp, clientURL);
                                    channel = channelFactory.CreateChannel();

                                    currentJob = channel.DownloadJob();
                                    if (currentJob != null)
                                    {
                                        byte[] hash = CreateHash(currentJob.code);
                                        if (hash.SequenceEqual(currentJob.hash))
                                        {
                                            /*Sourced from
                                             * https://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app
                                             */
                                            Job doJob = currentJob;
                                            if (string.IsNullOrEmpty(doJob.code))
                                            {
                                                throw new EmptyCodeException();
                                            }
                                            else
                                            {
                                                byte[] eoncodedBytes = Convert.FromBase64String(doJob.code);
                                                string code          = System.Text.Encoding.UTF8.GetString(eoncodedBytes);
                                                ChangeUIElements(true);
                                                Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
                                                Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(code);
                                                var answer = pythonScript.Execute();
                                                Dispatcher.BeginInvoke(new Action(() =>
                                                {
                                                    try
                                                    {
                                                        doJob.answer = answer;
                                                        channel.UploadAns(doJob);
                                                        jobCount++;
                                                        ChangeJobCount();
                                                    }
                                                    catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)                                                    //Converting the answer to a string
                                                    {
                                                        doJob.answer = answer.ToString();
                                                        channel.UploadAns(doJob);
                                                        jobCount++;
                                                        ChangeJobCount();
                                                    }
                                                    ChangeUIElements(false);
                                                    Thread.Sleep(2000);                                                    //Just so it doesn't constantly keep checking it sleeps for 2 seconds to chill for a bit
                                                }));
                                            }

                                            currentJob = null;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            fairSwarm = true;
                            for (int i = clientList.Count - 1; i >= 0; i--)
                            {
                                Client client = clientList[i];
                                if (me.port != client.port)
                                {
                                    ChannelFactory <PeerServerInterface> channelFactory;
                                    NetTcpBinding tcp          = new NetTcpBinding();
                                    tcp.MaxReceivedMessageSize = 2147483647;
                                    string clientURL           = String.Format("net.tcp://{0}:{1}/DataService", client.ipaddress, client.port);
                                    channelFactory             = new ChannelFactory <PeerServerInterface>(tcp, clientURL);
                                    channel = channelFactory.CreateChannel();


                                    currentJob = channel.DownloadJob();
                                    if (currentJob != null)
                                    {
                                        byte[] hash = CreateHash(currentJob.code);
                                        if (hash.SequenceEqual(currentJob.hash))
                                        {
                                            /*Sourced from
                                             * https://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app
                                             */
                                            Job doJob = currentJob;
                                            if (string.IsNullOrEmpty(doJob.code))
                                            {
                                                throw new EmptyCodeException();
                                            }
                                            byte[] eoncodedBytes = Convert.FromBase64String(doJob.code);
                                            string code          = System.Text.Encoding.UTF8.GetString(eoncodedBytes);
                                            ChangeUIElements(true);
                                            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
                                            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(code);
                                            var answer = pythonScript.Execute();
                                            Dispatcher.BeginInvoke(new Action(() =>
                                            {
                                                //If have time encode ans but who cares for now
                                                try
                                                {
                                                    doJob.answer = answer;
                                                    channel.UploadAns(doJob);
                                                    jobCount++;
                                                    ChangeJobCount();
                                                }
                                                catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)                                                //Converting the answer to a string
                                                {
                                                    doJob.answer = answer.ToString();
                                                    channel.UploadAns(doJob);
                                                    jobCount++;
                                                    ChangeJobCount();
                                                }
                                                ChangeUIElements(false);
                                                Thread.Sleep(5000);
                                            }));

                                            currentJob = null;
                                        }
                                    }
                                }
                            }
                        }

                        UpdateScore();
                        Thread.Sleep(10000);
                    }
                }
                catch (System.ServiceModel.EndpointNotFoundException e)
                {
                    //Occurs when someone leaves the swarm
                    UpdateScore();
                    logger.LogFunc("Error occured in the Networking Thread, someone has left the swarm abruptly");
                }
                catch (IronPython.Runtime.UnboundNameException e)
                {
                    //When the input something not code
                    MessageBox.Show("It appears were given a job that was in the wrong format");
                    ChangeUIElements(false);
                    currentJob.error = true;
                    channel.UploadAns(currentJob);
                    logger.LogFunc("Error occured in the Networking Thread, the users input code is invalid");
                }
                catch (EmptyCodeException e)
                {
                    //when the input is empty
                    logger.LogFunc("Error occured in the Networking Thread, the user didn't enter any code");
                }
            });
        }