Start() private method

private Start ( ) : void
return void
コード例 #1
0
        /// <summary>
        /// Fired when the plugin is enabled.
        /// </summary>
        public override void OnEnabled()
        {
            try
            {
                harmony = new Harmony($"com.joker.DI-{DateTime.Now.Ticks}");
                harmony.PatchAll();
            }
            catch (Exception e)
            {
                Log.Error(e);
            }

            Language = new Language();
            Network  = new Network(Instance.Config.Bot.IPAddress, Instance.Config.Bot.Port, TimeSpan.FromSeconds(Instance.Config.Bot.ReconnectionInterval));

            NetworkCancellationTokenSource = new CancellationTokenSource();

            Language.Save();
            Language.Load();

            RegisterEvents();

            coroutines.Add(Timing.RunCoroutine(CountTicks(), Segment.Update));

            Bot.UpdateActivityCancellationTokenSource      = new CancellationTokenSource();
            Bot.UpdateChannelsTopicCancellationTokenSource = new CancellationTokenSource();

            _ = Network.Start(NetworkCancellationTokenSource.Token);

            _ = Bot.UpdateActivity(Bot.UpdateActivityCancellationTokenSource.Token);
            _ = Bot.UpdateChannelsTopic(Bot.UpdateChannelsTopicCancellationTokenSource.Token);

            base.OnEnabled();
        }
コード例 #2
0
ファイル: TorPdos GUI.Designer.cs プロジェクト: tlorentzen/P2
        void BtnLoginClick(object sender, EventArgs e)
        {
            string pass = txtPassword.Text;
            string path = DiskHelper.GetRegistryValue("Path");

            if (IdHandler.IsValidUser(pass))
            {
                IdHandler.GetUuid(pass);
                LoggedIn();
                loggedIn = true;
                _idx     = new Index(path);
                _p2P     = new Network(25565, _idx, path);
                _p2P.Start();
                _idx.Load();
                IndexEventHandlers();

                if (!_idx.Load())
                {
                    _idx.BuildIndex();
                }
                _idx.Start();
                _idx.MakeIntegrityCheck();
            }
            else
            {
                Controls.Add(lblNope);
            }
        }
コード例 #3
0
ファイル: Core.cs プロジェクト: tabrath/meshwork
        private static void AddNetwork(NetworkInfo networkInfo)
        {
            foreach (Network thisNetwork in networks)
            {
                if (thisNetwork.NetworkID == networkInfo.NetworkID)
                {
                    throw new Exception("That network has already been added.");
                }
            }

            Network network = Network.FromNetworkInfo(networkInfo);

            networks.Add(network);

            /*
             *          if (!fileSystem.RootDirectory.HasSubdirectory(network.NetworkID)) {
             *                  Directory directory = fileSystem.RootDirectory.CreateSubdirectory(network.NetworkID);
             *                  directory.Requested = true;
             *          }
             */

            if (NetworkAdded != null)
            {
                NetworkAdded(network);
            }
            network.Start();
        }
コード例 #4
0
    public static void Main()
    {
        // Opens the server and sets its settings
        Console.Title = "Blackthorn Server";
        Logo();
        Console.WriteLine("[Initialize Server Startup]");

        // Checks if all directories exist, if they do not exist then create them
        Directories.Create();
        Console.WriteLine("Directories created.");

        // Clears and loads all required data
        Read.Required();
        Clean.Required();

        // Creates network devices
        Network.Start();
        Console.WriteLine("Network started.");

        // Calculates how long it took to initialize the server
        Console.WriteLine("\r\n" + "Server started. Type 'Help' to see the commands." + "\r\n");

        // Starts the ties
        Thread Comandos_Laço = new Thread(Tie.Commands);

        Comandos_Laço.Start();
        Tie.Principal();
    }
コード例 #5
0
ファイル: Program.cs プロジェクト: olejeek/game
        static void Main(string[] args)
        {
            //string connectionString =
            //    @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Ragnarok.mdb";
            //using (OleDbConnection connection = new OleDbConnection(connectionString))
            //{
            //    connection.Open();
            //    Console.WriteLine("ServerVersion: {0} \nDataSource: {1}",
            //    connection.ServerVersion, connection.DataSource);
            //    string command = "SELECT * FROM users";
            //    OleDbCommand cmd = new OleDbCommand(command, connection);
            //    OleDbDataReader reader = cmd.ExecuteReader();
            //    while (reader.Read())
            //    {
            //        Console.WriteLine("Id: {0, -4} Name: {1, -10} Pswd: {2, -10} Ban: {3}", reader[0],
            //            reader[1], reader[2], reader[3]);
            //    }
            //    connection.Close();
            //}
            //SkillList = new Dictionary<string, Skiller>();
            //SkillListFiller();
            //Location loc1 = new Location(0);
            //loc1.Start();
            Network netServer = Network.CreateServer();

            netServer.Start();
            Console.Read();
        }
コード例 #6
0
        private void ListenProcess(uint pid)
        {
            if (network == null)
            {
                network = new Network(pid);

                network.OnReceived += (mode, interval, timestamp) =>
                {
                    Dispatcher.Invoke(() => {
                        switch (mode)
                        {
                        case 0:
                            {
                                StopPlay(true);
                                Logger.Debug("net stop");
                                break;
                            }

                        case 1:
                            {
                                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));     // 当地时区
                                state.TimeWhenPlay = startTime.AddSeconds(timestamp + interval);
                                //var msTime = (dt - (DateTime.Now + SystemTimeOffset)).TotalMilliseconds;
                                if (state.ReadyFlag)
                                {
                                    StartPlay();
                                }
                                Logger.Info($"net: TimeWhenPlay[{state.TimeWhenPlay}]");
                                break;
                            }
                        }
                    });
                };

                network.OnStatusChanged += status =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        if (status)
                        {
                            captureStatusLabel.Content    = "状态:已同步";
                            captureStatusLabel.Foreground = System.Windows.Media.Brushes.BlueViolet;
                        }
                        else
                        {
                            captureStatusLabel.Content    = "状态:未同步";
                            captureStatusLabel.Foreground = System.Windows.Media.Brushes.Red;
                        }
                    });
                };
            }
            else if (pid != network.ProcessID)
            {
                network.Stop();
                network.ProcessID = pid;
            }

            network.Start();
        }
コード例 #7
0
 public void Start()
 {
     Network.Start();
     Listener.Start();
     Listener.BeginAcceptSocket(AcceptClient, null);
     HeartbeatTimer.Change(HeartbeatInterval, HeartbeatInterval);
     Console.WriteLine("Starbound: Listening on " + Listener.LocalEndpoint);
 }
