예제 #1
0
        public SimpleWallet(string networkId, string name, string password)
        {
            var path    = Wallet.GetFullFolderName(networkId, "wallets");
            var storage = new SecuredWalletStore(path);

            LyraWallet = Wallet.Open(storage, name, password);
        }
예제 #2
0
        public string ImportWallet(string name, string password)
        {
            string lyra_folder = Wallet.GetFullFolderName(_prog.NetworkId, "wallets");
            var    storage     = new SecuredWalletStore(lyra_folder);
            var    wallet      = Wallet.Open(storage, name, password);

            return(wallet.PrivateKey);
        }
예제 #3
0
        private async Task <Wallet> GetGenesisWalletAsync()
        {
            string lyra_folder = Wallet.GetFullFolderName(networkId, "wallets");
            var    storage     = new SecuredWalletStore(lyra_folder);
            var    wallet      = Wallet.Open(storage, "vault", "");

            client = LyraRestClient.Create(networkId, "windows", "unit test", "1.0");
            await wallet.SyncAsync(client);

            Assert.IsTrue(wallet.BaseBalance > 1000000m);
            return(wallet);
        }
예제 #4
0
        public void RestoreWallet(string networkId, string name, string password, string publicKey)
        {
            var path = Wallet.GetFullFolderName(networkId, "wallets");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var storage = new SecuredWalletStore(path);

            Wallet.Create(storage, name, password, networkId, publicKey);
        }
예제 #5
0
        private static IAccountDatabase GetStorage(string path)
        {
            IAccountDatabase store;

            if (path == null)
            {
                store = new AccountInMemoryStorage();
            }
            else
            {
                store = new SecuredWalletStore(path);
            }

            return(store);
        }
예제 #6
0
        private void GenerateWallet(string path, string networkId, string walletName, string password)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var secureFile = new SecuredWalletStore(path);

            if (secureFile.Exists(walletName))
            {
                Console.WriteLine($"Wallet named {walletName} already exists.");
                return;
            }

            Console.WriteLine($"Creating wallet for {networkId}.");

            var walletPass = password;

            if (string.IsNullOrEmpty(password))
            {
                var password1 = Prompt.GetPassword("Please specify a strong password for your wallet:",
                                                   promptColor: ConsoleColor.Red,
                                                   promptBgColor: ConsoleColor.Black);

                var password2 = Prompt.GetPassword("Repeat your password:"******"Passwords not match.");
                    return;
                }

                walletPass = password1;
            }


            (var privateKey, var publicKey) = Signatures.GenerateWallet();

            Console.WriteLine($"The new wallet {walletName} for {networkId} was created.");
            //Console.WriteLine($"Private Key: {privateKey}");
            Console.WriteLine($"Account ID: {publicKey}");

            secureFile.Create(walletName, walletPass, networkId, privateKey, publicKey, "");
            Console.WriteLine($"Wallet saved to: {path}{walletName}");
        }
        public async Task OpenAsync()
        {
            Console.WriteLine($"Opening wallet for {_network}");

            string lyrawalletfolder = Wallet.GetFullFolderName(_network, "wallets");
            var    walletStore      = new SecuredWalletStore(lyrawalletfolder);

            incWallet = Wallet.Open(walletStore, _name, _password);
            var client     = LyraRestClient.Create(_network, "", "", "");
            var syncResult = await incWallet.SyncAsync(client);

            if (syncResult != Lyra.Core.Blocks.APIResultCodes.Success)
            {
                Console.WriteLine("Can't sync wallet!");
                return;
            }

            Console.WriteLine($"Incentive wallet {incWallet.AccountId} balance: {incWallet.BaseBalance}\n");
        }
