Exemple #1
0
 private static void AddMovies(string sql, SqlConnection con, DataRequestService request, CinemaType cinemaType)
 {
     using (SqlCommand command = new SqlCommand(sql, con))
     {
         using (SqlDataReader reader = command.ExecuteReader())
         {
             while (reader.Read())
             {
                 Console.WriteLine("Adding Movies.." + reader.GetString(2));
                 request.ProvideData(cinemaType, reader.GetInt32(1));
                 //ADD MOVIES TO DB
                 foreach (var movie in request.MovieList)
                 {
                     if (movie.Original_Name == null)
                     {
                         movie.Original_Name = movie.Name;
                     }
                     movie.Name = Regex.Replace(movie.Name, "[^a-zA-Z]", "").ToLower();
                     //Check if movie exists in DB
                     UpdateOrInsertMovies(con, movie);
                 }
             }
         }
     }
 }
Exemple #2
0
        public DataServer(int port, int baseMetadataServerPort)
        {
            failing               = false;
            freezer               = new ManualResetEvent(true);
            uniqueFileId          = 0;
            this.port             = port;
            this.baseMetadataPort = baseMetadataServerPort;
            this.files            = new Dictionary <string, Data>();

            commandService                  = new CommandService();
            commandService.FailHandler     += Fail;
            commandService.RecoverHandler  += Recover;
            commandService.FreezeHandler   += Freeze;
            commandService.UnfreezeHandler += Unfreeze;

            requestService               = new DataRequestService();
            requestService.ReadHandler  += Read;
            requestService.WriteHandler += Write;
            //requestService.WriteableHandler += IsWriteable;
            //requestService.ReadableHandler += IsReadable;
            //requestService.CancelHandler += Cancel;
            requestService.VersionHandler += GetVersion;

            messageService = new DataMessageService();
            messageService.CreateNewFileHandler += NewFile;
            messageService.DeleteFileHandler    += DeleteFile;
            messageService.CopyFileHandler      += CopyFile;
            messageService.PasteFileHandler     += PasteFile;
        }
Exemple #3
0
        private static void UpdateDatabase(DataRequestService request, CinemaType cinemaType)
        {
            using (SqlConnection con = new SqlConnection(builder.ConnectionString))
            {
                Console.WriteLine("UpdateDB");
                con.Open();

                var sql = "select * from Cinema Where CinemaType=" + ((int)cinemaType).ToString();
                AddMovies(sql, con, request, cinemaType);
                con.Close();
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            try
            {
                DataRequestService request = new DataRequestService();

                using (SqlConnection con = new SqlConnection(builder.ConnectionString))
                    using (SqlCommand sqlCommand = new SqlCommand("TRUNCATE TABLE Show", con))
                    {
                        con.Open();
                        sqlCommand.ExecuteNonQuery();
                        con.Close();
                    }


                UpdateDatabase(request, CinemaType.cinemacity);
                UpdateDatabase(request, CinemaType.multikino);
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.StackTrace + "|" + e.Message + "|" + e.LineNumber + "|||");
            }
        }
