public SeriesIndexSearch(IServerConfigurationManager configurationManager, IHttpClient httpClient)
 {
     _configurationManager = configurationManager;
     _httpClient = httpClient;
     _cache = new Dictionary<string, string[]>();
     _lock = new AsyncLock();
 }
 public void TestGuardLock2()
 {
     for (int i = 0; i != 10; ++i)
     {
         using (var guard = new AsyncLock())
         {
             var results = new ConcurrentQueue<int>();
             var t2 = Task.Run(
                 async () =>
                 {
                     Thread.Sleep(TimeSpan.FromMilliseconds(200));
                     using (await guard.LockAsync(CancellationToken.None))
                         results.Enqueue(2);
                 });
             var t1 = Task.Run(
                 async () =>
                 {
                     using (await guard.LockAsync(CancellationToken.None))
                     {
                         Thread.Sleep(TimeSpan.FromMilliseconds(400));
                         results.Enqueue(1);
                     }
                 });
             Task.WaitAll(t1, t2);
             var resultsData = results.ToArray();
             Assert.Equal(1, resultsData[0]);
             Assert.Equal(2, resultsData[1]);
         }
     }
 }
Example #3
0
		public async Task Simple()
		{
			var _lock = new AsyncLock();
			using( await _lock ) {
				Console.WriteLine( "Locked" );
			}
		}
