コード例 #1
0
        static Global()
        {
            TorSocks5Endpoint = new IPEndPoint(IPAddress.Loopback, 9050);

            DataDir     = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Tests"));
            TorLogsFile = Path.Combine(DataDir, "TorLogs.txt");

            Logger.SetFilePath(Path.Combine(DataDir, "Logs.txt"));
            Logger.SetMinimumLevel(LogLevel.Info);
            Logger.SetModes(LogMode.Debug, LogMode.Console, LogMode.File);
        }
コード例 #2
0
        public Global()
        {
            DataDir          = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));
            TorLogsFile      = Path.Combine(DataDir, "TorLogs.txt");
            WalletsDir       = Path.Combine(DataDir, "Wallets");
            WalletBackupsDir = Path.Combine(DataDir, "WalletBackups");

            Directory.CreateDirectory(DataDir);
            Directory.CreateDirectory(WalletsDir);
            Directory.CreateDirectory(WalletBackupsDir);
        }
コード例 #3
0
ファイル: IoHelpers.cs プロジェクト: soobik/WalletWasabi
        public static void OpenFileInTextEditor(string filePath)
        {
            if (File.Exists(filePath))
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    // If no associated application/json MimeType is found xdg-open opens retrun error
                    // but it tries to open it anyway using the console editor (nano, vim, other..)
                    EnvironmentHelpers.ShellExec($"gedit {filePath} || xdg-open {filePath}", waitForExit: false);
                }
                else
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        bool openWithNotepad = true;                         // If there is an exception with the registry read we use notepad.

                        try
                        {
                            openWithNotepad = !EnvironmentHelpers.IsFileTypeAssociated("json");
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError(ex, nameof(IoHelpers));
                        }

                        if (openWithNotepad)
                        {
                            // Open file using Notepad.
                            using (Process process = Process.Start(new ProcessStartInfo
                            {
                                FileName = "notepad.exe",
                                Arguments = filePath,
                                CreateNoWindow = true,
                                UseShellExecute = false
                            }))
                            { }

                            return;                             // Opened with notepad, return.
                        }
                    }

                    // Open file wtih the default editor.
                    using (Process process = Process.Start(new ProcessStartInfo
                    {
                        FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? filePath : "open",
                        Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? $"-e {filePath}" : "",
                        CreateNoWindow = true,
                        UseShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    }))
                    { }
                }
            }
        }
コード例 #4
0
        private static string GetLogDirectory()
        {
            string logDirectory = EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.LogDirectory);

            if (logDirectory == null)
            {
                var nativeLogFile = EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.ProfilerLogPath);

                if (!string.IsNullOrEmpty(nativeLogFile))
                {
                    logDirectory = Path.GetDirectoryName(nativeLogFile);
                }
            }

            // This entire block may throw a SecurityException if not granted the System.Security.Permissions.FileIOPermission
            // because of the following API calls
            //   - Directory.Exists
            //   - Environment.GetFolderPath
            //   - Path.GetTempPath
            if (logDirectory == null)
            {
#if NETFRAMEWORK
                logDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Datadog .NET Tracer", "logs");
#else
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    logDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Datadog .NET Tracer", "logs");
                }
                else
                {
                    // Linux
                    logDirectory = "/var/log/datadog/dotnet";
                }
#endif
            }

            if (!Directory.Exists(logDirectory))
            {
                try
                {
                    Directory.CreateDirectory(logDirectory);
                }
                catch
                {
                    // Unable to create the directory meaning that the user
                    // will have to create it on their own.
                    // Last effort at writing logs
                    logDirectory = Path.GetTempPath();
                }
            }

            return(logDirectory);
        }
コード例 #5
0
 private static void SetupCircleCiEnvironment()
 {
     IsCI           = true;
     Provider       = "circleci";
     Repository     = EnvironmentHelpers.GetEnvironmentVariable("CIRCLE_REPOSITORY_URL");
     Commit         = EnvironmentHelpers.GetEnvironmentVariable("CIRCLE_SHA1");
     SourceRoot     = EnvironmentHelpers.GetEnvironmentVariable("CIRCLE_WORKING_DIRECTORY");
     PipelineId     = null;
     PipelineNumber = EnvironmentHelpers.GetEnvironmentVariable("CIRCLE_BUILD_NUM");
     PipelineUrl    = EnvironmentHelpers.GetEnvironmentVariable("CIRCLE_BUILD_URL");
     Branch         = EnvironmentHelpers.GetEnvironmentVariable("CIRCLE_BRANCH");
 }
