public IndexBuilderService(IRPCClient rpc, BlockNotifier blockNotifier, string indexFilePath)
        {
            RpcClient     = Guard.NotNull(nameof(rpc), rpc);
            BlockNotifier = Guard.NotNull(nameof(blockNotifier), blockNotifier);
            IndexFilePath = Guard.NotNullOrEmptyOrWhitespace(nameof(indexFilePath), indexFilePath);

            Index     = new List <FilterModel>();
            IndexLock = new AsyncLock();

            StartingHeight = SmartHeader.GetStartingHeader(RpcClient.Network).Height;

            _serviceStatus = NotStarted;

            IoHelpers.EnsureContainingDirectoryExists(IndexFilePath);
            if (File.Exists(IndexFilePath))
            {
                if (RpcClient.Network == Network.RegTest)
                {
                    File.Delete(IndexFilePath);                     // RegTest is not a global ledger, better to delete it.
                }
                else
                {
                    foreach (var line in File.ReadAllLines(IndexFilePath))
                    {
                        var filter = FilterModel.FromLine(line);
                        Index.Add(filter);
                    }
                }
            }

            BlockNotifier.OnBlock += BlockNotifier_OnBlock;
        }
Esempio n. 2
0
        public async Task WriteAllLinesAsync(IEnumerable <string> lines, CancellationToken cancellationToken = default, bool dismissNullOrEmptyContent = true)
        {
            if (dismissNullOrEmptyContent)
            {
                if (lines is null || !lines.Any())
                {
                    return;
                }
            }

            var byteArrayBuilder = new ByteArrayBuilder();

            foreach (var line in lines)
            {
                ContinueBuildHash(byteArrayBuilder, line);
            }

            var res = await WorkWithHashAsync(byteArrayBuilder, cancellationToken);

            if (res.same)
            {
                return;
            }

            IoHelpers.EnsureContainingDirectoryExists(NewFilePath);

            await File.WriteAllLinesAsync(NewFilePath, lines, cancellationToken);

            SafeMoveNewToOriginal();
            await WriteOutHashAsync(res.hash);
        }
        public new async Task AppendAllLinesAsync(IEnumerable <string> lines, CancellationToken cancellationToken = default)
        {
            if (lines is null || !lines.Any())
            {
                return;
            }

            IoHelpers.EnsureContainingDirectoryExists(NewFilePath);
            if (File.Exists(NewFilePath))
            {
                File.Delete(NewFilePath);
            }

            var byteArrayBuilder = new ByteArrayBuilder();

            var linesArray = lines.ToArray();
            var linesIndex = 0;

            using (var sr = OpenText())
                using (var fs = File.OpenWrite(NewFilePath))
                    using (var sw = new StreamWriter(fs, Encoding.ASCII, Constants.BigFileReadWriteBufferSize))
                    {
                        // 1. First copy.
                        if (!sr.EndOfStream)
                        {
                            var    lineTask = sr.ReadLineAsync();
                            Task   wTask    = Task.CompletedTask;
                            string?line     = null;
                            while (lineTask is { })
Esempio n. 4
0
 public override async Task StopAsync(CancellationToken cancellationToken)
 {
     if (AddressManagerFilePath is { } addressManagerFilePath)
     {
         IoHelpers.EnsureContainingDirectoryExists(addressManagerFilePath);
         var addressManager = AddressManager;
         if (addressManager is { })
Esempio n. 5
0
    public static async Task AddOrRemoveDesktopFileAsync(bool runOnSystemStartup)
    {
        string pathToDir         = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "autostart");
        string pathToDesktopFile = Path.Combine(pathToDir, "Wasabi.desktop");

        IoHelpers.EnsureContainingDirectoryExists(pathToDesktopFile);

        if (runOnSystemStartup)
        {
            string pathToExec = EnvironmentHelpers.GetExecutablePath();

            string pathToExecWithArgs = $"{pathToExec} {StartupHelper.SilentArgument}";

            IoHelpers.EnsureFileExists(pathToExec);

            string fileContents = string.Join(
                "\n",
                "[Desktop Entry]",
                $"Name={Constants.AppName}",
                "Type=Application",
                $"Exec={pathToExecWithArgs}",
                "Hidden=false",
                "Terminal=false",
                "X-GNOME-Autostart-enabled=true");

            await File.WriteAllTextAsync(pathToDesktopFile, fileContents).ConfigureAwait(false);
        }
        else
        {
            File.Delete(pathToDesktopFile);
        }
    }
Esempio n. 6
0
        public static async Task DisposeAsync()
        {
            try
            {
                await DisposeInWalletDependentServicesAsync();

                UpdateChecker?.Dispose();
                Logger.LogInfo($"{nameof(UpdateChecker)} is stopped.", nameof(Global));

                Synchronizer?.Dispose();
                Logger.LogInfo($"{nameof(Synchronizer)} is stopped.", nameof(Global));

                IoHelpers.EnsureContainingDirectoryExists(AddressManagerFilePath);
                AddressManager?.SavePeerFile(AddressManagerFilePath, Config.Network);
                Logger.LogInfo($"{nameof(AddressManager)} is saved to `{AddressManagerFilePath}`.", nameof(Global));

                Nodes?.Dispose();
                Logger.LogInfo($"{nameof(Nodes)} are disposed.", nameof(Global));

                if (!(RegTestMemPoolServingNode is null))
                {
                    RegTestMemPoolServingNode.Disconnect();
                    Logger.LogInfo($"{nameof(RegTestMemPoolServingNode)} is disposed.", nameof(Global));
                }

                TorManager?.Dispose();
                Logger.LogInfo($"{nameof(TorManager)} is stopped.", nameof(Global));
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, nameof(Global));
            }
        }
        private volatile bool _disposedValue = false;         // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    using (RoundsListLock.Lock())
                    {
                        foreach (CcjRound round in Rounds)
                        {
                            round.StatusChanged       -= Round_StatusChangedAsync;
                            round.CoinJoinBroadcasted -= Round_CoinJoinBroadcasted;
                        }

                        try
                        {
                            string roundCountFilePath = Path.Combine(FolderPath, "RoundCount.txt");

                            IoHelpers.EnsureContainingDirectoryExists(roundCountFilePath);
                            File.WriteAllText(roundCountFilePath, CcjRound.RoundCount.ToString());
                        }
                        catch (Exception ex)
                        {
                            Logger.LogDebug <CcjCoordinator>(ex);
                        }
                    }
                }

                _disposedValue = true;
            }
        }