Example #4
0
        public async Task SyncIntellisenseFiles()
        {
            var mutex = new AsyncLock();

            using (mutex.LockAsync())
            {
                if (_lastCheck > DateTime.Now.AddDays(-_days))
                    return;

                _lastCheck = DateTime.Now;

                try
                {
                    string catalog = await GetCataLog();

                    if (!string.IsNullOrEmpty(catalog))
                    {
                        await DownloadIntellisenseFiles(catalog);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            }
        }
		public void MaybeScheduleCompaction(AsyncLock.LockScope locker)
		{
			Debug.Assert(locker != null && locker.Locked);

			if (state.BackgroundCompactionScheduled)
			{
				return; // already scheduled, nothing to do
			}
			if (state.CancellationToken.IsCancellationRequested)
			{
				return;    // DB is being disposed; no more background compactions
			}
			if (manualCompactor != null && manualCompactor.InProgress)
			{
				return; // manual already in progress
			}
			if (state.ImmutableMemTable == null &&
				state.VersionSet.NeedsCompaction == false)
			{
				// No work to be done
				return;
			}

			state.BackgroundCompactionScheduled = true;
			Background.Work(ScheduleCompactionAsync());
		}
 public async Task WritePayloadAsync(NetworkStream ns, object payload, AsyncLock writerLock, CancellationToken cancellationToken = default(CancellationToken)) {
    var ms = memoryStreamPool.TakeObject();
    Serialize.To(ms, payload);
    using (await writerLock.LockAsync(cancellationToken).ConfigureAwait(false)) {
       await WriteMemoryStreamAsync(ns, ms, 0, (int)ms.Position, cancellationToken).ConfigureAwait(false);
    }
    ms.SetLength(0);
    memoryStreamPool.ReturnObject(ms);
 }
Example #7
0
		public async Task ReentrantAware()
		{
			var _lock = new AsyncLock();

			using( await _lock ) {
				Console.WriteLine( "In lock" );
				using( await _lock ) {
					Console.WriteLine( "Re-entrant lock" );
				}
			}
		}
Example #8
0
		public async Task LockReleaseLockRelease()
		{
			var _lock = new AsyncLock();
			using( await _lock ) {
				Console.WriteLine( "Locked" );
			}
			using( await _lock ) {
				Console.WriteLine( "Locked again" );
			}

		}
Example #9
0
		public async Task ExceptionShouldUnlockTheLock()
		{
			var _lock = new AsyncLock();

			Assert.That( _lock.HasLock, Is.False );
			try {
				using( await _lock ) {
					Assert.That( _lock.HasLock, Is.True );
					throw new Exception();
				}
			}
			catch( Exception e ) { }
			Assert.That( _lock.HasLock, Is.False );
		}
Example #10
0
		public async Task ExceptionShouldFlow()
		{
			var _lock = new AsyncLock();

			try {
				using( await _lock ) {
					throw new Exception( "Hello World" );
				}
				Assert.Fail( "Should never hit this line of code" );
			}
			catch( Exception e ) {
				Assert.That( e.Message, Is.EqualTo( "Hello World" ) );
				Trace.WriteLine( "Got Exception" );
			}
		}
		protected Task RunCompactionAsync(AsyncLock.LockScope locker)
		{
			Debug.Assert(state.BackgroundCompactionScheduled);
			state.BackgroundTask = Task.Factory.StartNew(async () =>
				{
					using (LogManager.OpenMappedContext("storage", state.DatabaseName))
					using (await locker.LockAsync())
					{
						try
						{
							bool needToWait = false;
							try
							{
								await semaphore.WaitAsync();
								await BackgroundCompactionAsync(locker).ConfigureAwait(false);
							}
							catch (Exception e)
							{
								log.ErrorException(string.Format("Compaction error: {0}", e.Message), e);

								needToWait = true;
							}

							// Wait a little bit before retrying background compaction in
							// case this is an environmental problem and we do not want to
							// chew up resources for failed compactions for the duration of
							// the problem.
							if (needToWait)
							{
								locker.Exit();
								await Task.Delay(1000).ConfigureAwait(false);
								await locker.LockAsync().ConfigureAwait(false);
							}

							await BackgroundCompactionAsync(locker).ConfigureAwait(false);
						}
						finally
						{
							semaphore.Release();
							state.BackgroundCompactionScheduled = false;
						}
					}

					return 1; // make R# happy
				}, TaskCreationOptions.LongRunning).Unwrap();

			return state.BackgroundTask;
		}
Example #12
0
		public async Task AsyncLock()
		{
			var _lock = new AsyncLock();
			using( await _lock ) {
				// warmup
			}

			var start = Stopwatch.GetTimestamp();
			for( var i = 0; i < Iterations; i++ ) {
				using( await _lock ) {
					i--;
					i++;
				}
			}
			ReportTime( start );
		}
Example #13
0
 static async Task TestAsyncLockAsync(int iterations, bool isContended)
 {
     var mutex = new AsyncLock();
     if (isContended)
     {
         var waits = new Task<IDisposable>[iterations];
         using (await mutex.LockAsync())
             for (int i = 0; i < iterations; i++)
                 waits[i] = mutex.LockAsync();
         for (int i = 0; i < iterations; i++)
             using (await waits[i]) { }
     }
     else
     {
         for (int i = 0; i < iterations; i++)
             using (await mutex.LockAsync()) { }
     }
 }
        public void TestGuardLock1()
        {
            Skip.IfNot(Environment.ProcessorCount > 1, "Only works on multi-core systems");

            for (int i = 0; i != 10; ++i)
            {
                using (var evt = new AutoResetEvent(false))
                {
                    using (var guard = new AsyncLock())
                    {
                        var results = new ConcurrentQueue<int>();
                        var t1 = Task.Run(
                            async () =>
                            {
                                using (await guard.LockAsync(CancellationToken.None))
                                {
                                    evt.Set();
                                    evt.WaitOne();
                                    Thread.Sleep(TimeSpan.FromMilliseconds(500));
                                    results.Enqueue(1);
                                }
                            });
                        evt.WaitOne();

                        var t2 = Task.Run(
                            async () =>
                            {
                                evt.Set();
                                using (await guard.LockAsync(CancellationToken.None))
                                {
                                    results.Enqueue(2);
                                }
                            });

                        Task.WaitAll(t1, t2);
                        var resultsData = results.ToArray();
                        Assert.Equal(1, resultsData[0]);
                        Assert.Equal(2, resultsData[1]);
                    }
                }
            }
        }
		private Task EnsureTableFileCreated(AsyncLock.LockScope lockScope)
		{
			return state.MakeRoomForWriteAsync(force: true, lockScope: lockScope); // force to create an ImmutableMemtable
		}
Example #16
0
        private volatile bool _disposedValue = false;         // To detect redundant calls

        public Coordinator(Network network, BlockNotifier blockNotifier, string folderPath, IRPCClient rpc, CoordinatorRoundConfig roundConfig)
        {
            Network       = Guard.NotNull(nameof(network), network);
            BlockNotifier = Guard.NotNull(nameof(blockNotifier), blockNotifier);
            FolderPath    = Guard.NotNullOrEmptyOrWhitespace(nameof(folderPath), folderPath, trim: true);
            RpcClient     = Guard.NotNull(nameof(rpc), rpc);
            RoundConfig   = Guard.NotNull(nameof(roundConfig), roundConfig);

            Rounds         = new List <CoordinatorRound>();
            RoundsListLock = new AsyncLock();

            CoinJoins                  = new List <uint256>();
            UnconfirmedCoinJoins       = new List <uint256>();
            CoinJoinsLock              = new AsyncLock();
            LastSuccessfulCoinJoinTime = DateTimeOffset.UtcNow;

            Directory.CreateDirectory(FolderPath);

            UtxoReferee = new UtxoReferee(Network, FolderPath, RpcClient, RoundConfig);

            if (File.Exists(CoinJoinsFilePath))
            {
                try
                {
                    var getTxTasks = new List <(Task <Transaction> txTask, string line)>();
                    var batch      = RpcClient.PrepareBatch();

                    var      toRemove = new List <string>();
                    string[] allLines = File.ReadAllLines(CoinJoinsFilePath);
                    foreach (string line in allLines)
                    {
                        try
                        {
                            getTxTasks.Add((batch.GetRawTransactionAsync(uint256.Parse(line)), line));
                        }
                        catch (Exception ex)
                        {
                            toRemove.Add(line);

                            var logEntry = ex is RPCException rpce && rpce.RPCCode == RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY
                                                                ? $"CoinJoins file contains invalid transaction ID {line}"
                                                                : $"CoinJoins file got corrupted. Deleting offending line \"{line.Substring(0, 20)}\".";

                            Logger.LogWarning($"{logEntry}. {ex.GetType()}: {ex.Message}");
                        }
                    }

                    batch.SendBatchAsync().GetAwaiter().GetResult();

                    foreach (var task in getTxTasks)
                    {
                        try
                        {
                            var tx = task.txTask.GetAwaiter().GetResult();
                            CoinJoins.Add(tx.GetHash());
                        }
                        catch (Exception ex)
                        {
                            toRemove.Add(task.line);

                            var logEntry = ex is RPCException rpce && rpce.RPCCode == RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY
                                                                ? $"CoinJoins file contains invalid transaction ID {task.line}"
                                                                : $"CoinJoins file got corrupted. Deleting offending line \"{task.line.Substring(0, 20)}\".";

                            Logger.LogWarning($"{logEntry}. {ex.GetType()}: {ex.Message}");
                        }
                    }

                    if (toRemove.Count != 0)                     // a little performance boost, it'll be empty almost always
                    {
                        var newAllLines = allLines.Where(x => !toRemove.Contains(x));
                        File.WriteAllLines(CoinJoinsFilePath, newAllLines);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning($"CoinJoins file got corrupted. Deleting {CoinJoinsFilePath}. {ex.GetType()}: {ex.Message}");
                    File.Delete(CoinJoinsFilePath);
                }

                uint256[] mempoolHashes = RpcClient.GetRawMempoolAsync().GetAwaiter().GetResult();
                UnconfirmedCoinJoins.AddRange(CoinJoins.Intersect(mempoolHashes));
            }

            try
            {
                string roundCountFilePath = Path.Combine(folderPath, "RoundCount.txt");
                if (File.Exists(roundCountFilePath))
                {
                    string roundCount = File.ReadAllText(roundCountFilePath);
                    CoordinatorRound.RoundCount = long.Parse(roundCount);
                }
                else
                {
                    // First time initializes (so the first constructor will increment it and we'll start from 1.)
                    CoordinatorRound.RoundCount = 0;
                }
            }
            catch (Exception ex)
            {
                CoordinatorRound.RoundCount = 0;
                Logger.LogInfo($"{nameof(CoordinatorRound.RoundCount)} file was corrupt. Resetting to 0.");
                Logger.LogDebug(ex);
            }

            BlockNotifier.OnBlock += BlockNotifier_OnBlockAsync;
        }
        /// <summary>
        /// Performs a backup on the game
        /// </summary>
        /// <param name="backupInformation">The backup information</param>
        /// <returns>True if the backup was successful</returns>
        public async Task <bool> BackupAsync(IBackupInfo backupInformation)
        {
            using (await AsyncLock.LockAsync())
            {
                RL.Logger?.LogInformationSource($"A backup has been requested for {backupInformation.GameDisplayName}");

                try
                {
                    // Make sure we have write access to the backup location
                    if (!FileManager.CheckDirectoryWriteAccess(RCPServices.Data.BackupLocation + AppViewModel.BackupFamily))
                    {
                        RL.Logger?.LogInformationSource($"Backup failed - backup location lacks write access");

                        // Request to restart as admin
                        await RCPServices.App.RequestRestartAsAdminAsync();

                        return(false);
                    }

                    // Get the backup information and group items by ID
                    var backupInfoByID = backupInformation.BackupDirectories.GroupBy(x => x.ID).ToList();

                    RL.Logger?.LogDebugSource($"{backupInfoByID.Count} backup directory ID groups were found");

                    // Get the backup info
                    var backupInfo = new List <BackupDir>();

                    // Get the latest save info from each group
                    foreach (var group in backupInfoByID)
                    {
                        if (group.Count() == 1)
                        {
                            backupInfo.Add(group.First());
                            continue;
                        }

                        RL.Logger?.LogDebugSource($"ID {group.Key} has multiple items");

                        // Find which group is the latest one
                        var groupItems = new Dictionary <BackupDir, DateTime>();

                        foreach (BackupDir item in group)
                        {
                            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                            if (!item.DirPath.DirectoryExists)
                            {
                                groupItems.Add(item, DateTime.MinValue);
                            }
                            else
                            {
                                groupItems.Add(item, Directory.GetFiles(item.DirPath, item.SearchPattern, item.SearchOption).Select(x => new FileInfo(x).LastWriteTime).OrderByDescending(x => x).FirstOrDefault());
                            }
                        }

                        // Get the latest directory
                        var latestDir = groupItems.OrderByDescending(x => x.Value).First().Key;

                        // Add the latest directory
                        backupInfo.Add(latestDir);

                        RL.Logger?.LogDebugSource($"The most recent backup directory was found under {latestDir.DirPath}");
                    }

                    // Make sure all the directories to back up exist
                    if (!backupInfo.Select(x => x.DirPath).DirectoriesExist())
                    {
                        RL.Logger?.LogInformationSource($"Backup failed - the input directories could not be found");

                        await Services.MessageUI.DisplayMessageAsync(String.Format(Resources.Backup_MissingDirectoriesError, backupInformation.GameDisplayName), Resources.Backup_FailedHeader, MessageType.Error);

                        return(false);
                    }

                    // Check if the backup should be compressed
                    bool compress = RCPServices.Data.CompressBackups;

                    RL.Logger?.LogDebugSource(compress ? $"The backup will be compressed" : $"The backup will not be compressed");

                    // Perform the backup and keep track if it succeeded
                    bool success = await(compress ?
                                         PerformCompressedBackupAsync(backupInfo, backupInformation.CompressedBackupLocation, backupInformation.GameDisplayName) :
                                         PerformBackupAsync(backupInfo, backupInformation.BackupLocation, backupInformation.GameDisplayName));

                    if (!success)
                    {
                        return(false);
                    }

                    // Remove old backups for the game
                    try
                    {
                        var newBackup = compress ? backupInformation.CompressedBackupLocation : backupInformation.BackupLocation;

                        foreach (RCPBackup existingBackup in backupInformation.ExistingBackups)
                        {
                            // Ignore the newly created backup
                            if (existingBackup.Path.CorrectPathCasing().Equals(newBackup.CorrectPathCasing()))
                            {
                                continue;
                            }

                            if (existingBackup.IsCompressed)
                            {
                                // Delete the file
                                FileManager.DeleteFile(existingBackup.Path);

                                RL.Logger?.LogInformationSource("Compressed leftover backup was deleted");
                            }
                            else
                            {
                                // Delete the directory
                                FileManager.DeleteDirectory(existingBackup.Path);

                                RL.Logger?.LogInformationSource("Non-compressed leftover backup was deleted");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.HandleError("Deleting leftover backups");
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    // Handle error
                    ex.HandleError("Backing up game", backupInformation);

                    // Display message to user
                    await Services.MessageUI.DisplayExceptionMessageAsync(ex, String.Format(Resources.Backup_Failed, backupInformation.GameDisplayName), Resources.Backup_FailedHeader);

                    // Return that backup did not succeed
                    return(false);
                }
            }
        }
Example #18
0
    private async Task <InputRegistrationResponse> RegisterInputCoreAsync(InputRegistrationRequest request, CancellationToken cancellationToken)
    {
        var coin = await OutpointToCoinAsync(request, cancellationToken).ConfigureAwait(false);

        using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false))
        {
            var round = GetRound(request.RoundId);

            var registeredCoins = Rounds.Where(x => !(x.Phase == Phase.Ended && !x.WasTransactionBroadcast))
                                  .SelectMany(r => r.Alices.Select(a => a.Coin));

            if (registeredCoins.Any(x => x.Outpoint == coin.Outpoint))
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.AliceAlreadyRegistered);
            }

            if (round.IsInputRegistrationEnded(Config.MaxInputCountByRound))
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.WrongPhase);
            }

            if (round is BlameRound blameRound && !blameRound.BlameWhitelist.Contains(coin.Outpoint))
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.InputNotWhitelisted);
            }

            // Compute but don't commit updated coinjoin to round state, it will
            // be re-calculated on input confirmation. This is computed in here
            // for validation purposes.
            _ = round.Assert <ConstructionState>().AddInput(coin);

            var coinJoinInputCommitmentData = new CoinJoinInputCommitmentData("CoinJoinCoordinatorIdentifier", round.Id);
            if (!OwnershipProof.VerifyCoinJoinInputProof(request.OwnershipProof, coin.TxOut.ScriptPubKey, coinJoinInputCommitmentData))
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.WrongOwnershipProof);
            }

            // Generate a new GUID with the secure random source, to be sure
            // that it is not guessable (Guid.NewGuid() documentation does
            // not say anything about GUID version or randomness source,
            // only that the probability of duplicates is very low).
            var id = new Guid(Random.GetBytes(16));

            var isPayingZeroCoordinationFee = InMemoryCoinJoinIdStore.Contains(coin.Outpoint.Hash);

            if (!isPayingZeroCoordinationFee)
            {
                // If the coin comes from a tx that all of the tx inputs are coming from a CJ (1 hop - no pay).
                Transaction tx = await Rpc.GetRawTransactionAsync(coin.Outpoint.Hash, true, cancellationToken).ConfigureAwait(false);

                if (tx.Inputs.All(input => InMemoryCoinJoinIdStore.Contains(input.PrevOut.Hash)))
                {
                    isPayingZeroCoordinationFee = true;
                }
            }

            var alice = new Alice(coin, request.OwnershipProof, round, id, isPayingZeroCoordinationFee);

            if (alice.CalculateRemainingAmountCredentials(round.FeeRate, round.CoordinationFeeRate) <= Money.Zero)
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.UneconomicalInput);
            }

            if (alice.TotalInputAmount < round.MinAmountCredentialValue)
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.NotEnoughFunds);
            }
            if (alice.TotalInputAmount > round.MaxAmountCredentialValue)
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.TooMuchFunds);
            }

            if (alice.TotalInputVsize > round.MaxVsizeAllocationPerAlice)
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.TooMuchVsize);
            }

            var amountCredentialTask = round.AmountCredentialIssuer.HandleRequestAsync(request.ZeroAmountCredentialRequests, cancellationToken);
            var vsizeCredentialTask  = round.VsizeCredentialIssuer.HandleRequestAsync(request.ZeroVsizeCredentialRequests, cancellationToken);

            if (round.RemainingInputVsizeAllocation < round.MaxVsizeAllocationPerAlice)
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.VsizeQuotaExceeded);
            }

            var commitAmountCredentialResponse = await amountCredentialTask.ConfigureAwait(false);

            var commitVsizeCredentialResponse = await vsizeCredentialTask.ConfigureAwait(false);

            alice.SetDeadlineRelativeTo(round.ConnectionConfirmationTimeFrame.Duration);
            round.Alices.Add(alice);

            return(new(alice.Id,
                       commitAmountCredentialResponse,
                       commitVsizeCredentialResponse,
                       alice.IsPayingZeroCoordinationFee));
        }
    }