コード例 #8
0
ファイル: GameManager.cs プロジェクト: bullgurkan/TicTacToe
    public void RunGame()
    {
        World        world = new World(20, 5);
        InputHandler input = new InputHandler(world);

        keybindingManager.Start();
        network?.Start();

        Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight);

        Console.CursorVisible = false;

        world.DrawWorldWholeWorld(input.HoveredTile, input.HoveredTile);

        int opponentHoveredTile = input.HoveredTile;

        //if no one has won keep playing
        while (endState < 1)
        {
            if (network == null)
            {
                endState = input.Update(world, network, keybindingManager, true);
                world.DrawHoveredPos(input.HoveredTile, input.HoveredTile);
            }
            else
            {
                endState = input.Update(world, network, keybindingManager, network.PlayerId == (int)world.CurrentPlayer);

                if (endState == 0 && network.PlayerId != (int)world.CurrentPlayer)
                {
                    int move = network.GetOpponentMove();

                    if (world.InBounds(move))
                    {
                        opponentHoveredTile = move;
                        endState            = world.MakeMove(opponentHoveredTile);
                    }
                }

                world.DrawHoveredPos(network.PlayerId == 1 ? input.HoveredTile : opponentHoveredTile, network.PlayerId == 2 ? input.HoveredTile : opponentHoveredTile);
            }



            System.Threading.Thread.Sleep(1);
        }

        network?.Stop();

        PostGame();
    }
コード例 #9
0
        private bool ListenNetwork()
        {
            Network network = TSingleton <Network> .Instance;

            if (network.Start(m_port))
            {
                Information("Listening TCP ..");
                Information("done\n");
                return(true);
            }
            Information("Listening TCP ..");
            Information("failed\n");
            return(false);
        }
コード例 #10
0
ファイル: Window1.xaml.cs プロジェクト: jcbozonier/flowsharp
        private void ClickButton_Click(object sender, RoutedEventArgs e)
        {
            network = new Network();
            network.AddComponent<AdderComponent>("Sum1");
            network.AddComponent<AutoInputComponent>("EvenNumberGenerator");
            network.AddComponent<AutoInputComponent>("OddNumberGenerator");
            network.AddComponent<OutputterComponent>("NetworkOutput");

            network.Connect("EvenNumberGenerator", "OUT", "Sum1", "Term1IN");
            network.Connect("OddNumberGenerator", "OUT", "Sum1", "Term2IN");
            network.Connect("Sum1", "OUT", "NetworkOutput", "IN");

            network.Start();
        }
コード例 #11
0
ファイル: Core.cs プロジェクト: rahulyhg/cms-cli
        public static void Start(WaveApplication appInfo)
        {
            // saving application info
            Application = appInfo;

            // saving data from global App object
            BuildID       = App.Instance.Build.BuildID;
            UseEncryption = !App.Instance.Build.PlatformOptions.Contains(PlatformOption.NoEncryption);
            IsMetro       = App.Instance.Build.ClientOptions[ClientOption.MetroOptimisations].Equals(WaveConstant.True, StringComparison.InvariantCultureIgnoreCase);

            // initialising agents
            Settings.Start();
            Cache.Start();
            Network.Start();
        }
コード例 #12
0
        private bool ListenNetwork()
        {
            Network network = new Network(m_port);

            if (network.Start())
            {
                Information("Listening TCP ..");

                Information("done\n");
                return(true);
            }
            Information("Listening TCP ..");

            Information("failed\n");
            return(false);
        }
コード例 #13
0
ファイル: Server.cs プロジェクト: j-oh/Online-CTF
        public Server()
        {
            Console.WriteLine("NetGame Server (" + Universal.GAME_VERSION + ")");
            string serverName = "My Server";

            random  = new Random();
            world   = new World();
            network = new Network();
            network.Start(world, serverName);
            world.SetNetwork(network);
            updateTimer          = new Timer(1000 / Universal.FRAME_RATE);
            updateTimer.Elapsed += new ElapsedEventHandler(UpdateElapsed);
            updateTimer.Start();
            while (true)
            {
                network.Update();
            }
        }
コード例 #14
0
    public static void Main()
    {
        // Verifica se todos os Directories existem, se não existirem então criá-los
        Directories.Create();

        // Carrega todos os Data
        Read.Data();

        // Inicializa todos os Devices
        Graphics.LerTextures();
        Audio.Som.Read();
        Network.Start();

        // Abre a Window
        Window.Objects.Text    = Lists.Options.Jogo_Name;
        Window.Objects.Visible = true;
        Jogo.OpenMenu();

        // Inicia a aplicação
        Tie.Principal();
    }
コード例 #15
0
ファイル: GolemServer.cs プロジェクト: LambdaSix/Golem
        public void Main(ServerOptions options)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var version  = assembly.GetName().Version;

            Console.WriteLine($"Golem - Version {version}");
            Console.WriteLine($"Core: Running on .net framework {Environment.Version}");

            SetupEnvironment();
            SetupNetwork();

            CreateKernel();
            Network.Start();
            // TODO: Issue global messages for ServerStarted
            CommandDispatcher = new CommandDispatcher();

            while (!_closing)
            {
                _signal.WaitOne();
                // TODO: Slice game tick
                // TODO: Slice message pump
                // TODO: Process any disposed network handles
            }
        }
コード例 #16
0
        /// <summary>
        /// Fired when the plugin is enabled.
        /// </summary>
        public override void OnEnabled()
        {
            Language = new Language();
            Network  = new Network(Instance.Config.Bot.IPAddress, Instance.Config.Bot.Port, TimeSpan.FromSeconds(Instance.Config.Bot.ReconnectionInterval));

            NetworkCancellationTokenSource = new CancellationTokenSource();

            Language.Save();
            Language.Load();

            RegisterEvents();

            coroutines.Add(Timing.RunCoroutine(CountTicks(), Segment.Update));

            Bot.UpdateActivityCancellationTokenSource      = new CancellationTokenSource();
            Bot.UpdateChannelsTopicCancellationTokenSource = new CancellationTokenSource();

            _ = Network.Start(NetworkCancellationTokenSource.Token);

            _ = Bot.UpdateActivity(Bot.UpdateActivityCancellationTokenSource.Token);
            _ = Bot.UpdateChannelsTopic(Bot.UpdateChannelsTopicCancellationTokenSource.Token);

            base.OnEnabled();
        }
