Exemplo n.º 1
0
 public Global(
     ITorManager torManager,
     IDataDirProvider dataDirProvider,
     Config config,
     UiConfig uiConfig,
     ChaincaseWalletManager walletManager,
     BitcoinStore bitcoinStore,
     ChaincaseSynchronizer synchronizer,
     FeeProviders feeProviders
     )
 {
     _torManager      = torManager;
     _dataDirProvider = dataDirProvider;
     _config          = config;
     _uiConfig        = uiConfig;
     _walletManager   = walletManager;
     _bitcoinStore    = bitcoinStore;
     _synchronizer    = synchronizer;
     _feeProviders    = feeProviders;
     using (BenchmarkLogger.Measure())
     {
         StoppingCts = new CancellationTokenSource();
         Logger.InitializeDefaults(Path.Combine(DataDir, "Logs.txt"));
         _uiConfig.LoadOrCreateDefaultFile();
     }
 }
Exemplo n.º 2
0
        public void RegisterServices(
            BitcoinStore bitcoinStore,
            WasabiSynchronizer syncer,
            NodesGroup nodes,
            ServiceConfiguration serviceConfiguration,
            IFeeProvider feeProvider,
            CoreNode coreNode = null)
        {
            if (State != WalletState.Uninitialized)
            {
                throw new InvalidOperationException($"{nameof(State)} must be {WalletState.Uninitialized}. Current state: {State}.");
            }

            BitcoinStore         = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
            Nodes                = Guard.NotNull(nameof(nodes), nodes);
            Synchronizer         = Guard.NotNull(nameof(syncer), syncer);
            ServiceConfiguration = Guard.NotNull(nameof(serviceConfiguration), serviceConfiguration);
            FeeProvider          = Guard.NotNull(nameof(feeProvider), feeProvider);
            CoreNode             = coreNode;

            ChaumianClient = new CoinJoinClient(Synchronizer, Network, KeyManager);

            TransactionProcessor = new TransactionProcessor(BitcoinStore.TransactionStore, KeyManager, ServiceConfiguration.DustThreshold, ServiceConfiguration.PrivacyLevelStrong);
            Coins = TransactionProcessor.Coins;

            TransactionProcessor.WalletRelevantTransactionProcessed += TransactionProcessor_WalletRelevantTransactionProcessedAsync;
            ChaumianClient.OnDequeue += ChaumianClient_OnDequeue;

            BitcoinStore.IndexStore.NewFilter += IndexDownloader_NewFilterAsync;
            BitcoinStore.IndexStore.Reorged   += IndexDownloader_ReorgedAsync;
            BitcoinStore.MempoolService.TransactionReceived += Mempool_TransactionReceived;

            State = WalletState.Initialized;
        }
 public TransactionBroadcaster(Network network, BitcoinStore bitcoinStore, HttpClientFactory httpClientFactory, WalletManager walletManager)
 {
     Network           = Guard.NotNull(nameof(network), network);
     BitcoinStore      = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
     HttpClientFactory = httpClientFactory;
     WalletManager     = Guard.NotNull(nameof(walletManager), walletManager);
 }
        private async Task <TransactionProcessor> CreateTransactionProcessorAsync([CallerMemberName] string callerName = "")
        {
            var datadir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Bench"));
            var dir     = Path.Combine(datadir, callerName, "TransactionStore");

            Console.WriteLine(dir);
            await IoHelpers.DeleteRecursivelyWithMagicDustAsync(dir);

            // Create the services.
            // 1. Create connection service.
            var nodes                = new NodesGroup(Network.Main);
            var bitcoinStore         = new BitcoinStore();
            var serviceConfiguration = new ServiceConfiguration(2, 2, 21, 50, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 45678), Money.Coins(0.0001m));

            // 2. Create wasabi synchronizer service.
            var synchronizer = new WasabiSynchronizer(Network.Main, bitcoinStore, () => new Uri("http://localhost:35474"), null);

            synchronizer.Start(requestInterval: TimeSpan.FromDays(1), TimeSpan.FromDays(1), 1000);

            // 3. Create key manager service.
            var keyManager = KeyManager.CreateNew(out _, "password");

            // 4. Create chaumian coinjoin client.
            var chaumianClient = new CoinJoinClient(synchronizer, Network.Main, keyManager);

            // 5. Create wallet service.
            await bitcoinStore.InitializeAsync(dir, Network.Main);

            var workDir      = Path.Combine(datadir, EnvironmentHelpers.GetMethodName());
            var feeProviders = new FeeProviders(new[] { synchronizer });

            var wallet = new WalletService(bitcoinStore, keyManager, synchronizer, nodes, workDir, serviceConfiguration, feeProviders);

            return(wallet.TransactionProcessor);
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (Network == Network.RegTest)
            {
                try
                {
                    EndPoint bitcoinCoreEndpoint = FullnodeP2PEndPoint;

                    Node node = await Node.ConnectAsync(Network.RegTest, bitcoinCoreEndpoint).ConfigureAwait(false);

                    Nodes.ConnectedNodes.Add(node);

                    RegTestMempoolServingNode = await Node.ConnectAsync(Network.RegTest, bitcoinCoreEndpoint).ConfigureAwait(false);

                    RegTestMempoolServingNode.Behaviors.Add(BitcoinStore.CreateUntrustedP2pBehavior());
                }
                catch (SocketException ex)
                {
                    Logger.LogError(ex);
                }
            }

            Nodes.Connect();

            var regTestMempoolServingNode = RegTestMempoolServingNode;

            if (regTestMempoolServingNode is not null)
            {
                regTestMempoolServingNode.VersionHandshake(stoppingToken);
                Logger.LogInfo("Start connecting to mempool serving regtest node...");
            }
        }
 public TransactionBroadcaster(Network network, BitcoinStore bitcoinStore, WasabiSynchronizer synchronizer, WalletManager walletManager)
 {
     Network       = Guard.NotNull(nameof(network), network);
     BitcoinStore  = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
     Synchronizer  = Guard.NotNull(nameof(synchronizer), synchronizer);
     WalletManager = Guard.NotNull(nameof(walletManager), walletManager);
 }
