示例#1
0
        public string ComputeMac([FromRoute] string userId, [FromRoute] string challengeId)
        {
            if (!Regex.IsMatch(userId, UserIdPattern))
            {
                return("Invalid userId. UserId should contains only alphabetical and numerical symbols!");
            }

            var key     = this.GetSecretKey(userId, challengeId);
            var message = Encoding.ASCII.GetBytes($"user={userId};");

            var mac = SHA1.Create().ComputeHash(key.Concat(message).ToArray());

            return(HexHelper.HexFromByteArray(mac));
        }
        public static async Task ProcessPayout(MySqlConnection connection, int blockchainID, Web3 cl, string contractAddress, EventLog <List <ParameterOutput> > eventLog)
        {
            using (await LockManager.GetLock(LockType.PayoutInsert).Lock())
            {
                var offerId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "offerId").Result);

                var amount = Web3.Convert.FromWei((BigInteger)eventLog.Event
                                                  .FirstOrDefault(e => e.Parameter.Name == "amount").Result);

                var holder = (string)eventLog.Event.FirstOrDefault(e => e.Parameter.Name == "holder")
                             .Result;

                if (OTContract_Holding_Paidout.Exists(connection, offerId, holder, amount, eventLog.Log.TransactionHash,
                                                      blockchainID))
                {
                    return;
                }

                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash,
                                                       eventLog.Log.BlockNumber,
                                                       cl, blockchainID);


                var receipt = cl.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                var transaction =
                    cl.Eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;

                OTContract_Holding_Paidout.InsertIfNotExist(connection, new OTContract_Holding_Paidout
                {
                    OfferID         = offerId,
                    Holder          = holder,
                    Amount          = amount,
                    Timestamp       = block.Timestamp,
                    TransactionHash = eventLog.Log.TransactionHash,
                    ContractAddress = contractAddress,
                    BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                    GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                    Data            = eventLog.Log.Data,
                    GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                    BlockchainID    = blockchainID
                });
            }
        }
        public static async Task ProcessOfferTasks(MySqlConnection connection, int blockchainID, Web3 cl,
                                                   string contractAddress, EventLog <List <ParameterOutput> > eventLog, EthApiService eth)
        {
            using (await LockManager.GetLock(LockType.OfferTask).Lock())
            {
                var offerId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "offerId").Result);

                if (OTContract_Holding_OfferTask.Exists(connection, offerId, blockchainID))
                {
                    return;
                }

                var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                       cl, blockchainID);

                var dataSetId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "dataSetId").Result);
                var dcNodeId =
                    HexHelper.ByteArrayToString((byte[])eventLog.Event
                                                .First(e => e.Parameter.Name == "dcNodeId").Result);

                var task = HexHelper.ByteArrayToString(
                    (byte[])eventLog.Event.First(e => e.Parameter.Name == "task").Result);

                var transaction = eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

                var receipt = eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

                await transaction;
                await receipt;

                OTContract_Holding_OfferTask.InsertIfNotExist(connection, new OTContract_Holding_OfferTask
                {
                    BlockNumber     = (UInt64)eventLog.Log.BlockNumber.Value,
                    Task            = task,
                    TransactionHash = eventLog.Log.TransactionHash,
                    ContractAddress = contractAddress,
                    DCNodeId        = dcNodeId,
                    DataSetId       = dataSetId,
                    OfferId         = offerId,
                    GasPrice        = (UInt64)transaction.Result.GasPrice.Value,
                    GasUsed         = (UInt64)receipt.Result.GasUsed.Value,
                    BlockchainID    = blockchainID
                });
            }
        }
示例#4
0
        public WalletInfo(string keyStoreJson, string password)
        {
            if (keyStoreJson == null)
            {
                throw new ArgumentNullException(nameof(keyStoreJson));
            }
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            PrivateKey = HexHelper.ToHex(new KeyStoreService()
                                         .DecryptKeyStoreFromJson(password, keyStoreJson), true);
            Address = EthECKey.GetPublicAddress(PrivateKey);
        }