Exemple #5
0
        public INdmConsumerServices Init(INdmServices services)
        {
            AddDecoders();
            var logManager = services.RequiredServices.LogManager;
            var logger     = logManager.GetClassLogger();

            var disableSendingDepositTransaction  = HasEnabledVariable("SENDING_DEPOSIT_TRANSACTION_DISABLED");
            var instantDepositVerificationEnabled = HasEnabledVariable("INSTANT_DEPOSIT_VERIFICATION_ENABLED");
            var backgroundServicesDisabled        = HasEnabledVariable("BACKGROUND_SERVICES_DISABLED");

            if (disableSendingDepositTransaction)
            {
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM sending deposit transaction is disabled ***");
                }
            }

            if (instantDepositVerificationEnabled)
            {
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM instant deposit verification is enabled ***");
                }
            }

            if (backgroundServicesDisabled)
            {
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM background services are disabled ***");
                }
            }

            var ndmConfig       = services.RequiredServices.NdmConfig;
            var configId        = ndmConfig.Id;
            var dbConfig        = services.RequiredServices.ConfigProvider.GetConfig <IDbConfig>();
            var contractAddress = string.IsNullOrWhiteSpace(ndmConfig.ContractAddress)
                ? Address.Zero
                : new Address(ndmConfig.ContractAddress);
            var rocksDbProvider = new ConsumerRocksDbProvider(services.RequiredServices.BaseDbPath, dbConfig,
                                                              logManager);
            var depositDetailsRlpDecoder  = new DepositDetailsDecoder();
            var depositApprovalRlpDecoder = new DepositApprovalDecoder();
            var receiptRlpDecoder         = new DataDeliveryReceiptDetailsDecoder();
            var sessionRlpDecoder         = new ConsumerSessionDecoder();
            var receiptRequestValidator   = new ReceiptRequestValidator(logManager);

            IDepositDetailsRepository          depositRepository;
            IConsumerDepositApprovalRepository depositApprovalRepository;
            IProviderRepository        providerRepository;
            IReceiptRepository         receiptRepository;
            IConsumerSessionRepository sessionRepository;

            switch (ndmConfig.Persistence?.ToLowerInvariant())
            {
            case "mongo":
                var database = services.RequiredServices.MongoProvider.GetDatabase();
                depositRepository         = new DepositDetailsMongoRepository(database);
                depositApprovalRepository = new ConsumerDepositApprovalMongoRepository(database);
                providerRepository        = new ProviderMongoRepository(database);
                receiptRepository         = new ReceiptMongoRepository(database, "consumerReceipts");
                sessionRepository         = new ConsumerSessionMongoRepository(database);
                break;

            case "memory":
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM is using in memory database ***");
                }
                var depositsDatabase = new DepositsInMemoryDb();
                depositRepository         = new DepositDetailsInMemoryRepository(depositsDatabase);
                depositApprovalRepository = new ConsumerDepositApprovalInMemoryRepository();
                providerRepository        = new ProviderInMemoryRepository(depositsDatabase);
                receiptRepository         = new ReceiptInMemoryRepository();
                sessionRepository         = new ConsumerSessionInMemoryRepository();
                break;

            default:
                depositRepository = new DepositDetailsRocksRepository(rocksDbProvider.DepositsDb,
                                                                      depositDetailsRlpDecoder);
                depositApprovalRepository = new ConsumerDepositApprovalRocksRepository(
                    rocksDbProvider.ConsumerDepositApprovalsDb, depositApprovalRlpDecoder);
                providerRepository = new ProviderRocksRepository(rocksDbProvider.DepositsDb,
                                                                 depositDetailsRlpDecoder);
                receiptRepository = new ReceiptRocksRepository(rocksDbProvider.ConsumerReceiptsDb,
                                                               receiptRlpDecoder);
                sessionRepository = new ConsumerSessionRocksRepository(rocksDbProvider.ConsumerSessionsDb,
                                                                       sessionRlpDecoder);
                break;
            }

            var requiredBlockConfirmations = ndmConfig.BlockConfirmations;
            var abiEncoder                = services.CreatedServices.AbiEncoder;
            var blockchainBridge          = services.CreatedServices.BlockchainBridge;
            var blockProcessor            = services.RequiredServices.BlockProcessor;
            var configManager             = services.RequiredServices.ConfigManager;
            var consumerAddress           = services.CreatedServices.ConsumerAddress;
            var cryptoRandom              = services.RequiredServices.CryptoRandom;
            var depositService            = services.CreatedServices.DepositService;
            var gasPriceService           = services.CreatedServices.GasPriceService;
            var ecdsa                     = services.RequiredServices.Ecdsa;
            var ethRequestService         = services.RequiredServices.EthRequestService;
            var jsonRpcNdmConsumerChannel = services.CreatedServices.JsonRpcNdmConsumerChannel;
            var ndmNotifier               = services.RequiredServices.Notifier;
            var nodePublicKey             = services.RequiredServices.Enode.PublicKey;
            var timestamper               = services.RequiredServices.Timestamper;
            var wallet                    = services.RequiredServices.Wallet;
            var httpClient                = services.RequiredServices.HttpClient;
            var jsonRpcClientProxy        = services.RequiredServices.JsonRpcClientProxy;
            var ethJsonRpcClientProxy     = services.RequiredServices.EthJsonRpcClientProxy;
            var transactionService        = services.CreatedServices.TransactionService;
            var monitoringService         = services.RequiredServices.MonitoringService;

            monitoringService?.RegisterMetrics(typeof(Metrics));

            var dataRequestFactory     = new DataRequestFactory(wallet, nodePublicKey);
            var transactionVerifier    = new TransactionVerifier(blockchainBridge, requiredBlockConfirmations);
            var depositUnitsCalculator = new DepositUnitsCalculator(sessionRepository, timestamper);
            var depositProvider        = new DepositProvider(depositRepository, depositUnitsCalculator, logManager);
            var kycVerifier            = new KycVerifier(depositApprovalRepository, logManager);
            var consumerNotifier       = new ConsumerNotifier(ndmNotifier);

            var dataAssetService   = new DataAssetService(providerRepository, consumerNotifier, logManager);
            var providerService    = new ProviderService(providerRepository, consumerNotifier, logManager);
            var dataRequestService = new DataRequestService(dataRequestFactory, depositProvider, kycVerifier, wallet,
                                                            providerService, timestamper, sessionRepository, consumerNotifier, logManager);

            var sessionService = new SessionService(providerService, depositProvider, dataAssetService,
                                                    sessionRepository, timestamper, consumerNotifier, logManager);
            var dataConsumerService = new DataConsumerService(depositProvider, sessionService,
                                                              consumerNotifier, timestamper, sessionRepository, logManager);
            var dataStreamService = new DataStreamService(dataAssetService, depositProvider,
                                                          providerService, sessionService, wallet, consumerNotifier, sessionRepository, logManager);
            var depositApprovalService = new DepositApprovalService(dataAssetService, providerService,
                                                                    depositApprovalRepository, timestamper, consumerNotifier, logManager);
            var depositConfirmationService = new DepositConfirmationService(blockchainBridge, consumerNotifier,
                                                                            depositRepository, depositService, logManager, requiredBlockConfirmations);

            IDepositManager depositManager = new DepositManager(depositService, depositUnitsCalculator,
                                                                dataAssetService, kycVerifier, providerService, abiEncoder, cryptoRandom, wallet, gasPriceService,
                                                                depositRepository, timestamper, logManager, requiredBlockConfirmations,
                                                                disableSendingDepositTransaction);

            if (instantDepositVerificationEnabled)
            {
                depositManager = new InstantDepositManager(depositManager, depositRepository, timestamper, logManager,
                                                           requiredBlockConfirmations);
            }

            var depositReportService = new DepositReportService(depositRepository, receiptRepository, sessionRepository,
                                                                timestamper);
            var receiptService = new ReceiptService(depositProvider, providerService, receiptRequestValidator,
                                                    sessionService, timestamper, receiptRepository, sessionRepository, abiEncoder, wallet, ecdsa,
                                                    nodePublicKey, logManager);
            var refundService = new RefundService(blockchainBridge, abiEncoder, wallet, depositRepository,
                                                  contractAddress, logManager);
            var refundClaimant = new RefundClaimant(refundService, blockchainBridge, depositRepository,
                                                    transactionVerifier, gasPriceService, timestamper, logManager);
            var accountService = new AccountService(configManager, dataStreamService, providerService,
                                                    sessionService, consumerNotifier, wallet, configId, consumerAddress, logManager);
            var proxyService    = new ProxyService(jsonRpcClientProxy, configManager, configId, logManager);
            var consumerService = new ConsumerService(accountService, dataAssetService, dataRequestService,
                                                      dataConsumerService, dataStreamService, depositManager, depositApprovalService, providerService,
                                                      receiptService, refundService, sessionService, proxyService);
            var ethPriceService             = new EthPriceService(httpClient, timestamper, logManager);
            var consumerTransactionsService = new ConsumerTransactionsService(transactionService, depositRepository,
                                                                              timestamper, logManager);
            var gasLimitService = new ConsumerGasLimitsService(depositService, refundService);

            IPersonalBridge personalBridge = services.RequiredServices.EnableUnsecuredDevWallet
                ? new PersonalBridge(ecdsa, wallet)
                : null;

            services.RequiredServices.RpcModuleProvider.Register(
                new SingletonModulePool <INdmRpcConsumerModule>(new NdmRpcConsumerModule(consumerService,
                                                                                         depositReportService, jsonRpcNdmConsumerChannel, ethRequestService, ethPriceService,
                                                                                         gasPriceService, consumerTransactionsService, gasLimitService, personalBridge, timestamper), true));

            if (!backgroundServicesDisabled)
            {
                var useDepositTimer = ndmConfig.ProxyEnabled;
                var consumerServicesBackgroundProcessor = new ConsumerServicesBackgroundProcessor(accountService,
                                                                                                  refundClaimant, depositConfirmationService, ethPriceService, gasPriceService, blockProcessor,
                                                                                                  depositRepository, consumerNotifier, logManager, useDepositTimer, ethJsonRpcClientProxy);
                consumerServicesBackgroundProcessor.Init();
            }

            return(new NdmConsumerServices(accountService, consumerService));
        }
        public async Task Init()
        {
            AddDecoders();
            ILogManager logManager = _api.LogManager;
            ILogger     logger     = logManager.GetClassLogger();

            bool disableSendingDepositTransaction  = HasEnabledVariable("SENDING_DEPOSIT_TRANSACTION_DISABLED");
            bool instantDepositVerificationEnabled = HasEnabledVariable("INSTANT_DEPOSIT_VERIFICATION_ENABLED");
            bool backgroundServicesDisabled        = HasEnabledVariable("BACKGROUND_SERVICES_DISABLED");

            if (disableSendingDepositTransaction)
            {
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM sending deposit transaction is disabled ***");
                }
            }

            if (instantDepositVerificationEnabled)
            {
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM instant deposit verification is enabled ***");
                }
            }

            if (backgroundServicesDisabled)
            {
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM background services are disabled ***");
                }
            }

            INdmConfig ndmConfig       = _api.NdmConfig;
            string     configId        = ndmConfig.Id;
            IDbConfig  dbConfig        = _api.ConfigProvider.GetConfig <IDbConfig>();
            Address    contractAddress = string.IsNullOrWhiteSpace(ndmConfig.ContractAddress)
                ? Address.Zero
                : new Address(ndmConfig.ContractAddress);
            DepositDetailsDecoder             depositDetailsRlpDecoder  = new DepositDetailsDecoder();
            DepositApprovalDecoder            depositApprovalRlpDecoder = new DepositApprovalDecoder();
            DataDeliveryReceiptDetailsDecoder receiptRlpDecoder         = new DataDeliveryReceiptDetailsDecoder();
            ConsumerSessionDecoder            sessionRlpDecoder         = new ConsumerSessionDecoder();
            ReceiptRequestValidator           receiptRequestValidator   = new ReceiptRequestValidator(logManager);

            IDepositDetailsRepository          depositRepository;
            IConsumerDepositApprovalRepository depositApprovalRepository;
            IProviderRepository        providerRepository;
            IReceiptRepository         receiptRepository;
            IConsumerSessionRepository sessionRepository;
            IDepositUnitsCalculator    depositUnitsCalculator;

            switch (ndmConfig.Persistence?.ToLowerInvariant())
            {
            case "mongo":
                IMongoDatabase?database = _api.MongoProvider.GetDatabase();
                if (database == null)
                {
                    throw new ApplicationException("Failed to initialize Mongo DB.");
                }

                sessionRepository         = new ConsumerSessionMongoRepository(database);
                depositUnitsCalculator    = new DepositUnitsCalculator(sessionRepository, _api.Timestamper);
                depositRepository         = new DepositDetailsMongoRepository(database, depositUnitsCalculator);
                depositApprovalRepository = new ConsumerDepositApprovalMongoRepository(database);
                providerRepository        = new ProviderMongoRepository(database);
                receiptRepository         = new ReceiptMongoRepository(database, "consumerReceipts");
                break;

            case "memory":
                if (logger.IsWarn)
                {
                    logger.Warn("*** NDM is using in memory database ***");
                }
                DepositsInMemoryDb depositsDatabase = new DepositsInMemoryDb();
                sessionRepository         = new ConsumerSessionInMemoryRepository();
                depositUnitsCalculator    = new DepositUnitsCalculator(sessionRepository, _api.Timestamper);
                depositRepository         = new DepositDetailsInMemoryRepository(depositsDatabase, depositUnitsCalculator);
                depositApprovalRepository = new ConsumerDepositApprovalInMemoryRepository();
                providerRepository        = new ProviderInMemoryRepository(depositsDatabase);
                receiptRepository         = new ReceiptInMemoryRepository();
                break;

            default:
                var dbInitializer = new ConsumerNdmDbInitializer(_api.DbProvider, ndmConfig, _api.RocksDbFactory, _api.MemDbFactory);
                await dbInitializer.InitAsync();

                sessionRepository = new ConsumerSessionRocksRepository(_api.Db <IDb>(ConsumerNdmDbNames.ConsumerSessions),
                                                                       sessionRlpDecoder);
                depositUnitsCalculator = new DepositUnitsCalculator(sessionRepository, _api.Timestamper);
                depositRepository      = new DepositDetailsRocksRepository(_api.Db <IDb>(ConsumerNdmDbNames.Deposits),
                                                                           depositDetailsRlpDecoder, depositUnitsCalculator);
                depositApprovalRepository = new ConsumerDepositApprovalRocksRepository(
                    _api.Db <IDb>(ConsumerNdmDbNames.ConsumerDepositApprovals), depositApprovalRlpDecoder);
                providerRepository = new ProviderRocksRepository(_api.Db <IDb>(ConsumerNdmDbNames.Deposits),
                                                                 depositDetailsRlpDecoder);
                receiptRepository = new ReceiptRocksRepository(_api.Db <IDb>(ConsumerNdmDbNames.ConsumerReceipts),
                                                               receiptRlpDecoder);

                break;
            }

            uint                 requiredBlockConfirmations = ndmConfig.BlockConfirmations;
            IAbiEncoder          abiEncoder       = _api.AbiEncoder;
            INdmBlockchainBridge blockchainBridge = _api.BlockchainBridge;
            IBlockProcessor      blockProcessor   = _api.MainBlockProcessor;
            IConfigManager       configManager    = _api.ConfigManager;
            Address              consumerAddress  = _api.ConsumerAddress;
            ICryptoRandom        cryptoRandom     = _api.CryptoRandom;
            IDepositService      depositService   = _api.DepositService;

            gasPriceService = _api.GasPriceService;
            IEthereumEcdsa ecdsa = _api.EthereumEcdsa;

            ethRequestService         = _api.EthRequestService;
            jsonRpcNdmConsumerChannel = _api.JsonRpcNdmConsumerChannel;
            INdmNotifier ndmNotifier   = _api.NdmNotifier;
            PublicKey    nodePublicKey = _api.Enode.PublicKey;

            timestamper = _api.Timestamper;
            IWallet                wallet                = _api.Wallet;
            IHttpClient            httpClient            = _api.HttpClient;
            IJsonRpcClientProxy?   jsonRpcClientProxy    = _api.JsonRpcClientProxy;
            IEthJsonRpcClientProxy?ethJsonRpcClientProxy = _api.EthJsonRpcClientProxy;
            TransactionService     transactionService    = _api.TransactionService;
            IMonitoringService     monitoringService     = _api.MonitoringService;
            IWebSocketsModule      ndmWebSocketsModule   = _api.WebSocketsManager.GetModule("ndm");

            monitoringService?.RegisterMetrics(typeof(Metrics));

            DataRequestFactory  dataRequestFactory  = new DataRequestFactory(wallet, nodePublicKey);
            TransactionVerifier transactionVerifier = new TransactionVerifier(blockchainBridge, requiredBlockConfirmations);
            DepositProvider     depositProvider     = new DepositProvider(depositRepository, depositUnitsCalculator, logManager);
            KycVerifier         kycVerifier         = new KycVerifier(depositApprovalRepository, logManager);
            ConsumerNotifier    consumerNotifier    = new ConsumerNotifier(ndmNotifier);

            DataAssetService   dataAssetService   = new DataAssetService(providerRepository, consumerNotifier, logManager);
            ProviderService    providerService    = new ProviderService(providerRepository, consumerNotifier, logManager);
            DataRequestService dataRequestService = new DataRequestService(dataRequestFactory, depositProvider, kycVerifier, wallet,
                                                                           providerService, timestamper, sessionRepository, consumerNotifier, logManager);

            SessionService sessionService = new SessionService(providerService, depositProvider, dataAssetService,
                                                               sessionRepository, timestamper, consumerNotifier, logManager);
            DataConsumerService dataConsumerService = new DataConsumerService(depositProvider, sessionService,
                                                                              consumerNotifier, timestamper, sessionRepository, logManager);
            DataStreamService dataStreamService = new DataStreamService(dataAssetService, depositProvider,
                                                                        providerService, sessionService, wallet, consumerNotifier, sessionRepository, logManager);
            DepositApprovalService depositApprovalService = new DepositApprovalService(dataAssetService, providerService,
                                                                                       depositApprovalRepository, timestamper, consumerNotifier, logManager);
            DepositConfirmationService depositConfirmationService = new DepositConfirmationService(blockchainBridge, consumerNotifier,
                                                                                                   depositRepository, depositService, logManager, requiredBlockConfirmations);

            IDepositManager depositManager = new DepositManager(depositService, depositUnitsCalculator,
                                                                dataAssetService, kycVerifier, providerService, abiEncoder, cryptoRandom, wallet, gasPriceService,
                                                                depositRepository, timestamper, logManager, requiredBlockConfirmations,
                                                                disableSendingDepositTransaction);

            if (instantDepositVerificationEnabled)
            {
                depositManager = new InstantDepositManager(depositManager, depositRepository, timestamper, logManager,
                                                           requiredBlockConfirmations);
            }

            depositReportService = new DepositReportService(depositRepository, depositUnitsCalculator, receiptRepository, sessionRepository,
                                                            timestamper);
            ReceiptService receiptService = new ReceiptService(depositProvider, providerService, receiptRequestValidator,
                                                               sessionService, timestamper, receiptRepository, sessionRepository, abiEncoder, wallet, ecdsa,
                                                               nodePublicKey, logManager);
            RefundService refundService = new RefundService(blockchainBridge, abiEncoder, depositRepository,
                                                            contractAddress, logManager, wallet);
            RefundClaimant refundClaimant = new RefundClaimant(refundService, blockchainBridge, depositRepository,
                                                               transactionVerifier, gasPriceService, timestamper, logManager);

            _api.AccountService = new AccountService(configManager, dataStreamService, providerService,
                                                     sessionService, consumerNotifier, wallet, configId, consumerAddress, logManager);
            _api.NdmAccountUpdater = new NdmAccountUpdater(ndmWebSocketsModule, consumerAddress, _api.MainBlockProcessor, _api.ChainHeadStateProvider);
            ProxyService proxyService = new ProxyService(jsonRpcClientProxy, configManager, configId, logManager);

            _api.ConsumerService = new ConsumerService(_api.AccountService, dataAssetService, dataRequestService,
                                                       dataConsumerService, dataStreamService, depositManager, depositApprovalService, providerService,
                                                       receiptService, refundService, sessionService, proxyService);
            ethPriceService             = new EthPriceService(httpClient, timestamper, logManager);
            daiPriceService             = new DaiPriceService(httpClient, timestamper, logManager);
            consumerTransactionsService = new ConsumerTransactionsService(transactionService, depositRepository,
                                                                          timestamper, logManager);
            gasLimitsService = new ConsumerGasLimitsService(depositService, refundService);

            if (!backgroundServicesDisabled)
            {
                bool useDepositTimer = ndmConfig.ProxyEnabled;
                ConsumerServicesBackgroundProcessor consumerServicesBackgroundProcessor =
                    new ConsumerServicesBackgroundProcessor(
                        _api.AccountService,
                        refundClaimant,
                        depositConfirmationService,
                        ethPriceService,
                        daiPriceService,
                        _api.GasPriceService,
                        _api.MainBlockProcessor,
                        depositRepository,
                        consumerNotifier,
                        logManager,
                        useDepositTimer,
                        ethJsonRpcClientProxy);
                consumerServicesBackgroundProcessor.Init();
            }
        }