コード例 #17
0
        public static void Start(string path, string configfile)
        {
            Runner.PingTime = 4373;
            Type t = Type.GetType("Mono.Runtime");

            if (t != null)
            {
                Runner.Mono = true;
            }
            else
            {
                Runner.Mono = false;
            }
            SimpleMesh.Service.Runner.StorePath  = path;
            SimpleMesh.Service.Runner.ConfigFile = configfile;

            SimpleMesh.Service.Runner.Network = new Trackfile();
            SimpleMesh.Service.Runner.Read();
            try
            {
                NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in adapters)
                {
                    IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
                    foreach (IPAddressInformation unicast in adapterProperties.UnicastAddresses)
                    {
                        if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            string[] chunks = unicast.Address.ToString().Split('.');
                            if (chunks[0] != "169")
                            {
                                Info.Addresses.Add(unicast.Address);
                            }
                        }
                        else
                        {
                            Info.Addresses.Add(unicast.Address);
                        }
                    }
                }
            }
            catch
            {
            }
            if (Info.Addresses.Count == 0)
            {
                try
                {
                    System.Net.IPHostEntry myiphost = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
                    foreach (System.Net.IPAddress myipadd in myiphost.AddressList)
                    {
                        Info.Addresses.Add(myipadd);
                    }
                }
                catch
                {
                    if (Runner.Mono == true)
                    {
                        Info.Addresses.Add(IPAddress.Any);
                        Info.Addresses.Add(IPAddress.IPv6Any);
                    }
                }
            }

            Info.Compile();
            SimpleMesh.Service.Runner.Write();
            SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", SimpleMesh.Service.Runner.StorePath);
            SimpleMesh.Service.Runner.DebugMessage("Debug.Info.ConfigFile", SimpleMesh.Service.Runner.ConfigFile);
            string TrackfilePath = SimpleMesh.Service.Runner.StorePath + System.IO.Path.DirectorySeparatorChar + @"default.tkf";

            Runner.DebugMessage("Debug.Info.Trackfile", "Trackfile Path: " + TrackfilePath);
            if (System.IO.File.Exists(TrackfilePath) == true)
            {
                SimpleMesh.Service.Runner.Network.Read(TrackfilePath);
            }
            else
            {
                Dictionary <string, string> Hints = SimpleMesh.Service.Runner.NetworkSpecCallback();
                string type;
                string trackfilelocation;
                if (Hints.TryGetValue("trackfilelocation", out trackfilelocation) == false)
                {
                    return;
                }
                if (Hints.TryGetValue("type", out type) == true)
                {
                    switch (type)
                    {
                    case "create":
                        string name;
                        if (Hints.TryGetValue("name", out name) == true)
                        {
                            SimpleMesh.Service.Runner.Network.Name = name;
                        }
                        else
                        {
                            SimpleMesh.Service.Runner.Network.Name = "Undefined";
                        }
                        string keylength;
                        Key    scratch = new Key();
                        if (Hints.TryGetValue("enrollkeylength", out keylength) == true)
                        {
                            scratch.Generate("RSA", keylength);
                        }
                        else
                        {
                            scratch.Generate("RSA");
                        }
                        Auth temp = new Auth();
                        temp.UUID = new UUID();
                        temp.Key  = scratch;
                        SimpleMesh.Service.Runner.Network.Enrollment.Add(temp.UUID.ToString(), temp);
                        break;

                    case "enroll":
                        Network.ReadOnce(trackfilelocation);
                        break;
                    }
                    try
                    {
                        Network.WriteOnce(trackfilelocation);
                    }
                    catch
                    {
                    }
                }
            }
            SimpleMesh.Service.Runner.Network.Write(TrackfilePath);

            /*
             * string inputstring = "Test";
             * byte[] ciphertext;
             * byte[] plaintext;
             * Network.Node.Key.Encrypt(true, UTF8Encoding.UTF8.GetBytes(inputstring), out ciphertext);
             * Network.Node.Key.Decrypt(true, ciphertext, out plaintext);
             * Console.WriteLine("output string = " + UTF8Encoding.UTF8.GetString(plaintext));
             * Console.ReadLine();
             */
            Runner.Native = true;
            Network.Start();
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: tlorentzen/P2
        static void Main()
        {
            bool   running  = true;
            bool   firstRun = true;
            MyForm torPdos  = new MyForm();

            //If the ''Path'' variable is not set, the GUI is run to set this up.
            if (string.IsNullOrEmpty(DiskHelper.GetRegistryValue("Path")))
            {
                Application.Run(torPdos);
            }
            //If the ''Path'' variable is set, but the userdata file does not exist,
            //the GUI is run to create this.
            else if (File.Exists(DiskHelper.GetRegistryValue("Path") + @".hidden\userdata") == false)
            {
                Application.Run(torPdos);
            }

            //Gets the local IP and the path to the users TorPDos-folder.
            string ownIp = NetworkHelper.GetLocalIpAddress();
            string path  = (DiskHelper.GetRegistryValue("Path"));

            //Starts the communication with the user, and ensures that
            //the user logs in.
            DiskHelper.ConsoleWrite("Welcome to TorPdos!");
            Console.WriteLine(@"Please login by typing: login [PASSWORD] or gui");
            while (running)
            {
                string console = Console.ReadLine();
                if (console != null)
                {
                    string[] param = console.Split(' ');
                    //Close program
                    if (console.Equals("quit") || console.Equals("q"))
                    {
                        Console.WriteLine(@"Quitting...");
                        _idx.Save();
                        _idx.Stop();
                        _p2P.SavePeer();
                        _p2P.Stop();
                        running = false;
                        Console.WriteLine(" \n Press any button to quit!");
                    }
                    else
                    {
                        //Handles the login of the user through the console.
                        while (IdHandler.GetUuid() == null)
                        {
                            if (console.StartsWith("login") && param.Length == 2)
                            {
                                if (IdHandler.GetUuid(param[1]) == "Invalid Password")
                                {
                                    Console.WriteLine();
                                    Console.WriteLine(@"Invalid password, try again");
                                    Console.WriteLine(@"Please login by typing: login [PASSWORD] or gui");
                                    console = Console.ReadLine();
                                    if (console != null)
                                    {
                                        param = console.Split(' ');
                                    }
                                }

                                //Gives the opportunity to open the GUI for login.
                            }
                            else if (console.Equals("gui"))
                            {
                                Application.Run(torPdos);
                            }
                            else
                            {
                                Console.WriteLine();
                                Console.WriteLine(@"Error! Try again");
                                Console.WriteLine(@"Please login by typing: login [PASSWORD] or gui");
                                console = Console.ReadLine();
                                param   = console.Split(' ');
                            }
                        }

                        //Handles the creation or loading of all the necessary
                        //files and directories.
                        if (firstRun)
                        {
                            // Load Index
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }

                            _idx         = new Index(path);
                            torPdos._idx = _idx;

                            // Prepare P2PNetwork
                            try{
                                _p2P = new Network(25565, _idx, path);
                                _p2P.Start();
                                torPdos._p2P = _p2P;
                            }
                            catch (SocketException) {
                                Application.Run(torPdos);
                            }

                            _idx.Load();
                            _idx.FileAdded   += Idx_FileAdded;
                            _idx.FileChanged += Idx_FileChanged;
                            _idx.FileDeleted += Idx_FileDeleted;
                            _idx.FileMissing += Idx_FileMissing;

                            if (!_idx.Load())
                            {
                                _idx.BuildIndex();
                            }

                            _idx.Start();

                            Console.WriteLine(@"Integrity check initialized...");
                            _idx.MakeIntegrityCheck();
                            Console.WriteLine(@"Integrity check finished!");

                            Console.WriteLine(@"Local: " + ownIp);
                            Console.WriteLine(@"Free space on C: " + DiskHelper.GetTotalAvailableSpace("C:\\"));
                            Console.WriteLine(@"UUID: " + IdHandler.GetUuid());
                            firstRun = false;

                            //Restart loop to take input
                            continue;
                        }

                        // Handle input
                        if (console.StartsWith("add") && param.Length == 3)
                        {
                            _p2P.AddPeer(param[1].Trim(), param[2].Trim());
                        }
                        else if (console.Equals("reindex"))
                        {
                            _idx.ReIndex();
                        }
                        else if (console.Equals("gui"))
                        {
                            MyForm torPdos2 = new MyForm();
                            Application.Run(torPdos2);
                        }
                        else if (console.Equals("status"))
                        {
                            _idx.Status();
                        }
                        else if (console.Equals("idxsave"))
                        {
                            _idx.Save();
                        }
                        else if (console.Equals("peersave"))
                        {
                            _p2P.SavePeer();
                        }
                        else if (console.Equals("ping"))
                        {
                            _p2P.Ping();
                        }
                        else if (console.Equals("integrity"))
                        {
                            _idx.MakeIntegrityCheck();
                        }
                        else if (console.Equals("list"))
                        {
                            List <Peer> peers = _p2P.GetPeerList();

                            Console.WriteLine();
                            Console.WriteLine(@"### Your Peerlist contains ###");
                            if (peers.Count > 0)
                            {
                                foreach (Peer peer in peers)
                                {
                                    RankingHandler rankingHandler = new RankingHandler();
                                    rankingHandler.GetRank(peer);
                                    Console.WriteLine(@"(R:" + peer.Rating + @") " + peer.GetUuid() + @" - " +
                                                      peer.GetIp() + @" - " +
                                                      (peer.IsOnline() ? "Online" : "Offline"));
                                    Console.WriteLine(@"disk: " + Convert.ToInt32((peer.diskSpace / 1e+9)) +
                                                      @"GB | avgPing: " + peer.GetAverageLatency() + "\n");
                                }
                            }
                            else
                            {
                                Console.WriteLine(@"The list is empty...");
                            }

                            Console.WriteLine();
                        }
                        else if (console.Trim().Equals(""))
                        {
                        }
                        else
                        {
                            Console.WriteLine(@"Unknown command");
                        }
                    }
                }
            }

            Console.ReadKey();
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: d3v1l401/NordicBlockchain
        static void Main(string[] args) {
            //if (!ConfigurationHelper.Import("NordicConf.json")) {
            //    Console.WriteLine("Configuration import failed, using default values and writing configuration file \"NordicConf.json\".");
            //    ConfigurationHelper.Export("NordicConf.json");
            //}
            var _hardcodedChallenge = "miner_test";

            ServerAuthenticator.Initialize("pubKey.pem", "privKey.pem", "");
            ClientAuthenticator.Initialize("pubKey.pem", "privKey.pem", "");
            ClientAuthenticator.Add(_hardcodedChallenge, File.ReadAllText("miner_pubKey.pem"));

            Console.WriteLine("---------- BLOCKCHAIN ----------\n");

            Blockchain _nbStructure = new Blockchain();
            var gBlock = _nbStructure.GetBlock(0);

            Console.WriteLine(gBlock.ToString());
            //_nbStructure.Add(new BlockData("", IOperation.OPERATION_TYPE.SECURITY_BC_COMPROMISE_NOTICE, "Lol"));
            
            Console.WriteLine(_nbStructure.LastBlock().ToString());

            Console.WriteLine("Fork Validity: " + _nbStructure.Validity());

            Console.WriteLine("\n---------- NODE VAULT ----------\n");

            Console.WriteLine("Importing current node credentials...");
            TrustVault _vault = new TrustVault(File.ReadAllText("privKey.pem"), File.ReadAllText("pubKey.pem"));
            Console.WriteLine(_vault.ToJson());

            Console.WriteLine("\n----------- NETWORK ------------\n");
            Console.WriteLine("Setting up network for 127.0.0.1:1337 (LOCAL ONLY BINDING!).");

            Network _net = new Network("127.0.0.1", 1337);
            if (_net.Setup()) {
                _net.Start();
                Console.WriteLine("Network started on 127.0.0.1:1337.");
                
            } else
                Console.WriteLine("Network setup failed.");

            Console.WriteLine("\n---------- SHAREDCACHE ---------\n");

            Console.WriteLine("Building Shared Node Cache for online nodes...");
            Console.WriteLine("\tOnly 1 node online.");
            SharedCache _cache = new SharedCache();
            _cache.AddAddress("127.0.0.1");
            Console.WriteLine(_cache.ToJson());

            Console.WriteLine("\n-------------- RSA -------------\n");

            RSA _rsa = new RSA(File.ReadAllText("privKey.pem"), File.ReadAllText("pubKey.pem"));
            var _signature = _rsa.Sign("makeAwish");
            var _verify = _rsa.VerifySignature("makeAwish", _signature, null);
            var _verify2 = _rsa.VerifySignature("makeAwisha", _signature, null);

            Console.WriteLine("Signed: " + _signature + "\n\n");
            Console.WriteLine("Verify: " + _verify);
            Console.WriteLine("Verify fake one: " + _verify2);

            Client cl = new Client();
            cl.Connect("ws://127.0.0.1:1337/blt");
            bool _sent = false;
            while (true) {
                if (WaitOrBreak(_nbStructure.LastBlock())) break;

                if (!_nbStructure.Validity()) {
                    Console.WriteLine("Blockchain violation detected!");

                    
                    break;
                }
                //try {
                //    if (!_sent) {
                //        IOperation _op = new OperationTransaction("d3vil401", "13.2", "none");
                //        ClmManager _clm = new ClmManager(_op);
                //        var _buffer = _clm.GetBuffer().Result.ToBase64();
                //
                //        cl.Send("ws://127.0.0.1:1337/blt", _buffer);
                //        _sent = true;
                //    }
                //
                //} catch (Exception ex) {
                //    Console.WriteLine(ex.Message);
                //}
            }
        }
