Example #1
0
 private void MergeDict <U, T>(ConcurrentDictionary <U, T> a, ConcurrentDictionary <U, T> b) where U : notnull
 {
     foreach (var bItem in b)
     {
         a.AddOrReplace(bItem.Key, bItem.Value);
     }
 }
        public async Task <bool> CompleteLogin(string userId, ECDSASignature sig, PubKey pubKey)
        {
            await using var dbContext = _contextFactory.CreateContext();
            userId = userId.ToLowerInvariant();
            var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
                       .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);

            if (user == null || !LoginStore.TryGetValue(userId, out var k1))
            {
                return(false);
            }

            var pubKeyBytes = pubKey.ToBytes();
            var credential  = user.Fido2Credentials
                              .Where(fido2Credential => fido2Credential.Type is Fido2Credential.CredentialType.LNURLAuth)
                              .FirstOrDefault(fido2Credential => fido2Credential.Blob.SequenceEqual(pubKeyBytes));

            if (credential is null)
            {
                return(false);
            }
            if (!global::LNURL.LNAuthRequest.VerifyChallenge(sig, pubKey, k1))
            {
                return(false);
            }
            LoginStore.Remove(userId, out _);

            FinalLoginStore.AddOrReplace(userId, k1);
            // 7. return OK to client
            return(true);
        }
Example #3
0
        private void AddRegistration(IRegistration registration)
        {
            if (!Options.AllowOverriding && registrations.ContainsKey(registration.ServiceType))
            {
                return;
            }

            registration.As <AbstractRegistration>(e => e.Container = this);
            registrations.AddOrReplace(registration.ServiceType, registration);
        }
Example #4
0
 void _Builder_NewTransaction(Transaction obj)
 {
     _Transactions.AddOrReplace(obj.GetHash(), obj);
     if (_Builder.Broadcast)
     {
         if (_Filter != null && _Filter.IsRelevantAndUpdate(obj) && _Known.TryAdd(obj.GetHash(), obj.GetHash()))
         {
             AttachedNode.SendMessageAsync(new InvPayload(obj));
         }
     }
 }
Example #5
0
        protected void Notify(string groupPath, List <ServiceMetadata> metadatas)
        {
            List <INotifyListener> listeners;

            if (_subscribed.TryGetValue(groupPath, out listeners))
            {
                listeners.ForEach(listener => this.Notify(groupPath, listener, metadatas));
            }

            _notified.AddOrReplace(groupPath, metadatas);
        }
Example #6
0
 void _Builder_NewBlock(Block obj)
 {
     _Blocks.AddOrReplace(obj.GetHash(), obj);
     foreach (var tx in obj.Transactions)
     {
         _Transactions.TryAdd(tx.GetHash(), tx);
     }
     if (_Builder.Broadcast)
     {
         AttachedNode.SendMessageAsync(new InvPayload(obj));
     }
 }
Example #7
0
        /// <summary>
        /// Gets the interaction device type identifier.
        /// </summary>
        /// <param name="application">The application.</param>
        /// <param name="operatingSystem">The operating system.</param>
        /// <param name="clientType">Type of the client.</param>
        /// <param name="deviceTypeData">The device type data.</param>
        /// <returns></returns>
        public int GetInteractionDeviceTypeId(string application, string operatingSystem, string clientType, string deviceTypeData)
        {
            var lookupKey    = $"{application}|{operatingSystem}|{clientType}";
            int?deviceTypeId = _deviceTypeIdLookup.GetValueOrNull(lookupKey);

            if (deviceTypeId == null)
            {
                deviceTypeId = GetOrCreateInteractionDeviceTypeId(application, operatingSystem, clientType, deviceTypeData);
                _deviceTypeIdLookup.AddOrReplace(lookupKey, deviceTypeId.Value);
            }

            return(deviceTypeId.Value);
        }
