Beispiel #1
0
        public async Task TestCommentAsync()
        {
            var url    = "https://dealer.devnet.lyra.live:7070";
            var dealer = new DealerClient(new Uri(new Uri(url), "/api/dealer/"));

            var(pvt, pub) = Signatures.GenerateWallet();

            var tradid = "L8FufT33KuUrAsHYgCC1zo4gVRdZA8WBS7SMM8Tevq74B4N4wemz5mBh8CqCmgS3vKa4TiTsVH5kMi49Gn4962hfn8JcT7";

            var cfg = new CommentConfig();

            cfg.TradeId = tradid;
            cfg.Content = "hahaha";
            cfg.Title   = "title";

            cfg.ByAccountId = pub;
            cfg.Created     = DateTime.UtcNow;

            cfg.EncContent = Convert.ToBase64String(Encoding.UTF8.GetBytes(cfg.Content));
            cfg.EncTitle   = Convert.ToBase64String(Encoding.UTF8.GetBytes(cfg.Title));

            cfg.Sign(pvt, pub);

            //var result = await dealer.CommentTradeAsync(cfg);
            //Assert.IsTrue(result.Successful(), $"comment failed: {result.ResultCode}");

            //var cmnts = await dealer.GetCommentsForTradeAsync(tradid);
            //Assert.IsTrue(cmnts.Count == 1, $"no comment found.");
            //Assert.IsTrue(cmnts.First().Content == cfg.Content);
        }
        public async Task SendReceiveTestAsync()
        {
            try
            {
                await semaphore.WaitAsync();

                var w1 = Restore(PRIVATE_KEY_1);
                var s1 = await w1.ReceiveAsync();

                Assert.IsTrue(s1.balance != null, $"Failed to receive token: {s1}");

                var w2 = Restore(PRIVATE_KEY_2);
                var s2 = await w2.ReceiveAsync();

                Assert.IsTrue(s2.balance != null, $"Failed to receive token: {s2}");

                var b1 = s1.balance;

                var b1Before = b1[LyraGlobal.OFFICIALTICKERCODE];
                Assert.IsTrue(b1Before > 100000m && b1Before < 30000000m);

                var b2Balances = s2.balance;
                var b2Before   = b2Balances?.ContainsKey(LyraGlobal.OFFICIALTICKERCODE) == true ? b2Balances[LyraGlobal.OFFICIALTICKERCODE] : 0m;

                var amount = Math.Round((decimal)((new Random().NextDouble() + 0.03) * 1000), 8);
                //var amounts = new Dictionary<string, decimal>();
                //amounts.Add(LyraGlobal.OFFICIALTICKERCODE, amount);
                var sendResult = await w1.SendAsync(amount, w2.AccountId, LyraGlobal.OFFICIALTICKERCODE);

                await w2.ReceiveAsync();

                var b1After = (await w1.GetBalanceAsync()).balance[LyraGlobal.OFFICIALTICKERCODE];
                var b2After = (await w2.GetBalanceAsync()).balance[LyraGlobal.OFFICIALTICKERCODE];

                // the shit deciml deserialize bug. https://stackoverflow.com/questions/24051206/handling-decimal-values-in-newtonsoft-json
                Assert.AreEqual(Math.Round(b1Before - 1m - amount, 4), Math.Round(b1After, 4));
                Assert.AreEqual(Math.Round(b2Before + amount, 4), Math.Round(b2After, 4));

                // test for new created wallet
                var(pvtx, pubx) = Signatures.GenerateWallet();
                var sendx = await w2.SendAsync(1, pubx, "LYR");

                Assert.AreEqual(b2After - 2, sendx.balance[LyraGlobal.OFFICIALTICKERCODE]);

                var wx = Restore(pvtx);
                var bx = await wx.GetBalanceAsync();

                Assert.AreEqual(null, bx.balance);
                Assert.IsTrue(bx.unreceived);

                var br = await wx.ReceiveAsync();

                Assert.AreEqual(1, br.balance["LYR"], "bx not receive properly.");
            }
            finally
            {
                semaphore.Release();
            }
        }
Beispiel #3
0
 public async Task BalanceEmptyAsync()
 {
     var(_, accoutId) = Signatures.GenerateWallet();
     await TestProcAsync(async (jsonRpc, cancellationToken) =>
     {
         var result = await jsonRpc.InvokeWithCancellationAsync <JObject>("Balance", new object[] { accoutId }, cancellationToken);
         Assert.IsNull(result["balance"]);
     }).ConfigureAwait(true);
 }
