Decompiled source of MidgardVanillaDeepNorth v1.0.4

BepInEx/patchers/MidgardSpeedItUpPicard.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Preloader;
using HarmonyLib;
using HarmonyLib.Public.Patching;
using Microsoft.CodeAnalysis;
using MidgardAntiCheat;
using Mono.Cecil;
using Mono.Cecil.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("MidgardSpeedItUpPicard")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MidgardSpeedItUpPicard")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("970A588D-9A2E-4CCF-B66B-397AEAD75715")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MidgardSpeedItUpPicard
{
	public static class MidgardSpeedItUpPicard
	{
		private enum Toggle
		{
			On,
			Off
		}

		[HarmonyPatch]
		private static class Patch_Preloader_PatchEntrypoint
		{
			private static readonly MethodInfo ChainloaderFinishedCallInstructionAdder = AccessTools.DeclaredMethod(typeof(Patch_Preloader_PatchEntrypoint), "AddChainloaderFinishedCall", (Type[])null, (Type[])null);

			private static readonly MethodInfo ChainloaderStart = AccessTools.DeclaredMethod(typeof(Patch_Preloader_PatchEntrypoint), "PreChainloader", (Type[])null, (Type[])null);

			private static readonly MethodInfo ILInstructionInserter = AccessTools.DeclaredMethod(typeof(ILProcessor), "InsertBefore", (Type[])null, (Type[])null);

			private static bool patched = false;

			private static IEnumerable<MethodInfo> TargetMethods()
			{
				return new MethodInfo[1] { AccessTools.DeclaredMethod(typeof(EnvVars).Assembly.GetType("BepInEx.Preloader.Preloader"), "PatchEntrypoint", (Type[])null, (Type[])null) };
			}

			private static void AddChainloaderFinishedCall(ILProcessor ilProcessor, Instruction instruction, AssemblyDefinition assembly)
			{
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				ilProcessor.InsertBefore(instruction, ilProcessor.Create(OpCodes.Call, assembly.MainModule.ImportReference((MethodBase)ChainloaderStart)));
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				bool foundInitMethod = false;
				foreach (CodeInstruction instruction in instructions)
				{
					yield return instruction;
					if (instruction.opcode == OpCodes.Ldloc_S && instruction.operand is LocalBuilder localBuilder && localBuilder.LocalIndex == 6)
					{
						foundInitMethod = true;
					}
					else if (foundInitMethod && CodeInstructionExtensions.Calls(instruction, ILInstructionInserter))
					{
						yield return new CodeInstruction(OpCodes.Ldloc_S, (object)11);
						yield return new CodeInstruction(OpCodes.Ldloc_S, (object)12);
						yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						yield return new CodeInstruction(OpCodes.Ldind_Ref, (object)null);
						yield return new CodeInstruction(OpCodes.Call, (object)ChainloaderFinishedCallInstructionAdder);
					}
				}
			}

			private static void PreChainloader()
			{
				if (!patched)
				{
					patched = true;
					if (delayedPatcher == Toggle.On)
					{
						delayedPatcherHarmony.PatchAll(typeof(InterceptChainloader));
					}
					if (unifiedLocalization == Toggle.On)
					{
						harmony.PatchAll(typeof(InterceptLocalization));
						harmony.PatchAll(typeof(InterceptLanguageLoad));
					}
					if (optimizeConfigSave == Toggle.On)
					{
						harmony.PatchAll(typeof(DelayConfigSave));
						harmony.PatchAll(typeof(ChangeConfigSaveBack));
						harmony.PatchAll(typeof(SkipManuallyChangedSaveOnConfigSet));
					}
				}
			}
		}

		[HarmonyPatch]
		private static class InterceptLocalization
		{
			private static readonly Dictionary<string, Dictionary<string, string>> localizationCache = new Dictionary<string, Dictionary<string, string>>();

			private static readonly HashSet<MethodBase> alreadyAppliedEnglishLoadCSV = new HashSet<MethodBase>();

			private static MethodInfo TargetMethod()
			{
				return AccessTools.DeclaredMethod(Type.GetType("Localization, assembly_guiutils"), "SetupLanguage", (Type[])null, (Type[])null);
			}

			[HarmonyPriority(0)]
			private static bool Prefix(object __instance, string language, ref Dictionary<string, string> ___m_translations, ref bool __result)
			{
				if (localizationCache.TryGetValue(language, out Dictionary<string, string> value))
				{
					___m_translations = value;
					if (language == "English" && (string)AccessTools.DeclaredMethod(Type.GetType("UnityEngine.PlayerPrefs, UnityEngine.CoreModule"), "GetString", new Type[2]
					{
						typeof(string),
						typeof(string)
					}, (Type[])null).Invoke(null, new object[2] { "language", "English" }) != "English")
					{
						Patch[] postfixes = PatchManager.ToPatchInfo((MethodBase)AccessTools.DeclaredMethod(Type.GetType("Localization, assembly_guiutils"), "LoadCSV", (Type[])null, (Type[])null)).postfixes;
						foreach (Patch val in postfixes)
						{
							if (alreadyAppliedEnglishLoadCSV.Contains(val.PatchMethod))
							{
								continue;
							}
							ParameterInfo[] parameters = val.PatchMethod.GetParameters();
							object[] array = new object[parameters.Length];
							int num = 0;
							ParameterInfo[] array2 = parameters;
							foreach (ParameterInfo parameterInfo in array2)
							{
								if (parameterInfo.Name == "__instance")
								{
									array[num] = __instance;
								}
								else if (parameterInfo.Name == "language")
								{
									array[num] = language;
								}
								else if (parameterInfo.Name == "__result")
								{
									array[num] = true;
								}
								else if (parameterInfo.Name.StartsWith("___"))
								{
									array[num] = AccessTools.Field(__instance.GetType(), parameterInfo.Name.Substring(3)).GetValue(__instance);
								}
								num++;
							}
							val.PatchMethod.Invoke(null, array);
							alreadyAppliedEnglishLoadCSV.Add(val.PatchMethod);
						}
					}
					__result = true;
					return false;
				}
				if (language != "English")
				{
					___m_translations = new Dictionary<string, string>(___m_translations);
				}
				return true;
			}

			[HarmonyPriority(0)]
			private static void Postfix(string language, Dictionary<string, string> ___m_translations, bool __result)
			{
				if (__result)
				{
					localizationCache[language] = ___m_translations;
				}
			}
		}

		[HarmonyPatch]
		private static class InterceptLanguageLoad
		{
			private static MethodInfo TargetMethod()
			{
				return AccessTools.DeclaredMethod(Type.GetType("Localization, assembly_guiutils"), "LoadLanguages", (Type[])null, (Type[])null);
			}

			[HarmonyPriority(0)]
			private static bool Prefix(ref List<string> __result)
			{
				Type type = Type.GetType("Localization, assembly_guiutils");
				object value = AccessTools.DeclaredField(type, "m_instance").GetValue(null);
				if (value != null)
				{
					__result = (List<string>)AccessTools.DeclaredMethod(type, "GetLanguages", (Type[])null, (Type[])null).Invoke(value, Array.Empty<object>());
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch]
		private static class InterceptChainloader
		{
			private static bool postChainloader = false;

			private static bool doNotSkipUpdate = false;

			private static readonly HashSet<MethodBase> methods = new HashSet<MethodBase>();

			private static readonly MethodInfo patchSkip = AccessTools.DeclaredMethod(typeof(InterceptChainloader), "SkipUpdates", (Type[])null, (Type[])null);

			private static readonly MethodInfo addReplacementOriginal = AccessTools.DeclaredMethod(typeof(PatchManager), "AddReplacementOriginal", (Type[])null, (Type[])null);

			private static MethodInfo TargetMethod()
			{
				return postChainloader ? AccessTools.DeclaredMethod(Type.GetType("FejdStartup, assembly_valheim"), "Awake", (Type[])null, (Type[])null) : AccessTools.DeclaredMethod(typeof(Chainloader), "Start", (Type[])null, (Type[])null);
			}

			private static bool SkipUpdates(MethodBase original, ref MethodInfo? __result)
			{
				if (!doNotSkipUpdate)
				{
					Type declaringType = original.DeclaringType;
					if ((object)declaringType == null || !passthroughClasses.Contains(declaringType.FullName))
					{
						methods.Add(original);
						__result = null;
						return false;
					}
				}
				return true;
			}

			[HarmonyPriority(800)]
			public static void Prefix()
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				doNotSkipUpdate = false;
				delayedPatcherHarmony.Patch((MethodBase)harmonyPatcher, new HarmonyMethod(patchSkip), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}

			[HarmonyPriority(0)]
			public static void Postfix()
			{
				if (MidgardAntiCheatPlugin.speeditup)
				{
					doNotSkipUpdate = true;
					if (postChainloader)
					{
						delayedPatcherHarmony.UnpatchSelf();
						string text = "after FejdStartup.Awake";
					}
					else
					{
						delayedPatcherHarmony.Unpatch((MethodBase)TargetMethod(), (HarmonyPatchType)0, delayedPatcherHarmony.Id);
						postChainloader = true;
						delayedPatcherHarmony.PatchAll(typeof(InterceptChainloader));
						string text = "after Chainloader end";
					}
					Stopwatch stopwatch = new Stopwatch();
					stopwatch.Start();
					lock (AccessTools.DeclaredField(typeof(PatchProcessor), "locker").GetValue(null))
					{
						foreach (MethodBase method in methods)
						{
							object obj = harmonyPatcher.Invoke(null, new object[2]
							{
								method,
								PatchManager.ToPatchInfo(method)
							});
							addReplacementOriginal.Invoke(null, new object[2] { method, obj });
						}
					}
					int num = (int)stopwatch.ElapsedMilliseconds;
					int num2 = num;
					logger.LogWarning((object)("Midgard Speed it up Picard version 1.0 warped to destination in " + num2 + " seconds! Now, Tea, Earl Grey, Hot!"));
					methods.Clear();
				}
				else
				{
					logger.LogWarning((object)"Sorry, Speed it up Picard is only taking orders from Midgard server...Picard will now quit, and rage like a Klingon!");
					Environment.Exit(1);
				}
			}
		}

		[HarmonyPatch]
		private static class DelayConfigSave
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.DeclaredConstructor(typeof(ConfigFile), new Type[3]
				{
					typeof(string),
					typeof(bool),
					typeof(BepInPlugin)
				}, false);
			}

			private static void Postfix(ConfigFile __instance)
			{
				__instance.SaveOnConfigSet = false;
				changedConfigFiles.Add(__instance);
			}
		}

		[HarmonyPatch]
		private static class ChangeConfigSaveBack
		{
			private static MethodInfo TargetMethod()
			{
				return AccessTools.DeclaredMethod(Type.GetType("FejdStartup, assembly_valheim"), "Awake", (Type[])null, (Type[])null);
			}

			private static void Postfix()
			{
				List<ConfigFile> changedConfigFiles = MidgardSpeedItUpPicard.changedConfigFiles;
				MidgardSpeedItUpPicard.changedConfigFiles = new List<ConfigFile>();
				foreach (ConfigFile item in changedConfigFiles)
				{
					item.Save();
					item.SaveOnConfigSet = true;
				}
			}
		}

		[HarmonyPatch]
		private static class SkipManuallyChangedSaveOnConfigSet
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.DeclaredPropertySetter(typeof(ConfigFile), "SaveOnConfigSet");
			}

			private static void Prefix(ConfigFile __instance)
			{
				if (changedConfigFiles.Remove(__instance))
				{
					__instance.Save();
				}
			}
		}

		public const string version = "version 1.0";

		private const string CONFIG_FILE_NAME = "MidgardSpeedItUpPicard.cfg";

		private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "MidgardSpeedItUpPicard.cfg"), true);

		private static readonly ManualLogSource logger = Logger.CreateLogSource("MidgardSpeedItUpPicard");

		private static readonly Harmony delayedPatcherHarmony = new Harmony("midgard.speedituppicard.patcher");

		private static readonly Harmony harmony = new Harmony("midgard.speedituppicard");

		private static readonly MethodInfo harmonyPatcher = AccessTools.DeclaredMethod(typeof(Harmony).Assembly.GetType("HarmonyLib.PatchFunctions"), "UpdateWrapper", (Type[])null, (Type[])null);

		private static readonly string[] hardcodedPassthrough = new string[4]
		{
			typeof(Assembly).FullName,
			"BepInEx.Preloader.RuntimeFixes.HarmonyInteropFix",
			"BepInEx.PluginInfo",
			typeof(Enum).FullName
		};

		private static HashSet<string> passthroughClasses = new HashSet<string>();

		private static readonly Toggle delayedPatcher = Toggle.Off;

		private static readonly Toggle unifiedLocalization = Toggle.On;

		private static readonly Toggle optimizeConfigSave = Toggle.On;

		private static List<ConfigFile> changedConfigFiles = new List<ConfigFile>();

		public static IEnumerable<string> TargetDLLs { get; } = Array.Empty<string>();

		public static void Patch(AssemblyDefinition assembly)
		{
		}

		public static void Initialize()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			logger.LogWarning((object)"Midgard Speed it up Picard is preparing to warp!");
			ConfigEntry<string> passthrough = Config.Bind<string>("Patched", ".", "", new ConfigDescription("", (AcceptableValueBase)null, Array.Empty<object>()));
			passthrough.SettingChanged += delegate
			{
				calcPassthrough();
			};
			calcPassthrough();
			harmony.PatchAll(typeof(Patch_Preloader_PatchEntrypoint));
			void calcPassthrough()
			{
				HashSet<string> hashSet = new HashSet<string>();
				foreach (string item in hardcodedPassthrough.Concat((unifiedLocalization != Toggle.On) ? ((IEnumerable<string>)Array.Empty<string>()) : ((IEnumerable<string>)new string[1] { "Localization" })).Concat(passthrough.Value.Split(new char[1] { ',' })))
				{
					hashSet.Add(item);
				}
				passthroughClasses = hashSet;
			}
		}
	}
}