Example #8
0
        public async Task UpdateClientState(ExplorerClient client, CancellationToken cancellation)
        {
            _logger.LogInformation($"Updating summary for {client.CryptoCode}");
            var          state  = (NBXplorerState?)null;
            string       error  = null;
            StatusResult status = null;

            try
            {
                status = await client.GetStatusAsync(cancellation);

                if (status == null)
                {
                    state = NBXplorerState.NotConnected;
                }
                else if (status.IsFullySynched)
                {
                    state = NBXplorerState.Ready;
                }
                else if (!status.IsFullySynched)
                {
                    state = NBXplorerState.Synching;
                }
            }
            catch (Exception ex) when(!cancellation.IsCancellationRequested)
            {
                _logger.LogWarning($"Could not update summary for {client.CryptoCode} because {ex.Message}");
                error = ex.Message;
            }

            if (status != null && error == null && status.NetworkType != _options.NetworkType)
            {
                error =
                    $"{client.CryptoCode}: NBXplorer is on a different ChainType (actual: {status.NetworkType}, expected: {_options.NetworkType})";
            }

            if (error != null)
            {
                state = NBXplorerState.NotConnected;
            }

            var summary = new NBXplorerSummary()
            {
                Status = status,
                State  = state.GetValueOrDefault(NBXplorerState.NotConnected),
                Error  = error
            };

            _logger.LogInformation($"summary updated {client.CryptoCode}");
            _summaries.AddOrReplace(client.CryptoCode.ToUpperInvariant(), summary);
        }
        public async Task <byte[]> RequestCreation(string userId)
        {
            await using var dbContext = _contextFactory.CreateContext();
            var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
                       .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);

            if (user == null)
            {
                return(null);
            }
            var k1 = RandomUtils.GetBytes(32);

            CreationStore.AddOrReplace(userId, k1);
            return(k1);
        }
Example #10
0
        public async Task <CredentialCreateOptions> RequestCreation(string userId)
        {
            await using var dbContext = _contextFactory.CreateContext();
            var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
                       .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);

            if (user == null)
            {
                return(null);
            }

            // 2. Get user existing keys by username
            var existingKeys =
                user.Fido2Credentials
                .Where(credential => credential.Type == Fido2Credential.CredentialType.FIDO2)
                .Select(c => c.GetFido2Blob().Descriptor).ToList();

            // 3. Create options
            var authenticatorSelection = new AuthenticatorSelection
            {
                RequireResidentKey = false,
                UserVerification   = UserVerificationRequirement.Preferred
            };

            var exts = new AuthenticationExtensionsClientInputs()
            {
                Extensions            = true,
                UserVerificationIndex = true,
                Location = true,
                UserVerificationMethod = true,
                BiometricAuthenticatorPerformanceBounds = new AuthenticatorBiometricPerfBounds
                {
                    FAR = float.MaxValue,
                    FRR = float.MaxValue
                },
            };

            var options = _fido2.RequestNewCredential(
                new Fido2User()
            {
                DisplayName = user.UserName, Name = user.UserName, Id = user.Id.ToBytesUTF8()
            },
                existingKeys, authenticatorSelection, AttestationConveyancePreference.None, exts);

            // options.Rp = new PublicKeyCredentialRpEntity(Request.Host.Host, options.Rp.Name, "");
            CreationStore.AddOrReplace(userId, options);
            return(options);
        }
        public async Task <byte[]> RequestLogin(string userId)
        {
            await using var dbContext = _contextFactory.CreateContext();
            var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
                       .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);

            if (!(user?.Fido2Credentials?.Any(credential => credential.Type == Fido2Credential.CredentialType.LNURLAuth) is true))
            {
                return(null);
            }

            var k1 = RandomUtils.GetBytes(32);

            FinalLoginStore.TryRemove(userId, out _);
            LoginStore.AddOrReplace(userId, k1);
            return(k1);
        }
        private async Task ListenForPayment(CancellationToken cancellationToken, KeyValuePair <string, LightningNodeService> lightningNodeService)
        {
            var linkedCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            _cancellationTokens.AddOrReplace(lightningNodeService.Key, linkedCancellation);
            _ = (await lightningNodeService.Value.ConstructClient().Listen(linkedCancellation.Token))
                .WaitInvoice(linkedCancellation.Token).ContinueWith(
                task =>
            {
                _ = _triggerDispatcher.DispatchTrigger(new ReceivedLightningPaymentTrigger()
                {
                    Data = new ReceivedLightningPaymentTriggerData()
                    {
                        LightningInvoice  = task.Result,
                        ExternalServiceId = lightningNodeService.Key
                    }
                });
                _ = ListenForPayment(cancellationToken, lightningNodeService);
            }, TaskScheduler.Default);
        }