Esempio n. 8
0
    public WabiSabiCoordinator(CoordinatorParameters parameters, IRPCClient rpc, ICoinJoinIdStore coinJoinIdStore)
    {
        Parameters = parameters;

        Warden          = new(parameters.UtxoWardenPeriod, parameters.PrisonFilePath, Config);
        ConfigWatcher   = new(parameters.ConfigChangeMonitoringPeriod, Config, () => Logger.LogInfo("WabiSabi configuration has changed."));
        CoinJoinIdStore = coinJoinIdStore;
        CoinJoinTransactionArchiver transactionArchiver = new(Path.Combine(parameters.CoordinatorDataDir, "CoinJoinTransactions"));

        CoinJoinFeeRateStatStore = CoinJoinFeeRateStatStore.LoadFromFile(parameters.CoinJoinFeeRateStatStoreFilePath, Config, rpc);
        IoHelpers.EnsureContainingDirectoryExists(Parameters.CoinJoinFeeRateStatStoreFilePath);
        CoinJoinFeeRateStatStore.NewStat += FeeRateStatStore_NewStat;

        var coinJoinScriptStore = CoinJoinScriptStore.LoadFromFile(parameters.CoinJoinScriptStoreFilePath);

        IoHelpers.EnsureContainingDirectoryExists(Parameters.CoinJoinScriptStoreFilePath);

        RoundParameterFactory roundParameterFactory = new RoundParameterFactory(Config, rpc.Network);

        Arena = new(
            parameters.RoundProgressSteppingPeriod,
            rpc.Network,
            Config,
            rpc,
            Warden.Prison,
            coinJoinIdStore,
            roundParameterFactory,
            transactionArchiver,
            coinJoinScriptStore);

        IoHelpers.EnsureContainingDirectoryExists(Parameters.CoinJoinIdStoreFilePath);
        Arena.CoinJoinBroadcast += Arena_CoinJoinBroadcast;
    }
