示例#1
0
        private Block addBlock()
        {
            Block        lastBlock   = storedChain.Last;
            IHashFactory hashFactory = MiningFactory.GetMiningHashFactoryForTransactions(pendingTransactions, lastBlock);
            Block        block       = new Block(MiningWallet.PublicKey, lastBlock.Hash, pendingTransactions, hashFactory);
            IMiner       miner       = MiningFactory.GetMiner(block.Transactions, lastBlock);

            miner.MineBlock(block);
            block.SignBlock(MiningWallet.Signer);

            storedChain.AddBlock(block);
            WalletManager.AcceptTransactions(block.Transactions);

            return(block);
        }
        public static async Task GetKeyTestAsync()
        {
            Wallet        wallet        = Wallet.FromJson(walletJson);
            WalletManager walletManager = new WalletManager(wallet);

            var     password        = "******";
            var     wif             = "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP";
            var     wifBytes        = Wallet.GetPrivateKeyFromWif(wif);
            KeyPair expectedKeyPair = new KeyPair(wifBytes);

            KeyPair key =
                await walletManager.GetKey("6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL", password);

            Assert.Equal(key.PrivateKey, expectedKeyPair.PrivateKey);
        }
        public static void ChangeApiEndPoints()
        {
            Wallet        wallet        = Wallet.FromJson(walletJson);
            WalletManager walletManager = new WalletManager(
                new NeoScanRestService(NeoScanNet.TestNet), new RpcClient(new Uri("http://seed4.travala.com:10332")), wallet);

            var beforeChanging = walletManager.GetDefaultAccount().TransactionManager.Client;
            var secondClient   = new RpcClient(new Uri("https://pyrpc1.narrative.network:443"));
            var secondRest     = new NeoScanRestService("http://86.715.152.211");

            walletManager.ChangeApiEndPoints(secondClient, secondRest);
            var afterChanging = walletManager.GetDefaultAccount().TransactionManager.Client;

            Assert.NotEqual(beforeChanging, afterChanging);
        }