Example #19
0
 public AsyncLockObserver(IObserver <T> observer, AsyncLock gate)
 {
     _gate     = gate;
     _observer = observer;
 }
        public async Task TestGuardLockEarlyDispose()
        {
            Skip.IfNot(Environment.ProcessorCount > 1, "Only works on multi-core systems");

            var cts = new CancellationTokenSource();
            var guard = new AsyncLock();
            var task = Task.Run(
                async () =>
                {
                    using (await guard.LockAsync(cts.Token))
                    {
                        await Task.Delay(200, CancellationToken.None);
                        cts.Token.ThrowIfCancellationRequested();
                    }
                },
                cts.Token);
            await Task.Delay(100, CancellationToken.None);
            cts.Cancel();
            guard.Dispose();

            await Task.Delay(200, CancellationToken.None);
            Assert.Equal(TaskStatus.Canceled, task.Status);
        }
Example #21
0
		public async Task ProperlyWaitsForReleaseAndCallsBackThruContext()
		{
			var _lock = new AsyncLock();

			var successfullSteps = 0;

			Action<int> next = expected => {
				var oldValue = Interlocked.CompareExchange( ref successfullSteps, expected + 1, expected );
				if( oldValue != expected ) {
					Trace.WriteLine( string.Format( "Expected {0} but was {1}", expected, oldValue ) );
				}
			};


			await Task.Run( async () => {

				var subTask = Task.Run( async () => {
					await Task.Delay( 50 );
					// assumes the lock is taken at this point
					Assert.That( _lock.HasLock, Is.True );

					using( var l = await _lock ) {
						Console.WriteLine( l );
						var properCallback1 = StackHelper.CurrentCallStack.Any( f => f.GetMethod().DeclaringType == typeof( ExecutionContext ) );
						Assert.That( properCallback1, Is.True );
						next( 2 );
					}
				} );

				using( var l = await _lock ) {
					Console.WriteLine( l );
					next( 0 );
					await Task.Delay( 500 );
					next( 1 );
				}

				await subTask;
			} );

			Assert.That( successfullSteps, Is.EqualTo( 3 ) );
		}
        public CcjCoordinator(Network network, string folderPath, RPCClient rpc, CcjRoundConfig roundConfig)
        {
            Network     = Guard.NotNull(nameof(network), network);
            FolderPath  = Guard.NotNullOrEmptyOrWhitespace(nameof(folderPath), folderPath, trim: true);
            RpcClient   = Guard.NotNull(nameof(rpc), rpc);
            RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig);

            Rounds         = new List <CcjRound>();
            RoundsListLock = new AsyncLock();

            CoinJoins            = new List <uint256>();
            UnconfirmedCoinJoins = new List <uint256>();
            CoinJoinsLock        = new AsyncLock();

            Directory.CreateDirectory(FolderPath);

            UtxoReferee = new UtxoReferee(Network, FolderPath, RpcClient);

            // Initialize RsaKey
            string rsaKeyPath = Path.Combine(FolderPath, "RsaKey.json");

            if (File.Exists(rsaKeyPath))
            {
                string rsaKeyJson = File.ReadAllText(rsaKeyPath, encoding: Encoding.UTF8);
                RsaKey = BlindingRsaKey.CreateFromJson(rsaKeyJson);
            }
            else
            {
                RsaKey = new BlindingRsaKey();
                File.WriteAllText(rsaKeyPath, RsaKey.ToJson(), encoding: Encoding.UTF8);
                Logger.LogInfo <CcjCoordinator>($"Created RSA key at: {rsaKeyPath}");
            }

            if (File.Exists(CoinJoinsFilePath))
            {
                try
                {
                    var      toRemove = new List <string>();
                    string[] allLines = File.ReadAllLines(CoinJoinsFilePath);
                    foreach (string line in allLines)
                    {
                        uint256     txHash = new uint256(line);
                        RPCResponse getRawTransactionResponse = RpcClient.SendCommand(RPCOperations.getrawtransaction, txHash.ToString(), true);
                        if (string.IsNullOrWhiteSpace(getRawTransactionResponse?.ResultString))
                        {
                            toRemove.Add(line);
                        }
                        else
                        {
                            CoinJoins.Add(txHash);
                            if (getRawTransactionResponse.Result.Value <int>("confirmations") <= 0)
                            {
                                UnconfirmedCoinJoins.Add(txHash);
                            }
                        }
                    }

                    if (toRemove.Count != 0)                     // a little performance boost, it'll be empty almost always
                    {
                        var newAllLines = allLines.Where(x => !toRemove.Contains(x));
                        File.WriteAllLines(CoinJoinsFilePath, newAllLines);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning <CcjCoordinator>($"CoinJoins file got corrupted. Deleting {CoinJoinsFilePath}. {ex.GetType()}: {ex.Message}");
                    File.Delete(CoinJoinsFilePath);
                }
            }
        }