Esempio n. 9
0
        public IndexBuilderService(RPCClient rpc, TrustedNodeNotifyingBehavior trustedNodeNotifyingBehavior, string indexFilePath, string bech32UtxoSetFilePath)
        {
            RpcClient = Guard.NotNull(nameof(rpc), rpc);
            TrustedNodeNotifyingBehavior = Guard.NotNull(nameof(trustedNodeNotifyingBehavior), trustedNodeNotifyingBehavior);
            IndexFilePath         = Guard.NotNullOrEmptyOrWhitespace(nameof(indexFilePath), indexFilePath);
            Bech32UtxoSetFilePath = Guard.NotNullOrEmptyOrWhitespace(nameof(bech32UtxoSetFilePath), bech32UtxoSetFilePath);

            Bech32UtxoSet        = new Dictionary <OutPoint, Script>();
            Bech32UtxoSetHistory = new List <ActionHistoryHelper>(capacity: 100);
            Index     = new List <FilterModel>();
            IndexLock = new AsyncLock();

            StartingFilter = StartingFilters.GetStartingFilter(RpcClient.Network);
            StartingHeight = StartingFilters.GetStartingHeight(RpcClient.Network);

            _running = 0;

            IoHelpers.EnsureContainingDirectoryExists(IndexFilePath);
            if (File.Exists(IndexFilePath))
            {
                if (RpcClient.Network == Network.RegTest)
                {
                    File.Delete(IndexFilePath);                     // RegTest is not a global ledger, better to delete it.
                }
                else
                {
                    var height = StartingHeight;
                    foreach (var line in File.ReadAllLines(IndexFilePath))
                    {
                        var filter = FilterModel.FromHeightlessLine(line, height);
                        height++;
                        Index.Add(filter);
                    }
                }
            }

            IoHelpers.EnsureContainingDirectoryExists(bech32UtxoSetFilePath);
            if (File.Exists(bech32UtxoSetFilePath))
            {
                if (RpcClient.Network == Network.RegTest)
                {
                    File.Delete(bech32UtxoSetFilePath);                     // RegTest is not a global ledger, better to delete it.
                }
                else
                {
                    foreach (var line in File.ReadAllLines(Bech32UtxoSetFilePath))
                    {
                        var parts = line.Split(':');

                        var txHash = new uint256(parts[0]);
                        var nIn    = int.Parse(parts[1]);
                        var script = new Script(ByteHelpers.FromHex(parts[2]), true);
                        Bech32UtxoSet.Add(new OutPoint(txHash, nIn), script);
                    }
                }
            }

            TrustedNodeNotifyingBehavior.BlockInv += TrustedNodeNotifyingBehavior_BlockInv;
        }
		public IndexBuilderService(RPCClient rpc, BlockNotifier blockNotifier, string indexFilePath, string bech32UtxoSetFilePath)
		{
			RpcClient = Guard.NotNull(nameof(rpc), rpc);
			BlockNotifier = Guard.NotNull(nameof(blockNotifier), blockNotifier);
			IndexFilePath = Guard.NotNullOrEmptyOrWhitespace(nameof(indexFilePath), indexFilePath);
			Bech32UtxoSetFilePath = Guard.NotNullOrEmptyOrWhitespace(nameof(bech32UtxoSetFilePath), bech32UtxoSetFilePath);

			Bech32UtxoSet = new Dictionary<OutPoint, UtxoEntry>();
			Bech32UtxoSetHistory = new List<ActionHistoryHelper>(capacity: 100);
			Index = new List<FilterModel>();
			IndexLock = new AsyncLock();

			StartingHeight = SmartHeader.GetStartingHeader(RpcClient.Network).Height;

			_running = 0;

			IoHelpers.EnsureContainingDirectoryExists(IndexFilePath);
			if (File.Exists(IndexFilePath))
			{
				if (RpcClient.Network == Network.RegTest)
				{
					File.Delete(IndexFilePath); // RegTest is not a global ledger, better to delete it.
				}
				else
				{
					foreach (var line in File.ReadAllLines(IndexFilePath))
					{
						var filter = FilterModel.FromLine(line);
						Index.Add(filter);
					}
				}
			}

			IoHelpers.EnsureContainingDirectoryExists(bech32UtxoSetFilePath);
			if (File.Exists(bech32UtxoSetFilePath))
			{
				if (RpcClient.Network == Network.RegTest)
				{
					File.Delete(bech32UtxoSetFilePath); // RegTest is not a global ledger, better to delete it.
				}
				else
				{
					foreach (var line in File.ReadAllLines(Bech32UtxoSetFilePath))
					{
						var parts = line.Split(':');

						var txHash = new uint256(parts[0]);
						var nIn = int.Parse(parts[1]);
						var script = new Script(ByteHelpers.FromHex(parts[2]), true);
						OutPoint outPoint = new OutPoint(txHash, nIn);
						var utxoEntry = new UtxoEntry(outPoint, script);
						Bech32UtxoSet.Add(outPoint, utxoEntry);
					}
				}
			}

			BlockNotifier.OnBlock += BlockNotifier_OnBlock;
		}