Exemplo n.º 7
0
        public Global(string dataDir, string torLogsFile, Config config, UiConfig uiConfig, WalletManager walletManager)
        {
            using (BenchmarkLogger.Measure())
            {
                CrashReporter = new CrashReporter();
                StoppingCts   = new CancellationTokenSource();
                DataDir       = dataDir;
                Config        = config;
                UiConfig      = uiConfig;
                TorLogsFile   = torLogsFile;

                Logger.InitializeDefaults(Path.Combine(DataDir, "Logs.txt"));

                HostedServices = new HostedServices();
                WalletManager  = walletManager;

                LegalDocuments = LegalDocuments.TryLoadAgreed(DataDir);

                WalletManager.OnDequeue += WalletManager_OnDequeue;
                WalletManager.WalletRelevantTransactionProcessed += WalletManager_WalletRelevantTransactionProcessed;

                var indexStore = new IndexStore(Network, new SmartHeaderChain());

                BitcoinStore = new BitcoinStore(
                    Path.Combine(DataDir, "BitcoinStore"), Network,
                    indexStore, new AllTransactionStore(), new MempoolService()
                    );

                SingleInstanceChecker = new SingleInstanceChecker(Network);
            }
        }
Exemplo n.º 8
0
        public Global(string dataDir, string torLogsFile, Config config, UiConfig uiConfig, WalletManager walletManager)
        {
            using (BenchmarkLogger.Measure())
            {
                StoppingCts = new CancellationTokenSource();
                DataDir     = dataDir;
                Config      = config;
                UiConfig    = uiConfig;
                TorSettings = new TorSettings(DataDir, torLogsFile, distributionFolderPath: EnvironmentHelpers.GetFullBaseDirectory());

                Logger.InitializeDefaults(Path.Combine(DataDir, "Logs.txt"));

                HostedServices = new HostedServices();
                WalletManager  = walletManager;

                LegalDocuments = LegalDocuments.TryLoadAgreed(DataDir);

                WalletManager.OnDequeue += WalletManager_OnDequeue;
                WalletManager.WalletRelevantTransactionProcessed += WalletManager_WalletRelevantTransactionProcessed;

                var networkWorkFolderPath = Path.Combine(DataDir, "BitcoinStore", Network.ToString());
                var transactionStore      = new AllTransactionStore(networkWorkFolderPath, Network);
                var indexStore            = new IndexStore(Path.Combine(networkWorkFolderPath, "IndexStore"), Network, new SmartHeaderChain());
                var mempoolService        = new MempoolService();
                var blocks = new FileSystemBlockRepository(Path.Combine(networkWorkFolderPath, "Blocks"), Network);

                BitcoinStore = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks);

                WasabiClientFactory wasabiClientFactory = Config.UseTor
                                        ? new WasabiClientFactory(Config.TorSocks5EndPoint, backendUriGetter: () => Config.GetCurrentBackendUri())
                                        : new WasabiClientFactory(torEndPoint: null, backendUriGetter: () => Config.GetFallbackBackendUri());

                Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, wasabiClientFactory);
            }
        }