Exemple #7
0
        public INdmConsumerServices Init(INdmServices services)
        {
            AddDecoders();
            var ndmConfig       = services.RequiredServices.NdmConfig;
            var dbConfig        = services.RequiredServices.ConfigProvider.GetConfig <IDbConfig>();
            var contractAddress = string.IsNullOrWhiteSpace(ndmConfig.ContractAddress)
                ? Address.Zero
                : new Address(ndmConfig.ContractAddress);
            var logManager      = services.RequiredServices.LogManager;
            var rocksDbProvider = new ConsumerRocksDbProvider(services.RequiredServices.BaseDbPath, dbConfig,
                                                              logManager);
            var depositDetailsRlpDecoder  = new DepositDetailsDecoder();
            var depositApprovalRlpDecoder = new DepositApprovalDecoder();
            var receiptRlpDecoder         = new DataDeliveryReceiptDetailsDecoder();
            var sessionRlpDecoder         = new ConsumerSessionDecoder();
            var receiptRequestValidator   = new ReceiptRequestValidator(logManager);

            IDepositDetailsRepository          depositRepository;
            IConsumerDepositApprovalRepository depositApprovalRepository;
            IProviderRepository        providerRepository;
            IReceiptRepository         receiptRepository;
            IConsumerSessionRepository sessionRepository;

            switch (ndmConfig.Persistence?.ToLowerInvariant())
            {
            case "mongo":
                var database = services.RequiredServices.MongoProvider.GetDatabase();
                depositRepository         = new DepositDetailsMongoRepository(database);
                depositApprovalRepository = new ConsumerDepositApprovalMongoRepository(database);
                providerRepository        = new ProviderMongoRepository(database);
                receiptRepository         = new ReceiptMongoRepository(database, "consumerReceipts");
                sessionRepository         = new ConsumerSessionMongoRepository(database);
                break;

            default:
                depositRepository = new DepositDetailsRocksRepository(rocksDbProvider.DepositsDb,
                                                                      depositDetailsRlpDecoder);
                depositApprovalRepository = new ConsumerDepositApprovalRocksRepository(

                    rocksDbProvider.ConsumerDepositApprovalsDb, depositApprovalRlpDecoder);
                providerRepository = new ProviderRocksRepository(rocksDbProvider.DepositsDb,
                                                                 depositDetailsRlpDecoder);
                receiptRepository = new ReceiptRocksRepository(rocksDbProvider.ConsumerReceiptsDb,
                                                               receiptRlpDecoder);
                sessionRepository = new ConsumerSessionRocksRepository(rocksDbProvider.ConsumerSessionsDb,
                                                                       sessionRlpDecoder);
                break;
            }

            var requiredBlockConfirmations = ndmConfig.BlockConfirmations;
            var abiEncoder                = services.CreatedServices.AbiEncoder;
            var blockchainBridge          = services.CreatedServices.BlockchainBridge;
            var blockProcessor            = services.RequiredServices.BlockProcessor;
            var configManager             = services.RequiredServices.ConfigManager;
            var consumerAddress           = services.CreatedServices.ConsumerAddress;
            var cryptoRandom              = services.RequiredServices.CryptoRandom;
            var ecdsa                     = services.RequiredServices.Ecdsa;
            var ethRequestService         = services.RequiredServices.EthRequestService;
            var jsonRpcNdmConsumerChannel = services.CreatedServices.JsonRpcNdmConsumerChannel;
            var ndmNotifier               = services.RequiredServices.Notifier;
            var nodePublicKey             = services.RequiredServices.Enode.PublicKey;
            var timestamper               = services.RequiredServices.Timestamper;
            var txPool                    = services.RequiredServices.TransactionPool;
            var wallet                    = services.RequiredServices.Wallet;

            var dataRequestFactory     = new DataRequestFactory(wallet, nodePublicKey);
            var transactionVerifier    = new TransactionVerifier(blockchainBridge, requiredBlockConfirmations);
            var depositUnitsCalculator = new DepositUnitsCalculator(sessionRepository, timestamper);
            var depositProvider        = new DepositProvider(depositRepository, depositUnitsCalculator, logManager);
            var kycVerifier            = new KycVerifier(depositApprovalRepository, logManager);
            var consumerNotifier       = new ConsumerNotifier(ndmNotifier);

            var dataAssetService   = new DataAssetService(providerRepository, consumerNotifier, logManager);
            var providerService    = new ProviderService(providerRepository, consumerNotifier, logManager);
            var dataRequestService = new DataRequestService(dataRequestFactory, depositProvider, kycVerifier, wallet,
                                                            providerService, timestamper, sessionRepository, consumerNotifier, logManager);
            var depositService = new DepositService(blockchainBridge, txPool, abiEncoder, wallet, contractAddress,
                                                    logManager);
            var sessionService = new SessionService(providerService, depositProvider, dataAssetService,
                                                    sessionRepository, timestamper, consumerNotifier, logManager);
            var dataConsumerService = new DataConsumerService(depositProvider, sessionService,
                                                              consumerNotifier, timestamper, sessionRepository, logManager);
            var dataStreamService = new DataStreamService(dataAssetService, depositProvider,
                                                          providerService, sessionService, wallet, consumerNotifier, sessionRepository, logManager);
            var depositApprovalService = new DepositApprovalService(dataAssetService, providerService,
                                                                    depositApprovalRepository, timestamper, consumerNotifier, logManager);
            var depositConfirmationService = new DepositConfirmationService(blockchainBridge, consumerNotifier,
                                                                            depositRepository, depositService, logManager, requiredBlockConfirmations);
            var depositManager = new DepositManager(depositService, depositUnitsCalculator, dataAssetService,
                                                    kycVerifier, providerService, abiEncoder, cryptoRandom, wallet, depositRepository, sessionRepository,
                                                    timestamper, logManager, requiredBlockConfirmations);
            var depositReportService = new DepositReportService(depositRepository, receiptRepository, sessionRepository,
                                                                timestamper);
            var receiptService = new ReceiptService(depositProvider, providerService, receiptRequestValidator,
                                                    sessionService, timestamper, receiptRepository, sessionRepository, abiEncoder, wallet, ecdsa,
                                                    nodePublicKey, logManager);
            var refundService = new RefundService(blockchainBridge, txPool, abiEncoder, wallet, depositRepository,
                                                  contractAddress, logManager);
            var refundClaimant = new RefundClaimant(refundService, blockchainBridge, depositRepository,
                                                    transactionVerifier, logManager);
            var accountService = new AccountService(configManager, dataStreamService, providerService,
                                                    sessionService, consumerNotifier, wallet, ndmConfig.Id, consumerAddress, logManager);
            var consumerService = new ConsumerService(accountService, dataAssetService, dataRequestService,
                                                      dataConsumerService, dataStreamService, depositManager, depositApprovalService, providerService,
                                                      receiptService, refundService, sessionService);

            IPersonalBridge personalBridge = services.RequiredServices.EnableUnsecuredDevWallet
                ? new PersonalBridge(ecdsa, wallet)
                : null;

            services.RequiredServices.RpcModuleProvider.Register(
                new SingletonModulePool <INdmRpcConsumerModule>(new NdmRpcConsumerModule(consumerService,
                                                                                         depositReportService, jsonRpcNdmConsumerChannel, ethRequestService, personalBridge, timestamper)));

            var consumerServicesBackgroundProcessor = new ConsumerServicesBackgroundProcessor(accountService,
                                                                                              refundClaimant, depositConfirmationService, blockProcessor, depositRepository, consumerNotifier,
                                                                                              logManager);

            consumerServicesBackgroundProcessor.Init();

            return(new NdmConsumerServices(accountService, consumerService));
        }
 public ConvertService()
 {
     _dataRequestService = new DataRequestService();
 }
        public void Read(int fileRegister, Semantics semantics, int contentRegister)
        {
            print("Read Command Started for fileRegister=" + fileRegister + ",Semantics=" + semantics + ",ContentRegister= " + contentRegister);
            Metadata md = fileRegisters[fileRegister];

            Server[]             sDTO = md.dataServers;
            DataRequestService[] drs  = new DataRequestService[md.nbDataServers];


            while (sDTO.Length < md.readQuorum)
            {
                try
                {
                    Console.WriteLine("To send the Read request I have DatServers=" + sDTO.Length + " less than the ReadQuorum " + md.readQuorum + ". So I will try to open the file again.");
                    this.Open(md.fileName);
                    md   = fileRegisters[fileRegister];
                    sDTO = md.dataServers;
                    Console.WriteLine("After Open Request the number of dataServers are " + sDTO.Length);
                }
                catch (Exception e)
                {
                }
            }



            int i = 0;

            for (i = 0; i < sDTO.GetLength(0); i++)
            {
                try
                {
                    if (dataServices.ContainsKey(sDTO[i].address))
                    {
                        //do nothing;
                    }
                    else
                    { //Get the proxy and store it in the Hashtable for future.
                        dataServices.Add(sDTO[i].address, (DataRequestService)Activator.GetObject(
                                             typeof(DataRequestService),
                                             sDTO[i].address));
                    }
                    //populate the Array.
                    drs[i] = (DataRequestService)dataServices[sDTO[i].address];
                }
                catch (Exception e)
                {
                }
            }


            if (semantics.Equals(Semantics.DEFAULT))
            {
                int[]     versions = new int[md.nbDataServers];
                int       k = 0; int cnt = 0; int maxVersion; int maxId = 0;
                ArrayList failedDataServers = new ArrayList();
                //Initialize versions
                for (k = 0; k < md.nbDataServers; k++)
                {
                    versions[k] = -3;
                }
                //Try for readquorum number of DataServers.
                for (k = 0; k < md.readQuorum; k++)
                {
                    try {
                        versions[k] = (drs[i].GetVersion(sDTO[k].localFileName));
                        cnt++;
                    }
                    catch (Exception e) {
                        failedDataServers.Add(k);
                        //DataServer is Failed.
                    }
                }
                if (cnt < md.readQuorum)
                {
                    for (k = md.readQuorum; k < md.nbDataServers; k++)
                    {
                        try {
                            versions[k] = (drs[i].GetVersion(sDTO[k].localFileName));
                            cnt++;
                            if (cnt >= md.readQuorum)
                            {
                                break;
                            }
                        }
                        catch (Exception e) {
                            failedDataServers.Add(k);
                            //DataServer is Failed.
                        }
                    }
                    k = 0; int index;
                    while (cnt < md.readQuorum)
                    {
                        index = (int)failedDataServers[k];
                        try {
                            versions[index] = (drs[index].GetVersion(sDTO[index].localFileName));
                            cnt++;
                            failedDataServers.RemoveAt(k);
                        }
                        catch (Exception e) {
                            //DataServer is still failed.
                        }
                        if (failedDataServers.Count != 0)
                        {
                            k = (k + 1) % failedDataServers.Count;
                        }
                    }
                }

                //Get the maximum version
                maxVersion = 0;
                for (k = 0; k < md.nbDataServers; k++)
                {
                    if (versions[k] >= maxVersion)
                    {
                        maxVersion = versions[k];
                        maxId      = k;
                    }
                }

                //Read and store the latest Version
                String fileName = fileRegisters[fileRegister].fileName;

                if (fileDetails.ContainsKey(fileName))
                {
                    if (((Indices)fileDetails[fileName]).getLatestVersionSeen() < maxVersion)
                    {
                        ((Indices)fileDetails[fileName]).setLatestVersionSeen(maxVersion);
                    }
                }

                Data contents = new Data(drs[maxId].Read(sDTO[maxId].localFileName, Semantics.DEFAULT));
                if (contentRegister == -1)
                {
                    dataRegisterForCopy = contents;
                }
                else
                {
                    addContentRegister(contents, contentRegister);
                }
            }

            else//semantics is Monotonic.
            {
                String fileName       = fileRegisters[fileRegister].fileName;
                int    currentVersion = -1;
                if (fileDetails.ContainsKey(fileName))
                {
                    currentVersion = ((Indices)fileDetails[fileName]).getLatestVersionSeen();
                }
                else
                {
                    Console.WriteLine("Version last seen,mcorresponding to fileRegister " + fileRegister + " Was not found in fileDetails HashTable. So returning witout Reading");
                    return;
                }
                int       maxVersion = currentVersion; int maxId = 0; int temp;
                int       k = 0; int cnt = 0; //int responseCount = 0;
                ArrayList retryServers = new ArrayList();
                for (k = 0; k < md.nbDataServers; k++)
                {
                    try {
                        temp = drs[k].GetVersion(sDTO[k].localFileName);
                        if (currentVersion < temp)
                        {
                            if (maxVersion < temp)
                            {
                                maxVersion = temp;
                                maxId      = k;
                                cnt++;
                            }
                            else
                            {
                                cnt++;
                            }
                        }
                        else if (currentVersion == temp && maxVersion == currentVersion)
                        {
                            maxId = k;
                            cnt++;
                        }
                        else if (currentVersion == temp && currentVersion < maxVersion)
                        {
                            cnt++;
                        }

                        else
                        {
                            retryServers.Add(k);
                        }
                    }
                    catch (Exception e) {
                        retryServers.Add(k);
                    }
                }

                if (cnt < md.readQuorum)
                {
                    int index = 0;
                    while (cnt < md.readQuorum)
                    {
                        index = (int)retryServers[k];
                        try {
                            temp = drs[index].GetVersion(sDTO[index].localFileName);
                            if (currentVersion < temp)
                            {
                                if (maxVersion < temp)
                                {
                                    maxVersion = temp;
                                    maxId      = index;
                                    cnt++;
                                }
                                else
                                {
                                    cnt++;
                                }

                                retryServers.RemoveAt(k);
                            }
                            else if (currentVersion == temp && maxVersion == currentVersion)
                            {
                                maxId = index;
                                cnt++;
                                retryServers.RemoveAt(k);
                            }
                            else if (currentVersion == temp && currentVersion < maxVersion)
                            {
                                cnt++;
                                retryServers.RemoveAt(k);
                            }
                        }
                        catch (Exception e) {
                            //DataServer is still failed.
                        }
                        k = (k + 1) % retryServers.Count;
                    }
                }

                //Read and Store the max version
                if (fileDetails.ContainsKey(fileName))
                {
                    ((Indices)fileDetails[fileName]).setLatestVersionSeen(maxVersion);
                }
                Data contents = new Data(drs[maxId].Read(sDTO[maxId].localFileName, Semantics.MONOTONIC));
                if (contentRegister == -1)
                {
                    dataRegisterForCopy = contents;
                }
                else
                {
                    addContentRegister(contents, contentRegister);
                }
            }
            print("Read Command execution complete for fileRegister=" + fileRegister + ",Semantics=" + semantics + ",ContentRegister= " + contentRegister);
        }
        public void Write(int fileRegister, byte[] content)
        {
            print("Write Command for fileRegister " + fileRegister + " started executing.");
            Metadata md = fileRegisters[fileRegister];

            Server[] sDTO = md.dataServers;

            if (sDTO.Length < md.writeQuorum)
            {
                Console.WriteLine("To send the write request I have DatServers less than the writeQuorum. So I will try to open the file again.");
                this.Open(md.fileName);
                md   = fileRegisters[fileRegister];
                sDTO = md.dataServers;
                Console.WriteLine("After Open Request the number of dataServers are " + sDTO.Length);
            }


            DataRequestService[] drs  = new DataRequestService[md.nbDataServers];
            int       maxVersionAtDS  = getMaxVersionForWrite(fileRegister, md, sDTO, drs);
            Random    rand            = new Random(md.ticket);
            int       randValue       = rand.Next();
            ArrayList failedServers   = new ArrayList();
            ArrayList possibleServers = new ArrayList();


            int i = 0; int cnt = 0;
            int requiredQuorum = sDTO.Length < md.writeQuorum ? sDTO.Length : md.writeQuorum;

            for (i = 0; i < sDTO.GetLength(0); i++)
            {
                try
                {
                    drs[i].Write(sDTO[i].localFileName, content, maxVersionAtDS + 1, md.ticket);
                    cnt++;
                    if (cnt >= requiredQuorum)
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    failedServers.Add(i);
                }
            }

            if (cnt < requiredQuorum)
            {
                i = 0; int index;
                while (cnt < requiredQuorum)
                {
                    index = (int)failedServers[i];
                    try
                    {
                        drs[index].Write(sDTO[index].localFileName, content, maxVersionAtDS + 1, md.ticket);
                        failedServers.RemoveAt(i);
                        cnt++;
                    }
                    catch (Exception e)
                    {
                        //Data Server failed again.
                    }
                    i = (i + 1) % failedServers.Count;
                }
            }

            print("Write Command Complete for  " + fileRegister + " completed executing.");
        }