Example #13
0
        public async Task <AssertionOptions> RequestLogin(string userId)
        {
            await using var dbContext = _contextFactory.CreateContext();
            var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
                       .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);

            if (!(user?.Fido2Credentials?.Any() is true))
            {
                return(null);
            }
            var existingCredentials = user.Fido2Credentials
                                      .Where(credential => credential.Type == Fido2Credential.CredentialType.FIDO2)
                                      .Select(c => c.GetBlob().Descriptor)
                                      .ToList();
            var exts = new AuthenticationExtensionsClientInputs()
            {
                SimpleTransactionAuthorization  = "FIDO",
                GenericTransactionAuthorization = new TxAuthGenericArg
                {
                    ContentType = "text/plain",
                    Content     = new byte[] { 0x46, 0x49, 0x44, 0x4F }
                },
                UserVerificationIndex = true,
                Location = true,
                UserVerificationMethod = true,
                Extensions             = true,
                AppID = _fido2Configuration.Origin
            };

            // 3. Create options
            var options = _fido2.GetAssertionOptions(
                existingCredentials,
                UserVerificationRequirement.Discouraged,
                exts
                );

            LoginStore.AddOrReplace(userId, options);
            return(options);
        }
Example #14
0
        public virtual async Task <Changelly> TryGetChangellyClient(string storeId, StoreData storeData = null)
        {
            if (_clientCache.ContainsKey(storeId))
            {
                return(_clientCache[storeId]);
            }

            if (storeData == null)
            {
                storeData = await _storeRepository.FindStore(storeId);

                if (storeData == null)
                {
                    throw new ChangellyException("Store not found");
                }
            }

            var blob = storeData.GetStoreBlob();
            var changellySettings = blob.ChangellySettings;


            if (changellySettings == null || !changellySettings.IsConfigured())
            {
                throw new ChangellyException("Changelly not configured for this store");
            }

            if (!changellySettings.Enabled)
            {
                throw new ChangellyException("Changelly not enabled for this store");
            }

            var changelly = new Changelly(_httpClientFactory.CreateClient("Changelly"), changellySettings.ApiKey,
                                          changellySettings.ApiSecret,
                                          changellySettings.ApiUrl);

            _clientCache.AddOrReplace(storeId, changelly);
            return(changelly);
        }