Exemplo n.º 9
0
        public static async Task <(string password, IRPCClient rpc, Network network, Coordinator coordinator, ServiceConfiguration serviceConfiguration, BitcoinStore bitcoinStore, Backend.Global global)> InitializeTestEnvironmentAsync(
            RegTestFixture regTestFixture,
            int numberOfBlocksToGenerate,
            [CallerFilePath] string callerFilePath     = "",
            [CallerMemberName] string callerMemberName = "")
        {
            var global = regTestFixture.Global;

            await AssertFiltersInitializedAsync(regTestFixture, global);             // Make sure filters are created on the server side.

            if (numberOfBlocksToGenerate != 0)
            {
                await global.RpcClient.GenerateAsync(numberOfBlocksToGenerate);                 // Make sure everything is confirmed.
            }
            global.Coordinator.UtxoReferee.Clear();

            var network = global.RpcClient.Network;
            var serviceConfiguration = new ServiceConfiguration(MixUntilAnonymitySet.PrivacyLevelSome.ToString(), 2, 21, 50, regTestFixture.BackendRegTestNode.P2pEndPoint, Money.Coins(Constants.DefaultDustThreshold));

            var dir              = Tests.Common.GetWorkDir(callerFilePath, callerMemberName);
            var indexStore       = new IndexStore(Path.Combine(dir, "indexStore"), network, new SmartHeaderChain());
            var transactionStore = new AllTransactionStore(Path.Combine(dir, "transactionStore"), network);
            var mempoolService   = new MempoolService();
            var blocks           = new FileSystemBlockRepository(Path.Combine(dir, "blocks"), network);
            var bitcoinStore     = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks);
            await bitcoinStore.InitializeAsync();

            return("password", global.RpcClient, network, global.Coordinator, serviceConfiguration, bitcoinStore, global);
        }
Exemplo n.º 10
0
        public async Task MempoolNotifiesAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

            using var node = await coreNode.CreateNewP2pNodeAsync();

            try
            {
                var network          = coreNode.Network;
                var rpc              = coreNode.RpcClient;
                var dir              = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName());
                var indexStore       = new IndexStore(Path.Combine(dir, "indexStore"), network, new SmartHeaderChain());
                var transactionStore = new AllTransactionStore(Path.Combine(dir, "transactionStore"), network);
                var mempoolService   = new MempoolService();
                var blocks           = new FileSystemBlockRepository(Path.Combine(dir, "blocks"), network);
                var bitcoinStore     = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks);
                await bitcoinStore.InitializeAsync();

                await rpc.GenerateAsync(101);

                node.Behaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior());
                node.VersionHandshake();

                var addr = new Key().PubKey.GetSegwitAddress(network);

                var txNum        = 10;
                var eventAwaiter = new EventsAwaiter <SmartTransaction>(
                    h => bitcoinStore.MempoolService.TransactionReceived += h,
                    h => bitcoinStore.MempoolService.TransactionReceived -= h,
                    txNum);

                var txTasks = new List <Task <uint256> >();
                var batch   = rpc.PrepareBatch();
                for (int i = 0; i < txNum; i++)
                {
                    txTasks.Add(batch.SendToAddressAsync(addr, Money.Coins(1)));
                }
                var batchTask = batch.SendBatchAsync();

                var stxs = await eventAwaiter.WaitAsync(TimeSpan.FromSeconds(21));

                await batchTask;
                var   hashes = await Task.WhenAll(txTasks);

                foreach (var stx in stxs)
                {
                    Assert.Contains(stx.GetHash(), hashes);
                }
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                node.Disconnect();
                await coreNode.TryStopAsync();
            }
        }
Exemplo n.º 11
0
        public BroadcastTransactionViewModel(
            BitcoinStore store,
            Network network,
            TransactionBroadcaster broadcaster,
            SmartTransaction transaction)
        {
            Title = "Broadcast Transaction";

            var nullMoney  = new Money(-1L);
            var nullOutput = new TxOut(nullMoney, Script.Empty);

            var psbt = PSBT.FromTransaction(transaction.Transaction, network);

            TxOut GetOutput(OutPoint outpoint) =>
            store.TransactionStore.TryGetTransaction(outpoint.Hash, out var prevTxn)
                                        ? prevTxn.Transaction.Outputs[outpoint.N]
                                        : nullOutput;

            var inputAddressAmount = psbt.Inputs
                                     .Select(x => x.PrevOut)
                                     .Select(GetOutput)
                                     .ToArray();

            var outputAddressAmount = psbt.Outputs
                                      .Select(x => x.GetCoin().TxOut)
                                      .ToArray();

            var psbtTxn = psbt.GetOriginalTransaction();

            _transactionId     = psbtTxn.GetHash().ToString();
            _inputCount        = inputAddressAmount.Length;
            _inputCountString  = $" input{TextHelpers.AddSIfPlural(_inputCount)} and ";
            _outputCount       = outputAddressAmount.Length;
            _outputCountString = $" output{TextHelpers.AddSIfPlural(_outputCount)}.";
            _totalInputValue   = inputAddressAmount.Any(x => x.Value == nullMoney)
                                ? null
                                : inputAddressAmount.Select(x => x.Value).Sum();
            _totalOutputValue = outputAddressAmount.Any(x => x.Value == nullMoney)
                                ? null
                                : outputAddressAmount.Select(x => x.Value).Sum();
            _networkFee = TotalInputValue is null || TotalOutputValue is null
                                ? null
                                : TotalInputValue - TotalOutputValue;

            EnableCancel = true;

            EnableBack = false;

            this.WhenAnyValue(x => x.IsBusy)
            .Subscribe(x => EnableCancel = !x);

            var nextCommandCanExecute = this.WhenAnyValue(x => x.IsBusy)
                                        .Select(x => !x);

            NextCommand = ReactiveCommand.CreateFromTask(
                async() => await OnNext(broadcaster, transaction),
                nextCommandCanExecute);

            EnableAutoBusyOn(NextCommand);
        }
