Esempio n. 1
0
        public static async Task InitializeWalletServiceAsync(KeyManager keyManager)
        {
            using (CancelWalletServiceInitialization = new CancellationTokenSource())
            {
                var token = CancelWalletServiceInitialization.Token;
                while (!Initialized)
                {
                    await Task.Delay(100, token);
                }

                if (Config.UseTor.Value)
                {
                    ChaumianClient = new CcjClient(Synchronizer, Network, keyManager, () => Config.GetCurrentBackendUri(), Config.GetTorSocks5EndPoint());
                }
                else
                {
                    ChaumianClient = new CcjClient(Synchronizer, Network, keyManager, Config.GetFallbackBackendUri(), null);
                }
                WalletService = new WalletService(BitcoinStore, keyManager, Synchronizer, ChaumianClient, MemPoolService, Nodes, DataDir, Config.ServiceConfiguration);

                ChaumianClient.Start();
                Logger.LogInfo("Start Chaumian CoinJoin service...");

                Logger.LogInfo("Starting WalletService...");
                await WalletService.InitializeAsync(token);

                Logger.LogInfo("WalletService started.");

                token.ThrowIfCancellationRequested();
                WalletService.Coins.CollectionChanged += Coins_CollectionChanged;
            }
            CancelWalletServiceInitialization = null;             // Must make it null explicitly, because dispose won't make it null.
        }
Esempio n. 2
0
        public async Task FailCreateWalletTest4()
        {
            WalletService walletService = new WalletService(CoreUnitOfWork, BankRoutingService, FeeService, Configuration);
            string        walletPass    = await walletService.CreateWallet("1203977780011", "Pera", "Peric", 1, "360123456", "1234");

            await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() => await walletService.CreateWallet("1203977780011", "Pera", "Peric", 1, "360123456", "1234"), $"Wallet already exists");
        }
        public AddAddressViewModel(WalletService ws, PoolingService ps)
        {
            _poolingService = ps;
            _walletService  = ws;

            Task.Run(() => _walletService.GetAvailabeTickers().ContinueWith((result) =>
            {
                if (result.Exception == null)
                {
                    var tickerSelected = new TickerDTO()
                    {
                        CoinSymbol = "Auto Detect",
                        Degraded   = false
                    };
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        TickerList.Add(tickerSelected);
                        foreach (var ticker in result.Result.OrderBy(o => o.CoinSymbol).ToList())
                        {
                            TickerList.Add(ticker);
                        }
                        NotifyOfPropertyChange(() => TickerList);
                        SelectedTicker = tickerSelected;
                    });
                }
            }));
        }
        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);
        }
Esempio n. 5
0
 public LightningController(
     BTCPayService btcpayService,
     WalletService walletService)
 {
     _btcpayService = btcpayService;
     _walletService = walletService;
 }