Example #23
0
        public CcjCoordinator(Network network, TrustedNodeNotifyingBehavior trustedNodeNotifyingBehavior, string folderPath, RPCClient rpc, CcjRoundConfig roundConfig)
        {
            Network = Guard.NotNull(nameof(network), network);
            TrustedNodeNotifyingBehavior = Guard.NotNull(nameof(trustedNodeNotifyingBehavior), trustedNodeNotifyingBehavior);
            FolderPath  = Guard.NotNullOrEmptyOrWhitespace(nameof(folderPath), folderPath, trim: true);
            RpcClient   = Guard.NotNull(nameof(rpc), rpc);
            RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig);

            Rounds         = new List <CcjRound>();
            RoundsListLock = new AsyncLock();

            CoinJoins     = new List <uint256>();
            CoinJoinsLock = new AsyncLock();

            Directory.CreateDirectory(FolderPath);

            UtxoReferee = new UtxoReferee(Network, FolderPath, RpcClient, RoundConfig);

            if (File.Exists(CoinJoinsFilePath))
            {
                try
                {
                    var      toRemove = new List <string>();
                    string[] allLines = File.ReadAllLines(CoinJoinsFilePath);
                    foreach (string line in allLines)
                    {
                        try
                        {
                            uint256     txHash = new uint256(line);
                            RPCResponse getRawTransactionResponse = RpcClient.SendCommand(RPCOperations.getrawtransaction, txHash.ToString(), true);
                            CoinJoins.Add(txHash);
                        }
                        catch (Exception ex)
                        {
                            toRemove.Add(line);

                            var logEntry = ex is RPCException rpce && rpce.RPCCode == RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY
                                                                ? $"CoinJoins file contains invalid transaction ID {line}"
                                                                : $"CoinJoins file got corrupted. Deleting offending line \"{line.Substring(0, 20)}\".";

                            Logger.LogWarning <CcjCoordinator>($"{logEntry}. {ex.GetType()}: {ex.Message}");
                        }
                    }

                    if (toRemove.Count != 0)                     // a little performance boost, it'll be empty almost always
                    {
                        var newAllLines = allLines.Where(x => !toRemove.Contains(x));
                        File.WriteAllLines(CoinJoinsFilePath, newAllLines);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning <CcjCoordinator>($"CoinJoins file got corrupted. Deleting {CoinJoinsFilePath}. {ex.GetType()}: {ex.Message}");
                    File.Delete(CoinJoinsFilePath);
                }
            }

            try
            {
                string roundCountFilePath = Path.Combine(folderPath, "RoundCount.txt");
                if (File.Exists(roundCountFilePath))
                {
                    string roundCount = File.ReadAllText(roundCountFilePath);
                    CcjRound.RoundCount = long.Parse(roundCount);
                }
                else
                {
                    // First time initializes (so the first constructor will increment it and we'll start from 1.)
                    CcjRound.RoundCount = 0;
                }
            }
            catch (Exception ex)
            {
                CcjRound.RoundCount = 0;
                Logger.LogInfo <CcjCoordinator>($"{nameof(CcjRound.RoundCount)} file was corrupt. Resetting to 0.");
                Logger.LogDebug <CcjCoordinator>(ex);
            }

            TrustedNodeNotifyingBehavior.Block += TrustedNodeNotifyingBehavior_BlockAsync;
        }
Example #24
0
        private async void Run(object host)
        {
#endif
            var readMutex = new AsyncLock();

            while (this._isRunning)
            {
                try
                {
                    await this._reader.LoadAsync(4);

                    Logger.WriteLine("[message available]");
                    using (await readMutex.LockAsync())
                    {
                        Logger.WriteLine("[message unlocked]");
                        uint payloadLength;
                        uint endpoint;

                        if (this._reader.UnconsumedBufferLength > 0)
                        {
                            IBuffer buffer = this._reader.ReadBuffer(4);

                            this.GetLengthAndEndpoint(buffer, out payloadLength, out endpoint);
                            Logger.WriteLine(">> RECEIVED MESSAGE FOR ENDPOINT: " + ((Endpoint)endpoint).ToString() + " (" + endpoint.ToString() + ") - " + payloadLength.ToString() + " bytes");
                            if (endpoint > 0 && payloadLength > 0)
                            {
                                byte[] payload = new byte[payloadLength];
                                await this._reader.LoadAsync(payloadLength);
                                this._reader.ReadBytes(payload);

                                P3bbleMessage msg = this.ReadMessage(payload, endpoint);

                                if (msg != null && this.MessageReceived != null)
                                {
                                    this.MessageReceived(msg);
                                }
                            }
                            else
                            {
                                Logger.WriteLine(">> RECEIVED MESSAGE WITH BAD ENDPOINT OR LENGTH: " + endpoint.ToString() + ", " + payloadLength.ToString());
                            }
                        }
                    }
                }
                catch
                {
                }
#if NETFX_CORE
                    await Task.Delay(100);
#endif
            }
#if NETFX_CORE
            },
Example #25
0
        public static (IAsyncObserver <TSource>, IAsyncObserver <TSource>) Amb <TSource>(IAsyncObserver <TSource> observer, IAsyncDisposable first, IAsyncDisposable second)
        {
            if (observer == null)
            {
                throw new ArgumentNullException(nameof(observer));
            }
            if (first == null)
            {
                throw new ArgumentNullException(nameof(first));
            }
            if (second == null)
            {
                throw new ArgumentNullException(nameof(second));
            }

            var gate = new AsyncLock();

            var state = AmbState.None;

            return
                (
                Create <TSource>(
                    async x =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (state == AmbState.None)
                    {
                        state = AmbState.First;
                        await second.DisposeAsync().ConfigureAwait(false);
                    }

                    if (state == AmbState.First)
                    {
                        await observer.OnNextAsync(x).ConfigureAwait(false);
                    }
                }
            },
                    async ex =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (state == AmbState.None)
                    {
                        state = AmbState.First;
                        await second.DisposeAsync().ConfigureAwait(false);
                    }

                    if (state == AmbState.First)
                    {
                        await observer.OnErrorAsync(ex).ConfigureAwait(false);
                    }
                }
            },
                    async() =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (state == AmbState.None)
                    {
                        state = AmbState.First;
                        await second.DisposeAsync().ConfigureAwait(false);
                    }

                    if (state == AmbState.First)
                    {
                        await observer.OnCompletedAsync().ConfigureAwait(false);
                    }
                }
            }
                    ),
                Create <TSource>(
                    async x =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (state == AmbState.None)
                    {
                        state = AmbState.Second;
                        await first.DisposeAsync().ConfigureAwait(false);
                    }

                    if (state == AmbState.Second)
                    {
                        await observer.OnNextAsync(x).ConfigureAwait(false);
                    }
                }
            },
                    async ex =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (state == AmbState.None)
                    {
                        state = AmbState.Second;
                        await first.DisposeAsync().ConfigureAwait(false);
                    }

                    if (state == AmbState.Second)
                    {
                        await observer.OnErrorAsync(ex).ConfigureAwait(false);
                    }
                }
            },
                    async() =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (state == AmbState.None)
                    {
                        state = AmbState.Second;
                        await first.DisposeAsync().ConfigureAwait(false);
                    }

                    if (state == AmbState.Second)
                    {
                        await observer.OnCompletedAsync().ConfigureAwait(false);
                    }
                }
            }
                    )
                );
        }