Exemplo n.º 12
0
        public OverviewViewModel(ChaincaseWalletManager walletManager, Config config, UiConfig uiConfig, BitcoinStore bitcoinStore, IMainThreadInvoker mainThreadInvoker)
        {
            _walletManager     = walletManager;
            _config            = config;
            _uiConfig          = uiConfig;
            _bitcoinStore      = bitcoinStore;
            _mainThreadInvoker = mainThreadInvoker;
            Transactions       = new ObservableCollection <TransactionViewModel>();

            if (_walletManager.HasDefaultWalletFile() && _walletManager.CurrentWallet == null)
            {
                _walletManager.SetDefaultWallet();
                Task.Run(async() => await LoadWalletAsync());

                TryWriteTableFromCache();
            }

            _hasSeed = this.WhenAnyValue(x => x._uiConfig.HasSeed)
                       .ToProperty(this, nameof(HasSeed));

            _isBackedUp = this.WhenAnyValue(x => x._uiConfig.IsBackedUp)
                          .ToProperty(this, nameof(IsBackedUp));

            var canBackUp = this.WhenAnyValue(x => x.HasSeed, x => x.IsBackedUp,
                                              (hasSeed, isBackedUp) => hasSeed && !isBackedUp);

            canBackUp.ToProperty(this, x => x.CanBackUp, out _canBackUp);

            Balance = _uiConfig.Balance;

            Initializing += OnInit;
            Initializing(this, EventArgs.Empty);
        }
Exemplo n.º 13
0
        public Global(INotificationManager notificationManager, ITorManager torManager, IDataDirProvider dataDirProvider)
        {
            TorManager          = torManager;
            NotificationManager = notificationManager;
            using (BenchmarkLogger.Measure())
            {
                StoppingCts = new CancellationTokenSource();
                DataDir     = dataDirProvider.Get();
                Directory.CreateDirectory(DataDir);
                Config   = new Config(Path.Combine(DataDir, "Config.json"));
                UiConfig = new UiConfig(Path.Combine(DataDir, "UiConfig.json"));

                Logger.InitializeDefaults(Path.Combine(DataDir, "Logs.txt"));

                UiConfig.LoadOrCreateDefaultFile();
                Config.LoadOrCreateDefaultFile();


                WalletManager            = new WalletManager(Network, new WalletDirectories(DataDir));
                WalletManager.OnDequeue += WalletManager_OnDequeue;
                WalletManager.WalletRelevantTransactionProcessed += WalletManager_WalletRelevantTransactionProcessed;

                var indexStore = new IndexStore(Network, new SmartHeaderChain());

                BitcoinStore = new BitcoinStore(
                    Path.Combine(DataDir, "BitcoinStore"), Network,
                    indexStore, new AllTransactionStore(), new MempoolService()
                    );
            }
        }
Exemplo n.º 14
0
        public WalletService(
            BitcoinStore bitcoinStore,
            KeyManager keyManager,
            WasabiSynchronizer syncer,
            CoinJoinClient chaumianClient,
            NodesGroup nodes,
            string workFolderDir,
            ServiceConfiguration serviceConfiguration,
            IFeeProvider feeProvider,
            CoreNode coreNode = null)
        {
            BitcoinStore         = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
            KeyManager           = Guard.NotNull(nameof(keyManager), keyManager);
            Nodes                = Guard.NotNull(nameof(nodes), nodes);
            Synchronizer         = Guard.NotNull(nameof(syncer), syncer);
            ChaumianClient       = Guard.NotNull(nameof(chaumianClient), chaumianClient);
            ServiceConfiguration = Guard.NotNull(nameof(serviceConfiguration), serviceConfiguration);
            FeeProvider          = Guard.NotNull(nameof(feeProvider), feeProvider);
            CoreNode             = coreNode;

            HandleFiltersLock = new AsyncLock();

            BlocksFolderPath = Path.Combine(workFolderDir, "Blocks", Network.ToString());
            RuntimeParams.SetDataDir(workFolderDir);

            BlockFolderLock = new AsyncLock();

            KeyManager.AssertCleanKeysIndexed();
            KeyManager.AssertLockedInternalKeysIndexed(14);

            TransactionProcessor = new TransactionProcessor(BitcoinStore.TransactionStore, KeyManager, ServiceConfiguration.DustThreshold, ServiceConfiguration.PrivacyLevelStrong);
            Coins = TransactionProcessor.Coins;

            TransactionProcessor.WalletRelevantTransactionProcessed += TransactionProcessor_WalletRelevantTransactionProcessedAsync;

            if (Directory.Exists(BlocksFolderPath))
            {
                if (Synchronizer.Network == Network.RegTest)
                {
                    Directory.Delete(BlocksFolderPath, true);
                    Directory.CreateDirectory(BlocksFolderPath);
                }
            }
            else
            {
                Directory.CreateDirectory(BlocksFolderPath);
            }

            var walletName = "UnnamedWallet";

            if (!string.IsNullOrWhiteSpace(KeyManager.FilePath))
            {
                walletName = Path.GetFileNameWithoutExtension(KeyManager.FilePath);
            }

            BitcoinStore.IndexStore.NewFilter += IndexDownloader_NewFilterAsync;
            BitcoinStore.IndexStore.Reorged   += IndexDownloader_ReorgedAsync;
            BitcoinStore.MempoolService.TransactionReceived += Mempool_TransactionReceived;
        }