示例#5
0
        /// <summary>
        /// Для препятсвий выбираются только те узлы, для которых есть все соседи.
        /// </summary>
        private static bool HasAllHeighbors(HashSet <OffsetCoords> coordHash, CubeCoords[] neighborCubeOffsets,
                                            CubeCoords cube)
        {
            foreach (var neighborCubeOffset in neighborCubeOffsets)
            {
                var neighborCube         = cube + neighborCubeOffset;
                var neighborOffsetCoords = HexHelper.ConvertToOffset(neighborCube);
                if (!coordHash.Contains(neighborOffsetCoords))
                {
                    return(false);
                }
            }

            return(true);
        }
        private static IEnumerable <Vector2Int> FindAvailableNeighbors(bool[][] fields, int x, int y, Vector2Int minIndexLimit, Vector2Int maxIndexLimit)
        {
            //var neighbors = new Vector2Int[6];

            for (var direction = 0; direction < 6; direction++)
            {
                var indexX   = Math.Abs(x % 2);
                var neighbor = HexHelper.IndexOfNeighbor(x, y, (HexHelper.Direction)direction);

                if (HasValidIndex(neighbor, minIndexLimit, maxIndexLimit) && fields[neighbor.x][neighbor.y])
                {
                    yield return(neighbor);
                }
            }
        }
示例#7
0
        private void ConnectRoomsWithCorridor(IMap map, HashSet <string> edgeHash, Room room, Room selectedRoom)
        {
            var currentNode = room.Nodes.First();
            var targetNode  = selectedRoom.Nodes.First();

            var points = CubeCoordsHelper.CubeDrawLine(currentNode.CubeCoords, targetNode.CubeCoords);

            foreach (var point in points)
            {
                var offsetCoords = HexHelper.ConvertToOffset(point);

                var node = CreateCorridorNode(map, edgeHash, currentNode, offsetCoords.X, offsetCoords.Y);
                currentNode = node;
            }
        }
        public override void LoopContent()
        {
            _dict.Clear();
            _dict.Add(CHART_REMOTE_PORT1, string.Format("{0},{1:f3},{2:f3},{3:f3}", Config.MachineName, Const.GnssInfo.LocalCoor_Tipx, Const.GnssInfo.LocalCoor_Tipy, Const.StrategyDataSource.MaterialHeight));
            _dict.Add(CHART_REMOTE_PORT2, string.Format("{0},{1:f3},{2:f3},{3:f3},{4:f3},{5:f3},{6:f3}", Config.MachineName, Const.RadarInfo.DistLeftFront, Const.RadarInfo.DistLeftMiddle, Const.RadarInfo.DistLeftBack, Const.RadarInfo.DistRightFront, Const.RadarInfo.DistRightMiddle, Const.RadarInfo.DistRightBack));
            _dict.Add(CHART_REMOTE_PORT3, string.Format("{0},{1:f3},{2:f3},{3:f3},{4:f3},{5:f3},{6:f3}", Config.MachineName, Const.GnssInfo.LocalCoor_Tipx, Const.GnssInfo.LocalCoor_Tipy, Const.GnssInfo.LocalCoor_Tipz, Const.GnssInfo.LocalCoor_Centrex, Const.GnssInfo.LocalCoor_Centrey, Const.GnssInfo.LocalCoor_Centrez));
            List <int> ports = _dict.Keys.Cast <int>().ToList();

            ports.ForEach(port =>
            {
                _dict[port] = HexHelper.GetStringSumResult(_dict[port]);
                try { _udp.SendString(_dict[port], Const.LocalIp, port); }
                catch (Exception) { }
            });
        }
示例#9
0
        public void ConvertToCubeTest(int offsetX, int offsetY, int cubeX, int cubeY, int cubeZ)
        {
            // ARRANGE
            var expectedCubeCoords = new CubeCoords(cubeX, cubeY, cubeZ);



            // ACT
            var factCubeCoords = HexHelper.ConvertToCube(offsetX, offsetY);



            // ASSERT
            factCubeCoords.Should().BeEquivalentTo(expectedCubeCoords);
        }