예제 #8
0
        public async Task <int> RunWalletAsync(ClientProgram options)
        {
            string network_id = options.NetworkId;

            bool   INMEMORY    = options.Database == Options.INMEMORY_DATABASE;
            string lyra_folder = Wallet.GetFullFolderName(network_id, "wallets");

            if (options.GenWalletName != null)
            {
                GenerateWallet(lyra_folder, network_id, options.GenWalletName, options.WalletPassword);
                return(0);
            }

            IAccountDatabase storage;

            if (INMEMORY)
            {
                storage = new AccountInMemoryStorage();
            }
            else
            {
                if (!Directory.Exists(lyra_folder))
                {
                    Directory.CreateDirectory(lyra_folder);
                }

                storage = new SecuredWalletStore(lyra_folder);
            }

            CommandProcessor command        = new CommandProcessor();
            string           walletName     = options.WalletName;
            string           walletPassword = options.WalletPassword;

            try
            {
                while (walletName == null || !File.Exists($"{lyra_folder}{Path.DirectorySeparatorChar}{walletName}{LyraGlobal.WALLETFILEEXT}"))
                {
                    walletName = Prompt.GetString($"Open wallet or creat a new wallet. Name:", "My Account");

                    if (!File.Exists($"{lyra_folder}{Path.DirectorySeparatorChar}{walletName}{LyraGlobal.WALLETFILEEXT}"))
                    {
                        if (Prompt.GetYesNo("Local account data not found. Would you like to create a new wallet?", defaultAnswer: true))
                        {
                            var password = Prompt.GetPassword("Please specify a strong password for your wallet:",
                                                              promptColor: ConsoleColor.Red,
                                                              promptBgColor: ConsoleColor.Black);

                            var password2 = Prompt.GetPassword("Repeat your password:"******"Passwords not match.");
                                continue;
                            }

                            walletPassword = password;

                            (var privateKey, var publicKey) = Signatures.GenerateWallet();

                            try
                            {
                                Wallet.Create(storage, walletName, walletPassword, network_id, privateKey);
                                Console.WriteLine("Wallet created.");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                continue;
                            }
                        }
                        else
                        {
                            string privatekey = Prompt.GetString($"Please enter private key to restore account:");

                            var password = Prompt.GetPassword("Please specify a strong password for your wallet:",
                                                              promptColor: ConsoleColor.Red,
                                                              promptBgColor: ConsoleColor.Black);

                            var password2 = Prompt.GetPassword("Repeat your password:"******"Passwords not match.");
                                continue;
                            }
                            walletPassword = password;

                            if (!Signatures.ValidatePrivateKey(privatekey))
                            {
                                Console.WriteLine("Private key is not valid.");
                                continue;
                            }

                            try
                            {
                                Wallet.Create(storage, walletName, walletPassword, network_id, privatekey);
                                Console.WriteLine("Wallet restored.");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                continue;
                            }
                        }
                    }
                }

                Wallet wallet;
                try
                {
                    walletPassword ??= Prompt.GetPassword($"Please input the password to open wallet {walletName}:",
                                                          promptColor: ConsoleColor.Red,
                                                          promptBgColor: ConsoleColor.Black);

                    wallet = Wallet.Open(storage, walletName, walletPassword);
                    Console.WriteLine("Wallet opened.");
                }
                catch (TamperedCipherTextException)
                {
                    Console.WriteLine("Wrong password.");
                    return(1);
                }

                LyraRestClient rpcClient;
                if (!string.IsNullOrWhiteSpace(options.Node))
                {
                    int port   = network_id.Equals("mainnet", StringComparison.InvariantCultureIgnoreCase) ? 5504 : 4504;
                    var apiUrl = $"https://{options.Node}:{port}/api/Node/";
                    rpcClient = LyraRestClient.Create(network_id, "Windows", $"{LyraGlobal.PRODUCTNAME} Client Cli", "1.0a", apiUrl);
                }
                else
                {
                    rpcClient = LyraRestClient.Create(network_id, "Windows", $"{LyraGlobal.PRODUCTNAME} Client Cli", "1.0a");//await LyraRpcClient.CreateAsync(network_id, "Lyra Client Cli", "1.0");
                }
                try
                {
                    Console.WriteLine("Try syncing wallet with Lyra blockchain...");
                    await wallet.SyncAsync(rpcClient, options.cancellation.Token);

                    Console.WriteLine("Wallet is synced.");
                }
                catch (Exception)
                {
                    Console.WriteLine("Startup sync failed. You may need to run sync command manually.");
                }

                var lastServiceBlock = await wallet.GetLastServiceBlockAsync();

                Console.WriteLine($"Last Service Block Received {lastServiceBlock.Height}");
                Console.WriteLine(string.Format("Transfer Fee: {0} ", lastServiceBlock.TransferFee));
                Console.WriteLine(string.Format("Token Generation Fee: {0} ", lastServiceBlock.TokenGenerationFee));
                Console.WriteLine(string.Format("Trade Fee: {0} ", lastServiceBlock.TradeFee));

                Console.WriteLine("\nType 'help' to see the list of available commands");
                Console.WriteLine("");

                var cmdInput = CommandProcessor.COMMAND_STATUS;

                if (options.Exec != null)
                {
                    var result = await command.ExecuteAsync(wallet, options.Exec, options.cancellation.Token);

                    Console.Write(string.Format("\n{0}> ", wallet.AccountName));
                }
                else
                {
                    while (!options.cancellation.IsCancellationRequested && cmdInput != CommandProcessor.COMMAND_STOP)
                    {
                        var result = await command.ExecuteAsync(wallet, cmdInput, options.cancellation.Token);

                        Console.Write(string.Format("\n{0}> ", wallet.AccountName));
                        //Console.Write
                        cmdInput = Console.ReadLine();
                    }
                }

                Console.WriteLine($"{LyraGlobal.PRODUCTNAME} Client is shutting down");
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception: {0}", ex.Message));
                Console.WriteLine($"{LyraGlobal.PRODUCTNAME} Client is shutting down");
            }

            return(0);
        }
        public async System.Threading.Tasks.Task RunPayAsync()
        {
            string lyrawalletfolder = Wallet.GetFullFolderName("mainnet", "wallets");
            var    walletStore      = new SecuredWalletStore(lyrawalletfolder);
            var    incWallet        = Wallet.Open(walletStore, "incentive", "");
            var    client           = LyraRestClient.Create("mainnet", "", "", "");
            var    syncResult       = await incWallet.SyncAsync(client);

            if (syncResult != Lyra.Core.Blocks.APIResultCodes.Success)
            {
                Console.WriteLine("Can't sync wallet!");
                return;
            }

            Console.WriteLine($"Incentive wallet {incWallet.AccountId} balance: {incWallet.BaseBalance}\n");

            // first lookup for failed payments
            var dbfn = @"C:\Users\Wizard\OneDrive\dev\lyra\Programs\IncProgram.db";

            using (var db = new LiteDatabase(dbfn))
            {
                var coll = db.GetCollection <IncPayment>("IncPay");

                async Task FixFailedPay()
                {
                    var lastPay = coll.FindOne(Query.All(Query.Descending));

                    Console.WriteLine($"Last payment time (UTC): {lastPay.TimeStamp}");

                    while (true)
                    {
                        foreach (var nodes in new[] { lastPay.MainnetNodes, lastPay.TestnetNodes })
                        {
                            if (nodes.Count(x => !x.SuccessPaid) == 0)
                            {
                                Console.WriteLine("No fix needed.");
                                return;
                            }

                            foreach (var node in nodes)
                            {
                                if (!node.SuccessPaid)
                                {
                                    Console.WriteLine($"fix failed pay for {node.AccountId} amont {node.PaidAmount}");
                                    await PayNodeAsync(incWallet, node, 0);

                                    coll.Update(lastPay);
                                }
                            }
                        }
                    }
                }

                //await FixFailedPay();

                var incPay = new IncPayment();
                incPay.TimeStamp = DateTime.UtcNow;

                incPay.MainnetNodes = await GetStatusFromNetworkAsync("mainnet");

                incPay.TestnetNodes = await GetStatusFromNetworkAsync("testnet");

                coll.Insert(incPay);

                var index = 1;
                Console.WriteLine("index SuccessPaid Rito NetworkId AccountId OfflineCount FullyUpgraded IsPrimary PosVotes SharedIP");
                decimal totalPayment = 0m;
                decimal package      = 400m;

                foreach (var nodes in new[] { incPay.MainnetNodes, incPay.TestnetNodes })
                {
                    foreach (var node in nodes)
                    {
                        await PayNodeAsync(incWallet, node, package);

                        if (node.SuccessPaid)
                        {
                            totalPayment += node.PaidAmount;
                        }

                        var resultStr = node.SuccessPaid ? "Paid" : "Failed";
                        Console.WriteLine($"No. {index} {resultStr} {node.PaidAmount:n} LYR to {node.NetworkId} {node.AccountId.Substring(0, 10)}... {node.OfflineCount} {node.FullyUpgraded} {node.IsPrimary} {node.PosVotes} {node.SharedIp}");
                        index++;

                        coll.Update(incPay);
                    }
                }

                Console.WriteLine($"Total payment: {totalPayment:n} LYR");

                await Task.Delay(60 * 1000);

                await FixFailedPay();
            }
        }
