Пример #1
0
 public override object GetObject(byte[] inputBytes, int startOffset, out int nextStartOffset)
 {
     return(ByteUtil.DecodeULong(inputBytes, startOffset, out nextStartOffset));
 }
Пример #2
0
        /// <inheritdoc />
        public async Task AddPeersAsync(
            IEnumerable <Peer> peers,
            TimeSpan?timeout,
            CancellationToken cancellationToken)
        {
            try
            {
                var tasks = new List <Task>();
                foreach (Peer peer in peers)
                {
                    if (peer is BoundPeer boundPeer)
                    {
                        tasks.Add(PingAsync(
                                      boundPeer,
                                      timeout: timeout,
                                      cancellationToken: cancellationToken));
                    }
                }

                _logger.Verbose("Trying to ping all {PeersNumber} peers.", tasks.Count);
                await Task.WhenAll(tasks);

                _logger.Verbose("Update complete.");
            }
            catch (DifferentAppProtocolVersionException e)
            {
                AppProtocolVersion expected = e.ExpectedVersion, actual = e.ActualVersion;
                _logger.Debug(
                    $"Different version encountered during {nameof(AddPeersAsync)}().\n" +
                    "Expected version: {ExpectedVersion} ({ExpectedVersionExtra}) " +
                    "[{ExpectedSignature}; {ExpectedSigner}]\n" +
                    "Actual version: {ActualVersion} ({ActualVersionExtra}) [{ActualSignature};" +
                    "{ActualSigner}]",
                    expected.Version,
                    expected.Extra,
                    ByteUtil.Hex(expected.Signature),
                    expected.Signer.ToString(),
                    actual.Version,
                    actual.Extra,
                    ByteUtil.Hex(actual.Signature),
                    actual.Signer
                    );
            }
            catch (TimeoutException)
            {
                _logger.Debug(
                    $"Timeout occurred during {nameof(AddPeersAsync)}() after {timeout}.");
                throw;
            }
            catch (TaskCanceledException)
            {
                _logger.Debug($"Task is cancelled during {nameof(AddPeersAsync)}().");
            }
            catch (Exception e)
            {
                _logger.Error(
                    e,
                    $"Unexpected exception occurred during {nameof(AddPeersAsync)}().");
                throw;
            }
        }
