Example #1
0
        public async Task <UserDto> DownloadUserDataAsync(string operationId, long nodeId)
        {
            var nodeConnection = connectionsService.GetNodeConnection(nodeId);

            if (nodeConnection != null)
            {
                string         requestUriString = $"https://{nodeConnection.Uri.Authority}/UserMigration/Download";
                HttpWebRequest httpWebRequest   = WebRequest.CreateHttp(requestUriString);
                byte[]         encryptedData    = Encryptor.SymmetricDataEncrypt(
                    Encoding.UTF8.GetBytes(operationId),
                    NodeData.Instance.NodeKeys.SignPrivateKey,
                    nodeConnection.SymmetricKey,
                    MessageDataType.Binary,
                    NodeData.Instance.NodeKeys.Password);
                httpWebRequest.Headers.Add("encryptedOperationId", Convert.ToBase64String(encryptedData));
                httpWebRequest.Headers.Add("nodeId", NodeSettings.Configs.Node.Id.ToString());
                using (WebResponse response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
                {
                    var    responseStream = response.GetResponseStream();
                    byte[] responseData   = responseStream.ReadAllBytes();
                    byte[] decryptedData  = Encryptor.SymmetricDataDecrypt(
                        responseData,
                        nodeConnection.SignPublicKey,
                        nodeConnection.SymmetricKey,
                        NodeData.Instance.NodeKeys.Password).DecryptedData;
                    return(ObjectSerializer.ByteArrayToObject <UserDto>(decryptedData));
                }
            }
            else
            {
                throw new ArgumentNullException(nameof(nodeId));
            }
        }
        public async Task SendPendingMessagesAsync(long nodeId)
        {
            try
            {
                var nodeConnection = _connectionsService.GetNodeConnection(nodeId);
                if (nodeConnection != null)
                {
                    var pendingMessages = await _pendingMessagesService.GetNodePendingMessagesAsync(nodeId).ConfigureAwait(false);

                    if (pendingMessages != null && pendingMessages.Any())
                    {
                        foreach (var message in pendingMessages)
                        {
                            await SendNoticeToNodeAsync(
                                nodeConnection,
                                ObjectSerializer.ByteArrayToObject <NodeNotice>(Convert.FromBase64String(message.Content))).ConfigureAwait(false);
                        }
                        await _pendingMessagesService.RemovePendingMessagesAsync(pendingMessages.Select(message => message.Id)).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
        public ConnectData GetConnectData(byte[] symmetricKey, byte[] signPublicKey, byte[] masterPassword)
        {
            byte[]      decryptedData = Encryptor.SymmetricDataDecrypt(Data, signPublicKey, symmetricKey, masterPassword).DecryptedData;
            ConnectData connectData   = ObjectSerializer.ByteArrayToObject <ConnectData>(decryptedData);

            connectData.SymmetricKey = symmetricKey;
            return(connectData);
        }
Example #4
0
 public T GetObjectByKey <T>(object keyValue)
 {
     try
     {
         return(ObjectSerializer.ByteArrayToObject <T>(redisDb.StringGet(keyValue.ToString())));
     }
     catch
     {
         return(default);
Example #5
0
        public async Task <ConversationPreviewVm> GetObject(string key)
        {
            byte[] array = (await redisDb.ListRangeAsync(key, 0, 0).ConfigureAwait(false)).FirstOrDefault();
            if (array == null)
            {
                return(null);
            }

            return(ObjectSerializer.ByteArrayToObject <ConversationPreviewVm>(array));
        }
        public ConnectData GetConnectData(byte[] signPublicKey, byte[] masterPassword, byte[] encPrivateKey = null)
        {
            ConnectData connectData;

            byte[] symmetricKey  = Encryptor.AsymmetricDecryptKey(EncryptedKey, encPrivateKey, signPublicKey, masterPassword).Data;
            byte[] decryptedData = Encryptor.SymmetricDataDecrypt(Data, signPublicKey, symmetricKey, masterPassword).DecryptedData;
            connectData = ObjectSerializer.ByteArrayToObject <ConnectData>(decryptedData);
            connectData.SymmetricKey = symmetricKey;
            return(connectData);
        }
Example #7
0
        public async Task <List <BlockVm> > GetBlockchainBlocksAsync(long startId, long endId)
        {
            using (WebClient webClient = new WebClient())
            {
                byte[] responseData = await webClient.DownloadDataTaskAsync($"https://{NodeSettings.Configs.LicensorUrl}/api/Blockchain/Download?startId={startId}&endId={endId}")
                                      .ConfigureAwait(false);

                return(ObjectSerializer.ByteArrayToObject <List <BlockVm> >(responseData));
            }
        }
Example #8
0
        public async Task <VerificationCodeInfo> GetObject(string key)
        {
            byte[] array = await redisDb.StringGetAsync(key).ConfigureAwait(false);

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

            return(ObjectSerializer.ByteArrayToObject <VerificationCodeInfo>(array));
        }
Example #9
0
        public async Task <IEnumerable <ConversationPreviewVm> > GetObjects(string key, long length)
        {
            RedisValue[] conversations = await redisDb.ListRangeAsync(key, 0, length).ConfigureAwait(false);

            if (conversations == null || !conversations.Any())
            {
                return(null);
            }

            return(conversations.Select(opt => ObjectSerializer.ByteArrayToObject <ConversationPreviewVm>(opt)));
        }
        public void Handle(byte[] data, NodeConnection current)
        {
            try
            {
                CommunicationObject @object;
                if (current.IsEncryptedConnection)
                {
                    byte[] decryptedData = Encryptor.SymmetricDataDecrypt(
                        data,
                        current.SignPublicKey,
                        current.SymmetricKey,
                        NodeData.Instance.NodeKeys.Password)
                                           .DecryptedData;
                    @object = ObjectSerializer.ByteArrayToObject <CommunicationObject>(decryptedData);
                }
                else
                {
                    @object = ObjectSerializer.ByteArrayToObject <CommunicationObject>(data);
                }
                nodeConnection = current;
                switch (@object.Type)
                {
                case ObjectType.NodeNotice:
                {
                    var notice = (NodeNotice)@object;
                    HandleNotice(notice);
                }
                break;

                case ObjectType.NodeRequest:
                {
                    var request = (NodeRequest)@object;
                    HandleRequest(request, current);
                }
                break;

                case ObjectType.NodeResponse:
                {
                    var response = (NodeResponse)@object;
                    HandleResponse(response);
                }
                break;
                }
                Logger.WriteLog(@object);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
Example #11
0
        public async Task <IEnumerable <BlockSegmentVm> > GetObjects(string key, long length)
        {
            List <BlockSegmentVm> result = new List <BlockSegmentVm>();

            RedisValue[] segments = await redisDb.ListRangeAsync(key, 0, length - 1).ConfigureAwait(false);

            await redisDb.ListTrimAsync(key, length, -1).ConfigureAwait(false);

            foreach (RedisValue serializedSegment in segments)
            {
                result.Add(ObjectSerializer.ByteArrayToObject <BlockSegmentVm>(serializedSegment));
            }
            return(result);
        }
Example #12
0
        public async Task <BlockchainInfo> GetBlockchainInfoAsync()
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    var data = await webClient.DownloadDataTaskAsync($"https://{NodeSettings.Configs.LicensorUrl}/api/Blockchain/Information").ConfigureAwait(false);

                    return(ObjectSerializer.ByteArrayToObject <BlockchainInfo>(data));
                }
            }
            catch (WebException ex)
            {
                Logger.WriteLog(ex);
                return(null);
            }
        }
Example #13
0
        private async void BeginReceiveAsync()
        {
            try
            {
                while (webSocket.State == WebSocketState.Open)
                {
                    try
                    {
                        byte[] receivedData = await ReceiveBytesAsync().ConfigureAwait(false);

                        if (IsEncrypted)
                        {
                            receivedData = Encryptor.SymmetricDataDecrypt(
                                receivedData,
                                licensorSignPublicKey,
                                symmetricKey,
                                NodeData.Instance.NodeKeys.Password).DecryptedData;
                        }
                        CommunicationObject communicationObject = ObjectSerializer.ByteArrayToObject <CommunicationObject>(receivedData);
                        if (communicationObject is LicensorResponse response)
                        {
                            Console.WriteLine($"Response received: {response.ResponseType}");
                            ResponseReceivedEvent.Invoke(response);
                        }
                        else if (communicationObject is LicensorNotice licensorNotice)
                        {
                            LicensorNoticeManager licensorNoticeManager = new LicensorNoticeManager();
                            await licensorNoticeManager.HandleNoticeAsync(licensorNotice).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLog(ex);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
            }
        }
Example #14
0
        private async Task <List <BlockVm> > GetBlocksAsync(NodeConnection node, long startId, long endId)
        {
            HttpWebRequest webRequest = WebRequest.CreateHttp($"https://{node.Uri.Authority}/Blockchain/Download?startId={startId}&endId={endId}");

            webRequest.Method = "GET";
            using (var response = await webRequest.GetResponseAsync().ConfigureAwait(false))
            {
                byte[]      responseBuffer = new byte[128 * 1024];
                List <byte> responseData   = new List <byte>();
                using (Stream stream = response.GetResponseStream())
                {
                    using (BinaryReader bReader = new BinaryReader(stream))
                    {
                        int count;
                        while ((count = bReader.Read(responseBuffer, 0, responseBuffer.Length)) > 0)
                        {
                            responseData.AddRange(responseBuffer.Take(count));
                            await stream.FlushAsync().ConfigureAwait(false);
                        }
                        return(ObjectSerializer.ByteArrayToObject <List <BlockVm> >(responseData.ToArray()));
                    }
                }
            }
        }
Example #15
0
        public async Task <BlockSegmentVm> GetObject(string key)
        {
            byte[] array = await redisDb.ListLeftPopAsync(key).ConfigureAwait(false);

            return(ObjectSerializer.ByteArrayToObject <BlockSegmentVm>(array));
        }
Example #16
0
        public async Task <bool> AuthAsync(bool recursive = false)
        {
            if (string.IsNullOrWhiteSpace(NodeSettings.Configs.LicensorUrl))
            {
                return(false);
            }
            if (webSocket.State != WebSocketState.Open)
            {
                try
                {
                    await ConnectAndListenAsync().ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    throw new LicensorException("No connection.", ex);
                }
            }
            try
            {
                AuthRequest request = new AuthRequest(NodeData.Instance.NodeKeys.PublicKey, NodeSettings.Configs.Node.Id);
                await SendRequestAsync(request).ConfigureAwait(false);

                var response = await GetResponseAsync(request).ConfigureAwait(false);

                if (response is AuthResponse authResponse)
                {
                    symmetricKey = Encryptor.AsymmetricDecryptKey(
                        authResponse.EncryptedKey,
                        NodeData.Instance.NodeKeys.PrivateKey,
                        authResponse.LicensorSignPublicKey,
                        NodeData.Instance.NodeKeys.Password).Data;
                    var nodeDecryptedData = Encryptor.SymmetricDataDecrypt(
                        authResponse.EncryptedNode,
                        authResponse.LicensorSignPublicKey,
                        symmetricKey,
                        NodeData.Instance.NodeKeys.Password).DecryptedData;
                    var tokenDecryptedData = Encryptor.SymmetricDataDecrypt(
                        authResponse.EncryptedAccessToken,
                        authResponse.LicensorSignPublicKey,
                        symmetricKey,
                        NodeData.Instance.NodeKeys.Password).DecryptedData;
                    NodeVm node         = ObjectSerializer.ByteArrayToObject <NodeVm>(nodeDecryptedData);
                    var    licensorSign = authResponse.LicensorSign;
                    node.StartDay = node.StartDay.ToUniversalTime();
                    var nodeJson = ObjectSerializer.ObjectToJson(node);
                    licensorPublicKey     = authResponse.LicensorPublicKey;
                    licensorSignPublicKey = authResponse.LicensorSignPublicKey;
                    expiredAt             = DateTime.UtcNow.AddDays(7).ToUnixTime();
                    bool isValid = Encryptor.CheckSign(
                        licensorSign.Sign,
                        licensorSignPublicKey,
                        Encoding.UTF8.GetBytes(nodeJson),
                        NodeData.Instance.NodeKeys.Password);
                    if (isValid)
                    {
                        NodeSettings.Configs.LicensorSign = licensorSign;
                    }
                    return(true);
                }
                else if (response is ResultResponse resultResponse)
                {
                    if (resultResponse.ErrorCode == ObjectsLibrary.LicensorResponseClasses.ErrorCode.KeyNotFound || resultResponse.ErrorCode == ObjectsLibrary.LicensorResponseClasses.ErrorCode.IdNotFound)
                    {
                        if (!recursive)
                        {
                            var nodeKeys = await AppServiceProvider.Instance.KeysService.GetActualNodeKeysAsync(NodeSettings.Configs.Node.Id).ConfigureAwait(false);
                            await AddNewKeyAsync(nodeKeys.PublicKey, nodeKeys.SignPublicKey, nodeKeys.KeyId, nodeKeys.ExpirationTime, nodeKeys.GenerationTime, false).ConfigureAwait(false);
                            await AuthAsync(recursive : true).ConfigureAwait(false);

                            return(true);
                        }
                    }
                    throw new ResponseException($"Authorization failed. Response error message: {resultResponse.ErrorMessage}");
                }
                return(false);
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                return(false);
            }
        }
Example #17
0
        public async Task <bool> UpdateObject(string key, ConversationPreviewVm conversation)
        {
            RedisValue[] conversations = await redisDb.ListRangeAsync(key, -2, 0).ConfigureAwait(false);

            await redisDb.ListTrimAsync(key, 0, -2).ConfigureAwait(false);

            List <ConversationPreviewVm> userConversations = conversations.Select(opt => ObjectSerializer.ByteArrayToObject <ConversationPreviewVm>(opt)).ToList();

            RedisValue[] serializedChats = System.Array.Empty <RedisValue>();
            userConversations.ForEach(item =>
            {
                if (item.ConversationId == conversation.ConversationId)
                {
                    item = conversation;
                }

                serializedChats = serializedChats.Append(ObjectSerializer.ObjectToByteArray(item)).ToArray();
            });
            return(await redisDb.ListRightPushAsync(key, serializedChats).ConfigureAwait(false) > 0);
        }
        private async Task RestoreOldBlockchainDataAsync()
        {
            using (BlockchainDbContext context = new BlockchainDbContext())
            {
                long maxId = await context.ObsoleteBlocks.MaxAsync(opt => opt.Id).ConfigureAwait(false);

                long minId = await context.ObsoleteBlocks.MinAsync(opt => opt.Id).ConfigureAwait(false);

                byte limit = 100;
                for (long i = minId; i < maxId; i += limit)
                {
                    var obsoleteBlocks = await context.ObsoleteBlocks
                                         .Where(block => block.Id >= i)
                                         .Take(limit)
                                         .ToListAsync().ConfigureAwait(false);

                    List <BlockVm>        blocks             = obsoleteBlocks.Select(block => ObjectSerializer.ByteArrayToObject <BlockVm>(block.Data)).ToList();
                    List <BlockSegmentVm> allSegments        = new List <BlockSegmentVm>();
                    List <BlockSegmentVm> noexistentSegments = new List <BlockSegmentVm>();
                    foreach (var block in blocks)
                    {
                        allSegments.AddRange(block.BlockSegments);
                    }
                    var segmentsCondition = PredicateBuilder.New <BlockSegment>();
                    segmentsCondition = allSegments.Aggregate(segmentsCondition,
                                                              (current, value) => current.Or(opt => opt.SegmentHash.SequenceEqual(value.SegmentHash)).Expand());
                    var existentSegments = await context.BlockSegments.Where(segmentsCondition).ToListAsync().ConfigureAwait(false);

                    noexistentSegments = allSegments
                                         .Where(segment => !existentSegments.Any(exSegment => segment.SegmentHash.SequenceEqual(exSegment.SegmentHash)))
                                         ?.ToList();
                    if (!noexistentSegments.IsNullOrEmpty())
                    {
                        BlockGenerationHelper.Instance.AddSegments(noexistentSegments);
                    }
                }
                NpgsqlParameter blockIdParam = new NpgsqlParameter("blockId", minId);
                RawSqlString    sqlString    = new RawSqlString(@"DELETE FROM ""ObsoleteBlocks"" WHERE ""Id"" >= @blockId");
                await context.Database.ExecuteSqlCommandAsync(sqlString, blockIdParam).ConfigureAwait(false);
            }
        }