コード例 #6
0
ファイル: Global.cs プロジェクト: kdmukai/WalletWasabi
        public Global()
        {
            DataDir          = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client"));
            TorLogsFile      = Path.Combine(DataDir, "TorLogs.txt");
            WalletsDir       = Path.Combine(DataDir, "Wallets");
            WalletBackupsDir = Path.Combine(DataDir, "WalletBackups");

            Directory.CreateDirectory(DataDir);
            Directory.CreateDirectory(WalletsDir);
            Directory.CreateDirectory(WalletBackupsDir);
            RpcMonitor = new RpcMonitor(TimeSpan.FromSeconds(7));
        }
コード例 #7
0
 private static void SetupBitbucketEnvironment()
 {
     IsCI           = true;
     Provider       = "bitbucketpipelines";
     Repository     = EnvironmentHelpers.GetEnvironmentVariable("BITBUCKET_GIT_SSH_ORIGIN");
     Commit         = EnvironmentHelpers.GetEnvironmentVariable("BITBUCKET_COMMIT");
     SourceRoot     = EnvironmentHelpers.GetEnvironmentVariable("BITBUCKET_CLONE_DIR");
     WorkspacePath  = EnvironmentHelpers.GetEnvironmentVariable("BITBUCKET_CLONE_DIR");
     PipelineId     = EnvironmentHelpers.GetEnvironmentVariable("BITBUCKET_PIPELINE_UUID");
     PipelineNumber = EnvironmentHelpers.GetEnvironmentVariable("BITBUCKET_BUILD_NUMBER");
     PipelineUrl    = null;
 }
コード例 #8
0
 private static void SetupGithubActionsEnvironment()
 {
     IsCI           = true;
     Provider       = "github";
     Repository     = EnvironmentHelpers.GetEnvironmentVariable("GITHUB_REPOSITORY");
     Commit         = EnvironmentHelpers.GetEnvironmentVariable("GITHUB_SHA");
     SourceRoot     = EnvironmentHelpers.GetEnvironmentVariable("GITHUB_WORKSPACE");
     PipelineId     = EnvironmentHelpers.GetEnvironmentVariable("GITHUB_RUN_ID");
     PipelineNumber = EnvironmentHelpers.GetEnvironmentVariable("GITHUB_RUN_NUMBER");
     PipelineUrl    = $"{Repository}/commit/{Commit}/checks";
     Branch         = EnvironmentHelpers.GetEnvironmentVariable("GITHUB_REF");
 }
コード例 #9
0
 private static void SetupBuildkiteEnvironment()
 {
     IsCI           = true;
     Provider       = "buildkite";
     Repository     = EnvironmentHelpers.GetEnvironmentVariable("BUILDKITE_REPO");
     Commit         = EnvironmentHelpers.GetEnvironmentVariable("BUILDKITE_COMMIT");
     SourceRoot     = EnvironmentHelpers.GetEnvironmentVariable("BUILDKITE_BUILD_CHECKOUT_PATH");
     PipelineId     = EnvironmentHelpers.GetEnvironmentVariable("BUILDKITE_BUILD_ID");
     PipelineNumber = EnvironmentHelpers.GetEnvironmentVariable("BUILDKITE_BUILD_NUMBER");
     PipelineUrl    = EnvironmentHelpers.GetEnvironmentVariable("BUILDKITE_BUILD_URL");
     Branch         = EnvironmentHelpers.GetEnvironmentVariable("BUILDKITE_BRANCH");
 }
コード例 #10
0
        public async Task CorrestWalletDirectoryNameAsync()
        {
            var baseDir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName());

            (string walletsPath, string walletsBackupPath) = await CleanupWalletDirectoriesAsync(baseDir);

            var walletDirectories = new WalletDirectories($" {baseDir} ");

            Assert.Equal(baseDir, walletDirectories.WorkDir);
            Assert.Equal(walletsPath, walletDirectories.WalletsDir);
            Assert.Equal(walletsBackupPath, walletDirectories.WalletsBackupDir);
        }
コード例 #11
0
ファイル: P2pBasedTests.cs プロジェクト: carsenk/WalletWasabi
        public async Task MempoolNotifiesAsync()
        {
            var coreNode = await TestNodeBuilder.CreateAsync();

            using var node = await coreNode.CreateP2pNodeAsync();

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

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

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

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

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

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

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

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

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

                foreach (var stx in stxs)
                {
                    Assert.Contains(stx.GetHash(), hashes);
                }
            }
            finally
            {
                node.Disconnect();
                await coreNode.StopAsync();
            }
        }