Пример #3
0
 public App Wechat()
 {
     return(new App
     {
         Name = "Wechat",
         FileTargetInfos = new Dictionary <string, TargetInfo>
         {
             {
                 "WeChatWin.dll",
                 new TargetInfo
                 {
                     Name = "WeChatWin.dll",
                     RelativePath = "WeChatWin.dll"
                 }
             }
         },
         FileCommonModifyInfos = new Dictionary <string, List <CommonModifyInfo> >
         {
             {
                 "WeChatWin.dll",
                 new List <CommonModifyInfo>
                 {
                     new CommonModifyInfo
                     {
                         Name = "WeChatWin.dll",
                         StartVersion = "2.8.0.88",
                         EndVersion = "",
                         ReplacePatterns = new List <ReplacePattern>
                         {
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("00 85 C0 74 7B 8B C8 E8"),
                                 Replace = ByteUtil.HexStringToByteArray("00 85 C0 EB 7B 8B C8 E8"),
                                 Category = "防撤回"
                             },
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("C0 C3 CC CC CC CC CC CC CC CC CC CC CC CC CC CC 55 8B EC 83 EC 14 53 56 57 6A FF 0F 57 C0 C7"),
                                 Replace = ByteUtil.HexStringToByteArray("C0 C3 CC CC CC CC CC CC CC CC CC CC CC CC CC CC C3 8B EC 83 EC 14 53 56 57 6A FF 0F 57 C0 C7"),
                                 Category = "多开"
                             }
                         }
                     },
                     new CommonModifyInfo
                     {
                         Name = "WeChatWin.dll",
                         StartVersion = "2.7.0.00",
                         EndVersion = "2.8.0.88",
                         ReplacePatterns = new List <ReplacePattern>
                         {
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("00 85 C0 74 32 B9"),
                                 Replace = ByteUtil.HexStringToByteArray("00 85 C0 EB 32 B9"),
                                 Category = "防撤回"
                             },
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("C0 C3 CC CC CC CC CC CC CC CC CC CC CC CC CC CC 55 8B EC 83 EC 14 53 56 57 6A FF 0F 57 C0 C7"),
                                 Replace = ByteUtil.HexStringToByteArray("C0 C3 CC CC CC CC CC CC CC CC CC CC CC CC CC CC C3 8B EC 83 EC 14 53 56 57 6A FF 0F 57 C0 C7"),
                                 Category = "多开"
                             }
                         }
                     }
                 }
             }
         },
         FileModifyInfos = new Dictionary <string, List <ModifyInfo> >
         {
             {
                 "WeChatWin.dll",
                 new List <ModifyInfo>
                 {
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.8.0.112",
                         SHA1Before = "7497fc006f061799138aa33419280e41891a7981",
                         SHA1After = "07e681be40af32738d59a9332fe966c83c05e455",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x0028ED79,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x007E7B10,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.8.0.106",
                         SHA1Before = "e772c81c8a1b79cac77b22dbe67b375fa340ba30",
                         SHA1After = "bcbc491910f07cb995ef154a281450f2d052e90b",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00289099,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x007E5960,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.8.0.88",
                         SHA1Before = "b34c73e38cfec186890b58caac5fc9962377cd9b",
                         SHA1After = "8c108e92de0b6b4d9e61ce38ab8dd339a27e505b",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00288489,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x007E3D80,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.8.0.82",
                         SHA1Before = "c359cc1a391441d261753f2844f9156638df8631",
                         SHA1After = "d1b4dee8f7f91e34d68501987fd0675b33fe85da",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00285FC9,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x007E16B0,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.7.2.78",
                         SHA1Before = "26a5c5503f1e176676da5657c12812da8aaa0243",
                         SHA1After = "d338215a815c09755c04949995ec3e4eab8dce60",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00285EA9,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x007E1380,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.7.2.76",
                         SHA1Before = "0003c7b2c0136a0eb2a6cfc2c694cb57b04b5517",
                         SHA1After = "88af6055a0f4d3bdaa6f717ec8b263d4418487b6",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00285BA9,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x007E0DA0,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.7.1.88",
                         SHA1Before = "034059bad50dd793140952391bfa7936133e69b4",
                         SHA1After = "dd6d80c30ca9e0ea9f7d2f1add498fc9aa4bc7a0",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00262389,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x007957B0,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.7.1.85",
                         SHA1Before = "de0df4e138b72460450f66c029e33f4510f5e2df",
                         SHA1After = "fbd35720aaff3cdcfd3ff18ea503dc06450e5c99",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00262389,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x00795680,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.7.1.82",
                         SHA1Before = "20e111a18872bf6c7148a897c11da26c1ec95520",
                         SHA1After = "1e0741d325ca6b1cd2402b829a3d13a2524af617",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00262389,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x00795650,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.7.1.74",
                         SHA1Before = "b1eaf7edc074a88be5d0f89230436cc2084d24d2",
                         SHA1After = "eb3d74ccd87a09059a005f4972861898fc3de463",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00262389,
                                 Content = new byte[] { 0xEB }
                             },
                             new Change
                             {
                                 Position = 0x00795550,
                                 Content = new byte[] { 0xC3 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll",
                         Version = "2.7.1.65",
                         SHA1Before = "8346b97d264725da924d240c6eb77df3e693385e",
                         SHA1After = "42bab2c9c79ef4f2088c00ea6d817973e14a5e6e",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 2495545,
                                 Content = new byte[] { 235 }
                             }
                         }
                     },
                     new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.7.1.59", SHA1Before = "df954d403edaca89cd5394927a325a0023e93281", SHA1After = "6aa22460c91bb5c5e2f0ec1af99b8a5f6d4318c0", Changes = new List <Change> {
                             new Change {
                                 Position = 2496073, Content = new byte[] { 235 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.7.1.43", SHA1Before = "39cd9e09e1a3eac09e6808749bff525c9e3216ce", SHA1After = "7b829f1ff0217e346a80f9510fdd7634ddd49445", Changes = new List <Change> {
                             new Change {
                                 Position = 2494169, Content = new byte[] { 235 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.7.0.70", SHA1Before = "3b0601864aff3c1d792f812ad1ca05f02aa761e3", SHA1After = "1e8734d32b0a8c12758e30f99c77f729991fb071", Changes = new List <Change> {
                             new Change {
                                 Position = 2475657, Content = new byte[] { 235 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.7.0.65", SHA1Before = "063c2e05a0df1bdb8987c2d978d93499bd2052ba", SHA1After = "5ed4c09a4f18643b967f063a824d7e65d0567f8a", Changes = new List <Change> {
                             new Change {
                                 Position = 2475449, Content = new byte[] { 117 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.8.68", SHA1Before = "2e9417f4276b12fe32ca7b4fee49272a4a2af334", SHA1After = "699602ee3cbb9ae5714f6e6ebc658c875a6c66e6", Changes = new List <Change> {
                             new Change {
                                 Position = 2454006, Content = new byte[] { 116 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.8.65", SHA1Before = "e01f6855a96c12c30808960903ed199a33e4952c", SHA1After = "d9120569cfd0433aebea107d7b90805cbbac7518", Changes = new List <Change> {
                             new Change {
                                 Position = 2454265, Content = new byte[] { 117 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.8.52", SHA1Before = "88131302f664df6a657c9ca49d152da536fe5729", SHA1After = "8d1454b73831644181e962c1fa0ea4e2da4124a3", Changes = new List <Change> {
                             new Change {
                                 Position = 2453049, Content = new byte[] { 117 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.8.51", SHA1Before = "d0a5517b1292a751501b00b4b1f0702db2d9fc30", SHA1After = "53e7b1525d49bf2c3250a8131ff0ba2510779b78", Changes = new List <Change> {
                             new Change {
                                 Position = 2452614, Content = new byte[] { 116 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.8.37", SHA1Before = "7e01f8b04a158a4a50bc5a6e67c2fb8b02233170", SHA1After = "a1895004415fe9bcd7e690bd6e482b833b515599", Changes = new List <Change> {
                             new Change {
                                 Position = 2452614, Content = new byte[] { 116 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.7.57", SHA1Before = "80a91aaf941bcb1c24a7d672838ac73e9ebb2e40", SHA1After = "a0d3f9a45a835f97aef7fe0872387d8cfb5c25a4", Changes = new List <Change> {
                             new Change {
                                 Position = 2433413, Content = new byte[] { 116 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.7.40", SHA1Before = "04bd0cb28df6630b518f42a3f9c2caa4a9359fbc", SHA1After = "13c91cf1d4609959771fd137b9a86a5ca365e1b6", Changes = new List <Change> {
                             new Change {
                                 Position = 2432934, Content = new byte[] { 116 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.7.32", SHA1Before = "a02519c1007ee6723947c262c720d63c619f633e", SHA1After = "f3007471ca8734c29783c25f0bb49949a783a44", Changes = new List <Change> {
                             new Change {
                                 Position = 2432806, Content = new byte[] { 116 }
                             }
                         }
                     }, new ModifyInfo {
                         Name = "WeChatWin.dll", Version = "2.6.6.28", SHA1Before = "0b19cb17a62c3ea0efce0fb675a1d3b17845cba3", SHA1After = "260948656725446b818ea668273ceff02ddfb44d", Changes = new List <Change> {
                             new Change {
                                 Position = 2401678, Content = new byte[] { 116 }
                             }
                         }
                     }
                 }
             }
         }
     });
 }
Пример #4
0
        public TransactionQuery()
        {
            Field <NonNullGraphType <ListGraphType <NonNullGraphType <TransactionType <T> > > > >(
                "transactions",
                arguments: new QueryArguments(
                    new QueryArgument <AddressType>
            {
                Name         = "signer",
                DefaultValue = null,
            },
                    new QueryArgument <AddressType>
            {
                Name         = "involvedAddress",
                DefaultValue = null,
            },
                    new QueryArgument <BooleanGraphType>
            {
                Name         = "desc",
                DefaultValue = false,
            },
                    new QueryArgument <IntGraphType>
            {
                Name         = "offset",
                DefaultValue = 0,
            },
                    new QueryArgument <IntGraphType> {
                Name = "limit"
            }
                    ),
                resolve: context =>
            {
                var signer   = context.GetArgument <Address?>("signer");
                var involved = context.GetArgument <Address?>("involvedAddress");
                bool desc    = context.GetArgument <bool>("desc");
                long offset  = context.GetArgument <long>("offset");
                int?limit    = context.GetArgument <int?>("limit", null);

                return(Query <T> .ListTransactions(signer, involved, desc, offset, limit));
            }
                );

            Field <NonNullGraphType <ListGraphType <NonNullGraphType <TransactionType <T> > > > >(
                "stagedTransactions",
                arguments: new QueryArguments(
                    new QueryArgument <AddressType>
            {
                Name         = "signer",
                DefaultValue = null,
            },
                    new QueryArgument <AddressType>
            {
                Name         = "involvedAddress",
                DefaultValue = null,
            },
                    new QueryArgument <BooleanGraphType>
            {
                Name         = "desc",
                DefaultValue = false,
            },
                    new QueryArgument <IntGraphType>
            {
                Name         = "offset",
                DefaultValue = 0,
            },
                    new QueryArgument <IntGraphType> {
                Name = "limit"
            }
                    ),
                resolve: context =>
            {
                var signer   = context.GetArgument <Address?>("signer");
                var involved = context.GetArgument <Address?>("involvedAddress");
                bool desc    = context.GetArgument <bool>("desc");
                int offset   = context.GetArgument <int>("offset");
                int?limit    = context.GetArgument <int?>("limit", null);

                return(Query <T> .ListStagedTransactions(signer, involved, desc, offset, limit));
            }
                );

            Field <TransactionType <T> >(
                "transaction",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "id"
            }
                    ),
                resolve: context =>
            {
                var id = new TxId(
                    ByteUtil.ParseHex(context.GetArgument <string>("id"))
                    );
                return(Query <T> .GetTransaction(id));
            }
                );

            Name = "TransactionQuery";
        }
Пример #5
0
        /// <summary>
        ///     Restores the state of this object from the data of ToBytes()
        /// </summary>
        /// <param name="data">The data to restore from</param>
        /// <param name="offset">The offset into the data to start</param>
        public override void Restore(byte[] data, ref int offset)
        {
            base.Restore(data, ref offset);

            Gain = ByteUtil.GetDoubleFromSizedArray(data, ref offset);
        }
Пример #6
0
        public unsafe static List <IDictionary> CreateXModelDictionary(ProcessReader reader, long address, int count, List <IDictionary> MapEntities)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Read buffer
            var byteBuffer = reader.ReadBytes(address, count * Marshal.SizeOf <GfxStaticModel>());
            // Loop number of models we have
            List <IDictionary> MapModels = new List <IDictionary>(count);

            for (int i = 0; i < count; i++)
            {
                Dictionary <string, string> ModelData = new Dictionary <string, string>();
                List <double> Position = new List <double>();
                List <double> angles   = new List <double>();
                // Read Struct
                var staticModel = ByteUtil.BytesToStruct <GfxStaticModel>(byteBuffer, i * Marshal.SizeOf <GfxStaticModel>());
                // Model Name
                var modelName = reader.ReadNullTerminatedString(reader.ReadInt32(staticModel.ModelPointer));

                var matrix = new Rotation.Matrix();
                // Copy X Values
                matrix.Values[0] = staticModel.Matrix[0];
                matrix.Values[1] = staticModel.Matrix[1];
                matrix.Values[2] = staticModel.Matrix[2];
                // Copy Y Values
                matrix.Values[4] = staticModel.Matrix[3];
                matrix.Values[5] = staticModel.Matrix[4];
                matrix.Values[6] = staticModel.Matrix[5];
                // Copy Z Values
                matrix.Values[8]  = staticModel.Matrix[6];
                matrix.Values[9]  = staticModel.Matrix[7];
                matrix.Values[10] = staticModel.Matrix[8];
                // Convert to Euler
                var euler = matrix.ToEuler();
                // Add it
                if (string.IsNullOrEmpty(modelName) == true || modelName.Contains("?") == true || modelName.Contains("'") == true || modelName.Contains("\\") == true || modelName.Contains("viewmodel") == true || modelName.Contains("*") == true || staticModel.ModelScale < 0.001 || staticModel.ModelScale > 10)
                {
                }
                else
                {
                    if (modelName.Contains("mlv"))
                    {
                        modelName = modelName.Replace("mlv", "");
                    }
                    ModelData.Add("Name", CleanInput(modelName));
                    ModelData.Add("PosX", string.Format("{0:0.0000}", staticModel.X));
                    ModelData.Add("PosY", string.Format("{0:0.0000}", staticModel.Y));
                    ModelData.Add("PosZ", string.Format("{0:0.0000}", staticModel.Z));
                    ModelData.Add("RotX", string.Format("{0:0.0000}", (float)Rotation.ToDegrees(euler).X).ToString(CultureInfo.InvariantCulture));
                    ModelData.Add("RotY", string.Format("{0:0.0000}", (float)Rotation.ToDegrees(euler).Y).ToString(CultureInfo.InvariantCulture));
                    ModelData.Add("RotZ", string.Format("{0:0.0000}", (float)Rotation.ToDegrees(euler).Z).ToString(CultureInfo.InvariantCulture));
                    ModelData.Add("Scale", string.Format("{0:0.0000}", staticModel.ModelScale).ToString(CultureInfo.InvariantCulture));
                    MapModels.Add(new Dictionary <string, string>(ModelData));
                }
            }
            foreach (IDictionary entity in MapEntities)
            {
                MapModels.Add(entity);
            }


            // Done
            return(MapModels);
        }
        private async Task TransferBlocksAsync(GetBlocks getData)
        {
            string identityHex = ByteUtil.Hex(getData.Identity);

            _logger.Verbose(
                "Preparing a {MessageType} message to reply to {Identity}...",
                nameof(Messages.Blocks),
                identityHex
                );

            var blocks = new List <byte[]>();

            List <BlockHash> hashes = getData.BlockHashes.ToList();
            int          i          = 1;
            int          total      = hashes.Count;
            const string logMsg     =
                "Fetching block {Index}/{Total} {Hash} to include in " +
                "a reply to {Identity}...";

            foreach (BlockHash hash in hashes)
            {
                _logger.Verbose(logMsg, i, total, hash, identityHex);
                if (_store.GetBlock <T>(BlockChain.Policy.GetHashAlgorithm, hash) is { } block)
                {
                    byte[] payload = Codec.Encode(block.MarshalBlock());
                    blocks.Add(payload);
                }

                if (blocks.Count == getData.ChunkSize)
                {
                    var response = new Messages.Blocks(blocks)
                    {
                        Identity = getData.Identity,
                    };
                    _logger.Verbose(
                        "Enqueuing a blocks reply (...{Index}/{Total})...",
                        i,
                        total
                        );
                    await Transport.ReplyMessageAsync(response, default);

                    blocks.Clear();
                }

                i++;
            }

            if (blocks.Any())
            {
                var response = new Messages.Blocks(blocks)
                {
                    Identity = getData.Identity,
                };
                _logger.Verbose(
                    "Enqueuing a blocks reply (...{Index}/{Total}) to {Identity}...",
                    total,
                    total,
                    identityHex
                    );
                await Transport.ReplyMessageAsync(response, default);
            }

            _logger.Debug("Blocks were transferred to {Identity}.", identityHex);
        }
Пример #8
0
 internal static Guid ParseChainId(string chainIdString) =>
 new Guid(ByteUtil.ParseHex(chainIdString));
Пример #9
0
 public override void Write(
     Utf8JsonWriter writer, ImmutableArray <byte> value, JsonSerializerOptions options)
 {
     writer.WriteStringValue(ByteUtil.Hex(value));
 }
Пример #10
0
        public async Task CanBroadcastBlock()
        {
            // If the bucket stored peers are the same, the block may not propagate,
            // so specify private keys to make the buckets different.
            var keyA = ByteUtil.ParseHex(
                "8568eb6f287afedece2c7b918471183db0451e1a61535bb0381cfdf95b85df20");
            var keyB = ByteUtil.ParseHex(
                "c34f7498befcc39a14f03b37833f6c7bb78310f1243616524eda70e078b8313c");
            var keyC = ByteUtil.ParseHex(
                "941bc2edfab840d79914d80fe3b30840628ac37a5d812d7f922b5d2405a223d3");

            var swarmA = CreateSwarm(new PrivateKey(keyA));
            var swarmB = CreateSwarm(new PrivateKey(keyB));
            var swarmC = CreateSwarm(new PrivateKey(keyC));

            BlockChain <DumbAction> chainA = swarmA.BlockChain;
            BlockChain <DumbAction> chainB = swarmB.BlockChain;
            BlockChain <DumbAction> chainC = swarmC.BlockChain;

            foreach (int i in Enumerable.Range(0, 10))
            {
                await chainA.MineBlock(swarmA.Address);
            }

            foreach (int i in Enumerable.Range(0, 3))
            {
                await chainB.MineBlock(swarmB.Address);
            }

            try
            {
                await StartAsync(swarmA);
                await StartAsync(swarmB);
                await StartAsync(swarmC);

                await BootstrapAsync(swarmB, swarmA.AsPeer);
                await BootstrapAsync(swarmC, swarmA.AsPeer);

                swarmB.BroadcastBlock(chainB[-1]);

                // chainA ignores block header received because its index is shorter.
                await swarmA.BlockHeaderReceived.WaitAsync();

                await swarmC.BlockAppended.WaitAsync();

                Assert.False(swarmA.BlockAppended.IsSet);

                // chainB doesn't applied to chainA since chainB is shorter
                // than chainA
                Assert.NotEqual(chainB, chainA);

                swarmA.BroadcastBlock(chainA[-1]);

                await swarmB.BlockAppended.WaitAsync();

                await swarmC.BlockAppended.WaitAsync();

                Log.Debug("Compare chainA and chainB");
                Assert.Equal(chainA.BlockHashes, chainB.BlockHashes);
                Log.Debug("Compare chainA and chainC");
                Assert.Equal(chainA.BlockHashes, chainC.BlockHashes);
            }
            finally
            {
                await StopAsync(swarmA);
                await StopAsync(swarmB);
                await StopAsync(swarmC);

                swarmA.Dispose();
                swarmB.Dispose();
                swarmC.Dispose();
            }
        }
Пример #11
0
 public override void Set(IReadOnlyList <string> fields)
 {
     _key     = new PublicKey(ByteUtil.ParseHex(fields[0]));
     RewardId = ParseInt(fields[1]);
 }
Пример #12
0
        public async Task DoNotRebroadcastTxsWithLowerNonce()
        {
            // If the bucket stored peers are the same, the block may not propagate,
            // so specify private keys to make the buckets different.
            var keyA = ByteUtil.ParseHex(
                "8568eb6f287afedece2c7b918471183db0451e1a61535bb0381cfdf95b85df20");
            var keyB = ByteUtil.ParseHex(
                "c34f7498befcc39a14f03b37833f6c7bb78310f1243616524eda70e078b8313c");
            var keyC = ByteUtil.ParseHex(
                "941bc2edfab840d79914d80fe3b30840628ac37a5d812d7f922b5d2405a223d3");

            var minerKey = new PrivateKey(keyB);
            var swarmA   = CreateSwarm(new PrivateKey(keyA));
            var swarmB   = CreateSwarm(minerKey);
            var swarmC   = CreateSwarm(new PrivateKey(keyC));

            BlockChain <DumbAction> chainA = swarmA.BlockChain;
            BlockChain <DumbAction> chainB = swarmB.BlockChain;
            BlockChain <DumbAction> chainC = swarmC.BlockChain;

            var privateKey = new PrivateKey();

            try
            {
                var tx1 = swarmA.BlockChain.MakeTransaction(
                    privateKey: privateKey,
                    actions: new DumbAction[] { });
                var tx2 = swarmA.BlockChain.MakeTransaction(
                    privateKey: privateKey,
                    actions: new DumbAction[] { });
                Assert.Equal(0, tx1.Nonce);
                Assert.Equal(1, tx2.Nonce);
                await StartAsync(swarmA);
                await StartAsync(swarmB);

                await swarmA.AddPeersAsync(new[] { swarmB.AsPeer }, null);

                swarmA.BroadcastTxs(new[] { tx1, tx2 });
                await swarmB.TxReceived.WaitAsync();

                Assert.Equal(
                    new HashSet <TxId> {
                    tx1.Id, tx2.Id
                },
                    chainB.GetStagedTransactionIds().ToHashSet());

                chainA.UnstageTransaction(tx2);
                Assert.Equal(1, chainA.GetNextTxNonce(privateKey.ToAddress()));
                swarmA.RoutingTable.RemovePeer((BoundPeer)swarmB.AsPeer);
                swarmB.RoutingTable.RemovePeer((BoundPeer)swarmA.AsPeer);
                Assert.Empty(swarmA.Peers);
                Assert.Empty(swarmB.Peers);
                await chainB.MineBlock(minerKey.ToAddress());

                var tx3 = chainA.MakeTransaction(
                    privateKey: privateKey,
                    actions: new DumbAction[] { });
                var tx4 = chainA.MakeTransaction(
                    privateKey: privateKey,
                    actions: new DumbAction[] { });
                Assert.Equal(1, tx3.Nonce);
                Assert.Equal(2, tx4.Nonce);

                await StartAsync(swarmC);

                await swarmA.AddPeersAsync(new[] { swarmB.AsPeer }, null);

                await swarmB.AddPeersAsync(new[] { swarmC.AsPeer }, null);

                swarmA.BroadcastTxs(new[] { tx3, tx4 });
                await swarmC.TxReceived.WaitAsync();

                Assert.DoesNotContain(tx3.Id, chainB.GetStagedTransactionIds());
                // SwarmC can not receive tx3 because SwarmB does not rebroadcast it.
                Assert.DoesNotContain(tx3.Id, chainC.GetStagedTransactionIds());
            }
            finally
            {
                await StopAsync(swarmA);
                await StopAsync(swarmB);
                await StopAsync(swarmC);

                swarmA.Dispose();
                swarmB.Dispose();
                swarmC.Dispose();
            }
        }
Пример #13
0
 public void Write(string value)
 {
     ByteUtil.EncodeString(value, out byte[] lengthBytes, out byte[] dataBytes);
     Write(lengthBytes);
     Write(dataBytes);
 }
Пример #14
0
 public override void WriteBytes(object obj, SerializerInputStream serializerInputStream)
 {
     serializerInputStream.Write(RpcSerializerUtil.Byte_TimeSpan);
     serializerInputStream.Write(ByteUtil.EncodeTimeSpan((TimeSpan)obj));
 }
Пример #15
0
        public void Convert_ByteArray_To_ByteString_Should_Succeed(int arraySize)
        {
            var testBytes = ByteUtil.GenerateRandomByteArray(arraySize);

            testBytes.ToByteString().Should().Equal(ByteString.CopyFrom(testBytes));
        }
Пример #16
0
 public byte[] serialize()
 {
     byte[] type = { (byte)Curve.DJB_TYPE };
     return(ByteUtil.combine(type, publicKey));
 }
Пример #17
0
        /// <summary>
        /// Reads BSP Data
        /// </summary>
        public static void ExportBSPData(ProcessReader reader, long assetPoolsAddress, long assetSizesAddress, string gameType, Action <object> printCallback = null)
        {
            // Found her
            printCallback?.Invoke("Found supported game: Call of Duty: Black Ops 2");
            // Validate by XModel Name
            if (reader.ReadNullTerminatedString(reader.ReadInt32(reader.ReadInt32(assetPoolsAddress + 0x14) + 4)) == "defaultvehicle")
            {
                // Load BSP Pools (they only have a size of 1 so we have no free header)
                var gfxMapAsset  = reader.ReadStruct <GfxMap>(reader.ReadInt32(assetPoolsAddress + 4 * 0x11));
                var mapEntsAsset = reader.ReadStruct <MapEntsMW2>(reader.ReadInt32(assetPoolsAddress + 4 * 0x10));

                // Name
                string gfxMapName = reader.ReadNullTerminatedString(gfxMapAsset.NamePointer);
                string mapEnt     = reader.ReadNullTerminatedString(mapEntsAsset.MapData);
                string mapName    = reader.ReadNullTerminatedString(gfxMapAsset.MapNamePointer);

                // Verify a BSP is actually loaded (if in base menu, etc, no map is loaded)
                if (String.IsNullOrWhiteSpace(gfxMapName))
                {
                    printCallback?.Invoke("No BSP loaded. Enter Main Menu or a Map to load in the required assets.");
                }
                else
                {
                    // New IW Map
                    var mapFile = new IWMap();
                    // Print Info
                    printCallback?.Invoke(String.Format("Loaded Gfx Map     -   {0}", gfxMapName));
                    printCallback?.Invoke(String.Format("Loaded Map         -   {0}", mapName));
                    printCallback?.Invoke(String.Format("Vertex Count       -   {0}", gfxMapAsset.GfxVertexCount));
                    printCallback?.Invoke(String.Format("Indices Count      -   {0}", gfxMapAsset.GfxIndicesCount));
                    printCallback?.Invoke(String.Format("Surface Count      -   {0}", gfxMapAsset.SurfaceCount));
                    printCallback?.Invoke(String.Format("Model Count        -   {0}", gfxMapAsset.GfxStaticModelsCount));

                    // Build output Folder
                    string outputName = Path.Combine("exported_maps", "black_ops_2", gameType, mapName, mapName);
                    Directory.CreateDirectory(Path.GetDirectoryName(outputName));

                    // Stop watch
                    var stopWatch = Stopwatch.StartNew();

                    // Read Vertices
                    printCallback?.Invoke("Parsing vertex data....");
                    var vertexBuffer = reader.ReadBytes(gfxMapAsset.GfxVerticesPointer, gfxMapAsset.GfxVertexBufferSize);
                    printCallback?.Invoke(String.Format("Parsed vertex data in {0:0.00} seconds.", stopWatch.ElapsedMilliseconds / 1000.0));

                    // Reset timer
                    stopWatch.Restart();

                    // Read Indices
                    printCallback?.Invoke("Parsing surface indices....");
                    var indices = ReadGfxIndices(reader, gfxMapAsset.GfxIndicesPointer, gfxMapAsset.GfxIndicesCount);
                    printCallback?.Invoke(String.Format("Parsed indices in {0:0.00} seconds.", stopWatch.ElapsedMilliseconds / 1000.0));

                    // Reset timer
                    stopWatch.Restart();

                    // Read Indices
                    printCallback?.Invoke("Parsing surfaces....");
                    var surfaces = ReadGfxSufaces(reader, gfxMapAsset.GfxSurfacesPointer, gfxMapAsset.SurfaceCount);
                    printCallback?.Invoke(String.Format("Parsed surfaces in {0:0.00} seconds.", stopWatch.ElapsedMilliseconds / 1000.0));

                    // Reset timer
                    stopWatch.Restart();

                    // Write OBJ
                    printCallback?.Invoke("Generating map files...");

                    // Create new OBJ
                    var obj = new WavefrontOBJ();

                    // Image Names (for Search String)
                    HashSet <string> imageNames = new HashSet <string>();

                    // Vertex Index Tracker
                    int vertexIndex = 0;

                    // Append Faces
                    foreach (var surface in surfaces)
                    {
                        // Create new Material
                        var material    = ReadMaterial(reader, surface.MaterialPointer);
                        var lutMaterial = ReadMaterial(reader, gfxMapAsset.LutMaterial);

                        // Add to images
                        imageNames.Add(material.DiffuseMap);
                        imageNames.Add(material.NormalMap);
                        imageNames.Add(material.SpecularMap);
                        imageNames.Add(lutMaterial.Lut);

                        // Add it
                        obj.AddMaterial(material);

                        // Add points
                        for (ushort i = 0; i < surface.FaceCount; i++)
                        {
                            // Face Indices
                            var faceIndex1 = indices[i * 3 + surface.FaceIndex];
                            var faceIndex2 = indices[i * 3 + surface.FaceIndex + 1];
                            var faceIndex3 = indices[i * 3 + surface.FaceIndex + 2];

                            // Validate unique points, and write to OBJ
                            if (faceIndex1 != faceIndex2 && faceIndex1 != faceIndex3 && faceIndex2 != faceIndex3)
                            {
                                // new Obj Face
                                var objFace = new WavefrontOBJ.Face(material.Name);

                                // Unpack vertices
                                var vertex1 = UnpackVertex(ByteUtil.BytesToStruct <GfxVertex>(vertexBuffer, surface.VertexBufferOffset + (faceIndex1 * 36)));
                                var vertex2 = UnpackVertex(ByteUtil.BytesToStruct <GfxVertex>(vertexBuffer, surface.VertexBufferOffset + (faceIndex2 * 36)));
                                var vertex3 = UnpackVertex(ByteUtil.BytesToStruct <GfxVertex>(vertexBuffer, surface.VertexBufferOffset + (faceIndex3 * 36)));

                                // Add Offsets
                                obj.Vertices.Add(vertex1.Position);
                                obj.Vertices.Add(vertex2.Position);
                                obj.Vertices.Add(vertex3.Position);

                                // Add Normals
                                obj.Normals.Add(vertex1.Normal);
                                obj.Normals.Add(vertex2.Normal);
                                obj.Normals.Add(vertex3.Normal);

                                // Add UVs
                                obj.UVs.Add(vertex1.UV);
                                obj.UVs.Add(vertex2.UV);
                                obj.UVs.Add(vertex3.UV);

                                // Add points
                                objFace.Vertices[0] = new WavefrontOBJ.Face.Vertex(vertexIndex, vertexIndex, vertexIndex);
                                objFace.Vertices[2] = new WavefrontOBJ.Face.Vertex(vertexIndex + 1, vertexIndex + 1, vertexIndex + 1);
                                objFace.Vertices[1] = new WavefrontOBJ.Face.Vertex(vertexIndex + 2, vertexIndex + 2, vertexIndex + 2);

                                // Add to OBJ
                                obj.Faces.Add(objFace);

                                vertexIndex += 3;
                            }
                        }
                    }

                    // Save it
                    obj.Save(outputName + ".obj");

                    // Build search strinmg
                    string searchString = "";

                    // Loop through images, and append each to the search string (for Wraith/Greyhound)
                    // NO NEED FOR IMAGE SEARCH STRING IN COD4
                    foreach (string imageName in imageNames)
                    {
                        searchString += String.Format("{0},", Path.GetFileNameWithoutExtension(imageName));
                    }

                    // Get dynamic models from Map Entities
                    List <IDictionary> MapEntities = CreateMapEntities(mapEnt, printCallback);

                    // Create .JSON with XModel Data
                    List <IDictionary> ModelData  = CreateXModelDictionary(reader, gfxMapAsset.GfxStaticModelsPointer, (int)gfxMapAsset.GfxStaticModelsCount, MapEntities);
                    string             xmodeljson = JToken.FromObject(ModelData).ToString(Formatting.Indented);
                    File.WriteAllText(outputName + "_xmodels.json", xmodeljson);

                    // Loop through xmodels, and append each to the search string (for Wraith/Greyhound)
                    List <string> xmodelList = CreateXModelList(ModelData);

                    // Create .JSON with World settings
                    Dictionary <string, string> world_settings = ParseWorldSettings(mapEnt);
                    string worldsettingsjson = JToken.FromObject(world_settings).ToString(Formatting.Indented);
                    File.WriteAllText(outputName + "_worldsettings.json", worldsettingsjson);


                    // Dump it
                    File.WriteAllText(outputName + "_search_string.txt", searchString);
                    File.WriteAllText(outputName + "_mapEnts.txt", mapEnt);
                    File.WriteAllText(outputName + "_xmodelList.txt", String.Join(",", xmodelList.ToArray()));

                    // Read entities and dump to map
                    mapFile.Entities.AddRange(ReadStaticModels(reader, gfxMapAsset.GfxStaticModelsPointer, (int)gfxMapAsset.GfxStaticModelsCount));
                    mapFile.DumpToMap(outputName + ".map");

                    // Done
                    printCallback?.Invoke(String.Format("Generated files in {0:0.00} seconds.", stopWatch.ElapsedMilliseconds / 1000.0));
                }
            }
            else
            {
                printCallback?.Invoke("Call of Duty: Black Ops 2 is supported, but this EXE is not.");
            }
        }
Пример #18
0
 public virtual void OnExists(Key key, bool exists)
 {
     parent.console.Info("Record: namespace={0} set={1} key={2} exists={3}",
                         key.ns, key.setName, ByteUtil.BytesToHexString(key.digest), exists);
 }
Пример #19
0
 public static bool isLegacy(byte[] message)
 {
     return(message != null && message.Length >= 1 &&
            ByteUtil.highBitsToInt(message[0]) <= UNSUPPORTED_VERSION);
 }
Пример #20
0
 public EthECKey(byte[] vch, bool isPrivate, byte prefix)
 {
     _ecKey = new ECKey(ByteUtil.Merge(new[] { prefix }, vch), isPrivate);
 }
Пример #21
0
        /* Test the code by comparing it against a known-good test vector. */
        public static void SelfCheck()
        {
            uint testFrame = 0x134;

            byte[] testKey  = new byte[] { 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x12 };
            bool[] goodAtoB = ByteUtil.BitsFromBytes(new byte[] { 0x53, 0x4E, 0xAA, 0x58, 0x2F, 0xE8, 0x15, 0x1A, 0xB6, 0xE1, 0x85, 0x5A, 0x72, 0x8C, 0x00 });
            bool[] goodBtoA = ByteUtil.BitsFromBytes(new byte[] { 0x24, 0xFD, 0x35, 0xA3, 0x5D, 0x5F, 0xB6, 0x52, 0x6D, 0x32, 0xF9, 0x06, 0xDF, 0x1A, 0xC0 });
            int    i        = 0;
            bool   failed   = false;

            CryptA5 a5 = new CryptA5();

            a5.Key   = testKey;
            a5.Count = testFrame;
            a5.RunAlgo();

            /* Compare against the test vector. */
            for (i = 0; i < 114; i++)
            {
                if (a5.DownlinkKey[i] != goodAtoB[i])
                {
                    failed = true;
                }
            }
            for (i = 0; i < 114; i++)
            {
                if (a5.UplinkKey[i] != goodBtoA[i])
                {
                    failed = true;
                }
            }

            if (failed)
            {
                /* Problems!  The test vectors didn't compare*/
                StringBuilder builder = new StringBuilder();

                /* Print some debugging output. */
                builder.Append("key: 0x");
                for (i = 0; i < 8; i++)
                {
                    builder.AppendFormat("{0:X02}", testKey[i]);
                }
                builder.Append("\r\n");
                builder.AppendFormat("frame number: 0x{0:X6}\r\n", (uint)testFrame);
                builder.Append("known good output:\r\n");
                builder.Append(" A->B: ");
                for (i = 0; i < 114; i++)
                {
                    builder.Append(goodAtoB[i] ? 1 : 0);
                }
                builder.Append("  B->A: ");
                for (i = 0; i < 114; i++)
                {
                    builder.Append(goodBtoA[i] ? 1 : 0);
                }
                builder.Append("\r\n");
                builder.Append("observed output:\r\n");
                builder.Append(" A->B: ");
                for (i = 0; i < 114; i++)
                {
                    builder.Append(a5.DownlinkKey[i] ? 1 : 0);
                }
                builder.Append("  B->A: ");
                for (i = 0; i < 114; i++)
                {
                    builder.Append(a5.UplinkKey[i] ? 1 : 0);
                }
                builder.Append("\r\n");

                builder.Append("\r\nI don't know why this broke; contact the authors.\r\n");
                Log.AddMessage(builder.ToString());
            }
        }
Пример #22
0
        public (SignalProtocolAddress, byte[]) Decrypt(CertificateValidator validator, byte[] ciphertext, long timestamp)
        {
            UnidentifiedSenderMessageContent content;

            try
            {
                IdentityKeyPair           ourIdentity = SignalProtocolStore.GetIdentityKeyPair();
                UnidentifiedSenderMessage wrapper     = new UnidentifiedSenderMessage(ciphertext);
                byte[]        ephemeralSalt           = ByteUtil.combine(Encoding.ASCII.GetBytes("UnidentifiedDelivery"), ourIdentity.getPublicKey().getPublicKey().serialize(), wrapper.Ephemeral.serialize());
                EphemeralKeys ephemeralKeys           = CalculateEphemeralKeys(wrapper.Ephemeral, ourIdentity.getPrivateKey(), ephemeralSalt);
                byte[]        staticKeyBytes          = Decrypt(ephemeralKeys.CipherKey, ephemeralKeys.MacKey, wrapper.EncryptedStatic);

                ECPublicKey staticKey    = Curve.decodePoint(staticKeyBytes, 0);
                byte[]      staticSalt   = ByteUtil.combine(ephemeralKeys.ChainKey, wrapper.EncryptedStatic);
                StaticKeys  staticKeys   = CalculateStaticKeys(staticKey, ourIdentity.getPrivateKey(), staticSalt);
                byte[]      messageBytes = Decrypt(staticKeys.CipherKey, staticKeys.MacKey, wrapper.EncryptedMessage);

                content = new UnidentifiedSenderMessageContent(messageBytes);
                validator.Validate(content.SenderCertificate, timestamp);

                if (!Enumerable.SequenceEqual(content.SenderCertificate.Key.serialize(), staticKeyBytes))
                {
                    throw new libsignal.InvalidKeyException("Sender's certificate key does not match key used in message");
                }

                if (content.SenderCertificate.Sender == LocalAddress.Name &&
                    content.SenderCertificate.SenderDeviceId == LocalAddress.DeviceId)
                {
                    throw new SelfSendException();
                }
            }
            catch (libsignal.InvalidKeyException e)
            {
                throw new InvalidMetadataMessageException(e);
            }
            catch (InvalidCertificateException e)
            {
                throw new InvalidMetadataMessageException(e);
            }
            catch (InvalidMacException e)
            {
                throw new InvalidMetadataMessageException(e);
            }

            try
            {
                return(new SignalProtocolAddress(content.SenderCertificate.Sender, (uint)content.SenderCertificate.SenderDeviceId),
                       Decrypt(content));
            }
            catch (InvalidMessageException e)
            {
                throw new ProtocolInvalidMessageException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
            catch (libsignal.InvalidKeyException e)
            {
                throw new ProtocolInvalidKeyException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
            catch (NoSessionException e)
            {
                throw new ProtocolNoSessionException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
            catch (LegacyMessageException e)
            {
                throw new ProtocolLegacyMessageException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
            catch (InvalidVersionException e)
            {
                throw new ProtocolInvalidVersionException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
            catch (DuplicateMessageException e)
            {
                throw new ProtocolDuplicateMessageException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
            catch (InvalidKeyIdException e)
            {
                throw new ProtocolInvalidKeyIdException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
            catch (UntrustedIdentityException e)
            {
                throw new ProtocolUntrustedIdentityException(e, content.SenderCertificate.Sender, content.SenderCertificate.SenderDeviceId);
            }
        }
Пример #23
0
    /// <summary>
    /// 接收远程主机发送的数据
    /// </summary>
    /// <param name="socket">要接收数据且已经连接到远程主机的</param>
    /// <param name="buffer">接收数据的缓冲区(需要接收的数据的长度,由 buffer 的长度决定)</param>
    /// <param name="outTime">接收数据的超时时间,单位秒(指定为-1时,将一直等待直到有数据需要接收)</param>
    /// <returns>0:接收成功;-1:超时;-2:出现错误;-3:出现异常</returns>
    public int recvData(Socket socket, int outTime)
    {
        if (!isConnect)
        {
            Debug.Log("==============Network Disconnect");
            return(-3);
        }

        byteBuffer.Initialize();
        int left    = byteBuffer.Length;
        int curRecv = 0;
        int hasRecv = 0;
        int length  = 0;

        try
        {
            while (true)
            {
                //MonoBehaviour.print("<color=red>socket.Connected=</color>" + socket.Connected);
                if (socket.Poll(outTime * 1000000, SelectMode.SelectRead) == true)
                {
                    //MonoBehaviour.print("<color=red>socket.Receive</color>");
                    curRecv = socket.Receive(byteBuffer, hasRecv, left, SocketFlags.None);
                    Debug.Log("=======socket.Receive " + curRecv + " " + hasRecv + " " + left);
                    // string str = "";
                    // for(int i = 0; i < curRecv; i++)
                    //     str += byteBuffer[i] + " ";
                    // Debug.Log("============socket.Receive Bytes " + str);

                    if (curRecv == 0)
                    {
                        //DebugUtil.log("接收数据出现错误,receive的字节长度为0!");
                        //GameApp.dataCache.errorData.SERVER_ERROR = eServerError.ERROR_EXCEPTION;
                        //throw new ArgumentException("接收数据出现错误,receive的字节长度为0!");
                        Debug.Log("==============recvData curRecv==0");
                        throw new ArgumentException("recvData curRecv==0");
                    }
                    left    -= curRecv;
                    hasRecv += curRecv;

                    int     dataLength = 0;
                    Boolean breakBol   = false;
                    do
                    {
                        byte[] intByte = new byte[] { byteBuffer[length], byteBuffer[length + 1], byteBuffer[length + 2], byteBuffer[length + 3] };
                        dataLength = ByteUtil.getInt(intByte, false);

                        Debug.Log("====receive do " + hasRecv + " " + length + " " + dataLength);

                        if ((length + dataLength + 4) <= hasRecv)
                        {
                            byte[] rContent = new byte[dataLength];

                            for (int i = 0; i < dataLength; i++)
                            {
                                //rContent[i] = _buffer[length + 9 + i];
                                rContent[i] = byteBuffer[length + 4 + i];
                            }

                            length += 4;
                            length += dataLength;


                            OnReceive(rContent, dataLength);

                            // receiveCallback(rContent, 0, 0);


                            if (length == hasRecv)
                            {
                                return(0);
                            }
                        }
                        else
                        {
                            Debug.Log("==========Need Join Pack");
                            breakBol = true;
                        }
                    } while (length < hasRecv && !breakBol);
                }
                // else
                // {
                //     Debug.Log("=========Socket Timeout");
                //     Close();
                //     return -3;
                // }
            }
        }
        catch (Exception err)
        {
            //GameApp.dataCache.errorData.SERVER_ERROR = eServerError.ERROR_EXCEPTION;
            //添加异常消息
            // addExceptionMsg(ECNLocalization.Get("网络连接异常,请检查您的网络!"));
            Debug.Log("========SocketClient error: " + err.Message);
            AddExceptionMsg("Connect failed! recvData");
        }
        return(-1);
    }
Пример #24
0
 private UPath DataPath(byte[] key)
 {
     return(UPath.Root / ByteUtil.Hex(key));
 }
Пример #25
0
        /// <summary>
        /// 启动连续地址电机,如加样器Y轴,距离地址连续,启动地址连续,反馈信号地址连续
        /// </summary>
        /// <param name="motors"></param>
        /// <param name="Distances">为负值时,不会应用校正因子</param>
        /// <param name="gap"></param>
        /// <param name="Comm"></param>
        /// <returns></returns>
        public static bool MoveMotors(Electromotor[] motors, decimal[] Distances, decimal[] gap, AbstractComm Comm, bool OnlyStart, bool PauseScan = true, bool IsInjectorY = false, bool IsInitInjectorY = false)
        {
            Constants.PauseResetEvent.WaitOne();
            if (Constants.UserAbort)
            {
                return(false);
            }
            var len = motors.Length;

            byte[] dis = new byte[len * 4];
            for (byte b = 0; b < len; b++)
            {
                var realdis = motors[b].GetRealDistance(Distances[b], gap == null?0m:gap[b]);
                if (motors[b].CurrentDistance == realdis)
                {
                    return(true);
                }
                else
                {
                    motors[b].CurrentDistance = realdis < 0?0: realdis;
                    Distances[b] = realdis;
                    var val  = Convert.ToInt32(realdis < 0? realdis:(realdis * Convert.ToDecimal(motors[b].Factor.SetValue)));
                    var bval = ByteUtil.Int4ToBytes(val);
                    Array.Copy(bval, 0, dis, 4 * b, 4);
                }
            }
            var result = true;

            if (PauseScan)
            {
                Comm.ScanRestEvent.Reset();
            }
            //关闭完成信号
            result = result && Comm.SetBatchCoil(motors[0].DoneCoil.Addr, (short)len, 0x00);

            result = result && Comm.SetBatchRegister(Comm.ConvertFatekAddrToModbusAddr(motors[0].Distance.Addr.Substring(1)), (short)(len * 2), dis);
            if (IsInjectorY)
            {
                result = result && Comm.SetCoilOn("M99");
                if (IsInitInjectorY)
                {
                    for (byte b = 0; b < Distances.Length; b++)
                    {
                        if (Distances[b] == 0)
                        {
                            Comm.SetCoilOn(motors[b].DoneCoil.Addr);//开启反馈信号
                        }
                    }
                }
            }
            else
            {
                result = result && StartMotor(motors, Comm, true, false);
            }
            if (PauseScan)
            {
                Comm.ScanRestEvent.Set();
            }
            if (!OnlyStart)
            {
                result = result && Comm.Doned(30000, true, motors.Select(item => item.DoneCoil.Addr).ToArray());
            }
            return(result);
        }
Пример #26
0
        public void Capabilities()
        {
            var none = Secp256K1.WithCaps(ContextFlag.None);
            var sign = Secp256K1.WithCaps(ContextFlag.SignOnly);
            var vrfy = Secp256K1.WithCaps(ContextFlag.VerifyOnly);
            var full = Secp256K1.WithCaps(ContextFlag.Full);

            var msgBytes = ByteUtil.Get_bytes(0, 32);
            var msg      = Message.from_slice(msgBytes);
            var rng      = RandomNumberGenerator.Create();

            // Try key generation
            var ex = Assert.Throws <Exception>(() => { none.generate_keypair(rng); });

            Assert.Equal("IncapableContext", ex.Message);
            ex = Assert.Throws <Exception>(() => { vrfy.generate_keypair(rng); });
            Assert.Equal("IncapableContext", ex.Message);

            sign.generate_keypair(rng);

            var fullKp = full.generate_keypair(rng);
            var sk     = fullKp.secretKey;
            var pk     = fullKp.publicKey;

            // Try signing
            ex = Assert.Throws <Exception>(() => { none.Sign(msg, sk); });
            Assert.Equal("IncapableContext", ex.Message);
            ex = Assert.Throws <Exception>(() => { vrfy.Sign(msg, sk); });
            Assert.Equal("IncapableContext", ex.Message);

            var ss = sign.Sign(msg, sk);
            var fs = full.Sign(msg, sk);

            Assert.Equal(ss.Value, fs.Value);

            ex = Assert.Throws <Exception>(() => { none.sign_recoverable(msg, sk); });
            Assert.Equal("IncapableContext", ex.Message);
            ex = Assert.Throws <Exception>(() => { vrfy.sign_recoverable(msg, sk); });
            Assert.Equal("IncapableContext", ex.Message);

            var srs = sign.sign_recoverable(msg, sk);
            var fsr = full.sign_recoverable(msg, sk);

            Assert.Equal(srs.Value, fsr.Value);

            var sig  = full.Sign(msg, sk);
            var sigr = full.sign_recoverable(msg, sk);

            // Try verifying
            ex = Assert.Throws <Exception>(() => { none.Verify(msg, sig, pk); });
            Assert.Equal("IncapableContext", ex.Message);
            ex = Assert.Throws <Exception>(() => { sign.Verify(msg, sig, pk); });
            Assert.Equal("IncapableContext", ex.Message);

            vrfy.Verify(msg, sig, pk);
            full.Verify(msg, sig, pk);

            // Try pk recovery
            ex = Assert.Throws <Exception>(() => { none.Recover(msg, sigr); });
            Assert.Equal("IncapableContext", ex.Message);
            ex = Assert.Throws <Exception>(() => { sign.Recover(msg, sigr); });
            Assert.Equal("IncapableContext", ex.Message);

            var vrc = vrfy.Recover(msg, sigr);
            var frc = full.Recover(msg, sigr);

            Assert.Equal(vrc.Value, frc.Value);
            Assert.Equal(frc.Value, pk.Value);

            // Check that we can produce keys from slices with no precomputation
            var pkSlice = pk.serialize_vec(none, false);
            var skSlice = sk.Value;
            var newPk   = PublicKey.from_slice(none, pkSlice);
            var newSk   = SecretKey.From_slice(none, skSlice);

            Assert.Equal(sk.Value, newSk.Value);
            Assert.Equal(pk.Value, newPk.Value);

            none.Dispose();
            sign.Dispose();
            vrfy.Dispose();
            full.Dispose();
        }
Пример #27
0
 public App QQ()
 {
     return(new App
     {
         Name = "QQ",
         FileTargetInfos = new Dictionary <string, TargetInfo>
         {
             {
                 "IM.dll",
                 new TargetInfo
                 {
                     Name = "IM.dll",
                     RelativePath = @"Bin\IM.dll"
                 }
             }
         },
         FileCommonModifyInfos = new Dictionary <string, List <CommonModifyInfo> >
         {
             {
                 "IM.dll",
                 new List <CommonModifyInfo>
                 {
                     new CommonModifyInfo
                     {
                         Name = "IM.dll",
                         StartVersion = "9.1.6.00000",
                         EndVersion = "",
                         ReplacePatterns = new List <ReplacePattern>
                         {
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 E8 8D 55 EC 52 89 5D EC 68 3F 3F 3F 54 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Replace = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 E8 8D 55 EC 52 89 5D EC EB 09 90 90 90 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Category = "防撤回"
                             },
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 F0 8D 55 EC 52 89 5D EC 68 3F 3F 3F 54 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Replace = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 F0 8D 55 EC 52 89 5D EC EB 09 90 90 90 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Category = "防撤回"
                             },
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("8B 75 14 8D 4D F4 83 C4 20 33 FF 89 7D F4 8B 06 51 68 3F 3F 3F 54 56 FF 50 78 85 C0 79 39 8D 45 0C C7 45 0C"),
                                 Replace = ByteUtil.HexStringToByteArray("8B 75 14 8D 4D F4 83 C4 20 33 FF 89 7D F4 8B 06 EB 08 90 90 90 90 56 FF 50 78 85 C0 79 39 8D 45 0C C7 45 0C"),
                                 Category = "防撤回"
                             }
                         }
                     }
                 }
             }
         },
         FileModifyInfos = new Dictionary <string, List <ModifyInfo> >
         {
             {
                 "IM.dll",
                 new List <ModifyInfo>
                 {
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.2.3.26592",
                         SHA1Before = "9114e7869572b4b868afcbc8b28eae932559ec60",
                         SHA1After = "42e15175fd53768bb48772dc69fb07a4eac5a623",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x0005AB95,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005ADB2,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005AF60,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.2.2.26569",
                         SHA1Before = "434254e76c520789558e075af677821258536311",
                         SHA1After = "237c9e489a97858a175f0f7c72ade4ebcbac7a69",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x0005A9CA,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005ABE7,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005AD95,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.2.1.26546",
                         SHA1Before = "8d8ea2c2cbf43f5acf8d684b153e90035352d5f5",
                         SHA1After = "7d194dd5be03982b533d7375c93d9a72587fe28d",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x0005A389,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005A5A6,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005A754,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.2.0.26453",
                         SHA1Before = "c1935ca6347b0c2a7e6108a7f8ee0643d39deb66",
                         SHA1After = "42811188a7e7b346a6a3c1066936b98c747acaf6",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x00056602,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005681F,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x000569CF,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.2.0.26389",
                         SHA1Before = "6f8855fb80acfa456f8f69989fe949308fe4d154",
                         SHA1After = "f6b8e05a178b9b10ba17c597fa0a44b7a2a966a8",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x000571C8,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x000573E5,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x00057595,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.1.9.26361",
                         SHA1Before = "022d3433d13d07a354c38816f61cb0b7ac60d3fd",
                         SHA1After = "873a57c1fb51cdd099c8cb7108b5ab5cb4459557",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x000567DE,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x000569FB,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x00056BAB,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.1.9.26346",
                         SHA1Before = "895eb70f707b8222e6460c91492b1281e525059b",
                         SHA1After = "0bb83990e2b5b5f23b7b43249941ff638201af54",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x000567DE,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x000569FB,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x00056BAB,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.1.8.26211",
                         SHA1Before = "a950d3cf5e8925f7775624271105ef78d9c5cb57",
                         SHA1After = "dffc1cb87b91e6467e13c935611f2f7fd76b9a8d",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x000524EF,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005270C,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x000528BC,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.1.7.25980",
                         SHA1Before = "c6632339fbe675312a70ae4620e70699c258cd36",
                         SHA1After = "e9ddc5cc681950796fc8fe4c55f580428c890b51",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x0005009F,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x000502BC,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0005046C,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     },
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "9.0.4.23786",
                         SHA1Before = "69a714f4eadb09f1453f6f022d4adbcd801cfab8",
                         SHA1After = "b48e77a924076b3ebdffc4af514c868c551d2bca",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x0004DB71,
                                 Content = new byte[] { 0xEB, 0x07, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0004DD8E,
                                 Content = new byte[] { 0xEB, 0x07, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0004DF93,
                                 Content = new byte[] { 0xEB, 0x07, 0x90, 0x90, 0x90 }
                             }
                         }
                     }
                 }
             }
         }
     });
 }
Пример #28
0
        public byte[] EncodeAbiTypes(ABIType[] abiTypes, params object[] values)
        {
            if ((values == null) && (abiTypes.Length > 0))
            {
                throw new ArgumentNullException(nameof(values), "No values specified for encoding");
            }

            if (values == null)
            {
                return new byte[] { }
            }
            ;

            if (values.Length > abiTypes.Length)
            {
                throw new Exception("Too many arguments: " + values.Length + " > " + abiTypes.Length);
            }

            var staticSize   = 0;
            var dynamicCount = 0;

            // calculating static size and number of dynamic params
            for (var i = 0; i < values.Length; i++)
            {
                var abiType       = abiTypes[i];
                var parameterSize = abiType.FixedSize;
                if (parameterSize < 0)
                {
                    dynamicCount++;
                    staticSize += 32;
                }
                else
                {
                    staticSize += parameterSize;
                }
            }

            var encodedBytes = new byte[values.Length + dynamicCount][];

            var currentDynamicPointer = staticSize;
            var currentDynamicCount   = 0;

            for (var i = 0; i < values.Length; i++)
            {
                var abiType = abiTypes[i];
                if (abiType.IsDynamic())
                {
                    var dynamicValueBytes = abiType.Encode(values[i]);

                    encodedBytes[i] = intTypeEncoder.EncodeInt(currentDynamicPointer);
                    encodedBytes[values.Length + currentDynamicCount] = dynamicValueBytes;
                    currentDynamicCount++;
                    currentDynamicPointer += dynamicValueBytes.Length;
                }
                else
                {
                    try
                    {
                        encodedBytes[i] = abiType.Encode(values[i]);
                    }
                    catch (Exception ex)
                    {
                        throw new AbiEncodingException(i, abiType, values[i],
                                                       $"An error occurred encoding abi value. Order: '{i + 1}', Type: '{abiType.Name}', Value: '{values[i] ?? "null"}'.  Ensure the value is valid for the abi type.",
                                                       ex);
                    }
                }
            }
            return(ByteUtil.Merge(encodedBytes));
        }
Пример #29
0
 public App TIM()
 {
     return(new App
     {
         Name = "TIM",
         FileTargetInfos = new Dictionary <string, TargetInfo>
         {
             {
                 "IM.dll",
                 new TargetInfo
                 {
                     Name = "IM.dll",
                     RelativePath = @"Bin\IM.dll"
                 }
             }
         },
         FileCommonModifyInfos = new Dictionary <string, List <CommonModifyInfo> >
         {
             {
                 "IM.dll",
                 new List <CommonModifyInfo>
                 {
                     new CommonModifyInfo
                     {
                         Name = "IM.dll",
                         StartVersion = "3.0.0.00000",
                         EndVersion = "",
                         ReplacePatterns = new List <ReplacePattern>
                         {
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 E8 8D 55 EC 52 89 5D EC 68 3F 3F 3F 54 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Replace = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 E8 8D 55 EC 52 89 5D EC EB 09 90 90 90 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Category = "防撤回"
                             },
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 F0 8D 55 EC 52 89 5D EC 68 3F 3F 3F 54 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Replace = ByteUtil.HexStringToByteArray("1C E9 9D 00 00 00 8B 45 F0 8D 55 EC 52 89 5D EC EB 09 90 90 90 8B 08 50 FF 51 78 85 C0 79 2D 8D 45 0C C7 45 0C"),
                                 Category = "防撤回"
                             },
                             new ReplacePattern
                             {
                                 Search = ByteUtil.HexStringToByteArray("8B 75 14 8D 4D F4 83 C4 20 33 FF 89 7D F4 8B 06 51 68 3F 3F 3F 54 56 FF 50 78 85 C0 79 39 8D 45 0C C7 45 0C"),
                                 Replace = ByteUtil.HexStringToByteArray("8B 75 14 8D 4D F4 83 C4 20 33 FF 89 7D F4 8B 06 EB 08 90 90 90 90 56 FF 50 78 85 C0 79 39 8D 45 0C C7 45 0C"),
                                 Category = "防撤回"
                             }
                         }
                     }
                 }
             }
         },
         FileModifyInfos = new Dictionary <string, List <ModifyInfo> >
         {
             {
                 "IM.dll",
                 new List <ModifyInfo>
                 {
                     new ModifyInfo
                     {
                         Name = "IM.dll",
                         Version = "2.3.2.21173",
                         SHA1Before = "ecf3e69f3fb100ffe2fee095ffded591b9781024",
                         SHA1After = "0514d1304e7ac46b4d33386ec3313888f5ae7171",
                         Changes = new List <Change>
                         {
                             new Change
                             {
                                 Position = 0x0004D78A,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0004D9A7,
                                 Content = new byte[] { 0xEB, 0x09, 0x90, 0x90, 0x90 }
                             },
                             new Change
                             {
                                 Position = 0x0004DB57,
                                 Content = new byte[] { 0xEB, 0x08, 0x90, 0x90, 0x90, 0x90 }
                             }
                         }
                     }
                 }
             }
         }
     });
 }
Пример #30
0
            //根据字节数组转成modbus响应上来的对象
            public static ModbusRTUResponse FromBytes(byte[] bytes, out string errMsg)
            {
                errMsg = "";
                try
                {
                    switch (bytes[1])
                    {
                    case 0x03:
                    {
                        if (bytes.Length != 7)
                        {
                            return(null);
                        }
                        //读寄存器回应
                        ModbusRTUResponse response = new ModbusRTUResponse();
                        response.PlcAddress = bytes[0];
                        response.Type       = ResponseType.Read;
                        // 含义:寄存器的个数*2
                        response.DataLength = bytes[2];
                        response.Values     = ByteUtil.ToUshorts(bytes, 3, response.DataLength);
                        response.CRC        = BitConverter.ToUInt16(bytes, 5);   // CRC 无需反转高低位
                        if (response.DataLength == 0x02)
                        {
                            // 针对单个寄存器
                            response.RegisterValue = response.Values[0];
                            response.RegisterCount = 0x01;
                        }
                        return(response);
                    }

                    case 0x10:
                    {
                        if (bytes.Length != 8)
                        {
                            return(null);
                        }
                        // 目前只有单个寄存器写入
                        ModbusRTUResponse response = new ModbusRTUResponse();
                        response.PlcAddress           = bytes[0];
                        response.Type                 = ResponseType.Write;
                        response.RegisterBeginAddress = ByteUtil.ToUshort(bytes, 2);
                        response.RegisterValue        = ByteUtil.ToUshort(bytes, 4);
                        response.CRC = BitConverter.ToUInt16(bytes, 6);          // CRC 无需反转高低位
                        return(response);
                    }

                    case 0x83:
                    {
                        if (bytes.Length != 5)
                        {
                            return(null);
                        }
                        // 读单个寄存器请求出错
                        ModbusRTUResponse response = new ModbusRTUResponse();
                        response.PlcAddress = bytes[0];
                        response.Type       = ResponseType.ReadError;
                        response.errMsg     = "读寄存器请求出错--" + GetErrMSg(bytes[2]);
                        response.CRC        = BitConverter.ToUInt16(bytes, 3);   // CRC 无需反转高低位
                        return(response);
                    }

                    case 0x86:
                    {
                        if (bytes.Length != 5)
                        {
                            return(null);
                        }
                        // 写单个寄存器请求出错
                        ModbusRTUResponse response = new ModbusRTUResponse();
                        response.PlcAddress = bytes[0];
                        response.Type       = ResponseType.WriteError;
                        response.errMsg     = "写寄存器请求出错--" + GetErrMSg(bytes[2]);
                        response.CRC        = BitConverter.ToUInt16(bytes, 3);   // CRC 无需反转高低位
                        return(response);
                    }
                    }
                }
                catch (Exception e)
                {
                    errMsg = e.Message;
                    return(null);
                }
                errMsg = "字节数组转modbus回应对象出现未知的功能码";
                return(null);
            }