Beispiel #4
0
 public override Task <CreateAccountReply> CreateAccount(Empty request, ServerCallContext context)
 {
     (string privateKey, string accountId) = Signatures.GenerateWallet();
     return(Task.FromResult(new CreateAccountReply
     {
         PrivateKey = privateKey,
         AccountId = accountId
     }));
 }
        public Task <AccountInfo> CreateAccount()
        {
            var keyPair = Signatures.GenerateWallet();

            return(Task.FromResult(new AccountInfo
            {
                PrivateKey = keyPair.privateKey,
                AccountId = keyPair.AccountId
            }));
        }
        public Dictionary <string, string> CreateWallet(int count)
        {
            var dict = new Dictionary <string, string>();

            for (int i = 1; i <= count; i++)
            {
                var nw = Signatures.GenerateWallet();
                dict.Add(nw.AccountId, nw.privateKey);
            }
            return(dict);
        }
        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}");
        }
Beispiel #8
0
        public TestAuthorizer(TestProbe testProbe)
        {
            //Console.WriteLine("initialize DagSystem");

            Environment.SetEnvironmentVariable("LYRA_NETWORK", "xtest");

            LyraNodeConfig.Init("xtest");

            fakeP2P   = testProbe;
            mockStore = new Mock <IAccountCollectionAsync>();
            var keypair = Signatures.GenerateWallet();

            posWallet = UT_Wallet.Restore(keypair.privateKey);
            var store = new MongoAccountCollection("mongodb://127.0.0.1/xunit", "xunit");

            TheDagSystem = new DagSystem(null, store, null, posWallet, fakeP2P);
        }
Beispiel #9
0
        // Create a new account (AccountName is the local wallet name)
        // Returns wallet address
        public string CreateAccount(string path, string accountName, AccountTypes accountType)
        {
            if (AccountExistsLocally(path, accountName))
            {
                throw new ApplicationException(String.Format(@"Account with name ""{0}"" already exists", AccountName));
            }

            _storage.Open(path, accountName);
            AccountName = accountName;
            Path        = path;

            var keys = Signatures.GenerateWallet();

            PrivateKey = keys.privateKey;
            _storage.StorePrivateKey(PrivateKey);
            AccountId = keys.AccountId;
            _storage.StoreAccountId(AccountId);

            return(AccountId);
        }
        public async Task TestGenerateWalletAsync()
        {
            var(pvtx, pubx) = Signatures.GenerateWallet();

            // first get some coin
            var gens = await GetGenesisWalletAsync();

            var dexwallet = await GetWalletAsync(pvtx);

            await gens.SendAsync(100, dexwallet.AccountId);

            await dexwallet.SyncAsync(null);

            Assert.AreEqual(100, dexwallet.BaseBalance);

            // request a wallet
            var crret = await dexwallet.CreateDexWalletAsync("TRX", "native");

            Assert.IsTrue(crret.Successful());
            await Task.Delay(4000);

            await TestDepositWithdraw(dexwallet);
        }
Beispiel #11
0
        public async Task <ExchangeAccount> AddExchangeAccount(string assocaitedAccountId)
        {
            var findResult = await _exchangeAccounts.FindAsync(a => a.AssociatedToAccountId == assocaitedAccountId);

            var findAccount = await findResult.FirstOrDefaultAsync();

            if (findAccount != null)
            {
                return(findAccount);
            }

            var walletPrivateKey = Signatures.GenerateWallet().privateKey;
            var walletAccountId  = Signatures.GetAccountIdFromPrivateKey(walletPrivateKey);

            var account = new ExchangeAccount()
            {
                AssociatedToAccountId = assocaitedAccountId,
                AccountId             = walletAccountId,
                PrivateKey            = walletPrivateKey
            };
            await _exchangeAccounts.InsertOneAsync(account);

            return(account);
        }
        public void WalletCreateNewTest()
        {
            var keypair = Signatures.GenerateWallet();

            keypair.AccountId.Should().StartWith(LyraGlobal.ADDRESSPREFIX.ToString());
        }
Beispiel #13
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 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);
        }