示例#4
0
        /// <inheritdoc />
        public void AddNodeStats(StringBuilder benchLog)
        {
            WalletManager manager = this.walletManager as WalletManager;

            if (manager != null)
            {
                int           height    = manager.LastBlockHeight();
                ChainedHeader block     = this.chain.GetBlock(height);
                uint256       hashBlock = block == null ? 0 : block.HashBlock;

                benchLog.AppendLine("LightWallet.Height: ".PadRight(LoggingConfiguration.ColumnLength + 1) +
                                    (manager.ContainsWallets ? height.ToString().PadRight(8) : "No Wallet".PadRight(8)) +
                                    (manager.ContainsWallets ? (" LightWallet.Hash: ".PadRight(LoggingConfiguration.ColumnLength - 1) + hashBlock) : string.Empty));
            }
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of the BalanceViewModel class.
        /// </summary>
        public BalanceViewModel(IDataService dataService)
        {
            _DataService = dataService;

            WalletManager.Get().RegisterAction(WalletEvent.BalanceUpdated, () =>
            {
                var balance            = WalletManager.Get().Value("Balance") as BalanceEntity;
                var totalBalanceString = string.Format("{0:0.0000}", balance?.TotalBalance ?? 0);

                if (decimal.TryParse(totalBalanceString, out decimal totalbalance))
                {
                    TotalBalance = totalbalance;
                }
            });
        }
示例#6
0
        public void TestEOSWallet()
        {
            var wif = "5KA2AqEoo7jqepqeEqK2FjjjgG5nxQN6vfuiSZqgJM79ej6eo4Q";

            byte[] data = wif.Base58CheckDecode();

            byte[] privateKey = new byte[32];
            ByteArrayUtils.CopyBytes(data, 1, privateKey, 0, privateKey.Length);

            var keys    = new KeyPair(privateKey);
            var wallet  = new WalletManager(keys);
            var address = wallet.GetAddress(WalletKind.EOS);

            Assert.IsTrue(address.Equals("EOS8dBKtG9fbhC1wi1SscL32iFRsSi4PsZDT2EHJcYXwV5dAMiBcK", StringComparison.OrdinalIgnoreCase));
        }
        public Task <string> HandleAsync(string body, CancellationToken cancellationToken)
        {
            if (!PSBT.TryParse(body, Network, out var psbt))
            {
                throw new Exception("What the heck are you trying to do?");
            }
            if (!psbt.IsAllFinalized())
            {
                throw new Exception("The PSBT should be finalized");
            }
            // Which coin to use
            var toUse = WalletManager.GetWallets()
                        .Where(x => x.State == WalletState.Started && !x.KeyManager.IsWatchOnly && !x.KeyManager.IsHardwareWallet)
                        .SelectMany(wallet => wallet.Coins.Select(coin => new { wallet.KeyManager, coin }))
                        .Where(x => x.coin.AnonymitySet >= PrivacyLevelThreshold && !x.coin.Unavailable)
                        .OrderBy(x => x.coin.IsBanned)
                        .ThenBy(x => x.coin.Confirmed)
                        .ThenBy(x => x.coin.Height)
                        .First();
            // Fees
            var originalFeeRate = psbt.GetEstimatedFeeRate();
            var paymentTx       = psbt.ExtractTransaction();

            foreach (var input in paymentTx.Inputs)
            {
                input.WitScript = WitScript.Empty;
            }
            // Get prv key for signature
            var serverCoinKey = toUse.KeyManager.GetSecrets("chaincase", toUse.coin.ScriptPubKey).First();
            var serverCoin    = toUse.coin.GetCoin();

            paymentTx.Inputs.Add(serverCoin.Outpoint);
            var paymentOutput     = paymentTx.Outputs.First();
            var inputSizeInVBytes = (int)Math.Ceiling(((3 * Constants.P2wpkhInputSizeInBytes) + Constants.P2pkhInputSizeInBytes) / 4m);

            // Get final value
            paymentOutput.Value += (Money)serverCoin.Amount - originalFeeRate.GetFee(inputSizeInVBytes);

            var newPsbt          = PSBT.FromTransaction(paymentTx, Network.Main);
            var serverCoinToSign = newPsbt.Inputs.FindIndexedInput(serverCoin.Outpoint);

            serverCoinToSign.UpdateFromCoin(serverCoin);
            serverCoinToSign.Sign(serverCoinKey.PrivateKey);
            serverCoinToSign.FinalizeInput();

            NotificationManager.ScheduleNotification("PayJoin Received", "The sender has paid you in a CoinJoin style transaction", 1);
            return(Task.FromResult(newPsbt.ToHex()));
        }
        public static async void ImportAccountNep2Test2()
        {
            Wallet        wallet        = new Wallet();
            WalletManager walletManager = new WalletManager(wallet);

            var account = await walletManager.CreateAccount("teste", "123456");

            var nep2Key = account.Nep2Key;

            var rebornAccount = await walletManager.ImportAccount(nep2Key, "123456", "teste2");

            var address1 = account.TransactionManager.Account.Address;
            var address2 = rebornAccount.TransactionManager.Account.Address;

            Assert.Equal(address1, address2);
        }
示例#9
0
        public TumbleBitManager(ILoggerFactory loggerFactory, WalletManager walletManager, WatchOnlyWalletManager watchOnlyWalletManager, ConcurrentChain chain, Network network, Signals signals, WalletTransactionHandler walletTransactionHandler, BlockStoreManager blockStoreManager, MempoolManager mempoolManager, WalletSyncManager walletSyncManager)
        {
            this.walletManager            = walletManager;
            this.watchOnlyWalletManager   = watchOnlyWalletManager;
            this.walletSyncManager        = walletSyncManager;
            this.walletTransactionHandler = walletTransactionHandler;
            this.chain             = chain;
            this.signals           = signals;
            this.network           = network;
            this.loggerFactory     = loggerFactory;
            this.logger            = loggerFactory.CreateLogger(this.GetType().FullName);
            this.blockStoreManager = blockStoreManager;
            this.mempoolManager    = mempoolManager;

            this.tumblingState = new TumblingState(loggerFactory, this.chain, this.walletManager, this.watchOnlyWalletManager, this.network, this.walletTransactionHandler, this.blockStoreManager, this.mempoolManager, this.walletSyncManager);
        }
示例#10
0
 public WalletManagerViewModel(WalletManager walletManager, UiConfig uiConfig, Config config, BitcoinStore bitcoinStore,
                               LegalChecker legalChecker, TransactionBroadcaster broadcaster, HttpClientFactory httpClientFactory)
 {
     WalletManager            = walletManager;
     BitcoinStore             = bitcoinStore;
     LegalChecker             = legalChecker;
     _walletDictionary        = new Dictionary <Wallet, WalletViewModelBase>();
     _walletActionsDictionary = new Dictionary <WalletViewModelBase, List <NavBarItemViewModel> >();
     _actions         = new ObservableCollection <NavBarItemViewModel>();
     _selectedWallets = new ObservableCollection <NavBarItemViewModel>();
     _wallets         = new ObservableCollection <WalletViewModelBase>();
     _loggedInAndSelectedAlwaysFirst = true;
     _config   = config;
     _uiConfig = uiConfig;
     _transactionBroadcaster = broadcaster;
     _httpClientFactory      = httpClientFactory;
        public void Given_GetMaximumSpendableAmountIsCalled_When_ThereAreNoSpendableFound_Then_MaxAmountReturnsAsZero()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            var walletManager = new WalletManager(this.LoggerFactory.Object, this.Network, new ChainIndexer(this.Network), new WalletSettings(NodeSettings.Default(this.Network)),
                                                  dataFolder, new Mock <IWalletFeePolicy>().Object, new Mock <IAsyncProvider>().Object, new NodeLifetime(), DateTimeProvider.Default, this.scriptAddressReader);

            var walletTransactionHandler = new WalletTransactionHandler(this.LoggerFactory.Object, walletManager, It.IsAny <WalletFeePolicy>(), this.Network, this.standardTransactionPolicy);

            HdAccount account = WalletTestsHelpers.CreateAccount("account 1");

            Types.Wallet wallet = WalletTestsHelpers.CreateWallet("wallet1");

            HdAddress accountAddress1 = WalletTestsHelpers.CreateAddress();

            wallet.walletStore.InsertOrUpdate(WalletTestsHelpers.CreateTransaction(new uint256(1), new Money(15000), 1, new SpendingDetails {
                TransactionId = new uint256(1)
            }, address: accountAddress1.Address));
            wallet.walletStore.InsertOrUpdate(WalletTestsHelpers.CreateTransaction(new uint256(2), new Money(10000), 1, new SpendingDetails {
                TransactionId = new uint256(1)
            }, address: accountAddress1.Address));

            HdAddress accountAddress2 = WalletTestsHelpers.CreateAddress();

            wallet.walletStore.InsertOrUpdate(WalletTestsHelpers.CreateTransaction(new uint256(3), new Money(20000), 3, new SpendingDetails {
                TransactionId = new uint256(1)
            }, address: accountAddress2.Address));
            wallet.walletStore.InsertOrUpdate(WalletTestsHelpers.CreateTransaction(new uint256(4), new Money(120000), 4, new SpendingDetails {
                TransactionId = new uint256(1)
            }, address: accountAddress2.Address));

            account.ExternalAddresses.Add(accountAddress1);
            account.InternalAddresses.Add(accountAddress2);

            wallet.AccountsRoot.Add(new AccountRoot()
            {
                Accounts = new List <HdAccount> {
                    account
                }
            });

            walletManager.Wallets.Add(wallet);

            (Money max, Money fee)result = walletTransactionHandler.GetMaximumSpendableAmount(new WalletAccountReference("wallet1", "account 1"), FeeType.Low, true);
            Assert.Equal(Money.Zero, result.max);
            Assert.Equal(Money.Zero, result.fee);
        }
示例#12
0
        public static async Task VerifyPassword()
        {
            Wallet        wallet        = Wallet.FromJson(walletJson);
            WalletManager walletManager = new WalletManager(wallet);

            var nep2Key = "6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL";

            var password      = "******";
            var wrongPassword = "******";

            bool correct = await walletManager.VerifyPassword(nep2Key, password);

            bool incorrect = await walletManager.VerifyPassword(nep2Key, wrongPassword);

            Assert.True(correct);
            Assert.False(incorrect);
        }
示例#13
0
        public RecoveryWordsViewModel(
            KeyManager keyManager,
            Mnemonic mnemonic,
            WalletManager walletManager)
        {
            MnemonicWords = new List <RecoveryWordViewModel>();

            for (int i = 0; i < mnemonic.Words.Length; i++)
            {
                MnemonicWords.Add(new RecoveryWordViewModel(i + 1, mnemonic.Words[i]));
            }

            NextCommand = ReactiveCommand.Create(
                () => Navigate().To(new ConfirmRecoveryWordsViewModel(MnemonicWords, keyManager, walletManager)));

            CancelCommand = ReactiveCommand.Create(() => Navigate().Clear());
        }
        public AddedWalletPageViewModel(WalletManager walletManager, KeyManager keyManager)
        {
            KeyManager = keyManager;
            WalletName = keyManager.WalletName;

            NextCommand = ReactiveCommand.Create(
                () =>
            {
                walletManager.AddWallet(keyManager);

                Navigate().Clear();

                var navBar = NavigationManager.Get <NavBarViewModel>();

                var wallet = navBar?.Items.OfType <WalletViewModelBase>().FirstOrDefault(x => x.WalletName == WalletName);

                if (wallet is { } && navBar is { })
示例#15
0
        public StakingService(WalletManager walletManager, string passphrase, NodeServices nodeServices)
        {
            this.walletManager = walletManager;
            this.passphrase    = passphrase;
            this.nodeServices  = nodeServices;

            this.cts         = new CancellationTokenSource();
            this.stakingTask = new Task(StakingLoop, this.cts.Token);
            this.stopwatch   = Stopwatch.StartNew();
            this.Status      = new StakingStatus {
                StartedUtc = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };
            this.PosV3 = new PosV3 {
                SearchInterval = 64, BlockInterval = 4 * 64
            };
            this.LastStakedBlock = new StakedBlock();
        }
示例#16
0
        public slash(Logger logger, ItemFactory itemFactory, MarketDB marketDB, CharacterDB characterDB, ItemDB itemDB, NotificationManager notificationManager, WalletManager walletManager)
        {
            this.Log                 = logger.CreateLogChannel("Slash");
            this.ItemFactory         = itemFactory;
            this.MarketDB            = marketDB;
            this.CharacterDB         = characterDB;
            this.ItemDB              = itemDB;
            this.NotificationManager = notificationManager;
            this.WalletManager       = walletManager;

            // register commands
            this.mCommands["create"]     = CreateCmd;
            this.mCommands["createitem"] = CreateCmd;
            this.mCommands["giveskills"] = GiveSkillCmd;
            this.mCommands["giveskill"]  = GiveSkillCmd;
            this.mCommands["giveisk"]    = GiveIskCmd;
        }
示例#17
0
 /// <summary>
 /// Initializes the instance of the object.
 /// </summary>
 /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
 /// <param name="minerSettings">Settings relevant to mining or staking.</param>
 /// <param name="loggerFactory">Factory to be used to create logger for the node.</param>
 /// <param name="powMining">POW miner.</param>
 /// <param name="posMinting">POS staker.</param>
 /// <param name="walletManager">Manager providing operations on wallets.</param>
 public MiningFeature(
     Network network,
     MinerSettings minerSettings,
     NodeSettings nodeSettings,
     ILoggerFactory loggerFactory,
     PowMining powMining,
     PosMinting posMinting       = null,
     WalletManager walletManager = null)
 {
     this.network       = network;
     this.minerSettings = minerSettings;
     this.minerSettings.Load(nodeSettings);
     this.powMining     = powMining;
     this.posMinting    = posMinting;
     this.walletManager = walletManager;
     this.logger        = loggerFactory.CreateLogger(this.GetType().FullName);
 }
示例#18
0
        public void RemoveWalletTest()
        {
            WalletManager walletManager = new WalletManager();
            var           output        = walletManager.AddWallet("Test Wallet", 5.1m);

            Assert.AreEqual(2, output);

            var walletList = walletManager.GetWallets();

            CollectionAssert.AllItemsAreUnique(walletList);

            var wallet = walletList.Last();
            var result = walletManager.RemoveWallet(wallet);

            Assert.AreEqual(1, result);
            CollectionAssert.DoesNotContain(walletList, wallet);
        }
示例#19
0
        private void SetExchangeChart(string exchange)
        {
            List <ExchangeBalance> list    = Balances.Where(item => item.Balance > 0 && item.Exchange == exchange).ToList();
            List <ExchangeBalance> wallets = WalletManager.GetWalletBalances();

            list.AddRange(wallets.Where(balance => balance.Exchange == exchange));

            List <string>  symbols = new List <string>();
            List <decimal> totals  = new List <decimal>();

            foreach (ExchangeBalance balance in list.OrderByDescending(item => item.TotalInBTC))
            {
                symbols.Add(balance.Symbol);
                totals.Add(balance.TotalInUSD);
            }

            decimal[] yValues = totals.ToArray();
            string[]  xValues = symbols.ToArray();

            Series series1 = chart.Series[0];

            series1["CollectedThreshold"]           = "1";
            series1["CollectedThresholdUsePercent"] = "true";
            series1["CollectedLabel"]      = "Below 1%";
            series1["CollectedLegendText"] = "Below 1%";
            series1["CollectedColor"]      = "Red";
            series1["CollectedToolTip"]    = "Below 1%";

            chart.Series["Default"].Font = PreferenceManager.GetFormFont(ParentForm);
            chart.Titles[0].Font         = chart.Series["Default"].Font;
            chart.Titles[0].Text         = symbols.Count + " " + exchange + " BALANCES BY PERCENTAGE (" + list.Sum(balance => balance.TotalInUSD).ToString("C") + ")";

            chart.Series["Default"].Points.DataBindXY(xValues, yValues);
            chart.Series["Default"].ChartType          = SeriesChartType.Pie;
            chart.Series["Default"]["PieLabelStyle"]   = "Outside";
            chart.Series["Default"]["PieDrawingStyle"] = "SoftEdge";

            chart.Series[0].ToolTip      = "Percent: #PERCENT";
            chart.Series[0].ToolTip      = "#VALX" + " : " + "#PERCENT" + " (" + "#VALY{$#,##0.00}" + ")";
            chart.Series[0].LabelToolTip = "#VALY{$#,##0.00}";
            chart.Series[0].Label        = "#VALX" + " (" + "#PERCENT" + ")";

            chart.ChartAreas[0].Area3DStyle.Enable3D    = true;
            chart.ChartAreas[0].Area3DStyle.Inclination = 0;
        }
        public void CheckWalletBalanceEstimationWithSpentAndUnConfirmedTransactions()
        {
            string dir        = AssureEmptyDir("TestData/WalletManagerTest/CheckWalletBalanceEstimationWithSpentAndUnConfirmedTransactions");
            var    dataFolder = new DataFolder(new NodeSettings {
                DataDir = dir
            });
            var loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>()))
            .Returns(new Mock <ILogger>().Object);
            Logs.Configure(loggerFactory.Object);

            var walletManager = new WalletManager(loggerFactory.Object, It.IsAny <ConnectionManager>(), Network.Main, new Mock <ConcurrentChain>().Object, NodeSettings.Default(),
                                                  dataFolder, new Mock <IWalletFeePolicy>().Object, new Mock <IAsyncLoopFactory>().Object, new NodeLifetime());

            // generate 3 wallet with 2 accounts containing 1000 external and 100 internal addresses each.
            walletManager.Wallets.Add(CreateWallet("wallet1"));
            this.AddAddressesToWallet(walletManager, 1000);

            var firstAccount = walletManager.Wallets.First().AccountsRoot.First().Accounts.First();

            // add two spent transactions
            for (int i = 1; i < 3; i++)
            {
                firstAccount.InternalAddresses.ElementAt(i).Transactions.Add(new TransactionData {
                    Amount = 10, BlockHeight = 10, SpendingDetails = new SpendingDetails()
                });
                firstAccount.ExternalAddresses.ElementAt(i).Transactions.Add(new TransactionData {
                    Amount = 10, BlockHeight = 10, SpendingDetails = new SpendingDetails()
                });
            }

            for (int i = 3; i < 5; i++)
            {
                firstAccount.InternalAddresses.ElementAt(i).Transactions.Add(new TransactionData {
                    Amount = 10
                });
                firstAccount.ExternalAddresses.ElementAt(i).Transactions.Add(new TransactionData {
                    Amount = 10
                });
            }

            Assert.Equal(0, firstAccount.GetSpendableAmount().ConfirmedAmount);
            Assert.Equal(40, firstAccount.GetSpendableAmount().UnConfirmedAmount);
        }
示例#21
0
        public static void ImportAccountWifTest()
        {
            Wallet        wallet        = new Wallet();
            WalletManager walletManager = new WalletManager(wallet);

            var account =
                walletManager.ImportAccount("L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP", "accoun1"); //wif
            var account2 = walletManager.ImportAccount("6PYVPVe1fQznphjbUxXP9KZJqPMVnVwCx5s5pr5axRJ8uHkMtZg97eT5kL",
                                                       "TestingOneTwoThree", "account2").Result;

            Assert.Equal(account2.Address, account.Address);          // make sure the importing from wif and importing from nep2 returns the same account
            var address       = "AStZHy8E6StCqYQbzMqi4poH7YNDHQKxvt"; // account address
            var addressScript = address.ToScriptHash();               // address to UInt160

            Assert.NotNull(account);
            Assert.Equal(account.Address, addressScript);
            Assert.Contains(account, wallet.Accounts);
        }
示例#22
0
        public RecoveryWordsViewModel(
            IScreen screen,
            KeyManager keyManager,
            Mnemonic mnemonic,
            WalletManager walletManager)
            : base(screen)
        {
            MnemonicWords = new List <RecoveryWordViewModel>();

            for (int i = 0; i < mnemonic.Words.Length; i++)
            {
                MnemonicWords.Add(new RecoveryWordViewModel(i + 1, mnemonic.Words[i]));
            }

            ContinueCommand = ReactiveCommand.Create(
                () => screen.Router.Navigate.Execute(
                    new ConfirmRecoveryWordsViewModel(HostScreen, MnemonicWords, keyManager, walletManager)));
        }
示例#23
0
        public MainWindowViewModel(Network network, UiConfig uiConfig, WalletManager walletManager, StatusBarViewModel statusBarViewModel, IShell shell)
        {
            Network       = network;
            UiConfig      = uiConfig;
            Shell         = shell;
            WalletManager = walletManager;
            _lockScreens  = new Stack <LockScreenViewModelBase>();

            _menuVisible = true;

            WindowState = uiConfig.WindowState;

            InitializeLockScreen();

            StatusBar = statusBarViewModel;

            DisplayWalletManager();
        }
        private async void BtnBarcodeClick(object sender, RoutedEventArgs e)
        {
            var dlg    = new WalletBarcodeItemDialog();
            var result = await dlg.ShowAsync();

            if (result != ContentDialogResult.Primary)
            {
                return;
            }

            var store = await WalletManager.RequestStoreAsync();

            dlg.Result.LogoImage = await(await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets")).GetFileAsync("StoreLogo.png");
            var id = "custom-" + Guid.NewGuid();
            await store.AddAsync(id, dlg.Result);

            await store.ShowAsync(id);
        }
示例#25
0
        public void CreateMultiSigTest()
        {
            string[] pubKeyString = new[] {
                "036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb",
                "0303897394935bb5418b1c1c4cf35513e276c6bd313ddd1330f113ec3dc34fbd0d",
                "02e2baf21e36df2007189d05b9e682f4192a101dcdf07eed7d6313625a930874b4"
            };

            var walletManager = new WalletManager("testwallet");

            var multiSigAccount    = walletManager.CreateMultiSigAccount(2, pubKeyString, "testMultiSig");
            var verificationScript = multiSigAccount.Contract.Script.ToHexString();
            var address            = "AJetuB7TxUkSmRNjot1G7FL5dDpNHE6QLZ";

            Assert.Equal(verificationScript,
                         $"5221036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb210303897394935bb5418b1c1c4cf35513e276c6bd313ddd1330f113ec3dc34fbd0d2102e2baf21e36df2007189d05b9e682f4192a101dcdf07eed7d6313625a930874b453ae");
            Assert.Equal(address, multiSigAccount.Address.ToAddress());
        }
示例#26
0
        public async Task <bool> Spend(Address address, ulong amount, byte[] data = null, byte[] asset = null)
        {
            address.Data = data;

            if (asset == null)
            {
                asset = Tests.zhash;
            }

            var tx = WalletManager.Sign(address, asset, amount);

            if (tx != null)
            {
                return((await NodeManager.Transmit(tx)) == BlockChain.BlockChain.TxResultEnum.Accepted);
            }

            return(false);
        }
示例#27
0
        private static Global CreateGlobal()
        {
            string dataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));

            Directory.CreateDirectory(dataDir);
            string torLogsFile = Path.Combine(dataDir, "TorLogs.txt");

            var uiConfig = new UiConfig(Path.Combine(dataDir, "UiConfig.json"));

            uiConfig.LoadOrCreateDefaultFile();
            var config = new Config(Path.Combine(dataDir, "Config.json"));

            config.LoadOrCreateDefaultFile();
            config.CorrectMixUntilAnonymitySet();
            var walletManager = new WalletManager(config.Network, new WalletDirectories(dataDir));

            return(new Global(dataDir, torLogsFile, config, uiConfig, walletManager));
        }
        public static async void ChangeDefaultAccount()
        {
            Wallet        wallet        = Wallet.FromJson(walletJson);
            WalletManager walletManager = new WalletManager(
                new NeoScanRestService(NeoScanNet.MainNet),
                new RpcClient(new Uri("http://seed4.travala.com:10332")),
                wallet);

            var account = await walletManager.CreateAccount("test1", "test123455");

            await walletManager.CreateAccount("test2", "test123455");

            walletManager.ChangeDefaultAccount(2);
            var defaultAccount   = walletManager.GetDefaultAccount();
            var accountToCompare = walletManager.GetAccount(account.Address.ToAddress());

            Assert.Equal(defaultAccount, accountToCompare);
        }
示例#29
0
        public void Given_GetMaximumSpendableAmountIsCalled_When_ThereAreNoConfirmedSpendableFound_Then_MaxAmountReturnsAsTheSumOfUnconfirmedTxs()
        {
            string dir        = AssureEmptyDir("TestData/WalletManagerTest/Given_GetMaximumSpendableAmountIsCalledForConfirmedTransactions_When_ThereAreNoConfirmedSpendableFound_Then_MaxAmountReturnsAsZero");
            var    dataFolder = new DataFolder(new NodeSettings {
                DataDir = dir
            });
            var walletFeePolicy = new Mock <IWalletFeePolicy>();

            walletFeePolicy.Setup(w => w.GetFeeRate(FeeType.Low.ToConfirmations())).Returns(new FeeRate(20000));

            var walletManager = new WalletManager(this.LoggerFactory.Object, Network.Main, new ConcurrentChain(Network.Main.GetGenesis().Header), NodeSettings.Default(),
                                                  dataFolder, new Mock <IWalletFeePolicy>().Object, new Mock <IAsyncLoopFactory>().Object, new NodeLifetime(), DateTimeProvider.Default);

            var walletTransactionHandler = new WalletTransactionHandler(this.LoggerFactory.Object, It.IsAny <ConcurrentChain>(), walletManager, walletFeePolicy.Object, Network.Main);

            HdAccount account = WalletTestsHelpers.CreateAccount("account 1");

            HdAddress accountAddress1 = WalletTestsHelpers.CreateAddress();

            accountAddress1.Transactions.Add(WalletTestsHelpers.CreateTransaction(new uint256(1), new Money(15000), null, null, null, new Key().ScriptPubKey));
            accountAddress1.Transactions.Add(WalletTestsHelpers.CreateTransaction(new uint256(2), new Money(10000), null, null, null, new Key().ScriptPubKey));

            HdAddress accountAddress2 = WalletTestsHelpers.CreateAddress();

            accountAddress2.Transactions.Add(WalletTestsHelpers.CreateTransaction(new uint256(3), new Money(20000), null, null, null, new Key().ScriptPubKey));
            accountAddress2.Transactions.Add(WalletTestsHelpers.CreateTransaction(new uint256(4), new Money(120000), null, null, null, new Key().ScriptPubKey));

            account.ExternalAddresses.Add(accountAddress1);
            account.InternalAddresses.Add(accountAddress2);

            var wallet = WalletTestsHelpers.CreateWallet("wallet1");

            wallet.AccountsRoot.Add(new AccountRoot()
            {
                Accounts = new List <HdAccount> {
                    account
                }
            });

            walletManager.Wallets.Add(wallet);

            (Money max, Money fee)result = walletTransactionHandler.GetMaximumSpendableAmount(new WalletAccountReference("wallet1", "account 1"), FeeType.Low, true);
            Assert.Equal(new Money(165000), result.max + result.fee);
        }
        private void RecoverWallet(WalletManagerViewModel owner)
        {
            WalletName    = Guard.Correct(WalletName);
            MnemonicWords = Guard.Correct(MnemonicWords);
            Password      = Guard.Correct(Password);        // Do not let whitespaces to the beginning and to the end.

            string walletFilePath = WalletManager.WalletDirectories.GetWalletFilePaths(WalletName).walletFilePath;

            if (string.IsNullOrWhiteSpace(WalletName))
            {
                NotificationHelpers.Error("Invalid wallet name.");
            }
            else if (File.Exists(walletFilePath))
            {
                NotificationHelpers.Error("Wallet name is already taken.");
            }
            else if (string.IsNullOrWhiteSpace(MnemonicWords))
            {
                NotificationHelpers.Error("Recovery Words were not supplied.");
            }
            else
            {
                var minGapLimit = int.Parse(MinGapLimit);
                var keyPath     = KeyPath.Parse(AccountKeyPath);

                try
                {
                    var mnemonic = new Mnemonic(MnemonicWords);
                    var km       = KeyManager.Recover(mnemonic, Password, filePath: null, keyPath, minGapLimit);
                    km.SetNetwork(Global.Network);
                    km.SetFilePath(walletFilePath);
                    WalletManager.AddWallet(km);

                    NotificationHelpers.Success("Wallet was recovered.");

                    owner.SelectLoadWallet(km);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    NotificationHelpers.Error(ex.ToUserFriendlyString());
                }
            }
        }