コード例 #12
0
        public RegTestFixture()
        {
            BackendNodeBuilder = NodeBuilder.CreateAsync(nameof(RegTestFixture)).GetAwaiter().GetResult();
            BackendNodeBuilder.CreateNodeAsync().GetAwaiter().GetResult();
            BackendNodeBuilder.StartAllAsync().GetAwaiter().GetResult();
            BackendRegTestNode = BackendNodeBuilder.Nodes[0];

            var rpc = BackendRegTestNode.CreateRpcClient();
            var connectionString = new RPCCredentialString()
            {
                Server       = rpc.Address.AbsoluteUri,
                UserPassword = BackendRegTestNode.Creds
            }.ToString();

            var testnetBackendDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Tests", "Backend"));

            IoHelpers.DeleteRecursivelyWithMagicDustAsync(testnetBackendDir).GetAwaiter().GetResult();
            Thread.Sleep(100);
            Directory.CreateDirectory(testnetBackendDir);
            Thread.Sleep(100);
            var config         = new Config(BackendNodeBuilder.Network, connectionString, IPAddress.Loopback.ToString(), IPAddress.Loopback.ToString(), BackendRegTestNode.Endpoint.Address.ToString(), Network.Main.DefaultPort, Network.TestNet.DefaultPort, BackendRegTestNode.Endpoint.Port);
            var configFilePath = Path.Combine(testnetBackendDir, "Config.json");

            config.SetFilePath(configFilePath);
            config.ToFileAsync().GetAwaiter().GetResult();

            var roundConfig         = CreateRoundConfig(Money.Coins(0.1m), Constants.OneDayConfirmationTarget, 0.7, 0.1m, 100, 120, 60, 60, 60, 1, 24, true, 11);
            var roundConfigFilePath = Path.Combine(testnetBackendDir, "CcjRoundConfig.json");

            roundConfig.SetFilePath(roundConfigFilePath);
            roundConfig.ToFileAsync().GetAwaiter().GetResult();

            var conf = new ConfigurationBuilder()
                       .AddInMemoryCollection(new[] { new KeyValuePair <string, string>("datadir", testnetBackendDir) })
                       .Build();

            BackendEndPoint = $"http://localhost:{new Random().Next(37130, 38000)}/";
            BackendHost     = WebHost.CreateDefaultBuilder()
                              .UseStartup <Startup>()
                              .UseConfiguration(conf)
                              .UseWebRoot("../../../../WalletWasabi.Backend/wwwroot")
                              .UseUrls(BackendEndPoint)
                              .Build();
            Global = (Backend.Global)BackendHost.Services.GetService(typeof(Backend.Global));
            var hostInitializationTask = BackendHost.RunWithTasksAsync();

            Logger.LogInfo($"Started Backend webhost: {BackendEndPoint}", nameof(Global));

            var delayTask = Task.Delay(3000);

            Task.WaitAny(delayTask, hostInitializationTask);             // Wait for server to initialize (Without this OSX CI will fail)
        }
コード例 #13
0
        public static async Task OpenFileInTextEditorAsync(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"The {Path.GetFileName(filePath)} file is not found.");
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                // If no associated application/json MimeType is found xdg-open opens retrun error
                // but it tries to open it anyway using the console editor (nano, vim, other..)
                await EnvironmentHelpers.ShellExecAsync($"which gedit &> /dev/null && gedit {filePath} || xdg-open {filePath}", waitForExit : false).ConfigureAwait(false);
            }
            else
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    bool openWithNotepad = true;                     // If there is an exception with the registry read we use notepad.

                    try
                    {
                        openWithNotepad = !EnvironmentHelpers.IsFileTypeAssociated("json");
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                    }

                    if (openWithNotepad)
                    {
                        // Open file using Notepad.
                        using Process notepadProcess = Process.Start(new ProcessStartInfo
                        {
                            FileName        = "notepad.exe",
                            Arguments       = filePath,
                            CreateNoWindow  = true,
                            UseShellExecute = false
                        });
                        return;                         // Opened with notepad, return.
                    }
                }

                // Open file with the default editor.
                using Process defaultEditorProcess = Process.Start(new ProcessStartInfo
                {
                    FileName        = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? filePath : "open",
                    Arguments       = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? $"-e {filePath}" : "",
                    CreateNoWindow  = true,
                    UseShellExecute = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                });
            }
        }