Example #26
0
        public static IAsyncObserver <TSource>[] Amb <TSource>(IAsyncObserver <TSource> observer, IAsyncDisposable[] subscriptions)
        {
            if (observer == null)
            {
                throw new ArgumentNullException(nameof(observer));
            }
            if (subscriptions == null)
            {
                throw new ArgumentNullException(nameof(subscriptions));
            }

            var gate = new AsyncLock();

            var winner = default(int?);

            var count = subscriptions.Length;

            async Task ElectWinnerAsync(int index)
            {
                winner = index;

                var dispose = new List <Task>(count - 1);

                for (var i = 0; i < count; i++)
                {
                    if (i != index)
                    {
                        dispose.Add(subscriptions[i].DisposeAsync());
                    }
                }

                await Task.WhenAll(dispose).ConfigureAwait(false);
            }

            IAsyncObserver <TSource> CreateObserver(int index) =>
            Create <TSource>(
                async x =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (winner == null)
                    {
                        await ElectWinnerAsync(index).ConfigureAwait(false);
                    }

                    if (winner == index)
                    {
                        await observer.OnNextAsync(x).ConfigureAwait(false);
                    }
                }
            },
                async ex =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (winner == null)
                    {
                        await ElectWinnerAsync(index).ConfigureAwait(false);
                    }

                    if (winner == index)
                    {
                        await observer.OnErrorAsync(ex).ConfigureAwait(false);
                    }
                }
            },
                async() =>
            {
                using (await gate.LockAsync().ConfigureAwait(false))
                {
                    if (winner == null)
                    {
                        await ElectWinnerAsync(index).ConfigureAwait(false);
                    }

                    if (winner == index)
                    {
                        await observer.OnCompletedAsync().ConfigureAwait(false);
                    }
                }
            }
                );

            var res = new IAsyncObserver <TSource> [count];

            for (var i = 0; i < count; i++)
            {
                res[i] = CreateObserver(i);
            }

            return(res);
        }
Example #27
0
 /// <param name="ipEndPoint">Opt out Tor with null.</param>
 internal TorSocks5Client(IPEndPoint ipEndPoint)
 {
     TorSocks5EndPoint = ipEndPoint;
     TcpClient         = new TcpClient();
     AsyncLock         = new AsyncLock();
 }
Example #28
0
 internal TaskManager(bool stopOnCompletion)
 {
     _lock            = new AsyncLock();
     StopOnCompletion = stopOnCompletion;
 }
        public async Task TestGuardLockMultipleDispose()
        {
            Skip.IfNot(Environment.ProcessorCount > 1, "Only works on multi-core systems");

            var guard = new AsyncLock();
            var task = Task.Run(
                async () =>
                {
                    using (await guard.LockAsync(CancellationToken.None))
                    {
                        await Task.Delay(100);
                        return Int32.MaxValue;
                    }
                });

            await Task.Delay(50);
            await Task.WhenAll(Enumerable.Repeat(Task.Run((Action)guard.Dispose), 100));
            Assert.Equal(Int32.MaxValue, await task);
        }
Example #30
0
 public AlteredCache(IAlteredPipeline <TRequest, TResponse> f, Func <TRequest, string> getKey, CacheItemPolicy cacheItemPolicy, ObjectCache cache, AsyncLock cacheLock) : base(async(request) =>
 {
     var key = $"{f.GetType().GUID}:{getKey(request)}";
     using (await cacheLock.LockAsync())
     {
         var response = cache.Get(key) as TResponse;
         if (response == null)
         {
             response = await f.Execute(request);
             cache.AddOrGetExisting(key, response, cacheItemPolicy);
         }
         return(response);
     }
 })
 {
 }
Example #31
0
        public async Task TestGuardLockMultipleDispose()
        {
            var guard = new AsyncLock();
            var task = Task.Run(
                async () =>
                {
                    using (await guard.LockAsync(CancellationToken.None))
                    {
                        await Task.Delay(100);
                        return Int32.MaxValue;
                    }
                });

            await Task.Delay(50);
            await Task.WhenAll(Enumerable.Repeat(Task.Run((Action)guard.Dispose), 100));
            Assert.Equal(Int32.MaxValue, await task);
        }
Example #32
0
 public static IAlteredPipeline <TRequest, TResponse> WithAlteredCache <TRequest, TResponse>(this IAlteredPipeline <TRequest, TResponse> f, Func <TRequest, string> getKey, CacheItemPolicy cacheItemPolicy = null, ObjectCache cache = null, AsyncLock cacheLock = null)
     where TResponse : class
 {
     cache           = cache ?? MemoryCache.Default;
     cacheItemPolicy = cacheItemPolicy ?? DefaultCacheItemPolicy;
     cacheLock       = cacheLock ?? new AsyncLock();
     return(new AlteredCache <TRequest, TResponse>(f, getKey, cacheItemPolicy, cache, cacheLock));
 }
		private async Task BackgroundCompactionAsync(AsyncLock.LockScope locker)
		{
			state.CancellationToken.ThrowIfCancellationRequested();

			if (state.ImmutableMemTable != null)
			{
				await CompactMemTableAsync(locker).ConfigureAwait(false);
			}

			var compaction = CompactionToProcess();

			if (compaction == null)
			{
				return;
			}

			if (IsManual == false && compaction.IsTrivialMove())
			{
				Debug.Assert(compaction.GetNumberOfInputFiles(0) == 1);
				var file = compaction.GetInput(0, 0);
				compaction.Edit.DeleteFile(compaction.Level, file.FileNumber);
				compaction.Edit.AddFile(compaction.Level + 1, file);

				await state.LogAndApplyAsync(compaction.Edit, locker).ConfigureAwait(false);

				log.Info("Moved {0} to level-{1} {2} bytes", file.FileNumber, compaction.Level + 1, file.FileSize);
			}
			else
			{
				using (var compactionState = new CompactionState(compaction))
				{
					try
					{
						await DoCompactionWorkAsync(compactionState, locker).ConfigureAwait(false);
					}
					finally
					{
						CleanupCompaction(compactionState);
					}
				}

				compaction.ReleaseInputs();
				DeleteObsoleteFiles();
			}
		}
Example #34
0
 internal LockReleaser(AsyncLock target)
 {
     this.target = target;
 }