示例#10
0
        /// <summary>
        /// Проверяет, доступен ли целевой узел из стартового узла.
        /// </summary>
        /// <param name="currentNode">Стартовый узел.</param>
        /// <param name="targetNode">Целевой проверяемый узел.</param>
        /// <returns>
        /// Возвращает true, если узел доступен. Иначе, false.
        /// </returns>
        public bool TargetIsOnLine(IGraphNode currentNode, IGraphNode targetNode)
        {
            if (currentNode is null)
            {
                throw new System.ArgumentNullException(nameof(currentNode));
            }

            if (targetNode is null)
            {
                throw new System.ArgumentNullException(nameof(targetNode));
            }

            var targetHexNode  = (HexNode)targetNode;
            var currentHexNode = (HexNode)currentNode;

            var line = CubeCoordsHelper.CubeDrawLine(currentHexNode.CubeCoords, targetHexNode.CubeCoords);

            for (var i = 1; i < line.Length; i++)
            {
                var prevPoint = line[i - 1];
                var testPoint = line[i];

                var prevOffsetCoords = HexHelper.ConvertToOffset(prevPoint);
                var testOffsetCoords = HexHelper.ConvertToOffset(testPoint);

                var prevNode = GetByCoords(prevOffsetCoords.X, prevOffsetCoords.Y);

                if (prevNode == null)
                {
                    return(false);
                }

                var testNode = GetByCoords(testOffsetCoords.X, testOffsetCoords.Y);

                if (testNode == null)
                {
                    return(false);
                }

                var hasNext = GetNext(prevNode).Contains(testNode);
                if (!hasNext)
                {
                    return(false);
                }
            }

            return(true);
        }