Esempio n. 11
0
        /// <summary>
        /// Creates a new instance of the object.
        /// </summary>
        /// <param name="settings">Tor settings.</param>
        /// <param name="torSocks5EndPoint">Valid Tor end point.</param>
        public TorProcessManager(TorSettings settings, EndPoint torSocks5EndPoint)
        {
            TorSocks5EndPoint = torSocks5EndPoint;
            TorProcess        = null;
            Settings          = settings;
            TorSocks5Client   = new TorSocks5Client(torSocks5EndPoint);

            IoHelpers.EnsureContainingDirectoryExists(Settings.LogFilePath);
        }
Esempio n. 12
0
 public void SetFilePath(string filePath)
 {
     FilePath = string.IsNullOrWhiteSpace(filePath) ? null : filePath;
     if (FilePath is null)
     {
         return;
     }
     IoHelpers.EnsureContainingDirectoryExists(FilePath);
 }
Esempio n. 13
0
 public void ToFile(string filePath)
 {
     IoHelpers.EnsureContainingDirectoryExists(filePath);
     lock (ToFileLock)
     {
         string jsonString = JsonConvert.SerializeObject(this, Formatting.Indented);
         File.WriteAllText(filePath, jsonString, Encoding.UTF8);
     }
 }
Esempio n. 14
0
    public async Task AppendAllLinesAsync(IEnumerable <string> lines, CancellationToken cancellationToken = default)
    {
        if (lines is null || !lines.Any())
        {
            return;
        }

        IoHelpers.EnsureContainingDirectoryExists(FilePath);

        await File.AppendAllLinesAsync(FilePath, lines, cancellationToken).ConfigureAwait(false);
    }
Esempio n. 15
0
        /// <summary>
        /// Creates a new instance of the object.
        /// </summary>
        /// <param name="settings">Tor settings.</param>
        /// <param name="torSocks5EndPoint">Valid Tor end point.</param>
        public TorProcessManager(TorSettings settings, EndPoint torSocks5EndPoint)
        {
            TorSocks5EndPoint = torSocks5EndPoint;
            _monitorState     = StateNotStarted;
            Stop            = new CancellationTokenSource();
            TorProcess      = null;
            Settings        = settings;
            TorSocks5Client = new TorSocks5Client(torSocks5EndPoint);

            IoHelpers.EnsureContainingDirectoryExists(Settings.LogFilePath);
        }
Esempio n. 16
0
        public static void DecryptLogEntries(string destination)
        {
            var encrypted = File.ReadAllText(FilePath);

            IoHelpers.EnsureContainingDirectoryExists(destination);

            foreach (var entry in encrypted.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var decryptedEntry = StringCipher.Decrypt(entry, FileEntryEncryptionPassword);
                File.AppendAllText(destination, $"{decryptedEntry}{EntrySeparator}");
            }
        }
Esempio n. 17
0
        public void WriteAllText(string text, Encoding encoding)
        {
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException(nameof(text), "Parameter cannot be null or empty.");
            }

            IoHelpers.EnsureContainingDirectoryExists(NewFilePath);

            File.WriteAllText(NewFilePath, text, encoding);
            SafeMoveNewToOriginal();
        }
    private async Task <(string dir, string matureFilters, string immatureFilters)> GetIndexStorePathsAsync([CallerFilePath] string callerFilePath = "", [CallerMemberName] string callerMemberName = "")
    {
        var dir = Path.Combine(Common.GetWorkDir(callerFilePath, callerMemberName), "IndexStore");
        await IoHelpers.TryDeleteDirectoryAsync(dir);

        var matureFilters   = Path.Combine(dir, "MatureIndex.dat");
        var immatureFilters = Path.Combine(dir, "ImmatureIndex.dat");

        IoHelpers.EnsureContainingDirectoryExists(matureFilters);
        IoHelpers.EnsureContainingDirectoryExists(immatureFilters);
        return(dir, matureFilters, immatureFilters);
    }