Example #35
0
    private async Task <ConnectionConfirmationResponse> ConfirmConnectionCoreAsync(ConnectionConfirmationRequest request, CancellationToken cancellationToken)
    {
        Round round;
        Alice alice;
        var   realAmountCredentialRequests = request.RealAmountCredentialRequests;
        var   realVsizeCredentialRequests  = request.RealVsizeCredentialRequests;

        using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false))
        {
            round = GetRound(request.RoundId, Phase.InputRegistration, Phase.ConnectionConfirmation);

            alice = GetAlice(request.AliceId, round);

            if (alice.ConfirmedConnection)
            {
                Prison.Ban(alice, round.Id);
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.AliceAlreadyConfirmedConnection, $"Round ({request.RoundId}): Alice ({request.AliceId}) already confirmed connection.");
            }

            if (realVsizeCredentialRequests.Delta != alice.CalculateRemainingVsizeCredentials(round.MaxVsizeAllocationPerAlice))
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.IncorrectRequestedVsizeCredentials, $"Round ({request.RoundId}): Incorrect requested vsize credentials.");
            }

            var remaining = alice.CalculateRemainingAmountCredentials(round.FeeRate, round.CoordinationFeeRate);
            if (realAmountCredentialRequests.Delta != remaining)
            {
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.IncorrectRequestedAmountCredentials, $"Round ({request.RoundId}): Incorrect requested amount credentials.");
            }
        }

        var amountZeroCredentialTask = round.AmountCredentialIssuer.HandleRequestAsync(request.ZeroAmountCredentialRequests, cancellationToken);
        var vsizeZeroCredentialTask  = round.VsizeCredentialIssuer.HandleRequestAsync(request.ZeroVsizeCredentialRequests, cancellationToken);
        Task <CredentialsResponse>?amountRealCredentialTask = null;
        Task <CredentialsResponse>?vsizeRealCredentialTask  = null;

        if (round.Phase is Phase.ConnectionConfirmation)
        {
            amountRealCredentialTask = round.AmountCredentialIssuer.HandleRequestAsync(realAmountCredentialRequests, cancellationToken);
            vsizeRealCredentialTask  = round.VsizeCredentialIssuer.HandleRequestAsync(realVsizeCredentialRequests, cancellationToken);
        }

        using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false))
        {
            alice = GetAlice(request.AliceId, round);

            switch (round.Phase)
            {
            case Phase.InputRegistration:
            {
                var commitAmountZeroCredentialResponse = await amountZeroCredentialTask.ConfigureAwait(false);

                var commitVsizeZeroCredentialResponse = await vsizeZeroCredentialTask.ConfigureAwait(false);

                alice.SetDeadlineRelativeTo(round.ConnectionConfirmationTimeFrame.Duration);
                return(new(
                           commitAmountZeroCredentialResponse,
                           commitVsizeZeroCredentialResponse));
            }

            case Phase.ConnectionConfirmation:
            {
                // If the phase was InputRegistration before then we did not pre-calculate real credentials.
                amountRealCredentialTask ??= round.AmountCredentialIssuer.HandleRequestAsync(realAmountCredentialRequests, cancellationToken);
                vsizeRealCredentialTask ??= round.VsizeCredentialIssuer.HandleRequestAsync(realVsizeCredentialRequests, cancellationToken);

                ConnectionConfirmationResponse response = new(
                    await amountZeroCredentialTask.ConfigureAwait(false),
                    await vsizeZeroCredentialTask.ConfigureAwait(false),
                    await amountRealCredentialTask.ConfigureAwait(false),
                    await vsizeRealCredentialTask.ConfigureAwait(false));

                // Update the coinjoin state, adding the confirmed input.
                round.CoinjoinState       = round.Assert <ConstructionState>().AddInput(alice.Coin);
                alice.ConfirmedConnection = true;

                return(response);
            }

            default:
                throw new WabiSabiProtocolException(WabiSabiProtocolErrorCode.WrongPhase, $"Round ({request.RoundId}): Wrong phase ({round.Phase}).");
            }
        }
    }
Example #36
0
 /// <summary>
 /// Creates the key for a lock.
 /// </summary>
 /// <param name="asyncLock">The lock to release. May not be <c>null</c>.</param>
 public Key(AsyncLock asyncLock)
 {
     this.asyncLock = asyncLock;
 }
 static BackupManager()
 {
     AsyncLock = new AsyncLock();
 }
 /// <param name="endPoint">Opt out Tor with null.</param>
 internal TorSocks5Client(EndPoint endPoint)
 {
     TorSocks5EndPoint = endPoint;
     TcpClient         = endPoint is null ? new TcpClient() : new TcpClient(endPoint.AddressFamily);
     AsyncLock         = new AsyncLock();
 }
        /// <summary>
        /// Restores a backup on the game
        /// </summary>
        /// <param name="backupInformation">The backup information</param>
        /// <returns>True if the backup was successful</returns>
        public async Task <bool> RestoreAsync(IBackupInfo backupInformation)
        {
            using (await AsyncLock.LockAsync())
            {
                RL.Logger?.LogInformationSource($"A backup restore has been requested for {backupInformation.GameDisplayName}");

                try
                {
                    // Get the backup directory
                    var existingBackup = backupInformation.ExistingBackups.FirstOrDefault();

                    // Make sure a backup exists
                    if (existingBackup == null)
                    {
                        RL.Logger?.LogInformationSource($"Restore failed - the input location could not be found");

                        await Services.MessageUI.DisplayMessageAsync(String.Format(Resources.Restore_MissingBackup, backupInformation.GameDisplayName), Resources.Restore_FailedHeader, MessageType.Error);

                        return(false);
                    }

                    // Get the backup information
                    var backupInfo = backupInformation.RestoreDirectories;

                    // Make sure we have write access to the restore destinations
                    if (backupInfo.Any(x => !FileManager.CheckDirectoryWriteAccess(x.DirPath)))
                    {
                        RL.Logger?.LogInformationSource($"Restore failed - one or more restore destinations lack write access");

                        // Request to restart as admin
                        await RCPServices.App.RequestRestartAsAdminAsync();

                        return(false);
                    }

                    using (var tempDir = new TempDirectory(true))
                    {
                        using var archiveTempDir = new TempDirectory(true);
                        bool hasCreatedTempBackup = false;

                        try
                        {
                            // If the backup is an archive, extract it to temp
                            if (existingBackup.IsCompressed)
                            {
                                using var file = File.OpenRead(existingBackup.Path);
                                using var zip  = new ZipArchive(file, ZipArchiveMode.Read);
                                zip.ExtractToDirectory(archiveTempDir.TempPath);
                            }

                            // Move existing files to temp in case the restore fails
                            foreach (BackupDir item in backupInfo)
                            {
                                // Make sure the directory exists
                                if (!item.DirPath.DirectoryExists)
                                {
                                    continue;
                                }

                                // Get the destination directory
                                var destDir = tempDir.TempPath + item.ID;

                                // Check if the entire directory should be moved
                                if (item.IsEntireDir())
                                {
                                    // Move the directory
                                    FileManager.MoveDirectory(item.DirPath, destDir, true, true);
                                }
                                else
                                {
                                    FileManager.MoveFiles(item, destDir, true);
                                }
                            }

                            hasCreatedTempBackup = true;

                            // Restore each backup directory
                            foreach (BackupDir item in backupInfo)
                            {
                                // Get the combined directory path
                                var dirPath = (existingBackup.IsCompressed ? archiveTempDir.TempPath : existingBackup.Path) + item.ID;

                                // Restore the backup
                                if (dirPath.DirectoryExists)
                                {
                                    FileManager.CopyDirectory(dirPath, item.DirPath, false, true);
                                }
                            }
                        }
                        catch
                        {
                            // Delete restored files if restore began
                            if (hasCreatedTempBackup)
                            {
                                foreach (BackupDir item in backupInfo)
                                {
                                    // Make sure the directory exists
                                    if (!item.DirPath.DirectoryExists)
                                    {
                                        continue;
                                    }

                                    // Check if the entire directory should be deleted
                                    if (item.IsEntireDir())
                                    {
                                        // Delete the directory
                                        FileManager.DeleteDirectory(item.DirPath);
                                    }
                                    else
                                    {
                                        // Delete each file
                                        foreach (FileSystemPath file in Directory.GetFiles(item.DirPath, item.SearchPattern, item.SearchOption))
                                        {
                                            // Delete the file
                                            FileManager.DeleteFile(file);
                                        }
                                    }
                                }
                            }

                            // Restore temp backup
                            foreach (BackupDir item in backupInfo)
                            {
                                // Get the combined directory path
                                var dirPath = tempDir.TempPath + item.ID;

                                // Make sure there is a directory to restore
                                if (!dirPath.DirectoryExists)
                                {
                                    continue;
                                }

                                // Restore
                                FileManager.MoveDirectory(dirPath, item.DirPath, false, false);
                            }

                            RL.Logger?.LogInformationSource($"Restore failed - clean up succeeded");

                            throw;
                        }
                    }

                    RL.Logger?.LogInformationSource($"Restore complete");

                    return(true);
                }
                catch (Exception ex)
                {
                    ex.HandleError("Restoring game", backupInformation);
                    await Services.MessageUI.DisplayExceptionMessageAsync(ex, String.Format(Resources.Restore_Failed, backupInformation.GameDisplayName), Resources.Restore_FailedHeader);

                    return(false);
                }
            }
        }
        /// <summary>
        /// Default constructor for a specific game
        /// </summary>
        /// <param name="game">The DosBox game</param>
        /// <param name="gameType">The type of game</param>
        protected BaseDosBoxConfigViewModel(Games game, GameType gameType)
        {
            Game     = game;
            GameType = gameType;

            // Create the async lock
            AsyncLock = new AsyncLock();

            // Create the commands
            SaveCommand           = new AsyncRelayCommand(SaveAsync);
            UseRecommendedCommand = new RelayCommand(UseRecommended);

            // Set up the available resolution values
            AvailableResolutionValues = new ObservableCollection <string>();

            const double ratio     = 16d / 10d;
            const int    minHeight = 200;
            double       maxHeight = SystemParameters.PrimaryScreenHeight;

            AvailableResolutionValues.Add($"Original");

            for (int height = minHeight; height <= maxHeight; height += minHeight)
            {
                AvailableResolutionValues.Add($"{height * ratio}x{height}");
            }

            // NOTE: Below options are not localized

            // Set available DosBox outputs
            AvailableDosBoxOutputs = new string[]
            {
                "default",
                "surface",
                "overlay",
                "opengl",
                "openglnb",
                "ddraw"
            };

            // Set available DosBox scalers
            AvailableDosBoxScalers = new string[]
            {
                "default",
                "none",
                "normal2x",
                "normal3x",
                "advmame2x",
                "advmame3x",
                "hq2x",
                "hq3x",
                "2xsai",
                "super2xsai",
                "supereagle",
                "advinterp2x",
                "advinterp3x",
                "tv2x",
                "tv3x",
                "rgb2x",
                "rgb3x",
                "scan2x",
                "scan3x"
            };

            // Set available DosBox core modes
            AvailableDosBoxCoreModes = new string[]
            {
                "default",
                "normal",
                "simple",
                "dynamic",
                "auto"
            };

            // Set available DosBox cycle modes
            AvailableDosBoxCycleModes = new string[]
            {
                "default",
                "auto",
                "max"
            };
        }
 public ClientProviderRuntime(IGrainFactory grainFactory)
 {
     caoTable     = new Dictionary <Type, Tuple <IGrainExtension, IAddressable> >();
     lockable     = new AsyncLock();
     GrainFactory = grainFactory;
 }