コード例 #20
0
        public void Comprassion(ref double timeMain, ref double timeBg)
        {
            double[][] arr1  = new double[16][];
            double[][] arr2  = new double[16][];
            double[][] arr3  = new double[16][];
            double[][] arr4  = new double[16][];
            double[][] arr5  = new double[16][];
            double[][] arr6  = new double[16][];
            double[][] arr7  = new double[16][];
            double[][] arr8  = new double[16][];
            double[][] arr9  = new double[16][];
            double[][] arr10 = new double[16][];
            double[][] arr11 = new double[16][];
            double[][] arr12 = new double[16][];
            double[][] arr13 = new double[16][];
            double[][] arr14 = new double[16][];
            double[][] arr15 = new double[16][];
            double[][] arr16 = new double[16][];
            for (int x = 0; x < 16; x++)
            {
                arr1[x]  = new double[16];
                arr2[x]  = new double[16];
                arr3[x]  = new double[16];
                arr4[x]  = new double[16];
                arr5[x]  = new double[16];
                arr6[x]  = new double[16];
                arr7[x]  = new double[16];
                arr8[x]  = new double[16];
                arr9[x]  = new double[16];
                arr10[x] = new double[16];
                arr11[x] = new double[16];
                arr12[x] = new double[16];
                arr13[x] = new double[16];
                arr14[x] = new double[16];
                arr15[x] = new double[16];
                arr16[x] = new double[16];
            }

            var time1 = System.Diagnostics.Stopwatch.StartNew();

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, MainR, i * 64, j * 64);
                    Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref MainR, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, MainG, i * 64, j * 64);
                    Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref MainG, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, MainB, i * 64, j * 64);
                    Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref MainB, i * 64, j * 64);
                }
            }
            time1.Stop();
            timeMain = time1.ElapsedMilliseconds;

            var time2 = System.Diagnostics.Stopwatch.StartNew();

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg1R, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg1R, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg1G, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg1G, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg1B, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg1B, i * 64, j * 64);
                }
            }


            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg2R, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg2R, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg2G, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg2G, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg2B, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg2B, i * 64, j * 64);
                }
            }


            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg3R, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg3R, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg3G, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg3G, i * 64, j * 64);
                }
            }

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    tmp1(ref arr1, ref arr2, ref arr3, ref arr4, ref arr5, ref arr6, ref arr7, ref arr8,
                         ref arr9, ref arr10, ref arr11, ref arr12, ref arr13, ref arr14, ref arr15, ref arr16, Bg3B, i * 64, j * 64);
                    Neural2.Network.Start(ref arr1, ref arr2, ref arr3, ref arr4);
                    Neural2.Network.Start(ref arr5, ref arr6, ref arr7, ref arr8);
                    Neural2.Network.Start(ref arr9, ref arr10, ref arr11, ref arr12);
                    Neural2.Network.Start(ref arr13, ref arr14, ref arr15, ref arr16);
                    tmp2(arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10,
                         arr11, arr12, arr13, arr14, arr15, arr16, ref Bg3B, i * 64, j * 64);
                }
            }
            time2.Stop();
            timeBg = time2.ElapsedMilliseconds / 3;
        }