Esempio n. 19
0
        public new async Task WriteAllLinesAsync(IEnumerable <string> lines, CancellationToken cancellationToken = default)
        {
            if (lines is null || !lines.Any())
            {
                return;
            }

            IoHelpers.EnsureContainingDirectoryExists(NewFilePath);

            await File.WriteAllLinesAsync(NewFilePath, lines, cancellationToken).ConfigureAwait(false);

            SafeMoveNewToOriginal();
        }
Esempio n. 20
0
        private async Task WriteOutHashAsync(byte[] hash)
        {
            try
            {
                IoHelpers.EnsureContainingDirectoryExists(DigestFilePath);

                await File.WriteAllBytesAsync(DigestFilePath, hash).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.LogWarning("Failed to create digest.");
                Logger.LogInfo(ex);
            }
        }
        private async Task WriteOutHashAsync(byte[] hash)
        {
            try
            {
                IoHelpers.EnsureContainingDirectoryExists(DigestFilePath);

                await File.WriteAllBytesAsync(DigestFilePath, hash);
            }
            catch (Exception ex)
            {
                Logger.LogWarning <DigestableSafeMutexIoManager>("Failed to create digest.");
                Logger.LogInfo <DigestableSafeMutexIoManager>(ex);
            }
        }
Esempio n. 22
0
        /// <param name="dataDir">Application data directory.</param>
        /// <param name="distributionFolderPath">Full path to folder containing Tor installation files.</param>
        public TorSettings(string dataDir, string distributionFolderPath, bool terminateOnExit, int?owningProcessId = null)
        {
            TorBinaryFilePath = GetTorBinaryFilePath();
            TorBinaryDir      = Path.Combine(MicroserviceHelpers.GetBinaryFolder(), "Tor");

            TorDataDir         = Path.Combine(dataDir, "tordata2");
            CookieAuthFilePath = Path.Combine(dataDir, "control_auth_cookie");
            LogFilePath        = Path.Combine(dataDir, "TorLogs.txt");
            IoHelpers.EnsureContainingDirectoryExists(LogFilePath);
            DistributionFolder = distributionFolderPath;
            TerminateOnExit    = terminateOnExit;
            OwningProcessId    = owningProcessId;
            GeoIpPath          = Path.Combine(DistributionFolder, "Tor", "Geoip", "geoip");
            GeoIp6Path         = Path.Combine(DistributionFolder, "Tor", "Geoip", "geoip6");
        }
        public async Task WriteAllLinesAsync(IEnumerable <string> lines, CancellationToken cancellationToken = default, bool dismissNullOrEmptyContent = true)
        {
            if (dismissNullOrEmptyContent)
            {
                if (lines is null || !lines.Any())
                {
                    return;
                }
            }

            IoHelpers.EnsureContainingDirectoryExists(NewFilePath);

            await File.WriteAllLinesAsync(NewFilePath, lines, cancellationToken);

            SafeMoveNewToOriginal();
        }
Esempio n. 24
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);
        }
Esempio n. 25
0
        private void ToFileNoLock(string filePath)
        {
            IoHelpers.EnsureContainingDirectoryExists(filePath);
            // Remove the last 100 blocks to ensure verification on the next run. This is needed of reorg.
            int    maturity     = 101;
            Height prevHeight   = BlockchainState.Height;
            int    matureHeight = Math.Max(0, prevHeight.Value - maturity);

            BlockchainState.Height = new Height(matureHeight);

            string jsonString = JsonConvert.SerializeObject(this, Formatting.Indented);

            File.WriteAllText(filePath, jsonString, Encoding.UTF8);

            // Re-add removed items for further operations.
            BlockchainState.Height = prevHeight;
        }