예제 #10
0
        // args: [number] the tps to simulate
        //
        static async Task Main(string[] args)
        {
            var workingFolder = @"C:\working\Friday";

            var lyraFolder = Wallet.GetFullFolderName(network_id, "wallets");

            Console.WriteLine("Press enter to begin.");
            Console.ReadLine();

            var rpcClient = LyraRestClient.Create(network_id, "Windows", $"{LyraGlobal.PRODUCTNAME} Client Cli", "1.0a");
            //var rpcClient = await LyraRestClient.CreateAsync(network_id, "Windows", "Lyra Client Cli", "1.0a", "http://192.168.3.62:4505/api/Node/");

            // create and save wallets
            var tt = new TransactionTester(rpcClient);
            //var wlts = tt.CreateWallet(1000);
            //var json = JsonConvert.SerializeObject(wlts);
            //File.WriteAllText(workingFolder + @"\wallets.json", json);

            //return;

            // key is account id
            var wallets = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(workingFolder + @"\\wallets.json"));

            //var tt = new TransactionTester(rpcClient);

            var secureStorage = new SecuredWalletStore(lyraFolder);
            var masterWallet  = Wallet.Open(secureStorage, "My Account", "");

            await masterWallet.SyncAsync(rpcClient);

            _ = Task.Run(async() =>
            {
                while (true)
                {
                    var state = await rpcClient.GetSyncStateAsync();
                    await Task.Delay(10000);
                    var state2 = await rpcClient.GetSyncStateAsync();

                    var tps = state2.Status.totalBlockCount - state.Status.totalBlockCount;

                    Console.WriteLine($"\n============> TPS: {tps} / 10\n");
                }
            }).ConfigureAwait(false);

            var all = await tt.RefreshBalancesAsync(wallets.Select(a => a.Value).ToArray());

            File.WriteAllText(workingFolder + @"\balances.json", JsonConvert.SerializeObject(all));

            var rich10     = JsonConvert.DeserializeObject <List <WalletBalance> >(File.ReadAllText(workingFolder + @"\balances.json"));
            var realRich10 = rich10.Where(a => a.balance.ContainsKey(lyraCoin) && a.balance.ContainsKey(testCoin))
                             .Where(a => a.balance[testCoin] >= 10000).ToDictionary(a => a.privateKey, a => a.balance);

            var rich90 = wallets.Where(a => !realRich10.ContainsKey(a.Value)).Take(90);

            File.WriteAllText(workingFolder + @"\rich90.json", JsonConvert.SerializeObject(rich90));

            //var rich90 = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(File.ReadAllText(workingFolder + @"\\rich90.json"));

            var poors = wallets.Where(a => !rich90.Any(x => x.Key == a.Key));

            var testGroup1 = rich90.Take(50);
            await tt.MultiThreadedSendAsync(new [] { masterWallet.PrivateKey }, testGroup1.Select(a => a.Key).ToArray(), new Dictionary <string, decimal> {
                { lyraCoin, 5000 }
            }, true);

            Console.WriteLine("Coin distribute OK. Press Enter to continue...");
            Console.ReadLine();

            await tt.MultiThreadedSendAsync(testGroup1.Select(a => a.Value).ToArray(), poors.Select(a => a.Key).ToArray(), new Dictionary <string, decimal> {
                { lyraCoin, 1 }
            });

            Console.ReadLine();

            //foreach(var b in masterWallet.GetLatestBlock().Balances)
            //{
            //    Console.WriteLine($"{b.Key}: {b.Value}");
            //}
            //Console.WriteLine("Hello Lyra!");

            //var top10 = wallets.Take(10).ToDictionary(a => a.Key, a => a.Value);

            //await tt.SingleThreadedSendAsync(10, masterWallet, top10.Keys.ToArray(), new Dictionary<string, decimal> {
            //    { lyraCoin, 10000 }, {testCoin, 1000000}
            //});

            //var top100 = wallets.Skip(10).Take(100).ToDictionary(a => a.Key, a => a.Value);
            //await tt.MultiThreadedSendAsync(10, top10.Select(a => new KeyPair(Base58Encoding.DecodePrivateKey(a.Value))).ToArray(),
            //    top100.Values.ToArray(), new Dictionary<string, decimal> {
            //        { lyraCoin, 100 }, {testCoin, 10000} }
            //    );
        }
