Exemplo n.º 1
0
        public async Task <APIResultCodes> RefreshBalanceAsync()
        {
            // implicty receive
            var rpcClient = LyraRestClient.Create(LyraWallet.NetworkId, Environment.OSVersion.Platform.ToString(), $"{LyraGlobal.PRODUCTNAME} Client Cli", "1.0a");

            return(await LyraWallet.Sync(rpcClient));
        }
        public async Task <SendResult> Send(string privateKey, double amount,
                                            string destAccountId, string ticker)
        {
            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");
                var wallet = new TransitWallet(privateKey, client);

                var result = await wallet.SendAsync((decimal)amount, destAccountId, ticker);

                if (result == Lyra.Core.Blocks.APIResultCodes.Success)
                {
                    return(new SendResult {
                        Success = true, SendHash = wallet.LastTxHash
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("In OpenWallet: " + ex.ToString());
            }

            return(new SendResult {
                Success = false, SendHash = ""
            });
        }
Exemplo n.º 3
0
        public override async Task <SendReply> Send(SendRequest request, ServerCallContext context)
        {
            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");
                var wallet = new TransitWallet(request.PrivateKey, client);

                var result = await wallet.SendAsync((decimal)request.Amount, request.DestAccountId, request.Ticker);

                if (result == Lyra.Core.Blocks.APIResultCodes.Success)
                {
                    return(new SendReply {
                        Success = true, SendHash = wallet.LastTxHash
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("In OpenWallet: " + ex.ToString());
            }

            return(new SendReply {
                Success = false, SendHash = ""
            });
        }
Exemplo n.º 4
0
        public override async Task <GetBalanceReply> GetBalance(GetBalanceRequest request, ServerCallContext context)
        {
            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");
                var wallet = new TransitWallet(request.PrivateKey, client);

                var result = await wallet.ReceiveAsync();

                if (result == Lyra.Core.Blocks.APIResultCodes.Success)
                {
                    var blances = await wallet.GetBalanceAsync();

                    if (blances != null)
                    {
                        var msg = new GetBalanceReply {
                            AccountId = wallet.AccountId
                        };
                        foreach (var kvp in blances)
                        {
                            msg.Balances.Add(new LyraBalance {
                                Ticker = kvp.Key, Balance = kvp.Value / 100000000
                            });
                        }
                        return(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("In OpenWallet: " + ex.ToString());
            }

            return(new GetBalanceReply());
        }
Exemplo n.º 5
0
            public async Task Execute(IJobExecutionContext context)
            {
                try
                {
                    var ic     = context.Scheduler.Context.Get("ic") as IncentiveScheduler;
                    var client = LyraRestClient.Create(ic._network, "Win", "IncProg", "1.0");
                    var bb     = await client.GetBillBoardAsync();

                    if (bb.ActiveNodes.Any())
                    {
                        var wallet = new IncWallet(ic._network, "incentive", "");
                        await wallet.OpenAsync();

                        var amount = 10;

                        foreach (var node in bb.ActiveNodes)
                        {
                            Console.WriteLine($"Pay {amount} to {node.AccountID}");

                            await wallet.PayAsync(node.AccountID, amount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error paying: {ex}");
                }
            }
        protected override async Task HandleAsync(NodeViewAction action, IDispatcher dispatcher)
        {
            int port = 4504;

            if (config["network"].Equals("mainnet", StringComparison.InvariantCultureIgnoreCase))
            {
                port = 5504;
            }

            var bb = await client.GetBillBoardAsync();

            var bag   = new ConcurrentDictionary <string, GetSyncStateAPIResult>();
            var tasks = bb.NodeAddresses
                        .Select(async node =>
            {
                var lcx = LyraRestClient.Create(config["network"], Environment.OSVersion.ToString(), "Nebula", "1.4", $"https://{node.Value}:{port}/api/Node/");
                try
                {
                    var syncState = await lcx.GetSyncState();
                    bag.TryAdd(node.Key, syncState);
                }
                catch (Exception ex)
                {
                    bag.TryAdd(node.Key, null);
                }
            });
            await Task.WhenAll(tasks);

            dispatcher.Dispatch(new NodeViewResultAction(bb, bag, config["ipdb"]));
        }
Exemplo n.º 7
0
        public async Task CreatePoolFactoryAsync()
        {
            var factory = await _sys.Storage.GetPoolFactoryAsync();

            if (factory != null)
            {
                return;
            }

            if (Board.CurrentLeader == _sys.PosWallet.AccountId)
            {
                var pf = await CreatePoolFactoryBlockAsync();
                await SendBlockToConsensusAndWaitResultAsync(pf);
            }
            else
            {
                // just send it to the leader
                var    platform  = Environment.OSVersion.Platform.ToString();
                var    appName   = "LyraNode";
                var    appVer    = "1.0";
                var    networkId = Settings.Default.LyraNode.Lyra.NetworkId;
                ushort peerPort  = 4504;
                if (networkId == "mainnet")
                {
                    peerPort = 5504;
                }

                if (Board.NodeAddresses.ContainsKey(Board.CurrentLeader))
                {
                    var client = LyraRestClient.Create(networkId, platform, appName, appVer, $"https://{Board.NodeAddresses[Board.CurrentLeader]}:{peerPort}/api/Node/");
                    _ = client.GetPoolAsync("a", "b");
                }
            }
        }
        public IncentiveProgram(IConfiguration configuration, INodeHistory history, RichList richList)
        {
            config  = configuration;
            History = history;
            rich    = richList;

            client = LyraRestClient.Create(config["network"], Environment.OSVersion.ToString(), "Nebula", "1.4");
        }
Exemplo n.º 9
0
        public async Task UT_PoolFactory_SetupAsync()
        {
            //var aggClient = new LyraAggregatedClient(networkId);
            //await aggClient.InitAsync();
            //client = aggClient;
            client = LyraRestClient.Create(networkId, "Windows", "UnitTest", "1.0");

            var w1 = Restore(testPrivateKey);
            await w1.SyncAsync(client);

            var balances = w1.GetLastSyncBlock().Balances;

            Assert.IsTrue(balances[LyraGlobal.OFFICIALTICKERCODE].ToBalanceDecimal() > 100000m, "Insufficient funds: LYR");

            // make sure we have 2 test token
            var genResult = await client.GetTokenGenesisBlockAsync(testPublicKey, testTokenA, await SignAPIAsync());

            if (genResult.ResultCode == APIResultCodes.TokenGenesisBlockNotFound)
            {
                var secs   = testTokenA.Split('/');
                var result = await w1.CreateTokenAsync(secs[1], secs[0], "", 8, 50000000000, true, "", "", "", Lyra.Core.Blocks.ContractTypes.Cryptocurrency, null);

                Assert.IsTrue(result.Successful(), "Failed to create token: " + result.ResultCode);
                await w1.SyncAsync(client);
            }

            genResult = await client.GetTokenGenesisBlockAsync(testPublicKey, testTokenB, await SignAPIAsync());

            if (genResult.ResultCode == APIResultCodes.TokenGenesisBlockNotFound)
            {
                var secs   = testTokenB.Split('/');
                var result = await w1.CreateTokenAsync(secs[1], secs[0], "", 8, 50000000000, true, "", "", "", Lyra.Core.Blocks.ContractTypes.Cryptocurrency, null);

                Assert.IsTrue(result.Successful(), "Failed to create token: " + result.ResultCode);
                await w1.SyncAsync(client);
            }

            var pool = await client.GetPoolAsync(LyraGlobal.OFFICIALTICKERCODE, testTokenA);

            if (pool.PoolAccountId == null)
            {
                var token0 = LyraGlobal.OFFICIALTICKERCODE;
                var token1 = testTokenA;

                var poolCreateResult = await w1.CreateLiquidatePoolAsync(token0, token1);

                await Task.Delay(3000);     // give consens network time to create it.

                Assert.IsTrue(poolCreateResult.ResultCode == APIResultCodes.Success, "Can't create pool for " + token1);
            }

            await w1.SyncAsync(client);

            balances = w1.GetLastSyncBlock().Balances;
            Assert.IsTrue(balances[testTokenA].ToBalanceDecimal() > 100000m, "Insufficient funds: " + testTokenA);
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
0
        public async Task TestGetServiceBlockAsync()
        {
            var client = LyraRestClient.Create(networkId, "Windows", "UnitTest", "1.0");

            var aggClient = new LyraAggregatedClient(networkId, false, null);
            await aggClient.InitAsync();

            var svcBlock1 = await client.GetLastServiceBlockAsync();

            var svcBlock2 = await aggClient.GetLastServiceBlockAsync();

            Assert.AreEqual(svcBlock1, svcBlock2);
        }
Exemplo n.º 12
0
        private async Task <Wallet> RefreshBalanceAsync(string masterKey)
        {
            // create wallet and update balance
            var store = new AccountInMemoryStorage();
            var name  = Guid.NewGuid().ToString();

            Wallet.Create(store, name, "", Program.network_id, masterKey);
            var wallet = Wallet.Open(store, name, "");

            Console.WriteLine("Sync wallet for " + wallet.AccountId);
            var rpcClient = LyraRestClient.Create(Program.network_id, "Windows", $"{LyraGlobal.PRODUCTNAME} Client Cli", "1.0a");
            await wallet.SyncAsync(rpcClient);

            return(wallet);
        }
Exemplo n.º 13
0
        public Wallet Restore(string privateKey)
        {
            client = LyraRestClient.Create(networkId, "Windows", "UnitTest", "1.0");

            var memStor = new AccountInMemoryStorage();

            try
            {
                Wallet.Create(memStor, "tmpAcct", "", networkId, privateKey);
                return(Wallet.Open(memStor, "tmpAcct", ""));
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 14
0
        public async Task TestGetTradableOtc()
        {
            var lyraApi = LyraRestClient.Create("devnet", "", "", "");
            var tosret  = await lyraApi.FindTradableOtcAsync();

            Assert.IsTrue(tosret.Successful());

            var allblks        = tosret.GetBlocks("orders");
            var tradableOrders = allblks.Cast <IOtcOrder>()
                                 .Where(a => a.Order.amount > 0)
                                 .OrderBy(a => a.Order.price)
                                 .ToList();
            var tradableCryptos = tradableOrders.Select(a => a.Order.crypto)
                                  .Distinct()
                                  .ToList();

            var daos = tosret.GetBlocks("daos").Cast <IDao>().ToList();
        }
        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");
        }
        public async Task <LyraStatus> GetStatus()
        {
            bool LyraIsReady = false;

            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");
                LyraIsReady = (await client.GetSyncStateAsync()).SyncState == Lyra.Data.API.ConsensusWorkingMode.Normal;
            }
            catch (Exception ex)
            {
                _logger.LogWarning("Failed to get sync state: " + ex.Message);
            }

            return(new LyraStatus
            {
                IsReady = LyraIsReady,
                NetworkId = _config["network"]
            });
        }
Exemplo n.º 17
0
        public async Task <APIResultCodes> RestoreAsync(string NetworkId, string NodeAPIURL, string PrivateKey)
        {
            try
            {
                var storage = new AccountInMemoryStorage();
                _wallet = Wallet.Create(storage, string.Empty, string.Empty, NetworkId, PrivateKey);

                var rpcClient  = LyraRestClient.Create(NetworkId, "Windows", $"{LyraGlobal.PRODUCTNAME} Client Cli", "1.0a", NodeAPIURL);
                var syncResult = await _wallet.SyncAsync(rpcClient);

                if (syncResult != APIResultCodes.Success)
                {
                    _wallet = null;
                }
                return(syncResult);
            }
            catch
            {
                return(APIResultCodes.FailedToSyncAccount);
            }
        }
Exemplo n.º 18
0
        public static async Task <decimal> GetLyraBalanceAsync(string lyraNetwork, string accountPvk)
        {
            var store  = new AccountInMemoryStorage();
            var wallet = Wallet.Create(store, "default", "", lyraNetwork,
                                       accountPvk);
            var lyraClient = LyraRestClient.Create(lyraNetwork, Environment.OSVersion.ToString(),
                                                   "Nebula Swap", "1.0");

            var syncResult = await wallet.Sync(lyraClient);

            if (syncResult == APIResultCodes.Success)
            {
                var block = wallet.GetLatestBlock();
                if (block.Balances?.ContainsKey("LYR") == true)
                {
                    return(block.Balances["LYR"].ToBalanceDecimal());
                }
            }

            return(0m);
        }
        private async Task RefreshNodeStatusAsync()
        {
            int port = 4504;

            if (config["network"].Equals("mainnet", StringComparison.InvariantCultureIgnoreCase))
            {
                port = 5504;
            }

            var bb = await client.GetBillBoardAsync();

            var bag   = new ConcurrentDictionary <string, GetSyncStateAPIResult>();
            var tasks = bb.NodeAddresses
                        .Select(async node =>
            {
                var lcx = LyraRestClient.Create(config["network"], Environment.OSVersion.ToString(), "Nebula", "1.4", $"https://{node.Value}:{port}/api/Node/");
                try
                {
                    var syncState = await lcx.GetSyncState();
                    bag.TryAdd(node.Key, syncState);
                }
                catch (Exception ex)
                {
                    bag.TryAdd(node.Key, null);
                }
            });
            await Task.WhenAll(tasks);

            var nvs = new NodeViewState(
                isLoading: false,
                billBoard: bb,
                NodeStatus: bag,
                ipdb: config["ipdb"]);

            nvs.Id        = 0; // create new for liteDB
            nvs.TimeStamp = DateTime.UtcNow;

            History.Insert(nvs);
        }
        public async Task <BalanceInfo> GetBalance(string privateKey)
        {
            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");
                var wallet = new TransitWallet(privateKey, client);

                var result = await wallet.ReceiveAsync();

                if (result == Lyra.Core.Blocks.APIResultCodes.Success)
                {
                    var blances = await wallet.GetBalanceAsync();

                    if (blances != null)
                    {
                        var msg = new BalanceInfo
                        {
                            AccountId = wallet.AccountId
                        };
                        var list = new List <LyraBalance>();
                        foreach (var kvp in blances)
                        {
                            list.Add(new LyraBalance {
                                Ticker = kvp.Key, Balance = kvp.Value / 100000000
                            });
                        }
                        msg.Balances = list.ToArray();
                        return(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("In OpenWallet: " + ex.ToString());
            }

            return(new BalanceInfo());
        }
        public async Task <TxInfo> GetTransByHash(string hash)
        {
            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");

                var result = await client.GetBlockAsync(hash);

                if (result.ResultCode == Lyra.Core.Blocks.APIResultCodes.Success && result.GetBlock() is TransactionBlock block)
                {
                    var tx = new TxInfo
                    {
                        TxHash = block.Hash,
                        Height = block.Height,
                        Time   = block.TimeStamp
                    };

                    tx.TxType = block is SendTransferBlock ? TransactionType.Send : TransactionType.Receive;
                    if (tx.TxType == TransactionType.Send)
                    {
                        tx.OwnerAccountId = block.AccountID;
                        tx.PeerAccountId  = (block as SendTransferBlock).DestinationAccountId;

                        var rcvBlockQuery = await client.GetBlockBySourceHashAsync(block.Hash);

                        if (rcvBlockQuery.ResultCode == APIResultCodes.Success)
                        {
                            tx.IsReceived = true;
                            tx.RecvHash   = rcvBlockQuery.GetBlock().Hash;
                        }
                        else
                        {
                            tx.IsReceived = false;
                            tx.RecvHash   = ""; //gRPC don't like null
                        }
                    }
                    else
                    {
                        tx.OwnerAccountId = block.AccountID;

                        var sndBlockQuery = await client.GetBlockAsync((block as ReceiveTransferBlock).SourceHash);

                        if (sndBlockQuery.ResultCode == APIResultCodes.Success)
                        {
                            tx.PeerAccountId = (sndBlockQuery.GetBlock() as SendTransferBlock).AccountID;
                        }

                        tx.IsReceived = true;
                        tx.RecvHash   = block.Hash;
                    }

                    return(tx);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("In OpenWallet: " + ex.ToString());
            }

            return(new TxInfo {
                TxHash = ""
            });
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        public async Task InitAsync()
        {
            ServicePointManager.DefaultConnectionLimit = 30;
            var platform = Environment.OSVersion.Platform.ToString();
            var appName  = "LyraAggregatedClient";
            var appVer   = "1.0";

            ushort peerPort = 4504;

            if (_networkId == "mainnet")
            {
                peerPort = 5504;
            }

            // get nodes list (from billboard)
            var seedNodes = GetSeedNodes();

            var seeds = seedNodes.Select(a => LyraRestClient.Create(_networkId, platform, appName, appVer, $"https://{a}:{peerPort}/api/Node/")).ToList();

            BillBoard currentBillBoard = null;

            do
            {
                try
                {
                    Console.WriteLine($"LyraAggregatedClient.InitAsync Seed Only: {_seedsOnly}");
                    var rand = new Random();
                    foreach (var sd in seedNodes.OrderBy(a => rand.Next()))
                    {
                        try
                        {
                            var apiClient = LyraRestClient.Create(_networkId, platform, appName, appVer, $"https://{sd}:{peerPort}/api/Node/");
                            currentBillBoard = await apiClient.GetBillBoardAsync();

                            Console.WriteLine($"LyraAggregatedClient.InitAsync Got billboard from {sd}");
                            break;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("LyraAggregatedClient.InitAsync: " + e.Message);
                        }
                    }

                    //var bbtasks = seeds.Select(client => client.GetBillBoardAsync()).ToList();
                    //try
                    //{
                    //    await Task.WhenAll(bbtasks);
                    //}
                    //catch (Exception ex)
                    //{
                    //    Console.WriteLine($"In LyraAggregatedClient.InitAsync: " + ex.Message);
                    //}
                    //var goodbb = bbtasks.Where(a => !(a.IsFaulted || a.IsCanceled) && a.IsCompleted && a.Result != null).Select(a => a.Result).ToList();

                    //if (goodbb.Count == 0)
                    //    continue;

                    //// pickup best result
                    //var best = goodbb
                    //        .GroupBy(b => b.CurrentLeader)
                    //        .Select(g => new
                    //        {
                    //            Data = g.Key,
                    //            Count = g.Count()
                    //        })
                    //        .OrderByDescending(x => x.Count)
                    //        .First();

                    //if (best.Count >= seedNodes.Length - 2 && !string.IsNullOrWhiteSpace(best.Data))
                    //{
                    //    var r = new Random();
                    //    currentBillBoard = goodbb.ElementAt(r.Next(0, goodbb.Count()));
                    //    //currentBillBoard = goodbb.First(a => a.CurrentLeader == best.Data);
                    //}
                    //else
                    //{
                    //    await Task.Delay(2000);
                    //    continue;
                    //}

                    if (_seedsOnly)
                    {
                        // create clients for primary nodes
                        _primaryClients = seedNodes
                                          .Select(c => LyraRestClient.Create(_networkId, platform, appName, appVer, $"https://{c}:{peerPort}/api/Node/"))
                                          .ToList();
                    }
                    else if (currentBillBoard == null)
                    {
                        Console.WriteLine("Error init LyraAggregatedClient. Billboard is null.");
                        await Task.Delay(1000);

                        continue;
                    }
                    else
                    {
                        // create clients for primary nodes
                        _primaryClients = currentBillBoard.NodeAddresses
                                          .Where(a => currentBillBoard.PrimaryAuthorizers.Contains(a.Key))
                                          .Where(a => a.Key != _poswallet)
                                          .Select(c => LyraRestClient.Create(_networkId, platform, appName, appVer, $"https://{c.Value}:{peerPort}/api/Node/"))
                                          //.Take(7)    // don't spam the whole network
                                          .ToList();
                    }

                    if (_primaryClients.Count < 2)      // billboard not harvest address enough
                    {
                        await Task.Delay(2000);
                    }

                    foreach (var primaryClient in _primaryClients)
                    {
                        primaryClient.SetTimeout(TimeSpan.FromSeconds(5));
                    }
                }
                catch (Exception exx)
                {
                    Console.WriteLine("Error init LyraAggregatedClient. Error: " + exx.ToString());
                    await Task.Delay(1000);

                    continue;
                }
            } while (currentBillBoard == null || _primaryClients.Count < 2);
        }
Exemplo n.º 24
0
        public override async Task <GetTransactionsReply> GetTransactions(GetTransactionsRequest request, ServerCallContext context)
        {
            var resp = new GetTransactionsReply {
            };

            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");
                var result = await client.SearchTransactionsAsync(request.AccountId,
                                                                  request.StartTime.ToDateTime().Ticks,
                                                                  request.EndTime.ToDateTime().Ticks,
                                                                  request.Count);

                if (result.ResultCode == APIResultCodes.Success)
                {
                    for (int i = 0; i < result.Transactions.Count; i++)
                    {
                        var txDesc = result.Transactions[i];
                        var tx     = new LyraTransaction
                        {
                            Height    = txDesc.Height,
                            Time      = Timestamp.FromDateTime(txDesc.TimeStamp),
                            IsReceive = txDesc.IsReceive,

                            SendAccountId = txDesc.SendAccountId ?? "",
                            SendHash      = txDesc.SendHash ?? "",
                            RecvAccountId = txDesc.RecvAccountId,
                            RecvHash      = txDesc.RecvHash ?? ""   // protobuf not like null
                        };

                        if (txDesc.Changes == null || !txDesc.Changes.ContainsKey(LyraGlobal.OFFICIALTICKERCODE))
                        {
                            tx.BalanceChange = 0;
                        }
                        else
                        {
                            tx.BalanceChange = txDesc.Changes[LyraGlobal.OFFICIALTICKERCODE] / LyraGlobal.TOKENSTORAGERITO;
                        }

                        if (txDesc.Balances == null || !txDesc.Balances.ContainsKey(LyraGlobal.OFFICIALTICKERCODE))
                        {
                            tx.Balance = 0;
                        }
                        else
                        {
                            tx.Balance = txDesc.Balances[LyraGlobal.OFFICIALTICKERCODE] / LyraGlobal.TOKENSTORAGERITO;
                        }



                        resp.Transactions.Add(tx);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("In OpenWallet: " + ex.ToString());
            }

            return(resp);
        }
Exemplo n.º 25
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.
                }
            }
        }
        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();
            }
        }
Exemplo n.º 27
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} }
            //    );
        }
        public async Task <TransactionInfo> GetTransactions(string accountId,
                                                            long startTimeTicks, long endTimeTicks, int count)
        {
            var resp = new TransactionInfo {
            };

            try
            {
                var client = LyraRestClient.Create(_config["network"], Environment.OSVersion.ToString(), "LyraBroker", "1.0");
                var result = await client.SearchTransactionsAsync(accountId,
                                                                  startTimeTicks,
                                                                  endTimeTicks,
                                                                  count);

                if (result.ResultCode == APIResultCodes.Success)
                {
                    var list = new List <Transaction>();
                    for (int i = 0; i < result.Transactions.Count; i++)
                    {
                        var txDesc = result.Transactions[i];
                        var tx     = new Transaction
                        {
                            Height    = txDesc.Height,
                            Time      = txDesc.TimeStamp,
                            IsReceive = txDesc.IsReceive,

                            SendAccountId = txDesc.SendAccountId ?? "",
                            SendHash      = txDesc.SendHash ?? "",
                            RecvAccountId = txDesc.RecvAccountId,
                            RecvHash      = txDesc.RecvHash ?? ""   // protobuf not like null
                        };

                        if (txDesc.Changes == null || !txDesc.Changes.ContainsKey(LyraGlobal.OFFICIALTICKERCODE))
                        {
                            tx.BalanceChange = 0;
                        }
                        else
                        {
                            tx.BalanceChange = txDesc.Changes[LyraGlobal.OFFICIALTICKERCODE] / LyraGlobal.TOKENSTORAGERITO;
                        }

                        if (txDesc.Balances == null || !txDesc.Balances.ContainsKey(LyraGlobal.OFFICIALTICKERCODE))
                        {
                            tx.Balance = 0;
                        }
                        else
                        {
                            tx.Balance = txDesc.Balances[LyraGlobal.OFFICIALTICKERCODE] / LyraGlobal.TOKENSTORAGERITO;
                        }

                        list.Add(tx);
                    }
                    resp.Transactions = list.ToArray();
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("In OpenWallet: " + ex.ToString());
            }

            return(resp);
        }
        private SemaphoreSlim semaphore = new SemaphoreSlim(1);      // we need to run tests in serial

        public static TransitWallet Restore(string privateKey)
        {
            var accountId = Signatures.GetAccountIdFromPrivateKey(privateKey);

            return(new TransitWallet(accountId, privateKey, LyraRestClient.Create(TestConfig.networkId, "Windows", "UnitTest", "1.0")));
        }