public async Task SetUp()
        {
            _config        = new VaultConfig();
            _config.Host   = "localhost:8082";
            _config.Scheme = "http";
            _config.Path   = "api/v1";
            _config.Token  = $"bearer  {TestContext.Parameters["token"]}";

            var vaultSealingForTestsHelper = new VaultSealingForTestsHelper(_config);
            await vaultSealingForTestsHelper.Unseal();

            _vaultService = new VaultService(_config, new TestLogManager(LogLevel.Trace));
            _vaultModule  = new VaultModule(_vaultService, new TestLogManager(LogLevel.Trace));

            provide.Model.Vault.Vault vault = new provide.Model.Vault.Vault();
            vault.Name        = "Test Vault";
            vault.Description = "Test Vault used for test purposes";
            ResultWrapper <provide.Model.Vault.Vault> res = await _vaultModule.vault_createVault(vault);

            if (res.Result != Result.Success || res.Data.Id is null)
            {
                throw new ApplicationException("Failed to create vault");
            }

            _vaultId = res.Data.Id.Value;
        }
Exemple #2
0
        public async Task SetUp()
        {
            VaultConfig config = new VaultConfig();

            config.Host   = "localhost:8082";
            config.Scheme = "http";
            config.Path   = "api/v1";
            config.Token  = $"bearer  {TestContext.Parameters["token"]}";

            _vaultService = new VaultService(
                config,
                new TestLogManager(LogLevel.Trace)
                );

            provide.Model.Vault.Vault vault = new provide.Model.Vault.Vault();
            vault.Name        = "Name";
            vault.Description = "Description";

            // Create a single Vault instance
            provide.Model.Vault.Vault response = await _vaultService.CreateVault(vault);

            response.Id.Should().NotBeNull();

            _vaultId = response.Id !.Value;
            _wallet  = new VaultWallet(_vaultService, _vaultId.ToString(), LimboLogs.Instance);
        }
        public async Task ConnectionError()
        {
            var vault  = new VaultService(new Uri("http://unknown-server:8200"));
            var result = await vault.HealthStatusAsync();

            Assert.Equal(VaultHealthStatus.ConnectionError, result);
        }
        private async Task <DefaultVaultService> AuthVaultService()
        {
            var token = "de24bef9-56f1-8391-98ce-f6fa9ab53df1";
            var vault = new VaultService(_vaultAddress).AuthenticateUsingToken(token) as DefaultVaultService;

            return(vault);
        }
Exemple #5
0
 public ProfileController(ProfileService ps, VaultService vs, KeepService ks, VaultKeepService vks)
 {
     _ks  = ks;
     _vs  = vs;
     _ps  = ps;
     _vks = vks;
 }
Exemple #6
0
        public async Task Init(INethermindApi api)
        {
            _vaultConfig = api.Config <IVaultConfig>();

            _api          = api;
            _logger       = api.LogManager.GetClassLogger();
            _vaultService = new VaultService(_vaultConfig, _api.LogManager);

            if (_vaultConfig.Enabled)
            {
                var passwordProvider = new FilePasswordProvider()
                {
                    FileName = _vaultConfig.VaultKeyFile.GetApplicationResourcePath()
                }
                .OrReadFromConsole("Provide passsphrase to unlock Vault");
                var vaultKeyStoreFacade = new VaultKeyStoreFacade(passwordProvider);
                _vaultSealingHelper = new VaultSealingHelper(vaultKeyStoreFacade, _vaultConfig, _logger);
                await _vaultSealingHelper.Unseal();
            }

            IVaultWallet wallet      = new VaultWallet(_vaultService, _vaultConfig.VaultId, _api.LogManager);
            ITxSigner    vaultSigner = new VaultTxSigner(wallet, _api.ChainSpec.ChainId);

            // TODO: change vault to provide, use sealer to set the gas price as well
            // TODO: need to verify the timing of initializations so the TxSender replacement works fine
            _api.TxSender = new VaultTxSender(vaultSigner, _vaultConfig, _api.ChainSpec.ChainId);
        }
 public void SetUp()
 {
     _config        = new VaultConfig();
     _config.Host   = "localhost:8082";
     _config.Scheme = "http";
     _config.Path   = "api/v1";
     _config.Token  = $"bearer  {TestContext.Parameters["token"]}";
     _vaultService  = new VaultService(_config, LimboLogs.Instance);
 }
        private void Unlock_Click(object sender, RoutedEventArgs e)
        {
            var password     = Password.Password;
            var vaultService = new VaultService();

            vaultService.DecryptVault(_VaultStatus, password);
            _Editor.VaultUnlocked();
            Close();
        }
 public LoginViewModel(
     IEventAggregator eventAggregator,
     IDataService dataService,
     VaultService vaultService)
 {
     _eventAggregator = eventAggregator;
     _dataService     = dataService;
     _vaultService    = vaultService;
     _vaultService.PasswordChanged += _vaultService_PasswordChanged;
     _canLogin = true;
     _userName = "******";
 }