예제 #11
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _waitOrder = new AutoResetEvent(false);
            try
            {
                var networkId = LyraNodeConfig.GetNetworkId();

                _log.LogInformation($"{LyraGlobal.PRODUCTNAME} {LyraGlobal.NODE_VERSION} Mode: {Neo.Settings.Default.LyraNode.Lyra.Mode}: Starting node daemon for {networkId}.");

                // something must be initialized first

                Wallet PosWallet;

                string lyrawalletfolder = Wallet.GetFullFolderName(networkId, "wallets");

                if (!Directory.Exists(lyrawalletfolder))
                {
                    Directory.CreateDirectory(lyrawalletfolder);
                }

                var walletStore = new SecuredWalletStore(lyrawalletfolder);
                if (!walletStore.Exists(Neo.Settings.Default.LyraNode.Lyra.Wallet.Name))
                {
                    _log.LogInformation($"Creating wallet for {networkId}.");

                    (var privateKey, var publicKey) = Signatures.GenerateWallet();

                    _log.LogInformation($"The new wallet {Neo.Settings.Default.LyraNode.Lyra.Wallet.Name} for {networkId} was created.");
                    //Console.WriteLine($"Private Key: {privateKey}");
                    _log.LogInformation($"Account ID: {publicKey}");

                    walletStore.Create(Neo.Settings.Default.LyraNode.Lyra.Wallet.Name, Neo.Settings.Default.LyraNode.Lyra.Wallet.Password, networkId, privateKey, publicKey, "");
                    _log.LogInformation($"Wallet saved to: {lyrawalletfolder}{Neo.Settings.Default.LyraNode.Lyra.Wallet.Name}.lyrawallet");
                }

                PosWallet = Wallet.Open(walletStore,
                                        Neo.Settings.Default.LyraNode.Lyra.Wallet.Name,
                                        Neo.Settings.Default.LyraNode.Lyra.Wallet.Password,
                                        LyraRestClient.Create(networkId, "", "NodeService", "1.0", LyraGlobal.SelectNode(networkId) + "Node/"));
                _log.LogInformation($"Staking wallet: {PosWallet.AccountId}");
                PosWallet.SetVoteFor(PosWallet.AccountId);

                var blcokcount = await _store.GetBlockCountAsync();

                if (blcokcount > 0 && networkId == "devnet") // not genesis
                {
                    try
                    {
                        await PosWallet.SyncAsync(null);
                    }
                    catch { }
                }

                var localNode = DagSystem.ActorSystem.ActorOf(Neo.Network.P2P.LocalNode.Props());
                Dag = new DagSystem(_hostEnv, _store, _lyraEventContext, PosWallet, localNode);
                _   = Task.Run(async() => await Dag.StartAsync()).ConfigureAwait(false);
                await Task.Delay(30000);
            }
            catch (Exception ex)
            {
                _log.LogCritical($"NodeService: Error Initialize! {ex}");
            }

            while (!stoppingToken.IsCancellationRequested)
            {
                // do work
                if (_waitOrder.WaitOne(1000))
                {
                    _waitOrder.Reset();
                }
                else
                {
                    // no new order. do house keeping.
                }
            }
        }