BepInEx/plugins/MidgardAntiCheatAndModEnforceSystem.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn;
using Microsoft.CodeAnalysis;
using MidgardAntiCheat;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Midgard Anti-Cheat and plugin enforcing system")]
[assembly: AssemblyDescription("Anti-Cheat, plugin verify and config enforcer system for Midgard Valheim server")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MidgardAntiCheatSystem")]
[assembly: AssemblyCopyright("Copyright ©  2024 - Ravenis")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("33A48729-24B4-4336-B364-4672EBBD15EE")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class ZNetExtensions
{
	public enum ZNetInstanceType
	{
		Local,
		Client,
		Server
	}

	public static bool IsLocalInstance(this ZNet znet)
	{
		return znet.IsServer() && !znet.IsDedicated();
	}

	public static bool IsClientInstance(this ZNet znet)
	{
		return !znet.IsServer() && !znet.IsDedicated();
	}

	public static bool IsServerInstance(this ZNet znet)
	{
		return znet.IsServer() && znet.IsDedicated();
	}

	public static ZNetInstanceType GetInstanceType(this ZNet znet)
	{
		if (znet.IsLocalInstance())
		{
			return ZNetInstanceType.Local;
		}
		if (znet.IsClientInstance())
		{
			return ZNetInstanceType.Client;
		}
		return ZNetInstanceType.Server;
	}
}
namespace AntiMods.GamePatches
{
	public static class ZNet_RPC_PeerInfoPatch
	{
		public static bool Prefix(ref ZNet __instance, ZRpc rpc, ZPackage pkg)
		{
			if (__instance.IsServer())
			{
				string text = "";
				MidgardAntiCheatPlugin.ReadServerStatusFromFile(Paths.PluginPath + "\\serverstatus.dat");
				if (MidgardAntiCheatPlugin.servermode != "Online")
				{
					int num = (Utility.IsNullOrWhiteSpace(text) ? 3 : 89);
					ZLog.Log((object)("[Midgard Anti-Cheat] [AntiMods]: Kicking Client: " + rpc.GetSocket().GetEndPointString() + " (Server is starting up...)"));
					rpc.Invoke("Error", new object[1] { num });
					return false;
				}
				if (MidgardAntiCheatPlugin.servermode == "Online")
				{
					if (pkg.Size() > 32)
					{
						pkg.SetPos(pkg.Size() - 32 - 1);
						if (pkg.ReadByte() == 32)
						{
							pkg.SetPos(pkg.GetPos() - 1);
							text = pkg.ReadString();
						}
					}
					MidgardAntiCheatPlugin.ReadServerModeFromFile(Paths.PluginPath + "\\servermode.dat");
					ZLog.Log((object)("[Midgard Anti-Cheat] [AntiMods]: Got client hash: " + text + "\nmine: " + MidgardAntiCheatPlugin.PluginsHash));
					ZLog.LogWarning((object)("[Midgard Anti-Cheat] Plugin Hashes are equal: " + !text.Equals(MidgardAntiCheatPlugin.PluginsHash) + " Enforce same mods system is on: " + MidgardAntiCheatPlugin.forcesamemods));
					ZLog.LogWarning((object)("[Midgard Anti-Cheat] Is Admin: " + !ZNet.instance.m_adminList.Contains(rpc.GetSocket().GetHostName()) + "Admin bypasses forcemod system: " + MidgardAntiCheatPlugin.adminbypass));
					pkg.SetPos(0);
					if (MidgardAntiCheatPlugin.adminbypass && ZNet.instance.m_adminList.Contains(rpc.GetSocket().GetHostName()))
					{
						return true;
					}
					if (MidgardAntiCheatPlugin.servermode != "All")
					{
						int num2 = (Utility.IsNullOrWhiteSpace(text) ? 3 : 89);
						ZLog.Log((object)("[Midgard Anti-Cheat] [AntiMods]: Kicking Client: " + rpc.GetSocket().GetEndPointString() + " (Server is not in All mode)"));
						rpc.Invoke("Error", new object[1] { num2 });
						return false;
					}
					if (!text.Equals(MidgardAntiCheatPlugin.PluginsHash) && MidgardAntiCheatPlugin.forcesamemods)
					{
						int num3 = (Utility.IsNullOrWhiteSpace(text) ? 3 : 99);
						ZLog.Log((object)("[Midgard Anti-Cheat] [AntiMods]: Kicking Client: " + rpc.GetSocket().GetEndPointString() + " (incompatible mods)"));
						rpc.Invoke("Error", new object[1] { num3 });
						MidgardAntiCheatPlugin.serverhash = text;
						return false;
					}
					ZLog.Log((object)("[Midgard Anti-Cheat] [AntiMods]: Accepting Client: " + rpc.GetSocket().GetEndPointString()));
					return true;
				}
			}
			return false;
		}
	}
}
namespace MidgardAntiCheat
{
	internal class Rpc
	{
		public static Dictionary<long, bool> Clients = new Dictionary<long, bool>(10);

		public static void AcHandshake(ZRpc rpc, long sender, string hash)
		{
			ZLog.Log((object)(ZNet.instance.IsServer() ? "Server" : ("Clientreceived AcHandshake from " + sender)));
			if (ZNet.instance.IsServer())
			{
				Clients.Add(sender, MidgardAntiCheatPlugin.PluginsHash.Equals(hash));
				ZLog.Log((object)("AC: Storing " + sender));
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "AcHandshake", new object[1] { "" });
			}
			else
			{
				ZLog.Log((object)"AC: Got server request, sending hash");
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "AcHandshake", new object[1] { "123451" });
			}
		}

		public static void AcRoutedHandshake(long sender, ZPackage pkg)
		{
			ZLog.Log((object)(ZNet.instance.IsServer() ? "Server" : ("Clientreceived AcRoutedHandshake from " + sender)));
			if (ZNet.instance.IsServer())
			{
				ZLog.Log((object)("AC: Storing " + sender));
			}
			else
			{
				ZLog.Log((object)"AC: Got server request, sending hash");
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	public static class RegisterAndCheckVersion
	{
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			peer.m_rpc.Register<ZPackage>("AntiCheat_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_AntiCheat_Version);
			ZPackage val = new ZPackage();
			val.Write(MidgardAntiCheatPlugin.PluginsHash);
			peer.m_rpc.Invoke("AntiCheat_VersionCheck", new object[1] { val });
		}
	}
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	public static class VerifyClient
	{
		private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance)
		{
			if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc))
			{
				return true;
			}
			rpc.Invoke("Error", new object[1] { 3 });
			return false;
		}

		private static void Postfix(ZNet __instance)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "AntiCheatRequestAdminSync", new object[1] { (object)new ZPackage() });
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
	public class ShowConnectionError
	{
		private static void Postfix(FejdStartup __instance)
		{
			if (__instance.m_connectionFailedPanel.activeSelf)
			{
				__instance.m_connectionFailedError.fontSizeMax = 25f;
				__instance.m_connectionFailedError.fontSizeMin = 15f;
				__instance.m_connectionFailedError.verticalAlignment = (VerticalAlignmentOptions)514;
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + MidgardAntiCheatPlugin.ConnectionError;
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect")]
	public static class RemoveDisconnectedPeerFromVerified
	{
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			if (__instance.IsServer())
			{
				RpcHandlers.ValidatedPeers.Remove(peer.m_rpc);
			}
		}
	}
	public static class RpcHandlers
	{
		public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>();

		public static void RPC_AntiCheat_Version(ZRpc rpc, ZPackage pkg)
		{
			string text = pkg.ReadString();
			if (ZNet.instance.m_adminList.Contains(rpc.GetSocket().GetHostName()))
			{
				ZLog.Log((object)"[Midgard Anti-Cheat] [AntiMods]: Admin detected, bypassing mod force check...)");
				ValidatedPeers.Add(rpc);
			}
			else if (text != MidgardAntiCheatPlugin.PluginsHash)
			{
				MidgardAntiCheatPlugin.ConnectionError = "[Midgard Anti-Cheat] MOD force system error: Incompatible mod hash, try updating the modpack first or join https://midgard.website/discord";
				if (ZNet.instance.IsServer())
				{
					ZLog.Log((object)("[Midgard Anti-Cheat] [AntiMods]: Client hash: " + text + "  Server hash: " + MidgardAntiCheatPlugin.PluginsHash));
				}
				rpc.Invoke("Error", new object[1] { 3 });
			}
			else if (!ZNet.instance.IsServer())
			{
				ZLog.Log((object)"[Midgard Anti-Cheat] [AntiMods]: Received same version from server!");
			}
			else
			{
				ZLog.Log((object)("[Midgard Anti-Cheat] [AntiMods]: Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list"));
				ValidatedPeers.Add(rpc);
			}
		}
	}
	[HarmonyReversePatch(/*Could not decode attribute arguments.*/)]
	[HarmonyPatch(typeof(ZRoutedRpc), "GetServerPeerID")]
	public static class HookedZRoutedRpc
	{
		public static long GetServerPeerID(object instance)
		{
			throw new NotImplementedException();
		}
	}
	public static class HashAlgorithmExtensions
	{
		public static int ModCount;

		private static string FinalHash(int hash, bool upperCase)
		{
			if (upperCase)
			{
				return hash.ToString(upperCase ? "X2" : "x2");
			}
			return hash.ToString();
		}

		public static string PluginHashes(string path)
		{
			string text = "";
			int hash = 0;
			List<string> list = (from d in Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories)
				where !d.Contains("MMHOOK")
				select d).ToList();
			File.Delete(path + "\\plugins.dat");
			File.WriteAllLines(path + "\\plugins.dat", list);
			MD5 mD = MD5.Create();
			List<string> list2 = list;
			for (int num = 0; num < list.Count; num++)
			{
				byte[] array = File.ReadAllBytes(list2[num]);
				if (num == list.Count - 1)
				{
					mD.TransformFinalBlock(array, 0, array.Length);
					list2[num] = BitConverter.ToString(mD.Hash).Replace("-", "").ToLower();
					text = string.Join("", list2);
					hash = StringExtensionMethods.GetStableHashCode(text);
				}
				else if (!list[num].Contains("MMHOOK_"))
				{
					mD.TransformBlock(array, 0, array.Length, array, 0);
					mD.TransformFinalBlock(array, 0, array.Length);
					list2[num] = BitConverter.ToString(mD.Hash).Replace("-", "").ToLower();
				}
			}
			File.Delete(path + "\\serverstatus.dat");
			File.Delete(path + "\\hashes.dat");
			File.Delete(path + "\\finalhash.dat");
			File.WriteAllLines(path + "\\hashes.dat", list2);
			File.WriteAllText(path + "\\finalhash.dat", FinalHash(hash, upperCase: true));
			File.WriteAllText(path + "\\serverstatus.dat", "Starting up...");
			ModCount = list.Count;
			return FinalHash(hash, upperCase: true);
		}
	}
	public class Damage_Rule
	{
		public static bool Execute(HitData hit)
		{
			if (MidgardAntiCheatPlugin.AntiParams_IsEnabled)
			{
				if (!MidgardAntiCheatPlugin.anti_debug_mode && !MidgardAntiCheatPlugin.anti_damage_boost)
				{
					return true;
				}
				Character attacker = hit.GetAttacker();
				if ((Object)(object)attacker != (Object)null && MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogError((object)("[Midgard Anti-Cheat] Send Char" + (object)attacker));
				}
				if ((Object)(object)attacker != (Object)null && attacker.IsPlayer())
				{
					ZNetPeer peer = ZNet.instance.GetPeer((long)((Object)attacker).GetInstanceID());
					if (MidgardAntiCheatPlugin.debugmode)
					{
						ZLog.LogError((object)("[Midgard Anti-Cheat] Player Detected, player:" + ((Object)attacker).GetInstanceID()));
						ZLog.LogError((object)("[Midgard Anti-Cheat] Damage = " + hit.GetTotalDamage()));
					}
					float totalDamage = hit.GetTotalDamage();
					if (peer != null && (!MidgardAntiCheatPlugin.admins_bypass || !ZNet.instance.m_adminList.Contains(peer.m_rpc.GetSocket().GetHostName())) && totalDamage > 1000f)
					{
						if (MidgardAntiCheatPlugin.debugmode)
						{
							ZLog.LogError((object)"[Midgard Anti-Cheat] Player Detected with possible Damage Boost.");
						}
						MidgardAntiCheatPlugin.toKick.Add(peer);
					}
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Character), "RPC_Damage")]
	public class DamageCharacter_Patch
	{
		private static bool Prefix(ref Character __instance, ref long sender, ref HitData hit)
		{
			if (MidgardAntiCheatPlugin.AntiParams_IsEnabled)
			{
				if (MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogWarning((object)"[Midgard Anti-Cheat] Damage to Character");
				}
				return Damage_Rule.Execute(hit);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(WearNTear), "RPC_Damage")]
	public class DamageWearNTear_Patch
	{
		private static bool Prefix(ref WearNTear __instance, ref long sender, ref HitData hit)
		{
			if (MidgardAntiCheatPlugin.AntiParams_IsEnabled)
			{
				if (MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogWarning((object)"[Midgard Anti-Cheat] Damage to WearNTear");
				}
				return Damage_Rule.Execute(hit);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(TreeBase), "RPC_Damage")]
	public class DamageTreeBase_Patch
	{
		private static bool Prefix(ref TreeBase __instance, ref long sender, ref HitData hit)
		{
			if (MidgardAntiCheatPlugin.AntiParams_IsEnabled)
			{
				if (MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogWarning((object)"[Midgard Anti-Cheat] Damage to TreeBase");
				}
				return Damage_Rule.Execute(hit);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(TreeLog), "RPC_Damage")]
	public class DamageTreeLog_Patch
	{
		private static bool Prefix(ref TreeLog __instance, ref long sender, ref HitData hit)
		{
			if (MidgardAntiCheatPlugin.AntiParams_IsEnabled)
			{
				if (MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogWarning((object)"[Midgard Anti-Cheat] Damage to TreeBase");
				}
				return Damage_Rule.Execute(hit);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(MineRock5), "RPC_Damage")]
	public class DamageMineRock5_Patch
	{
		private static bool Prefix(ref MineRock5 __instance, ref long sender, ref HitData hit)
		{
			if (MidgardAntiCheatPlugin.AntiParams_IsEnabled)
			{
				if (MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogWarning((object)"[Midgard Anti-Cheat] Damage to MineRock5");
				}
				return Damage_Rule.Execute(hit);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
	public class DamageDestructible_Patch
	{
		private static bool Prefix(ref Destructible __instance, ref long sender, ref HitData hit)
		{
			if (MidgardAntiCheatPlugin.AntiParams_IsEnabled)
			{
				if (MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogWarning((object)"[Midgard Anti-Cheat] Damage to MineRock5");
				}
				return Damage_Rule.Execute(hit);
			}
			return true;
		}
	}
	[BepInPlugin("midgard.anticheat", "Midgard Anti-Cheat & Mod Enforcing System", "1.0.1")]
	public class MidgardAntiCheatPlugin : BaseUnityPlugin
	{
		public const string version = "1.0.1";

		public const string pluginname = "Midgard Anti-Cheat & Mod Enforcing System";

		public const string pluginid = "midgard.anticheat";

		public static string description = "Midgard Anti-Cheat & Mod Enforcing System";

		internal static string ConnectionError = "";

		public const int HashLength = 32;

		public static string PluginsHash = "";

		public static Harmony harmony = new Harmony("midgard.anticheat");

		public static List<ZNetPeer> toKick = new List<ZNetPeer>();

		public static Dictionary<ZNetPeer, Vector3> posMap;

		public static ManualLogSource logger;

		public static List<string> playernames = new List<string>();

		public static int Counter = 0;

		public static bool antiMods_IsEnabled;

		public static bool forcesamemods;

		public static bool ignoremmhooks;

		public static bool adminbypass;

		public static bool AntiParams_IsEnabled;

		public static bool ban_on_trigger;

		public static bool admins_bypass;

		public static bool anti_fly;

		public static bool anti_debug_mode;

		public static bool anti_god_mode;

		public static bool anti_damage_boost;

		public static bool debugmode;

		public static bool anti_health_boost;

		public static bool speeditup;

		public static string serverhash;

		public static string AntiModsActivated;

		public static string AntiModsError;

		public static string AntiModsKickServer;

		public static string AntiModsKickClient;

		public static string AntiParamsMsg;

		private static readonly StringBuilder sb = new StringBuilder();

		private static PlayerProfile playerProfile;

		private static int statCount = 0;

		public static string servermode;

		public static string serverstatus;

		public static bool AntiMods_IsEnabled
		{
			get
			{
				return antiMods_IsEnabled;
			}
			set
			{
				antiMods_IsEnabled = value;
			}
		}

		public static void ReadServerModeFromFile(string filePath)
		{
			if (File.Exists(filePath))
			{
				servermode = File.ReadAllText(filePath).Trim();
			}
			else
			{
				servermode = "All";
			}
		}

		public static void ReadServerStatusFromFile(string filePath)
		{
			if (File.Exists(filePath))
			{
				serverstatus = File.ReadAllText(filePath).Trim();
			}
			else
			{
				serverstatus = "Unknown";
			}
		}

		private static void AddLine()
		{
			if (statCount > 0)
			{
				sb.Append("\n");
			}
			statCount = 0;
		}

		public static void WriteOnlineList()
		{
			if (ZNet.m_isServer)
			{
				playernames.Clear();
				List<ZNetPeer> peers = ZNet.m_instance.m_peers;
				for (int i = 0; i < ZNet.m_instance.m_peers.Count; i++)
				{
					playernames.Add(peers[i].m_playerName + "                     " + peers[i].m_rpc.m_pingTimer + "ms<br>");
				}
				File.Delete(Paths.PluginPath + "\\players_online.dat");
				File.WriteAllLines(Paths.PluginPath + "\\players_online.dat", playernames);
				File.Delete(Paths.PluginPath + "\\players_online_count.dat");
				File.WriteAllText(Paths.PluginPath + "\\players_online_count.dat", peers.Count.ToString());
			}
		}

		private void Watcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.PluginPath);
			fileSystemWatcher.Changed += CheckInjections;
			fileSystemWatcher.Created += CheckInjections;
			fileSystemWatcher.Renamed += CheckInjections;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
			FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(Paths.BepInExRootPath);
			fileSystemWatcher2.Changed += CheckInjections;
			fileSystemWatcher2.Created += CheckInjections;
			fileSystemWatcher2.Renamed += CheckInjections;
			fileSystemWatcher2.IncludeSubdirectories = true;
			fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher2.EnableRaisingEvents = true;
		}

		private void CheckInjections(object sender, FileSystemEventArgs e)
		{
			Process[] processesByName = Process.GetProcessesByName("ValheimToolerLauncher");
			if (processesByName.Length != 0)
			{
				ZLog.Log((object)"[Midgard Anti-Cheat] Valheim Tooler DETECTED! Closing Valheim and ValheimTooler...");
				Thread.Sleep(3000);
				Process[] processesByName2 = Process.GetProcessesByName("ValheimToolerLauncher");
				foreach (Process process in processesByName2)
				{
					process.Kill();
				}
				Process[] processesByName3 = Process.GetProcessesByName("valheim");
				foreach (Process process2 in processesByName3)
				{
					process2.Kill();
				}
			}
		}

		private void Awake()
		{
			forcesamemods = true;
			AntiMods_IsEnabled = true;
			ban_on_trigger = false;
			adminbypass = true;
			anti_fly = true;
			anti_debug_mode = true;
			anti_god_mode = true;
			anti_damage_boost = true;
			anti_health_boost = true;
			speeditup = true;
			debugmode = false;
			AntiModsActivated = "[Midgard Anti-Cheat] Mod Forcing Enabled.";
			AntiModsError = "[Midgard Anti-Cheat] Mod hash error!";
			AntiModsKickClient = "[Midgard Anti-Cheat] You were kicked for using outdated/wrong/missized/missing/ files, or admin is working on something at the moment. Join https://midgard.website/discord for more info!";
			AntiModsKickServer = "[Midgard Anti-Cheat] Player have been kicked for using not allowed mod(s)!";
			AntiParamsMsg = "[Midgard Anti-Cheat] Player {0} punished for {1}!";
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			harmony.PatchAll(executingAssembly);
			Logger.LogWarning((object)"[Midgard Anti-Cheat] Patching and generating mod hash...");
			posMap = new Dictionary<ZNetPeer, Vector3>();
			toKick = new List<ZNetPeer>();
			if (ZNet.m_isServer)
			{
				StartTimer(1000);
			}
			AntiMods();
			Watcher();
			File.WriteAllText(Paths.PluginPath + "\\serverstatus.dat", "Online");
		}

		public void StartTimer(int dueTime)
		{
			Timer timer = new Timer(TimerProc);
			timer.Change(dueTime, 30000);
		}

		private void TimerProc(object state)
		{
			Timer timer = (Timer)state;
			WriteOnlineList();
		}

		public static void AntiMods()
		{
			if (Paths.ProcessName.Equals("valheim_server", StringComparison.OrdinalIgnoreCase))
			{
				PluginsHash = HashAlgorithmExtensions.PluginHashes(Paths.BepInExRootPath + "\\..\\MidgardClientMods");
			}
			else
			{
				PluginsHash = HashAlgorithmExtensions.PluginHashes(Paths.PluginPath);
			}
			Logger.LogWarning((object)("[Midgard Anti-Cheat] Total Mod count: " + HashAlgorithmExtensions.ModCount));
			Logger.LogWarning((object)("[Midgard Anti-Cheat] Final Mod hash: " + PluginsHash));
			Logger.LogWarning((object)"[Midgard Anti-Cheat] Done patching.");
		}

		private void OnDestroy()
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "SetupGui")]
	public static class FejdStartup_SetupGui_Patch
	{
		public static void Postfix(ref FejdStartup __instance)
		{
			__instance.m_versionLabel.fontSize = 7f;
			__instance.m_versionLabel.fontSizeMax = 8f;
			__instance.m_versionLabel.richText = false;
			string versionString = Version.GetVersionString(false);
			__instance.m_versionLabel.alignment = (TextAlignmentOptions)514;
			TMP_Text versionLabel = __instance.m_versionLabel;
			string text = (__instance.m_versionLabel.text = "Midgard - Vanilla \n" + Version.GetVersionString(false) + "\nMidgard Anti-Cheat and \nMod Enforcing System 1.0.1");
			versionLabel.SetText(text);
			if ((Object)(object)__instance.m_versionLabel != (Object)null)
			{
				__instance.m_versionLabel.alignment = (TextAlignmentOptions)514;
				__instance.m_versionLabel.verticalAlignment = (VerticalAlignmentOptions)512;
				__instance.m_versionLabel.horizontalAlignment = (HorizontalAlignmentOptions)2;
			}
		}
	}
	[HarmonyPatch(typeof(FejdStartup))]
	public class FejdStartup_ShowConnectErrorPatch
	{
		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		public static void Postfix(FejdStartup __instance)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Invalid comparison between Unknown and I4
			__instance.m_connectionFailedError.alignment = (TextAlignmentOptions)544;
			__instance.m_connectionFailedError.verticalAlignment = (VerticalAlignmentOptions)512;
			__instance.m_connectionFailedError.horizontalAlignment = (HorizontalAlignmentOptions)2;
			if ((int)ZNet.GetConnectionStatus() == 99)
			{
				__instance.m_connectionFailedError.text = "[Midgard Mod Enforcing System] You were kicked for using outdated wrong missized missing files, or admin is working on something at the moment\nYou can NOT add, delete or modify any mods in any way, every player must have excatly same client!\nCheck mod manager if there is update for Midgard modpack itself.\nServer mod hash: " + MidgardAntiCheatPlugin.serverhash + "\nYour client hash: " + MidgardAntiCheatPlugin.PluginsHash + "\nJoin https://midgard.website/discord for more info!";
			}
			else if ((int)ZNet.GetConnectionStatus() == 89)
			{
				__instance.m_connectionFailedError.text = "[Midgard Server] You were kicked due to server is in Admin Only mode.\nJoin https://midgard.website/discord for more info!";
			}
			else
			{
				__instance.m_connectionFailedError.text = "[Midgard Server] Server seems to be down...try again in few minutes.\nJoin https://midgard.website/discord for more info!";
			}
		}
	}
	public class MidgardAntiCheatAck
	{
		public static void RPC_MidgardAntiCheatAck(long sender)
		{
			RpcQueue.GotAck();
		}

		public static void SendAck(long target)
		{
			ZRoutedRpc.instance.InvokeRoutedRPC(target, "MidgardAntiCheatAck", Array.Empty<object>());
		}
	}
	internal static class GameObjectAssistant
	{
		private static ConcurrentDictionary<float, Stopwatch> stopwatches = new ConcurrentDictionary<float, Stopwatch>();

		public static Stopwatch GetStopwatch(GameObject o)
		{
			float gameObjectPosHash = GetGameObjectPosHash(o);
			Stopwatch value = null;
			if (!stopwatches.TryGetValue(gameObjectPosHash, out value))
			{
				value = new Stopwatch();
				stopwatches.TryAdd(gameObjectPosHash, value);
			}
			return value;
		}

		private static float GetGameObjectPosHash(GameObject o)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			return 1000f * o.transform.position.x + o.transform.position.y + 0.001f * o.transform.position.z;
		}

		public static T GetChildComponentByName<T>(string name, GameObject objected) where T : Component
		{
			T[] componentsInChildren = objected.GetComponentsInChildren<T>(true);
			foreach (T val in componentsInChildren)
			{
				if (((Object)((Component)val).gameObject).name == name)
				{
					return val;
				}
			}
			return default(T);
		}
	}
	internal static class Helper
	{
		public static Character getPlayerCharacter(Player __instance)
		{
			return (Character)(object)__instance;
		}

		public static float tFloat(this float value, int digits)
		{
			double num = Math.Pow(10.0, digits);
			double num2 = Math.Truncate(num * (double)value) / num;
			return (float)num2;
		}

		public static float applyModifierValue(float targetValue, float value)
		{
			if (value == 50f)
			{
				value = 51f;
			}
			if (value == -50f)
			{
				value = -51f;
			}
			if (value <= -100f)
			{
				value = -100f;
			}
			float num = targetValue;
			if (value >= 0f)
			{
				return targetValue + targetValue / 100f * value;
			}
			return targetValue - targetValue / 100f * (value * -1f);
		}

		public static string CreateMD5(string input)
		{
			using MD5 mD = MD5.Create();
			byte[] bytes = Encoding.ASCII.GetBytes(input);
			byte[] array = mD.ComputeHash(bytes);
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < array.Length; i++)
			{
				stringBuilder.Append(array[i].ToString("X2"));
			}
			return stringBuilder.ToString();
		}

		public static int Clamp(int value, int min, int max)
		{
			return Math.Min(max, Math.Max(min, value));
		}

		public static float Clamp(float value, float min, float max)
		{
			return Math.Min(max, Math.Max(min, value));
		}
	}
	public static class ListExtensions
	{
		public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize)
		{
			return (from x in source.Select((T x, int i) => new
				{
					Index = i,
					Value = x
				})
				group x by x.Index / chunkSize into x
				select x.Select(v => v.Value).ToList()).ToList();
		}
	}
	public class RpcData
	{
		public string Name;

		public long Target = 0L;

		public object[] Payload;
	}
	public static class RpcQueue
	{
		private static Queue<RpcData> _rpcQueue = new Queue<RpcData>();

		private static bool _ack = true;

		public static void Enqueue(RpcData rpc)
		{
			_rpcQueue.Enqueue(rpc);
		}

		public static bool SendNextRpc()
		{
			if (_rpcQueue.Count == 0 || !_ack)
			{
				return false;
			}
			RpcData rpcData = _rpcQueue.Dequeue();
			if (Utility.IsNullOrWhiteSpace(rpcData.Name) || rpcData.Payload == null)
			{
				return false;
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(rpcData.Target, rpcData.Name, rpcData.Payload);
			_ack = false;
			return true;
		}

		public static void GotAck()
		{
			_ack = true;
		}
	}
}
namespace MidgardAntiCheat.AntiParams.GamePatches
{
	[HarmonyPatch(typeof(Character), "RPC_Heal")]
	public class HealthRPC_Heal_Patch
	{
		private static bool Prefix(ref Character __instance, ref long sender, ref float hp, ref bool showText)
		{
			float health = __instance.GetHealth();
			if ((double)health <= 0.0 || __instance.IsDead() || !__instance.IsPlayer())
			{
				return true;
			}
			if (MidgardAntiCheatPlugin.debugmode)
			{
				ZLog.LogWarning((object)("[Midgard Anti-Cheat] Is Player/Is Dead:" + __instance.IsPlayer() + __instance.IsDead()));
			}
			float maxHealth = __instance.GetMaxHealth();
			Character val = __instance;
			if (MidgardAntiCheatPlugin.debugmode)
			{
				ZLog.LogWarning((object)("[Midgard Anti-Cheat] Max Health/Player Character:" + maxHealth + (object)val));
			}
			if (maxHealth >= 1000f || health >= 1000f)
			{
				ZNetPeer peer = ZNet.instance.GetPeer((long)((Object)val).GetInstanceID());
				if (MidgardAntiCheatPlugin.debugmode)
				{
					ZLog.LogWarning((object)("[Midgard Anti-Cheat] Peer:" + (object)peer));
				}
				if (peer != null && (!MidgardAntiCheatPlugin.admins_bypass || !ZNet.instance.m_adminList.Contains(peer.m_rpc.GetSocket().GetHostName())))
				{
					if (MidgardAntiCheatPlugin.debugmode)
					{
						ZLog.LogError((object)"[Midgard Anti-Cheat] Player Detected with possible Health Boost.");
					}
					MidgardAntiCheatPlugin.toKick.Add(peer);
				}
				return true;
			}
			return true;
		}
	}
}