Exemplo n.º 15
0
        private long _blockRequests;         // There are priority requests in queue.

        public WasabiSynchronizer(Network network, BitcoinStore bitcoinStore, Func <Uri> baseUriAction, EndPoint torSocks5EndPoint)
        {
            WasabiClient = new WasabiClient(baseUriAction, torSocks5EndPoint);
            Network      = Guard.NotNull(nameof(network), network);
            LastResponse = null;
            _running     = 0;
            Cancel       = new CancellationTokenSource();
            BitcoinStore = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
        }
Exemplo n.º 16
0
 public WalletManagerViewModel(WalletManager walletManager, UiConfig uiConfig, BitcoinStore bitcoinStore)
 {
     Model                           = walletManager;
     BitcoinStore                    = bitcoinStore;
     _walletDictionary               = new Dictionary <Wallet, WalletViewModelBase>();
     _walletActionsDictionary        = new Dictionary <WalletViewModelBase, List <NavBarItemViewModel> >();
     _actions                        = new ObservableCollection <NavBarItemViewModel>();
     _wallets                        = new ObservableCollection <WalletViewModelBase>();
     _loggedInAndSelectedAlwaysFirst = true;
Exemplo n.º 17
0
 public TransactionBroadcaster(Network network, BitcoinStore bitcoinStore, WasabiSynchronizer synchronizer, NodesGroup nodes, WalletManager walletManager, IRPCClient rpc)
 {
     Nodes         = Guard.NotNull(nameof(nodes), nodes);
     Network       = Guard.NotNull(nameof(network), network);
     BitcoinStore  = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
     Synchronizer  = Guard.NotNull(nameof(synchronizer), synchronizer);
     WalletManager = Guard.NotNull(nameof(walletManager), walletManager);
     RpcClient     = rpc;
 }
Exemplo n.º 18
0
        public Wallet(
            Network network,
            BitcoinStore bitcoinStore,
            KeyManager keyManager,
            WasabiSynchronizer syncer,
            NodesGroup nodes,
            string workFolderDir,
            ServiceConfiguration serviceConfiguration,
            IFeeProvider feeProvider,
            CoreNode coreNode = null)
        {
            Network              = Guard.NotNull(nameof(network), network);
            BitcoinStore         = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
            KeyManager           = Guard.NotNull(nameof(keyManager), keyManager);
            Nodes                = Guard.NotNull(nameof(nodes), nodes);
            Synchronizer         = Guard.NotNull(nameof(syncer), syncer);
            ServiceConfiguration = Guard.NotNull(nameof(serviceConfiguration), serviceConfiguration);
            FeeProvider          = Guard.NotNull(nameof(feeProvider), feeProvider);
            CoreNode             = coreNode;

            ChaumianClient    = new CoinJoinClient(Synchronizer, Network, keyManager);
            HandleFiltersLock = new AsyncLock();

            BlocksFolderPath = Path.Combine(workFolderDir, "Blocks", Network.ToString());
            RuntimeParams.SetDataDir(workFolderDir);

            BlockFolderLock = new AsyncLock();

            KeyManager.AssertCleanKeysIndexed();
            KeyManager.AssertLockedInternalKeysIndexed(14);

            TransactionProcessor = new TransactionProcessor(BitcoinStore.TransactionStore, KeyManager, ServiceConfiguration.DustThreshold, ServiceConfiguration.PrivacyLevelStrong);
            Coins = TransactionProcessor.Coins;

            TransactionProcessor.WalletRelevantTransactionProcessed += TransactionProcessor_WalletRelevantTransactionProcessedAsync;
            ChaumianClient.OnDequeue += ChaumianClient_OnDequeue;

            if (Directory.Exists(BlocksFolderPath))
            {
                if (Network == Network.RegTest)
                {
                    Directory.Delete(BlocksFolderPath, true);
                    Directory.CreateDirectory(BlocksFolderPath);
                }
            }
            else
            {
                Directory.CreateDirectory(BlocksFolderPath);
            }

            BitcoinStore.IndexStore.NewFilter += IndexDownloader_NewFilterAsync;
            BitcoinStore.IndexStore.Reorged   += IndexDownloader_ReorgedAsync;
            BitcoinStore.MempoolService.TransactionReceived += Mempool_TransactionReceived;

            State = WalletState.Initialized;
        }
Exemplo n.º 19
0
        private HashSet <string> GetLabels(WalletManager walletManager, BitcoinStore store)
        {
            // Don't refresh wallet list as it may be slow.
            IEnumerable <SmartLabel> labels = walletManager.GetWallets(refreshWalletList: false)
                                              .Select(x => x.KeyManager)
                                              .SelectMany(x => x.GetLabels());

            var txStore = store.TransactionStore;

            if (txStore is { })
Exemplo n.º 20
0
        private long _blockRequests;         // There are priority requests in queue.

        /// <param name="httpClientFactory">The class takes ownership of the instance.</param>
        public WasabiSynchronizer(BitcoinStore bitcoinStore, HttpClientFactory httpClientFactory)
        {
            LastResponse      = null;
            _running          = StateNotStarted;
            BitcoinStore      = bitcoinStore;
            HttpClientFactory = httpClientFactory;
            WasabiClient      = httpClientFactory.SharedWasabiClient;

            StopCts = new CancellationTokenSource();
        }
Exemplo n.º 21
0
 public TransactionBroadcaster(Network network, BitcoinStore bitcoinStore, WasabiSynchronizer synchronizer, NodesGroup nodes, RPCClient rpc)
 {
     Nodes              = Guard.NotNull(nameof(nodes), nodes);
     Network            = Guard.NotNull(nameof(network), network);
     BitcoinStore       = Guard.NotNull(nameof(bitcoinStore), bitcoinStore);
     Synchronizer       = Guard.NotNull(nameof(synchronizer), synchronizer);
     WalletServices     = new List <WalletService>();
     WalletServicesLock = new object();
     RpcClient          = rpc;
 }
Exemplo n.º 22
0
        public AddWalletPageViewModel(
            LegalDocuments legalDocuments,
            WalletManager walletManager,
            BitcoinStore store,
            Network network)
        {
            Title           = "Add Wallet";
            SelectionMode   = NavBarItemSelectionMode.Button;
            _legalDocuments = legalDocuments;

            this.WhenAnyValue(x => x.WalletName)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Select(x => !string.IsNullOrWhiteSpace(x))
            .Subscribe(x => OptionsEnabled = x && !Validations.Any);

            RecoverWalletCommand = ReactiveCommand.Create(
                () => { Navigate().To(new RecoverWalletViewModel(WalletName, network, walletManager)); });

            ImportWalletCommand = ReactiveCommand.Create(() => new ImportWalletViewModel(WalletName, walletManager));

            ConnectHardwareWalletCommand = ReactiveCommand.Create(() =>
            {
                Navigate().To(new ConnectHardwareWalletViewModel(WalletName, network, walletManager));
            });

            CreateWalletCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                var result = await NavigateDialog(
                    new EnterPasswordViewModel("Type the password of the wallet and click Continue."));

                if (result is { } password)
                {
                    IsBusy = true;

                    var(km, mnemonic) = await Task.Run(
                        () =>
                    {
                        var walletGenerator = new WalletGenerator(
                            walletManager.WalletDirectories.WalletsDir,
                            network)
                        {
                            TipHeight = store.SmartHeaderChain.TipHeight
                        };
                        return(walletGenerator.GenerateWallet(WalletName, password));
                    });

                    Navigate().To(new RecoveryWordsViewModel(km, mnemonic, walletManager), NavigationMode.Clear);

                    IsBusy = false;
                }
            });

            this.ValidateProperty(x => x.WalletName, errors => ValidateWalletName(errors, walletManager, WalletName));
        }