Beispiel #15
0
        public async Task CreateStakingAccountAsync()
        {
            try
            {
                await semaphore.WaitAsync();

                // sync wallet first
                var w1         = Restore(testPrivateKey);
                var syncResult = await w1.SyncAsync(client);

                Assert.IsTrue(syncResult == APIResultCodes.Success);

                var(pvt, pub) = Signatures.GenerateWallet();
                var wx = Restore(pvt);
                await w1.SendAsync(500, wx.AccountId);

                await Task.Delay(1000);

                await wx.SyncAsync(client);

                await Task.Delay(1000);

                int totalStaking = 2;
                // test create profiting account
                var result = await wx.CreateProfitingAccountAsync($"UT{_rand.Next()}", ProfitingType.Node, 1m, totalStaking * 2);

                Assert.IsTrue(result.ResultCode == APIResultCodes.Success, $"Result: {result.ResultCode}");

                var pgen = result.GetBlock() as ProfitingBlock;
                Assert.IsNotNull(pgen);

                Console.WriteLine($"Profit account: {pgen.AccountID}");

                var           stopwatch   = Stopwatch.StartNew();
                List <Wallet> stkWallets1 = new List <Wallet>();
                List <Wallet> stkWallets2 = new List <Wallet>();
                for (int i = 0; i < totalStaking; i++)
                {
                    var(pvtx, pubx) = Signatures.GenerateWallet();
                    var stkx = Restore(pvtx);
                    stkWallets1.Add(stkx);

                    await w1.SendAsync(30m, stkx.AccountId);

                    await stkx.SyncAsync(client);

                    // test create staking account
                    var result2 = await stkx.CreateStakingAccountAsync($"UT{_rand.Next()}", pgen.AccountID, 1000, true);

                    Assert.IsTrue(result2.ResultCode == APIResultCodes.Success, $"Result2: {result2.ResultCode}");

                    var stkgen = result2.GetBlock() as StakingBlock;
                    Assert.IsNotNull(stkgen);

                    // test add staking
                    var result3 = await stkx.AddStakingAsync(stkgen.AccountID, 10m);

                    Assert.IsTrue(result3.ResultCode == APIResultCodes.Success, $"Result3: {result3.ResultCode}");
                }
                for (int i = 0; i < totalStaking; i++)
                {
                    var(pvtx, pubx) = Signatures.GenerateWallet();
                    var stkx = Restore(pvtx);
                    stkWallets2.Add(stkx);

                    await w1.SendAsync(30m, stkx.AccountId);

                    await stkx.SyncAsync(client);

                    // test create staking account
                    var result2 = await stkx.CreateStakingAccountAsync($"UT{_rand.Next()}", pgen.AccountID, 1000, false);

                    Assert.IsTrue(result2.ResultCode == APIResultCodes.Success, $"Result2: {result2.ResultCode}");

                    var stkgen = result2.GetBlock() as StakingBlock;
                    Assert.IsNotNull(stkgen);

                    // test add staking
                    var result3 = await stkx.AddStakingAsync(stkgen.AccountID, 10m);

                    Assert.IsTrue(result3.ResultCode == APIResultCodes.Success, $"Result3: {result3.ResultCode}");
                }
                stopwatch.Stop();
                await Task.Delay(5000);

                Console.WriteLine($"create staking uses {stopwatch.ElapsedMilliseconds} ms");
                await w1.SendAsync(200, pgen.AccountID);

                var dvdret = await wx.CreateDividendsAsync(pgen.AccountID);

                Assert.IsTrue(dvdret.Successful(), $"Create dividens failed: {dvdret.ResultCode}");
                await Task.Delay(20000);

                foreach (var stkx in stkWallets1)
                {
                    var stkactcall = await stkx.RPC.GetAllBrokerAccountsForOwnerAsync(stkx.AccountId);

                    Assert.IsTrue(stkactcall.Successful());

                    var stkact = stkactcall.GetBlocks().First(a => a is IStaking) as IStaking;
                    var last   = await stkx.RPC.GetLastBlockAsync((stkact as TransactionBlock).AccountID);

                    Assert.AreEqual(60m, (last.GetBlock() as TransactionBlock).Balances["LYR"].ToBalanceDecimal());

                    await stkx.SyncAsync(client);

                    Assert.AreEqual(8m, stkx.BaseBalance);
                }

                foreach (var stkx in stkWallets2)
                {
                    var stkactcall = await stkx.RPC.GetAllBrokerAccountsForOwnerAsync(stkx.AccountId);

                    Assert.IsTrue(stkactcall.Successful());

                    var stkact = stkactcall.GetBlocks().First(a => a is IStaking) as IStaking;
                    var last   = await stkx.RPC.GetLastBlockAsync((stkact as TransactionBlock).AccountID);

                    Assert.AreEqual(10m, (last.GetBlock() as TransactionBlock).Balances["LYR"].ToBalanceDecimal());

                    await stkx.SyncAsync(client);

                    Assert.AreEqual(58m, stkx.BaseBalance);
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
Beispiel #16
0
 public static (string privateKey, string accountId) GenerateWalletKey()
 {
     return(Signatures.GenerateWallet());
 }
Beispiel #17
0
 public UT_WalletJsonRpc()
 {
     (_privateKey, _accountId) = Signatures.GenerateWallet();
     NetworkId = TestConfig.networkId;
 }
 public void GenerateWallet()
 {
     (_privatekey, _accountid) = Signatures.GenerateWallet();
 }