Example #42
0
 public AsyncLockWaiter( AsyncLock @lock )
     : base(@lock)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AsyncConcurrentDictionary{TKey, TValue}"/> class.
 /// </summary>
 public AsyncConcurrentDictionary()
 {
     _locker     = new AsyncLock();
     _dictionary = new Dictionary <TKey, TValue>();
 }
 static DownloadsService()
 {
     DownloadsService.AsyncLock = new AsyncLock();
 }
Example #45
0
		public AsyncLockTest()
		{
			_lock = new AsyncLock();
		}
Example #46
0
 /// <summary>
 /// Release the lock.
 /// </summary>
 public void Dispose()
 {
     if (asyncLock == null)
         return;
     asyncLock.ReleaseLock();
     asyncLock = null;
 }
    static SecretCodeManager()
    {
        AsyncLock = new AsyncLock();

        Codes = new Dictionary <Key[], Func <Task> >()
        {
            {
                // Konami code
                new Key[]
                {
                    Key.Up,
                    Key.Up,
                    Key.Down,
                    Key.Down,
                    Key.Left,
                    Key.Right,
                    Key.Left,
                    Key.Right,
                    Key.B,
                    Key.A
                },
                async() =>
                {
                    Application.Current.SetTheme(Services.Data.Theme_DarkMode, false, "Red");

                    await Services.MessageUI.DisplayMessageAsync(Resources.SecretCodes_Konami, Resources.SecretCodes_KonamiHeader, MessageType.Success);
                }
            },
            {
                // RayCarrot code
                new Key[]
                {
                    Key.R,
                    Key.A,
                    Key.Y,
                    Key.C,
                    Key.A,
                    Key.R,
                    Key.R,
                    Key.O,
                    Key.T,
                },
                async() =>
                {
                    Application.Current.SetTheme(Services.Data.Theme_DarkMode, false, "Orange");

                    await Services.MessageUI.DisplayMessageAsync(Resources.SecretCodes_RayCarrot, Resources.SecretCodes_RayCarrotHeader, MessageType.Success);
                }
            },
            {
                // Lime code
                new Key[]
                {
                    Key.S,
                    Key.O,
                    Key.U,
                    Key.R,
                },
                async() =>
                {
                    Application.Current.SetTheme(Services.Data.Theme_DarkMode, false, "Lime");

                    await Services.MessageUI.DisplayMessageAsync(Resources.SecretCodes_Lime, Resources.SecretCodes_LimeHeader, MessageType.Success);
                }
            },
            {
                // Secret code
                new Key[]
                {
                    Key.S,
                    Key.E,
                    Key.C,
                    Key.R,
                    Key.E,
                    Key.T,
                },
                async() =>
                {
                    await Services.MessageUI.DisplayMessageAsync(Resources.SecretCodes_Secret, Resources.SecretCodes_SecretHeader, MessageType.Success);
                }
            },
        };

        CurrentInput = new List <Key>(Codes.OrderBy(x => x.Key.Length).First().Key.Length);
    }
Example #48
0
 public SocksConnection()
 {
     EndPoint   = null;
     _asyncLock = new AsyncLock();
 }
Example #49
0
        public async Task TestGuardLockEarlyDispose()
        {
            var cts = new CancellationTokenSource();
            var guard = new AsyncLock();
            var task = Task.Run(
                async () =>
                {
                    using (await guard.LockAsync(cts.Token))
                    {
                        await Task.Delay(200, CancellationToken.None);
                        cts.Token.ThrowIfCancellationRequested();
                    }
                },
                cts.Token);
            await Task.Delay(100, CancellationToken.None);
            cts.Cancel();
            guard.Dispose();

            await Task.Delay(200, CancellationToken.None);
            Assert.Equal(TaskStatus.Canceled, task.Status);
        }
 public ItemRepository(AsyncLock mutex, SQLiteAsyncConnection sqliteConnection) : base(mutex, sqliteConnection)
 {
 }
 /// <summary>
 /// Creates a new instance of the AniDbTitleMatcher class.
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="downloader">The AniDB title downloader.</param>
 public AniDbTitleMatcher(ILogger logger, IAniDbTitleDownloader downloader)
 {
     _logger = logger;
     _downloader = downloader;
     _lock = new AsyncLock();
 }