コード例 #14
0
ファイル: IndexStore.cs プロジェクト: ratpoison4/WalletWasabi
        private async Task TryEnsureBackwardsCompatibilityAsync()
        {
            try
            {
                // Before Wasabi 1.1.5
                var oldIndexFilePath = Path.Combine(EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client")), $"Index{Network}.dat");

                // Before Wasabi 1.1.6
                var oldFileNames = new[]
                {
                    "ImmatureIndex.dat",
                    "ImmatureIndex.dat.dig",
                    "MatureIndex.dat",
                    "MatureIndex.dat.dig"
                };

                var oldIndexFolderPath = Path.Combine(EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client")), "BitcoinStore", Network.ToString());

                foreach (var fileName in oldFileNames)
                {
                    var oldFilePath = Path.Combine(oldIndexFolderPath, fileName);
                    if (File.Exists(oldFilePath))
                    {
                        string newFilePath = oldFilePath.Replace(oldIndexFolderPath, WorkFolderPath);
                        if (File.Exists(newFilePath))
                        {
                            File.Delete(newFilePath);
                        }

                        File.Move(oldFilePath, newFilePath);
                    }
                }

                if (File.Exists(oldIndexFilePath))
                {
                    string[] allLines = await File.ReadAllLinesAsync(oldIndexFilePath);

                    var matureLines   = allLines.SkipLast(100);
                    var immatureLines = allLines.TakeLast(100);

                    await MatureIndexFileManager.WriteAllLinesAsync(matureLines);

                    await ImmatureIndexFileManager.WriteAllLinesAsync(immatureLines);

                    File.Delete(oldIndexFilePath);
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning($"Backwards compatibility could not be ensured. Exception: {ex}.");
            }
        }
コード例 #15
0
        static void Main(string[] args)
        {
            var server     = EnvironmentHelpers.GetServerUrl();
            var apiKey     = EnvironmentHelpers.GetApiKey();
            var endpoint   = new OctopusServerEndpoint(server, apiKey);
            var repository = new OctopusRepository(endpoint);

            var tenantResources = repository.Tenants.FindByName("Team 😄");

            ConsoleHelpers.Dump(tenantResources);

            Console.ReadKey();
        }
コード例 #16
0
        private static int GetRateLimit()
        {
            string rawRateLimit = EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.LogRateLimit);

            if (!string.IsNullOrEmpty(rawRateLimit) &&
                int.TryParse(rawRateLimit, out var rate) &&
                (rate >= 0))
            {
                return(rate);
            }

            return(DefaultLogMessageRateLimit);
        }
        public static async Task Run(
            [TimerTrigger("0 * * * * *")] TimerInfo myTimer,
            [OrchestrationClient] DurableOrchestrationClient client,
            [Microsoft.Azure.WebJobs.Table("MetricDatas", "Metrics", "001")] MetricData data,
            IAsyncCollector <MetricData> table,
            ILogger log)
        {
            log.LogMetricsCollector($"Executed at: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");

            var t = await client.GetStatusAsync(InstanceId);

            var content = JsonConvert.DeserializeObject <Content>(data.Content);

            if (IsStarted)
            {
                log.LogMetricsCollector("Get active message.");
                var currentActiveMessageCount = AzureHelpers.GetCurrentMetrics();

                log.LogMetricsCollector($"Current message count: {currentActiveMessageCount}");

                log.LogMetricsCollector($"Calculate current part metrics.");

                var currentDayActiveMessageCount = currentActiveMessageCount - content.MessageCount;

                content.MessageCount = currentActiveMessageCount;
                content.AddData(currentActiveMessageCount);
                var @event = new MetricCollected(currentDayActiveMessageCount);

                data.Content = JsonConvert.SerializeObject(content);
                await table.AddAsync(data);

                log.LogMetricsCollector($"Raise event to scaling function.");
                await client.RaiseEventAsync(InstanceId, nameof(MetricCollected), @event);

                log.LogMetricsCollector("Done.");
            }
            else
            {
                AutoregresiveParam = EnvironmentHelpers.GetIntegerEnvironmentParameter(nameof(MasterPerformMetricsCollector.AutoregresiveParam));
                IntegrationParam   = EnvironmentHelpers.GetIntegerEnvironmentParameter(nameof(MasterPerformMetricsCollector.IntegrationParam));
                MoveAverrageParam  = EnvironmentHelpers.GetIntegerEnvironmentParameter(nameof(MasterPerformMetricsCollector.MoveAverrageParam));
                Period             = EnvironmentHelpers.GetIntegerEnvironmentParameter(nameof(MasterPerformMetricsCollector.Period));
                Q = EnvironmentHelpers.GetIntegerEnvironmentParameter(nameof(MasterPerformMetricsCollector.Q));
                var costForPeriod = EnvironmentHelpers.GetDoubleEnvironmentParameter("CostForPeriod");
                CostOfOneMachine = EnvironmentHelpers.GetIntegerEnvironmentParameter(nameof(MasterPerformMetricsCollector.CostOfOneMachine));

                log.LogMetricsCollector($"Start first forecasting.");
                IsStarted  = true;
                InstanceId = await client.StartNewAsync(nameof(ScalingFunction), new ScalingState(content.Data, costForPeriod));
            }
        }
コード例 #18
0
        private void LoadAzureCredentials()
        {
            cRndRandom = new Random(System.Environment.TickCount);
            String  pStrCreds = File.ReadAllText("../../../../azure/creds.json");
            JObject pJOtCreds = JObject.Parse(pStrCreds);

            cStrTableStorageRootURL = pJOtCreds["TableStorageRootURL"].Value <String>();
            cStrConnectionString    = pJOtCreds["ConnectionString"].Value <String>();
            EnvironmentHelpers.SetEnvironmentVariable("HOME", @"C:\Temp", EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("TableStorageRootURL", cStrTableStorageRootURL, EnvironmentVariableTarget.Process);
            EnvironmentHelpers.SetEnvironmentVariable("AzureWebJobsStorage", cStrConnectionString, EnvironmentVariableTarget.Process);

            cLisUsers = new List <CreateUserArgs>();
            for (Int32 curUserIndex = 1; curUserIndex <= NOOFUSERS; curUserIndex++)
            {
                String pStrEmail = String.Format("{0}@{1}.com",
                                                 CryptographyHelpers.RandomString(12),
                                                 CryptographyHelpers.RandomString(12));
                String pStrUserName       = CryptographyHelpers.RandomString(12);
                String pStrActivationCode = CryptographyHelpers.RandomString(6);
                cLisUsers.Add(new CreateUserArgs()
                {
                    Email          = pStrEmail,
                    UserName       = pStrUserName,
                    ActivationCode = pStrActivationCode
                });
            }

            for (Int32 curUserIndex = 1; curUserIndex <= NOOFUSERS; curUserIndex++)
            {
                CreateUserArgs pCUAUser = cLisUsers[curUserIndex - 1];
                pCUAUser.Friends = new List <CreateUserArgs>();
                List <Int32> pLisIndexes = new List <Int32>();
                for (Int32 curFriendIndex = 1; curFriendIndex <= NOOFRIENDSPERUSER; curFriendIndex++)
                {
                    List <CreateUserArgs> pLisFriends = new List <CreateUserArgs>();

                    //Get a random user that isn't us
                    Int32 pIntUserIndex = cRndRandom.Next(0, NOOFUSERS);
                    while (pIntUserIndex == curFriendIndex - 1 ||
                           pLisIndexes.Contains(pIntUserIndex))
                    {
                        pIntUserIndex = cRndRandom.Next(0, NOOFUSERS);
                    }

                    pLisIndexes.Add(pIntUserIndex);
                    pCUAUser.Friends.Add(cLisUsers[pIntUserIndex]);
                }
            }
        }
コード例 #19
0
        private void ProcessDirectory(string directoryPath)
        {
            var savedDirectory = Directory.GetCurrentDirectory();

            Directory.SetCurrentDirectory(directoryPath);
            _loader = EnvironmentHelpers.CreateProxy <AssemblyLoader>(directoryPath, out _testDomain);
            foreach (var file in Directory.GetFiles(directoryPath).Where(file => file.EndsWith(".dll")))
            {
                AssemblyRecord assembly = CreateAssemblyRecord(file);
                _assemblies[assembly.Name] = assembly;
                if (RequiresExactVersionMatch(assembly))
                {
                    AddSharedAssemblyExactVersion(assembly);
                }
                else
                {
                    AddSharedAssembly(assembly);
                }
            }

            // Now check for assembly mismatches
            foreach (var assembly in _assemblies.Values)
            {
                foreach (var reference in assembly.Children)
                {
                    CheckAssemblyReference(reference, assembly);
                }
            }

            foreach (var assembly in _assemblies.Values)
            {
                foreach (var parent in assembly.ReferencingAssembly)
                {
                    _dependencyMapLogger.LogRecord(
                        new DependencyMap
                    {
                        AssemblyName               = assembly.Name,
                        AssemblyVersion            = assembly.Version.ToString(),
                        ReferencingAssembly        = parent.Name,
                        ReferencingAssemblyVersion = parent.Version.ToString(),
                        Severity = 3
                    });
                }
            }

            FindExtraAssemblies();

            AppDomain.Unload(_testDomain);
            Directory.SetCurrentDirectory(savedDirectory);
        }
コード例 #20
0
        internal static NativeCallTargetDefinition[] GetServerlessDefinitions()
        {
            try
            {
                LambdaHandler handler      = new LambdaHandler(EnvironmentHelpers.GetEnvironmentVariable(HandlerEnvName));
                var           assemblyName = typeof(InstrumentationDefinitions).Assembly.FullName;
                var           paramCount   = handler.ParamTypeArray.Length;

                var integrationType = GetIntegrationType(handler.ParamTypeArray[0], paramCount);
                return(new NativeCallTargetDefinition[]
                {
                    new(handler.GetAssembly(), handler.GetFullType(), handler.GetMethodName(), handler.ParamTypeArray, 0, 0, 0, 65535, 65535, 65535, assemblyName, integrationType)
                });
            }
コード例 #21
0
        public async Task TrustedNotifierNotifiesTxAsync()
        {
            using var services = new HostedServices();
            var coreNode = await TestNodeBuilder.CreateAsync(services);

            await services.StartAllAsync(CancellationToken.None);

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

                var network = rpc.Network;

                var dir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName());

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

                var txNum          = 10;
                var txEventAwaiter = new EventsAwaiter <SmartTransaction>(
                    h => notifier.TransactionReceived += h,
                    h => notifier.TransactionReceived -= h,
                    txNum);

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

                var arrivedTxs = await txEventAwaiter.WaitAsync(TimeSpan.FromSeconds(21));

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

                foreach (var hash in arrivedTxs.Select(x => x.GetHash()))
                {
                    Assert.Contains(hash, hashes);
                }
            }
            finally
            {
                await services.StopAllAsync(CancellationToken.None);

                await coreNode.TryStopAsync();
            }
        }
コード例 #22
0
        public async Task ServesWalletFilesAsync()
        {
            var baseDir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName());

            await CleanupWalletDirectoriesAsync(baseDir);

            var    walletDirectories = new WalletDirectories(baseDir);
            string walletName        = "FooWallet.json";

            (string walletPath, string walletBackupPath) = walletDirectories.GetWalletFilePaths(walletName);

            Assert.Equal(Path.Combine(walletDirectories.WalletsDir, walletName), walletPath);
            Assert.Equal(Path.Combine(walletDirectories.WalletsBackupDir, walletName), walletBackupPath);
        }
コード例 #23
0
    private void EnsureBackwardsCompatibility()
    {
        try
        {
            // Before Wasabi 1.1.7
            var networkIndependentTransactionsFolderPath = Path.Combine(EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client")), "Transactions");
            if (Directory.Exists(networkIndependentTransactionsFolderPath))
            {
                var oldTransactionsFolderPath = Path.Combine(networkIndependentTransactionsFolderPath, Network.Name);
                if (Directory.Exists(oldTransactionsFolderPath))
                {
                    lock (Lock)
                    {
                        foreach (var filePath in Directory.EnumerateFiles(oldTransactionsFolderPath))
                        {
                            try
                            {
                                string jsonString            = File.ReadAllText(filePath, Encoding.UTF8);
                                var    allWalletTransactions = JsonConvert.DeserializeObject <IEnumerable <SmartTransaction> >(jsonString)?.OrderByBlockchain() ?? Enumerable.Empty <SmartTransaction>();
                                foreach (var tx in allWalletTransactions)
                                {
                                    AddOrUpdateNoLock(tx);
                                }

                                File.Delete(filePath);
                            }
                            catch (Exception ex)
                            {
                                Logger.LogTrace(ex);
                            }
                        }

                        Directory.Delete(oldTransactionsFolderPath, recursive: true);
                    }
                }

                // If all networks successfully migrated, too, then delete the transactions folder, too.
                if (!Directory.EnumerateFileSystemEntries(networkIndependentTransactionsFolderPath).Any())
                {
                    Directory.Delete(networkIndependentTransactionsFolderPath, recursive: true);
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogWarning("Backwards compatibility could not be ensured.");
            Logger.LogWarning(ex);
        }
    }
コード例 #24
0
        public void CanStoreSeedWords()
        {
            var testDir  = EnvironmentHelpers.GetDataDir(Path.Combine("Chaincase", "Tests", "StorageTests"));
            var config   = new Config(Path.Combine(testDir, "Config.json"));
            var uiConfig = new UiConfig(Path.Combine(testDir, "UiConfig.json"));

            SensitiveStorage storage  = new(new MockHsmStorage(), config, uiConfig);
            string           password = "******";
            Mnemonic         mnemonic = new(Wordlist.English);

            storage.SetSeedWords(password, mnemonic.ToString());
            var gotSeedWords = storage.GetSeedWords(password).Result;

            Assert.True(gotSeedWords == mnemonic.ToString());
        }
コード例 #25
0
        public Global()
        {
            TorSocks5Endpoint = new IPEndPoint(IPAddress.Loopback, 9050);

            DataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Tests"));

            string torLogsFile           = Path.Combine(DataDir, "TorLogs.txt");
            string torDistributionFolder = Path.Combine(EnvironmentHelpers.GetFullBaseDirectory(), "TorDaemons");

            TorSettings = new TorSettings(DataDir, torLogsFile, torDistributionFolder);

            Logger.SetFilePath(Path.Combine(DataDir, "Logs.txt"));
            Logger.SetMinimumLevel(LogLevel.Info);
            Logger.SetModes(LogMode.Debug, LogMode.Console, LogMode.File);
        }
コード例 #26
0
        static void Main(string[] args)
        {
            var server     = EnvironmentHelpers.GetServerUrl();
            var apiKey     = EnvironmentHelpers.GetApiKey();
            var endpoint   = new OctopusServerEndpoint(server, apiKey);
            var repository = new OctopusRepository(endpoint);

            var guest = repository.Configuration.Get <GuestConfigurationResource>();

            ConsoleHelpers.Dump(guest);
            guest.IsEnabled = !guest.IsEnabled;
            guest           = repository.Configuration.Modify(guest);
            ConsoleHelpers.Dump(guest);
            Console.ReadLine();
        }
コード例 #27
0
        public bool Match(IReportRecord other)
        {
            var result = false;
            var record = other as ExtraAssembly;

            if (record != null)
            {
                result = string.Equals(EnvironmentHelpers.GetDirectoryName(record.Directory),
                                       EnvironmentHelpers.GetDirectoryName(Directory), StringComparison.OrdinalIgnoreCase) &&
                         string.Equals(record.AssemblyName, AssemblyName, StringComparison.OrdinalIgnoreCase) &&
                         record.ProblemId == ProblemId;
            }

            return(result);
        }
コード例 #28
0
        public async Task CreatesWalletDirectoriesAsync()
        {
            var baseDir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName());

            (string walletsPath, string walletsBackupPath) = await CleanupWalletDirectoriesAsync(baseDir);

            new WalletDirectories(baseDir);
            Assert.True(Directory.Exists(walletsPath));
            Assert.True(Directory.Exists(walletsBackupPath));

            // Testing what happens if the directories are already exist.
            new WalletDirectories(baseDir);
            Assert.True(Directory.Exists(walletsPath));
            Assert.True(Directory.Exists(walletsBackupPath));
        }
コード例 #29
0
        /// <summary>
        /// Generate the serialized module metadata for a given module.
        /// </summary>
        public void SerializeModule()
        {
            var outputModuleManifestPath   = _fileHelper.OutputModuleManifestPath;
            var outputModuleDirectory      = _fileHelper.OutputModuleDirectory;
            var outputDirectories          = _fileHelper.OutputDirectories;
            var serializedCmdletsDirectory = _fileHelper.SerializedCmdletsDirectory;
            var moduleName = _fileHelper.ModuleName;
            IEnumerable <string> nestedModules = null;

            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddScript("(Test-ModuleManifest -Path " + outputModuleManifestPath + ").NestedModules");
                var cmdletResult = powershell.Invoke();
                nestedModules = cmdletResult.Select(c => c.ToString() + ".dll");
            }

            if (nestedModules.Any())
            {
                List <string> requiredModules = null;
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.AddScript("(Test-ModuleManifest -Path " + outputModuleManifestPath + ").RequiredModules");
                    var cmdletResult = powershell.Invoke();
                    requiredModules = cmdletResult.Select(c => c.ToString())
                                      .Join(outputDirectories,
                                            module => 1,
                                            directory => 1,
                                            (module, directory) => Path.Combine(directory, module))
                                      .Where(f => Directory.Exists(f))
                                      .ToList();
                }

                requiredModules.Add(outputModuleDirectory);
                foreach (var nestedModule in nestedModules)
                {
                    var assemblyPath         = Directory.GetFiles(outputModuleDirectory, nestedModule, SearchOption.AllDirectories).FirstOrDefault();
                    var proxy                = EnvironmentHelpers.CreateProxy <CmdletLoader>(outputModuleManifestPath, out _appDomain);
                    var newModuleMetadata    = proxy.GetModuleMetadata(assemblyPath, requiredModules);
                    var serializedCmdletName = nestedModule + ".json";
                    var serializedCmdletFile = Path.Combine(serializedCmdletsDirectory, serializedCmdletName);
                    SerializeCmdlets(serializedCmdletFile, newModuleMetadata);
                }
            }
            else
            {
                Console.WriteLine("No nested module(s) found for " + moduleName + " -- skipping serialization step.");
            }
        }
コード例 #30
0
        private void PrepareTestEnv(out string dir, out Network network, out string mempoolFile, out string txFile, out SmartTransaction uTx1, out SmartTransaction uTx2, out SmartTransaction uTx3, out SmartTransaction cTx1, out SmartTransaction cTx2, out SmartTransaction cTx3, [CallerFilePath] string callerFilePath = "", [CallerMemberName] string callerMemberName = "")
        {
            dir         = PrepareWorkDir(EnvironmentHelpers.ExtractFileName(callerFilePath), callerMemberName);
            network     = Network.TestNet;
            mempoolFile = Path.Combine(dir, "Mempool", "Transactions.dat");
            txFile      = Path.Combine(dir, "ConfirmedTransactions", Constants.ConfirmedTransactionsVersion, "Transactions.dat");
            IoHelpers.EnsureContainingDirectoryExists(mempoolFile);
            IoHelpers.EnsureContainingDirectoryExists(txFile);

            uTx1 = SmartTransaction.FromLine("34fc45781f2ac8e541b6045c2858c755dd2ab85e0ea7b5778b4d0cc191468571:01000000000102d5ae6e2612cdf8932d0e4f684d8ad9afdbca0afffba5c3dc0bf85f2b661bfb670000000000ffffffffbfd117908d5ba536624630519aaea7419605efa33bf1cb50c5ff7441f7b27a5b0100000000ffffffff01c6473d0000000000160014f9d25fe27812c3d35ad3819fcab8b95098effe15024730440220165730f8275434a5484b6aba3c71338a109b7cfd7380fdc18c6791a6afba9dee0220633b3b65313e57bdbd491d17232e6702912869d81461b4c939600d1cc99c06ec012102667c9fb272660cd6c06f853314b53c41da851f86024f9475ff15ea0636f564130247304402205e81562139231274cd7f705772c2810e34b7a291bd9882e6c567553babca9c7402206554ebd60d62a605a27bd4bf6482a533dd8dd35b12dc9d6abfa21738fdf7b57a012102b25dec5439a1aad8d901953a90d16252514a55f547fe2b85bc12e3f72cff1c4b00000000:Mempool::0::1570464578:False", network);
            uTx2 = SmartTransaction.FromLine("b5cd5b4431891d913a6fbc0e946798b6f730c8b97f95a5c730c24189bed24ce7:01000000010113145dd6264da43406a0819b6e2d791ec9281322f33944ef034c3307f38c330000000000ffffffff0220a10700000000001600149af662cf9564700b93bd46fac8b51f64f2adad2343a5070000000000160014f1938902267eac1ae527128fe7773657d2b757b900000000:Mempool::0::1555590391:False", network);
            uTx3 = SmartTransaction.FromLine("89e6788e63c5966fae0ccf6e85665ec62754f982b9593d7e3c4b78ac0e93208d:01000000000101f3e7c1bce1e0566800d8e6cae8f0d771a2ace8939cc6be7c8c21b05e590969530000000000ffffffff01cc2b0f0000000000160014e0ff6f42032bbfda63fabe0832b4ccb7be7350ae024730440220791e34413957c0f8348718d5d767f660657faf241801e74b5b81ac69e8912f60022041f3e9aeca137044565e1a81b6bcca74a88166436e5fa5f0e390448ac18fa5900121034dc07f3c26734591eb97f7e112888c3198d62bc3718106cba5a5688c62485b4500000000:Mempool::0::1555590448:False", network);
            cTx1 = SmartTransaction.FromLine("95374c1037eb5268c8ae6681eb26756459d19754d41b660c251e6f62df586d29:0100000001357852bdf4e75a4ee2afe213463ff8afbed977ea5459a310777322504254ffdf0100000000ffffffff0240420f0000000000160014dc992214c430bf306fe446e9bac1dfc4ad4d3ee368cc100300000000160014005340d370675c47f7a04eb186200dd98c3d463c00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:307::1569940579:False", network);
            cTx2 = SmartTransaction.FromLine("af73b4c173da1bd24063e35a755babfa40728a282d6f56eeef4ce5a81ab26ee7:01000000013c81d2dcb25ad36781d1a6f9faa68f4a8b927f40e0b4e4b6184bb4761ebfc0dd0000000000ffffffff016f052e0000000000160014ae6e31ee9dae103f50979f761c2f9b44661da24f00000000:1580176:0000000034522ee38f074e1f4330b9c2f20c6a2b9a96de6f474a5f5f8fa76e2b:346::1569940633:False", network);
            cTx3 = SmartTransaction.FromLine("ebcef423f6b03ef89dce076b53e624c966381f76e5d8b2b5034d3615ae950b2f:01000000000101296d58df626f1e250c661bd45497d159647526eb8166aec86852eb37104c37950100000000ffffffff01facb100300000000160014d5461e0e7077d62c4cf9c18a4e9ba10efd4930340247304402206d2c5b2b182474531ed07587e44ea22b136a37d5ddbd35aa2d984da7be5f7e5202202abd8435d9856e3d0892dbd54e9c05f2a20d9d5f333247314b925947a480a2eb01210321dd0574c773a35d4a7ebf17bf8f974b5665c0183598f1db53153e74c876768500000000:1580673:0000000017b09a77b815f3df513ff698d1f3b0e8c5e16ac0d6558e2d831f3bf9:130::1570462988:False", network);
        }