Esempio n. 26
0
        private void ToFileNoLock(string filePath)
        {
            IoHelpers.EnsureContainingDirectoryExists(filePath);
            // Remove the last 100 blocks to ensure verification on the next run. This is needed of reorg.
            int    maturity     = 101;
            Height prevHeight   = BlockchainState.BestHeight;
            int    matureHeight = Math.Max(0, prevHeight.Value - maturity);

            BlockchainState.BestHeight = new Height(matureHeight);
            HashSet <BlockState> toRemove = BlockchainState.BlockStates.Where(x => x.BlockHeight >= BlockchainState.BestHeight).ToHashSet();

            BlockchainState.BlockStates.RemoveAll(x => toRemove.Contains(x));

            string jsonString = JsonConvert.SerializeObject(this, Formatting.Indented);

            File.WriteAllText(filePath, jsonString, Encoding.UTF8);

            // Re-add removed items for further operations.
            BlockchainState.BlockStates.AddRange(toRemove.OrderBy(x => x));
            BlockchainState.BestHeight = prevHeight;
        }
Esempio n. 27
0
        private static Prison DeserializePrison(string prisonFilePath)
        {
            IoHelpers.EnsureContainingDirectoryExists(prisonFilePath);
            var inmates = new List <Inmate>();

            if (File.Exists(prisonFilePath))
            {
                try
                {
                    foreach (var inmate in File.ReadAllLines(prisonFilePath).Select(Inmate.FromString))
                    {
                        inmates.Add(inmate);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    Logger.LogWarning($"Deleting {prisonFilePath}");
                    File.Delete(prisonFilePath);
                }
            }

            var prison = new Prison(inmates);

            var(noted, banned) = prison.CountInmates();
            if (noted > 0)
            {
                Logger.LogInfo($"{noted} noted UTXOs are found in prison.");
            }

            if (banned > 0)
            {
                Logger.LogInfo($"{banned} banned UTXOs are found in prison.");
            }

            return(prison);
        }
Esempio n. 28
0
 public async Task SerializeAsync(int pid)
 {
     IoHelpers.EnsureContainingDirectoryExists(FilePath);
     await File.WriteAllTextAsync(FilePath, pid.ToString()).ConfigureAwait(false);
 }
Esempio n. 29
0
        public void Start(bool ensureRunning, string dataDir)
        {
            if (TorSocks5EndPoint is null)
            {
                return;
            }

            new Thread(delegate()              // Don't ask. This is the only way it worked on Win10/Ubuntu18.04/Manjuro(1 processor VM)/Fedora(1 processor VM)
            {
                try
                {
                    // 1. Is it already running?
                    // 2. Can I simply run it from output directory?
                    // 3. Can I copy and unzip it from assets?
                    // 4. Throw exception.

                    try
                    {
                        if (IsTorRunningAsync(TorSocks5EndPoint).GetAwaiter().GetResult())
                        {
                            Logger.LogInfo <TorProcessManager>("Tor is already running.");
                            return;
                        }

                        var fullBaseDirectory = Path.GetFullPath(AppContext.BaseDirectory);
                        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            if (!fullBaseDirectory.StartsWith('/'))
                            {
                                fullBaseDirectory.Insert(0, "/");
                            }
                        }

                        var torDir = Path.Combine(dataDir, "tor");

                        var torPath = "";
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            torPath = $@"{torDir}\Tor\tor.exe";
                        }
                        else                         // Linux or OSX
                        {
                            torPath = $@"{torDir}/Tor/tor";
                        }

                        if (!File.Exists(torPath))
                        {
                            Logger.LogInfo <TorProcessManager>($"Tor instance NOT found at {torPath}. Attempting to acquire it...");
                            InstallTor(fullBaseDirectory, torDir);
                        }
                        else if (!IoHelpers.CheckExpectedHash(torPath, Path.Combine(fullBaseDirectory, "TorDaemons")))
                        {
                            Logger.LogInfo <TorProcessManager>($"Updating Tor...");

                            string backupTorDir = $"{torDir}_backup";
                            if (Directory.Exists(backupTorDir))
                            {
                                Directory.Delete(backupTorDir, true);
                            }
                            Directory.Move(torDir, backupTorDir);

                            InstallTor(fullBaseDirectory, torDir);
                        }
                        else
                        {
                            Logger.LogInfo <TorProcessManager>($"Tor instance found at {torPath}.");
                        }

                        string torArguments = $"--SOCKSPort {TorSocks5EndPoint}";
                        if (!string.IsNullOrEmpty(LogFile))
                        {
                            IoHelpers.EnsureContainingDirectoryExists(LogFile);
                            var logFileFullPath = Path.GetFullPath(LogFile);
                            torArguments       += $" --Log \"notice file {logFileFullPath}\"";
                        }

                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            TorProcess = Process.Start(new ProcessStartInfo {
                                FileName               = torPath,
                                Arguments              = torArguments,
                                UseShellExecute        = false,
                                CreateNoWindow         = true,
                                RedirectStandardOutput = true
                            });
                            Logger.LogInfo <TorProcessManager>($"Starting Tor process with Process.Start.");
                        }
                        else                         // Linux and OSX
                        {
                            string runTorCmd = $"LD_LIBRARY_PATH=$LD_LIBRARY_PATH:={torDir}/Tor && export LD_LIBRARY_PATH && cd {torDir}/Tor && ./tor {torArguments}";
                            EnvironmentHelpers.ShellExec(runTorCmd, false);
                            Logger.LogInfo <TorProcessManager>($"Started Tor process with shell command: {runTorCmd}.");
                        }

                        if (ensureRunning)
                        {
                            Task.Delay(3000).ConfigureAwait(false).GetAwaiter().GetResult();                             // dotnet brainfart, ConfigureAwait(false) IS NEEDED HERE otherwise (only on) Manjuro Linux fails, WTF?!!
                            if (!IsTorRunningAsync(TorSocks5EndPoint).GetAwaiter().GetResult())
                            {
                                throw new TorException("Attempted to start Tor, but it is not running.");
                            }
                            Logger.LogInfo <TorProcessManager>("Tor is running.");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new TorException("Could not automatically start Tor. Try running Tor manually.", ex);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError <TorProcessManager>(ex);
                }
            }).Start();
        }