コード例 #21
0
 public void Restart()
 {
     Network.Start();
 }
コード例 #22
0
        static void Main(string[] args)
        {
            #region Configs.

            BlockchainStorageManagerParameters managerParameters = new BlockchainStorageManagerParameters()
            {
                BlocksInUnit = 2
            };
            UnitRepositoryParameters repositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain")
            };
            WalletManagerParameters walletManagerParameters = new WalletManagerParameters()
            {
                WalletDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wallets")
            };

            NetworkParameters networkParametersFirst = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), AddressBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8900,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            BasicMiningFactoryParameters parameters = new BasicMiningFactoryParameters()
            {
                HashLeastUpFactor = 1.25,
                HashMostUpFactor  = 1.75,

                HashLeastDownFactor = 0.25,
                HashMostDownFactor  = 0.75,

                DifficultyLeastUpFactor = 1.25,
                DifficultyMostUpFactor  = 1.75,

                DifficultyLeastDownFactor = 0.25,
                DifficultyMostDownFactor  = 0.75,

                MinDifficulty = Difficulty
            };

            JsonSerializer jsonSerializer = new JsonSerializer()
            {
                Formatting = Formatting.Indented
            };

            using (Stream jsonFile = File.Open(MiningConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, parameters);

            using (Stream jsonFile = File.Open(ManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, managerParameters);

            using (Stream jsonFile = File.Open(RepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, repositoryParameters);

            using (Stream jsonFile = File.Open(WalletManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, walletManagerParameters);

            using (Stream jsonFile = File.Open(NetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersFirst);

            JsonBasicMiningFactoryConfig       miningConfig        = new JsonBasicMiningFactoryConfig(MiningConfigPath);
            JsonBlockchainStorageManagerConfig managerConfig       = new JsonBlockchainStorageManagerConfig(ManagerConfigPath);
            JsonUnitRepositoryConfig           repositoryConfig    = new JsonUnitRepositoryConfig(RepositoryConfigPath);
            JsonWalletManagerConfig            walletManagerConfig = new JsonWalletManagerConfig(WalletManagerConfigPath);
            JsonNetworkConfig networkConfig = new JsonNetworkConfig(NetworkConfigPath);

            #endregion

            #region Directory remove.

            removeDirectory(repositoryConfig.DirectoryPath);
            removeDirectory(SecondPeerRepositoryPath);
            //removeDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Directory creation.

            Directory.CreateDirectory(repositoryParameters.DirectoryPath);
            Directory.CreateDirectory(Path.Combine(repositoryConfig.DirectoryPath, "addressers"));
            Directory.CreateDirectory(Path.Combine(repositoryConfig.DirectoryPath, "units"));
            //Directory.CreateDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Initial units.

            // Addressers.
            string addresser0Path = Path.Combine(repositoryParameters.DirectoryPath, "addressers", "addresser0.addr");

            File.Create(addresser0Path).Close();

            // Units.
            string unit0Path = Path.Combine(repositoryParameters.DirectoryPath, "units", "unit0.unit");

            File.Create(unit0Path).Close();

            BlockchainUnit unit0 = new BlockchainUnit(unit0Path, new AddressStorage(addresser0Path));

            #endregion

            IMiningFactory    miningFactory          = new BasicMiningFactory(miningConfig);
            IHashFactory      hashFactory            = miningFactory.GetMiningHashFactoryById(3);
            IHashFactory      transactionHashFactory = new TransactionHashFactory();
            ISignatureFactory signatureFactory       = new ECDSAFactory();
            IWalletManager    walletManager          = new WalletManager(walletManagerConfig, signatureFactory, transactionHashFactory);

            Wallet wallet = walletManager.GetWallets().First();

            #region Initial transactions.

            LinkedList <Transaction> firstInitialList  = new LinkedList <Transaction>();
            LinkedList <Transaction> secondInitialList = new LinkedList <Transaction>();

            Transaction firstInitialTransaction  = new Transaction(wallet.PublicKey, wallet.PublicKey, 32, transactionHashFactory);
            Transaction secondInitialTransaction = new Transaction(wallet.PublicKey, wallet.PublicKey, 19, transactionHashFactory);
            Transaction thirdInitialTransaction  = new Transaction(wallet.PublicKey, wallet.PublicKey, 32, transactionHashFactory);
            Transaction fourthInitialTransaction = new Transaction(wallet.PublicKey, wallet.PublicKey, 19, transactionHashFactory);

            firstInitialTransaction.SignTransaction(wallet.Signer);
            secondInitialTransaction.SignTransaction(wallet.Signer);
            thirdInitialTransaction.SignTransaction(wallet.Signer);
            fourthInitialTransaction.SignTransaction(wallet.Signer);

            firstInitialList.AddLast(firstInitialTransaction);
            firstInitialList.AddLast(secondInitialTransaction);
            secondInitialList.AddLast(thirdInitialTransaction);
            secondInitialList.AddLast(fourthInitialTransaction);

            #endregion

            #region Initial blocks.

            IHashFactory miningHashFactory = miningFactory.GetMiningHashFactoryById(3);
            IMiner       miner             = new BasicMiner(3, Difficulty, miningHashFactory);

            Block firstInitialBlock = new Block(wallet.PublicKey, new byte[hashFactory.GetDigest().HashLength], firstInitialList, hashFactory);

            miner.MineBlock(firstInitialBlock);
            firstInitialBlock.SignBlock(wallet.Signer);

            Block secondInitialBlock = new Block(wallet.PublicKey, firstInitialBlock.Hash, secondInitialList, hashFactory);

            miner.MineBlock(secondInitialBlock);
            secondInitialBlock.SignBlock(wallet.Signer);

            unit0.AddBlock(firstInitialBlock);
            unit0.AddBlock(secondInitialBlock);

            unit0.Dispose();

            #endregion

            Copy(repositoryConfig.DirectoryPath, SecondPeerRepositoryPath);

            UnitRepository           repository     = new UnitRepository(repositoryConfig);
            BlockchainStorageManager storageManager = new BlockchainStorageManager(managerConfig, repository);
            Blockchain blockchain = new Blockchain(wallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, storageManager);

            wallet.Blockchain = blockchain;

            #region Network.

            AddressBook  addressBook = new AddressBook(AddressBookPath);
            IBroadcaster network     = new Network(blockchain, addressBook, networkConfig, wallet.Signer);

            blockchain.NetworkBroadcaster = network;

            network.Start();

            #endregion

            Console.WriteLine("First");
            Console.WriteLine("0 - send transaction;\n1 - mine new block;\n2 - validate blockchain;\n3 - count your balance;\n4 - quit");

            string input;

            do
            {
                input = Console.ReadLine();

                switch (input)
                {
                case "0":
                    wallet.SendTokens(8, addressBook.First().Key.PublicKey);

                    break;

                case "1":
                    blockchain.ProcessPendingTransactions();

                    break;

                case "2":
                    Console.WriteLine(blockchain.IsValid ? "Blockchain is valid" : "Blockchain is invalid");

                    break;

                case "3":
                    Console.WriteLine($"Current balance for testing wallet: " + blockchain.CountBalanceForWallet(wallet.PublicKey));

                    break;

                case "4":
                    Console.WriteLine("Bye!");

                    break;

                default:
                    Console.WriteLine("Wrong input!");

                    break;
                }
            }while (input != "4");

            network.Stop();
        }
コード例 #23
0
ファイル: Main.cs プロジェクト: 11dot001001/GameClient
 public static void Start()
 {
     DataModel.Reset();
     Network.Start();
 }
コード例 #24
0
ファイル: Program.cs プロジェクト: zergon321/SimpleCoin
        static void Main(string[] args)
        {
            #region Configs.

            BlockchainStorageManagerParameters managerParameters = new BlockchainStorageManagerParameters()
            {
                BlocksInUnit = 2
            };
            UnitRepositoryParameters repositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain")
            };
            WalletManagerParameters walletManagerParameters = new WalletManagerParameters()
            {
                WalletDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wallets")
            };

            NetworkParameters networkParametersFirst = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), AddressBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8910,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            BasicMiningFactoryParameters parameters = new BasicMiningFactoryParameters()
            {
                HashLeastUpFactor = 1.25,
                HashMostUpFactor  = 1.75,

                HashLeastDownFactor = 0.25,
                HashMostDownFactor  = 0.75,

                DifficultyLeastUpFactor = 1.25,
                DifficultyMostUpFactor  = 1.75,

                DifficultyLeastDownFactor = 0.25,
                DifficultyMostDownFactor  = 0.75,

                MinDifficulty = Difficulty
            };

            JsonSerializer jsonSerializer = new JsonSerializer()
            {
                Formatting = Formatting.Indented
            };

            using (Stream jsonFile = File.Open(MiningConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, parameters);

            using (Stream jsonFile = File.Open(ManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, managerParameters);

            using (Stream jsonFile = File.Open(RepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, repositoryParameters);

            using (Stream jsonFile = File.Open(WalletManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, walletManagerParameters);

            using (Stream jsonFile = File.Open(NetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersFirst);

            JsonBasicMiningFactoryConfig       miningConfig        = new JsonBasicMiningFactoryConfig(MiningConfigPath);
            JsonBlockchainStorageManagerConfig managerConfig       = new JsonBlockchainStorageManagerConfig(ManagerConfigPath);
            JsonUnitRepositoryConfig           repositoryConfig    = new JsonUnitRepositoryConfig(RepositoryConfigPath);
            JsonWalletManagerConfig            walletManagerConfig = new JsonWalletManagerConfig(WalletManagerConfigPath);
            JsonNetworkConfig networkConfig = new JsonNetworkConfig(NetworkConfigPath);

            #endregion

            IMiningFactory    miningFactory          = new BasicMiningFactory(miningConfig);
            IHashFactory      hashFactory            = miningFactory.GetMiningHashFactoryById(3);
            IHashFactory      transactionHashFactory = new TransactionHashFactory();
            ISignatureFactory signatureFactory       = new ECDSAFactory();
            IWalletManager    walletManager          = new WalletManager(walletManagerConfig, signatureFactory, transactionHashFactory);

            Wallet                   wallet         = walletManager.GetWallets().First();
            UnitRepository           repository     = new UnitRepository(repositoryConfig);
            BlockchainStorageManager storageManager = new BlockchainStorageManager(managerConfig, repository);
            Blockchain               blockchain     = new Blockchain(wallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, storageManager);

            wallet.Blockchain = blockchain;

            #region Network.

            AddressBook  addressBook = new AddressBook(AddressBookPath);
            IBroadcaster network     = new Network(blockchain, addressBook, networkConfig, wallet.Signer);

            blockchain.NetworkBroadcaster = network;

            network.Start();

            #endregion

            Console.WriteLine("Second");
            Console.WriteLine("0 - send transaction;\n1 - mine new block;\n2 - validate blockchain;\n3 - count your balance;\n4 - quit\n5 - create new wallet");

            string input;

            do
            {
                input = Console.ReadLine();

                switch (input)
                {
                case "0":
                    wallet.SendTokens(8, addressBook.First().Key.PublicKey);

                    break;

                case "1":
                    blockchain.ProcessPendingTransactions();

                    break;

                case "2":
                    Console.WriteLine(blockchain.IsValid ? "Blockchain is valid" : "Blockchain is invalid");

                    break;

                case "3":
                    Console.WriteLine(blockchain.CountBalanceForWallet(wallet.PublicKey));

                    break;

                case "4":
                    Console.WriteLine("Bye!");

                    break;

                case "5":
                    Wallet newOne = walletManager.AddNewWallet();

                    Console.WriteLine("New wallet created!");
                    Console.WriteLine($"Public key: {hashFactory.GetByteConverter().ConvertToString(newOne.PublicKey)}");

                    break;

                default:
                    Console.WriteLine("Wrong input!");

                    break;
                }
            }while (input != "4");

            network.Stop();
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: zergon321/SimpleCoin
        static void Main(string[] args)
        {
            #region Configs creation.

            BlockchainStorageManagerParameters managerParameters = new BlockchainStorageManagerParameters()
            {
                BlocksInUnit = 2
            };
            UnitRepositoryParameters firstRepositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain0")
            };
            UnitRepositoryParameters secondRepositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain1")
            };
            WalletManagerParameters walletManagerParameters = new WalletManagerParameters()
            {
                WalletDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wallets")
            };

            NetworkParameters networkParametersFirst = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), FirstBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8900,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            NetworkParameters networkParametersSecond = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), SecondBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8910,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            BasicMiningFactoryParameters parameters = new BasicMiningFactoryParameters()
            {
                HashLeastUpFactor = 1.25,
                HashMostUpFactor  = 1.75,

                HashLeastDownFactor = 0.25,
                HashMostDownFactor  = 0.75,

                DifficultyLeastUpFactor = 1.25,
                DifficultyMostUpFactor  = 1.75,

                DifficultyLeastDownFactor = 0.25,
                DifficultyMostDownFactor  = 0.75,

                MinDifficulty = Difficulty
            };

            JsonSerializer jsonSerializer = new JsonSerializer()
            {
                Formatting = Formatting.Indented
            };

            using (Stream jsonFile = File.Open(MiningConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, parameters);

            using (Stream jsonFile = File.Open(ManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, managerParameters);

            using (Stream jsonFile = File.Open(FirstRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, firstRepositoryParameters);

            using (Stream jsonFile = File.Open(SecondRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, secondRepositoryParameters);

            using (Stream jsonFile = File.Open(WalletManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, walletManagerParameters);

            using (Stream jsonFile = File.Open(FirstNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersFirst);

            using (Stream jsonFile = File.Open(SecondNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersSecond);

            JsonBasicMiningFactoryConfig       miningConfig           = new JsonBasicMiningFactoryConfig(MiningConfigPath);
            JsonBlockchainStorageManagerConfig managerConfig          = new JsonBlockchainStorageManagerConfig(ManagerConfigPath);
            JsonUnitRepositoryConfig           firstRepositoryConfig  = new JsonUnitRepositoryConfig(FirstRepositoryConfigPath);
            JsonUnitRepositoryConfig           secondRepositoryConfig = new JsonUnitRepositoryConfig(SecondRepositoryConfigPath);
            JsonWalletManagerConfig            walletManagerConfig    = new JsonWalletManagerConfig(WalletManagerConfigPath);
            JsonNetworkConfig firstNetworkConfig  = new JsonNetworkConfig(FirstNetworkConfigPath);
            JsonNetworkConfig secondNetworkConfig = new JsonNetworkConfig(SecondNetworkConfigPath);

            #endregion

            #region Directory remove.

            removeDirectory(firstRepositoryConfig.DirectoryPath);
            removeDirectory(secondRepositoryConfig.DirectoryPath);
            removeDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Directory creation.

            Directory.CreateDirectory(firstRepositoryParameters.DirectoryPath);
            Directory.CreateDirectory(secondRepositoryParameters.DirectoryPath);
            Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "addressers"));
            Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "units"));
            Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "addressers"));
            Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "units"));
            Directory.CreateDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Initial units.

            // Addressers.
            string firstAddresser0Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr");
            string secondAddresser0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr");

#if (CREATE_EXTRA_FILE)
            string firstAddresser1Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr");
            string secondAddresser1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr");
#endif

            File.Create(firstAddresser0Path).Close();
            File.Create(secondAddresser0Path).Close();

#if (CREATE_EXTRA_FILE)
            File.Create(firstAddresser1Path).Close();
            File.Create(secondAddresser1Path).Close();
#endif

            // Units.
            string firstUnit0Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit0.unit");
            string secondUnit0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit0.unit");

#if (CREATE_EXTRA_FILE)
            string firstUnit1Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit1.unit");
            string secondUnit1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit1.unit");
#endif

            File.Create(firstUnit0Path).Close();
            File.Create(secondUnit0Path).Close();

#if (CREATE_EXTRA_FILE)
            File.Create(firstUnit1Path).Close();
            File.Create(secondUnit1Path).Close();
#endif

            BlockchainUnit firstUnit0  = new BlockchainUnit(firstUnit0Path, new AddressStorage(firstAddresser0Path));
            BlockchainUnit secondUnit0 = new BlockchainUnit(secondUnit0Path, new AddressStorage(secondAddresser0Path));

            #endregion

            IMiningFactory    miningFactory          = new BasicMiningFactory(miningConfig);
            IHashFactory      hashFactory            = miningFactory.GetMiningHashFactoryById(3);
            IHashFactory      transactionHashFactory = new TransactionHashFactory();
            ISignatureFactory signatureFactory       = new ECDSAFactory();
            IWalletManager    walletManager          = new WalletManager(walletManagerConfig, signatureFactory, transactionHashFactory);

            Wallet firstWallet = walletManager.AddNewWallet();

            #region Initial transactions.

            LinkedList <Transaction> firstInitialList  = new LinkedList <Transaction>();
            LinkedList <Transaction> secondInitialList = new LinkedList <Transaction>();

            Transaction firstInitialTransaction  = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory);
            Transaction secondInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory);
            Transaction thirdInitialTransaction  = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory);
            Transaction fourthInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory);

            firstInitialTransaction.SignTransaction(firstWallet.Signer);
            secondInitialTransaction.SignTransaction(firstWallet.Signer);
            thirdInitialTransaction.SignTransaction(firstWallet.Signer);
            fourthInitialTransaction.SignTransaction(firstWallet.Signer);

            firstInitialList.AddLast(firstInitialTransaction);
            firstInitialList.AddLast(secondInitialTransaction);
            secondInitialList.AddLast(thirdInitialTransaction);
            secondInitialList.AddLast(fourthInitialTransaction);

            #endregion

            #region Initial blocks.

            IHashFactory miningHashFactory = miningFactory.GetMiningHashFactoryById(3);
            IMiner       miner             = new BasicMiner(3, Difficulty, miningHashFactory);

            Block firstInitialBlock = new Block(firstWallet.PublicKey, new byte[hashFactory.GetDigest().HashLength], firstInitialList, hashFactory);

            miner.MineBlock(firstInitialBlock);
            firstInitialBlock.SignBlock(firstWallet.Signer);

            Block secondInitialBlock = new Block(firstWallet.PublicKey, firstInitialBlock.Hash, secondInitialList, hashFactory);

            miner.MineBlock(secondInitialBlock);
            secondInitialBlock.SignBlock(firstWallet.Signer);

            firstUnit0.AddBlock(firstInitialBlock);
            firstUnit0.AddBlock(secondInitialBlock);
            secondUnit0.AddBlock(firstInitialBlock);
            secondUnit0.AddBlock(secondInitialBlock);

            firstUnit0.Dispose();
            secondUnit0.Dispose();

            #endregion

            UnitRepository firstRepository  = new UnitRepository(firstRepositoryConfig);
            UnitRepository secondRepository = new UnitRepository(secondRepositoryConfig);

            BlockchainStorageManager firstManager  = new BlockchainStorageManager(managerConfig, firstRepository);
            BlockchainStorageManager secondManager = new BlockchainStorageManager(managerConfig, secondRepository);

            Blockchain firstBlockchain  = new Blockchain(firstWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, firstManager);
            Wallet     secondWallet     = walletManager.AddNewWallet();
            Blockchain secondBlockchain = new Blockchain(secondWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, secondManager);

            #region Address books creation.

            File.Create(FirstBookPath).Close();
            File.Create(SecondBookPath).Close();

            PeerAddress firstPeer  = new PeerAddress(firstWallet.PublicKey);
            PeerAddress secondPeer = new PeerAddress(secondWallet.PublicKey);

            AddressBook firstPeerAddressBook  = new AddressBook(FirstBookPath);
            AddressBook secondPeerAddressBook = new AddressBook(SecondBookPath);

            firstPeerAddressBook.Add(secondPeer, "ws://" + secondNetworkConfig.PeerHostName + $":{secondNetworkConfig.PeerPort}/simplecoin");
            secondPeerAddressBook.Add(firstPeer, "ws://" + firstNetworkConfig.PeerHostName + $":{firstNetworkConfig.PeerPort}/simplecoin");

            firstPeerAddressBook.SaveOnDrive();
            secondPeerAddressBook.SaveOnDrive();

            #endregion

            #region Network.

            IBroadcaster firstNetwork = new Network(firstBlockchain, firstPeerAddressBook, firstNetworkConfig, firstWallet.Signer);

            IBroadcaster secondNetwork = new Network(secondBlockchain, secondPeerAddressBook, secondNetworkConfig, secondWallet.Signer);

            firstBlockchain.NetworkBroadcaster  = firstNetwork;
            secondBlockchain.NetworkBroadcaster = secondNetwork;

            firstNetwork.Start();
            secondNetwork.Start();

            #endregion

            firstWallet.Blockchain  = firstBlockchain;
            secondWallet.Blockchain = secondBlockchain;

            firstWallet.SendTokens(16, secondWallet.PublicKey);
            firstWallet.SendTokens(8, secondWallet.PublicKey);

            secondBlockchain.ProcessPendingTransactions();

            secondWallet.SendTokens(8, firstWallet.PublicKey);
            firstBlockchain.ProcessPendingTransactions();

            Console.WriteLine("First blockchain:\n");

            foreach (Block block in firstBlockchain)
            {
                Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented));
                Console.WriteLine();
            }

            Console.WriteLine("--------------------------------------------------------------------------------------");

            Console.WriteLine("Second blockchain:\n");

            foreach (Block block in secondBlockchain)
            {
                Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented));
                Console.WriteLine();
            }

            Console.WriteLine("}\n");

            Console.WriteLine(firstBlockchain.IsValid ? "First blockchain is valid" : "First blockchain is invalid");
            Console.WriteLine(firstBlockchain.IsValid ? "Second blockchain is valid" : "Second blockchain is invalid");

            Console.WriteLine($"Cryptocurrency ownership for first wallet: {firstBlockchain.CountBalanceForWallet(firstWallet.PublicKey)}");
            Console.WriteLine($"Cryptocurrency ownership for second wallet: {firstBlockchain.CountBalanceForWallet(secondWallet.PublicKey)}");
        }