Example #15
0
 void _Builder_NewTransaction(Transaction obj)
 {
     _Transactions.AddOrReplace(obj.GetHash(), obj);
     BroadcastCore(obj);
 }
        private async Task DownloadNextBlocks(Node node, CancellationToken ctsToken, int maxBlocksToDownload = 1)
        {
            var heights = new List <Height>();

            try
            {
                await _sem.WaitAsync(ctsToken).ConfigureAwait(false);

                if (BlocksToDownload.Count == 0)
                {
                    await Task.Delay(100, ctsToken).ContinueWith(tsk => { }).ConfigureAwait(false);

                    return;
                }

                if (BlocksToDownload.Count < maxBlocksToDownload * 2)
                {
                    maxBlocksToDownload = 1;
                }

                for (int i = 0; i < maxBlocksToDownload; i++)
                {
                    // todo check if we have that much block
                    var height = BlocksToDownload.Min();
                    BlocksToDownload.TryRemove(height);
                    heights.Add(height);
                }
            }
            finally
            {
                _sem.Release();
            }
            try
            {
                var headers = new HashSet <ChainedBlock>();
                foreach (var height in heights)
                {
                    WalletJob.TryGetHeader(height, out ChainedBlock neededHeader);
                    headers.Add(neededHeader);
                }

                var delayMinutes     = heights.Count;
                var timeoutToken     = new CancellationTokenSource(TimeSpan.FromMinutes(delayMinutes)).Token;
                var downloadCtsToken = CancellationTokenSource.CreateLinkedTokenSource(timeoutToken, ctsToken).Token;

                HashSet <Block> blocks = null;
                try
                {
                    blocks = new HashSet <Block>(await Task.Run(() => node.GetBlocks(headers.ToArray(), downloadCtsToken)).ConfigureAwait(false));
                }
                catch
                {
                    if (timeoutToken.IsCancellationRequested)
                    {
                        node.DisconnectAsync($"Block download time > {delayMinutes}min");
                    }
                    else
                    {
                        node.DisconnectAsync("Block download failed");
                    }
                    blocks = null;
                }
                if (blocks == null)
                {
                    foreach (var height in heights)
                    {
                        BlocksToDownload.Add(height);
                    }
                }
                else
                {
                    int i = 0;
                    foreach (var block in blocks)
                    {
                        DownloadedBlocks.AddOrReplace(heights[i], block);
                        i++;
                    }
                }
            }
            catch
            {
                try
                {
                    await _sem.WaitAsync(ctsToken).ConfigureAwait(false);

                    foreach (var height in heights)
                    {
                        BlocksToDownload.Add(height);
                    }
                }
                finally
                {
                    _sem.Release();
                }
            }
        }
        public SetupGameState(
            Lobby lobby,
            int numExpectedPerUser,
            string unityTitle        = "Setup Time!",
            string unityInstructions = "",
            TimeSpan?setupDuration   = null)
            : base(lobby: lobby, exit: new WaitForUsers_StateExit(lobby))
        {
            ConcurrentDictionary <User, int> usersToNumSubmitted = new ConcurrentDictionary <User, int>();

            foreach (User user in lobby.GetAllUsers())
            {
                usersToNumSubmitted.AddOrReplace(user, 0);
            }
            StateChain setupChain = new StateChain(
                stateGenerator: (int counter) =>
            {
                if (counter < numExpectedPerUser)
                {
                    SimplePromptUserState setupUserState = new SimplePromptUserState(
                        promptGenerator: (User user) =>
                    {
                        return(CountingPromptGenerator(user, usersToNumSubmitted[user]));
                    },
                        formSubmitHandler: (User user, UserFormSubmission input) =>
                    {
                        (bool, string)handlerResponse = CountingFormSubmitHandler(user, input, usersToNumSubmitted[user]);
                        if (handlerResponse.Item1)
                        {
                            usersToNumSubmitted[user]++;
                        }
                        return(handlerResponse);
                    },
                        userTimeoutHandler: (User user, UserFormSubmission input) =>
                    {
                        return(CountingUserTimeoutHandler(user, input, usersToNumSubmitted[user]));
                    });

                    setupUserState.AddPerUserExitListener((User user) =>
                    {
                        if (usersToNumSubmitted.All(kvp => kvp.Value >= numExpectedPerUser))     // if after this users submission everyone has finished the expected amount it rushes everyone through
                        {
                            this.HurryUsers();
                        }
                    });

                    return(setupUserState);
                }
                else
                {
                    return(null);
                }
            },
                stateDuration: setupDuration);

            this.Entrance.Transition(setupChain);
            setupChain.Transition(this.Exit);
            this.Legacy_UnityView = new Legacy_UnityView(lobby)
            {
                ScreenId = new StaticAccessor <TVScreenId> {
                    Value = TVScreenId.WaitForUserInputs
                },
                Title = new StaticAccessor <string> {
                    Value = unityTitle
                },
                Instructions = new StaticAccessor <string> {
                    Value = unityInstructions
                },
            };
        }
        public ExtraSetupGameState(
            Lobby lobby,
            int numExtraObjectsNeeded)
            : base(lobby: lobby, exit: new WaitForUsers_StateExit(lobby))
        {
            int numLeft = numExtraObjectsNeeded;
            ConcurrentDictionary <User, int> usersToNumSubmitted = new ConcurrentDictionary <User, int>();

            foreach (User user in lobby.GetAllUsers())
            {
                usersToNumSubmitted.AddOrReplace(user, 0);
            }
            StateChain extraChain = new StateChain(
                stateGenerator: (int counter) =>
            {
                if (numLeft > 0)
                {
                    SimplePromptUserState setupUserState = new SimplePromptUserState(
                        promptGenerator: (User user) =>
                    {
                        return(CountingPromptGenerator(user, usersToNumSubmitted[user]));
                    },
                        formSubmitHandler: (User user, UserFormSubmission input) =>
                    {
                        (bool, string)handlerResponse = CountingFormSubmitHandler(user, input, usersToNumSubmitted[user]);
                        if (handlerResponse.Item1)
                        {
                            numLeft--;
                            usersToNumSubmitted[user]++;
                        }
                        return(handlerResponse);
                    });

                    setupUserState.AddPerUserExitListener((User user) =>
                    {
                        if (numLeft <= 0)
                        {
                            this.HurryUsers();
                        }
                    });

                    return(setupUserState);
                }
                else
                {
                    return(null);
                }
            });

            if (numExtraObjectsNeeded <= 0)
            {
                this.Entrance.Transition(this.Exit);
            }
            else
            {
                this.Entrance.Transition(extraChain);
                extraChain.Transition(this.Exit);
            }

            this.Legacy_UnityView = new Legacy_UnityView(lobby)
            {
                ScreenId = new StaticAccessor <TVScreenId> {
                    Value = TVScreenId.WaitForUserInputs
                },
                Title = new StaticAccessor <string> {
                    Value = "Oh! It seems like we didn't get enough to move on. Keep em comming!"
                },
                Instructions = new StaticAccessor <string> {
                    Value = Invariant($"{numExtraObjectsNeeded} more required")
                },
            };
        }
 private void Set(WalletId walletId, KeyPathInformation information)
 {
     _walletReceiveState.AddOrReplace(walletId, information);
 }