Esempio n. 30
0
        public new async Task AppendAllLinesAsync(IEnumerable <string> lines, CancellationToken cancellationToken = default)
        {
            if (lines is null || !lines.Any())
            {
                return;
            }

            IoHelpers.EnsureContainingDirectoryExists(NewFilePath);
            if (File.Exists(NewFilePath))
            {
                File.Delete(NewFilePath);
            }

            var byteArrayBuilder = new ByteArrayBuilder();

            var linesArray = lines.ToArray();
            var linesIndex = 0;

            using (var sr = OpenText())
                using (var fs = File.OpenWrite(NewFilePath))
                    using (var sw = new StreamWriter(fs, Encoding.ASCII, Constants.BigFileReadWriteBufferSize))
                    {
                        // 1. First copy.
                        if (!sr.EndOfStream)
                        {
                            var    lineTask = sr.ReadLineAsync();
                            Task   wTask    = Task.CompletedTask;
                            string line     = null;
                            while (lineTask != null)
                            {
                                if (line is null)
                                {
                                    line = await lineTask.ConfigureAwait(false);
                                }

                                lineTask = sr.EndOfStream ? null : sr.ReadLineAsync();

                                if (linesArray[linesIndex] == line)                 // If the line is a line we want to write, then we know that someone else have worked into the file.
                                {
                                    linesIndex++;
                                    continue;
                                }

                                await wTask.ConfigureAwait(false);

                                wTask = sw.WriteLineAsync(line);

                                ContinueBuildHash(byteArrayBuilder, line);

                                cancellationToken.ThrowIfCancellationRequested();

                                line = null;
                            }
                            await wTask.ConfigureAwait(false);
                        }
                        await sw.FlushAsync().ConfigureAwait(false);

                        // 2. Then append.
                        foreach (var line in linesArray)
                        {
                            await sw.WriteLineAsync(line).ConfigureAwait(false);

                            ContinueBuildHash(byteArrayBuilder, line);

                            cancellationToken.ThrowIfCancellationRequested();
                        }

                        await sw.FlushAsync().ConfigureAwait(false);
                    }

            var res = await WorkWithHashAsync(byteArrayBuilder, cancellationToken).ConfigureAwait(false);

            if (res.same)
            {
                return;
            }

            SafeMoveNewToOriginal();
            await WriteOutHashAsync(res.hash).ConfigureAwait(false);
        }