Exemplo n.º 23
0
        private long _blockRequests;         // There are priority requests in queue.

        public WasabiSynchronizer(Network network, BitcoinStore bitcoinStore, WasabiClientFactory wasabiClientFactory)
        {
            Network             = network;
            LastResponse        = null;
            _running            = StateNotStarted;
            BitcoinStore        = bitcoinStore;
            WasabiClientFactory = wasabiClientFactory;
            WasabiClient        = wasabiClientFactory.NewBackendClient();

            Cancel = new CancellationTokenSource();
        }
Exemplo n.º 24
0
        public TransactionDetailsViewModel(TransactionSummary transactionSummary, BitcoinStore bitcoinStore, Wallet wallet, IObservable <Unit> updateTrigger)
        {
            _bitcoinStore  = bitcoinStore;
            _wallet        = wallet;
            _updateTrigger = updateTrigger;

            NextCommand = ReactiveCommand.Create(OnNext);
            CopyTransactionIdCommand = ReactiveCommand.CreateFromTask(OnCopyTransactionId);

            UpdateValues(transactionSummary);
        }
 public WalletManagerViewModel(WalletManager walletManager, UiConfig uiConfig, BitcoinStore bitcoinStore,
                               LegalChecker legalChecker, TransactionBroadcaster broadcaster)
 {
     WalletManager            = walletManager;
     BitcoinStore             = bitcoinStore;
     LegalChecker             = legalChecker;
     _walletDictionary        = new Dictionary <Wallet, WalletViewModelBase>();
     _walletActionsDictionary = new Dictionary <WalletViewModelBase, List <NavBarItemViewModel> >();
     _actions = new ObservableCollection <NavBarItemViewModel>();
     _wallets = new ObservableCollection <WalletViewModelBase>();
     _loggedInAndSelectedAlwaysFirst = true;
     _transactionBroadcaster         = broadcaster;
Exemplo n.º 26
0
        public async Task MempoolNotifiesAsync()
        {
            var coreNode = await TestNodeBuilder.CreateAsync();

            using var node = await coreNode.CreateP2pNodeAsync();

            try
            {
                var rpc = coreNode.RpcClient;
                await rpc.GenerateAsync(101);

                var network      = rpc.Network;
                var bitcoinStore = new BitcoinStore();

                var dir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetMethodName());
                await bitcoinStore.InitializeAsync(dir, network);

                node.Behaviors.Add(bitcoinStore.CreateMempoolBehavior());
                node.VersionHandshake();

                var addr = new Key().PubKey.GetSegwitAddress(network);

                var txNum        = 10;
                var eventAwaiter = new EventsAwaiter <SmartTransaction>(
                    h => bitcoinStore.MempoolService.TransactionReceived += h,
                    h => bitcoinStore.MempoolService.TransactionReceived -= h,
                    txNum);

                var txTasks = new List <Task <uint256> >();
                var batch   = rpc.PrepareBatch();
                for (int i = 0; i < txNum; i++)
                {
                    txTasks.Add(batch.SendToAddressAsync(addr, Money.Coins(1)));
                }
                var batchTask = batch.SendBatchAsync();

                var stxs = await eventAwaiter.WaitAsync(TimeSpan.FromSeconds(21));

                await batchTask;
                var   hashes = await Task.WhenAll(txTasks);

                foreach (var stx in stxs)
                {
                    Assert.Contains(stx.GetHash(), hashes);
                }
            }
            finally
            {
                node.Disconnect();
                await coreNode.StopAsync();
            }
        }
