diff --git a/src/Neo/Plugins/IPluginSettings.cs b/src/Neo/Plugins/IPluginSettings.cs new file mode 100644 index 0000000000..aa2ca387a4 --- /dev/null +++ b/src/Neo/Plugins/IPluginSettings.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2025 The Neo Project. +// +// IPluginSettings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +namespace Neo.Plugins +{ + public interface IPluginSettings + { + public UnhandledExceptionPolicy ExceptionPolicy { get; } + } +} diff --git a/src/Neo/Plugins/PluginSettings.cs b/src/Neo/Plugins/PluginSettings.cs deleted file mode 100644 index 3fa36f7265..0000000000 --- a/src/Neo/Plugins/PluginSettings.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2015-2025 The Neo Project. -// -// PluginSettings.cs file belongs to the neo project and is free -// software distributed under the MIT software license, see the -// accompanying file LICENSE in the main directory of the -// repository or http://www.opensource.org/licenses/mit-license.php -// for more details. -// -// Redistribution and use in source and binary forms with or without -// modifications are permitted. - -#nullable enable - -using Microsoft.Extensions.Configuration; -using Org.BouncyCastle.Security; -using System; - -namespace Neo.Plugins -{ - public abstract class PluginSettings(IConfigurationSection section) - { - public UnhandledExceptionPolicy ExceptionPolicy - { - get - { - var policyString = section.GetValue(nameof(UnhandledExceptionPolicy), nameof(UnhandledExceptionPolicy.StopNode)); - if (Enum.TryParse(policyString, true, out UnhandledExceptionPolicy policy)) - { - return policy; - } - - throw new InvalidParameterException($"{policyString} is not a valid UnhandledExceptionPolicy"); - } - } - } -} - -#nullable disable diff --git a/src/Plugins/ApplicationLogs/LogReader.cs b/src/Plugins/ApplicationLogs/LogReader.cs index 9e451ad583..c13638c34c 100644 --- a/src/Plugins/ApplicationLogs/LogReader.cs +++ b/src/Plugins/ApplicationLogs/LogReader.cs @@ -38,7 +38,7 @@ public class LogReader : Plugin, ICommittingHandler, ICommittedHandler, ILogHand public override string Name => "ApplicationLogs"; public override string Description => "Synchronizes smart contract VM executions and notifications (NotifyLog) on blockchain."; - protected override UnhandledExceptionPolicy ExceptionPolicy => Settings.Default.ExceptionPolicy; + protected override UnhandledExceptionPolicy ExceptionPolicy => ApplicationLogsSettings.Default.ExceptionPolicy; #region Ctor @@ -61,7 +61,7 @@ public override void Dispose() { Blockchain.Committing -= ((ICommittingHandler)this).Blockchain_Committing_Handler; Blockchain.Committed -= ((ICommittedHandler)this).Blockchain_Committed_Handler; - if (Settings.Default.Debug) + if (ApplicationLogsSettings.Default.Debug) ApplicationEngine.InstanceHandler -= ConfigureAppEngine; GC.SuppressFinalize(this); } @@ -73,20 +73,20 @@ private void ConfigureAppEngine(ApplicationEngine engine) protected override void Configure() { - Settings.Load(GetConfiguration()); + ApplicationLogsSettings.Load(GetConfiguration()); } protected override void OnSystemLoaded(NeoSystem system) { - if (system.Settings.Network != Settings.Default.Network) + if (system.Settings.Network != ApplicationLogsSettings.Default.Network) return; - string path = string.Format(Settings.Default.Path, Settings.Default.Network.ToString("X8")); + string path = string.Format(ApplicationLogsSettings.Default.Path, ApplicationLogsSettings.Default.Network.ToString("X8")); var store = system.LoadStore(GetFullPath(path)); _neostore = new NeoStore(store); _neosystem = system; - RpcServerPlugin.RegisterMethods(this, Settings.Default.Network); + RpcServerPlugin.RegisterMethods(this, ApplicationLogsSettings.Default.Network); - if (Settings.Default.Debug) + if (ApplicationLogsSettings.Default.Debug) ApplicationEngine.InstanceHandler += ConfigureAppEngine; } @@ -217,14 +217,14 @@ internal void OnGetContractCommand(UInt160 scripthash, uint page = 1, uint pageS void ICommittingHandler.Blockchain_Committing_Handler(NeoSystem system, Block block, DataCache snapshot, IReadOnlyList applicationExecutedList) { - if (system.Settings.Network != Settings.Default.Network) + if (system.Settings.Network != ApplicationLogsSettings.Default.Network) return; if (_neostore is null) return; _neostore.StartBlockLogBatch(); _neostore.PutBlockLog(block, applicationExecutedList); - if (Settings.Default.Debug) + if (ApplicationLogsSettings.Default.Debug) { foreach (var appEng in applicationExecutedList.Where(w => w.Transaction != null)) { @@ -238,7 +238,7 @@ void ICommittingHandler.Blockchain_Committing_Handler(NeoSystem system, Block bl void ICommittedHandler.Blockchain_Committed_Handler(NeoSystem system, Block block) { - if (system.Settings.Network != Settings.Default.Network) + if (system.Settings.Network != ApplicationLogsSettings.Default.Network) return; if (_neostore is null) return; @@ -247,10 +247,10 @@ void ICommittedHandler.Blockchain_Committed_Handler(NeoSystem system, Block bloc void ILogHandler.ApplicationEngine_Log_Handler(ApplicationEngine sender, LogEventArgs e) { - if (Settings.Default.Debug == false) + if (ApplicationLogsSettings.Default.Debug == false) return; - if (_neosystem.Settings.Network != Settings.Default.Network) + if (_neosystem.Settings.Network != ApplicationLogsSettings.Default.Network) return; if (e.ScriptContainer == null) @@ -296,7 +296,7 @@ private void PrintExecutionToConsole(BlockchainExecutionModel model) ConsoleHelper.Info($" {GetMethodParameterName(notifyItem.ScriptHash, notifyItem.EventName, ncount, i)}: ", $"{notifyItem.State[i].ToJson()}"); } } - if (Settings.Default.Debug) + if (ApplicationLogsSettings.Default.Debug) { if (model.Logs.Length == 0) ConsoleHelper.Info("Logs: ", "[]"); @@ -366,7 +366,7 @@ private JObject EventModelToJObject(BlockchainEventModel model) try { - trigger["stack"] = appLog.Stack.Select(s => s.ToJson(Settings.Default.MaxStackSize)).ToArray(); + trigger["stack"] = appLog.Stack.Select(s => s.ToJson(ApplicationLogsSettings.Default.MaxStackSize)).ToArray(); } catch (Exception ex) { @@ -399,7 +399,7 @@ private JObject EventModelToJObject(BlockchainEventModel model) return notification; }).ToArray(); - if (Settings.Default.Debug) + if (ApplicationLogsSettings.Default.Debug) { trigger["logs"] = appLog.Logs.Select(s => { @@ -445,7 +445,7 @@ private JObject BlockItemToJObject(BlockchainExecutionModel blockExecutionModel) }; try { - trigger["stack"] = blockExecutionModel.Stack.Select(q => q.ToJson(Settings.Default.MaxStackSize)).ToArray(); + trigger["stack"] = blockExecutionModel.Stack.Select(q => q.ToJson(ApplicationLogsSettings.Default.MaxStackSize)).ToArray(); } catch (Exception ex) { @@ -476,7 +476,7 @@ private JObject BlockItemToJObject(BlockchainExecutionModel blockExecutionModel) return notification; }).ToArray(); - if (Settings.Default.Debug) + if (ApplicationLogsSettings.Default.Debug) { trigger["logs"] = blockExecutionModel.Logs.Select(s => { diff --git a/src/Plugins/ApplicationLogs/Settings.cs b/src/Plugins/ApplicationLogs/Settings.cs index 63e4d9bfb4..c43876f370 100644 --- a/src/Plugins/ApplicationLogs/Settings.cs +++ b/src/Plugins/ApplicationLogs/Settings.cs @@ -13,7 +13,7 @@ namespace Neo.Plugins.ApplicationLogs { - internal class Settings : PluginSettings + internal class ApplicationLogsSettings : IPluginSettings { public string Path { get; } public uint Network { get; } @@ -21,19 +21,22 @@ internal class Settings : PluginSettings public bool Debug { get; } - public static Settings Default { get; private set; } = default!; + public static ApplicationLogsSettings Default { get; private set; } = default!; - private Settings(IConfigurationSection section) : base(section) + public UnhandledExceptionPolicy ExceptionPolicy { get; } + + private ApplicationLogsSettings(IConfigurationSection section) { Path = section.GetValue("Path", "ApplicationLogs_{0}"); Network = section.GetValue("Network", 5195086u); MaxStackSize = section.GetValue("MaxStackSize", (int)ushort.MaxValue); Debug = section.GetValue("Debug", false); + ExceptionPolicy = section.GetValue("UnhandledExceptionPolicy", UnhandledExceptionPolicy.Ignore); } public static void Load(IConfigurationSection section) { - Default = new Settings(section); + Default = new ApplicationLogsSettings(section); } } } diff --git a/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs b/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs index 703caaaec5..b207b58425 100644 --- a/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs +++ b/src/Plugins/ApplicationLogs/Store/LogStorageStore.cs @@ -160,14 +160,14 @@ public Guid PutStackItemState(StackItem stackItem) { _snapshot.Put(key, BinarySerializer.Serialize(stackItem, ExecutionEngineLimits.Default with { - MaxItemSize = (uint)Settings.Default.MaxStackSize + MaxItemSize = (uint)ApplicationLogsSettings.Default.MaxStackSize })); } catch { _snapshot.Put(key, BinarySerializer.Serialize(StackItem.Null, ExecutionEngineLimits.Default with { - MaxItemSize = (uint)Settings.Default.MaxStackSize + MaxItemSize = (uint)ApplicationLogsSettings.Default.MaxStackSize })); } return id; diff --git a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs index a18fb00ce2..d2019f01c8 100644 --- a/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs +++ b/src/Plugins/DBFTPlugin/Consensus/ConsensusContext.cs @@ -59,7 +59,7 @@ public partial class ConsensusContext : IDisposable, ISerializable private ECPoint _myPublicKey; private int _witnessSize; private readonly NeoSystem neoSystem; - private readonly Settings dbftSettings; + private readonly DbftSettings dbftSettings; private readonly ISigner _signer; private readonly IStore store; private Dictionary cachedMessages; @@ -113,7 +113,7 @@ public bool ValidatorsChanged public int Size => throw new NotImplementedException(); - public ConsensusContext(NeoSystem neoSystem, Settings settings, ISigner signer) + public ConsensusContext(NeoSystem neoSystem, DbftSettings settings, ISigner signer) { _signer = signer; this.neoSystem = neoSystem; diff --git a/src/Plugins/DBFTPlugin/Consensus/ConsensusService.cs b/src/Plugins/DBFTPlugin/Consensus/ConsensusService.cs index 9671fc6981..51f9d0a327 100644 --- a/src/Plugins/DBFTPlugin/Consensus/ConsensusService.cs +++ b/src/Plugins/DBFTPlugin/Consensus/ConsensusService.cs @@ -54,13 +54,13 @@ private class Timer { public uint Height; public byte ViewNumber; } /// This variable is only true during OnRecoveryMessageReceived /// private bool isRecovering = false; - private readonly Settings dbftSettings; + private readonly DbftSettings dbftSettings; private readonly NeoSystem neoSystem; - public ConsensusService(NeoSystem neoSystem, Settings settings, ISigner signer) + public ConsensusService(NeoSystem neoSystem, DbftSettings settings, ISigner signer) : this(neoSystem, settings, new ConsensusContext(neoSystem, settings, signer)) { } - internal ConsensusService(NeoSystem neoSystem, Settings settings, ConsensusContext context) + internal ConsensusService(NeoSystem neoSystem, DbftSettings settings, ConsensusContext context) { this.neoSystem = neoSystem; localNode = neoSystem.LocalNode; @@ -336,7 +336,7 @@ protected override void PostStop() base.PostStop(); } - public static Props Props(NeoSystem neoSystem, Settings dbftSettings, ISigner signer) + public static Props Props(NeoSystem neoSystem, DbftSettings dbftSettings, ISigner signer) { return Akka.Actor.Props.Create(() => new ConsensusService(neoSystem, dbftSettings, signer)); } diff --git a/src/Plugins/DBFTPlugin/DBFTPlugin.cs b/src/Plugins/DBFTPlugin/DBFTPlugin.cs index 7c7b203b52..b085980097 100644 --- a/src/Plugins/DBFTPlugin/DBFTPlugin.cs +++ b/src/Plugins/DBFTPlugin/DBFTPlugin.cs @@ -26,7 +26,7 @@ public class DBFTPlugin : Plugin, IServiceAddedHandler, IMessageReceivedHandler, private IActorRef consensus; private bool started = false; private NeoSystem neoSystem; - private Settings settings; + private DbftSettings settings; public override string Description => "Consensus plugin with dBFT algorithm."; @@ -39,7 +39,7 @@ public DBFTPlugin() RemoteNode.MessageReceived += ((IMessageReceivedHandler)this).RemoteNode_MessageReceived_Handler; } - public DBFTPlugin(Settings settings) : this() + public DBFTPlugin(DbftSettings settings) : this() { this.settings = settings; } @@ -51,7 +51,7 @@ public override void Dispose() protected override void Configure() { - settings ??= new Settings(GetConfiguration()); + settings ??= new DbftSettings(GetConfiguration()); } protected override void OnSystemLoaded(NeoSystem system) diff --git a/src/Plugins/DBFTPlugin/Settings.cs b/src/Plugins/DBFTPlugin/DbftSettings.cs similarity index 64% rename from src/Plugins/DBFTPlugin/Settings.cs rename to src/Plugins/DBFTPlugin/DbftSettings.cs index db091e2e9f..3f8e302643 100644 --- a/src/Plugins/DBFTPlugin/Settings.cs +++ b/src/Plugins/DBFTPlugin/DbftSettings.cs @@ -1,6 +1,6 @@ // Copyright (C) 2015-2025 The Neo Project. // -// Settings.cs file belongs to the neo project and is free +// DbftSettings.cs file belongs to the neo project and is free // software distributed under the MIT software license, see the // accompanying file LICENSE in the main directory of the // repository or http://www.opensource.org/licenses/mit-license.php @@ -13,7 +13,7 @@ namespace Neo.Plugins.DBFTPlugin { - public class Settings : PluginSettings + public class DbftSettings : IPluginSettings { public string RecoveryLogs { get; } public bool IgnoreRecoveryLogs { get; } @@ -22,7 +22,19 @@ public class Settings : PluginSettings public uint MaxBlockSize { get; } public long MaxBlockSystemFee { get; } - public Settings(IConfigurationSection section) : base(section) + public UnhandledExceptionPolicy ExceptionPolicy { get; } + + public DbftSettings() + { + RecoveryLogs = "ConsensusState"; + IgnoreRecoveryLogs = false; + AutoStart = false; + Network = 5195086u; + MaxBlockSystemFee = 150000000000L; + ExceptionPolicy = UnhandledExceptionPolicy.StopNode; + } + + public DbftSettings(IConfigurationSection section) { RecoveryLogs = section.GetValue("RecoveryLogs", "ConsensusState"); IgnoreRecoveryLogs = section.GetValue("IgnoreRecoveryLogs", false); @@ -30,6 +42,7 @@ public Settings(IConfigurationSection section) : base(section) Network = section.GetValue("Network", 5195086u); MaxBlockSize = section.GetValue("MaxBlockSize", 262144u); MaxBlockSystemFee = section.GetValue("MaxBlockSystemFee", 150000000000L); + ExceptionPolicy = section.GetValue("UnhandledExceptionPolicy", UnhandledExceptionPolicy.StopNode); } } } diff --git a/src/Plugins/OracleService/OracleService.cs b/src/Plugins/OracleService/OracleService.cs index f404ebaa5c..208dbb6c26 100644 --- a/src/Plugins/OracleService/OracleService.cs +++ b/src/Plugins/OracleService/OracleService.cs @@ -63,7 +63,7 @@ public class OracleService : Plugin, ICommittingHandler, IServiceAddedHandler, I public override string Description => "Built-in oracle plugin"; - protected override UnhandledExceptionPolicy ExceptionPolicy => Settings.Default.ExceptionPolicy; + protected override UnhandledExceptionPolicy ExceptionPolicy => OracleSettings.Default.ExceptionPolicy; public override string ConfigFile => System.IO.Path.Combine(RootPath, "OracleService.json"); @@ -74,17 +74,17 @@ public OracleService() protected override void Configure() { - Settings.Load(GetConfiguration()); + OracleSettings.Load(GetConfiguration()); foreach (var (_, p) in protocols) p.Configure(); } protected override void OnSystemLoaded(NeoSystem system) { - if (system.Settings.Network != Settings.Default.Network) return; + if (system.Settings.Network != OracleSettings.Default.Network) return; _system = system; _system.ServiceAdded += ((IServiceAddedHandler)this).NeoSystem_ServiceAdded_Handler; - RpcServerPlugin.RegisterMethods(this, Settings.Default.Network); + RpcServerPlugin.RegisterMethods(this, OracleSettings.Default.Network); } @@ -94,7 +94,7 @@ void IServiceAddedHandler.NeoSystem_ServiceAdded_Handler(object sender, object s { walletProvider = service as IWalletProvider; _system.ServiceAdded -= ((IServiceAddedHandler)this).NeoSystem_ServiceAdded_Handler; - if (Settings.Default.AutoStart) + if (OracleSettings.Default.AutoStart) { walletProvider.WalletChanged += ((IWalletChangedHandler)this).IWalletProvider_WalletChanged_Handler; } @@ -173,9 +173,9 @@ private void OnShow() void ICommittingHandler.Blockchain_Committing_Handler(NeoSystem system, Block block, DataCache snapshot, IReadOnlyList applicationExecutedList) { - if (system.Settings.Network != Settings.Default.Network) return; + if (system.Settings.Network != OracleSettings.Default.Network) return; - if (Settings.Default.AutoStart && status == OracleStatus.Unstarted) + if (OracleSettings.Default.AutoStart && status == OracleStatus.Unstarted) { OnStart(); } @@ -193,7 +193,7 @@ private async void OnTimer(object state) foreach (var (id, task) in pendingQueue) { var span = TimeProvider.Current.UtcNow - task.Timestamp; - if (span > Settings.Default.MaxTaskTimeout) + if (span > OracleSettings.Default.MaxTaskTimeout) { outOfDate.Add(id); continue; @@ -270,7 +270,7 @@ private async Task SendResponseSignatureAsync(ulong requestId, byte[] txSign, Ke var param = "\"" + Convert.ToBase64String(keyPair.PublicKey.ToArray()) + "\", " + requestId + ", \"" + Convert.ToBase64String(txSign) + "\",\"" + Convert.ToBase64String(sign) + "\""; var content = "{\"id\":" + Interlocked.Increment(ref counter) + ",\"jsonrpc\":\"2.0\",\"method\":\"submitoracleresponse\",\"params\":[" + param + "]}"; - var tasks = Settings.Default.Nodes.Select(p => SendContentAsync(p, content)); + var tasks = OracleSettings.Default.Nodes.Select(p => SendContentAsync(p, content)); await Task.WhenAll(tasks); } @@ -364,7 +364,7 @@ private void SyncPendingQueue(DataCache snapshot) if (!protocols.TryGetValue(uri.Scheme, out IOracleProtocol protocol)) return (OracleResponseCode.ProtocolNotSupported, $"Invalid Protocol:<{url}>"); - using CancellationTokenSource ctsTimeout = new(Settings.Default.MaxOracleTimeout); + using CancellationTokenSource ctsTimeout = new(OracleSettings.Default.MaxOracleTimeout); using CancellationTokenSource ctsLinked = CancellationTokenSource.CreateLinkedTokenSource(cancelSource.Token, ctsTimeout.Token); try diff --git a/src/Plugins/OracleService/Settings.cs b/src/Plugins/OracleService/OracleSettings.cs similarity index 84% rename from src/Plugins/OracleService/Settings.cs rename to src/Plugins/OracleService/OracleSettings.cs index 8dd8cd2ad7..62c9eed9a5 100644 --- a/src/Plugins/OracleService/Settings.cs +++ b/src/Plugins/OracleService/OracleSettings.cs @@ -1,6 +1,6 @@ // Copyright (C) 2015-2025 The Neo Project. // -// Settings.cs file belongs to the neo project and is free +// OracleSettings.cs file belongs to the neo project and is free // software distributed under the MIT software license, see the // accompanying file LICENSE in the main directory of the // repository or http://www.opensource.org/licenses/mit-license.php @@ -38,7 +38,7 @@ public NeoFSSettings(IConfigurationSection section) } } - class Settings : PluginSettings + class OracleSettings : IPluginSettings { public uint Network { get; } public Uri[] Nodes { get; } @@ -50,9 +50,11 @@ class Settings : PluginSettings public NeoFSSettings NeoFS { get; } public bool AutoStart { get; } - public static Settings Default { get; private set; } + public static OracleSettings Default { get; private set; } - private Settings(IConfigurationSection section) : base(section) + public UnhandledExceptionPolicy ExceptionPolicy { get; } + + private OracleSettings(IConfigurationSection section) { Network = section.GetValue("Network", 5195086u); Nodes = section.GetSection("Nodes").GetChildren().Select(p => new Uri(p.Get(), UriKind.Absolute)).ToArray(); @@ -60,6 +62,7 @@ private Settings(IConfigurationSection section) : base(section) MaxOracleTimeout = TimeSpan.FromMilliseconds(section.GetValue("MaxOracleTimeout", 15000)); AllowPrivateHost = section.GetValue("AllowPrivateHost", false); AllowedContentTypes = section.GetSection("AllowedContentTypes").GetChildren().Select(p => p.Get()).ToArray(); + ExceptionPolicy = section.GetValue("UnhandledExceptionPolicy", UnhandledExceptionPolicy.Ignore); if (AllowedContentTypes.Count() == 0) AllowedContentTypes = AllowedContentTypes.Concat("application/json").ToArray(); Https = new HttpsSettings(section.GetSection("Https")); @@ -69,7 +72,7 @@ private Settings(IConfigurationSection section) : base(section) public static void Load(IConfigurationSection section) { - Default = new Settings(section); + Default = new OracleSettings(section); } } } diff --git a/src/Plugins/OracleService/Protocols/OracleHttpsProtocol.cs b/src/Plugins/OracleService/Protocols/OracleHttpsProtocol.cs index c74b69c8da..860edb0d6f 100644 --- a/src/Plugins/OracleService/Protocols/OracleHttpsProtocol.cs +++ b/src/Plugins/OracleService/Protocols/OracleHttpsProtocol.cs @@ -37,9 +37,9 @@ public OracleHttpsProtocol() public void Configure() { client.DefaultRequestHeaders.Accept.Clear(); - foreach (string type in Settings.Default.AllowedContentTypes) + foreach (string type in OracleSettings.Default.AllowedContentTypes) client.DefaultRequestHeaders.Accept.ParseAdd(type); - client.Timeout = Settings.Default.Https.Timeout; + client.Timeout = OracleSettings.Default.Https.Timeout; } public void Dispose() @@ -57,7 +57,7 @@ public void Dispose() int redirects = 2; do { - if (!Settings.Default.AllowPrivateHost) + if (!OracleSettings.Default.AllowPrivateHost) { IPHostEntry entry = await Dns.GetHostEntryAsync(uri.Host, cancellation); if (entry.IsInternal()) @@ -83,7 +83,7 @@ public void Dispose() return (OracleResponseCode.Forbidden, null); if (!message.IsSuccessStatusCode) return (OracleResponseCode.Error, message.StatusCode.ToString()); - if (!Settings.Default.AllowedContentTypes.Contains(message.Content.Headers.ContentType.MediaType)) + if (!OracleSettings.Default.AllowedContentTypes.Contains(message.Content.Headers.ContentType.MediaType)) return (OracleResponseCode.ContentTypeNotSupported, null); if (message.Content.Headers.ContentLength.HasValue && message.Content.Headers.ContentLength > OracleResponse.MaxResultSize) return (OracleResponseCode.ResponseTooLarge, null); diff --git a/src/Plugins/OracleService/Protocols/OracleNeoFSProtocol.cs b/src/Plugins/OracleService/Protocols/OracleNeoFSProtocol.cs index c8e29555b7..6f0cb3dc65 100644 --- a/src/Plugins/OracleService/Protocols/OracleNeoFSProtocol.cs +++ b/src/Plugins/OracleService/Protocols/OracleNeoFSProtocol.cs @@ -52,7 +52,7 @@ public void Dispose() Utility.Log(nameof(OracleNeoFSProtocol), LogLevel.Debug, $"Request: {uri.AbsoluteUri}"); try { - (OracleResponseCode code, string data) = await GetAsync(uri, Settings.Default.NeoFS.EndPoint, cancellation); + (OracleResponseCode code, string data) = await GetAsync(uri, OracleSettings.Default.NeoFS.EndPoint, cancellation); Utility.Log(nameof(OracleNeoFSProtocol), LogLevel.Debug, $"NeoFS result, code: {code}, data: {data}"); return (code, data); } @@ -85,7 +85,7 @@ public void Dispose() }; using Client client = new(privateKey, host); var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellation); - tokenSource.CancelAfter(Settings.Default.NeoFS.Timeout); + tokenSource.CancelAfter(OracleSettings.Default.NeoFS.Timeout); if (ps.Length == 2) return GetPayload(client, objectAddr, tokenSource.Token); return ps[2] switch diff --git a/src/Plugins/RpcServer/Settings.cs b/src/Plugins/RpcServer/RcpServerSettings.cs similarity index 87% rename from src/Plugins/RpcServer/Settings.cs rename to src/Plugins/RpcServer/RcpServerSettings.cs index 4125349874..f447750170 100644 --- a/src/Plugins/RpcServer/Settings.cs +++ b/src/Plugins/RpcServer/RcpServerSettings.cs @@ -1,6 +1,6 @@ // Copyright (C) 2015-2025 The Neo Project. // -// Settings.cs file belongs to the neo project and is free +// RcpServerSettings.cs file belongs to the neo project and is free // software distributed under the MIT software license, see the // accompanying file LICENSE in the main directory of the // repository or http://www.opensource.org/licenses/mit-license.php @@ -18,17 +18,20 @@ namespace Neo.Plugins.RpcServer { - class Settings : PluginSettings + class RpcServerSettings : IPluginSettings { - public IReadOnlyList Servers { get; init; } + public IReadOnlyList Servers { get; init; } - public Settings(IConfigurationSection section) : base(section) + public UnhandledExceptionPolicy ExceptionPolicy { get; } + + public RpcServerSettings(IConfigurationSection section) { - Servers = section.GetSection(nameof(Servers)).GetChildren().Select(p => RpcServerSettings.Load(p)).ToArray(); + Servers = [.. section.GetSection(nameof(Servers)).GetChildren().Select(RpcServersSettings.Load)]; + ExceptionPolicy = section.GetValue("UnhandledExceptionPolicy", UnhandledExceptionPolicy.Ignore); } } - public record RpcServerSettings + public record RpcServersSettings { public uint Network { get; init; } public IPAddress BindAddress { get; init; } @@ -55,7 +58,7 @@ public record RpcServerSettings public TimeSpan SessionExpirationTime { get; init; } public int FindStoragePageSize { get; init; } - public static RpcServerSettings Default { get; } = new RpcServerSettings + public static RpcServersSettings Default { get; } = new RpcServersSettings { Network = 5195086u, BindAddress = IPAddress.None, @@ -78,7 +81,7 @@ public record RpcServerSettings FindStoragePageSize = 50 }; - public static RpcServerSettings Load(IConfigurationSection section) => new() + public static RpcServersSettings Load(IConfigurationSection section) => new() { Network = section.GetValue("Network", Default.Network), BindAddress = IPAddress.Parse(section.GetSection("BindAddress").Value), diff --git a/src/Plugins/RpcServer/RpcServer.cs b/src/Plugins/RpcServer/RpcServer.cs index ef957406aa..a776fad808 100644 --- a/src/Plugins/RpcServer/RpcServer.cs +++ b/src/Plugins/RpcServer/RpcServer.cs @@ -41,7 +41,7 @@ public partial class RpcServer : IDisposable private readonly Dictionary _methodsWithParams = new(); private IWebHost host; - private RpcServerSettings settings; + private RpcServersSettings settings; private readonly NeoSystem system; private readonly LocalNode localNode; @@ -49,7 +49,7 @@ public partial class RpcServer : IDisposable private readonly byte[] _rpcUser; private readonly byte[] _rpcPass; - public RpcServer(NeoSystem system, RpcServerSettings settings) + public RpcServer(NeoSystem system, RpcServersSettings settings) { this.system = system; this.settings = settings; @@ -225,7 +225,7 @@ public void StartRpcServer() host.Start(); } - internal void UpdateSettings(RpcServerSettings settings) + internal void UpdateSettings(RpcServersSettings settings) { this.settings = settings; } diff --git a/src/Plugins/RpcServer/RpcServerPlugin.cs b/src/Plugins/RpcServer/RpcServerPlugin.cs index e537e5de12..70300ea131 100644 --- a/src/Plugins/RpcServer/RpcServerPlugin.cs +++ b/src/Plugins/RpcServer/RpcServerPlugin.cs @@ -19,7 +19,7 @@ public class RpcServerPlugin : Plugin public override string Name => "RpcServer"; public override string Description => "Enables RPC for the node"; - private Settings settings; + private RpcServerSettings settings; private static readonly Dictionary servers = new(); private static readonly Dictionary> handlers = new(); @@ -28,8 +28,8 @@ public class RpcServerPlugin : Plugin protected override void Configure() { - settings = new Settings(GetConfiguration()); - foreach (RpcServerSettings s in settings.Servers) + settings = new RpcServerSettings(GetConfiguration()); + foreach (var s in settings.Servers) if (servers.TryGetValue(s.Network, out RpcServer server)) server.UpdateSettings(s); } @@ -43,7 +43,7 @@ public override void Dispose() protected override void OnSystemLoaded(NeoSystem system) { - RpcServerSettings s = settings.Servers.FirstOrDefault(p => p.Network == system.Settings.Network); + var s = settings.Servers.FirstOrDefault(p => p.Network == system.Settings.Network); if (s is null) return; if (s.EnableCors && string.IsNullOrEmpty(s.RpcUser) == false && s.AllowOrigins.Length == 0) diff --git a/src/Plugins/SignClient/SignClient.cs b/src/Plugins/SignClient/SignClient.cs index ad54ac6426..fd37f02095 100644 --- a/src/Plugins/SignClient/SignClient.cs +++ b/src/Plugins/SignClient/SignClient.cs @@ -46,7 +46,7 @@ public class SignClient : Plugin, ISigner public SignClient() { } - public SignClient(Settings settings) + public SignClient(SignSettings settings) { Reset(settings); } @@ -66,7 +66,7 @@ private void Reset(string name, SecureSign.SecureSignClient? client) if (!string.IsNullOrEmpty(_name)) SignerManager.RegisterSigner(_name, this); } - private ServiceConfig GetServiceConfig(Settings settings) + private ServiceConfig GetServiceConfig(SignSettings settings) { var methodConfig = new MethodConfig { @@ -93,7 +93,7 @@ private ServiceConfig GetServiceConfig(Settings settings) return new ServiceConfig { MethodConfigs = { methodConfig } }; } - private void Reset(Settings settings) + private void Reset(SignSettings settings) { // _settings = settings; var serviceConfig = GetServiceConfig(settings); @@ -332,7 +332,7 @@ public ReadOnlyMemory SignBlock(Block block, ECPoint publicKey, uint netwo protected override void Configure() { var config = GetConfiguration(); - if (config is not null) Reset(new Settings(config)); + if (config is not null) Reset(new SignSettings(config)); } /// diff --git a/src/Plugins/SignClient/Settings.cs b/src/Plugins/SignClient/SignSettings.cs similarity index 84% rename from src/Plugins/SignClient/Settings.cs rename to src/Plugins/SignClient/SignSettings.cs index 4bb58e4382..c6da1a971a 100644 --- a/src/Plugins/SignClient/Settings.cs +++ b/src/Plugins/SignClient/SignSettings.cs @@ -1,6 +1,6 @@ // Copyright (C) 2015-2025 The Neo Project. // -// Settings.cs file belongs to the neo project and is free +// SignSettings.cs file belongs to the neo project and is free // software distributed under the MIT software license, see the // accompanying file LICENSE in the main directory of the // repository or http://www.opensource.org/licenses/mit-license.php @@ -13,7 +13,7 @@ namespace Neo.Plugins.SignClient { - public class Settings : PluginSettings + public class SignSettings : IPluginSettings { public const string SectionName = "PluginConfiguration"; private const string DefaultEndpoint = "http://127.0.0.1:9991"; @@ -21,28 +21,29 @@ public class Settings : PluginSettings /// /// The name of the sign client(i.e. Signer). /// - public readonly string Name; + public string Name { get; } /// /// The host of the sign client(i.e. Signer). /// The "Endpoint" should be "vsock://contextId:port" if use vsock. /// The "Endpoint" should be "http://host:port" or "https://host:port" if use tcp. /// - public readonly string Endpoint; + public string Endpoint { get; } /// /// Create a new settings instance from the configuration section. /// /// The configuration section. /// If the endpoint type or endpoint is invalid. - public Settings(IConfigurationSection section) : base(section) + public SignSettings(IConfigurationSection section) { Name = section.GetValue("Name", "SignClient"); Endpoint = section.GetValue("Endpoint", DefaultEndpoint); // Only support local host at present + ExceptionPolicy = section.GetValue("UnhandledExceptionPolicy", UnhandledExceptionPolicy.Ignore); _ = GetVsockAddress(); // for check the endpoint is valid } - public static Settings Default + public static SignSettings Default { get { @@ -54,10 +55,12 @@ public static Settings Default }) .Build() .GetSection(SectionName); - return new Settings(section); + return new SignSettings(section); } } + public UnhandledExceptionPolicy ExceptionPolicy { get; } + /// /// Get the vsock address from the endpoint. /// diff --git a/src/Plugins/StateService/StatePlugin.cs b/src/Plugins/StateService/StatePlugin.cs index 0118e20efb..981b525acd 100644 --- a/src/Plugins/StateService/StatePlugin.cs +++ b/src/Plugins/StateService/StatePlugin.cs @@ -39,7 +39,7 @@ public class StatePlugin : Plugin, ICommittingHandler, ICommittedHandler, IWalle public override string Description => "Enables MPT for the node"; public override string ConfigFile => System.IO.Path.Combine(RootPath, "StateService.json"); - protected override UnhandledExceptionPolicy ExceptionPolicy => Settings.Default.ExceptionPolicy; + protected override UnhandledExceptionPolicy ExceptionPolicy => StateServiceSettings.Default.ExceptionPolicy; internal IActorRef Store; internal IActorRef Verifier; @@ -58,16 +58,16 @@ public StatePlugin() protected override void Configure() { - Settings.Load(GetConfiguration()); + StateServiceSettings.Load(GetConfiguration()); } protected override void OnSystemLoaded(NeoSystem system) { - if (system.Settings.Network != Settings.Default.Network) return; + if (system.Settings.Network != StateServiceSettings.Default.Network) return; _system = system; - Store = _system.ActorSystem.ActorOf(StateStore.Props(this, string.Format(Settings.Default.Path, system.Settings.Network.ToString("X8")))); + Store = _system.ActorSystem.ActorOf(StateStore.Props(this, string.Format(StateServiceSettings.Default.Path, system.Settings.Network.ToString("X8")))); _system.ServiceAdded += ((IServiceAddedHandler)this).NeoSystem_ServiceAdded_Handler; - RpcServerPlugin.RegisterMethods(this, Settings.Default.Network); + RpcServerPlugin.RegisterMethods(this, StateServiceSettings.Default.Network); } void IServiceAddedHandler.NeoSystem_ServiceAdded_Handler(object sender, object service) @@ -76,7 +76,7 @@ void IServiceAddedHandler.NeoSystem_ServiceAdded_Handler(object sender, object s { walletProvider = service as IWalletProvider; _system.ServiceAdded -= ((IServiceAddedHandler)this).NeoSystem_ServiceAdded_Handler; - if (Settings.Default.AutoVerify) + if (StateServiceSettings.Default.AutoVerify) { walletProvider.WalletChanged += ((IWalletChangedHandler)this).IWalletProvider_WalletChanged_Handler; } @@ -101,7 +101,7 @@ public override void Dispose() void ICommittingHandler.Blockchain_Committing_Handler(NeoSystem system, Block block, DataCache snapshot, IReadOnlyList applicationExecutedList) { - if (system.Settings.Network != Settings.Default.Network) return; + if (system.Settings.Network != StateServiceSettings.Default.Network) return; StateStore.Singleton.UpdateLocalStateRootSnapshot(block.Index, snapshot.GetChangeSet() .Where(p => p.Value.State != TrackState.None && p.Key.Id != NativeContract.Ledger.Id) @@ -110,13 +110,13 @@ void ICommittingHandler.Blockchain_Committing_Handler(NeoSystem system, Block bl void ICommittedHandler.Blockchain_Committed_Handler(NeoSystem system, Block block) { - if (system.Settings.Network != Settings.Default.Network) return; + if (system.Settings.Network != StateServiceSettings.Default.Network) return; StateStore.Singleton.UpdateLocalStateRoot(block.Index); } private void CheckNetwork() { - var network = Settings.Default.Network; + var network = StateServiceSettings.Default.Network; if (_system is null || _system.Settings.Network != network) throw new InvalidOperationException($"Network doesn't match: {_system?.Settings.Network} != {network}"); } @@ -170,7 +170,7 @@ private void OnGetStateHeight() [ConsoleCommand("get proof", Category = "StateService", Description = "Get proof of key and contract hash")] private void OnGetProof(UInt256 rootHash, UInt160 scriptHash, string key) { - if (_system is null || _system.Settings.Network != Settings.Default.Network) throw new InvalidOperationException("Network doesn't match"); + if (_system is null || _system.Settings.Network != StateServiceSettings.Default.Network) throw new InvalidOperationException("Network doesn't match"); try { ConsoleHelper.Info("Proof: ", GetProof(rootHash, scriptHash, Convert.FromBase64String(key))); @@ -233,7 +233,7 @@ private string GetProof(Trie trie, StorageKey skey) private string GetProof(UInt256 rootHash, UInt160 scriptHash, byte[] key) { - (!Settings.Default.FullState && StateStore.Singleton.CurrentLocalRootHash != rootHash).False_Or(RpcError.UnsupportedState); + (!StateServiceSettings.Default.FullState && StateStore.Singleton.CurrentLocalRootHash != rootHash).False_Or(RpcError.UnsupportedState); using var store = StateStore.Singleton.GetStoreSnapshot(); var trie = new Trie(store, rootHash); @@ -306,7 +306,7 @@ private StorageKey ParseStorageKey(byte[] data) public JToken FindStates(JArray _params) { var rootHash = Result.Ok_Or(() => UInt256.Parse(_params[0].AsString()), RpcError.InvalidParams.WithData($"Invalid root hash: {_params[0]}")); - (!Settings.Default.FullState && StateStore.Singleton.CurrentLocalRootHash != rootHash).False_Or(RpcError.UnsupportedState); + (!StateServiceSettings.Default.FullState && StateStore.Singleton.CurrentLocalRootHash != rootHash).False_Or(RpcError.UnsupportedState); var scriptHash = Result.Ok_Or(() => UInt160.Parse(_params[1].AsString()), RpcError.InvalidParams.WithData($"Invalid script hash: {_params[1]}")); var prefix = Result.Ok_Or(() => Convert.FromBase64String(_params[2].AsString()), RpcError.InvalidParams.WithData($"Invalid prefix: {_params[2]}")); @@ -314,11 +314,11 @@ public JToken FindStates(JArray _params) if (3 < _params.Count) key = Result.Ok_Or(() => Convert.FromBase64String(_params[3].AsString()), RpcError.InvalidParams.WithData($"Invalid key: {_params[3]}")); - int count = Settings.Default.MaxFindResultItems; + int count = StateServiceSettings.Default.MaxFindResultItems; if (4 < _params.Count) count = Result.Ok_Or(() => int.Parse(_params[4].AsString()), RpcError.InvalidParams.WithData($"Invalid count: {_params[4]}")); - if (Settings.Default.MaxFindResultItems < count) - count = Settings.Default.MaxFindResultItems; + if (StateServiceSettings.Default.MaxFindResultItems < count) + count = StateServiceSettings.Default.MaxFindResultItems; using var store = StateStore.Singleton.GetStoreSnapshot(); var trie = new Trie(store, rootHash); @@ -367,7 +367,7 @@ public JToken FindStates(JArray _params) public JToken GetState(JArray _params) { var rootHash = Result.Ok_Or(() => UInt256.Parse(_params[0].AsString()), RpcError.InvalidParams.WithData($"Invalid root hash: {_params[0]}")); - (!Settings.Default.FullState && StateStore.Singleton.CurrentLocalRootHash != rootHash).False_Or(RpcError.UnsupportedState); + (!StateServiceSettings.Default.FullState && StateStore.Singleton.CurrentLocalRootHash != rootHash).False_Or(RpcError.UnsupportedState); var scriptHash = Result.Ok_Or(() => UInt160.Parse(_params[1].AsString()), RpcError.InvalidParams.WithData($"Invalid script hash: {_params[1]}")); var key = Result.Ok_Or(() => Convert.FromBase64String(_params[2].AsString()), RpcError.InvalidParams.WithData($"Invalid key: {_params[2]}")); diff --git a/src/Plugins/StateService/Settings.cs b/src/Plugins/StateService/StateServiceSettings.cs similarity index 68% rename from src/Plugins/StateService/Settings.cs rename to src/Plugins/StateService/StateServiceSettings.cs index a9b96590ed..d2aad3b590 100644 --- a/src/Plugins/StateService/Settings.cs +++ b/src/Plugins/StateService/StateServiceSettings.cs @@ -1,6 +1,6 @@ // Copyright (C) 2015-2025 The Neo Project. // -// Settings.cs file belongs to the neo project and is free +// StateServiceSettings.cs file belongs to the neo project and is free // software distributed under the MIT software license, see the // accompanying file LICENSE in the main directory of the // repository or http://www.opensource.org/licenses/mit-license.php @@ -13,7 +13,7 @@ namespace Neo.Plugins.StateService { - internal class Settings : PluginSettings + internal class StateServiceSettings : IPluginSettings { public string Path { get; } public bool FullState { get; } @@ -21,20 +21,23 @@ internal class Settings : PluginSettings public bool AutoVerify { get; } public int MaxFindResultItems { get; } - public static Settings Default { get; private set; } + public static StateServiceSettings Default { get; private set; } - private Settings(IConfigurationSection section) : base(section) + public UnhandledExceptionPolicy ExceptionPolicy { get; } + + private StateServiceSettings(IConfigurationSection section) { Path = section.GetValue("Path", "Data_MPT_{0}"); FullState = section.GetValue("FullState", false); Network = section.GetValue("Network", 5195086u); AutoVerify = section.GetValue("AutoVerify", false); MaxFindResultItems = section.GetValue("MaxFindResultItems", 100); + ExceptionPolicy = section.GetValue("UnhandledExceptionPolicy", UnhandledExceptionPolicy.StopPlugin); } public static void Load(IConfigurationSection section) { - Default = new Settings(section); + Default = new StateServiceSettings(section); } } } diff --git a/src/Plugins/StateService/Storage/StateSnapshot.cs b/src/Plugins/StateService/Storage/StateSnapshot.cs index 60af6f29ce..fe9faf1122 100644 --- a/src/Plugins/StateService/Storage/StateSnapshot.cs +++ b/src/Plugins/StateService/Storage/StateSnapshot.cs @@ -25,7 +25,7 @@ class StateSnapshot : IDisposable public StateSnapshot(IStore store) { _snapshot = store.GetSnapshot(); - Trie = new Trie(_snapshot, CurrentLocalRootHash(), Settings.Default.FullState); + Trie = new Trie(_snapshot, CurrentLocalRootHash(), StateServiceSettings.Default.FullState); } public StateRoot GetStateRoot(uint index) diff --git a/src/Plugins/StorageDumper/StorageDumper.cs b/src/Plugins/StorageDumper/StorageDumper.cs index 21995c1254..047407d965 100644 --- a/src/Plugins/StorageDumper/StorageDumper.cs +++ b/src/Plugins/StorageDumper/StorageDumper.cs @@ -30,7 +30,7 @@ public class StorageDumper : Plugin, ICommittingHandler, ICommittedHandler /// private JObject? _currentBlock; private string? _lastCreateDirectory; - protected override UnhandledExceptionPolicy ExceptionPolicy => Settings.Default?.ExceptionPolicy ?? UnhandledExceptionPolicy.Ignore; + protected override UnhandledExceptionPolicy ExceptionPolicy => StorageSettings.Default?.ExceptionPolicy ?? UnhandledExceptionPolicy.Ignore; public override string Description => "Exports Neo-CLI status data"; @@ -50,7 +50,7 @@ public override void Dispose() protected override void Configure() { - Settings.Load(GetConfiguration()); + StorageSettings.Load(GetConfiguration()); } protected override void OnSystemLoaded(NeoSystem system) @@ -74,7 +74,7 @@ internal void OnDumpStorage(UInt160? contractHash = null) prefix = BitConverter.GetBytes(contract.Id); } var states = _system.StoreView.Find(prefix); - JArray array = new JArray(states.Where(p => !Settings.Default!.Exclude.Contains(p.Key.Id)).Select(p => new JObject + JArray array = new JArray(states.Where(p => !StorageSettings.Default!.Exclude.Contains(p.Key.Id)).Select(p => new JObject { ["key"] = Convert.ToBase64String(p.Key.ToArray()), ["value"] = Convert.ToBase64String(p.Value.ToArray()) @@ -95,13 +95,13 @@ void ICommittingHandler.Blockchain_Committing_Handler(NeoSystem system, Block bl private void OnPersistStorage(uint network, DataCache snapshot) { var blockIndex = NativeContract.Ledger.CurrentIndex(snapshot); - if (blockIndex >= Settings.Default!.HeightToBegin) + if (blockIndex >= StorageSettings.Default!.HeightToBegin) { var stateChangeArray = new JArray(); foreach (var trackable in snapshot.GetChangeSet()) { - if (Settings.Default.Exclude.Contains(trackable.Key.Id)) + if (StorageSettings.Default.Exclude.Contains(trackable.Key.Id)) continue; var state = new JObject(); switch (trackable.Value.State) @@ -156,10 +156,10 @@ private void InitFileWriter(uint network, IReadOnlyStore snapshot) { uint blockIndex = NativeContract.Ledger.CurrentIndex(snapshot); if (_writer == null - || blockIndex % Settings.Default!.BlockCacheSize == 0) + || blockIndex % StorageSettings.Default!.BlockCacheSize == 0) { string path = GetOrCreateDirectory(network, blockIndex); - var filepart = (blockIndex / Settings.Default!.BlockCacheSize) * Settings.Default.BlockCacheSize; + var filepart = (blockIndex / StorageSettings.Default!.BlockCacheSize) * StorageSettings.Default.BlockCacheSize; path = $"{path}/dump-block-{filepart}.dump"; if (_writer != null) { @@ -182,7 +182,7 @@ private string GetOrCreateDirectory(uint network, uint blockIndex) private string GetDirectoryPath(uint network, uint blockIndex) { - uint folder = (blockIndex / Settings.Default!.StoragePerFolder) * Settings.Default.StoragePerFolder; + uint folder = (blockIndex / StorageSettings.Default!.StoragePerFolder) * StorageSettings.Default.StoragePerFolder; return $"./StorageDumper_{network}/BlockStorage_{folder}"; } diff --git a/src/Plugins/StorageDumper/Settings.cs b/src/Plugins/StorageDumper/StorageSettings.cs similarity index 76% rename from src/Plugins/StorageDumper/Settings.cs rename to src/Plugins/StorageDumper/StorageSettings.cs index 5dcfd95775..b5009b43e0 100644 --- a/src/Plugins/StorageDumper/Settings.cs +++ b/src/Plugins/StorageDumper/StorageSettings.cs @@ -1,6 +1,6 @@ // Copyright (C) 2015-2025 The Neo Project. // -// Settings.cs file belongs to the neo project and is free +// StorageSettings.cs file belongs to the neo project and is free // software distributed under the MIT software license, see the // accompanying file LICENSE in the main directory of the // repository or http://www.opensource.org/licenses/mit-license.php @@ -14,7 +14,7 @@ namespace Neo.Plugins.StorageDumper { - internal class Settings : PluginSettings + internal class StorageSettings : IPluginSettings { /// /// Amount of storages states (heights) to be dump in a given json file @@ -30,9 +30,11 @@ internal class Settings : PluginSettings public uint StoragePerFolder { get; } public IReadOnlyList Exclude { get; } - public static Settings? Default { get; private set; } + public static StorageSettings? Default { get; private set; } - private Settings(IConfigurationSection section) : base(section) + public UnhandledExceptionPolicy ExceptionPolicy { get; } + + private StorageSettings(IConfigurationSection section) { // Geting settings for storage changes state dumper BlockCacheSize = section.GetValue("BlockCacheSize", 1000u); @@ -41,11 +43,12 @@ private Settings(IConfigurationSection section) : base(section) Exclude = section.GetSection("Exclude").Exists() ? section.GetSection("Exclude").GetChildren().Select(p => int.Parse(p.Value!)).ToArray() : new[] { NativeContract.Ledger.Id }; + ExceptionPolicy = section.GetValue("UnhandledExceptionPolicy", UnhandledExceptionPolicy.Ignore); } public static void Load(IConfigurationSection section) { - Default = new Settings(section); + Default = new StorageSettings(section); } } } diff --git a/tests/Neo.Plugins.ApplicationLogs.Tests/UT_LogReader.cs b/tests/Neo.Plugins.ApplicationLogs.Tests/UT_LogReader.cs index 1346b6b5d3..7b1615429a 100644 --- a/tests/Neo.Plugins.ApplicationLogs.Tests/UT_LogReader.cs +++ b/tests/Neo.Plugins.ApplicationLogs.Tests/UT_LogReader.cs @@ -30,7 +30,7 @@ using System.Linq; using System.Threading.Tasks; using static Neo.Plugins.ApplicationsLogs.Tests.UT_LogReader; -using Settings = Neo.Plugins.ApplicationLogs.Settings; +using ApplicationLogsSettings = Neo.Plugins.ApplicationLogs.ApplicationLogsSettings; namespace Neo.Plugins.ApplicationsLogs.Tests { @@ -69,7 +69,7 @@ public NeoSystemFixture() _memoryStoreProvider = new TestMemoryStoreProvider(_memoryStore); logReader = new LogReader(); Plugin.Plugins.Add(logReader); // initialize before NeoSystem to let NeoSystem load the plugin - _neoSystem = new NeoSystem(TestProtocolSettings.SoleNode with { Network = Settings.Default.Network }, _memoryStoreProvider); + _neoSystem = new NeoSystem(TestProtocolSettings.SoleNode with { Network = ApplicationLogsSettings.Default.Network }, _memoryStoreProvider); _walletAccount = _wallet.Import("KxuRSsHgJMb3AMSN6B9P3JHNGMFtxmuimqgR9MmXPcv3CLLfusTd"); NeoSystem system = _neoSystem; @@ -85,7 +85,7 @@ public NeoSystemFixture() SystemFee = 1000_0000, } ]; - byte[] signature = txs[0].Sign(_walletAccount.GetKey(), Settings.Default.Network); + byte[] signature = txs[0].Sign(_walletAccount.GetKey(), ApplicationLogsSettings.Default.Network); txs[0].Witnesses = [new Witness { InvocationScript = new byte[] { (byte)OpCode.PUSHDATA1, (byte)signature.Length }.Concat(signature).ToArray(), @@ -105,7 +105,7 @@ public NeoSystemFixture() Transactions = txs, }; block.Header.MerkleRoot ??= MerkleTree.ComputeRoot(block.Transactions.Select(t => t.Hash).ToArray()); - signature = block.Sign(_walletAccount.GetKey(), Settings.Default.Network); + signature = block.Sign(_walletAccount.GetKey(), ApplicationLogsSettings.Default.Network); block.Header.Witness = new Witness { InvocationScript = new byte[] { (byte)OpCode.PUSHDATA1, (byte)signature.Length }.Concat(signature).ToArray(), diff --git a/tests/Neo.Plugins.DBFTPlugin.Tests/MockBlockchain.cs b/tests/Neo.Plugins.DBFTPlugin.Tests/MockBlockchain.cs index 317c2706d7..e12ac35659 100644 --- a/tests/Neo.Plugins.DBFTPlugin.Tests/MockBlockchain.cs +++ b/tests/Neo.Plugins.DBFTPlugin.Tests/MockBlockchain.cs @@ -46,7 +46,7 @@ internal static void ResetStore() TheNeoSystem.Blockchain.Ask(new Blockchain.Initialize()).Wait(); } - internal static Settings CreateDefaultSettings() + internal static DbftSettings CreateDefaultSettings() { var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddInMemoryCollection(new Dictionary @@ -60,7 +60,7 @@ internal static Settings CreateDefaultSettings() }) .Build(); - return new Settings(config.GetSection("ApplicationConfiguration:DBFTPlugin")); + return new DbftSettings(config.GetSection("ApplicationConfiguration:DBFTPlugin")); } internal static DataCache GetTestSnapshot() diff --git a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Failures.cs b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Failures.cs index 2cbb3aba93..7da73ed19b 100644 --- a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Failures.cs +++ b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Failures.cs @@ -44,7 +44,7 @@ public class UT_DBFT_Failures : TestKit private MockWallet[] testWallets; private IActorRef[] consensusServices; private MemoryStore memoryStore; - private Settings settings; + private DbftSettings settings; [TestInitialize] public void Setup() diff --git a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_MessageFlow.cs b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_MessageFlow.cs index 5077f3d3ae..bb04e472f2 100644 --- a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_MessageFlow.cs +++ b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_MessageFlow.cs @@ -52,7 +52,7 @@ public class UT_DBFT_MessageFlow : TestKit private const int ValidatorCount = 4; // Use 4 validators for faster testing private NeoSystem neoSystem; private MemoryStore memoryStore; - private Settings settings; + private DbftSettings settings; private MockWallet[] testWallets; private IActorRef[] consensusServices; private ConsensusTestUtilities testHelper; diff --git a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_NormalFlow.cs b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_NormalFlow.cs index 5a4ec42654..b6105a9ab8 100644 --- a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_NormalFlow.cs +++ b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_NormalFlow.cs @@ -44,7 +44,7 @@ public class UT_DBFT_NormalFlow : TestKit private MockWallet[] testWallets; private IActorRef[] consensusServices; private MemoryStore memoryStore; - private Settings settings; + private DbftSettings settings; [TestInitialize] public void Setup() diff --git a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Performance.cs b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Performance.cs index 24e71abb63..f5380213d9 100644 --- a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Performance.cs +++ b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Performance.cs @@ -41,7 +41,7 @@ public class UT_DBFT_Performance : TestKit private TestProbe blockchain; private TestProbe txRouter; private MemoryStore memoryStore; - private Settings settings; + private DbftSettings settings; [TestInitialize] public void Setup() diff --git a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Recovery.cs b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Recovery.cs index 3e923eda69..f00a787e62 100644 --- a/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Recovery.cs +++ b/tests/Neo.Plugins.DBFTPlugin.Tests/UT_DBFT_Recovery.cs @@ -44,7 +44,7 @@ public class UT_DBFT_Recovery : TestKit private MockWallet[] testWallets; private IActorRef[] consensusServices; private MemoryStore memoryStore; - private Settings settings; + private DbftSettings settings; [TestInitialize] public void Setup() diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcErrorHandling.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcErrorHandling.cs index af027c5f16..b69f06fa7a 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcErrorHandling.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcErrorHandling.cs @@ -44,7 +44,7 @@ public void TestSetup() _memoryStore = new MemoryStore(); _memoryStoreProvider = new TestMemoryStoreProvider(_memoryStore); _neoSystem = new NeoSystem(TestProtocolSettings.SoleNode, _memoryStoreProvider); - _rpcServer = new RpcServer(_neoSystem, RpcServerSettings.Default); + _rpcServer = new RpcServer(_neoSystem, RpcServersSettings.Default); _wallet = TestUtils.GenerateTestWallet("test-wallet.json"); _walletAccount = _wallet.CreateAccount(); diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs index 306caaa910..3aa5bbf80e 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Blockchain.cs @@ -442,7 +442,7 @@ public void TestFindStorage() .ForEach(i => TestUtils.StorageItemAdd(snapshot, contractState.Id, [0x01, (byte)i], [0x02])); snapshot.Commit(); var result4 = _rpcServer.FindStorage(new(contractState.Hash), Convert.ToBase64String(new byte[] { 0x01 }), 0); - Assert.AreEqual(RpcServerSettings.Default.FindStoragePageSize, result4["next"].AsNumber()); + Assert.AreEqual(RpcServersSettings.Default.FindStoragePageSize, result4["next"].AsNumber()); Assert.IsTrue(result4["truncated"].AsBoolean()); } @@ -453,7 +453,7 @@ public void TestFindStorage_Pagination() var contractState = TestUtils.GetContract(); snapshot.AddContract(contractState.Hash, contractState); var prefix = new byte[] { 0xAA }; - int totalItems = RpcServerSettings.Default.FindStoragePageSize + 5; + int totalItems = RpcServersSettings.Default.FindStoragePageSize + 5; for (int i = 0; i < totalItems; i++) { @@ -466,9 +466,9 @@ public void TestFindStorage_Pagination() // Get first page var resultPage1 = _rpcServer.FindStorage(new(contractState.Hash), Convert.ToBase64String(prefix), 0); Assert.IsTrue(resultPage1["truncated"].AsBoolean()); - Assert.AreEqual(RpcServerSettings.Default.FindStoragePageSize, ((JArray)resultPage1["results"]).Count); + Assert.AreEqual(RpcServersSettings.Default.FindStoragePageSize, ((JArray)resultPage1["results"]).Count); int nextIndex = (int)resultPage1["next"].AsNumber(); - Assert.AreEqual(RpcServerSettings.Default.FindStoragePageSize, nextIndex); + Assert.AreEqual(RpcServersSettings.Default.FindStoragePageSize, nextIndex); // Get second page var resultPage2 = _rpcServer.FindStorage(new(contractState.Hash), Convert.ToBase64String(prefix), nextIndex); diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs index 341a75cf6c..9a087720e7 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.Node.cs @@ -44,7 +44,7 @@ public void TestGetPeers() localNode.AddPeers(new List() { new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 11332) }); localNode.AddPeers(new List() { new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 12332) }); localNode.AddPeers(new List() { new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 13332) }); - var rpcServer = new RpcServer(neoSystem, RpcServerSettings.Default); + var rpcServer = new RpcServer(neoSystem, RpcServersSettings.Default); var result = rpcServer.GetPeers(); Assert.IsInstanceOfType(result, typeof(JObject)); @@ -62,7 +62,7 @@ public void TestGetPeers_NoUnconnected() var settings = TestProtocolSettings.SoleNode; var memoryStoreProvider = new TestMemoryStoreProvider(new MemoryStore()); var neoSystem = new NeoSystem(settings, memoryStoreProvider); - var rpcServer = new RpcServer(neoSystem, RpcServerSettings.Default); + var rpcServer = new RpcServer(neoSystem, RpcServersSettings.Default); // Get peers immediately (should have no unconnected) var result = rpcServer.GetPeers(); @@ -81,7 +81,7 @@ public void TestGetPeers_NoConnected() var settings = TestProtocolSettings.SoleNode; var memoryStoreProvider = new TestMemoryStoreProvider(new MemoryStore()); var neoSystem = new NeoSystem(settings, memoryStoreProvider); - var rpcServer = new RpcServer(neoSystem, RpcServerSettings.Default); + var rpcServer = new RpcServer(neoSystem, RpcServersSettings.Default); // Get peers immediately (should have no connected) var result = rpcServer.GetPeers(); diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.SmartContract.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.SmartContract.cs index ef46e6c763..3fbd7607b8 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.SmartContract.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.SmartContract.cs @@ -206,7 +206,7 @@ public void TestInvokeScript_GasLimitExceeded() var scriptBase64 = Convert.ToBase64String(loopScript); // Use a temporary RpcServer with a very low MaxGasInvoke setting - var lowGasSettings = RpcServerSettings.Default with + var lowGasSettings = RpcServersSettings.Default with { MaxGasInvoke = 1_000_000 // Low gas limit (1 GAS = 100,000,000 datoshi) }; @@ -432,7 +432,7 @@ public void TestTraverseIterator() public void TestIteratorMethods_SessionsDisabled() { // Use a temporary RpcServer with sessions disabled - var sessionsDisabledSettings = RpcServerSettings.Default with { SessionEnabled = false }; + var sessionsDisabledSettings = RpcServersSettings.Default with { SessionEnabled = false }; var tempRpcServer = new RpcServer(_neoSystem, sessionsDisabledSettings); var randomSessionId = Guid.NewGuid().ToString(); diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs index 70f1cf3c25..97479adf4b 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs @@ -30,7 +30,7 @@ namespace Neo.Plugins.RpcServer.Tests public partial class UT_RpcServer { private NeoSystem _neoSystem; - private RpcServerSettings _rpcServerSettings; + private RpcServersSettings _rpcServerSettings; private RpcServer _rpcServer; private TestMemoryStoreProvider _memoryStoreProvider; private MemoryStore _memoryStore; @@ -46,7 +46,7 @@ public void TestSetup() _memoryStore = new MemoryStore(); _memoryStoreProvider = new TestMemoryStoreProvider(_memoryStore); _neoSystem = new NeoSystem(TestProtocolSettings.SoleNode, _memoryStoreProvider); - _rpcServerSettings = RpcServerSettings.Default with + _rpcServerSettings = RpcServersSettings.Default with { SessionEnabled = true, SessionExpirationTime = TimeSpan.FromSeconds(0.3), @@ -92,7 +92,7 @@ public void TestCheckAuth() { var memoryStoreProvider = new TestMemoryStoreProvider(new MemoryStore()); var neoSystem = new NeoSystem(TestProtocolSettings.SoleNode, memoryStoreProvider); - var rpcServerSettings = RpcServerSettings.Default with + var rpcServerSettings = RpcServersSettings.Default with { SessionEnabled = true, SessionExpirationTime = TimeSpan.FromSeconds(0.3), diff --git a/tests/Neo.Plugins.SignClient.Tests/UT_SignClient.cs b/tests/Neo.Plugins.SignClient.Tests/UT_SignClient.cs index 1709ea4e0f..34eaef598b 100644 --- a/tests/Neo.Plugins.SignClient.Tests/UT_SignClient.cs +++ b/tests/Neo.Plugins.SignClient.Tests/UT_SignClient.cs @@ -55,12 +55,12 @@ private static SignClient NewClient(Block? block, ExtensiblePayload? payload) var section = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { - [Settings.SectionName + ":Name"] = "SignClient", - [Settings.SectionName + ":Endpoint"] = endpoint, + [SignSettings.SectionName + ":Name"] = "SignClient", + [SignSettings.SectionName + ":Endpoint"] = endpoint, }) .Build() - .GetSection(Settings.SectionName); - return new SignClient(new Settings(section)); + .GetSection(SignSettings.SectionName); + return new SignClient(new SignSettings(section)); } var mockClient = new Mock(); diff --git a/tests/Neo.Plugins.SignClient.Tests/UT_Vsock.cs b/tests/Neo.Plugins.SignClient.Tests/UT_Vsock.cs index 18828b69f0..c686e30e46 100644 --- a/tests/Neo.Plugins.SignClient.Tests/UT_Vsock.cs +++ b/tests/Neo.Plugins.SignClient.Tests/UT_Vsock.cs @@ -29,7 +29,7 @@ public void TestGetVsockAddress() .Build() .GetSection("PluginConfiguration"); - var settings = new Settings(section); + var settings = new SignSettings(section); Assert.AreEqual(address, settings.GetVsockAddress()); section = new ConfigurationBuilder() @@ -39,7 +39,7 @@ public void TestGetVsockAddress() }) .Build() .GetSection("PluginConfiguration"); - Assert.IsNull(new Settings(section).GetVsockAddress()); + Assert.IsNull(new SignSettings(section).GetVsockAddress()); } [TestMethod] @@ -52,7 +52,7 @@ public void TestInvalidEndpoint() }) .Build() .GetSection("PluginConfiguration"); - Assert.ThrowsExactly(() => _ = new Settings(section).GetVsockAddress()); + Assert.ThrowsExactly(() => _ = new SignSettings(section).GetVsockAddress()); section = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary @@ -61,7 +61,7 @@ public void TestInvalidEndpoint() }) .Build() .GetSection("PluginConfiguration"); - Assert.ThrowsExactly(() => _ = new Settings(section).GetVsockAddress()); + Assert.ThrowsExactly(() => _ = new SignSettings(section).GetVsockAddress()); } } } diff --git a/tests/Neo.UnitTests/Plugins/TestPlugin.cs b/tests/Neo.UnitTests/Plugins/TestPlugin.cs index bb05024579..b31df5a5f2 100644 --- a/tests/Neo.UnitTests/Plugins/TestPlugin.cs +++ b/tests/Neo.UnitTests/Plugins/TestPlugin.cs @@ -20,12 +20,15 @@ namespace Neo.UnitTests.Plugins { - internal class TestPluginSettings(IConfigurationSection section) : PluginSettings(section) + internal class TestPluginSettings : IPluginSettings { public static TestPluginSettings Default { get; private set; } + + public UnhandledExceptionPolicy ExceptionPolicy => UnhandledExceptionPolicy.Ignore; + public static void Load(IConfigurationSection section) { - Default = new TestPluginSettings(section); + Default = new TestPluginSettings(); } } internal class TestNonPlugin