示例#11
0
        bool parse(string line, int filedIdLength, int packetNumLength, out string fileId, out packet packet)
        {
            fileId = "";
            packet = null;

            if (string.IsNullOrEmpty(line))
            {
                return(false);
            }

            try
            {
                Match m = Regex.Match(line, RegexData);
                if (m == null || !m.Success)
                {
                    return(false);
                }

                string dom;
                string data = m.Value.Trim();
                StringHelper.Split(data, '.', out data, out dom);

                if (filedIdLength > 0)
                {
                    fileId = data.Substring(0, filedIdLength);
                    if (string.IsNullOrEmpty(fileId))
                    {
                        return(false);
                    }
                }

                int packetNum = 0;
                if (packetNumLength > 0)
                {
                    packetNum = BitConverterHelper.ToInt32(HexHelper.FromHexString(data.Substring(filedIdLength, packetNumLength)), 0);
                }

                packet = new packet()
                {
                    Data = HexHelper.FromHexString(data.Remove(0, filedIdLength + packetNumLength)), Order = packetNum
                };
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#12
0
        public void ThenМонстрIdСтоитВУзле(int monsterId, string isNot, int offsetX, int offsetY)
        {
            var monster      = Context.GetMonsterById(monsterId);
            var node         = (HexNode)monster.Node;
            var cubeCoords   = node.CubeCoords;
            var offsetCoords = HexHelper.ConvertToOffset(cubeCoords);

            if (string.IsNullOrWhiteSpace(isNot))
            {
                offsetCoords.Should().Be(new OffsetCoords(offsetX, offsetY));
            }
            else
            {
                offsetCoords.Should().NotBe(new OffsetCoords(offsetX, offsetY));
            }
        }
示例#13
0
    public Hex GetHoverHex(Vector2 point)
    {
        var q = (2.0f / 3.0f * point.x) / hexRadius;
        var r = (-1.0f / 3.0f * point.x + Mathf.Sqrt(3) / 3 * point.y) / hexRadius;

        try
        {
            Vector2 hexCoords = HexHelper.HexRound(point);
            return(hexTable.Where(h => h.Column == hexCoords.x && h.Row == hexCoords.y).FirstOrDefault());
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
            return(new Hex());
        }
    }
示例#14
0
    void Start()
    {
        material             = Instantiate(material);
        material.renderQueue = 2001;
        material.color       = color;

        List <Tuple <Vector3, Vector3> > edges = new List <Tuple <Vector3, Vector3> >();

        foreach (HexTile tile in tiles)
        {
            if (tile.isOccluded || tile.type == HexTileType.Disabled)
            {
                continue;
            }

            foreach (HexPath path in tile.neighbors)
            {
                // path is crossing a border
                if (path.target.type == HexTileType.Disabled || path.target.isOccluded || !tiles.Contains(path.target))
                {
                    LineHexagon lineHex = tile.GetComponent <LineHexagon>();
                    Vector3[]   corners = lineHex.worldSpaceCorners;

                    edges.Add(new Tuple <Vector3, Vector3>(corners[path.index], corners[(path.index + 1) % 6]));
                }
            }
        }

        List <Vector3[]> lineStrips = CreateLineStrips(edges);

        foreach (Vector3[] lineStrip in lineStrips)
        {
            GameObject stripObject = new GameObject("outline");
            stripObject.transform.SetParent(transform);
            stripObject.layer = 14;

            MeshFilter   filter   = stripObject.AddComponent <MeshFilter>();
            MeshRenderer renderer = stripObject.AddComponent <MeshRenderer>();
            renderer.material = material;

            Mesh mesh = new Mesh();
            mesh.vertices = HexHelper.CreateLineStripVertices(lineStrip, thickness / 2.0f);
            mesh.SetIndices(HexHelper.CreateLineStripIndices(lineStrip.Length, true), MeshTopology.Triangles, 0);

            filter.mesh = mesh;
        }
    }
示例#15
0
        public void SimpleTest()
        {
            var sb       = new StringBuilder();
            var reverser = new CrcReverser
            {
                PrintLine = s => sb.AppendLine(s),
                MaxDepth  = 6
            };

            var  crcHex = "0x7C1FD48A";
            uint crcToMatch;

            HexHelper.TryParseCrcHex(crcHex, out crcToMatch);
            reverser.Execute(Constants.DefaultCharSet, crcToMatch);

            Assert.AreEqual("zbbW0" + Environment.NewLine, sb.ToString());
        }
示例#16
0
        public override string ToString()
        {
            var valueType = GetValueType();

            if (valueType == typeof(float[]))
            {
                return(ToString <float>(d => BinaryPrimitives.ReadSingleBigEndian(d).ToString("e9", System.Globalization.CultureInfo.InvariantCulture)));
            }
            else if (valueType == typeof(ushort[]))
            {
                return(ToString <ushort>(d => BinaryPrimitives.ReadUInt16BigEndian(d).ToString()));
            }
            else
            {
                return(HexHelper.ByteArrayToHexViaLookup32((byte[])Value, NodeInfo.ElementsPerRow));
            }
        }
示例#17
0
        public byte[] FromString(string value)
        {
            Type valueType = this.GetValueType();

            if (valueType == typeof(float[]))
            {
                return(FromString <float>(value, (s, d) => BinaryPrimitives.WriteSingleBigEndian(d, Convert.ToSingle(s, CultureInfo.InvariantCulture))));
            }
            else if (valueType == typeof(ushort[]))
            {
                return(FromString <ushort>(value, (s, d) => BinaryPrimitives.WriteUInt16BigEndian(d, Convert.ToUInt16(s))));
            }
            else
            {
                return(HexHelper.HexLineToByteUsingByteManipulation(value));
            }
        }
示例#18
0
        private void ProcessMouseCommands(SectorViewModelContext sectorViewModelContext)
        {
            var mouseState = Mouse.GetState();

            var inverseCameraTransform = Matrix.Invert(_camera.Transform);

            var mouseInWorld = Vector2.Transform(new Vector2(mouseState.X, mouseState.Y), inverseCameraTransform);

            var offsetMouseInWorld =
                HexHelper.ConvertWorldToOffset((int)mouseInWorld.X, (int)mouseInWorld.Y * 2,
                                               (int)(MapMetrics.UnitSize / 2));

            var map = _sector.Map;

            var hoverNodes = map.Nodes.OfType <HexNode>().Where(node => node.OffsetCoords == offsetMouseInWorld);
            var hoverNode  = hoverNodes.FirstOrDefault();

            _uiState.HoverViewModel =
                GetViewModelByNode(sectorViewModelContext, _uiState.HoverViewModel, hoverNode);

            if (!_leftMousePressed &&
                mouseState.LeftButton == ButtonState.Pressed &&
                _uiState.HoverViewModel != null &&
                _uiState.CanPlayerGivesCommand &&
                !BottomMenuPanel.MouseIsOver &&
                !PersonMarkersPanel.MouseIsOver)
            {
                _leftMousePressed = true;

                _uiState.SelectedViewModel = _uiState.HoverViewModel;
                var command = SelectCommandBySelectedViewModel(
                    _uiState.SelectedViewModel,
                    _commandFactory,
                    _uiState);

                if (command.CanExecute().IsSuccess)
                {
                    _commandPool.Push(command);
                }
            }

            if (_leftMousePressed && mouseState.LeftButton == ButtonState.Released)
            {
                _leftMousePressed = false;
            }
        }
示例#19
0
    private IGraphNode GetTargetNode(HexNode actorHexNode, StepDirection direction)
    {
        if (direction == StepDirection.Undefined)
        {
            throw new ArgumentException("Не определено направление.", nameof(direction));
        }

        var neighborNodes = _sectorManager.CurrentSector.Map.GetNext(actorHexNode).OfType <HexNode>();
        var directions    = HexHelper.GetOffsetClockwise();

        var stepDirectionIndex = _stepDirectionIndexes[direction];
        var targetCubeCoords   = actorHexNode.CubeCoords + directions[stepDirectionIndex];

        var targetNode = neighborNodes.SingleOrDefault(x => x.CubeCoords == targetCubeCoords);

        return(targetNode);
    }
示例#20
0
 private static void FillMap(ISectorMap map, int mapWidth, int mapHeight, int mapSize, HexNode centerNode)
 {
     for (var x = 0; x < mapWidth; x++)
     {
         for (var y = 0; y < mapHeight; y++)
         {
             var testOffsetCoords = new OffsetCoords(x, y);
             var testCubeCoords   = HexHelper.ConvertToCube(testOffsetCoords);
             var distanceToCenter = centerNode.CubeCoords.DistanceTo(testCubeCoords);
             if (distanceToCenter > 0 && distanceToCenter <= mapSize)
             {
                 var node = new HexNode(testOffsetCoords);
                 map.AddNode(node);
             }
         }
     }
 }
        private static Locality GetNeighborLocality(Agent agent, Globe globe)
        {
            Locality targetLocality = null;

            var nextCoords      = HexHelper.GetOffsetClockwise().OrderBy(item => Guid.NewGuid()).ToArray();
            var agentCubeCoords = HexHelper.ConvertToCube(agent.Localtion.Coords.X, agent.Localtion.Coords.Y);

            for (var i = 0; i < nextCoords.Length; i++)
            {
                var scanCubeCoords   = agentCubeCoords + nextCoords[i];
                var scanOffsetCoords = HexHelper.ConvertToOffset(scanCubeCoords);

                var freeX = scanOffsetCoords.X;
                var freeY = scanOffsetCoords.Y;

                if (freeX < 0)
                {
                    continue;
                }

                if (freeX >= globe.Terrain.Length)
                {
                    continue;
                }

                if (freeY < 0)
                {
                    continue;
                }

                if (freeY >= globe.Terrain[freeX].Length)
                {
                    continue;
                }

                var freeLocaltion1 = globe.Terrain[freeX][freeY];

                if (globe.LocalitiesCells.TryGetValue(freeLocaltion1, out var otherCheckLocality))
                {
                    targetLocality = otherCheckLocality;
                    break;
                }
            }

            return(targetLocality);
        }
示例#22
0
        private byte getByteFromXml(XmlNode node)
        {
            string val = node.Attributes["byte"].Value;
            byte   key;

            // starting with an "@" means it's a reference value
            if (val.StartsWith("@"))
            {
                key = FlatTokens[val.Substring(1)].Byte;
            }
            else if (!byte.TryParse(val, out key))
            {
                key = (HexHelper.GetByteArray(val, 1))[0];
            }

            return(key);
        }
示例#23
0
        /// <summary>
        /// Encode command.
        /// </summary>
        /// <returns>Result package</returns>
        public unsafe byte[] Encode()
        {
            byte[] result = new byte[5];
            fixed(byte *p0 = result)
            {
                byte *p = p0;

                *       p++ = (byte)FunctionCode;
                ushort *up  = (ushort *)p;

                *up++ = Address;
                *up++ = Count;
                HexHelper.SwapEvenOdd(p, 0, 4);
            }

            return(result);
        }
示例#24
0
        public async Task Update()
        {
            if (lamp == null)
            {
                return;
            }

            if (lamp.consumer == null)
            {
                return;
            }

            LampStateGetHueResult hueResult = await this.lamp.consumer.GetHueAsync();

            LampStateGetSaturationResult saturationResult = await this.lamp.consumer.GetSaturationAsync();

            LampStateGetBrightnessResult brigtnessResult = await this.lamp.consumer.GetBrightnessAsync();

            LampStateGetColorTempResult tempResult = await this.lamp.consumer.GetColorTempAsync();

            LampStateGetOnOffResult onOffResult = await this.lamp.consumer.GetOnOffAsync();

            var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
            await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                this.hue = HexHelper.ConvertHue(hueResult.Hue);
                this.OnPropertyChanged(HUE_PROPERTY);

                this.saturation = (byte)HexHelper.hexToPercent(saturationResult.Saturation);

                this.onOffState = onOffResult.OnOff;
                this.OnPropertyChanged(ON_OFF_PROPERTY);

                var brightness = (byte)HexHelper.hexToPercent(brigtnessResult.Brightness);
                if (this.brightness != brightness)
                {
                    this.brightness = brightness;
                    this.OnPropertyChanged(BRIGHT_PROPERTY);
                }
                this.temperature = tempResult.ColorTemp;
                this.OnPropertyChanged(TEMP_PROPERTY);

                this.DisplayColour = new SolidColorBrush(ColourHelper.ColorFromHSV(this.Hue, this.saturation, this.brightness));
            });
        }
        public static async Task ProcessLitigationInitiated(MySqlConnection connection, int blockchainID, Web3 cl,
                                                            EventLog <List <ParameterOutput> > eventLog, EthApiService eth)
        {
            if (OTContract_Litigation_LitigationInitiated.TransactionExists(connection, eventLog.Log.TransactionHash, blockchainID))
            {
                return;
            }

            var block = await BlockHelper.GetBlock(connection, eventLog.Log.BlockHash, eventLog.Log.BlockNumber,
                                                   cl, blockchainID);

            var offerId =
                HexHelper.ByteArrayToString((byte[])eventLog.Event
                                            .First(e => e.Parameter.Name == "offerId").Result);

            var holderIdentity = (string)eventLog.Event
                                 .First(e => e.Parameter.Name == "holderIdentity").Result;

            var requestedObjectIndex = (BigInteger)eventLog.Event
                                       .First(e => e.Parameter.Name == "requestedObjectIndex").Result;


            var requestedBlockIndex = (BigInteger)eventLog.Event
                                      .First(e => e.Parameter.Name == "requestedBlockIndex").Result;

            var transaction = await eth.Transactions.GetTransactionByHash.SendRequestAsync(eventLog.Log.TransactionHash);

            var receipt = await eth.Transactions.GetTransactionReceipt.SendRequestAsync(eventLog.Log.TransactionHash);

            var row = new OTContract_Litigation_LitigationInitiated
            {
                TransactionHash      = eventLog.Log.TransactionHash,
                BlockNumber          = (UInt64)eventLog.Log.BlockNumber.Value,
                Timestamp            = block.Timestamp,
                OfferId              = offerId,
                RequestedObjectIndex = (UInt64)requestedObjectIndex,
                RequestedBlockIndex  = (UInt64)requestedBlockIndex,
                HolderIdentity       = holderIdentity,
                GasPrice             = (UInt64)transaction.GasPrice.Value,
                GasUsed              = (UInt64)receipt.GasUsed.Value,
                BlockchainID         = blockchainID
            };

            await OTContract_Litigation_LitigationInitiated.InsertIfNotExist(connection, row);
        }