Exemplo n.º 27
0
        public CoinViewModel(ChaincaseWalletManager walletManager, Config config, BitcoinStore bitcoinStore, SmartCoin model)
        {
            _walletManager = walletManager;
            _config        = config;
            _bitcoinStore  = bitcoinStore;
            Model          = model;

            Disposables = new CompositeDisposable();

            _coinJoinInProgress = Model.WhenAnyValue(x => x.CoinJoinInProgress)
                                  .ObserveOn(RxApp.MainThreadScheduler)
                                  .ToProperty(this, x => x.CoinJoinInProgress)
                                  .DisposeWith(Disposables);

            _unspent = Model.WhenAnyValue(x => x.Unspent).ToProperty(this, x => x.Unspent, scheduler: RxApp.MainThreadScheduler)
                       .DisposeWith(Disposables);

            _confirmed = Model.WhenAnyValue(x => x.Confirmed).ToProperty(this, x => x.Confirmed, scheduler: RxApp.MainThreadScheduler)
                         .DisposeWith(Disposables);

            _unavailable = Model.WhenAnyValue(x => x.Unavailable).ToProperty(this, x => x.Unavailable, scheduler: RxApp.MainThreadScheduler)
                           .DisposeWith(Disposables);

            this.WhenAnyValue(x => x.Status)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => this.RaisePropertyChanged(nameof(ToolTip)));

            _cluster = Model
                       .WhenAnyValue(x => x.Clusters, x => x.Clusters.Labels)
                       .Select(x => x.Item2.ToString())
                       .ToProperty(this, x => x.Clusters, scheduler: RxApp.MainThreadScheduler)
                       .DisposeWith(Disposables);

            Observable
            .Merge(Model.WhenAnyValue(x => x.IsBanned, x => x.SpentAccordingToBackend, x => x.CoinJoinInProgress).Select(_ => Unit.Default))
            .Merge(Observable.FromEventPattern(_walletManager.CurrentWallet.ChaumianClient, nameof(_walletManager.CurrentWallet.ChaumianClient.StateUpdated)).Select(_ => Unit.Default))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => RefreshSmartCoinStatus())
            .DisposeWith(Disposables);

            _bitcoinStore.SmartHeaderChain
            .WhenAnyValue(x => x.TipHeight).Select(_ => Unit.Default)
            .Merge(Model.WhenAnyValue(x => x.Height).Select(_ => Unit.Default))
            .Throttle(TimeSpan.FromSeconds(0.1))                     // DO NOT TAKE THIS THROTTLE OUT, OTHERWISE SYNCING WITH COINS IN THE WALLET WILL STACKOVERFLOW!
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ => this.RaisePropertyChanged(nameof(Confirmations)))
            .DisposeWith(Disposables);
        }