Example #20
0
        private async Task DownloadNextBlocksAsync(Node node, CancellationToken ctsToken, int maxBlocksToDownload = 1)
        {
            var heights = new List <Height>();

            using (await _asyncLock.LockAsync())
            {
                if (_blocksToDownload.Count == 0)
                {
                    await Task.Delay(100, ctsToken).ContinueWith(tsk => { });

                    return;
                }

                if (_blocksToDownload.Count < maxBlocksToDownload * 2)
                {
                    maxBlocksToDownload = 1;
                }

                for (int i = 0; i < maxBlocksToDownload; i++)
                {
                    // todo check if we have that much block
                    var height = _blocksToDownload.Min();
                    _blocksToDownload.TryRemove(height);
                    heights.Add(height);
                }
            }
            try
            {
                var headers = new HashSet <ChainedBlock>();
                foreach (var height in heights)
                {
                    var neededHeader = await _walletJob.TryGetHeaderAsync(height);

                    headers.Add(neededHeader);
                }

                var delayMinutes = heights.Count;
                using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(delayMinutes)))
                {
                    var timeoutToken     = cancellationTokenSource.Token;
                    var downloadCtsToken = CancellationTokenSource.CreateLinkedTokenSource(timeoutToken, ctsToken).Token;

                    HashSet <Block> blocks = null;
                    try
                    {
                        blocks = new HashSet <Block>(await Task.Run(() => node.GetBlocks(headers.ToArray(), downloadCtsToken)));
                    }
                    catch (Exception)
                    {
                        if (timeoutToken.IsCancellationRequested)
                        {
                            node.DisconnectAsync($"Block download time > {delayMinutes}min");
                        }
                        else
                        {
                            node.DisconnectAsync("Block download failed");
                        }
                        blocks = null;
                    }
                    if (blocks == null)
                    {
                        foreach (var height in heights)
                        {
                            _blocksToDownload.Add(height);
                        }
                    }
                    else
                    {
                        int i = 0;
                        foreach (var block in blocks)
                        {
                            _downloadedBlocks.AddOrReplace(heights[i], block);
                            i++;
                        }
                    }
                }
            }
            catch (Exception)
            {
                using (_asyncLock.Lock())
                {
                    foreach (var height in heights)
                    {
                        _blocksToDownload.Add(height);
                    }
                }
            }
        }