示例#26
0
        public string ValidateRawToken(
            [FromRoute] string userId,
            [FromRoute] string challengeId,
            [FromRoute] string rawToken)
        {
            using (var hash = SHA256.Create())
            {
                var seed = hash.ComputeHash(Encoding.ASCII.GetBytes(userId + challengeId + "GetEncryptedToken"));

                // converting hex -> byte -> ascii string
                rawToken = Encoding.ASCII.GetString(HexHelper.StringToByteArray(rawToken));
                if (TokenHelper.ValidateTokenString(rawToken) && TokenHelper.ValidateTokenUser(rawToken, seed))
                {
                    return("Raw Token decoded and validated. Wellcome to secretNet!");
                }
            }
            return("Token is incorrect");
        }
        private static IEnumerable <OffsetCoords> GetAvailableCoords(OffsetCoords[] regionDraftCoords)
        {
            var coordHash = new HashSet <OffsetCoords>(regionDraftCoords);

            var neighborCubeOffsets = HexHelper.GetOffsetClockwise();

            foreach (var coords in regionDraftCoords)
            {
                var cube = HexHelper.ConvertToCube(coords);

                var isValid = HasAllHeighbors(coordHash, neighborCubeOffsets, cube);

                if (isValid)
                {
                    yield return(coords);
                }
            }
        }