Exemple #10
0
        public void Can_Initialize_VaultTxSender_without_exceptions()
        {
            var vaultConfig = new VaultConfig();

            vaultConfig.VaultId = "1b16996e-3595-4985-816c-043345d22f8c";
            var _vaultService = new VaultService(vaultConfig, LimboLogs.Instance);

            IVaultWallet wallet      = new VaultWallet(_vaultService, vaultConfig.VaultId, LimboLogs.Instance);
            ITxSigner    vaultSigner = new VaultTxSigner(wallet, 1);

            Assert.DoesNotThrow(() => { new VaultTxSender(vaultSigner, vaultConfig, 1); });
        }
        public async Task SetUp()
        {
            _config        = new VaultConfig();
            _config.Host   = "localhost:8082";
            _config.Scheme = "http";
            _config.Path   = "api/v1";
            _config.Token  = $"bearer  {TestContext.Parameters["token"]}";
            var vaultSealingForTestsHelper = new VaultSealingForTestsHelper(_config);
            await vaultSealingForTestsHelper.Unseal();

            _vaultService = new VaultService(_config, LimboLogs.Instance);
        }
Exemple #12
0
        static void Main(string[] args)
        {
            try
            {
                UserCredential credential;
                // Load client secrets.
                using (var stream =
                           new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
                {
                    /* The file token.json stores the user's access and refresh tokens, and is created
                     * automatically when the authorization flow completes for the first time. */
                    string credPath = "token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.FromStream(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                    Console.WriteLine("Credential file saved to: " + credPath);
                }

                // Create Vault API service.
                var service = new VaultService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName
                });

                // Define request parameters.
                MattersResource.ListRequest request = service.Matters.List();
                request.PageSize = 10;

                // List matters.
                ListMattersResponse response = request.Execute();
                Console.WriteLine("Matters:");
                if (response.Matters == null || response.Matters.Count == 0)
                {
                    Console.WriteLine("No matters found.");
                    return;
                }
                foreach (var matter in response.Matters)
                {
                    Console.WriteLine("{0} ({1})", matter.Name, matter.MatterId);
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #13
0
        public IHttpActionResult GetVaultById(int vaultId)
        {
            VaultService vaultService = CreateVaultService();
            var          vault        = vaultService.GetVaultById(vaultId);

            if (vault.GameId != null)
            {
                vault.GameUrl = "https://" + HttpContext.Current.Request.Url.Authority + "/api/Game?GameId=" + vault.GameId;
            }
            if (vault.LocationId != null)
            {
                vault.LocationUrl = "https://" + HttpContext.Current.Request.Url.Authority + "/api/Location?LocationId=" + vault.LocationId;
            }
            return(Ok(vault));
        }
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/vault.googleapis.com-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Vault API service.
            var service = new VaultService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define request parameters.
            MattersResource.ListRequest request = service.Matters.List();
            request.PageSize = 10;

            // List matters.
            ListMattersResponse response = request.Execute();

            Console.WriteLine("Matters:");
            if (response.Matters != null && response.Matters.Count > 0)
            {
                foreach (var matter in response.Matters)
                {
                    Console.WriteLine("{0} ({1})", matter.Name, matter.MatterId);
                }
            }
            else
            {
                Console.WriteLine("No matters found.");
            }
            Console.Read();
        }
        public Task Init(INethermindApi api)
        {
            _vaultConfig  = api.Config <IVaultConfig>();
            _api          = api;
            _logger       = api.LogManager.GetClassLogger();
            _vaultService = new VaultService(_vaultConfig, _api.LogManager);

            IVaultWallet wallet      = new VaultWallet(_vaultService, _vaultConfig.VaultId, _api.LogManager);
            ITxSigner    vaultSigner = new VaultTxSigner(wallet, _api.ChainSpec.ChainId);

            // TODO: change vault to provide, use sealer to set the gas price as well
            // TODO: need to verify the timing of initializations so the TxSender replacement works fine
            _api.TxSender = new VaultTxSender(vaultSigner, _vaultConfig, _api.ChainSpec.ChainId);

            return(Task.CompletedTask);
        }
Exemple #16
0
        public static void RefreshTreeView()
        {
            RootNode.Items.Clear();

            var projectDirectory = Path.GetDirectoryName(ProjectPath);
            var vaultService     = new VaultService();
            var userVaultItem    = new TreeViewItem();

            userVaultItem.Header            = "User Vault";
            userVaultItem.MouseDoubleClick += (sender, args) =>
            {
                OpenFileService.OpenFile(vaultService.GetUserVaultPath());
            };
            RootNode.Items.Add(userVaultItem);
            RecursivelyBuildFolderTree(RootNode.Items, projectDirectory);
        }
Exemple #17
0
        /// <summary>
        /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from the HashiCorp Vault. This provider uses 'token' authentication.
        /// </summary>
        /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param>
        /// <param name="vaultUri">The HashiCorp Vault uri.</param>
        /// <param name="token">The authentication token.</param>
        /// <param name="prefix">The prefix to use when retrieving secrets from the Vault.</param>
        /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
        public static IConfigurationBuilder AddVault(this IConfigurationBuilder configurationBuilder, Uri vaultUri, string token, string prefix)
        {
            if (vaultUri == null)
            {
                throw new ArgumentNullException(nameof(vaultUri));
            }
            if (string.IsNullOrWhiteSpace(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

            var vault  = new VaultService(vaultUri).AuthenticateUsingToken(token);
            var source = new VaultConfigurationSource(vault, prefix);

            return(configurationBuilder.Add(source));
        }
Exemple #18
0
        public IHttpActionResult GetVaultsByCharacterId(int characterIdGetVaults)
        {
            VaultService vaultService = CreateVaultService();
            var          vaults       = vaultService.GetAllVaultsByCharacterId(characterIdGetVaults);

            foreach (VaultListItem h in vaults)
            {
                if (h.GameId != null)
                {
                    h.GameUrl = "https://" + HttpContext.Current.Request.Url.Authority + "/api/Game?GameId=" + h.GameId;
                }
                if (h.LocationId != null)
                {
                    h.LocationUrl = "https://" + HttpContext.Current.Request.Url.Authority + "/api/Location?LocationId=" + h.LocationId;
                }
            }
            return(Ok(vaults));
        }
Exemple #19
0
        public static async Task <string> PrintInvoiceAsync([ActivityTrigger] DurableActivityContext inputs, ILogger log)
        {
            CloudStorageAccount cloudStorageAccount = null;

            var(orderId, parentId) = inputs.GetInput <(string, string)>();
            log.LogInformation($" >>>>>> Printing invoice for the order {orderId}. <<<<<<");

            var storageConnectionString = String.Empty;
            // local debug uses visualstudio user as MSI
            var securityVault = new VaultService(Environment.GetEnvironmentVariable("VaultName"));

            try
            {
                storageConnectionString = securityVault.GetSecret("cn-storageaccount").Result;
            }
            catch (Exception)
            {
                storageConnectionString = Environment.GetEnvironmentVariable("StorageConnectionString");
            }

            var text = new AsciiArt("to blob storage");

            log.LogInformation(text.ToString());

            // save document to blob storage
            cloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString);
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
            var             blobContainer   = cloudBlobClient.GetContainerReference("invoices");

            var blockBlob = blobContainer.GetBlockBlobReference($"{orderId}.png");
            var bytes     = Encoding.ASCII.GetBytes(orderId);

            using (var ms = new MemoryStream())
            {
                ms.Write(bytes, 0, bytes.Length);
                ms.Flush();
                ms.Position = 0;
                blockBlob.UploadFromStream(ms);
            }

            // Demo code : Never use random in functions
            return(String.Format("LBL{0}", Guid.NewGuid().ToString()));
        }
Exemple #20
0
        /// <summary>
        /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from the HashiCorp Vault. This provider uses 'userpass' authentication.
        /// </summary>
        /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param>
        /// <param name="vaultUri">The HashiCorp Vault uri.</param>
        /// <param name="userName">The user name for userpass authentication.</param>
        /// <param name="password">The password for userpass authentication.</param>
        /// <param name="prefix">The prefix to use when retrieving secrets from the Vault.</param>
        /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
        public static IConfigurationBuilder AddVault(this IConfigurationBuilder configurationBuilder, Uri vaultUri, string userName, string password, string prefix)
        {
            if (vaultUri == null)
            {
                throw new ArgumentNullException(nameof(vaultUri));
            }
            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            var vault  = new VaultService(vaultUri).AuthenticateUsingUserPass(userName, password);
            var source = new VaultConfigurationSource(vault, prefix);

            return(configurationBuilder.Add(source));
        }
        public VaultEditor(string filePath)
        {
            InitializeComponent();
            _VaultService = new VaultService();
            _Vault        = _VaultService.OpenVaultFile(filePath);
            if (_Vault.IsInitialized)
            {
                InitializeButton.Visibility = Visibility.Hidden;
            }
            if (_Vault.IsUnlocked || !_Vault.IsInitialized)
            {
                UnlockButton.Visibility = Visibility.Hidden;
            }

            if (!_Vault.IsUnlocked || !_Vault.IsInitialized)
            {
                // If we have not unlocked the vault, it cannot be modified.
                NewSecretButton.IsEnabled = false;
            }
        }
Exemple #22
0
 public LoginView(VaultService vaultService)
 {
     _vaultService = vaultService;
     InitializeComponent();
 }
Exemple #23
0
 public VaultsController(VaultService vs, VaultKeepService vks)
 {
     _vks = vks;
     _vs  = vs;
 }
Exemple #24
0
 public ProfilesController(ProfileService ps, KeepsService ks, VaultService vs)
 {
     _ps = ps;
     _ks = ks;
     _vs = vs;
 }
Exemple #25
0
        private VaultService CreateVaultService()
        {
            var vaultService = new VaultService();

            return(vaultService);
        }
        private Task InitBlockchain()
        {
            if (_api.ChainSpec == null)
            {
                throw new StepDependencyException(nameof(_api.ChainSpec));
            }
            if (_api.DbProvider == null)
            {
                throw new StepDependencyException(nameof(_api.DbProvider));
            }
            if (_api.SpecProvider == null)
            {
                throw new StepDependencyException(nameof(_api.SpecProvider));
            }

            ILogger     logger     = _api.LogManager.GetClassLogger();
            IInitConfig initConfig = _api.Config <IInitConfig>();
            ISyncConfig syncConfig = _api.Config <ISyncConfig>();

            if (syncConfig.DownloadReceiptsInFastSync && !syncConfig.DownloadBodiesInFastSync)
            {
                logger.Warn($"{nameof(syncConfig.DownloadReceiptsInFastSync)} is selected but {nameof(syncConfig.DownloadBodiesInFastSync)} - enabling bodies to support receipts download.");
                syncConfig.DownloadBodiesInFastSync = true;
            }

            Account.AccountStartNonce = _api.ChainSpec.Parameters.AccountStartNonce;

            Signer signer = new Signer(_api.SpecProvider.ChainId, _api.OriginalSignerKey, _api.LogManager);

            _api.Signer      = signer;
            _api.SignerStore = signer;

            _api.StateProvider = new StateProvider(
                _api.DbProvider.StateDb,
                _api.DbProvider.CodeDb,
                _api.LogManager);

            _api.EthereumEcdsa = new EthereumEcdsa(_api.SpecProvider.ChainId, _api.LogManager);
            _api.TxPool        = new TxPool.TxPool(
                new PersistentTxStorage(_api.DbProvider.PendingTxsDb),
                Timestamper.Default,
                _api.EthereumEcdsa,
                _api.SpecProvider,
                _api.Config <ITxPoolConfig>(),
                _api.StateProvider,
                _api.LogManager);

            TxSealer standardSealer = new TxSealer(_api.Signer, _api.Timestamper);
            NonceReservingTxSealer nonceReservingTxSealer =
                new NonceReservingTxSealer(_api.Signer, _api.Timestamper, _api.TxPool);

            IVaultConfig vaultConfig = _api.Config <IVaultConfig>();

            if (!vaultConfig.Enabled)
            {
                _api.TxSender = new TxPoolSender(_api.TxPool, standardSealer, nonceReservingTxSealer);
            }
            else
            {
                IVaultService vaultService = new VaultService(vaultConfig, _api.LogManager);
                IVaultWallet  wallet       = new VaultWallet(vaultService, vaultConfig.VaultId, _api.LogManager);
                ITxSigner     vaultSigner  = new VaultTxSigner(wallet, _api.ChainSpec.ChainId);

                // change vault to provide, use sealer to set the gas price as well
                _api.TxSender = new VaultTxSender(vaultSigner, vaultConfig, _api.ChainSpec.ChainId);
            }

            IBloomConfig?bloomConfig = _api.Config <IBloomConfig>();

            IFileStoreFactory fileStoreFactory = initConfig.DiagnosticMode == DiagnosticMode.MemDb
                ? (IFileStoreFactory) new InMemoryDictionaryFileStoreFactory()
                : new FixedSizeFileStoreFactory(Path.Combine(initConfig.BaseDbPath, DbNames.Bloom), DbNames.Bloom, Bloom.ByteLength);

            _api.BloomStorage = bloomConfig.Index
                ? new BloomStorage(bloomConfig, _api.DbProvider.BloomDb, fileStoreFactory)
                : (IBloomStorage)NullBloomStorage.Instance;

            _api.DisposeStack.Push(_api.BloomStorage);

            _api.ChainLevelInfoRepository = new ChainLevelInfoRepository(_api.DbProvider.BlockInfosDb);

            _api.BlockTree = new BlockTree(
                _api.DbProvider.BlocksDb,
                _api.DbProvider.HeadersDb,
                _api.DbProvider.BlockInfosDb,
                _api.ChainLevelInfoRepository,
                _api.SpecProvider,
                _api.TxPool,
                _api.BloomStorage,
                _api.Config <ISyncConfig>(),
                _api.LogManager);

            // Init state if we need system calls before actual processing starts
            if (_api.BlockTree.Head != null)
            {
                _api.StateProvider.StateRoot = _api.BlockTree.Head.StateRoot;
            }

            _api.ReceiptStorage = initConfig.StoreReceipts ? (IReceiptStorage?)new PersistentReceiptStorage(_api.DbProvider.ReceiptsDb, _api.SpecProvider, new ReceiptsRecovery()) : NullReceiptStorage.Instance;
            _api.ReceiptFinder  = new FullInfoReceiptFinder(_api.ReceiptStorage, new ReceiptsRecovery(), _api.BlockTree);

            _api.RecoveryStep = new TxSignaturesRecoveryStep(_api.EthereumEcdsa, _api.TxPool, _api.LogManager);

            _api.StorageProvider = new StorageProvider(
                _api.DbProvider.StateDb,
                _api.StateProvider,
                _api.LogManager);

            // blockchain processing
            BlockhashProvider blockhashProvider = new BlockhashProvider(
                _api.BlockTree, _api.LogManager);

            VirtualMachine virtualMachine = new VirtualMachine(
                _api.StateProvider,
                _api.StorageProvider,
                blockhashProvider,
                _api.SpecProvider,
                _api.LogManager);

            _api.TransactionProcessor = new TransactionProcessor(
                _api.SpecProvider,
                _api.StateProvider,
                _api.StorageProvider,
                virtualMachine,
                _api.LogManager);

            InitSealEngine();
            if (_api.SealValidator == null)
            {
                throw new StepDependencyException(nameof(_api.SealValidator));
            }

            /* validation */
            _api.HeaderValidator = CreateHeaderValidator();

            OmmersValidator ommersValidator = new OmmersValidator(
                _api.BlockTree,
                _api.HeaderValidator,
                _api.LogManager);

            TxValidator txValidator = new TxValidator(_api.SpecProvider.ChainId);

            _api.BlockValidator = new BlockValidator(
                txValidator,
                _api.HeaderValidator,
                ommersValidator,
                _api.SpecProvider,
                _api.LogManager);

            ReadOnlyDbProvider readOnly    = new ReadOnlyDbProvider(_api.DbProvider, false);
            StateReader        stateReader = new StateReader(readOnly.StateDb, readOnly.CodeDb, _api.LogManager);

            _api.TxPoolInfoProvider = new TxPoolInfoProvider(stateReader, _api.TxPool);

            _api.MainBlockProcessor = CreateBlockProcessor();

            BlockchainProcessor blockchainProcessor = new BlockchainProcessor(
                _api.BlockTree,
                _api.MainBlockProcessor,
                _api.RecoveryStep,
                _api.LogManager,
                new BlockchainProcessor.Options
            {
                AutoProcess            = !syncConfig.BeamSync,
                StoreReceiptsByDefault = initConfig.StoreReceipts,
            });

            _api.BlockProcessingQueue = blockchainProcessor;
            _api.BlockchainProcessor  = blockchainProcessor;

            if (syncConfig.BeamSync)
            {
                BeamBlockchainProcessor beamBlockchainProcessor = new BeamBlockchainProcessor(
                    new ReadOnlyDbProvider(_api.DbProvider, false),
                    _api.BlockTree,
                    _api.SpecProvider,
                    _api.LogManager,
                    _api.BlockValidator,
                    _api.RecoveryStep,
                    _api.RewardCalculatorSource !,
                    _api.BlockProcessingQueue,
                    _api.SyncModeSelector !);

                _api.DisposeStack.Push(beamBlockchainProcessor);
            }

            return(Task.CompletedTask);
        }
Exemple #27
0
 public VaultsController(VaultService service, KeepService kservice)
 {
     _service  = service;
     _kservice = kservice;
 }
Exemple #28
0
 public AccountController(ProfileService ps, KeepService ks, VaultService vs)
 {
     _ps = ps;
     _ks = ks;
     _vs = vs;
 }
        public virtual Task Execute(CancellationToken cancellationToken)
        {
            if (_api.RpcModuleProvider == null)
            {
                throw new StepDependencyException(nameof(_api.RpcModuleProvider));
            }
            if (_api.TxPool == null)
            {
                throw new StepDependencyException(nameof(_api.TxPool));
            }
            if (_api.BlockTree == null)
            {
                throw new StepDependencyException(nameof(_api.BlockTree));
            }
            if (_api.Wallet == null)
            {
                throw new StepDependencyException(nameof(_api.Wallet));
            }
            if (_api.SpecProvider == null)
            {
                throw new StepDependencyException(nameof(_api.SpecProvider));
            }
            if (_api.TxSender == null)
            {
                throw new StepDependencyException(nameof(_api.TxSender));
            }

            ILogger        logger        = _api.LogManager.GetClassLogger();
            IJsonRpcConfig jsonRpcConfig = _api.Config <IJsonRpcConfig>();

            if (!jsonRpcConfig.Enabled)
            {
                return(Task.CompletedTask);
            }

            // the following line needs to be called in order to make sure that the CLI library is referenced from runner and built alongside
            if (logger.IsDebug)
            {
                logger.Debug($"Resolving CLI ({nameof(CliModuleLoader)})");
            }

            IInitConfig     initConfig     = _api.Config <IInitConfig>();
            INdmConfig      ndmConfig      = _api.Config <INdmConfig>();
            IJsonRpcConfig  rpcConfig      = _api.Config <IJsonRpcConfig>();
            IBaselineConfig baselineConfig = _api.Config <IBaselineConfig>();
            IVaultConfig    vaultConfig    = _api.Config <IVaultConfig>();
            INetworkConfig  networkConfig  = _api.Config <INetworkConfig>();

            if (ndmConfig.Enabled && !(_api.NdmInitializer is null) && ndmConfig.ProxyEnabled)
            {
                EthModuleProxyFactory proxyFactory = new EthModuleProxyFactory(_api.EthJsonRpcClientProxy, _api.Wallet);
                _api.RpcModuleProvider.Register(new SingletonModulePool <IEthModule>(proxyFactory, true));
                if (logger.IsInfo)
                {
                    logger.Info("Enabled JSON RPC Proxy for NDM.");
                }
            }
            else
            {
                EthModuleFactory ethModuleFactory = new EthModuleFactory(
                    _api.DbProvider,
                    _api.TxPool,
                    _api.TxSender,
                    _api.Wallet,
                    _api.BlockTree,
                    _api.EthereumEcdsa,
                    _api.MainBlockProcessor,
                    _api.ReceiptFinder,
                    _api.SpecProvider,
                    rpcConfig,
                    _api.BloomStorage,
                    _api.LogManager,
                    initConfig.IsMining);
                _api.RpcModuleProvider.Register(new BoundedModulePool <IEthModule>(8, ethModuleFactory));
            }

            ProofModuleFactory proofModuleFactory = new ProofModuleFactory(_api.DbProvider, _api.BlockTree, _api.RecoveryStep, _api.ReceiptFinder, _api.SpecProvider, _api.LogManager);

            _api.RpcModuleProvider.Register(new BoundedModulePool <IProofModule>(2, proofModuleFactory));

            DebugModuleFactory debugModuleFactory = new DebugModuleFactory(
                _api.DbProvider,
                _api.BlockTree,
                rpcConfig,
                _api.BlockValidator,
                _api.RecoveryStep,
                _api.RewardCalculatorSource,
                _api.ReceiptStorage,
                new ReceiptMigration(_api),
                _api.ConfigProvider,
                _api.SpecProvider,
                _api.LogManager);

            _api.RpcModuleProvider.Register(new BoundedModulePool <IDebugModule>(8, debugModuleFactory));

            TraceModuleFactory traceModuleFactory = new TraceModuleFactory(_api.DbProvider, _api.BlockTree, rpcConfig, _api.RecoveryStep, _api.RewardCalculatorSource, _api.ReceiptStorage, _api.SpecProvider, _api.LogManager);

            _api.RpcModuleProvider.Register(new BoundedModulePool <ITraceModule>(8, traceModuleFactory));

            PersonalModule personalModule = new PersonalModule(
                _api.EthereumEcdsa,
                _api.Wallet,
                _api.LogManager);

            _api.RpcModuleProvider.Register(new SingletonModulePool <IPersonalModule>(personalModule, true));

            AdminModule adminModule = new AdminModule(_api.BlockTree, networkConfig, _api.PeerManager, _api.StaticNodesManager, _api.Enode, initConfig.BaseDbPath);

            _api.RpcModuleProvider.Register(new SingletonModulePool <IAdminModule>(adminModule, true));

            LogFinder logFinder = new LogFinder(
                _api.BlockTree,
                _api.ReceiptFinder,
                _api.BloomStorage,
                _api.LogManager,
                new ReceiptsRecovery(), 1024);

            if (baselineConfig.Enabled)
            {
                IDbProvider  dbProvider  = _api.DbProvider !;
                IStateReader stateReader = new StateReader(dbProvider.StateDb, dbProvider.CodeDb, _api.LogManager);

                BaselineModuleFactory baselineModuleFactory = new BaselineModuleFactory(
                    _api.TxSender,
                    stateReader,
                    logFinder,
                    _api.BlockTree,
                    _api.AbiEncoder,
                    _api.FileSystem,
                    _api.LogManager);

                _api.RpcModuleProvider.Register(new SingletonModulePool <IBaselineModule>(baselineModuleFactory, true));
                if (logger?.IsInfo ?? false)
                {
                    logger !.Info($"Baseline RPC Module has been enabled");
                }
            }

            TxPoolModule txPoolModule = new TxPoolModule(_api.BlockTree, _api.TxPoolInfoProvider, _api.LogManager);

            _api.RpcModuleProvider.Register(new SingletonModulePool <ITxPoolModule>(txPoolModule, true));


            if (vaultConfig.Enabled)
            {
                VaultService vaultService = new VaultService(vaultConfig, _api.LogManager);
                VaultModule  vaultModule  = new VaultModule(vaultService, _api.LogManager);
                _api.RpcModuleProvider.Register(new SingletonModulePool <IVaultModule>(vaultModule, true));
                if (logger?.IsInfo ?? false)
                {
                    logger !.Info($"Vault RPC Module has been enabled");
                }
            }

            NetModule netModule = new NetModule(_api.LogManager, new NetBridge(_api.Enode, _api.SyncServer));

            _api.RpcModuleProvider.Register(new SingletonModulePool <INetModule>(netModule, true));

            ParityModule parityModule = new ParityModule(
                _api.EthereumEcdsa,
                _api.TxPool,
                _api.BlockTree,
                _api.ReceiptFinder,
                _api.Enode,
                _api.EngineSignerStore,
                _api.KeyStore,
                _api.LogManager);

            _api.RpcModuleProvider.Register(new SingletonModulePool <IParityModule>(parityModule, true));

            return(Task.CompletedTask);
        }
Exemple #30
0
 public ProfilesController(KeepService ks, VaultService vs, ProfileService ps)
 {
     _ps    = ps;
     _vserv = vs;
     _kserv = ks;
 }