Example #52
0
        public async Task InitializeTask()
        {
            try
            {
                _isInitialize = true;

                _mutex     = new AsyncLock();
                _mutexRead = new AsyncLock();

                //1.
                Services = new ServiceCollection();
                this.Services.AddOptions();

                //2.Configuration
                //string basePath = Directory.GetCurrentDirectory() + @"\..\..\..\..";
                string basePath = Directory.GetCurrentDirectory();
                this.ConfigurationBuilder = new ConfigurationBuilder()
                                            .SetBasePath(basePath)
                                            .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: false);

                this.Configuration = ConfigurationBuilder.Build();

                Services.Configure <PipeSettings>((pipeSettings) =>
                {
                    this.Configuration.Bind("Pipe", pipeSettings);
                });

                Services.Configure <BlockSettings>((blockSettings) =>
                {
                    this.Configuration.Bind("Block", blockSettings);
                });

                Services.Configure <DataProviderSettings>((dataProviderSettings) =>
                {
                    this.Configuration.Bind("DataProvider", dataProviderSettings);
                });

                Services.Configure <DataSourceTypeSettings>((dataSourceTypeSettings) =>
                {
                    this.Configuration.Bind("DataSource", dataSourceTypeSettings);
                });

                //3.Logging
                Services.AddLogging(builder =>
                {
                    var loggingSection = this.Configuration.GetSection("Logging");
                    var includeScopes  = loggingSection.GetValue <bool>("IncludeScopes");

                    builder.AddConfiguration(loggingSection);

                    //加入一个ConsoleLoggerProvider
                    builder.AddConsole(consoleLoggerOptions =>
                    {
                        consoleLoggerOptions.IncludeScopes = includeScopes;
                    });

                    //加入一个DebugLoggerProvider
                    builder.AddDebug();
                });

                //DbContext
                Services.AddScoped <ContosoContext, SqliteContosoContext>((sp) =>
                {
                    var logFactory = sp.GetRequiredService <ILoggerFactory>();
                    string sqliteConnectionString = this.Configuration.GetConnectionString("ContosoSqlite");
                    //var sqliteContosoContext = new SqliteContosoContext(new DbContextOptionsBuilder<ContosoContext>().UseLoggerFactory(logFactory)
                    //                                                                                                 .UseSqlite(sqliteConnectionString).Options);
                    var sqliteContosoContext = new SqliteContosoContext(new DbContextOptionsBuilder <ContosoContext>()
                                                                        .UseSqlite(sqliteConnectionString).Options);
                    return(sqliteContosoContext);
                });

                Services.AddScoped <ContosoContext, SqlServerContosoContext>((sp) =>
                {
                    var logFactory = sp.GetRequiredService <ILoggerFactory>();
                    string sqlServerConnectString = this.Configuration.GetConnectionString("ContosoSqlServer");
                    //var sqlServerContosoContext = new SqlServerContosoContext(new DbContextOptionsBuilder<ContosoContext>().UseLoggerFactory(logFactory)
                    //                                                                                                       .UseSqlServer(sqlServerConnectString).Options);
                    var sqlServerContosoContext = new SqlServerContosoContext(new DbContextOptionsBuilder <ContosoContext>()
                                                                              .UseSqlServer(sqlServerConnectString).Options);
                    return(sqlServerContosoContext);
                });

                Services.AddScoped <IDbContextFactory <ContosoContext>, DbContextFactory>();

                Services.AddScoped(typeof(IDataflowBulkInserter <,>), typeof(DataflowBulkInserter <,>));
                Services.AddScoped(typeof(IDataflowPipeBulkInserter <,>), typeof(DataflowPipeBulkInserter <,>));
                Services.AddScoped(typeof(IPipeBulkInserter <,>), typeof(PipeBulkInserter <,>));
                //Services.AddScoped<IDataflowBulkInserter<Order, Order>, DataflowBulkInserter<Order, Order>>();
                // Services.AddScoped<IDataflowPipeBulkInserter<Order, Order>, DataflowPipeBulkInserter<Order, Order>>();
                // Services.AddScoped<IPipeBulkInserter<Order, Order>, PipeBulkInserter<Order, Order>>();

                //Repository
                Services.AddScoped <ISqlOrderRepository, SqlOrderRepository>();

                //Mapper
                Services.AddAutoMapper(typeof(Contoso.DataSource.AutoMapper.AutoMapperProfileConfiguration));

                //DataSource
                Services.AddScoped <ISqlServerOrderDataSource, DataSource.SqlServer.SqlServerOrderDataSource>();

                //DataSourceFactory
                Services.AddScoped <IContosoDataSource, SqlServerContosoDataSource>();
                Services.AddScoped <IDataSourceFactory <IContosoDataSource>, ContosoDataSourceFactory>();

                // Services.AddSingleton<IPipeWebApiSender<PurchaseOrderDto, int>, PipeWebApiSender<PurchaseOrderDto, int>>();

                //4.
                this.ServiceProvider = this.Services.BuildServiceProvider();

                //5.
                _loggerFactory = ServiceProvider.GetRequiredService <ILoggerFactory>();
                _logger        = _loggerFactory.CreateLogger <WebApiSender>();

                var repositoryFactory = this.ServiceProvider.GetRequiredService <IDbContextFactory <ContosoContext> >();
                var dbContext         = repositoryFactory.CreateDbContext();

                var dataflowBulkInserter     = this.ServiceProvider.GetRequiredService <IDataflowBulkInserter <OrderDto, OrderDto> >();
                var dataflowPipeBulkInserter = this.ServiceProvider.GetRequiredService <IDataflowPipeBulkInserter <OrderDto, OrderDto> >();
                var pipeBulkInserter         = this.ServiceProvider.GetRequiredService <IPipeBulkInserter <OrderDto, OrderDto> >();

                var mapper = this.ServiceProvider.GetRequiredService <IMapper>();

                var contosoDataSourceFactory = this.ServiceProvider.GetRequiredService <IDataSourceFactory <IContosoDataSource> >();
                var orderDataSource          = contosoDataSourceFactory.Current.OrderDataSource;

                _cancellationTokenSource = new CancellationTokenSource();
                _durationManage          = new DurationManage();
                await OrderJsonProvider.InitializeTask();

                //  return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                // return Task.FromException(ex);
            }
        }
Example #53
0
 public NonBlockedWaiter( AsyncLock @lock )
     : base(@lock)
 {
 }
 protected BasePageViewModel()
 {
     App.SelectedPageChanged += App_SelectedPageChangedAsync;
     _pageChangedLock         = new AsyncLock();
 }
Example #55
0
 /// <summary>
 /// Creates a new instance of the AniDbTitleMatcher class.
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="downloader">The AniDB title downloader.</param>
 public AniDbTitleMatcher(ILogger logger, IAniDbTitleDownloader downloader)
 {
     _logger     = logger;
     _downloader = downloader;
     _lock       = new AsyncLock();
 }
Example #56
0
        public WebSocketClientHandle(WebSocketServer server, WebSocket socket)
        {
            this.id       = Helpers.RandomString(16);
            this.socket   = socket;
            this.sendLock = AsyncLock.Create("WebSocketClientHandle-" + this.id);
            this.onClose  = () => { };

            var socketDestroyer = new CancellationTokenSource();

            Console.WriteLine("  --> New WebSocketClient {0}", this.id);

            byte[] buffer = new byte[65536]; // 8 KB buffer
            Helpers.AsyncTaskLoop(() =>
            {
                if (socket.State == WebSocketState.Open)
                {
                    return(socket.ReceiveAsync(new ArraySegment <byte>(buffer), socketDestroyer.Token)
                           .ContinueWith(prev =>
                    {
                        try
                        {
                            var received = prev.Result;
                            // Console.WriteLine("WebSocket {0}: {1} {2} {3}", this.id, received.Count, received.MessageType, received.EndOfMessage);
                            if (prev.Result.MessageType == WebSocketMessageType.Close)
                            {
                                Console.WriteLine("  !!! WebSocket Client {0} dropped connection", this.id);
                                Console.WriteLine("  !!! Closing WebSocket {0}", this.id);
                                socketDestroyer.Cancel();

                                // return Task.CompletedTask;
                                return socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close OK", CancellationToken.None)
                                .ContinueWith(_ =>
                                {
                                    this.onClose();
                                    this.socket.Dispose();
                                });
                            }
                            else
                            {
                                string message = Encoding.UTF8.GetString(buffer, 0, prev.Result.Count);
                                // Console.WriteLine("  !!! Message from WebSocket {0}: {1}", this.id, message);

                                // Spawning a new task to make the message handler "non-blocking"
                                // TODO: Errors thrown inside here will become silent, so that needs to be handled
                                // Also, now that the single execution flow is broken, the requests are under race conditions
                                return Task.Run(() => this.onMessage(message));
                            }
                        }
                        catch (AggregateException ae)
                        {
                            Console.WriteLine("  !!! Exception during async communication with Client {0}", this.id);
                            Console.WriteLine("  ... Connection closed... if this was not expected, inspect the AggregateException here");
                            foreach (var ie in ae.Flatten().InnerExceptions)
                            {
                                Console.WriteLine("Exception -------------------");
                                Console.WriteLine(ie.Message);
                                Console.WriteLine(ie.InnerException.Message);
                                Console.WriteLine(ie.InnerException.StackTrace);
                                Console.WriteLine("-----------------------------\n");
                            }
                            socketDestroyer.Cancel();
                            this.onClose();
                            this.socket.Dispose();
                            return Task.CompletedTask;
                        }
                    }).Unwrap());
                }
                else
                {
                    Console.WriteLine("  !!! WebSocket {0} Connection Dropped!", this.id);
                    socketDestroyer.Cancel();
                    this.onClose();
                    this.socket.Dispose();
                    return(Task.CompletedTask);
                }
            }, socketDestroyer.Token);
        }
Example #57
0
 /// <summary>
 /// Creates the key for a lock.
 /// </summary>
 /// <param name="asyncLock">The lock to release. May not be <c>null</c>.</param>
 public Key(AsyncLock asyncLock)
 {
     this.asyncLock = asyncLock;
 }
Example #58
0
 public LockHelper()
 {
     _mutex = new AsyncLock();
 }
 public ByteArrayListStream()
 {
     // Initially we have nothing to read so Reads should be parked
     readStreamLock = AsyncLock.CreateLocked(out lockRelease);
 }
Example #60
0
 public CrossBleRadioAdapter()
 {
     PeripheralSearchLock  = new AsyncLock();
     AdapterManagementLock = new AsyncLock();
     PeripheralCache       = new Dictionary <Guid, CrossBleRadioPeripheral>();
 }