示例#28
0
        public string ValidateEncryptedToken(
            [FromRoute] string userId,
            [FromRoute] string challengeId,
            [FromRoute] string encryptedToken)
        {
            using (var hash = SHA256.Create())
            {
                var seed = hash.ComputeHash(Encoding.ASCII.GetBytes(userId + challengeId + "GetEncryptedToken"));
                var encryptedTokenBytes = HexHelper.StringToByteArray(encryptedToken);

                // change seed to make independant encryption key
                seed[0] ^= 255;
                try
                {
                    byte[] plainTextWithMac;
                    try
                    {
                        plainTextWithMac = this.paddingOracleManger.DecryptCbc(encryptedTokenBytes, seed);
                    }
                    catch (Exception ex)
                    {
                        var debug = this.paddingOracleManger.DecryptCbc(encryptedTokenBytes, seed, PaddingMode.None);
                        throw;
                    }

                    // change it back
                    seed[0] ^= 255;
                    var plainText = this.paddingOracleManger.VerifyMac(
                        plainTextWithMac,
                        seed);
                    var stringToken = Encoding.ASCII.GetString(plainText);

                    if (TokenHelper.ValidateTokenString(stringToken) && TokenHelper.ValidateTokenUser(stringToken, seed))
                    {
                        return("Token have been decoded and validated");
                    }
                    return("Token is incorrect");
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            }
        }
        public StaticObjectViewModel(Game game, IStaticObject staticObject, SpriteBatch spriteBatch,
                                     bool createHighlighted = false)
        {
            _game        = game;
            StaticObject = staticObject;
            _spriteBatch = spriteBatch;

            var graphics = new StaticObjectGraphics(game, staticObject);

            var worldCoords = HexHelper.ConvertToWorld(((HexNode)StaticObject.Node).OffsetCoords);

            var hexSize = MapMetrics.UnitSize / 2;
            var staticObjectPosition = new Vector2(
                (int)Math.Round(worldCoords[0] * hexSize * Math.Sqrt(HIGHLIGHT_DURATION_SECONDS),
                                MidpointRounding.ToEven),
                (int)Math.Round(worldCoords[1] * hexSize * 2 / 2, MidpointRounding.ToEven)
                );

            _rootSprite = new SpriteContainer
            {
                Position = staticObjectPosition
            };

            var hasNoShadow = StaticObject.Purpose == PropContainerPurpose.Puddle ||
                              StaticObject.Purpose == PropContainerPurpose.Pit;

            if (!hasNoShadow)
            {
                var shadowTexture = _game.Content.Load <Texture2D>("Sprites/game-objects/simple-object-shadow");
                _rootSprite.AddChild(new Sprite(shadowTexture)
                {
                    Position = new Vector2(0, 0),
                    Origin   = new Vector2(0.5f, 0.5f),
                    Color    = new Color(Color.White, 0.5f)
                });
            }

            _rootSprite.AddChild(graphics);

            if (createHighlighted)
            {
                _highlightCounter = HIGHLIGHT_DURATION_SECONDS;
            }
        }
示例#30
0
        public string AuthenticateUserEncrypted(
            [FromRoute] string userId,
            [FromRoute] string challengeId,
            [FromRoute] string encryptedToken)
        {
            using (var hash = SHA256.Create())
            {
                var seed = hash.ComputeHash(Encoding.ASCII.GetBytes(userId + challengeId));

                byte[] encryptedTokenBytes;
                try
                {
                    encryptedTokenBytes = HexHelper.StringToByteArray(encryptedToken);
                }
                catch (Exception)
                {
                    return($"Invalid token format! Can not deformat token!");
                }

                byte[] decryptedTokenBytes;
                try
                {
                    decryptedTokenBytes = this.cbcIvIsKeyManager.DecryptCbc(encryptedTokenBytes, seed);
                }
                catch (Exception)
                {
                    return($"Invalid token format! Can not decrypt token!");
                }

                var token = Encoding.ASCII.GetString(decryptedTokenBytes);

                if (!TokenHelper.ValidateTokenString(token))
                {
                    return($"Invalid token format! Received token [{token}] contains invalid characters!. Raw token is [{BitConverter.ToString(decryptedTokenBytes).Replace("-", "")}]");
                }

                if (!TokenHelper.ValidateTokenUser(token, seed))
                {
                    return("Access denied");
                }

                return($"Wellcome {userId}!");
            }
        }