Esempio n. 6
0
        public async Task TestWalletWithdrawFailTooMuchMoney()
        {
            try
            {
                //Arrange
                WalletService walletService = new WalletService(_coreUnitOfWork,
                                                                new RakicRaiffeisenBrosBankService(),
                                                                new PassService(TestConfigurations.PassMin, TestConfigurations.PassMin),
                                                                TestConfigurations.NumberOfDaysBeforeComission,
                                                                new TransferFactory(TestConfigurations.PercentageComissionStartingAmount,
                                                                                    TestConfigurations.FixedComission,
                                                                                    TestConfigurations.PercentageComission),
                                                                TestConfigurations.MaxWithdraw, TestConfigurations.MaxDeposit);

                var result = await walletService.Withdraw(
                    "2609992760003", "111111", 1000001);

                var wallet = await _coreUnitOfWork.WalletRepository.GetById(result.Id);

                Assert.Fail("Expected error not thrown");
            }
            catch (WalletServiceException ex)
            {
                Assert.IsTrue(ex is WalletServiceException);
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
Esempio n. 7
0
        public async Task CalculateTransferFeeFixedFeeSuccessTest()
        {
            try
            {
                //Arrange
                Configuration["FirstTransactionFreeEachMonth"] = "False";
                var    walletService = new WalletService(CoreUnitOfWork, BankRoutingService, Configuration, FeeService);
                string password      = await walletService.CreateWallet("ime", "prezime", "0605996781029", (short)BankType.BrankoBank, "1234", "123456789876543210");

                //Act
                decimal fee1 = await walletService.CalculateTransferFee("0605996781029", password, 1);

                decimal fee2 = await walletService.CalculateTransferFee("0605996781029", password, 5000);

                decimal fee3 = await walletService.CalculateTransferFee("0605996781029", password, 9999);

                //Assert
                Assert.AreEqual(100, fee1, "Fee1 must be 100.00 RSD.");
                Assert.AreEqual(100, fee2, "Fee2 must be 100.00 RSD.");
                Assert.AreEqual(100, fee3, "Fee3 must be 100.00 RSD.");
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
            finally
            {
                Configuration["FirstTransactionFreeEachMonth"] = "True";
            }
        }
Esempio n. 8
0
        public async Task BlockWallet()
        {
            try
            {
                //Arrange
                WalletService walletService = new WalletService(_coreUnitOfWork,
                                                                new RakicRaiffeisenBrosBankService(),
                                                                new PassService(TestConfigurations.PassMin, TestConfigurations.PassMin),
                                                                TestConfigurations.NumberOfDaysBeforeComission,
                                                                new TransferFactory(TestConfigurations.PercentageComissionStartingAmount,
                                                                                    TestConfigurations.FixedComission,
                                                                                    TestConfigurations.PercentageComission),
                                                                TestConfigurations.MaxWithdraw, TestConfigurations.MaxDeposit);

                var result = await walletService.BlockWallet("2609992760000");

                var wallet = await _coreUnitOfWork.WalletRepository.GetById(result.Id);

                Assert.AreNotEqual(null, wallet, "Wallet must not be null");
                Assert.AreEqual(true, wallet.IsBlocked, "Wallet is not blocked");
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
Esempio n. 9
0
        public void GetWalletDetailsById_ValidWalletId_ReturnsBalanceForAnExistingWallet(Guid walletId, string expTransactionId, int expVersion, int expCoins)
        {
            using (var mock = AutoMock.GetLoose())
            {
                Wallet expected = new Wallet
                {
                    WalletId        = new Guid("1d4e7d81-ce9d-457b-b056-0f883baa783d"),
                    TransactionType = Const.Credit,
                    Coins           = expCoins,
                    TransactionId   = expTransactionId,
                    Version         = expVersion
                };

                IEnumerable <Wallet> response = new List <Wallet> {
                    expected
                };
                var walletRepo = new Mock <IWalletRepository>();
                walletRepo.Setup(p => p.GetWalletById(It.IsAny <Guid>())).Returns(response);
                walletRepo.Setup(p => p.AddWalletData(expected));
                WalletService walletService = new WalletService(walletRepo.Object);

                walletService.CreateAndCreditWallet(expected);
                var actual = walletService.GetWalletDetailsById(walletId);

                Assert.Equal(expected.Coins, actual.Coins);
                Assert.Equal(expected.TransactionId, actual.TransactionId);
                Assert.Equal(expected.Version, actual.Version);
            }
        }
Esempio n. 10
0
        public async Task CalculateTransferFeeFirstTransferInMonthNoFeeSuccessTest()
        {
            try
            {
                //Arrange
                var    walletService = new WalletService(CoreUnitOfWork, BankRoutingService, Configuration, FeeService);
                string password      = await walletService.CreateWallet("ime", "prezime", "0605996781029", (short)BankType.BrankoBank, "1234", "123456789876543210");

                Wallet wallet = await CoreUnitOfWork.WalletRepository.GetById("0605996781029");

                //Act
                decimal fee1 = await walletService.CalculateTransferFee("0605996781029", password, 10000);

                var date  = new SqlParameter("@LastTransferDateTime", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                var query = DbContext.Database
                            .ExecuteSqlRaw("UPDATE Wallets SET LastTransferDateTime = @LastTransferDateTime", date);
                DbContext.Entry(wallet).Reload();

                decimal fee2 = await walletService.CalculateTransferFee("0605996781029", password, 100000);

                //Assert
                Assert.AreEqual(0, fee1, "Fee1 must be 0.00 RSD.");
                Assert.AreEqual(1000, fee2, "Fee2 must be 1000.00 RSD.");
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
Esempio n. 11
0
        public void CreateAndCreditWallet_DuplicateCredit_ReturnsStatusCodeAcceptedAndBalance(int coins, string transactionId, int version, HttpStatusCode expHttpCode, int expBalance)
        {
            using (var mock = AutoMock.GetLoose())
            {
                Wallet payload = new Wallet
                {
                    WalletId        = new Guid("1d4e7d81-ce9d-457b-b056-0f883baa783d"),
                    TransactionType = Const.Credit,
                    Coins           = coins,
                    TransactionId   = transactionId,
                    Version         = version
                };

                IEnumerable <Wallet> response = new List <Wallet>()
                {
                    payload
                };
                var walletRepo = new Mock <IWalletRepository>();
                walletRepo.Setup(p => p.GetWalletById(It.IsAny <Guid>())).Returns(response);
                walletRepo.Setup(p => p.AddWalletData(payload));
                WalletService walletService = new WalletService(walletRepo.Object);

                var actual = walletService.CreateAndCreditWallet(payload);

                Assert.Equal(expHttpCode, actual.Item1);
                Assert.Equal(expBalance, actual.Item2);
            }
        }
Esempio n. 12
0
        public async Task GetBalanceAsync_NoPreviousTransactions_Returns0()
        {
            //// Arrange

            // Setup Mocks

            Mock <IWalletRepository> walletRepositoryMock = new Mock <IWalletRepository>();

            walletRepositoryMock
            .Setup(walletRepository => walletRepository.GetLastWalletEntryAsync())
            .Returns(Task.FromResult(default(WalletEntry)));

            IWalletRepository walletRepository = walletRepositoryMock.Object;

            // Initialize SUT

            IWalletService walletService = new WalletService(walletRepository);

            // Set Expectations

            Balance expectedBalance = new Balance {
                Amount = 0
            };

            //// Act

            Balance actualBalance = await walletService.GetBalanceAsync();

            //// Assert

            actualBalance.ShouldCompare(expectedBalance);

            walletRepositoryMock.Verify(walletRepository => walletRepository.GetLastWalletEntryAsync(), Times.Once);
            walletRepositoryMock.VerifyNoOtherCalls();
        }
Esempio n. 13
0
 public WalletController(FridayCoinContext context)
 {
     _context            = context;
     _coinService        = new FridayCoinService(context);
     _transactionService = new TransactionService(context, _coinService);
     _walletService      = new WalletService(context, _coinService);
 }
        //Get api/wallet
        public IHttpActionResult GetWallet()
        {
            WalletService walletService = CreateWalletService();
            var           wallets       = walletService.GetWallet();

            return(Ok(wallets));
        }
        public async Task CallWalletsApi()
        {
            // Arrange
            var httpMessageHandler = new Mock <HttpMessageHandler>();
            var httpClient         = httpMessageHandler.CreateClient();
            var list = new List <Models.Wallet>
            {
                new Models.Wallet
                {
                    Id      = 1,
                    Name    = "Private",
                    Balance = 999.95m
                }
            };

            httpMessageHandler.SetupRequest(HttpMethod.Get, "https://localhost:5003/api/wallets")
            .ReturnsResponse(JsonConvert.SerializeObject(list), "application/json");
            var httpContext = new Mock <IHttpContextAccessor>();

            httpContext.SetupGet(m => m.HttpContext.Request.Headers["Authorization"]).Returns("Bearer XYZ");
            var walletsService = new WalletService(httpClient, httpContext.Object);

            // Act
            var wallets = await walletsService.GetWallets();

            // Assert
            httpMessageHandler.VerifyAnyRequest(Times.Once());
            // Assert.Equal(list, wallets); // TODO: check why it doesn't work
        }
        public async Task SuccessWalletWithdrawTest()
        {
            try
            {
                string jmbg = "2904992785075";
                //Arrange
                var    walletService = new WalletService(CoreUnitOfWork, BankRoutingService, FeeService, Configuration);
                string password      = await walletService.CreateWallet(jmbg, "TestIme", "TestPrezime", (short)BankType.FirstBank, "360123456789999874", "1234");

                await walletService.Deposit(jmbg, password, 2000m);

                //Act

                await walletService.Withdraw(jmbg, password, 1000m);

                //Assert
                Wallet wallet = await CoreUnitOfWork.WalletRepository.GetById(jmbg);

                Assert.AreEqual(1000m, wallet.Balance, "Balance must be 1000");
                Assert.AreNotEqual(0, wallet.Transactions.Count(), "Transaction count must be different than 0");
                Assert.AreEqual(TransactionType.Withdraw, wallet.Transactions.FirstOrDefault(transaction => transaction.Type == TransactionType.Withdraw).Type);
                Assert.AreEqual(1000m, wallet.Transactions.FirstOrDefault(transaction => transaction.Type == TransactionType.Withdraw).Amount, $"Transaction amount must be 10000.");
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
        public async Task ThrowException_WhenAParameter_IsNotPassed()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_WhenAParameter_IsNotPassed")
                             .Options;

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var amountsDictionary = Enum.GetNames(typeof(TransactionType)).ToDictionary(name => name, value => 0m);

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 0,
                User     = user,
            };

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = null // here there is no passed parameter
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            var getCurrencySymbol = CultureReferences.CurrencySymbols.TryGetValue(userWallet.Currency.ToString(), out string currencySymbol);
            var currencies        = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);
                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.GetUserWallet(user));
            }
        }
Esempio n. 18
0
        private async Task TryWalletDeposit_OnBlockedWallet()
        {
            //Arrange
            WalletService walletService = new WalletService(_coreUnitOfWork,
                                                            new RakicRaiffeisenBrosBankService(),
                                                            new PassService(TestConfigurations.PassMin, TestConfigurations.PassMin),
                                                            TestConfigurations.NumberOfDaysBeforeComission,
                                                            new TransferFactory(TestConfigurations.PercentageComissionStartingAmount,
                                                                                TestConfigurations.FixedComission,
                                                                                TestConfigurations.PercentageComission),
                                                            TestConfigurations.MaxWithdraw, TestConfigurations.MaxDeposit);

            try
            {
                var result = await walletService.Deposit(
                    "2609992760000", "111111", 1000);

                Assert.Fail("Expected error not thrown");
            }
            catch (WalletServiceException ex)
            {
                var wallet = await walletService.GetWallet("2609992760000", "111111");

                Assert.AreEqual(20000, wallet.Balance, "Balance doesn't match");
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
        public async Task SuccessGetWalletTransactionsByDateTest()
        {
            try
            {
                string jmbg = "2904992785075";
                //Arrange
                var    walletService = new WalletService(CoreUnitOfWork, BankRoutingService, FeeService, Configuration);
                string password      = await walletService.CreateWallet(jmbg, "TestIme", "TestPrezime", (short)BankType.FirstBank, "360123456789999874", "1234");

                await walletService.Deposit(jmbg, password, 1000m);

                //Act
                var walletTransactionsDTO = await walletService.GetWalletTransactionsByDate(jmbg, password, DateTime.Now);

                //Assert
                Wallet wallet = await CoreUnitOfWork.WalletRepository.GetFirstOrDefaultWithIncludes(w => w.JMBG == jmbg,
                                                                                                    w => w.Transactions.Where(t => t.TransactionDateTime.Date == DateTime.Now.Date));

                Assert.AreEqual(walletTransactionsDTO.JMBG, wallet.JMBG);
                Assert.AreEqual(walletTransactionsDTO.Balance, wallet.Balance);
                Assert.AreEqual(walletTransactionsDTO.Transactions.Count, 1);
                Assert.AreEqual(walletTransactionsDTO.Transactions.Count, wallet.Transactions.Count);
                Assert.AreEqual(walletTransactionsDTO.Transactions.First().Type, TransactionType.Deposit);
                Assert.AreEqual(walletTransactionsDTO.Transactions.First().Amount, 1000m);
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
Esempio n. 20
0
        public async Task TestWalletWithdraw()
        {
            //starts with 20000
            try
            {
                //Arrange
                WalletService walletService = new WalletService(_coreUnitOfWork,
                                                                new RakicRaiffeisenBrosBankService(),
                                                                new PassService(TestConfigurations.PassMin, TestConfigurations.PassMin),
                                                                TestConfigurations.NumberOfDaysBeforeComission,
                                                                new TransferFactory(TestConfigurations.PercentageComissionStartingAmount,
                                                                                    TestConfigurations.FixedComission,
                                                                                    TestConfigurations.PercentageComission),
                                                                TestConfigurations.MaxWithdraw, TestConfigurations.MaxDeposit);

                var result = await walletService.Withdraw(
                    "2609992760003", "111111", 1000);

                var wallet = await _coreUnitOfWork.WalletRepository.GetById(result.Id);

                Assert.AreEqual(19000, wallet.Balance, "Balance doesn't match");
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
Esempio n. 21
0
        private async void UpdateView(object state)
        {
            if (PoloniexClient != null)
            {
                if (semaphoreSlim != null)
                {
                    await semaphoreSlim.WaitAsync();

                    try
                    {
                        MarketService.Instance().MarketList = await PoloniexClient.Markets.GetSummaryAsync();

                        WalletService.Instance().WalletList = await PoloniexClient.Wallet.GetBalancesAsync();

                        try
                        {
                            FachadaWSSGSService.Instance().getUltimoValorVOResponse = await FachadaWSSGS.getUltimoValorVOAsync(10813);
                        }
                        catch
                        {
                        }

                        await ucHeader.LoadLoanOffersAsync(PoloniexClient);
                    }
                    finally
                    {
                        if (semaphoreSlim != null)
                        {
                            semaphoreSlim.Release();
                        }
                    }
                }
            }
        }
        public async Task RetrieveWalletIfExists()
        {
            var contextOptions = new DbContextOptionsBuilder <CasinoContext>()
                                 .UseInMemoryDatabase(databaseName: "RetrieveWalletIfExists")
                                 .Options;

            var user = new User()
            {
                Id = "valid-user"
            };
            var wallet = new Wallet()
            {
                Id = "wallet-test", User = user, CurrencyId = 1
            };

            using (var context = new CasinoContext(contextOptions))
            {
                context.Wallets.Add(wallet);
                context.SaveChanges();

                var walletService = new WalletService(context);
                var result        = await walletService.RetrieveWallet("valid-user");

                Assert.IsNotNull(result);
                Assert.AreEqual("wallet-test", result.Id);
                Assert.AreEqual(1, result.CurrencyId);
            }
        }
Esempio n. 23
0
        public async Task SuccessGetWalletInfoTest()
        {
            try
            {
                string jmbg = "2904992785075";
                //Arrange
                var    walletService = new WalletService(CoreUnitOfWork, BankRoutingService, FeeService, Configuration);
                string password      = await walletService.CreateWallet(jmbg, "TestIme", "TestPrezime", (short)BankType.FirstBank, "360123456789999874", "1234");

                //Act
                var walletInfoDTO = await walletService.GetWalletInfo(jmbg, password);

                //Assert

                Assert.AreEqual(walletInfoDTO.JMBG, jmbg);
                Assert.AreEqual(walletInfoDTO.FirstName, "TestIme");
                Assert.AreEqual(walletInfoDTO.LastName, "TestPrezime");
                Assert.AreEqual(walletInfoDTO.Bank, BankType.FirstBank);
                Assert.AreEqual(walletInfoDTO.BankAccountNumber, "360123456789999874");
                Assert.AreEqual(walletInfoDTO.Balance, 0m);
                Assert.AreEqual(walletInfoDTO.IsBlocked, false);
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
Esempio n. 24
0
        public static async Task DisposeInWalletDependentServicesAsync()
        {
            if (WalletService != null)
            {
                WalletService.Coins.CollectionChanged -= Coins_CollectionChanged;
            }
            CancelWalletServiceInitialization?.Cancel();
            CancelWalletServiceInitialization = null;

            if (!(WalletService is null))
            {
                if (!(WalletService.KeyManager is null))                 // This should not ever happen.
                {
                    string backupWalletFilePath = Path.Combine(WalletBackupsDir, Path.GetFileName(WalletService.KeyManager.FilePath));
                    WalletService.KeyManager?.ToFile(backupWalletFilePath);
                    Logger.LogInfo($"{nameof(KeyManager)} backup saved to {backupWalletFilePath}.", nameof(Global));
                }
                WalletService.Dispose();
                WalletService = null;
            }

            Logger.LogInfo($"{nameof(WalletService)} is stopped.", nameof(Global));

            if (!(ChaumianClient is null))
            {
                await ChaumianClient.StopAsync();

                ChaumianClient = null;
            }
            Logger.LogInfo($"{nameof(ChaumianClient)} is stopped.", nameof(Global));
        }
Esempio n. 25
0
        public void TestGetWalletByUser1()
        {
            Users.User loggedUser = new User("user1");

            var     userSession    = new MockUserSession(loggedUser);
            Wallets walletProvider = new Wallets();

            var user = new Users.User("user2");

            user.AddFriend(loggedUser);

            // Link wallets to user
            walletProvider.AddWallet(user, new Wallet("wallet1"));
            walletProvider.AddWallet(user, new Wallet("wallet2"));
            walletProvider.AddWallet(user, new Wallet("wallet3"));

            List <Wallet> userWallets = walletProvider.FindWalletsByUser(user);

            var walletSvc = new WalletService(userSession, walletProvider);
            var wallets   = walletSvc.GetWalletsByUser(user);

            // Does NUnit Assert work on container(object)..?
            Assert.IsNotNull(wallets);
            Assert.AreEqual(userWallets.Count, wallets.Count);
            for (int i = 0; i < userWallets.Count; ++i)
            {
                Assert.AreEqual(userWallets[i], wallets[i]);
            }
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            return(Task.Factory.StartNew(() =>
            {
                var userName = context.UserName;
                var password = context.Password;
                var walletService = new WalletService(); // our created one
                var wallet = walletService.ValidateUser(userName, password);
                if (wallet != null)
                {
                    var claims = new List <Claim>()
                    {
                        //new Claim(ClaimTypes.Sid, Convert.ToString(wallet.Id)),
                        //new Claim(ClaimTypes.Name, wallet.FName+" "+wallet.LName),
                        //new Claim(ClaimTypes.Role, "Admin"),
                        //new Claim(ClaimTypes.Email, wallet.Email),
                        //new Claim("Id",  Convert.ToString(wallet.Id)),
                        //new Claim("Username",  wallet.Username)
                    };

                    ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims, Startup.OAuthOptions.AuthenticationType);

                    var properties = CreateProperties(wallet.name);
                    var ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                }
                else
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                    context.Response.Headers.Add("AuthorizationResponse", new[] { "Failed" });
                }
            }));
        }
Esempio n. 27
0
        public async Task ThrowIfWalletAlreadyExists()
        {
            var contextOptions = new DbContextOptionsBuilder <CasinoContext>()
                                 .UseInMemoryDatabase(databaseName: "ThrowIfWalletAlreadyExists")
                                 .Options;

            var user = new User()
            {
                Id = "test-user-id", IsDeleted = false
            };
            var wallet = new Wallet()
            {
                Id = "test-wallet", User = user
            };

            using (var context = new CasinoContext(contextOptions))
            {
                context.Wallets.Add(wallet);
                context.SaveChanges();

                var walletService = new WalletService(context);
                await Assert.ThrowsExceptionAsync <EntityAlreadyExistsException>
                    (async() => await walletService.CreateWallet("test-user-id", 1));
            }
        }
        public async Task FailWalletTransferTest5()
        {
            try
            {
                string jmbg1 = "2904992785075";
                string jmbg2 = "2904990785034";
                //Arrange
                var    walletService = new WalletService(CoreUnitOfWork, BankRoutingService, FeeService, Configuration);
                string password1     = await walletService.CreateWallet(jmbg1, "TestIme1", "TestPrezime1", (short)BankType.FirstBank, "360123456789999874", "1234");

                string password2 = await walletService.CreateWallet(jmbg2, "TestIme2", "TestPrezime2", (short)BankType.FirstBank, "360123456789999889", "1224");

                await walletService.Deposit(jmbg1, password1, 2000m);

                Wallet wallet2 = await CoreUnitOfWork.WalletRepository.GetById(jmbg2);

                wallet2.Block();

                //Assert
                await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() => await walletService.Transfer(jmbg1, password1, 2000000m, jmbg2), $"Forbidden transfer to blocked wallet #{jmbg2}");
            }
            catch (Exception ex)
            {
                Assert.Fail("Unexpected error: " + ex.Message);
            }
        }
Esempio n. 29
0
        public async Task CreateWalletIfNoneFound()
        {
            var contextOptions = new DbContextOptionsBuilder <CasinoContext>()
                                 .UseInMemoryDatabase(databaseName: "CreateWalletIfNoneFound")
                                 .Options;

            var user = new User()
            {
                Id = "test-user-id", IsDeleted = false
            };

            var currency = new Currency()
            {
                Id = 1, Name = "Test-currency"
            };

            using (var context = new CasinoContext(contextOptions))
            {
                context.Users.Add(user);
                context.Currencies.Add(currency);
                context.SaveChanges();

                var walletService = new WalletService(context);

                var result = await walletService.CreateWallet("test-user-id", 1);

                Assert.IsNotNull(result);
                Assert.AreEqual("test-user-id", result.UserId);
                Assert.AreEqual(1, result.CurrencyId);
            }
        }
 public RouletteTable(int maxChipsOnTable, RandomNumberGenerator generator, Timer timer, WalletService walletService)
 {
     this.maxChipsOnTable = maxChipsOnTable;
     this.rng = generator;
     this.timer = timer;
     this.walletService = walletService;
 }
        private WalletService CreateWalletService()
        {
            var userId        = Guid.Parse(User.Identity.GetUserId());
            var walletService = new WalletService(userId);

            return(walletService);
        }