Exemplo n.º 28
0
        public HistoryViewModel(Wallet wallet, UiConfig uiConfig, IObservable <Unit> updateTrigger)
        {
            _wallet                = wallet;
            _bitcoinStore          = wallet.BitcoinStore;
            _showCoinJoin          = uiConfig.ShowCoinJoinInHistory;
            _transactionSourceList = new SourceList <HistoryItemViewModel>();

            var coinJoinFilter = this.WhenAnyValue(x => x.ShowCoinJoin).Select(CoinJoinFilter);

            _transactionSourceList
            .Connect()
            .Filter(coinJoinFilter)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Sort(SortExpressionComparer <HistoryItemViewModel> .Descending(x => x.OrderIndex))
            .Bind(out _transactions)
            .Subscribe();

            this.WhenAnyValue(x => x.ShowCoinJoin)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(showCoinJoin => uiConfig.ShowCoinJoinInHistory = showCoinJoin);

            this.WhenAnyValue(x => x.SelectedItem)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(selectedItem =>
            {
                if (selectedItem is null)
                {
                    return;
                }

                Navigate(NavigationTarget.DialogScreen).To(new TransactionDetailsViewModel(selectedItem.TransactionSummary, _bitcoinStore, wallet, updateTrigger));
            });

            this.WhenAnyValue(x => x.SelectedItem)
            .Throttle(TimeSpan.FromMilliseconds(100))
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ =>
            {
                SelectedItem = null;
            });

            updateTrigger.Subscribe(async _ => await UpdateAsync());
            RxApp.MainThreadScheduler.Schedule(async() => await UpdateAsync());
        }
Exemplo n.º 29
0
    public Global(string dataDir, Config config, UiConfig uiConfig, WalletManager walletManager)
    {
        using (BenchmarkLogger.Measure())
        {
            DataDir     = dataDir;
            Config      = config;
            UiConfig    = uiConfig;
            TorSettings = new TorSettings(DataDir, distributionFolderPath: EnvironmentHelpers.GetFullBaseDirectory(), Config.TerminateTorOnExit, Environment.ProcessId);

            HostedServices = new HostedServices();
            WalletManager  = walletManager;

            var networkWorkFolderPath = Path.Combine(DataDir, "BitcoinStore", Network.ToString());
            AllTransactionStore = new AllTransactionStore(networkWorkFolderPath, Network);
            SmartHeaderChain smartHeaderChain = new(maxChainSize : 20_000);
            IndexStore = new IndexStore(Path.Combine(networkWorkFolderPath, "IndexStore"), Network, smartHeaderChain);
            var mempoolService = new MempoolService();
            var blocks         = new FileSystemBlockRepository(Path.Combine(networkWorkFolderPath, "Blocks"), Network);

            BitcoinStore = new BitcoinStore(IndexStore, AllTransactionStore, mempoolService, blocks);

            if (Config.UseTor)
            {
                BackendHttpClientFactory  = new HttpClientFactory(TorSettings.SocksEndpoint, backendUriGetter: () => Config.GetCurrentBackendUri());
                ExternalHttpClientFactory = new HttpClientFactory(TorSettings.SocksEndpoint, backendUriGetter: null);
            }
            else
            {
                BackendHttpClientFactory  = new HttpClientFactory(torEndPoint: null, backendUriGetter: () => Config.GetFallbackBackendUri());
                ExternalHttpClientFactory = new HttpClientFactory(torEndPoint: null, backendUriGetter: null);
            }

            Synchronizer           = new WasabiSynchronizer(BitcoinStore, BackendHttpClientFactory);
            LegalChecker           = new(DataDir);
            TransactionBroadcaster = new TransactionBroadcaster(Network, BitcoinStore, BackendHttpClientFactory, WalletManager);

            RoundStateUpdaterCircuit = new PersonCircuit();

            Cache = new MemoryCache(new MemoryCacheOptions
            {
                SizeLimit = 1_000,
                ExpirationScanFrequency = TimeSpan.FromSeconds(30)
            });
Exemplo n.º 30
0
        public AddWalletPageViewModel(NavigationStateViewModel navigationState, WalletManager walletManager,
                                      BitcoinStore store, Network network) : base(navigationState, NavigationTarget.DialogScreen)
        {
            Title = "Add Wallet";

            this.WhenAnyValue(x => x.WalletName)
            .Select(x => !string.IsNullOrWhiteSpace(x))
            .Subscribe(x => OptionsEnabled = x && !Validations.Any);

            RecoverWalletCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                NavigateTo(new RecoverWalletViewModel(navigationState, WalletName, network, walletManager), NavigationTarget.DialogScreen);
            });

            CreateWalletCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                var enterPassword = new EnterPasswordViewModel(
                    navigationState,
                    NavigationTarget.DialogScreen,
                    "Type the password of the wallet and click Continue.");

                NavigateTo(enterPassword, NavigationTarget.DialogScreen);

                var result = await enterPassword.GetDialogResultAsync();

                if (result is { } password)
                {
                    var(km, mnemonic) = await Task.Run(
                        () =>
                    {
                        var walletGenerator = new WalletGenerator(
                            walletManager.WalletDirectories.WalletsDir,
                            network)
                        {
                            TipHeight = store.SmartHeaderChain.TipHeight
                        };
                        return(walletGenerator.GenerateWallet(WalletName, password));
                    });

                    NavigateTo(new RecoveryWordsViewModel(navigationState, km, mnemonic, walletManager), NavigationTarget.DialogScreen, true);
                }