From 6d658d0b040c9d7206f77ed046a1fc6dc5956dbf Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 14:04:36 +0900 Subject: [PATCH 1/9] refactor: Remove AppAddress --- .submodules/lib9c | 1 + src/client/Directory.Build.props | 4 + src/client/GlobalUsings.cs | 1 + .../ExampleClient.cs | 3 +- .../ExampleRemoteNodeService.cs | 9 +- .../Client.BlockChain.cs | 10 +- src/client/LibplanetConsole.Client/Client.cs | 3 +- .../LibplanetConsole.Client/IBlockChain.cs | 11 +- src/client/LibplanetConsole.Client/IClient.cs | 3 +- .../AppAddress.Bencodex.cs | 18 +- .../LibplanetConsole.Common/AppAddress.cs | 168 +++++++++--------- src/common/LibplanetConsole.Common/AppPeer.cs | 3 +- .../LibplanetConsole.Common/AppPrivateKey.cs | 2 +- .../LibplanetConsole.Common/AppPublicKey.cs | 2 +- .../Commands/KeyCommandBase.cs | 5 +- .../Converters/AppAddressConverter.cs | 8 +- .../Converters/AppAddressJsonConverter.cs | 44 ++--- .../DataAnnotations/AppAddressAttribute.cs | 4 +- .../Extensions/AddressExtensions.cs | 24 +++ src/common/LibplanetConsole.Seed/Peer.cs | 3 +- .../LibplanetConsole.Seed/PeerCollection.cs | 3 +- src/console/Directory.Build.props | 4 + src/console/GlobalUsings.cs | 1 + .../ExampleNodeContent.cs | 19 +- .../IExampleNodeContent.cs | 10 +- .../LibplanetConsole.Console/Client.cs | 3 +- .../ClientCollection.cs | 10 +- .../LibplanetConsole.Console/IAddressable.cs | 4 +- .../LibplanetConsole.Console/IApplication.cs | 3 +- .../LibplanetConsole.Console/IBlockChain.cs | 11 +- .../IClientCollection.cs | 8 +- .../INodeCollection.cs | 7 +- .../Node.BlockChain.cs | 10 +- src/console/LibplanetConsole.Console/Node.cs | 3 +- .../NodeCollection.cs | 9 +- src/node/Directory.Build.props | 4 + src/node/GlobalUsings.cs | 1 + .../EvidenceNode.cs | 4 +- .../Commands/ExampleNodeCommand.cs | 4 +- .../ExampleNode.cs | 16 +- .../ExampleNodeService.cs | 10 +- .../IExampleNode.cs | 10 +- src/node/LibplanetConsole.Node/IBlockChain.cs | 11 +- src/node/LibplanetConsole.Node/INode.cs | 3 +- .../LibplanetConsole.Node/Node.BlockChain.cs | 22 +-- src/node/LibplanetConsole.Node/Node.cs | 2 +- .../Services/BlockChainService.cs | 11 +- .../LibplanetConsole.Client/ClientInfo.cs | 6 +- .../LibplanetConsole.Evidence/EvidenceInfo.cs | 4 +- .../Services/IExampleNodeCallback.cs | 6 +- .../Services/IExampleNodeService.cs | 8 +- .../LibplanetConsole.Node/BlockInfo.Node.cs | 3 +- src/shared/LibplanetConsole.Node/BlockInfo.cs | 3 +- src/shared/LibplanetConsole.Node/NodeInfo.cs | 3 +- .../Services/IBlockChainService.cs | 11 +- .../TransactionInfo.Node.cs | 2 +- .../LibplanetConsole.Node/TransactionInfo.cs | 3 +- 57 files changed, 322 insertions(+), 256 deletions(-) create mode 160000 .submodules/lib9c create mode 100644 src/client/GlobalUsings.cs create mode 100644 src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs create mode 100644 src/console/GlobalUsings.cs create mode 100644 src/node/GlobalUsings.cs diff --git a/.submodules/lib9c b/.submodules/lib9c new file mode 160000 index 00000000..178eafae --- /dev/null +++ b/.submodules/lib9c @@ -0,0 +1 @@ +Subproject commit 178eafae4e054b283a6e198254bba4a85e8f6f6d diff --git a/src/client/Directory.Build.props b/src/client/Directory.Build.props index 4a6ad14e..14c92fef 100644 --- a/src/client/Directory.Build.props +++ b/src/client/Directory.Build.props @@ -14,4 +14,8 @@ LIBPLANET_CLIENT + + + + diff --git a/src/client/GlobalUsings.cs b/src/client/GlobalUsings.cs new file mode 100644 index 00000000..67618185 --- /dev/null +++ b/src/client/GlobalUsings.cs @@ -0,0 +1 @@ +global using Libplanet.Crypto; diff --git a/src/client/LibplanetConsole.Client.Example/ExampleClient.cs b/src/client/LibplanetConsole.Client.Example/ExampleClient.cs index 2b8ba69d..eb0f94c3 100644 --- a/src/client/LibplanetConsole.Client.Example/ExampleClient.cs +++ b/src/client/LibplanetConsole.Client.Example/ExampleClient.cs @@ -1,4 +1,5 @@ using System.ComponentModel.Composition; +using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Example.Services; @@ -15,7 +16,7 @@ internal sealed class ExampleClient( { private readonly ExampleRemoteNodeService _remoteNodeService = remoteNodeService; - public AppAddress Address => client.Address; + public Address Address => client.Address; public bool IsExample { get; } = settings.IsExample; diff --git a/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs b/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs index df67bb4e..f6a248b3 100644 --- a/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs +++ b/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs @@ -1,5 +1,5 @@ using System.ComponentModel.Composition; -using LibplanetConsole.Common; +using Libplanet.Crypto; using LibplanetConsole.Common.Services; using LibplanetConsole.Example.Services; @@ -7,14 +7,13 @@ namespace LibplanetConsole.Client.Example; [Export] internal sealed class ExampleRemoteNodeService - : RemoteService, - IExampleNodeCallback + : RemoteService, IExampleNodeCallback { - public void OnSubscribed(AppAddress address) + public void OnSubscribed(Address address) { } - public void OnUnsubscribed(AppAddress address) + public void OnUnsubscribed(Address address) { } } diff --git a/src/client/LibplanetConsole.Client/Client.BlockChain.cs b/src/client/LibplanetConsole.Client/Client.BlockChain.cs index 9e962e7c..50220d3c 100644 --- a/src/client/LibplanetConsole.Client/Client.BlockChain.cs +++ b/src/client/LibplanetConsole.Client/Client.BlockChain.cs @@ -33,7 +33,7 @@ public async Task SendTransactionAsync( public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) => RemoteBlockChainService.GetBlockHashAsync(height, cancellationToken); - public Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken) + public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) => RemoteBlockChainService.GetNextNonceAsync(address, cancellationToken); public Task GetTipHashAsync(CancellationToken cancellationToken) @@ -41,8 +41,8 @@ public Task GetTipHashAsync(CancellationToken cancellationToken) public async Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { var value = await RemoteBlockChainService.GetStateAsync( @@ -52,8 +52,8 @@ public async Task GetStateAsync( public async Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { var value = await RemoteBlockChainService.GetStateByStateRootHashAsync( diff --git a/src/client/LibplanetConsole.Client/Client.cs b/src/client/LibplanetConsole.Client/Client.cs index 56e4a7d9..a48309ed 100644 --- a/src/client/LibplanetConsole.Client/Client.cs +++ b/src/client/LibplanetConsole.Client/Client.cs @@ -1,4 +1,5 @@ using System.Security; +using Libplanet.Crypto; using LibplanetConsole.Client.Services; using LibplanetConsole.Common; using LibplanetConsole.Node; @@ -38,7 +39,7 @@ public Client(ApplicationBase application, ApplicationOptions options) public AppPublicKey PublicKey { get; } - public AppAddress Address => PublicKey.Address; + public Address Address => PublicKey.Address; public TextWriter Out { get; set; } = Console.Out; diff --git a/src/client/LibplanetConsole.Client/IBlockChain.cs b/src/client/LibplanetConsole.Client/IBlockChain.cs index 9555ec62..ec5ff37f 100644 --- a/src/client/LibplanetConsole.Client/IBlockChain.cs +++ b/src/client/LibplanetConsole.Client/IBlockChain.cs @@ -1,5 +1,6 @@ using Bencodex.Types; using Libplanet.Action; +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Client; @@ -10,20 +11,20 @@ public interface IBlockChain Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); - Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken); + Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetBlockHashAsync(long height, CancellationToken cancellationToken); diff --git a/src/client/LibplanetConsole.Client/IClient.cs b/src/client/LibplanetConsole.Client/IClient.cs index be0ef8cc..afdf118a 100644 --- a/src/client/LibplanetConsole.Client/IClient.cs +++ b/src/client/LibplanetConsole.Client/IClient.cs @@ -1,4 +1,5 @@ using Libplanet.Action; +using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Node; @@ -18,7 +19,7 @@ public interface IClient : IVerifier AppPublicKey PublicKey { get; } - AppAddress Address { get; } + Address Address { get; } AppEndPoint NodeEndPoint { get; set; } diff --git a/src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs b/src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs index 7440cbd4..fd078306 100644 --- a/src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs +++ b/src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs @@ -1,12 +1,12 @@ -using Bencodex.Types; -using Libplanet.Crypto; +// using Bencodex.Types; +// using Libplanet.Crypto; -namespace LibplanetConsole.Common; +// namespace LibplanetConsole.Common; -public readonly partial record struct AppAddress -{ - public static AppAddress FromBencodex(IValue value) - => new AppAddress(new Address(value)); +// public readonly partial record struct AppAddress +// { +// public static AppAddress FromBencodex(IValue value) +// => new AppAddress(new Address(value)); - public IValue ToBencodex() => _address.Bencoded; -} +// public IValue ToBencodex() => _address.Bencoded; +// } diff --git a/src/common/LibplanetConsole.Common/AppAddress.cs b/src/common/LibplanetConsole.Common/AppAddress.cs index a809a3b8..3fe36147 100644 --- a/src/common/LibplanetConsole.Common/AppAddress.cs +++ b/src/common/LibplanetConsole.Common/AppAddress.cs @@ -1,84 +1,84 @@ -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json.Serialization; -using Libplanet.Crypto; -using LibplanetConsole.Common.Converters; - -namespace LibplanetConsole.Common; - -[JsonConverter(typeof(AppAddressJsonConverter))] -[TypeConverter(typeof(AppAddressConverter))] -public readonly partial record struct AppAddress : IFormattable -{ - public const string RegularExpression = "0x[0-9a-fA-F]{40}"; - private readonly Address _address; - - public AppAddress(Address address) => _address = address; - - public AppAddress(byte[] bytes) - : this(new Address(bytes)) - { - } - - public static explicit operator AppAddress(Address address) - => new(address); - - public static explicit operator Address(AppAddress address) - => address._address; - - public static string ToString(AppAddress? address) - => address?.ToString() ?? string.Empty; - - public static AppAddress Parse(string text) => new(new Address(text)); - - public static AppAddress? ParseOrDefault(string text) - => text == string.Empty ? null : Parse(text); - - public static AppAddress ParseOrFallback(string text, AppAddress fallback) - => text == string.Empty ? fallback : Parse(text); - - public static bool TryParse(string text, [MaybeNullWhen(false)] out AppAddress address) - { - try - { - address = Parse(text); - return true; - } - catch - { - address = default; - return false; - } - } - - public override string ToString() => _address.ToString(); - - public string ToString(string? format, IFormatProvider? formatProvider) - { - if (format is "S") - { - return $"{_address}"[0..8]; - } - - return ToString(); - } - - public string ToShortString() => ToString(format: "S", formatProvider: null); - - public AppAddress Derive(byte[] key) - { - var bytes = _address.ToByteArray(); - var hashed = GetHahsed(key, bytes); - return new AppAddress(hashed); - - static byte[] GetHahsed(byte[] key, byte[] bytes) - { - using var hmac = new HMACSHA1(key); - return hmac.ComputeHash(bytes); - } - } - - public AppAddress Derive(string key) => Derive(Encoding.UTF8.GetBytes(key)); -} +// using System.ComponentModel; +// using System.Diagnostics.CodeAnalysis; +// using System.Security.Cryptography; +// using System.Text; +// using System.Text.Json.Serialization; +// using Libplanet.Crypto; +// using LibplanetConsole.Common.Converters; + +// namespace LibplanetConsole.Common; + +// [JsonConverter(typeof(AppAddressJsonConverter))] +// [TypeConverter(typeof(AppAddressConverter))] +// public readonly partial record struct AppAddress : IFormattable +// { +// public const string RegularExpression = "0x[0-9a-fA-F]{40}"; +// private readonly Address _address; + +// public AppAddress(Address address) => _address = address; + +// public AppAddress(byte[] bytes) +// : this(new Address(bytes)) +// { +// } + +// public static explicit operator AppAddress(Address address) +// => new(address); + +// public static explicit operator Address(AppAddress address) +// => address._address; + +// public static string ToString(AppAddress? address) +// => address?.ToString() ?? string.Empty; + +// public static AppAddress Parse(string text) => new(new Address(text)); + +// public static AppAddress? ParseOrDefault(string text) +// => text == string.Empty ? null : Parse(text); + +// public static AppAddress ParseOrFallback(string text, AppAddress fallback) +// => text == string.Empty ? fallback : Parse(text); + +// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppAddress address) +// { +// try +// { +// address = Parse(text); +// return true; +// } +// catch +// { +// address = default; +// return false; +// } +// } + +// public override string ToString() => _address.ToString(); + +// public string ToString(string? format, IFormatProvider? formatProvider) +// { +// if (format is "S") +// { +// return $"{_address}"[0..8]; +// } + +// return ToString(); +// } + +// public string ToShortString() => ToString(format: "S", formatProvider: null); + +// public AppAddress Derive(byte[] key) +// { +// var bytes = _address.ToByteArray(); +// var hashed = GetHahsed(key, bytes); +// return new AppAddress(hashed); + +// static byte[] GetHahsed(byte[] key, byte[] bytes) +// { +// using var hmac = new HMACSHA1(key); +// return hmac.ComputeHash(bytes); +// } +// } + +// public AppAddress Derive(string key) => Derive(Encoding.UTF8.GetBytes(key)); +// } diff --git a/src/common/LibplanetConsole.Common/AppPeer.cs b/src/common/LibplanetConsole.Common/AppPeer.cs index 338c31b6..849b2479 100644 --- a/src/common/LibplanetConsole.Common/AppPeer.cs +++ b/src/common/LibplanetConsole.Common/AppPeer.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using Libplanet.Crypto; using LibplanetConsole.Common.Converters; namespace LibplanetConsole.Common; @@ -17,7 +18,7 @@ public static readonly string RegularExpression public AppEndPoint EndPoint { get; } = endPoint; - public AppAddress Address => PublicKey.Address; + public Address Address => PublicKey.Address; public static string ToString(AppPeer? peer) => peer?.ToString() ?? string.Empty; diff --git a/src/common/LibplanetConsole.Common/AppPrivateKey.cs b/src/common/LibplanetConsole.Common/AppPrivateKey.cs index e184bdf9..ffb493c8 100644 --- a/src/common/LibplanetConsole.Common/AppPrivateKey.cs +++ b/src/common/LibplanetConsole.Common/AppPrivateKey.cs @@ -33,7 +33,7 @@ public AppPrivateKey() public AppPublicKey PublicKey => (AppPublicKey)_privateKey.PublicKey; - public AppAddress Address => (AppAddress)_privateKey.PublicKey.Address; + public Address Address => _privateKey.PublicKey.Address; public static explicit operator AppPrivateKey(PrivateKey privateKey) => new(privateKey); diff --git a/src/common/LibplanetConsole.Common/AppPublicKey.cs b/src/common/LibplanetConsole.Common/AppPublicKey.cs index a6d810a6..088f6604 100644 --- a/src/common/LibplanetConsole.Common/AppPublicKey.cs +++ b/src/common/LibplanetConsole.Common/AppPublicKey.cs @@ -19,7 +19,7 @@ namespace LibplanetConsole.Common; public AppPublicKey(PublicKey publicKey) => _publicKey = publicKey; - public AppAddress Address => new(_publicKey.Address); + public Address Address => _publicKey.Address; public static explicit operator AppPublicKey(PublicKey publicKey) => new(publicKey); diff --git a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs index 67a389cd..975588f7 100644 --- a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs +++ b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs @@ -1,4 +1,5 @@ using JSSoft.Commands; +using Libplanet.Crypto; using LibplanetConsole.Common.Extensions; namespace LibplanetConsole.Common.Commands; @@ -70,12 +71,12 @@ public void Derive( { var info = new { - Address = AppAddress.Parse(address).Derive(keyword), + Address = new Address(address).Derive(keyword), }; Out.WriteLineAsJson(info); } - private static AppAddress GetAddress(string key) + private static Address GetAddress(string key) { if (AppPrivateKey.TryParse(key, out var privateKey) == true) { diff --git a/src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs index 7965189b..313d8c44 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs @@ -1,6 +1,7 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using Libplanet.Crypto; namespace LibplanetConsole.Common.Converters; @@ -18,7 +19,7 @@ public override bool CanConvertTo( { if (value is string text) { - return AppAddress.ParseOrDefault(text); + return ParseOrDefault(text); } return base.ConvertFrom(context, culture, value); @@ -27,11 +28,14 @@ public override bool CanConvertTo( public override object? ConvertTo( ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { - if (value is AppAddress address) + if (value is Address address) { return address.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } + + public static Address? ParseOrDefault(string text) + => text == string.Empty ? null : new Address(text); } diff --git a/src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs index e56e3727..0a0da677 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs @@ -1,26 +1,26 @@ -using System.Text.Json; -using System.Text.Json.Serialization; +// using System.Text.Json; +// using System.Text.Json.Serialization; -namespace LibplanetConsole.Common.Converters; +// namespace LibplanetConsole.Common.Converters; -public sealed class AppAddressJsonConverter : JsonConverter -{ - public override AppAddress Read( - ref Utf8JsonReader reader, - Type typeToConvert, - JsonSerializerOptions options) - { - if (reader.GetString() is string text) - { - return AppAddress.Parse(text); - } +// public sealed class AppAddressJsonConverter : JsonConverter +// { +// public override AppAddress Read( +// ref Utf8JsonReader reader, +// Type typeToConvert, +// JsonSerializerOptions options) +// { +// if (reader.GetString() is string text) +// { +// return AppAddress.Parse(text); +// } - throw new JsonException("Cannot read AppAddress from JSON."); - } +// throw new JsonException("Cannot read AppAddress from JSON."); +// } - public override void Write( - Utf8JsonWriter writer, AppAddress value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } -} +// public override void Write( +// Utf8JsonWriter writer, AppAddress value, JsonSerializerOptions options) +// { +// writer.WriteStringValue(value.ToString()); +// } +// } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppAddressAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/AppAddressAttribute.cs index 0bc2cbed..eadafb46 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppAddressAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/AppAddressAttribute.cs @@ -7,8 +7,10 @@ namespace LibplanetConsole.Common.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] public sealed class AppAddressAttribute : RegularExpressionAttribute { + public const string RegularExpression = "0x[0-9a-fA-F]{40}"; + public AppAddressAttribute() - : base($"^{AppAddress.RegularExpression}$") + : base($"^{RegularExpression}$") { } } diff --git a/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs new file mode 100644 index 00000000..5fa4f3c5 --- /dev/null +++ b/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs @@ -0,0 +1,24 @@ +using System.Security.Cryptography; +using System.Text; +using Libplanet.Crypto; + +namespace LibplanetConsole.Common.Extensions; + +public static class AddressExtensions +{ + public static Address Derive(this Address @this, byte[] key) + { + var bytes = @this.ToByteArray(); + var hashed = GetHahsed(key, bytes); + return new Address(hashed); + + static byte[] GetHahsed(byte[] key, byte[] bytes) + { + using var hmac = new HMACSHA1(key); + return hmac.ComputeHash(bytes); + } + } + + public static Address Derive(this Address @this, string key) + => Derive(@this, Encoding.UTF8.GetBytes(key)); +} diff --git a/src/common/LibplanetConsole.Seed/Peer.cs b/src/common/LibplanetConsole.Seed/Peer.cs index a9b4ee91..14641760 100644 --- a/src/common/LibplanetConsole.Seed/Peer.cs +++ b/src/common/LibplanetConsole.Seed/Peer.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using Libplanet.Crypto; using Libplanet.Net.Messages; using Libplanet.Net.Transports; using LibplanetConsole.Common; @@ -16,7 +17,7 @@ internal Peer(ITransport transport, AppPeer appPeer) AppPeer = appPeer; } - public AppAddress Address => AppPeer.Address; + public Address Address => AppPeer.Address; public AppPeer AppPeer { get; } diff --git a/src/common/LibplanetConsole.Seed/PeerCollection.cs b/src/common/LibplanetConsole.Seed/PeerCollection.cs index d93ac6ad..0d51fb3b 100644 --- a/src/common/LibplanetConsole.Seed/PeerCollection.cs +++ b/src/common/LibplanetConsole.Seed/PeerCollection.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Concurrent; +using Libplanet.Crypto; using Libplanet.Net.Transports; using LibplanetConsole.Common; using Serilog; @@ -8,7 +9,7 @@ namespace LibplanetConsole.Seed; public sealed class PeerCollection : IEnumerable { - private readonly ConcurrentDictionary _infoByAddress = []; + private readonly ConcurrentDictionary _infoByAddress = []; private readonly SeedOptions _seedOptions; private readonly ILogger _logger = Log.ForContext(); diff --git a/src/console/Directory.Build.props b/src/console/Directory.Build.props index 53631d9a..ac9d8e36 100644 --- a/src/console/Directory.Build.props +++ b/src/console/Directory.Build.props @@ -14,4 +14,8 @@ LIBPLANET_CONSOLE + + + + diff --git a/src/console/GlobalUsings.cs b/src/console/GlobalUsings.cs new file mode 100644 index 00000000..67618185 --- /dev/null +++ b/src/console/GlobalUsings.cs @@ -0,0 +1 @@ +global using Libplanet.Crypto; diff --git a/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs b/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs index e02c3ef2..68b2179f 100644 --- a/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs +++ b/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs @@ -1,5 +1,6 @@ using System.ComponentModel.Composition; using System.Text; +using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Common.Services; using LibplanetConsole.Console.Services; @@ -17,9 +18,9 @@ internal sealed class ExampleNodeContent(INode node, ExampleSettings settings) private readonly StringBuilder _log = new(); private RemoteService? _remoteService; - public event EventHandler>? Subscribed; + public event EventHandler>? Subscribed; - public event EventHandler>? Unsubscribed; + public event EventHandler>? Unsubscribed; public int Count { get; private set; } @@ -32,24 +33,24 @@ internal sealed class ExampleNodeContent(INode node, ExampleSettings settings) private RemoteService RemoteService => _remoteService ??= new RemoteService(this); - public Task GetAddressesAsync(CancellationToken cancellationToken) + public Task GetAddressesAsync(CancellationToken cancellationToken) => Service.GetAddressesAsync(cancellationToken); - public void Subscribe(AppAddress address) => Service.Subscribe(address); + public void Subscribe(Address address) => Service.Subscribe(address); - public void Unsubscribe(AppAddress address) => Service.Unsubscribe(address); + public void Unsubscribe(Address address) => Service.Unsubscribe(address); - async void IExampleNodeCallback.OnSubscribed(AppAddress address) + async void IExampleNodeCallback.OnSubscribed(Address address) { Count = await Service.GetAddressCountAsync(CancellationToken.None); _log.AppendLine($"{nameof(IExampleNodeCallback.OnSubscribed)}: {address}"); - Subscribed?.Invoke(this, new ItemEventArgs(address)); + Subscribed?.Invoke(this, new ItemEventArgs
(address)); } - async void IExampleNodeCallback.OnUnsubscribed(AppAddress address) + async void IExampleNodeCallback.OnUnsubscribed(Address address) { Count = await Service.GetAddressCountAsync(CancellationToken.None); _log.AppendLine($"{nameof(IExampleNodeCallback.OnUnsubscribed)}: {address}"); - Unsubscribed?.Invoke(this, new ItemEventArgs(address)); + Unsubscribed?.Invoke(this, new ItemEventArgs
(address)); } } diff --git a/src/console/LibplanetConsole.Console.Example/IExampleNodeContent.cs b/src/console/LibplanetConsole.Console.Example/IExampleNodeContent.cs index 7f6ed1fb..c5be23e9 100644 --- a/src/console/LibplanetConsole.Console.Example/IExampleNodeContent.cs +++ b/src/console/LibplanetConsole.Console.Example/IExampleNodeContent.cs @@ -4,15 +4,15 @@ namespace LibplanetConsole.Console.Example; public interface IExampleNodeContent { - event EventHandler>? Subscribed; + event EventHandler>? Subscribed; - event EventHandler>? Unsubscribed; + event EventHandler>? Unsubscribed; int Count { get; } - Task GetAddressesAsync(CancellationToken cancellationToken); + Task GetAddressesAsync(CancellationToken cancellationToken); - void Subscribe(AppAddress address); + void Subscribe(Address address); - void Unsubscribe(AppAddress address); + void Unsubscribe(Address address); } diff --git a/src/console/LibplanetConsole.Console/Client.cs b/src/console/LibplanetConsole.Console/Client.cs index 9092a485..e53481ff 100644 --- a/src/console/LibplanetConsole.Console/Client.cs +++ b/src/console/LibplanetConsole.Console/Client.cs @@ -1,6 +1,7 @@ using System.Collections; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; +using Libplanet.Crypto; using LibplanetConsole.Client; using LibplanetConsole.Client.Services; using LibplanetConsole.Common; @@ -60,7 +61,7 @@ public Client(ApplicationBase application, ClientOptions clientOptions) public AppPublicKey PublicKey { get; } - public AppAddress Address => PublicKey.Address; + public Address Address => PublicKey.Address; public bool IsAttached => _closeToken != Guid.Empty; diff --git a/src/console/LibplanetConsole.Console/ClientCollection.cs b/src/console/LibplanetConsole.Console/ClientCollection.cs index 275d3f5a..27c8237d 100644 --- a/src/console/LibplanetConsole.Console/ClientCollection.cs +++ b/src/console/LibplanetConsole.Console/ClientCollection.cs @@ -1,7 +1,7 @@ using System.Collections; using System.Collections.Specialized; using System.ComponentModel.Composition; -using LibplanetConsole.Common; +using Libplanet.Crypto; using LibplanetConsole.Common.Exceptions; using LibplanetConsole.Framework; using Microsoft.Extensions.DependencyInjection; @@ -63,15 +63,15 @@ public Client? Current public Client this[int index] => _clientList[index]; - public Client this[AppAddress address] => _clientList.Single(item => item.Address == address); + public Client this[Address address] => _clientList.Single(item => item.Address == address); IClient IClientCollection.this[int index] => this[index]; - IClient IClientCollection.this[AppAddress address] => this[address]; + IClient IClientCollection.this[Address address] => this[address]; public bool Contains(Client item) => _clientList.Contains(item); - public bool Contains(AppAddress address) => _clientList.Exists(item => item.Address == address); + public bool Contains(Address address) => _clientList.Exists(item => item.Address == address); public int IndexOf(Client item) { @@ -86,7 +86,7 @@ public int IndexOf(Client item) return -1; } - public int IndexOf(AppAddress address) + public int IndexOf(Address address) { for (var i = 0; i < _clientList.Count; i++) { diff --git a/src/console/LibplanetConsole.Console/IAddressable.cs b/src/console/LibplanetConsole.Console/IAddressable.cs index 2fa6a42f..3b7e8dc9 100644 --- a/src/console/LibplanetConsole.Console/IAddressable.cs +++ b/src/console/LibplanetConsole.Console/IAddressable.cs @@ -1,8 +1,8 @@ -using LibplanetConsole.Common; +using Libplanet.Crypto; namespace LibplanetConsole.Console; public interface IAddressable { - AppAddress Address { get; } + Address Address { get; } } diff --git a/src/console/LibplanetConsole.Console/IApplication.cs b/src/console/LibplanetConsole.Console/IApplication.cs index eeef8ef2..66cf60f1 100644 --- a/src/console/LibplanetConsole.Console/IApplication.cs +++ b/src/console/LibplanetConsole.Console/IApplication.cs @@ -1,3 +1,4 @@ +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Console; @@ -18,6 +19,6 @@ public interface IApplication : IAsyncDisposable, IServiceProvider IAddressable GetAddressable(string address); - IAddressable GetAddressable(AppAddress address) + IAddressable GetAddressable(Address address) => GetAddressable(address.ToString()); } diff --git a/src/console/LibplanetConsole.Console/IBlockChain.cs b/src/console/LibplanetConsole.Console/IBlockChain.cs index 72903b7a..b33513ca 100644 --- a/src/console/LibplanetConsole.Console/IBlockChain.cs +++ b/src/console/LibplanetConsole.Console/IBlockChain.cs @@ -1,5 +1,6 @@ using Bencodex.Types; using Libplanet.Action; +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Console; @@ -10,20 +11,20 @@ public interface IBlockChain Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); - Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken); + Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetBlockHashAsync(long height, CancellationToken cancellationToken); diff --git a/src/console/LibplanetConsole.Console/IClientCollection.cs b/src/console/LibplanetConsole.Console/IClientCollection.cs index e1c4027e..e5419de3 100644 --- a/src/console/LibplanetConsole.Console/IClientCollection.cs +++ b/src/console/LibplanetConsole.Console/IClientCollection.cs @@ -1,5 +1,5 @@ using System.Collections.Specialized; -using LibplanetConsole.Common; +using Libplanet.Crypto; namespace LibplanetConsole.Console; @@ -13,15 +13,15 @@ public interface IClientCollection : IEnumerable, INotifyCollectionChan IClient this[int index] { get; } - IClient this[AppAddress address] { get; } + IClient this[Address address] { get; } bool Contains(IClient item); - bool Contains(AppAddress address); + bool Contains(Address address); int IndexOf(IClient item); - int IndexOf(AppAddress address); + int IndexOf(Address address); Task AddNewAsync(AddNewClientOptions options, CancellationToken cancellationToken); } diff --git a/src/console/LibplanetConsole.Console/INodeCollection.cs b/src/console/LibplanetConsole.Console/INodeCollection.cs index d8cac9d4..0e041482 100644 --- a/src/console/LibplanetConsole.Console/INodeCollection.cs +++ b/src/console/LibplanetConsole.Console/INodeCollection.cs @@ -1,4 +1,5 @@ using System.Collections.Specialized; +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Console; @@ -13,15 +14,15 @@ public interface INodeCollection : IEnumerable, INotifyCollectionChanged INode this[int index] { get; } - INode this[AppAddress address] { get; } + INode this[Address address] { get; } bool Contains(INode item); - bool Contains(AppAddress address); + bool Contains(Address address); int IndexOf(INode item); - int IndexOf(AppAddress address); + int IndexOf(Address address); Task AddNewAsync(AddNewNodeOptions options, CancellationToken cancellationToken); } diff --git a/src/console/LibplanetConsole.Console/Node.BlockChain.cs b/src/console/LibplanetConsole.Console/Node.BlockChain.cs index e073cacc..42707983 100644 --- a/src/console/LibplanetConsole.Console/Node.BlockChain.cs +++ b/src/console/LibplanetConsole.Console/Node.BlockChain.cs @@ -13,7 +13,7 @@ internal sealed partial class Node { public event EventHandler? BlockAppended; - public Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken) + public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) => _blockChainService.Service.GetNextNonceAsync(address, cancellationToken); public async Task SendTransactionAsync( @@ -53,8 +53,8 @@ public Task GetTipHashAsync(CancellationToken cancellationToken) public async Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { var bytes = await _blockChainService.Service.GetStateAsync( @@ -67,8 +67,8 @@ public async Task GetStateAsync( public async Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { var bytes = await _blockChainService.Service.GetStateByStateRootHashAsync( diff --git a/src/console/LibplanetConsole.Console/Node.cs b/src/console/LibplanetConsole.Console/Node.cs index fbd5bc4a..4296371f 100644 --- a/src/console/LibplanetConsole.Console/Node.cs +++ b/src/console/LibplanetConsole.Console/Node.cs @@ -2,6 +2,7 @@ using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using Bencodex; +using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; using LibplanetConsole.Common.Services; @@ -72,7 +73,7 @@ public AppEndPoint ConsensusEndPoint public AppPublicKey PublicKey { get; } - public AppAddress Address => PublicKey.Address; + public Address Address => PublicKey.Address; public bool IsAttached => _closeToken != Guid.Empty; diff --git a/src/console/LibplanetConsole.Console/NodeCollection.cs b/src/console/LibplanetConsole.Console/NodeCollection.cs index 10759406..f0da11a5 100644 --- a/src/console/LibplanetConsole.Console/NodeCollection.cs +++ b/src/console/LibplanetConsole.Console/NodeCollection.cs @@ -1,6 +1,7 @@ using System.Collections; using System.Collections.Specialized; using System.ComponentModel.Composition; +using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; using LibplanetConsole.Console.Services; @@ -65,15 +66,15 @@ public Node? Current public Node this[int index] => _nodeList[index]; - public Node this[AppAddress address] => _nodeList.Single(item => item.Address == address); + public Node this[Address address] => _nodeList.Single(item => item.Address == address); INode INodeCollection.this[int index] => this[index]; - INode INodeCollection.this[AppAddress address] => this[address]; + INode INodeCollection.this[Address address] => this[address]; public bool Contains(Node item) => _nodeList.Contains(item); - public bool Contains(AppAddress address) => _nodeList.Exists(item => item.Address == address); + public bool Contains(Address address) => _nodeList.Exists(item => item.Address == address); public int IndexOf(Node item) { @@ -88,7 +89,7 @@ public int IndexOf(Node item) return -1; } - public int IndexOf(AppAddress address) + public int IndexOf(Address address) { for (var i = 0; i < _nodeList.Count; i++) { diff --git a/src/node/Directory.Build.props b/src/node/Directory.Build.props index b889a7e8..4618ace0 100644 --- a/src/node/Directory.Build.props +++ b/src/node/Directory.Build.props @@ -14,4 +14,8 @@ LIBPLANET_NODE + + + + diff --git a/src/node/GlobalUsings.cs b/src/node/GlobalUsings.cs new file mode 100644 index 00000000..67618185 --- /dev/null +++ b/src/node/GlobalUsings.cs @@ -0,0 +1 @@ +global using Libplanet.Crypto; diff --git a/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs b/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs index f5119738..f2fb8d94 100644 --- a/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs +++ b/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs @@ -20,7 +20,7 @@ public async Task AddEvidenceAsync(CancellationToken cancellationT var blockChain = node.GetRequiredService(); var height = blockChain.Tip.Index; var validatorAddress = node.Address; - var evidence = new TestEvidence(height, (Address)validatorAddress, DateTimeOffset.UtcNow); + var evidence = new TestEvidence(height, validatorAddress, DateTimeOffset.UtcNow); blockChain.AddEvidence(evidence); await Task.CompletedTask; return (EvidenceInfo)evidence; @@ -36,7 +36,7 @@ public async Task GetEvidenceAsync( Type = item.GetType().Name, Id = item.Id.ToString(), Height = item.Height, - TargetAddress = (AppAddress)item.TargetAddress, + TargetAddress = item.TargetAddress, Timestamp = item.Timestamp, }); await Task.CompletedTask; diff --git a/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs b/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs index b3c9214b..8fca3aad 100644 --- a/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs +++ b/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs @@ -14,13 +14,13 @@ internal sealed class ExampleNodeCommand(IExampleNode sampleNode) [CommandMethod] public void Subscribe(string address) { - sampleNode.Subscribe(AppAddress.Parse(address)); + sampleNode.Subscribe(new Address(address)); } [CommandMethod] public void Unsubscribe(string address) { - sampleNode.Unsubscribe(AppAddress.Parse(address)); + sampleNode.Unsubscribe(new Address(address)); } [CommandMethod] diff --git a/src/node/LibplanetConsole.Node.Example/ExampleNode.cs b/src/node/LibplanetConsole.Node.Example/ExampleNode.cs index c0bfd36f..d623d62c 100644 --- a/src/node/LibplanetConsole.Node.Example/ExampleNode.cs +++ b/src/node/LibplanetConsole.Node.Example/ExampleNode.cs @@ -10,20 +10,20 @@ internal sealed class ExampleNode( IApplication application, ExampleSettings settings) : IExampleNode { private readonly IApplication _application = application; - private readonly HashSet _addresses = []; + private readonly HashSet
_addresses = []; - public event EventHandler>? Subscribed; + public event EventHandler>? Subscribed; - public event EventHandler>? Unsubscribed; + public event EventHandler>? Unsubscribed; public int Count => _addresses.Count; public bool IsExample { get; } = settings.IsExample; - public Task GetAddressesAsync(CancellationToken cancellationToken) + public Task GetAddressesAsync(CancellationToken cancellationToken) => _application.InvokeAsync(() => _addresses.ToArray(), cancellationToken); - public void Subscribe(AppAddress address) + public void Subscribe(Address address) { if (_addresses.Contains(address) == true) { @@ -31,11 +31,11 @@ public void Subscribe(AppAddress address) } _addresses.Add(address); - Subscribed?.Invoke(this, new ItemEventArgs(address)); + Subscribed?.Invoke(this, new ItemEventArgs
(address)); Console.Out.WriteLine($"Subscribed: '{address}'"); } - public void Unsubscribe(AppAddress address) + public void Unsubscribe(Address address) { if (_addresses.Contains(address) != true) { @@ -43,7 +43,7 @@ public void Unsubscribe(AppAddress address) } _addresses.Remove(address); - Unsubscribed?.Invoke(this, new ItemEventArgs(address)); + Unsubscribed?.Invoke(this, new ItemEventArgs
(address)); Console.Out.WriteLine($"Unsubscribed: '{address}'"); } } diff --git a/src/node/LibplanetConsole.Node.Example/ExampleNodeService.cs b/src/node/LibplanetConsole.Node.Example/ExampleNodeService.cs index 2ab2979a..012e41a6 100644 --- a/src/node/LibplanetConsole.Node.Example/ExampleNodeService.cs +++ b/src/node/LibplanetConsole.Node.Example/ExampleNodeService.cs @@ -31,16 +31,16 @@ public async Task GetAddressCountAsync(CancellationToken cancellationToken) return addresses.Length; } - public Task GetAddressesAsync(CancellationToken cancellationToken) + public Task GetAddressesAsync(CancellationToken cancellationToken) => _exampleNode.GetAddressesAsync(cancellationToken); - public void Subscribe(AppAddress address) => _exampleNode.Subscribe(address); + public void Subscribe(Address address) => _exampleNode.Subscribe(address); - public void Unsubscribe(AppAddress address) => _exampleNode.Unsubscribe(address); + public void Unsubscribe(Address address) => _exampleNode.Unsubscribe(address); - private void ExampleNode_Subscribed(object? sender, ItemEventArgs e) + private void ExampleNode_Subscribed(object? sender, ItemEventArgs
e) => Callback.OnSubscribed(e.Item); - private void ExampleNode_Unsubscribed(object? sender, ItemEventArgs e) + private void ExampleNode_Unsubscribed(object? sender, ItemEventArgs
e) => Callback.OnUnsubscribed(e.Item); } diff --git a/src/node/LibplanetConsole.Node.Example/IExampleNode.cs b/src/node/LibplanetConsole.Node.Example/IExampleNode.cs index a1fd82cd..dbc030f8 100644 --- a/src/node/LibplanetConsole.Node.Example/IExampleNode.cs +++ b/src/node/LibplanetConsole.Node.Example/IExampleNode.cs @@ -4,17 +4,17 @@ namespace LibplanetConsole.Node.Example; public interface IExampleNode { - event EventHandler>? Subscribed; + event EventHandler>? Subscribed; - event EventHandler>? Unsubscribed; + event EventHandler>? Unsubscribed; int Count { get; } bool IsExample { get; } - Task GetAddressesAsync(CancellationToken cancellationToken); + Task GetAddressesAsync(CancellationToken cancellationToken); - void Subscribe(AppAddress address); + void Subscribe(Address address); - void Unsubscribe(AppAddress address); + void Unsubscribe(Address address); } diff --git a/src/node/LibplanetConsole.Node/IBlockChain.cs b/src/node/LibplanetConsole.Node/IBlockChain.cs index 63a24f51..8b31c51e 100644 --- a/src/node/LibplanetConsole.Node/IBlockChain.cs +++ b/src/node/LibplanetConsole.Node/IBlockChain.cs @@ -1,5 +1,6 @@ using Bencodex.Types; using Libplanet.Action; +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Node; @@ -10,20 +11,20 @@ public interface IBlockChain Task AddTransactionAsync(IAction[] actions, CancellationToken cancellationToken); - Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken); + Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetBlockHashAsync(long height, CancellationToken cancellationToken); diff --git a/src/node/LibplanetConsole.Node/INode.cs b/src/node/LibplanetConsole.Node/INode.cs index bbe5b577..23af2080 100644 --- a/src/node/LibplanetConsole.Node/INode.cs +++ b/src/node/LibplanetConsole.Node/INode.cs @@ -1,4 +1,5 @@ using Libplanet.Action; +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Node; @@ -15,7 +16,7 @@ public interface INode : IVerifier, ISigner, IServiceProvider AppPublicKey PublicKey { get; } - AppAddress Address => PublicKey.Address; + Address Address => PublicKey.Address; Task StartAsync(CancellationToken cancellationToken); diff --git a/src/node/LibplanetConsole.Node/Node.BlockChain.cs b/src/node/LibplanetConsole.Node/Node.BlockChain.cs index 8bdf0d68..c25c5d03 100644 --- a/src/node/LibplanetConsole.Node/Node.BlockChain.cs +++ b/src/node/LibplanetConsole.Node/Node.BlockChain.cs @@ -27,7 +27,7 @@ public async Task AddTransactionAsync( var privateKey = AppPrivateKey.FromSecureString(_privateKey); var blockChain = BlockChain; var genesisBlock = blockChain.Genesis; - var nonce = blockChain.GetNextTxNonce((Address)privateKey.Address); + var nonce = blockChain.GetNextTxNonce(privateKey.Address); var values = actions.Select(item => item.PlainValue).ToArray(); var transaction = Transaction.Create( nonce: nonce, @@ -75,7 +75,7 @@ public async Task AddTransactionAsync( _logger.Debug("Node added a transaction: {AppId}", transaction.Id); } - public Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken) + public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) { ObjectDisposedExceptionUtility.ThrowIf(_isDisposed, this); InvalidOperationExceptionUtility.ThrowIf( @@ -87,7 +87,7 @@ public Task GetNextNonceAsync(AppAddress address, CancellationToken cancel long GetNextNonce() { var blockChain = BlockChain; - var nonce = blockChain.GetNextTxNonce((Address)address); + var nonce = blockChain.GetNextTxNonce(address); return nonce; } } @@ -110,8 +110,8 @@ AppHash GetTipHash() public Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { ObjectDisposedExceptionUtility.ThrowIf(_isDisposed, this); @@ -127,8 +127,8 @@ IValue GetStateByBlockHash() var worldState = isTip ? blockChain.GetNextWorldState() ?? blockChain.GetWorldState(block.Hash) : blockChain.GetWorldState(block.Hash); - var account = worldState.GetAccountState((Address)accountAddress); - return account.GetState((Address)address) + var account = worldState.GetAccountState(accountAddress); + return account.GetState(address) ?? throw new InvalidOperationException("State not found."); } @@ -137,8 +137,8 @@ IValue GetStateByBlockHash() public Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { ObjectDisposedExceptionUtility.ThrowIf(_isDisposed, this); @@ -150,8 +150,8 @@ IValue GetStateByStateRootHash() { var blockChain = BlockChain; var worldState = blockChain.GetWorldState((HashDigest)stateRootHash); - var account = worldState.GetAccountState((Address)accountAddress); - return account.GetState((Address)address) + var account = worldState.GetAccountState(accountAddress); + return account.GetState(address) ?? throw new InvalidOperationException("State not found."); } diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index d604d205..a5577824 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -84,7 +84,7 @@ public AppEndPoint ConsensusEndPoint public AppPublicKey PublicKey { get; } - public AppAddress Address => PublicKey.Address; + public Address Address => PublicKey.Address; public BlockChain BlockChain => _swarm?.BlockChain ?? throw new InvalidOperationException(); diff --git a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs index d589969f..65879d5b 100644 --- a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs +++ b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs @@ -1,5 +1,6 @@ using System.ComponentModel.Composition; using Bencodex; +using Libplanet.Crypto; using Libplanet.Types.Tx; using LibplanetConsole.Common; using LibplanetConsole.Common.Services; @@ -28,7 +29,7 @@ public async Task SendTransactionAsync( return (AppId)tx.Id; } - public Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken) + public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) => _node.GetNextNonceAsync(address, cancellationToken); public Task GetTipHashAsync(CancellationToken cancellationToken) @@ -36,8 +37,8 @@ public Task GetTipHashAsync(CancellationToken cancellationToken) public async Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { var value = await _node.GetStateAsync( @@ -47,8 +48,8 @@ public async Task GetStateAsync( public async Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken) { var value = await _node.GetStateByStateRootHashAsync( diff --git a/src/shared/LibplanetConsole.Client/ClientInfo.cs b/src/shared/LibplanetConsole.Client/ClientInfo.cs index 8f6a1bc3..c3f9b292 100644 --- a/src/shared/LibplanetConsole.Client/ClientInfo.cs +++ b/src/shared/LibplanetConsole.Client/ClientInfo.cs @@ -1,13 +1,13 @@ +using Libplanet.Crypto; using Libplanet.Types.Blocks; -using LibplanetConsole.Common; namespace LibplanetConsole.Client; public readonly record struct ClientInfo { - public AppAddress Address { get; init; } + public Address Address { get; init; } - public AppAddress NodeAddress { get; init; } + public Address NodeAddress { get; init; } public BlockHash GenesisHash { get; init; } diff --git a/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs b/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs index ab832e20..1dd228a7 100644 --- a/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs +++ b/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs @@ -9,7 +9,7 @@ public readonly record struct EvidenceInfo public string Id { get; init; } - public AppAddress TargetAddress { get; init; } + public Address TargetAddress { get; init; } public long Height { get; init; } @@ -22,7 +22,7 @@ public static explicit operator EvidenceInfo(EvidenceBase evidence) Type = evidence.GetType().Name, Id = evidence.Id.ToString(), Height = evidence.Height, - TargetAddress = (AppAddress)evidence.TargetAddress, + TargetAddress = evidence.TargetAddress, Timestamp = evidence.Timestamp, }; } diff --git a/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs b/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs index a3b27126..96ece7c2 100644 --- a/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs +++ b/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs @@ -1,10 +1,10 @@ -using LibplanetConsole.Common; +using Libplanet.Crypto; namespace LibplanetConsole.Example.Services; public interface IExampleNodeCallback { - void OnSubscribed(AppAddress address); + void OnSubscribed(Address address); - void OnUnsubscribed(AppAddress address); + void OnUnsubscribed(Address address); } diff --git a/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs b/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs index e36a38fa..833c5f3e 100644 --- a/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs +++ b/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs @@ -1,14 +1,14 @@ -using LibplanetConsole.Common; +using Libplanet.Crypto; namespace LibplanetConsole.Example.Services; public interface IExampleNodeService { - void Subscribe(AppAddress address); + void Subscribe(Address address); - void Unsubscribe(AppAddress address); + void Unsubscribe(Address address); Task GetAddressCountAsync(CancellationToken cancellationToken); - Task GetAddressesAsync(CancellationToken cancellationToken); + Task GetAddressesAsync(CancellationToken cancellationToken); } diff --git a/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs b/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs index 1f7bd7b7..4429281e 100644 --- a/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs +++ b/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs @@ -1,5 +1,4 @@ #if LIBPLANET_NODE -using System.Linq; using Libplanet.Blockchain; using Libplanet.Types.Blocks; using Libplanet.Types.Tx; @@ -13,7 +12,7 @@ public BlockInfo(BlockChain blockChain, Block block) { Height = block.Index; Hash = (AppHash)block.Hash; - Miner = (AppAddress)block.Miner; + Miner = block.Miner; Transactions = [.. block.Transactions.Select(GetTransaction)]; TransactionInfo GetTransaction(Transaction transaction) diff --git a/src/shared/LibplanetConsole.Node/BlockInfo.cs b/src/shared/LibplanetConsole.Node/BlockInfo.cs index c9c865ff..ad8af62b 100644 --- a/src/shared/LibplanetConsole.Node/BlockInfo.cs +++ b/src/shared/LibplanetConsole.Node/BlockInfo.cs @@ -1,3 +1,4 @@ +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Node; @@ -12,7 +13,7 @@ public BlockInfo() public AppHash Hash { get; init; } - public AppAddress Miner { get; init; } + public Address Miner { get; init; } public TransactionInfo[] Transactions { get; init; } = []; } diff --git a/src/shared/LibplanetConsole.Node/NodeInfo.cs b/src/shared/LibplanetConsole.Node/NodeInfo.cs index f4a8fbd8..b5623eb9 100644 --- a/src/shared/LibplanetConsole.Node/NodeInfo.cs +++ b/src/shared/LibplanetConsole.Node/NodeInfo.cs @@ -1,3 +1,4 @@ +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Node; @@ -12,7 +13,7 @@ public readonly record struct NodeInfo public string ConsensusEndPoint { get; init; } - public AppAddress Address { get; init; } + public Address Address { get; init; } public AppHash GenesisHash { get; init; } diff --git a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs index 0aa90453..e5c5c474 100644 --- a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs +++ b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs @@ -1,3 +1,4 @@ +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Node.Services; @@ -6,20 +7,20 @@ public interface IBlockChainService { Task SendTransactionAsync(byte[] transaction, CancellationToken cancellationToken); - Task GetNextNonceAsync(AppAddress address, CancellationToken cancellationToken); + Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( AppHash blockHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( AppHash stateRootHash, - AppAddress accountAddress, - AppAddress address, + Address accountAddress, + Address address, CancellationToken cancellationToken); Task GetBlockHashAsync(long height, CancellationToken cancellationToken); diff --git a/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs b/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs index f6d2342e..498e79fa 100644 --- a/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs +++ b/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs @@ -9,7 +9,7 @@ public readonly partial record struct TransactionInfo public TransactionInfo(TxExecution execution, ITransaction transaction) { Id = (AppId)transaction.Id; - Signer = (AppAddress)transaction.Signer; + Signer = transaction.Signer; Actions = GetActionInfos(transaction); IsFailed = execution.Fail; } diff --git a/src/shared/LibplanetConsole.Node/TransactionInfo.cs b/src/shared/LibplanetConsole.Node/TransactionInfo.cs index bee17c51..9ad57ef7 100644 --- a/src/shared/LibplanetConsole.Node/TransactionInfo.cs +++ b/src/shared/LibplanetConsole.Node/TransactionInfo.cs @@ -1,3 +1,4 @@ +using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Node; @@ -10,7 +11,7 @@ public TransactionInfo() public AppId Id { get; init; } = default; - public AppAddress Signer { get; init; } = default; + public Address Signer { get; init; } = default; public ActionInfo[] Actions { get; init; } = []; From 411d3d2cc68ffac7dd48a3bdfa50937770cea443 Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 14:29:11 +0900 Subject: [PATCH 2/9] refactor: Remove AppPublicKey --- GlobalUsings.props | 14 ++ src/client/Directory.Build.props | 4 +- src/client/GlobalUsings.cs | 1 - src/client/LibplanetConsole.Client/Client.cs | 3 +- src/client/LibplanetConsole.Client/IClient.cs | 2 +- src/common/LibplanetConsole.Common/AppPeer.cs | 9 +- .../LibplanetConsole.Common/AppPrivateKey.cs | 2 +- .../AppPublicKey.Bencodex.cs | 30 +-- .../LibplanetConsole.Common/AppPublicKey.cs | 188 +++++++++--------- .../Commands/KeyCommandBase.cs | 4 +- ...Converter.cs => PublicKeyJsonConverter.cs} | 11 +- ...ddressAttribute.cs => AddressAttribute.cs} | 6 +- ...cKeyAttribute.cs => PublicKeyAttribute.cs} | 10 +- .../Extensions/PublicKeyExtensions.cs | 29 +++ .../LibplanetConsole.Common/ISeedService.cs | 4 +- .../LibplanetConsole.Common.csproj | 2 + .../LibplanetConsole.Common/SeedInfo.cs | 2 +- .../LibplanetConsole.Seed/PeerUtility.cs | 2 +- src/console/Directory.Build.props | 4 +- src/console/GlobalUsings.cs | 1 - .../EntryCommands/InitializeCommand.cs | 2 +- .../LibplanetConsole.Console/Client.cs | 2 +- .../LibplanetConsole.Console/IClient.cs | 2 +- src/console/LibplanetConsole.Console/INode.cs | 2 +- src/console/LibplanetConsole.Console/Node.cs | 2 +- .../Services/SeedService.cs | 2 +- src/node/Directory.Build.props | 4 +- src/node/GlobalUsings.cs | 1 - .../ActionProvider.cs | 62 ++++++ .../EntryCommands/GenesisCommand.cs | 6 +- .../EntryCommands/InitializeCommand.cs | 2 +- .../LibplanetConsole.Node/ActionProvider.cs | 2 +- .../LibplanetConsole.Node/IActionProvider.cs | 2 +- src/node/LibplanetConsole.Node/INode.cs | 2 +- src/node/LibplanetConsole.Node/Node.cs | 3 +- src/node/LibplanetConsole.Node/PeerUtility.cs | 2 +- .../Services/SeedService.cs | 2 +- .../Actions/InitializeValidator.cs | 55 +++++ .../LibplanetConsole.Node/GenesisOptions.cs | 2 +- 39 files changed, 322 insertions(+), 163 deletions(-) create mode 100644 GlobalUsings.props delete mode 100644 src/client/GlobalUsings.cs rename src/common/LibplanetConsole.Common/Converters/{AppPublicKeyJsonConverter.cs => PublicKeyJsonConverter.cs} (54%) rename src/common/LibplanetConsole.Common/DataAnnotations/{AppAddressAttribute.cs => AddressAttribute.cs} (69%) rename src/common/LibplanetConsole.Common/DataAnnotations/{AppPublicKeyAttribute.cs => PublicKeyAttribute.cs} (50%) create mode 100644 src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs delete mode 100644 src/console/GlobalUsings.cs delete mode 100644 src/node/GlobalUsings.cs create mode 100644 src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs create mode 100644 src/shared/LibplanetConsole.Bank/Actions/InitializeValidator.cs diff --git a/GlobalUsings.props b/GlobalUsings.props new file mode 100644 index 00000000..bbd502e5 --- /dev/null +++ b/GlobalUsings.props @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/src/client/Directory.Build.props b/src/client/Directory.Build.props index 14c92fef..c3a9309c 100644 --- a/src/client/Directory.Build.props +++ b/src/client/Directory.Build.props @@ -14,8 +14,6 @@ LIBPLANET_CLIENT - - - + diff --git a/src/client/GlobalUsings.cs b/src/client/GlobalUsings.cs deleted file mode 100644 index 67618185..00000000 --- a/src/client/GlobalUsings.cs +++ /dev/null @@ -1 +0,0 @@ -global using Libplanet.Crypto; diff --git a/src/client/LibplanetConsole.Client/Client.cs b/src/client/LibplanetConsole.Client/Client.cs index a48309ed..ea16da57 100644 --- a/src/client/LibplanetConsole.Client/Client.cs +++ b/src/client/LibplanetConsole.Client/Client.cs @@ -2,6 +2,7 @@ using Libplanet.Crypto; using LibplanetConsole.Client.Services; using LibplanetConsole.Common; +using LibplanetConsole.Common.Extensions; using LibplanetConsole.Node; using LibplanetConsole.Node.Services; using Microsoft.Extensions.DependencyInjection; @@ -37,7 +38,7 @@ public Client(ApplicationBase application, ApplicationOptions options) public event EventHandler? Stopped; - public AppPublicKey PublicKey { get; } + public PublicKey PublicKey { get; } public Address Address => PublicKey.Address; diff --git a/src/client/LibplanetConsole.Client/IClient.cs b/src/client/LibplanetConsole.Client/IClient.cs index afdf118a..b299a1cf 100644 --- a/src/client/LibplanetConsole.Client/IClient.cs +++ b/src/client/LibplanetConsole.Client/IClient.cs @@ -17,7 +17,7 @@ public interface IClient : IVerifier bool IsRunning { get; } - AppPublicKey PublicKey { get; } + PublicKey PublicKey { get; } Address Address { get; } diff --git a/src/common/LibplanetConsole.Common/AppPeer.cs b/src/common/LibplanetConsole.Common/AppPeer.cs index 849b2479..e2072454 100644 --- a/src/common/LibplanetConsole.Common/AppPeer.cs +++ b/src/common/LibplanetConsole.Common/AppPeer.cs @@ -1,20 +1,21 @@ using System.Text.Json.Serialization; using Libplanet.Crypto; using LibplanetConsole.Common.Converters; +using LibplanetConsole.Common.DataAnnotations; namespace LibplanetConsole.Common; [JsonConverter(typeof(AppPeerJsonConverter))] -public readonly struct AppPeer(AppPublicKey publicKey, AppEndPoint endPoint) +public readonly struct AppPeer(PublicKey publicKey, AppEndPoint endPoint) { public const string HostExpression = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; public const string PortExpression = @"\d{1,5}"; public static readonly string RegularExpression - = $"^{AppPublicKey.RegularExpression},{AppEndPoint.RegularExpression}$"; + = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; - public AppPublicKey PublicKey { get; } = publicKey; + public PublicKey PublicKey { get; } = publicKey; public AppEndPoint EndPoint { get; } = endPoint; @@ -28,7 +29,7 @@ public static AppPeer Parse(string text) var items = text.Split(',', StringSplitOptions.RemoveEmptyEntries); if (items.Length == 2) { - var publicKey = AppPublicKey.Parse(items[0]); + var publicKey = PublicKey.FromHex(items[0]); var endPoint = AppEndPoint.Parse(items[1].Trim()); return new AppPeer(publicKey, endPoint); } diff --git a/src/common/LibplanetConsole.Common/AppPrivateKey.cs b/src/common/LibplanetConsole.Common/AppPrivateKey.cs index ffb493c8..9c41cf0b 100644 --- a/src/common/LibplanetConsole.Common/AppPrivateKey.cs +++ b/src/common/LibplanetConsole.Common/AppPrivateKey.cs @@ -31,7 +31,7 @@ public AppPrivateKey() { } - public AppPublicKey PublicKey => (AppPublicKey)_privateKey.PublicKey; + public PublicKey PublicKey => (PublicKey)_privateKey.PublicKey; public Address Address => _privateKey.PublicKey.Address; diff --git a/src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs b/src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs index c83fc800..611650c4 100644 --- a/src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs +++ b/src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs @@ -1,19 +1,19 @@ -using Bencodex.Types; -using Libplanet.Crypto; +// using Bencodex.Types; +// using Libplanet.Crypto; -namespace LibplanetConsole.Common; +// namespace LibplanetConsole.Common; -public readonly partial record struct AppPublicKey -{ - public static AppPublicKey FromBencodex(IValue value) - { - if (value is not Binary binary) - { - throw new InvalidCastException("The given value is not a binary."); - } +// public readonly partial record struct AppPublicKey +// { +// public static AppPublicKey FromBencodex(IValue value) +// { +// if (value is not Binary binary) +// { +// throw new InvalidCastException("The given value is not a binary."); +// } - return new(new PublicKey(binary.ByteArray)); - } +// return new(new PublicKey(binary.ByteArray)); +// } - public IValue ToBencodex() => new Binary(_publicKey.Format(true)); -} +// public IValue ToBencodex() => new Binary(_publicKey.Format(true)); +// } diff --git a/src/common/LibplanetConsole.Common/AppPublicKey.cs b/src/common/LibplanetConsole.Common/AppPublicKey.cs index 088f6604..cd076b5e 100644 --- a/src/common/LibplanetConsole.Common/AppPublicKey.cs +++ b/src/common/LibplanetConsole.Common/AppPublicKey.cs @@ -1,94 +1,94 @@ -using System.Diagnostics.CodeAnalysis; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Bencodex; -using Bencodex.Types; -using Libplanet.Common; -using Libplanet.Crypto; -using LibplanetConsole.Common.Converters; - -namespace LibplanetConsole.Common; - -[JsonConverter(typeof(AppPublicKeyJsonConverter))] -public readonly partial record struct AppPublicKey : IFormattable -{ - public const string RegularExpression = "(?:[0-9a-fA-F]{130}|[0-9a-fA-F]{66})"; - private static readonly Codec _codec = new(); - private readonly PublicKey _publicKey; - - public AppPublicKey(PublicKey publicKey) => _publicKey = publicKey; - - public Address Address => _publicKey.Address; - - public static explicit operator AppPublicKey(PublicKey publicKey) - => new(publicKey); - - public static explicit operator PublicKey(AppPublicKey publicKey) - => publicKey._publicKey; - - public static string ToString(AppPublicKey? publicKey) - => publicKey?.ToString() ?? string.Empty; - - public static AppPublicKey Parse(string text) => new(PublicKey.FromHex(text)); - - public static AppPublicKey? ParseOrDefault(string text) - => text == string.Empty ? null : Parse(text); - - public static bool TryParse(string text, [MaybeNullWhen(false)] out AppPublicKey publicKey) - { - try - { - publicKey = Parse(text); - return true; - } - catch - { - publicKey = default; - return false; - } - } - - public override string ToString() => _publicKey.ToHex(compress: false); - - public string ToString(string? format, IFormatProvider? formatProvider) - { - if (format is "S" or "C") - { - return _publicKey.ToHex(compress: true); - } - - return ToString(); - } - - public string ToShortString() => ToString(format: "S", formatProvider: null); - - public byte[] ToByteArray() => [.. _publicKey.ToImmutableArray(compress: false)]; - - public string Encrypt(object obj) - { - var json = JsonSerializer.Serialize(obj); - var encodings = Encoding.UTF8.GetBytes(json); - var encrypted = _publicKey.Encrypt(encodings); - return ByteUtil.Hex(encrypted); - } - - public byte[] Encrypt(byte[] bytes) => _publicKey.Encrypt(bytes); - - public bool Verify(object obj, byte[] signature) - { - if (obj is IValue value) - { - return _publicKey.Verify(_codec.Encode(value), signature); - } - - if (obj is IBencodable bencodable) - { - return _publicKey.Verify(_codec.Encode(bencodable.Bencoded), signature); - } - - var json = JsonSerializer.Serialize(obj); - var bytes = Encoding.UTF8.GetBytes(json); - return _publicKey.Verify(bytes, signature); - } -} +// using System.Diagnostics.CodeAnalysis; +// using System.Text; +// using System.Text.Json; +// using System.Text.Json.Serialization; +// using Bencodex; +// using Bencodex.Types; +// using Libplanet.Common; +// using Libplanet.Crypto; +// using LibplanetConsole.Common.Converters; + +// namespace LibplanetConsole.Common; + +// [JsonConverter(typeof(AppPublicKeyJsonConverter))] +// public readonly partial record struct AppPublicKey : IFormattable +// { +// public const string RegularExpression = "(?:[0-9a-fA-F]{130}|[0-9a-fA-F]{66})"; +// private static readonly Codec _codec = new(); +// private readonly PublicKey _publicKey; + +// public AppPublicKey(PublicKey publicKey) => _publicKey = publicKey; + +// public Address Address => _publicKey.Address; + +// public static explicit operator AppPublicKey(PublicKey publicKey) +// => new(publicKey); + +// public static explicit operator PublicKey(AppPublicKey publicKey) +// => publicKey._publicKey; + +// public static string ToString(AppPublicKey? publicKey) +// => publicKey?.ToString() ?? string.Empty; + +// public static AppPublicKey Parse(string text) => new(PublicKey.FromHex(text)); + +// public static AppPublicKey? ParseOrDefault(string text) +// => text == string.Empty ? null : Parse(text); + +// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppPublicKey publicKey) +// { +// try +// { +// publicKey = Parse(text); +// return true; +// } +// catch +// { +// publicKey = default; +// return false; +// } +// } + +// public override string ToString() => _publicKey.ToHex(compress: false); + +// public string ToString(string? format, IFormatProvider? formatProvider) +// { +// if (format is "S" or "C") +// { +// return _publicKey.ToHex(compress: true); +// } + +// return ToString(); +// } + +// public string ToShortString() => ToString(format: "S", formatProvider: null); + +// public byte[] ToByteArray() => [.. _publicKey.ToImmutableArray(compress: false)]; + +// public string Encrypt(object obj) +// { +// var json = JsonSerializer.Serialize(obj); +// var encodings = Encoding.UTF8.GetBytes(json); +// var encrypted = _publicKey.Encrypt(encodings); +// return ByteUtil.Hex(encrypted); +// } + +// public byte[] Encrypt(byte[] bytes) => _publicKey.Encrypt(bytes); + +// public bool Verify(object obj, byte[] signature) +// { +// if (obj is IValue value) +// { +// return _publicKey.Verify(_codec.Encode(value), signature); +// } + +// if (obj is IBencodable bencodable) +// { +// return _publicKey.Verify(_codec.Encode(bencodable.Bencoded), signature); +// } + +// var json = JsonSerializer.Serialize(obj); +// var bytes = Encoding.UTF8.GetBytes(json); +// return _publicKey.Verify(bytes, signature); +// } +// } diff --git a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs index 975588f7..2ece02d6 100644 --- a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs +++ b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs @@ -26,7 +26,6 @@ public void New( { PrivateKey = AppPrivateKey.ToString(privateKey), privateKey.PublicKey, - PublicKeyShort = privateKey.PublicKey.ToShortString(), privateKey.Address, }; }).ToArray(); @@ -43,7 +42,6 @@ public void Public( var info = new { key.PublicKey, - PublicKeyShort = key.PublicKey.ToShortString(), }; Out.WriteLineAsJson(info); } @@ -83,7 +81,7 @@ private static Address GetAddress(string key) return privateKey.Address; } - if (AppPublicKey.TryParse(key, out var publicKey) == true) + if (PublicKey.FromHex(key) is { } publicKey) { return publicKey.Address; } diff --git a/src/common/LibplanetConsole.Common/Converters/AppPublicKeyJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/PublicKeyJsonConverter.cs similarity index 54% rename from src/common/LibplanetConsole.Common/Converters/AppPublicKeyJsonConverter.cs rename to src/common/LibplanetConsole.Common/Converters/PublicKeyJsonConverter.cs index b6b448ec..0bb914c1 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppPublicKeyJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/PublicKeyJsonConverter.cs @@ -1,25 +1,26 @@ using System.Text.Json; using System.Text.Json.Serialization; +using Libplanet.Crypto; namespace LibplanetConsole.Common.Converters; -public sealed class AppPublicKeyJsonConverter : JsonConverter +public sealed class PublicKeyJsonConverter : JsonConverter { - public override AppPublicKey Read( + public override PublicKey Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.GetString() is string text) { - return AppPublicKey.Parse(text); + return PublicKey.FromHex(text); } - throw new JsonException("Cannot read AppPublicKey from JSON."); + throw new JsonException("Cannot read PublicKey from JSON."); } public override void Write( - Utf8JsonWriter writer, AppPublicKey value, JsonSerializerOptions options) + Utf8JsonWriter writer, PublicKey value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppAddressAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/AddressAttribute.cs similarity index 69% rename from src/common/LibplanetConsole.Common/DataAnnotations/AppAddressAttribute.cs rename to src/common/LibplanetConsole.Common/DataAnnotations/AddressAttribute.cs index eadafb46..558c2671 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppAddressAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/AddressAttribute.cs @@ -5,17 +5,17 @@ namespace LibplanetConsole.Common.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] -public sealed class AppAddressAttribute : RegularExpressionAttribute +public sealed class AddressAttribute : RegularExpressionAttribute { public const string RegularExpression = "0x[0-9a-fA-F]{40}"; - public AppAddressAttribute() + public AddressAttribute() : base($"^{RegularExpression}$") { } } [AttributeUsage(AttributeTargets.Property)] -public sealed class AddressArrayAttribute : ArrayAttribute +public sealed class AddressArrayAttribute : ArrayAttribute { } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppPublicKeyAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/PublicKeyAttribute.cs similarity index 50% rename from src/common/LibplanetConsole.Common/DataAnnotations/AppPublicKeyAttribute.cs rename to src/common/LibplanetConsole.Common/DataAnnotations/PublicKeyAttribute.cs index f884d67f..68d808b9 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppPublicKeyAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/PublicKeyAttribute.cs @@ -5,15 +5,17 @@ namespace LibplanetConsole.Common.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] -public sealed class AppPublicKeyAttribute : RegularExpressionAttribute +public sealed class PublicKeyAttribute : RegularExpressionAttribute { - public AppPublicKeyAttribute() - : base($"^{AppPublicKey.RegularExpression}$") + public const string RegularExpression = "(?:[0-9a-fA-F]{130}|[0-9a-fA-F]{66})"; + + public PublicKeyAttribute() + : base($"^{RegularExpression}$") { } } [AttributeUsage(AttributeTargets.Property)] -public sealed class AppPublicKeyArrayAttribute : ArrayAttribute +public sealed class PublicKeyArrayAttribute : ArrayAttribute { } diff --git a/src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs new file mode 100644 index 00000000..3e1006ef --- /dev/null +++ b/src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs @@ -0,0 +1,29 @@ +using System.Text; +using System.Text.Json; +using Bencodex; +using Bencodex.Types; +using Libplanet.Crypto; + +namespace LibplanetConsole.Common.Extensions; + +public static class PublicKeyExtensions +{ + private static readonly Codec _codec = new(); + + public static bool Verify(this PublicKey @this, object obj, byte[] signature) + { + if (obj is IValue value) + { + return @this.Verify(_codec.Encode(value), signature); + } + + if (obj is IBencodable bencodable) + { + return @this.Verify(_codec.Encode(bencodable.Bencoded), signature); + } + + var json = JsonSerializer.Serialize(obj); + var bytes = Encoding.UTF8.GetBytes(json); + return @this.Verify(bytes, signature); + } +} diff --git a/src/common/LibplanetConsole.Common/ISeedService.cs b/src/common/LibplanetConsole.Common/ISeedService.cs index 55afaa96..f219f9ae 100644 --- a/src/common/LibplanetConsole.Common/ISeedService.cs +++ b/src/common/LibplanetConsole.Common/ISeedService.cs @@ -1,6 +1,8 @@ +using Libplanet.Crypto; + namespace LibplanetConsole.Common; public interface ISeedService { - Task GetSeedAsync(AppPublicKey publicKey, CancellationToken cancellationToken); + Task GetSeedAsync(PublicKey publicKey, CancellationToken cancellationToken); } diff --git a/src/common/LibplanetConsole.Common/LibplanetConsole.Common.csproj b/src/common/LibplanetConsole.Common/LibplanetConsole.Common.csproj index 328c27a7..998bbf95 100644 --- a/src/common/LibplanetConsole.Common/LibplanetConsole.Common.csproj +++ b/src/common/LibplanetConsole.Common/LibplanetConsole.Common.csproj @@ -58,4 +58,6 @@ + + diff --git a/src/common/LibplanetConsole.Common/SeedInfo.cs b/src/common/LibplanetConsole.Common/SeedInfo.cs index 64ea5601..50fbdac6 100644 --- a/src/common/LibplanetConsole.Common/SeedInfo.cs +++ b/src/common/LibplanetConsole.Common/SeedInfo.cs @@ -8,7 +8,7 @@ public readonly record struct SeedInfo public AppPeer ConsensusSeedPeer { get; init; } - public SeedInfo Encrypt(AppPublicKey publicKey) => this with + public SeedInfo Encrypt(PublicKey publicKey) => this with { }; diff --git a/src/common/LibplanetConsole.Seed/PeerUtility.cs b/src/common/LibplanetConsole.Seed/PeerUtility.cs index 6b56580c..c66321e0 100644 --- a/src/common/LibplanetConsole.Seed/PeerUtility.cs +++ b/src/common/LibplanetConsole.Seed/PeerUtility.cs @@ -11,5 +11,5 @@ public static BoundPeer ToBoundPeer(AppPeer peer) => new((PublicKey)peer.PublicKey, (DnsEndPoint)peer.EndPoint); public static AppPeer ToAppPeer(BoundPeer boundPeer) - => new((AppPublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); + => new((PublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); } diff --git a/src/console/Directory.Build.props b/src/console/Directory.Build.props index ac9d8e36..5dd94c29 100644 --- a/src/console/Directory.Build.props +++ b/src/console/Directory.Build.props @@ -14,8 +14,6 @@ LIBPLANET_CONSOLE - - - + diff --git a/src/console/GlobalUsings.cs b/src/console/GlobalUsings.cs deleted file mode 100644 index 67618185..00000000 --- a/src/console/GlobalUsings.cs +++ /dev/null @@ -1 +0,0 @@ -global using Libplanet.Crypto; diff --git a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs index 1cc0fd47..740cc484 100644 --- a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs +++ b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs @@ -117,7 +117,7 @@ protected override void OnExecute() { GenesisKey = AppPrivateKey.ToString(genesisKey), Validators = nodeOptions.Select( - item => AppPublicKey.ToString(item.PrivateKey.PublicKey)), + item => item.PrivateKey.PublicKey.ToHex(compress: false)), Timestamp = dateTimeOffset, ActionProviderModulePath, ActionProviderType, diff --git a/src/console/LibplanetConsole.Console/Client.cs b/src/console/LibplanetConsole.Console/Client.cs index e53481ff..1e7b2a00 100644 --- a/src/console/LibplanetConsole.Console/Client.cs +++ b/src/console/LibplanetConsole.Console/Client.cs @@ -59,7 +59,7 @@ public Client(ApplicationBase application, ClientOptions clientOptions) public event EventHandler? Disposed; - public AppPublicKey PublicKey { get; } + public PublicKey PublicKey { get; } public Address Address => PublicKey.Address; diff --git a/src/console/LibplanetConsole.Console/IClient.cs b/src/console/LibplanetConsole.Console/IClient.cs index c065e793..71bcc715 100644 --- a/src/console/LibplanetConsole.Console/IClient.cs +++ b/src/console/LibplanetConsole.Console/IClient.cs @@ -23,7 +23,7 @@ public interface IClient : IAddressable, IAsyncDisposable, IServiceProvider, ISi ClientInfo Info { get; } - AppPublicKey PublicKey { get; } + PublicKey PublicKey { get; } Task AttachAsync(CancellationToken cancellationToken); diff --git a/src/console/LibplanetConsole.Console/INode.cs b/src/console/LibplanetConsole.Console/INode.cs index ca0c9f92..0d5d19b2 100644 --- a/src/console/LibplanetConsole.Console/INode.cs +++ b/src/console/LibplanetConsole.Console/INode.cs @@ -23,7 +23,7 @@ public interface INode : IAddressable, IAsyncDisposable, IServiceProvider, ISign NodeInfo Info { get; } - AppPublicKey PublicKey { get; } + PublicKey PublicKey { get; } Task AttachAsync(CancellationToken cancellationToken); diff --git a/src/console/LibplanetConsole.Console/Node.cs b/src/console/LibplanetConsole.Console/Node.cs index 4296371f..2eee2198 100644 --- a/src/console/LibplanetConsole.Console/Node.cs +++ b/src/console/LibplanetConsole.Console/Node.cs @@ -71,7 +71,7 @@ public AppEndPoint SwarmEndPoint public AppEndPoint ConsensusEndPoint => _consensusEndPoint ?? throw new InvalidOperationException("ConsensusPeer is not set."); - public AppPublicKey PublicKey { get; } + public PublicKey PublicKey { get; } public Address Address => PublicKey.Address; diff --git a/src/console/LibplanetConsole.Console/Services/SeedService.cs b/src/console/LibplanetConsole.Console/Services/SeedService.cs index adf28b0d..e3179cbf 100644 --- a/src/console/LibplanetConsole.Console/Services/SeedService.cs +++ b/src/console/LibplanetConsole.Console/Services/SeedService.cs @@ -38,7 +38,7 @@ public SeedService(ApplicationBase application) public AppPeer ConsensusSeedPeer => _consensusSeedNode.BoundPeer; public async Task GetSeedAsync( - AppPublicKey publicKey, CancellationToken cancellationToken) + PublicKey publicKey, CancellationToken cancellationToken) { var seedPeer = _blocksyncSeedNode.BoundPeer; var consensusSeedPeer = _consensusSeedNode.BoundPeer; diff --git a/src/node/Directory.Build.props b/src/node/Directory.Build.props index 4618ace0..ebce5647 100644 --- a/src/node/Directory.Build.props +++ b/src/node/Directory.Build.props @@ -14,8 +14,6 @@ LIBPLANET_NODE - - - + diff --git a/src/node/GlobalUsings.cs b/src/node/GlobalUsings.cs deleted file mode 100644 index 67618185..00000000 --- a/src/node/GlobalUsings.cs +++ /dev/null @@ -1 +0,0 @@ -global using Libplanet.Crypto; diff --git a/src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs b/src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs new file mode 100644 index 00000000..6b543e17 --- /dev/null +++ b/src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs @@ -0,0 +1,62 @@ +using System.Collections.Immutable; +using System.Numerics; +using System.Reflection; +using Libplanet.Action; +using Libplanet.Action.Loader; +using Libplanet.Crypto; +using Libplanet.Types.Assets; +using Libplanet.Types.Consensus; +using LibplanetConsole.Common; +using LibplanetConsole.Common.Actions; +using LibplanetConsole.Framework; +using Nekoyume.Action; +using Nekoyume.Action.Loader; +using Nekoyume.Action.ValidatorDelegation; + +namespace LibplanetConsole.Node.Delegation; + +internal sealed class ActionProvider : IActionProvider +{ + public ImmutableArray BeginBlockActions { get; } = + [ + new SlashValidator(), + new AllocateReward(), + ]; + + public ImmutableArray EndBlockActions { get; } = + [ + new UpdateValidators(), + new RecordProposer(), + new RewardGold(), + new ReleaseValidatorUnbondings(), + ]; + + public ImmutableArray BeginTxActions { get; } = []; + + public ImmutableArray EndTxActions { get; } = []; + + public IActionLoader GetActionLoader() + { + var assemblies = ApplicationContainer.GetAssemblies(Assembly.GetExecutingAssembly()); + IActionLoader[] actionLoaders = + [ + new NCActionLoader(), + .. assemblies.Select(item => new AssemblyActionLoader(item)), + ]; + return new AggregateTypedActionLoader(actionLoaders); + } + + public IAction[] GetGenesisActions(AppPrivateKey genesisKey, PublicKey[] validatorKeys) + { + var validators = validatorKeys + .Select(item => new Validator((PublicKey)item, BigInteger.One)) + .ToArray(); + var action = new InitializeStates + { + Validators = validators, + GoldCurrency = Currency.Uncapped("NCG", 2, genesisKey.Address), + }; + + return [action]; + } +} diff --git a/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs b/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs index cba0cea8..edd3ab36 100644 --- a/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs +++ b/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs @@ -23,7 +23,7 @@ public sealed class GenesisCommand : CommandBase [CommandPropertyExclusion(nameof(ValidatorCount))] [CommandSummary("The public keys of the validators. mutually exclusive with " + "'--validator-count'.")] - [AppPublicKeyArray] + [PublicKeyArray] public string[] Validators { get; set; } = []; [CommandProperty] @@ -90,11 +90,11 @@ protected override void OnExecute() } } - private AppPublicKey[] GetValidators() + private PublicKey[] GetValidators() { if (Validators.Length > 0) { - return [.. Validators.Select(AppPublicKey.Parse)]; + return [.. Validators.Select(PublicKey.FromHex)]; } else if (ValidatorCount > 0) { diff --git a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs index 3a7e4838..2a5cca1f 100644 --- a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs +++ b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs @@ -146,7 +146,7 @@ protected override void OnExecute() { GenesisKey = AppPrivateKey.ToString(genesisOptions.GenesisKey), Validators = genesisOptions.Validators.Select( - item => AppPublicKey.ToString(item)), + item => item.ToHex(compress: false)), genesisOptions.Timestamp, genesisOptions.ActionProviderModulePath, genesisOptions.ActionProviderType, diff --git a/src/node/LibplanetConsole.Node/ActionProvider.cs b/src/node/LibplanetConsole.Node/ActionProvider.cs index dddc3e4e..2157b9f6 100644 --- a/src/node/LibplanetConsole.Node/ActionProvider.cs +++ b/src/node/LibplanetConsole.Node/ActionProvider.cs @@ -24,7 +24,7 @@ internal sealed class ActionProvider : IActionProvider public ImmutableArray EndTxActions { get; } = []; - public IAction[] GetGenesisActions(AppPrivateKey genesisKey, AppPublicKey[] validatorKeys) + public IAction[] GetGenesisActions(AppPrivateKey genesisKey, PublicKey[] validatorKeys) { var validators = validatorKeys .Select(item => new Validator((PublicKey)item, BigInteger.One)) diff --git a/src/node/LibplanetConsole.Node/IActionProvider.cs b/src/node/LibplanetConsole.Node/IActionProvider.cs index 12cca330..a16cc61f 100644 --- a/src/node/LibplanetConsole.Node/IActionProvider.cs +++ b/src/node/LibplanetConsole.Node/IActionProvider.cs @@ -15,7 +15,7 @@ public interface IActionProvider ImmutableArray EndTxActions { get; } - IAction[] GetGenesisActions(AppPrivateKey genesisKey, AppPublicKey[] validatorKeys); + IAction[] GetGenesisActions(AppPrivateKey genesisKey, PublicKey[] validatorKeys); IActionLoader GetActionLoader(); } diff --git a/src/node/LibplanetConsole.Node/INode.cs b/src/node/LibplanetConsole.Node/INode.cs index 23af2080..9a4dbf4d 100644 --- a/src/node/LibplanetConsole.Node/INode.cs +++ b/src/node/LibplanetConsole.Node/INode.cs @@ -14,7 +14,7 @@ public interface INode : IVerifier, ISigner, IServiceProvider bool IsRunning { get; } - AppPublicKey PublicKey { get; } + PublicKey PublicKey { get; } Address Address => PublicKey.Address; diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index a5577824..2b0c8d52 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -15,6 +15,7 @@ using Libplanet.Types.Tx; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; +using LibplanetConsole.Common.Extensions; using LibplanetConsole.Common.Services; using LibplanetConsole.Seed; using Serilog; @@ -82,7 +83,7 @@ public AppEndPoint ConsensusEndPoint public bool IsDisposed => _isDisposed; - public AppPublicKey PublicKey { get; } + public PublicKey PublicKey { get; } public Address Address => PublicKey.Address; diff --git a/src/node/LibplanetConsole.Node/PeerUtility.cs b/src/node/LibplanetConsole.Node/PeerUtility.cs index 2fc1879e..c8ec8612 100644 --- a/src/node/LibplanetConsole.Node/PeerUtility.cs +++ b/src/node/LibplanetConsole.Node/PeerUtility.cs @@ -11,5 +11,5 @@ public static BoundPeer ToBoundPeer(AppPeer peer) => new((PublicKey)peer.PublicKey, (DnsEndPoint)peer.EndPoint); public static AppPeer ToAppPeer(BoundPeer boundPeer) - => new((AppPublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); + => new((PublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); } diff --git a/src/node/LibplanetConsole.Node/Services/SeedService.cs b/src/node/LibplanetConsole.Node/Services/SeedService.cs index e2a7fbc8..ac1630ce 100644 --- a/src/node/LibplanetConsole.Node/Services/SeedService.cs +++ b/src/node/LibplanetConsole.Node/Services/SeedService.cs @@ -17,7 +17,7 @@ internal sealed class SeedService(ApplicationBase application) private SeedNode? _consensusSeedNode; public async Task GetSeedAsync( - AppPublicKey publicKey, CancellationToken cancellationToken) + PublicKey publicKey, CancellationToken cancellationToken) { if (_blocksyncSeedNode is null || _consensusSeedNode is null) { diff --git a/src/shared/LibplanetConsole.Bank/Actions/InitializeValidator.cs b/src/shared/LibplanetConsole.Bank/Actions/InitializeValidator.cs new file mode 100644 index 00000000..22808341 --- /dev/null +++ b/src/shared/LibplanetConsole.Bank/Actions/InitializeValidator.cs @@ -0,0 +1,55 @@ +using Bencodex.Types; +using Libplanet.Action; +using Libplanet.Action.State; +using Libplanet.Crypto; +using Libplanet.Types.Assets; +using LibplanetConsole.Common; + +namespace LibplanetConsole.Bank.Actions; + +[ActionType(TypeIdentifier)] +public sealed class InitializeValidator : ActionBase +{ + private const string TypeIdentifier = "initialize_validator"; + + public InitializeValidator(PublicKey validator, decimal amount) + { + Validator = validator; + Amount = amount; + } + + public InitializeValidator() + { + Validator = new PrivateKey().PublicKey; + } + + public PublicKey Validator { get; set; } + + public decimal Amount { get; set; } + + public Currency Currency { get; set; } = AssetUtility.NCG; + + protected override Dictionary OnInitialize(Dictionary values) + { + return base.OnInitialize(values) + .Add("validator", Validator.ToBencodex()) + .Add("amount", $"{Amount:R}") + .Add("currency", Currency.Serialize()); + } + + protected override void OnLoadPlainValue(Dictionary values) + { + base.OnLoadPlainValue(values); + Validator = PublicKey.FromBencodex(values["validator"]); + Amount = decimal.Parse((Text)values["amount"]); + Currency = new Currency(values["currency"]); + } + + protected override IWorld OnExecute(IActionContext context) + { + GasTracer.UseGas(1); + var world = context.PreviousState; + + return world; + } +} diff --git a/src/shared/LibplanetConsole.Node/GenesisOptions.cs b/src/shared/LibplanetConsole.Node/GenesisOptions.cs index 175bdc7a..5b4377af 100644 --- a/src/shared/LibplanetConsole.Node/GenesisOptions.cs +++ b/src/shared/LibplanetConsole.Node/GenesisOptions.cs @@ -4,7 +4,7 @@ public sealed record class GenesisOptions { public AppPrivateKey GenesisKey { get; init; } = new(); - public AppPublicKey[] Validators { get; init; } = []; + public PublicKey[] Validators { get; init; } = []; public DateTimeOffset Timestamp { get; init; } = DateTimeOffset.MinValue; From 5ca60a2a268d8861bf51b2df420adbe56e04501e Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 14:31:55 +0900 Subject: [PATCH 3/9] refactor: Remove AppId --- .../Client.BlockChain.cs | 6 +- .../LibplanetConsole.Client/IBlockChain.cs | 4 +- src/client/LibplanetConsole.Client/IClient.cs | 2 +- .../Services/ClientService.cs | 2 +- src/common/LibplanetConsole.Common/AppId.cs | 88 +++++++++---------- .../Converters/AppIdJsonConverter.cs | 44 +++++----- .../LibplanetConsole.Console/Client.cs | 2 +- .../LibplanetConsole.Console/IBlockChain.cs | 4 +- .../LibplanetConsole.Console/IClient.cs | 2 +- .../Node.BlockChain.cs | 6 +- src/node/LibplanetConsole.Node/IBlockChain.cs | 4 +- src/node/LibplanetConsole.Node/INode.cs | 2 +- .../LibplanetConsole.Node/Node.BlockChain.cs | 12 +-- .../Services/BlockChainService.cs | 6 +- .../Services/IClientService.cs | 2 +- .../LibplanetConsole.Node/ActionInfo.cs | 2 +- .../Services/IBlockChainService.cs | 4 +- .../TransactionInfo.Node.cs | 4 +- .../LibplanetConsole.Node/TransactionInfo.cs | 2 +- 19 files changed, 99 insertions(+), 99 deletions(-) diff --git a/src/client/LibplanetConsole.Client/Client.BlockChain.cs b/src/client/LibplanetConsole.Client/Client.BlockChain.cs index 50220d3c..7e020f20 100644 --- a/src/client/LibplanetConsole.Client/Client.BlockChain.cs +++ b/src/client/LibplanetConsole.Client/Client.BlockChain.cs @@ -13,7 +13,7 @@ internal sealed partial class Client : IBlockChain { private static readonly Codec _codec = new(); - public async Task SendTransactionAsync( + public async Task SendTransactionAsync( IAction[] actions, CancellationToken cancellationToken) { var privateKey = AppPrivateKey.FromSecureString(_privateKey); @@ -26,7 +26,7 @@ public async Task SendTransactionAsync( genesisHash: (BlockHash)genesisHash, actions: [.. actions.Select(item => item.PlainValue)]); var txData = tx.Serialize(); - _logger.Debug("Client sends a transaction: {AppId}", tx.Id); + _logger.Debug("Client sends a transaction: {TxId}", tx.Id); return await RemoteBlockChainService.SendTransactionAsync(txData, cancellationToken); } @@ -62,7 +62,7 @@ public async Task GetStateByStateRootHashAsync( } public async Task GetActionAsync( - AppId txId, int actionIndex, CancellationToken cancellationToken) + TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction { var bytes = await RemoteBlockChainService.GetActionAsync( diff --git a/src/client/LibplanetConsole.Client/IBlockChain.cs b/src/client/LibplanetConsole.Client/IBlockChain.cs index ec5ff37f..a9be0663 100644 --- a/src/client/LibplanetConsole.Client/IBlockChain.cs +++ b/src/client/LibplanetConsole.Client/IBlockChain.cs @@ -9,7 +9,7 @@ public interface IBlockChain { event EventHandler? BlockAppended; - Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); + Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); @@ -29,6 +29,6 @@ Task GetStateByStateRootHashAsync( Task GetBlockHashAsync(long height, CancellationToken cancellationToken); - Task GetActionAsync(AppId txId, int actionIndex, CancellationToken cancellationToken) + Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction; } diff --git a/src/client/LibplanetConsole.Client/IClient.cs b/src/client/LibplanetConsole.Client/IClient.cs index b299a1cf..b74160a0 100644 --- a/src/client/LibplanetConsole.Client/IClient.cs +++ b/src/client/LibplanetConsole.Client/IClient.cs @@ -27,5 +27,5 @@ public interface IClient : IVerifier Task StopAsync(CancellationToken cancellationToken); - Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); + Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); } diff --git a/src/client/LibplanetConsole.Client/Services/ClientService.cs b/src/client/LibplanetConsole.Client/Services/ClientService.cs index 77d02086..7d521ee7 100644 --- a/src/client/LibplanetConsole.Client/Services/ClientService.cs +++ b/src/client/LibplanetConsole.Client/Services/ClientService.cs @@ -36,7 +36,7 @@ public async Task StartAsync( public Task StopAsync(CancellationToken cancellationToken) => _client.StopAsync(cancellationToken); - public async Task SendTransactionAsync( + public async Task SendTransactionAsync( TransactionOptions transactionOptions, CancellationToken cancellationToken) { if (transactionOptions.TryVerify(_client) == true) diff --git a/src/common/LibplanetConsole.Common/AppId.cs b/src/common/LibplanetConsole.Common/AppId.cs index a87da0b8..9d538262 100644 --- a/src/common/LibplanetConsole.Common/AppId.cs +++ b/src/common/LibplanetConsole.Common/AppId.cs @@ -1,58 +1,58 @@ -using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json.Serialization; -using Libplanet.Common; -using Libplanet.Types.Tx; -using LibplanetConsole.Common.Converters; +// using System.Collections.Immutable; +// using System.Diagnostics.CodeAnalysis; +// using System.Text.Json.Serialization; +// using Libplanet.Common; +// using Libplanet.Types.Tx; +// using LibplanetConsole.Common.Converters; -namespace LibplanetConsole.Common; +// namespace LibplanetConsole.Common; -[JsonConverter(typeof(AppIdJsonConverter))] -public readonly record struct AppId : IFormattable -{ - private readonly ImmutableArray _bytes; +// [JsonConverter(typeof(AppIdJsonConverter))] +// public readonly record struct AppId : IFormattable +// { +// private readonly ImmutableArray _bytes; - public AppId(byte[] bytes) => _bytes = [.. bytes]; +// public AppId(byte[] bytes) => _bytes = [.. bytes]; - public AppId(ImmutableArray bytes) => _bytes = bytes; +// public AppId(ImmutableArray bytes) => _bytes = bytes; - public AppId(TxId txId) => _bytes = txId.ByteArray; +// public AppId(TxId txId) => _bytes = txId.ByteArray; - public static explicit operator AppId(TxId txId) => new(txId); +// public static explicit operator AppId(TxId txId) => new(txId); - public static explicit operator TxId(AppId id) => new(id._bytes); +// public static explicit operator TxId(AppId id) => new(id._bytes); - public static string ToString(AppId? blockHash) - => blockHash?.ToString() ?? string.Empty; +// public static string ToString(AppId? blockHash) +// => blockHash?.ToString() ?? string.Empty; - public static AppId Parse(string text) => new(ByteUtil.ParseHexToImmutable(text)); +// public static AppId Parse(string text) => new(ByteUtil.ParseHexToImmutable(text)); - public static AppId? ParseOrDefault(string text) - => text == string.Empty ? null : Parse(text); +// public static AppId? ParseOrDefault(string text) +// => text == string.Empty ? null : Parse(text); - public static bool TryParse(string text, [MaybeNullWhen(false)] out AppId blockHash) - { - try - { - blockHash = Parse(text); - return true; - } - catch - { - blockHash = default; - return false; - } - } +// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppId blockHash) +// { +// try +// { +// blockHash = Parse(text); +// return true; +// } +// catch +// { +// blockHash = default; +// return false; +// } +// } - public override string ToString() => ByteUtil.Hex(_bytes); +// public override string ToString() => ByteUtil.Hex(_bytes); - public string ToString(string? format, IFormatProvider? formatProvider) - { - if (format is "S") - { - return ToString()[..8]; - } +// public string ToString(string? format, IFormatProvider? formatProvider) +// { +// if (format is "S") +// { +// return ToString()[..8]; +// } - return ToString(); - } -} +// return ToString(); +// } +// } diff --git a/src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs index 0451c89d..8226c338 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs @@ -1,26 +1,26 @@ -using System.Text.Json; -using System.Text.Json.Serialization; +// using System.Text.Json; +// using System.Text.Json.Serialization; -namespace LibplanetConsole.Common.Converters; +// namespace LibplanetConsole.Common.Converters; -public sealed class AppIdJsonConverter : JsonConverter -{ - public override AppId Read( - ref Utf8JsonReader reader, - Type typeToConvert, - JsonSerializerOptions options) - { - if (reader.GetString() is string text) - { - return AppId.Parse(text); - } +// public sealed class TxIdJsonConverter : JsonConverter +// { +// public override TxId Read( +// ref Utf8JsonReader reader, +// Type typeToConvert, +// JsonSerializerOptions options) +// { +// if (reader.GetString() is string text) +// { +// return TxId.Parse(text); +// } - throw new JsonException("Cannot read AppId from JSON."); - } +// throw new JsonException("Cannot read TxId from JSON."); +// } - public override void Write( - Utf8JsonWriter writer, AppId value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } -} +// public override void Write( +// Utf8JsonWriter writer, TxId value, JsonSerializerOptions options) +// { +// writer.WriteStringValue(value.ToString()); +// } +// } diff --git a/src/console/LibplanetConsole.Console/Client.cs b/src/console/LibplanetConsole.Console/Client.cs index 1e7b2a00..6b310a28 100644 --- a/src/console/LibplanetConsole.Console/Client.cs +++ b/src/console/LibplanetConsole.Console/Client.cs @@ -185,7 +185,7 @@ public async Task StopAsync(CancellationToken cancellationToken) Stopped?.Invoke(this, EventArgs.Empty); } - public async Task SendTransactionAsync(string text, CancellationToken cancellationToken) + public async Task SendTransactionAsync(string text, CancellationToken cancellationToken) { var transactionOptions = new TransactionOptions { diff --git a/src/console/LibplanetConsole.Console/IBlockChain.cs b/src/console/LibplanetConsole.Console/IBlockChain.cs index b33513ca..b3a61a04 100644 --- a/src/console/LibplanetConsole.Console/IBlockChain.cs +++ b/src/console/LibplanetConsole.Console/IBlockChain.cs @@ -9,7 +9,7 @@ public interface IBlockChain { event EventHandler? BlockAppended; - Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); + Task SendTransactionAsync(IAction[] actions, CancellationToken cancellationToken); Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); @@ -29,6 +29,6 @@ Task GetStateByStateRootHashAsync( Task GetBlockHashAsync(long height, CancellationToken cancellationToken); - Task GetActionAsync(AppId txId, int actionIndex, CancellationToken cancellationToken) + Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction; } diff --git a/src/console/LibplanetConsole.Console/IClient.cs b/src/console/LibplanetConsole.Console/IClient.cs index 71bcc715..a6b6eb0f 100644 --- a/src/console/LibplanetConsole.Console/IClient.cs +++ b/src/console/LibplanetConsole.Console/IClient.cs @@ -33,5 +33,5 @@ public interface IClient : IAddressable, IAsyncDisposable, IServiceProvider, ISi Task StopAsync(CancellationToken cancellationToken); - Task SendTransactionAsync(string text, CancellationToken cancellationToken); + Task SendTransactionAsync(string text, CancellationToken cancellationToken); } diff --git a/src/console/LibplanetConsole.Console/Node.BlockChain.cs b/src/console/LibplanetConsole.Console/Node.BlockChain.cs index 42707983..488433fc 100644 --- a/src/console/LibplanetConsole.Console/Node.BlockChain.cs +++ b/src/console/LibplanetConsole.Console/Node.BlockChain.cs @@ -16,7 +16,7 @@ internal sealed partial class Node public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) => _blockChainService.Service.GetNextNonceAsync(address, cancellationToken); - public async Task SendTransactionAsync( + public async Task SendTransactionAsync( IAction[] actions, CancellationToken cancellationToken) { var privateKey = _nodeOptions.PrivateKey; @@ -35,7 +35,7 @@ public async Task SendTransactionAsync( return txId; } - public Task SendTransactionAsync( + public Task SendTransactionAsync( Transaction transaction, CancellationToken cancellationToken) { return _blockChainService.Service.SendTransactionAsync( @@ -83,7 +83,7 @@ public Task GetBlockHashAsync(long height, CancellationToken cancellati => _blockChainService.Service.GetBlockHashAsync(height, cancellationToken); public async Task GetActionAsync( - AppId txId, + TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction diff --git a/src/node/LibplanetConsole.Node/IBlockChain.cs b/src/node/LibplanetConsole.Node/IBlockChain.cs index 8b31c51e..bdfac04f 100644 --- a/src/node/LibplanetConsole.Node/IBlockChain.cs +++ b/src/node/LibplanetConsole.Node/IBlockChain.cs @@ -9,7 +9,7 @@ public interface IBlockChain { event EventHandler? BlockAppended; - Task AddTransactionAsync(IAction[] actions, CancellationToken cancellationToken); + Task AddTransactionAsync(IAction[] actions, CancellationToken cancellationToken); Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); @@ -29,6 +29,6 @@ Task GetStateByStateRootHashAsync( Task GetBlockHashAsync(long height, CancellationToken cancellationToken); - Task GetActionAsync(AppId txId, int actionIndex, CancellationToken cancellationToken) + Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction; } diff --git a/src/node/LibplanetConsole.Node/INode.cs b/src/node/LibplanetConsole.Node/INode.cs index 9a4dbf4d..0b77bdb7 100644 --- a/src/node/LibplanetConsole.Node/INode.cs +++ b/src/node/LibplanetConsole.Node/INode.cs @@ -22,5 +22,5 @@ public interface INode : IVerifier, ISigner, IServiceProvider Task StopAsync(CancellationToken cancellationToken); - Task AddTransactionAsync(IAction[] actions, CancellationToken cancellationToken); + Task AddTransactionAsync(IAction[] actions, CancellationToken cancellationToken); } diff --git a/src/node/LibplanetConsole.Node/Node.BlockChain.cs b/src/node/LibplanetConsole.Node/Node.BlockChain.cs index c25c5d03..6e551ca5 100644 --- a/src/node/LibplanetConsole.Node/Node.BlockChain.cs +++ b/src/node/LibplanetConsole.Node/Node.BlockChain.cs @@ -16,7 +16,7 @@ internal sealed partial class Node : IBlockChain { private static readonly Codec _codec = new(); - public async Task AddTransactionAsync( + public async Task AddTransactionAsync( IAction[] actions, CancellationToken cancellationToken) { ObjectDisposedExceptionUtility.ThrowIf(_isDisposed, this); @@ -35,7 +35,7 @@ public async Task AddTransactionAsync( genesisHash: genesisBlock.Hash, actions: new TxActionList(values)); await AddTransactionAsync(transaction, cancellationToken); - return (AppId)transaction.Id; + return (TxId)transaction.Id; } public async Task AddTransactionAsync( @@ -46,7 +46,7 @@ public async Task AddTransactionAsync( condition: IsRunning != true, message: "Node is not running."); - _logger.Debug("Node adds a transaction: {AppId}", transaction.Id); + _logger.Debug("Node adds a transaction: {TxId}", transaction.Id); var blockChain = BlockChain; var manualResetEvent = _eventByTxId.GetOrAdd(transaction.Id, _ => { @@ -72,7 +72,7 @@ public async Task AddTransactionAsync( throw new InvalidOperationException(sb.ToString()); } - _logger.Debug("Node added a transaction: {AppId}", transaction.Id); + _logger.Debug("Node added a transaction: {TxId}", transaction.Id); } public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) @@ -176,7 +176,7 @@ AppHash GetBlockHash() } public Task GetActionAsync( - AppId txId, int actionIndex, CancellationToken cancellationToken) + TxId txId, int actionIndex, CancellationToken cancellationToken) { byte[] GetAction() { @@ -190,7 +190,7 @@ byte[] GetAction() } public Task GetActionAsync( - AppId txId, int actionIndex, CancellationToken cancellationToken) + TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction { T GetAction() diff --git a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs index 65879d5b..30005636 100644 --- a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs +++ b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs @@ -21,12 +21,12 @@ public BlockChainService(Node node) _node.BlockAppended += Node_BlockAppended; } - public async Task SendTransactionAsync( + public async Task SendTransactionAsync( byte[] transaction, CancellationToken cancellationToken) { var tx = Transaction.Deserialize(transaction); await _node.AddTransactionAsync(tx, cancellationToken); - return (AppId)tx.Id; + return (TxId)tx.Id; } public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) @@ -61,7 +61,7 @@ public Task GetBlockHashAsync(long height, CancellationToken cancellati => _node.GetBlockHashAsync(height, cancellationToken); public Task GetActionAsync( - AppId txId, int actionIndex, CancellationToken cancellationToken) + TxId txId, int actionIndex, CancellationToken cancellationToken) => _node.GetActionAsync(txId, actionIndex, cancellationToken); private void Node_BlockAppended(object? sender, BlockEventArgs e) diff --git a/src/shared/LibplanetConsole.Client/Services/IClientService.cs b/src/shared/LibplanetConsole.Client/Services/IClientService.cs index a8c3a657..9154f825 100644 --- a/src/shared/LibplanetConsole.Client/Services/IClientService.cs +++ b/src/shared/LibplanetConsole.Client/Services/IClientService.cs @@ -10,6 +10,6 @@ public interface IClientService Task GetInfoAsync(CancellationToken cancellationToken); - Task SendTransactionAsync( + Task SendTransactionAsync( TransactionOptions transactionOptions, CancellationToken cancellationToken); } diff --git a/src/shared/LibplanetConsole.Node/ActionInfo.cs b/src/shared/LibplanetConsole.Node/ActionInfo.cs index 1fe623cd..e5355b66 100644 --- a/src/shared/LibplanetConsole.Node/ActionInfo.cs +++ b/src/shared/LibplanetConsole.Node/ActionInfo.cs @@ -23,7 +23,7 @@ public ActionInfo() public string TypeId { get; init; } = string.Empty; - public AppId TxId { get; init; } = default; + public TxId TxId { get; init; } = default; public int Index { get; init; } } diff --git a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs index e5c5c474..c5a37cbf 100644 --- a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs +++ b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs @@ -5,7 +5,7 @@ namespace LibplanetConsole.Node.Services; public interface IBlockChainService { - Task SendTransactionAsync(byte[] transaction, CancellationToken cancellationToken); + Task SendTransactionAsync(byte[] transaction, CancellationToken cancellationToken); Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); @@ -25,5 +25,5 @@ Task GetStateByStateRootHashAsync( Task GetBlockHashAsync(long height, CancellationToken cancellationToken); - Task GetActionAsync(AppId txId, int actionIndex, CancellationToken cancellationToken); + Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken); } diff --git a/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs b/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs index 498e79fa..cc7567d7 100644 --- a/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs +++ b/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs @@ -8,7 +8,7 @@ public readonly partial record struct TransactionInfo { public TransactionInfo(TxExecution execution, ITransaction transaction) { - Id = (AppId)transaction.Id; + Id = (TxId)transaction.Id; Signer = transaction.Signer; Actions = GetActionInfos(transaction); IsFailed = execution.Fail; @@ -20,7 +20,7 @@ private static ActionInfo[] GetActionInfos(ITransaction transaction) for (var i = 0; i < transaction.Actions.Count; i++) { var action = transaction.Actions[i]; - infos[i] = new ActionInfo(action) { Index = i, TxId = (AppId)transaction.Id }; + infos[i] = new ActionInfo(action) { Index = i, TxId = (TxId)transaction.Id }; } return infos; diff --git a/src/shared/LibplanetConsole.Node/TransactionInfo.cs b/src/shared/LibplanetConsole.Node/TransactionInfo.cs index 9ad57ef7..6ea061f2 100644 --- a/src/shared/LibplanetConsole.Node/TransactionInfo.cs +++ b/src/shared/LibplanetConsole.Node/TransactionInfo.cs @@ -9,7 +9,7 @@ public TransactionInfo() { } - public AppId Id { get; init; } = default; + public TxId Id { get; init; } = default; public Address Signer { get; init; } = default; From 8492ee95a486142222706ca83d146bc6d4f3386a Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 17:54:30 +0900 Subject: [PATCH 4/9] refactor: Remove AppPeer --- src/common/LibplanetConsole.Common/AppPeer.cs | 64 +++++++++---------- .../Converters/AppPeerJsonConverter.cs | 42 ++++++------ .../DataAnnotations/AppPeerAttribute.cs | 9 ++- .../LibplanetConsole.Common/SeedInfo.cs | 18 ------ .../Services/RemoteServiceContext.cs | 1 + .../Services/Serializer.cs | 49 ++++++++++++++ .../LibplanetConsole.Seed/BoundPeerUtility.cs | 29 +++++++++ .../Converters/BoundPeerJsonConverter.cs | 27 ++++++++ .../ISeedService.cs | 2 +- .../LibplanetConsole.Seed.csproj | 5 ++ src/common/LibplanetConsole.Seed/Peer.cs | 11 ++-- .../LibplanetConsole.Seed/PeerCollection.cs | 2 +- .../LibplanetConsole.Seed/PeerUtility.cs | 15 ----- src/common/LibplanetConsole.Seed/SeedInfo.cs | 15 +++++ src/common/LibplanetConsole.Seed/SeedNode.cs | 21 ++++-- .../Services/SeedService.cs | 5 +- src/node/LibplanetConsole.Node/Node.cs | 16 ++--- src/node/LibplanetConsole.Node/PeerUtility.cs | 24 +++---- src/shared/LibplanetConsole.Node/NodeInfo.cs | 5 +- .../AppPeerTest.cs | 26 ++++---- 20 files changed, 247 insertions(+), 139 deletions(-) delete mode 100644 src/common/LibplanetConsole.Common/SeedInfo.cs create mode 100644 src/common/LibplanetConsole.Common/Services/Serializer.cs create mode 100644 src/common/LibplanetConsole.Seed/BoundPeerUtility.cs create mode 100644 src/common/LibplanetConsole.Seed/Converters/BoundPeerJsonConverter.cs rename src/common/{LibplanetConsole.Common => LibplanetConsole.Seed}/ISeedService.cs (81%) delete mode 100644 src/common/LibplanetConsole.Seed/PeerUtility.cs create mode 100644 src/common/LibplanetConsole.Seed/SeedInfo.cs diff --git a/src/common/LibplanetConsole.Common/AppPeer.cs b/src/common/LibplanetConsole.Common/AppPeer.cs index e2072454..37a93b9f 100644 --- a/src/common/LibplanetConsole.Common/AppPeer.cs +++ b/src/common/LibplanetConsole.Common/AppPeer.cs @@ -1,43 +1,43 @@ -using System.Text.Json.Serialization; -using Libplanet.Crypto; -using LibplanetConsole.Common.Converters; -using LibplanetConsole.Common.DataAnnotations; +// using System.Text.Json.Serialization; +// using Libplanet.Crypto; +// using LibplanetConsole.Common.Converters; +// using LibplanetConsole.Common.DataAnnotations; -namespace LibplanetConsole.Common; +// namespace LibplanetConsole.Common; -[JsonConverter(typeof(AppPeerJsonConverter))] -public readonly struct AppPeer(PublicKey publicKey, AppEndPoint endPoint) -{ - public const string HostExpression - = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; +// [JsonConverter(typeof(AppPeerJsonConverter))] +// public readonly struct AppPeer(PublicKey publicKey, AppEndPoint endPoint) +// { +// public const string HostExpression +// = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; - public const string PortExpression = @"\d{1,5}"; - public static readonly string RegularExpression - = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; +// public const string PortExpression = @"\d{1,5}"; +// public static readonly string RegularExpression +// = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; - public PublicKey PublicKey { get; } = publicKey; +// public PublicKey PublicKey { get; } = publicKey; - public AppEndPoint EndPoint { get; } = endPoint; +// public AppEndPoint EndPoint { get; } = endPoint; - public Address Address => PublicKey.Address; +// public Address Address => PublicKey.Address; - public static string ToString(AppPeer? peer) - => peer?.ToString() ?? string.Empty; +// public static string ToString(AppPeer? peer) +// => peer?.ToString() ?? string.Empty; - public static AppPeer Parse(string text) - { - var items = text.Split(',', StringSplitOptions.RemoveEmptyEntries); - if (items.Length == 2) - { - var publicKey = PublicKey.FromHex(items[0]); - var endPoint = AppEndPoint.Parse(items[1].Trim()); - return new AppPeer(publicKey, endPoint); - } +// public static AppPeer Parse(string text) +// { +// var items = text.Split(',', StringSplitOptions.RemoveEmptyEntries); +// if (items.Length == 2) +// { +// var publicKey = PublicKey.FromHex(items[0]); +// var endPoint = AppEndPoint.Parse(items[1].Trim()); +// return new AppPeer(publicKey, endPoint); +// } - throw new FormatException($"'{text}' is not supported."); - } +// throw new FormatException($"'{text}' is not supported."); +// } - public static AppPeer? ParseOrDefault(string text) => text == string.Empty ? null : Parse(text); +// public static AppPeer? ParseOrDefault(string text) => text == string.Empty ? null : Parse(text); - public override string ToString() => $"{PublicKey}, {EndPoint}"; -} +// public override string ToString() => $"{PublicKey}, {EndPoint}"; +// } diff --git a/src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs index 55fd5f29..14882764 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs @@ -1,25 +1,25 @@ -using System.Text.Json; -using System.Text.Json.Serialization; +// using System.Text.Json; +// using System.Text.Json.Serialization; -namespace LibplanetConsole.Common.Converters; +// namespace LibplanetConsole.Common.Converters; -public sealed class AppPeerJsonConverter : JsonConverter -{ - public override AppPeer Read( - ref Utf8JsonReader reader, - Type typeToConvert, - JsonSerializerOptions options) - { - if (reader.GetString() is string text) - { - return AppPeer.Parse(text); - } +// public sealed class AppPeerJsonConverter : JsonConverter +// { +// public override AppPeer Read( +// ref Utf8JsonReader reader, +// Type typeToConvert, +// JsonSerializerOptions options) +// { +// if (reader.GetString() is string text) +// { +// return AppPeer.Parse(text); +// } - throw new JsonException("Cannot read AppPeer from JSON."); - } +// throw new JsonException("Cannot read AppPeer from JSON."); +// } - public override void Write(Utf8JsonWriter writer, AppPeer value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } -} +// public override void Write(Utf8JsonWriter writer, AppPeer value, JsonSerializerOptions options) +// { +// writer.WriteStringValue(value.ToString()); +// } +// } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs index 7ec0c895..4162191c 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs @@ -7,8 +7,15 @@ namespace LibplanetConsole.Common.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] public sealed class AppPeerAttribute : RegularExpressionAttribute { + public const string HostExpression + = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; + + public const string PortExpression = @"\d{1,5}"; + public static readonly string RegularExpression + = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; + public AppPeerAttribute() - : base($"^{AppPeer.RegularExpression}$") + : base($"^{RegularExpression}$") { } } diff --git a/src/common/LibplanetConsole.Common/SeedInfo.cs b/src/common/LibplanetConsole.Common/SeedInfo.cs deleted file mode 100644 index 50fbdac6..00000000 --- a/src/common/LibplanetConsole.Common/SeedInfo.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace LibplanetConsole.Common; - -public readonly record struct SeedInfo -{ - public static SeedInfo Empty { get; } = default; - - public AppPeer BlocksyncSeedPeer { get; init; } - - public AppPeer ConsensusSeedPeer { get; init; } - - public SeedInfo Encrypt(PublicKey publicKey) => this with - { - }; - - public SeedInfo Decrypt(AppPrivateKey privateKey) => this with - { - }; -} diff --git a/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs b/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs index 49cdc941..b892e11d 100644 --- a/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs +++ b/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs @@ -61,5 +61,6 @@ public async Task CloseAsync(Guid token, CancellationToken cancellationToken) private sealed class InternalClientContext(IService[] services) : ClientContext(services) { + // : ISerializer } } diff --git a/src/common/LibplanetConsole.Common/Services/Serializer.cs b/src/common/LibplanetConsole.Common/Services/Serializer.cs new file mode 100644 index 00000000..5acb962b --- /dev/null +++ b/src/common/LibplanetConsole.Common/Services/Serializer.cs @@ -0,0 +1,49 @@ +// using System.Text.Json; +// using System.Text.Json.Serialization; +// using JSSoft.Communication; + +// namespace LibplanetConsole.Common.Services; + +// internal sealed class CommunicationSerializer : ISerializer +// { +// private static readonly Dictionary _converterByType = +// [ +// typeof(BoundPeer) +// ] + +// private static readonly JsonSerializerOptions Options = new() +// { +// IncludeFields = true, +// Converters = +// { +// // new ArgumentExceptionConverter(), +// // new ArgumentNullExceptionConverter(), +// // new ArgumentOutOfRangeExceptionConverter(), +// // new ExceptionConverter(), +// // new IndexOutOfRangeExceptionConverter(), +// // new InvalidOperationExceptionConverter(), +// // new ObjectDisposedExceptionConverter(), +// // new NotSupportedExceptionConverter(), +// // new NullReferenceExceptionConverter(), +// // new SystemExceptionConverter(), +// // new ExceptionConverterFactory(), +// }, +// }; + +// private readonly ISerializer _serializer; + +// public CommunicationSerializer(ISerializer serializer) +// { +// _serializer = serializer; +// } + +// public object? Deserialize(Type type, string text) +// { +// if (Options.Converters.con) +// } + +// public string Serialize(Type type, object? data) +// { +// throw new NotImplementedException(); +// } +// } diff --git a/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs b/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs new file mode 100644 index 00000000..09b322df --- /dev/null +++ b/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs @@ -0,0 +1,29 @@ +using System.Net; +using Libplanet.Crypto; +using Libplanet.Net; +using LibplanetConsole.Common; + +namespace LibplanetConsole.Seed; + +public static class BoundPeerUtility +{ + public static string ToString(BoundPeer? boundPeer) + => boundPeer is not null + ? $"{boundPeer.PublicKey.ToHex(compress: false)}, {boundPeer.EndPoint.Host}:{boundPeer.EndPoint.Port}" + : string.Empty; + + public static BoundPeer Parse(string text) + { + var items = text.Split(',', StringSplitOptions.RemoveEmptyEntries); + if (items.Length == 2) + { + var publicKey = PublicKey.FromHex(items[0]); + var endPoint = (DnsEndPoint)AppEndPoint.Parse(items[1].Trim()); + return new BoundPeer(publicKey, endPoint); + } + + throw new FormatException($"'{text}' is not supported."); + } + + public static BoundPeer? ParseOrDefault(string text) => text == string.Empty ? null : Parse(text); +} diff --git a/src/common/LibplanetConsole.Seed/Converters/BoundPeerJsonConverter.cs b/src/common/LibplanetConsole.Seed/Converters/BoundPeerJsonConverter.cs new file mode 100644 index 00000000..e00a9042 --- /dev/null +++ b/src/common/LibplanetConsole.Seed/Converters/BoundPeerJsonConverter.cs @@ -0,0 +1,27 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace LibplanetConsole.Seed.Converters; + +public sealed class BoundPeerJsonConverter : JsonConverter +{ + public override BoundPeer Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) + { + if (reader.GetString() is string text) + { + return BoundPeerUtility.Parse(text); + } + + throw new JsonException("Cannot read BoundPeer from JSON."); + } + + public override void Write( + Utf8JsonWriter writer, BoundPeer value, JsonSerializerOptions options) + { + var text = BoundPeerUtility.ToString(value); + writer.WriteStringValue(text); + } +} diff --git a/src/common/LibplanetConsole.Common/ISeedService.cs b/src/common/LibplanetConsole.Seed/ISeedService.cs similarity index 81% rename from src/common/LibplanetConsole.Common/ISeedService.cs rename to src/common/LibplanetConsole.Seed/ISeedService.cs index f219f9ae..ed760513 100644 --- a/src/common/LibplanetConsole.Common/ISeedService.cs +++ b/src/common/LibplanetConsole.Seed/ISeedService.cs @@ -1,6 +1,6 @@ using Libplanet.Crypto; -namespace LibplanetConsole.Common; +namespace LibplanetConsole.Seed; public interface ISeedService { diff --git a/src/common/LibplanetConsole.Seed/LibplanetConsole.Seed.csproj b/src/common/LibplanetConsole.Seed/LibplanetConsole.Seed.csproj index 1d2da5a8..0a8eacfe 100644 --- a/src/common/LibplanetConsole.Seed/LibplanetConsole.Seed.csproj +++ b/src/common/LibplanetConsole.Seed/LibplanetConsole.Seed.csproj @@ -14,4 +14,9 @@ + + + + + diff --git a/src/common/LibplanetConsole.Seed/Peer.cs b/src/common/LibplanetConsole.Seed/Peer.cs index 14641760..c33dbf83 100644 --- a/src/common/LibplanetConsole.Seed/Peer.cs +++ b/src/common/LibplanetConsole.Seed/Peer.cs @@ -3,7 +3,6 @@ using Libplanet.Net.Messages; using Libplanet.Net.Transports; using LibplanetConsole.Common; -using static LibplanetConsole.Seed.PeerUtility; namespace LibplanetConsole.Seed; @@ -11,15 +10,15 @@ public sealed class Peer { private readonly ITransport _transport; - internal Peer(ITransport transport, AppPeer appPeer) + internal Peer(ITransport transport, BoundPeer appPeer) { _transport = transport; - AppPeer = appPeer; + BoundPeer = appPeer; } - public Address Address => AppPeer.Address; + public Address Address => BoundPeer.Address; - public AppPeer AppPeer { get; } + public BoundPeer BoundPeer { get; } public DateTimeOffset LastUpdated { get; private set; } @@ -44,7 +43,7 @@ internal async Task PingAsync(TimeSpan timeout, CancellationToken cancella var pingMsg = new PingMsg(); var stopwatch = Stopwatch.StartNew(); var replyMessage = await _transport.SendMessageAsync( - ToBoundPeer(AppPeer), + BoundPeer, pingMsg, timeout, cancellationToken); diff --git a/src/common/LibplanetConsole.Seed/PeerCollection.cs b/src/common/LibplanetConsole.Seed/PeerCollection.cs index 0d51fb3b..5d0108be 100644 --- a/src/common/LibplanetConsole.Seed/PeerCollection.cs +++ b/src/common/LibplanetConsole.Seed/PeerCollection.cs @@ -26,7 +26,7 @@ public IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() => _infoByAddress.Values.GetEnumerator(); - internal void AddOrUpdate(AppPeer boundPeer, ITransport transport) + internal void AddOrUpdate(BoundPeer boundPeer, ITransport transport) { _infoByAddress.AddOrUpdate( key: boundPeer.Address, diff --git a/src/common/LibplanetConsole.Seed/PeerUtility.cs b/src/common/LibplanetConsole.Seed/PeerUtility.cs deleted file mode 100644 index c66321e0..00000000 --- a/src/common/LibplanetConsole.Seed/PeerUtility.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Net; -using Libplanet.Crypto; -using Libplanet.Net; -using LibplanetConsole.Common; - -namespace LibplanetConsole.Seed; - -internal static class PeerUtility -{ - public static BoundPeer ToBoundPeer(AppPeer peer) - => new((PublicKey)peer.PublicKey, (DnsEndPoint)peer.EndPoint); - - public static AppPeer ToAppPeer(BoundPeer boundPeer) - => new((PublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); -} diff --git a/src/common/LibplanetConsole.Seed/SeedInfo.cs b/src/common/LibplanetConsole.Seed/SeedInfo.cs new file mode 100644 index 00000000..e0678136 --- /dev/null +++ b/src/common/LibplanetConsole.Seed/SeedInfo.cs @@ -0,0 +1,15 @@ +using System.Text.Json.Serialization; +using LibplanetConsole.Seed.Converters; + +namespace LibplanetConsole.Seed; + +public readonly record struct SeedInfo +{ + public static SeedInfo Empty { get; } = default; + + [JsonConverter(typeof(BoundPeerJsonConverter))] + public BoundPeer BlocksyncSeedPeer { get; init; } + + [JsonConverter(typeof(BoundPeerJsonConverter))] + public BoundPeer ConsensusSeedPeer { get; init; } +} diff --git a/src/common/LibplanetConsole.Seed/SeedNode.cs b/src/common/LibplanetConsole.Seed/SeedNode.cs index 0a0b21bf..fb6ecd38 100644 --- a/src/common/LibplanetConsole.Seed/SeedNode.cs +++ b/src/common/LibplanetConsole.Seed/SeedNode.cs @@ -1,17 +1,26 @@ -using Dasync.Collections; +using System.ComponentModel; +using System.Net; +using System.Text.Json.Serialization; +using Dasync.Collections; using Libplanet.Crypto; using Libplanet.Net; using Libplanet.Net.Messages; using Libplanet.Net.Options; using Libplanet.Net.Transports; using LibplanetConsole.Common; +using LibplanetConsole.Seed.Converters; using Serilog; -using static LibplanetConsole.Seed.PeerUtility; namespace LibplanetConsole.Seed; public sealed class SeedNode(SeedOptions seedOptions) { + static SeedNode() + { + TypeDescriptor.AddAttributes( + typeof(BoundPeer), new JsonConverterAttribute(typeof(BoundPeerJsonConverter))); + } + public static readonly AppPrivateKey AppProtocolKey = AppPrivateKey.Parse("2a15e7deaac09ce631e1faa184efadb175b6b90989cf1faed9dfc321ad1db5ac"); @@ -31,8 +40,8 @@ public static readonly AppProtocolVersion AppProtocolVersion public PeerCollection Peers { get; } = new(seedOptions); - public AppPeer BoundPeer => new( - seedOptions.PrivateKey.PublicKey, seedOptions.EndPoint); + public BoundPeer BoundPeer => new( + seedOptions.PrivateKey.PublicKey, (DnsEndPoint)seedOptions.EndPoint); public async Task StartAsync(CancellationToken cancellationToken) { @@ -149,7 +158,7 @@ private async Task ReceiveMessageAsync(Message message) { case FindNeighborsMsg: var alivePeers = peers.Where(item => item.IsAlive) - .Select(item => ToBoundPeer(item.AppPeer)) + .Select(item => item.BoundPeer) .ToArray(); var neighborsMsg = new NeighborsMsg(alivePeers); await transport.ReplyMessageAsync( @@ -169,7 +178,7 @@ await transport.ReplyMessageAsync( if (message.Remote is BoundPeer boundPeer) { - peers.AddOrUpdate(ToAppPeer(boundPeer), transport); + peers.AddOrUpdate(boundPeer, transport); } } } diff --git a/src/console/LibplanetConsole.Console/Services/SeedService.cs b/src/console/LibplanetConsole.Console/Services/SeedService.cs index e3179cbf..7f217df3 100644 --- a/src/console/LibplanetConsole.Console/Services/SeedService.cs +++ b/src/console/LibplanetConsole.Console/Services/SeedService.cs @@ -1,4 +1,5 @@ using System.ComponentModel.Composition; +using Libplanet.Net; using LibplanetConsole.Common; using LibplanetConsole.Common.Services; using LibplanetConsole.Framework; @@ -33,9 +34,9 @@ public SeedService(ApplicationBase application) }); } - public AppPeer BlocksyncSeedPeer => _blocksyncSeedNode.BoundPeer; + public BoundPeer BlocksyncSeedPeer => _blocksyncSeedNode.BoundPeer; - public AppPeer ConsensusSeedPeer => _consensusSeedNode.BoundPeer; + public BoundPeer ConsensusSeedPeer => _consensusSeedNode.BoundPeer; public async Task GetSeedAsync( PublicKey publicKey, CancellationToken cancellationToken) diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index 2b0c8d52..2e8b5380 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -19,7 +19,6 @@ using LibplanetConsole.Common.Services; using LibplanetConsole.Seed; using Serilog; -using static LibplanetConsole.Node.PeerUtility; namespace LibplanetConsole.Node; @@ -93,13 +92,13 @@ public AppEndPoint ConsensusEndPoint public Swarm Swarm => _swarm ?? throw new InvalidOperationException(); - public AppPeer[] Peers + public BoundPeer[] Peers { get { if (_swarm is not null) { - return [.. _swarm.Peers.Select(item => ToAppPeer(item))]; + return [.. _swarm.Peers.Select(item => item)]; } throw new InvalidOperationException(); @@ -164,10 +163,10 @@ var swarmTransport = await CreateTransport(privateKey, blocksyncEndPoint, appProtocolVersion); var swarmOptions = new SwarmOptions { - StaticPeers = [ToBoundPeer(blocksyncSeedPeer)], + StaticPeers = [blocksyncSeedPeer], BootstrapOptions = new() { - SeedPeers = [ToBoundPeer(blocksyncSeedPeer)], + SeedPeers = [blocksyncSeedPeer], }, }; var consensusTransport = await CreateTransport( @@ -176,7 +175,7 @@ var swarmTransport appProtocolVersion: appProtocolVersion); var consensusReactorOption = new ConsensusReactorOption { - SeedPeers = [ToBoundPeer(consensusSeedPeer)], + SeedPeers = [consensusSeedPeer], ConsensusPort = consensusEndPoint.Port, ConsensusPrivateKey = privateKey, TargetBlockInterval = TimeSpan.FromSeconds(2), @@ -314,8 +313,7 @@ private static async Task GetSeedInfoAsync( { for (var i = 0; i < 10; i++) { - var decrypted = await service.GetSeedAsync(publicKey, cancellationToken); - var seedInfo = decrypted.Decrypt(privateKey); + var seedInfo = await service.GetSeedAsync(publicKey, cancellationToken); if (Equals(seedInfo, SeedInfo.Empty) != true) { return seedInfo; @@ -351,7 +349,7 @@ private void UpdateNodeInfo() GenesisHash = (AppHash)BlockChain.Genesis.Hash, TipHash = (AppHash)BlockChain.Tip.Hash, IsRunning = IsRunning, - Peers = [.. Peers], + // Peers = [.. Peers], }; } diff --git a/src/node/LibplanetConsole.Node/PeerUtility.cs b/src/node/LibplanetConsole.Node/PeerUtility.cs index c8ec8612..004d4905 100644 --- a/src/node/LibplanetConsole.Node/PeerUtility.cs +++ b/src/node/LibplanetConsole.Node/PeerUtility.cs @@ -1,15 +1,15 @@ -using System.Net; -using Libplanet.Crypto; -using Libplanet.Net; -using LibplanetConsole.Common; +// using System.Net; +// using Libplanet.Crypto; +// using Libplanet.Net; +// using LibplanetConsole.Common; -namespace LibplanetConsole.Node; +// namespace LibplanetConsole.Node; -internal static class PeerUtility -{ - public static BoundPeer ToBoundPeer(AppPeer peer) - => new((PublicKey)peer.PublicKey, (DnsEndPoint)peer.EndPoint); +// internal static class PeerUtility +// { +// public static BoundPeer ToBoundPeer(AppPeer peer) +// => new((PublicKey)peer.PublicKey, (DnsEndPoint)peer.EndPoint); - public static AppPeer ToAppPeer(BoundPeer boundPeer) - => new((PublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); -} +// public static AppPeer ToAppPeer(BoundPeer boundPeer) +// => new((PublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); +// } diff --git a/src/shared/LibplanetConsole.Node/NodeInfo.cs b/src/shared/LibplanetConsole.Node/NodeInfo.cs index b5623eb9..9b203764 100644 --- a/src/shared/LibplanetConsole.Node/NodeInfo.cs +++ b/src/shared/LibplanetConsole.Node/NodeInfo.cs @@ -1,4 +1,5 @@ using Libplanet.Crypto; +// using Libplanet.Net; using LibplanetConsole.Common; namespace LibplanetConsole.Node; @@ -21,7 +22,7 @@ public readonly record struct NodeInfo public bool IsRunning { get; init; } - public AppPeer[] Peers { get; init; } + // public BoundPeer[] Peers { get; init; } public static NodeInfo Empty { get; } = new NodeInfo { @@ -29,6 +30,6 @@ public readonly record struct NodeInfo AppProtocolVersion = string.Empty, SwarmEndPoint = string.Empty, ConsensusEndPoint = string.Empty, - Peers = [], + // Peers = [], }; } diff --git a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs b/test/LibplanetConsole.Common.Tests/AppPeerTest.cs index 01c80795..b0d4887a 100644 --- a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs +++ b/test/LibplanetConsole.Common.Tests/AppPeerTest.cs @@ -1,14 +1,14 @@ -namespace LibplanetConsole.Common.Tests; +// namespace LibplanetConsole.Common.Tests; -public class AppPeerTest -{ - [Fact] - public void Test1() - { - var publicKey = new AppPrivateKey().PublicKey; - var endPoint = new AppEndPoint("localhost", 12345); - var peer = new AppPeer(publicKey, endPoint); - Assert.Equal(publicKey, peer.PublicKey); - Assert.Equal(endPoint, peer.EndPoint); - } -} +// public class AppPeerTest +// { +// [Fact] +// public void Test1() +// { +// var publicKey = new AppPrivateKey().PublicKey; +// var endPoint = new AppEndPoint("localhost", 12345); +// var peer = new AppPeer(publicKey, endPoint); +// Assert.Equal(publicKey, peer.PublicKey); +// Assert.Equal(endPoint, peer.EndPoint); +// } +// } From 7fe5dff3572145057304b9e22174f8bbdff177ce Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 18:10:23 +0900 Subject: [PATCH 5/9] refactor: Remove AppHash --- .../Client.BlockChain.cs | 9 +- .../LibplanetConsole.Client/IBlockChain.cs | 9 +- src/common/LibplanetConsole.Common/AppHash.cs | 96 +++++++++---------- .../LibplanetConsole.Common/AppPrivateKey.cs | 2 +- .../Converters/AppHashJsonConverter.cs | 44 ++++----- .../LibplanetConsole.Console/IBlockChain.cs | 9 +- .../Node.BlockChain.cs | 9 +- .../DuplicateVoteViolator.cs | 4 +- .../LibplanetConsole.Node/ActionProvider.cs | 2 +- src/node/LibplanetConsole.Node/IBlockChain.cs | 9 +- .../LibplanetConsole.Node/Node.BlockChain.cs | 26 ++--- src/node/LibplanetConsole.Node/Node.cs | 4 +- .../Services/BlockChainService.cs | 11 ++- .../LibplanetConsole.Node/BlockInfo.Node.cs | 2 +- src/shared/LibplanetConsole.Node/BlockInfo.cs | 2 +- src/shared/LibplanetConsole.Node/NodeInfo.cs | 4 +- .../Services/IBlockChainService.cs | 9 +- .../TransactionInfo.Node.cs | 4 +- 18 files changed, 131 insertions(+), 124 deletions(-) diff --git a/src/client/LibplanetConsole.Client/Client.BlockChain.cs b/src/client/LibplanetConsole.Client/Client.BlockChain.cs index 7e020f20..121cffcf 100644 --- a/src/client/LibplanetConsole.Client/Client.BlockChain.cs +++ b/src/client/LibplanetConsole.Client/Client.BlockChain.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Bencodex; using Bencodex.Types; using Libplanet.Action; @@ -30,17 +31,17 @@ public async Task SendTransactionAsync( return await RemoteBlockChainService.SendTransactionAsync(txData, cancellationToken); } - public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) + public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) => RemoteBlockChainService.GetBlockHashAsync(height, cancellationToken); public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) => RemoteBlockChainService.GetNextNonceAsync(address, cancellationToken); - public Task GetTipHashAsync(CancellationToken cancellationToken) + public Task GetTipHashAsync(CancellationToken cancellationToken) => RemoteBlockChainService.GetTipHashAsync(cancellationToken); public async Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken) @@ -51,7 +52,7 @@ public async Task GetStateAsync( } public async Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken) diff --git a/src/client/LibplanetConsole.Client/IBlockChain.cs b/src/client/LibplanetConsole.Client/IBlockChain.cs index a9be0663..89be3a54 100644 --- a/src/client/LibplanetConsole.Client/IBlockChain.cs +++ b/src/client/LibplanetConsole.Client/IBlockChain.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Bencodex.Types; using Libplanet.Action; using Libplanet.Crypto; @@ -13,21 +14,21 @@ public interface IBlockChain Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); - Task GetTipHashAsync(CancellationToken cancellationToken); + Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken); - Task GetBlockHashAsync(long height, CancellationToken cancellationToken); + Task GetBlockHashAsync(long height, CancellationToken cancellationToken); Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction; diff --git a/src/common/LibplanetConsole.Common/AppHash.cs b/src/common/LibplanetConsole.Common/AppHash.cs index b3706950..a0eef2e7 100644 --- a/src/common/LibplanetConsole.Common/AppHash.cs +++ b/src/common/LibplanetConsole.Common/AppHash.cs @@ -1,64 +1,64 @@ -using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; -using System.Security.Cryptography; -using System.Text.Json.Serialization; -using Libplanet.Common; -using Libplanet.Types.Blocks; -using LibplanetConsole.Common.Converters; +// using System.Collections.Immutable; +// using System.Diagnostics.CodeAnalysis; +// using System.Security.Cryptography; +// using System.Text.Json.Serialization; +// using Libplanet.Common; +// using Libplanet.Types.Blocks; +// using LibplanetConsole.Common.Converters; -namespace LibplanetConsole.Common; +// namespace LibplanetConsole.Common; -[JsonConverter(typeof(AppHashJsonConverter))] -public readonly record struct AppHash : IFormattable -{ - private readonly ImmutableArray _bytes; +// [JsonConverter(typeof(AppHashJsonConverter))] +// public readonly record struct AppHash : IFormattable +// { +// private readonly ImmutableArray _bytes; - public AppHash(byte[] bytes) => _bytes = [.. bytes]; +// public AppHash(byte[] bytes) => _bytes = [.. bytes]; - public AppHash(ImmutableArray bytes) => _bytes = bytes; +// public AppHash(ImmutableArray bytes) => _bytes = bytes; - public AppHash(BlockHash blockHash) => _bytes = blockHash.ByteArray; +// public AppHash(BlockHash blockHash) => _bytes = blockHash.ByteArray; - public static explicit operator AppHash(BlockHash blockHash) => new(blockHash); +// public static explicit operator AppHash(BlockHash blockHash) => new(blockHash); - public static explicit operator AppHash(HashDigest hashDigest) - => new(hashDigest.ByteArray); +// public static explicit operator AppHash(HashDigest hashDigest) +// => new(hashDigest.ByteArray); - public static explicit operator BlockHash(AppHash hash) => new(hash._bytes); +// public static explicit operator BlockHash(AppHash hash) => new(hash._bytes); - public static explicit operator HashDigest(AppHash hash) => new(hash._bytes); +// public static explicit operator HashDigest(AppHash hash) => new(hash._bytes); - public static string ToString(AppHash? blockHash) - => blockHash?.ToString() ?? string.Empty; +// public static string ToString(AppHash? blockHash) +// => blockHash?.ToString() ?? string.Empty; - public static AppHash Parse(string text) => new(ByteUtil.ParseHexToImmutable(text)); +// public static AppHash Parse(string text) => new(ByteUtil.ParseHexToImmutable(text)); - public static AppHash? ParseOrDefault(string text) - => text == string.Empty ? null : Parse(text); +// public static AppHash? ParseOrDefault(string text) +// => text == string.Empty ? null : Parse(text); - public static bool TryParse(string text, [MaybeNullWhen(false)] out AppHash blockHash) - { - try - { - blockHash = Parse(text); - return true; - } - catch - { - blockHash = default; - return false; - } - } +// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppHash blockHash) +// { +// try +// { +// blockHash = Parse(text); +// return true; +// } +// catch +// { +// blockHash = default; +// return false; +// } +// } - public override string ToString() => ByteUtil.Hex(_bytes); +// public override string ToString() => ByteUtil.Hex(_bytes); - public string ToString(string? format, IFormatProvider? formatProvider) - { - if (format is "S") - { - return ToString()[..8]; - } +// public string ToString(string? format, IFormatProvider? formatProvider) +// { +// if (format is "S") +// { +// return ToString()[..8]; +// } - return ToString(); - } -} +// return ToString(); +// } +// } diff --git a/src/common/LibplanetConsole.Common/AppPrivateKey.cs b/src/common/LibplanetConsole.Common/AppPrivateKey.cs index 9c41cf0b..9bec3432 100644 --- a/src/common/LibplanetConsole.Common/AppPrivateKey.cs +++ b/src/common/LibplanetConsole.Common/AppPrivateKey.cs @@ -31,7 +31,7 @@ public AppPrivateKey() { } - public PublicKey PublicKey => (PublicKey)_privateKey.PublicKey; + public PublicKey PublicKey => _privateKey.PublicKey; public Address Address => _privateKey.PublicKey.Address; diff --git a/src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs index c3e00b8a..f43e63a3 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs @@ -1,26 +1,26 @@ -using System.Text.Json; -using System.Text.Json.Serialization; +// using System.Text.Json; +// using System.Text.Json.Serialization; -namespace LibplanetConsole.Common.Converters; +// namespace LibplanetConsole.Common.Converters; -public sealed class AppHashJsonConverter : JsonConverter -{ - public override AppHash Read( - ref Utf8JsonReader reader, - Type typeToConvert, - JsonSerializerOptions options) - { - if (reader.GetString() is string text) - { - return AppHash.Parse(text); - } +// public sealed class AppHashJsonConverter : JsonConverter +// { +// public override AppHash Read( +// ref Utf8JsonReader reader, +// Type typeToConvert, +// JsonSerializerOptions options) +// { +// if (reader.GetString() is string text) +// { +// return AppHash.Parse(text); +// } - throw new JsonException("Cannot read AppHash from JSON."); - } +// throw new JsonException("Cannot read AppHash from JSON."); +// } - public override void Write( - Utf8JsonWriter writer, AppHash value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } -} +// public override void Write( +// Utf8JsonWriter writer, AppHash value, JsonSerializerOptions options) +// { +// writer.WriteStringValue(value.ToString()); +// } +// } diff --git a/src/console/LibplanetConsole.Console/IBlockChain.cs b/src/console/LibplanetConsole.Console/IBlockChain.cs index b3a61a04..536cfce8 100644 --- a/src/console/LibplanetConsole.Console/IBlockChain.cs +++ b/src/console/LibplanetConsole.Console/IBlockChain.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Bencodex.Types; using Libplanet.Action; using Libplanet.Crypto; @@ -13,21 +14,21 @@ public interface IBlockChain Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); - Task GetTipHashAsync(CancellationToken cancellationToken); + Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken); - Task GetBlockHashAsync(long height, CancellationToken cancellationToken); + Task GetBlockHashAsync(long height, CancellationToken cancellationToken); Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction; diff --git a/src/console/LibplanetConsole.Console/Node.BlockChain.cs b/src/console/LibplanetConsole.Console/Node.BlockChain.cs index 488433fc..cd910805 100644 --- a/src/console/LibplanetConsole.Console/Node.BlockChain.cs +++ b/src/console/LibplanetConsole.Console/Node.BlockChain.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Bencodex.Types; using Libplanet.Action; using Libplanet.Crypto; @@ -48,11 +49,11 @@ void IBlockChainCallback.OnBlockAppended(BlockInfo blockInfo) BlockAppended?.Invoke(this, new BlockEventArgs(blockInfo)); } - public Task GetTipHashAsync(CancellationToken cancellationToken) + public Task GetTipHashAsync(CancellationToken cancellationToken) => _blockChainService.Service.GetTipHashAsync(cancellationToken); public async Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken) @@ -66,7 +67,7 @@ public async Task GetStateAsync( } public async Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken) @@ -79,7 +80,7 @@ public async Task GetStateByStateRootHashAsync( return _codec.Decode(bytes); } - public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) + public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) => _blockChainService.Service.GetBlockHashAsync(height, cancellationToken); public async Task GetActionAsync( diff --git a/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs b/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs index 644fb50a..1bd55121 100644 --- a/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs +++ b/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs @@ -47,7 +47,7 @@ private static Vote MakeRandomVote( INode node, long height, int round, BigInteger power) { var hash = new BlockHash(GetRandomBytes(BlockHash.Size)); - var publicKey = (PublicKey)node.PublicKey; + var publicKey = node.PublicKey; var voteMetadata = new VoteMetadata( height, round, @@ -76,7 +76,7 @@ private void InvokeViolation(ConsensusContext consensusContext) var round = (int)consensusContext.Round; var context = consensusContext.GetContext(); var validatorSet = context.GetValidatorSet(); - var publicKey = (PublicKey)node.PublicKey; + var publicKey = node.PublicKey; var validator = validatorSet.Validators.First(item => item.PublicKey == publicKey); var power = validator.Power; var vote = MakeRandomVote(node, height, round, power); diff --git a/src/node/LibplanetConsole.Node/ActionProvider.cs b/src/node/LibplanetConsole.Node/ActionProvider.cs index 2157b9f6..75fc8df4 100644 --- a/src/node/LibplanetConsole.Node/ActionProvider.cs +++ b/src/node/LibplanetConsole.Node/ActionProvider.cs @@ -27,7 +27,7 @@ internal sealed class ActionProvider : IActionProvider public IAction[] GetGenesisActions(AppPrivateKey genesisKey, PublicKey[] validatorKeys) { var validators = validatorKeys - .Select(item => new Validator((PublicKey)item, BigInteger.One)) + .Select(item => new Validator(item, BigInteger.One)) .ToArray(); var validatorSet = new ValidatorSet(validators: [.. validators]); var actions = new IAction[] diff --git a/src/node/LibplanetConsole.Node/IBlockChain.cs b/src/node/LibplanetConsole.Node/IBlockChain.cs index bdfac04f..ee49b537 100644 --- a/src/node/LibplanetConsole.Node/IBlockChain.cs +++ b/src/node/LibplanetConsole.Node/IBlockChain.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Bencodex.Types; using Libplanet.Action; using Libplanet.Crypto; @@ -13,21 +14,21 @@ public interface IBlockChain Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); - Task GetTipHashAsync(CancellationToken cancellationToken); + Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken); - Task GetBlockHashAsync(long height, CancellationToken cancellationToken); + Task GetBlockHashAsync(long height, CancellationToken cancellationToken); Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken) where T : IAction; diff --git a/src/node/LibplanetConsole.Node/Node.BlockChain.cs b/src/node/LibplanetConsole.Node/Node.BlockChain.cs index 6e551ca5..07b9ff4a 100644 --- a/src/node/LibplanetConsole.Node/Node.BlockChain.cs +++ b/src/node/LibplanetConsole.Node/Node.BlockChain.cs @@ -35,7 +35,7 @@ public async Task AddTransactionAsync( genesisHash: genesisBlock.Hash, actions: new TxActionList(values)); await AddTransactionAsync(transaction, cancellationToken); - return (TxId)transaction.Id; + return transaction.Id; } public async Task AddTransactionAsync( @@ -92,24 +92,24 @@ long GetNextNonce() } } - public Task GetTipHashAsync(CancellationToken cancellationToken) + public Task GetTipHashAsync(CancellationToken cancellationToken) { ObjectDisposedExceptionUtility.ThrowIf(_isDisposed, this); InvalidOperationExceptionUtility.ThrowIf( condition: IsRunning != true, message: "Node is not running."); - AppHash GetTipHash() + BlockHash GetTipHash() { var blockChain = BlockChain; - return (AppHash)blockChain.Tip.Hash; + return blockChain.Tip.Hash; } return Task.Run(GetTipHash, cancellationToken); } public Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken) @@ -122,7 +122,7 @@ public Task GetStateAsync( IValue GetStateByBlockHash() { var blockChain = BlockChain; - var block = blockHash == default ? blockChain.Tip : blockChain[(BlockHash)blockHash]; + var block = blockHash is null ? blockChain.Tip : blockChain[blockHash.Value]; var isTip = block.Hash.Equals(blockChain.Tip.Hash); var worldState = isTip ? blockChain.GetNextWorldState() ?? blockChain.GetWorldState(block.Hash) @@ -136,7 +136,7 @@ IValue GetStateByBlockHash() } public Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken) @@ -149,7 +149,7 @@ public Task GetStateByStateRootHashAsync( IValue GetStateByStateRootHash() { var blockChain = BlockChain; - var worldState = blockChain.GetWorldState((HashDigest)stateRootHash); + var worldState = blockChain.GetWorldState(stateRootHash); var account = worldState.GetAccountState(accountAddress); return account.GetState(address) ?? throw new InvalidOperationException("State not found."); @@ -158,18 +158,18 @@ IValue GetStateByStateRootHash() return Task.Run(GetStateByStateRootHash, cancellationToken); } - public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) + public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) { ObjectDisposedExceptionUtility.ThrowIf(_isDisposed, this); InvalidOperationExceptionUtility.ThrowIf( condition: IsRunning != true, message: "Node is not running."); - AppHash GetBlockHash() + BlockHash GetBlockHash() { var blockChain = BlockChain; var block = blockChain[height]; - return (AppHash)block.Hash; + return block.Hash; } return Task.Run(GetBlockHash, cancellationToken); @@ -181,7 +181,7 @@ public Task GetActionAsync( byte[] GetAction() { var blockChain = BlockChain; - var transaction = blockChain.GetTransaction((TxId)txId); + var transaction = blockChain.GetTransaction(txId); var action = transaction.Actions[actionIndex]; return _codec.Encode(action); } @@ -196,7 +196,7 @@ public Task GetActionAsync( T GetAction() { var blockChain = BlockChain; - var transaction = blockChain.GetTransaction((TxId)txId); + var transaction = blockChain.GetTransaction(txId); var value = transaction.Actions[actionIndex]; if (Activator.CreateInstance(typeof(T)) is T action) { diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index 2e8b5380..907b6177 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -346,8 +346,8 @@ private void UpdateNodeInfo() { SwarmEndPoint = AppEndPoint.ToString(SwarmEndPoint), ConsensusEndPoint = AppEndPoint.ToString(ConsensusEndPoint), - GenesisHash = (AppHash)BlockChain.Genesis.Hash, - TipHash = (AppHash)BlockChain.Tip.Hash, + GenesisHash = BlockChain.Genesis.Hash, + TipHash = BlockChain.Tip.Hash, IsRunning = IsRunning, // Peers = [.. Peers], }; diff --git a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs index 30005636..ebd8f53b 100644 --- a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs +++ b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs @@ -1,4 +1,5 @@ using System.ComponentModel.Composition; +using System.Security.Cryptography; using Bencodex; using Libplanet.Crypto; using Libplanet.Types.Tx; @@ -26,17 +27,17 @@ public async Task SendTransactionAsync( { var tx = Transaction.Deserialize(transaction); await _node.AddTransactionAsync(tx, cancellationToken); - return (TxId)tx.Id; + return tx.Id; } public Task GetNextNonceAsync(Address address, CancellationToken cancellationToken) => _node.GetNextNonceAsync(address, cancellationToken); - public Task GetTipHashAsync(CancellationToken cancellationToken) + public Task GetTipHashAsync(CancellationToken cancellationToken) => _node.GetTipHashAsync(cancellationToken); public async Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken) @@ -47,7 +48,7 @@ public async Task GetStateAsync( } public async Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken) @@ -57,7 +58,7 @@ public async Task GetStateByStateRootHashAsync( return _codec.Encode(value); } - public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) + public Task GetBlockHashAsync(long height, CancellationToken cancellationToken) => _node.GetBlockHashAsync(height, cancellationToken); public Task GetActionAsync( diff --git a/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs b/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs index 4429281e..4ca85eb6 100644 --- a/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs +++ b/src/shared/LibplanetConsole.Node/BlockInfo.Node.cs @@ -11,7 +11,7 @@ public readonly partial record struct BlockInfo public BlockInfo(BlockChain blockChain, Block block) { Height = block.Index; - Hash = (AppHash)block.Hash; + Hash = block.Hash; Miner = block.Miner; Transactions = [.. block.Transactions.Select(GetTransaction)]; diff --git a/src/shared/LibplanetConsole.Node/BlockInfo.cs b/src/shared/LibplanetConsole.Node/BlockInfo.cs index ad8af62b..78211573 100644 --- a/src/shared/LibplanetConsole.Node/BlockInfo.cs +++ b/src/shared/LibplanetConsole.Node/BlockInfo.cs @@ -11,7 +11,7 @@ public BlockInfo() public long Height { get; init; } - public AppHash Hash { get; init; } + public BlockHash Hash { get; init; } public Address Miner { get; init; } diff --git a/src/shared/LibplanetConsole.Node/NodeInfo.cs b/src/shared/LibplanetConsole.Node/NodeInfo.cs index 9b203764..7f6a420e 100644 --- a/src/shared/LibplanetConsole.Node/NodeInfo.cs +++ b/src/shared/LibplanetConsole.Node/NodeInfo.cs @@ -16,9 +16,9 @@ public readonly record struct NodeInfo public Address Address { get; init; } - public AppHash GenesisHash { get; init; } + public BlockHash GenesisHash { get; init; } - public AppHash TipHash { get; init; } + public BlockHash TipHash { get; init; } public bool IsRunning { get; init; } diff --git a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs index c5a37cbf..5b5ef3c7 100644 --- a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs +++ b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs @@ -1,3 +1,4 @@ +using System.Security.Cryptography; using Libplanet.Crypto; using LibplanetConsole.Common; @@ -9,21 +10,21 @@ public interface IBlockChainService Task GetNextNonceAsync(Address address, CancellationToken cancellationToken); - Task GetTipHashAsync(CancellationToken cancellationToken); + Task GetTipHashAsync(CancellationToken cancellationToken); Task GetStateAsync( - AppHash blockHash, + BlockHash? blockHash, Address accountAddress, Address address, CancellationToken cancellationToken); Task GetStateByStateRootHashAsync( - AppHash stateRootHash, + HashDigest stateRootHash, Address accountAddress, Address address, CancellationToken cancellationToken); - Task GetBlockHashAsync(long height, CancellationToken cancellationToken); + Task GetBlockHashAsync(long height, CancellationToken cancellationToken); Task GetActionAsync(TxId txId, int actionIndex, CancellationToken cancellationToken); } diff --git a/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs b/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs index cc7567d7..1563f65a 100644 --- a/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs +++ b/src/shared/LibplanetConsole.Node/TransactionInfo.Node.cs @@ -8,7 +8,7 @@ public readonly partial record struct TransactionInfo { public TransactionInfo(TxExecution execution, ITransaction transaction) { - Id = (TxId)transaction.Id; + Id = transaction.Id; Signer = transaction.Signer; Actions = GetActionInfos(transaction); IsFailed = execution.Fail; @@ -20,7 +20,7 @@ private static ActionInfo[] GetActionInfos(ITransaction transaction) for (var i = 0; i < transaction.Actions.Count; i++) { var action = transaction.Actions[i]; - infos[i] = new ActionInfo(action) { Index = i, TxId = (TxId)transaction.Id }; + infos[i] = new ActionInfo(action) { Index = i, TxId = transaction.Id }; } return infos; From 3219df35754728c12d360592298b580b7fcf6664 Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 18:31:45 +0900 Subject: [PATCH 6/9] refactor: Remove AppPrivateKey --- .../ApplicationSettings.cs | 8 +- .../EntryCommands/InitializeCommand.cs | 6 +- .../Repository.cs | 6 +- .../ApplicationOptions.cs | 4 +- .../Client.BlockChain.cs | 2 +- .../LibplanetConsole.Common/AppPrivateKey.cs | 258 +++++++++--------- .../Commands/KeyCommandBase.cs | 8 +- .../Converters/AppPrivateKeyJsonConverter.cs | 10 +- .../DataAnnotations/AppPeerAttribute.cs | 42 +-- ...PointAttribute.cs => EndPointAttribute.cs} | 6 +- ...KeyAttribute.cs => PrivateKeyAttribute.cs} | 10 +- .../Extensions/PrivateKeyExtensions.cs | 38 +++ .../PrivateKeyUtility.cs | 40 +++ src/common/LibplanetConsole.Seed/SeedNode.cs | 4 +- .../LibplanetConsole.Seed/SeedOptions.cs | 2 +- .../ApplicationSettings.cs | 18 +- .../EntryCommands/InitializeCommand.cs | 24 +- .../LibplanetConsole.Console/ClientOptions.cs | 4 +- .../LibplanetConsole.Console/ClientProcess.cs | 2 +- .../ClientRepositoryProcess.cs | 4 +- .../Commands/ClientCommand.cs | 2 +- .../Commands/NodeCommand.cs | 2 +- src/console/LibplanetConsole.Console/Node.cs | 1 + .../NodeGenesisProcess.cs | 2 +- .../LibplanetConsole.Console/NodeOptions.cs | 4 +- .../LibplanetConsole.Console/NodeProcess.cs | 2 +- .../NodeRepositoryProcess.cs | 4 +- .../LibplanetConsole.Console/Repository.cs | 6 +- .../RepositoryPathResolver.cs | 18 +- .../Services/SeedService.cs | 2 +- .../ActionProvider.cs | 2 +- .../ApplicationSettings.cs | 10 +- .../EntryCommands/GenesisCommand.cs | 9 +- .../EntryCommands/InitializeCommand.cs | 12 +- .../Repository.cs | 6 +- .../ExplorerSettings.cs | 2 +- .../LibplanetConsole.Node/ActionProvider.cs | 2 +- .../ApplicationOptions.cs | 4 +- .../LibplanetConsole.Node/BlockUtility.cs | 2 +- .../LibplanetConsole.Node/IActionProvider.cs | 2 +- .../LibplanetConsole.Node/Node.BlockChain.cs | 2 +- src/node/LibplanetConsole.Node/Node.cs | 6 +- .../Services/SeedService.cs | 2 +- .../LibplanetConsole.Node/GenesisOptions.cs | 2 +- .../AppPeerTest.cs | 2 +- 45 files changed, 342 insertions(+), 262 deletions(-) rename src/common/LibplanetConsole.Common/DataAnnotations/{AppEndPointAttribute.cs => EndPointAttribute.cs} (66%) rename src/common/LibplanetConsole.Common/DataAnnotations/{AppPrivateKeyAttribute.cs => PrivateKeyAttribute.cs} (52%) create mode 100644 src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs create mode 100644 src/common/LibplanetConsole.Common/PrivateKeyUtility.cs diff --git a/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs b/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs index 7bc436ac..0717e43e 100644 --- a/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs +++ b/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs @@ -14,13 +14,13 @@ internal sealed record class ApplicationSettings [CommandProperty] [CommandSummary("Indicates the EndPoint on which the client will run. " + "If omitted, a random endpoint is used.")] - [AppEndPoint] + [EndPoint] public string EndPoint { get; init; } = string.Empty; [CommandProperty] [CommandSummary("Indicates the private key of the client. " + "If omitted, a random private key is used.")] - [AppPrivateKey] + [PrivateKey] public string PrivateKey { get; init; } = string.Empty; [CommandProperty("parent")] @@ -31,7 +31,7 @@ internal sealed record class ApplicationSettings [CommandProperty] [CommandSummary("Indicates the EndPoint of the node to connect to.")] - [AppEndPoint] + [EndPoint] public string NodeEndPoint { get; init; } = string.Empty; [CommandProperty] @@ -48,7 +48,7 @@ internal sealed record class ApplicationSettings public ApplicationOptions ToOptions(object[] components) { var endPoint = AppEndPoint.ParseOrNext(EndPoint); - var privateKey = AppPrivateKey.ParseOrRandom(PrivateKey); + var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); return new ApplicationOptions(endPoint, privateKey) { ParentProcessId = ParentProcessId, diff --git a/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs b/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs index 880470ae..7a678cda 100644 --- a/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs +++ b/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs @@ -23,13 +23,13 @@ public InitializeCommand() [CommandProperty] [CommandSummary("Indicates the private key of the client. " + "If omitted, a random private key is used.")] - [AppPrivateKey] + [PrivateKey] public string PrivateKey { get; init; } = string.Empty; [CommandProperty] [CommandSummary("The endpoint of the client. " + "If omitted, a random endpoint is used.")] - [AppEndPoint] + [EndPoint] public string EndPoint { get; set; } = string.Empty; [CommandProperty] @@ -46,7 +46,7 @@ protected override void OnExecute() { var outputPath = Path.GetFullPath(OutputPath); var endPoint = AppEndPoint.ParseOrNext(EndPoint); - var privateKey = AppPrivateKey.ParseOrRandom(PrivateKey); + var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); var logPath = Path.Combine(outputPath, LogPath.Fallback("app.log")); var repository = new Repository { diff --git a/src/client/LibplanetConsole.Client.Executable/Repository.cs b/src/client/LibplanetConsole.Client.Executable/Repository.cs index 9cf608e9..ca5ad287 100644 --- a/src/client/LibplanetConsole.Client.Executable/Repository.cs +++ b/src/client/LibplanetConsole.Client.Executable/Repository.cs @@ -13,7 +13,7 @@ public sealed record class Repository public required AppEndPoint EndPoint { get; init; } - public required AppPrivateKey PrivateKey { get; init; } + public required PrivateKey PrivateKey { get; init; } public AppEndPoint? NodeEndPoint { get; init; } @@ -38,7 +38,7 @@ public static Repository Load(string settingsPath) return new() { EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), - PrivateKey = AppPrivateKey.Parse(applicationSettings.PrivateKey), + PrivateKey = new PrivateKey(applicationSettings.PrivateKey), LogPath = Path.GetFullPath(applicationSettings.LogPath, directoryName), Source = settingsPath, NodeEndPoint = AppEndPoint.ParseOrDefault(applicationSettings.NodeEndPoint), @@ -81,7 +81,7 @@ public dynamic Save(string repositoryPath) Application = new ApplicationSettings { EndPoint = EndPoint.ToString(), - PrivateKey = AppPrivateKey.ToString(privateKey), + PrivateKey = PrivateKeyUtility.ToString(privateKey), LogPath = GetRelativePathFromDirectory(repositoryPath, LogPath), NodeEndPoint = AppEndPoint.ToString(NodeEndPoint), }, diff --git a/src/client/LibplanetConsole.Client/ApplicationOptions.cs b/src/client/LibplanetConsole.Client/ApplicationOptions.cs index d6456bd2..8feeabbf 100644 --- a/src/client/LibplanetConsole.Client/ApplicationOptions.cs +++ b/src/client/LibplanetConsole.Client/ApplicationOptions.cs @@ -4,7 +4,7 @@ namespace LibplanetConsole.Client; public sealed record class ApplicationOptions { - public ApplicationOptions(AppEndPoint endPoint, AppPrivateKey privateKey) + public ApplicationOptions(AppEndPoint endPoint, PrivateKey privateKey) { EndPoint = endPoint; PrivateKey = privateKey; @@ -12,7 +12,7 @@ public ApplicationOptions(AppEndPoint endPoint, AppPrivateKey privateKey) public AppEndPoint EndPoint { get; } - public AppPrivateKey PrivateKey { get; } + public PrivateKey PrivateKey { get; } public int ParentProcessId { get; init; } diff --git a/src/client/LibplanetConsole.Client/Client.BlockChain.cs b/src/client/LibplanetConsole.Client/Client.BlockChain.cs index 121cffcf..6a296e0c 100644 --- a/src/client/LibplanetConsole.Client/Client.BlockChain.cs +++ b/src/client/LibplanetConsole.Client/Client.BlockChain.cs @@ -17,7 +17,7 @@ internal sealed partial class Client : IBlockChain public async Task SendTransactionAsync( IAction[] actions, CancellationToken cancellationToken) { - var privateKey = AppPrivateKey.FromSecureString(_privateKey); + var privateKey = PrivateKeyUtility.FromSecureString(_privateKey); var address = privateKey.Address; var nonce = await RemoteBlockChainService.GetNextNonceAsync(address, cancellationToken); var genesisHash = NodeInfo.GenesisHash; diff --git a/src/common/LibplanetConsole.Common/AppPrivateKey.cs b/src/common/LibplanetConsole.Common/AppPrivateKey.cs index 9bec3432..41562b8a 100644 --- a/src/common/LibplanetConsole.Common/AppPrivateKey.cs +++ b/src/common/LibplanetConsole.Common/AppPrivateKey.cs @@ -1,129 +1,129 @@ -using System.Diagnostics.CodeAnalysis; -using System.Security; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Bencodex; -using Bencodex.Types; -using Libplanet.Common; -using Libplanet.Crypto; -using LibplanetConsole.Common.Converters; -using LibplanetConsole.Common.Extensions; - -namespace LibplanetConsole.Common; - -[JsonConverter(typeof(AppPrivateKeyJsonConverter))] -public sealed record class AppPrivateKey -{ - public const string RegularExpression = "[0-9a-fA-F]{64}"; - private static readonly Codec _codec = new(); - private readonly PrivateKey _privateKey; - - public AppPrivateKey(PrivateKey privateKey) => _privateKey = privateKey; - - public AppPrivateKey(byte[] bytes) - : this(new PrivateKey(bytes)) - { - } - - public AppPrivateKey() - : this(new PrivateKey()) - { - } - - public PublicKey PublicKey => _privateKey.PublicKey; - - public Address Address => _privateKey.PublicKey.Address; - - public static explicit operator AppPrivateKey(PrivateKey privateKey) - => new(privateKey); - - public static explicit operator PrivateKey(AppPrivateKey privateKey) - => privateKey._privateKey; - - public static string ToString(AppPrivateKey? privateKey) - => privateKey is not null ? ByteUtil.Hex(privateKey.ToByteArray()) : string.Empty; - - public static AppPrivateKey Parse(string text) => new(new PrivateKey(text)); - - public static AppPrivateKey? ParseOrDefault(string text) - => text == string.Empty ? null : Parse(text); - - public static AppPrivateKey ParseOrRandom(string text) - => text == string.Empty ? new AppPrivateKey() : Parse(text); - - public static bool TryParse(string text, [MaybeNullWhen(false)] out AppPrivateKey privateKey) - { - try - { - privateKey = Parse(text); - return true; - } - catch - { - privateKey = default; - return false; - } - } - - public override string? ToString() - { -#if DEBUG - System.Diagnostics.Trace.TraceWarning( - "AppPrivateKey.ToString() is called. It may be a security risk."); -#endif - return base.ToString(); - } - - public byte[] ToByteArray() => [.. _privateKey.ByteArray]; - - public static AppPrivateKey FromSecureString(SecureString secureString) - { - using var ptr = new StringPointer(secureString); - var text = ptr.GetString(); - var bytes = ByteUtil.ParseHex(text); - return new(bytes); - } - - public SecureString ToSecureString() - { - var secureString = new SecureString(); - var text = ByteUtil.Hex(_privateKey.ByteArray); - secureString.AppendString(text); - return secureString; - } - - public object? Decrypt(string text, Type type) - { - var bytes = ByteUtil.ParseHex(text); - var decrypted = _privateKey.Decrypt(bytes); - var json = Encoding.UTF8.GetString(decrypted); - return JsonSerializer.Deserialize(json, type); - } - - public byte[] Decrypt(byte[] bytes) => _privateKey.Decrypt(bytes); - - public T Decrypt(string text) - where T : notnull => Decrypt(text, typeof(T)) switch - { - T result => result, - _ => throw new InvalidOperationException($"Failed to decrypt {text} as {typeof(T)}."), - }; - - public byte[] Sign(object obj) - { - if (obj is IValue value) - { - return _privateKey.Sign(_codec.Encode(value)); - } - - if (obj is IBencodable bencodable) - { - return _privateKey.Sign(_codec.Encode(bencodable.Bencoded)); - } - - var json = JsonSerializer.Serialize(obj); - var bytes = Encoding.UTF8.GetBytes(json); - return _privateKey.Sign(bytes); - } -} +// using System.Diagnostics.CodeAnalysis; +// using System.Security; +// using System.Text; +// using System.Text.Json; +// using System.Text.Json.Serialization; +// using Bencodex; +// using Bencodex.Types; +// using Libplanet.Common; +// using Libplanet.Crypto; +// using LibplanetConsole.Common.Converters; +// using LibplanetConsole.Common.Extensions; + +// namespace LibplanetConsole.Common; + +// [JsonConverter(typeof(PrivateKeyJsonConverter))] +// public sealed record class PrivateKey +// { +// public const string RegularExpression = "[0-9a-fA-F]{64}"; +// private static readonly Codec _codec = new(); +// private readonly PrivateKey _privateKey; + +// public PrivateKey(PrivateKey privateKey) => _privateKey = privateKey; + +// public PrivateKey(byte[] bytes) +// : this(new PrivateKey(bytes)) +// { +// } + +// public PrivateKey() +// : this(new PrivateKey()) +// { +// } + +// public PublicKey PublicKey => _privateKey.PublicKey; + +// public Address Address => _privateKey.PublicKey.Address; + +// public static explicit operator PrivateKey(PrivateKey privateKey) +// => new(privateKey); + +// public static explicit operator PrivateKey(PrivateKey privateKey) +// => privateKey._privateKey; + +// public static string ToString(PrivateKey? privateKey) +// => privateKey is not null ? ByteUtil.Hex(privateKey.ToByteArray()) : string.Empty; + +// public static PrivateKey Parse(string text) => new(new PrivateKey(text)); + +// public static PrivateKey? ParseOrDefault(string text) +// => text == string.Empty ? null : Parse(text); + +// public static PrivateKey ParseOrRandom(string text) +// => text == string.Empty ? new PrivateKey() : Parse(text); + +// public static bool TryParse(string text, [MaybeNullWhen(false)] out PrivateKey privateKey) +// { +// try +// { +// privateKey = Parse(text); +// return true; +// } +// catch +// { +// privateKey = default; +// return false; +// } +// } + +// public override string? ToString() +// { +// #if DEBUG +// System.Diagnostics.Trace.TraceWarning( +// "PrivateKey.ToString() is called. It may be a security risk."); +// #endif +// return base.ToString(); +// } + +// public byte[] ToByteArray() => [.. _privateKey.ByteArray]; + +// public static PrivateKey FromSecureString(SecureString secureString) +// { +// using var ptr = new StringPointer(secureString); +// var text = ptr.GetString(); +// var bytes = ByteUtil.ParseHex(text); +// return new(bytes); +// } + +// public SecureString ToSecureString() +// { +// var secureString = new SecureString(); +// var text = ByteUtil.Hex(_privateKey.ByteArray); +// secureString.AppendString(text); +// return secureString; +// } + +// public object? Decrypt(string text, Type type) +// { +// var bytes = ByteUtil.ParseHex(text); +// var decrypted = _privateKey.Decrypt(bytes); +// var json = Encoding.UTF8.GetString(decrypted); +// return JsonSerializer.Deserialize(json, type); +// } + +// public byte[] Decrypt(byte[] bytes) => _privateKey.Decrypt(bytes); + +// public T Decrypt(string text) +// where T : notnull => Decrypt(text, typeof(T)) switch +// { +// T result => result, +// _ => throw new InvalidOperationException($"Failed to decrypt {text} as {typeof(T)}."), +// }; + +// public byte[] Sign(object obj) +// { +// if (obj is IValue value) +// { +// return _privateKey.Sign(_codec.Encode(value)); +// } + +// if (obj is IBencodable bencodable) +// { +// return _privateKey.Sign(_codec.Encode(bencodable.Bencoded)); +// } + +// var json = JsonSerializer.Serialize(obj); +// var bytes = Encoding.UTF8.GetBytes(json); +// return _privateKey.Sign(bytes); +// } +// } diff --git a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs index 2ece02d6..d7412340 100644 --- a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs +++ b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs @@ -21,10 +21,10 @@ public void New( var info = Enumerable.Range(0, count).Select(_ => { - var privateKey = new AppPrivateKey(); + var privateKey = new PrivateKey(); return new { - PrivateKey = AppPrivateKey.ToString(privateKey), + PrivateKey = PrivateKeyUtility.ToString(privateKey), privateKey.PublicKey, privateKey.Address, }; @@ -38,7 +38,7 @@ public void Public( [CommandSummary("Indicates the private key that corresponds to the public key.")] string privateKey) { - var key = AppPrivateKey.Parse(privateKey); + var key = new PrivateKey(privateKey); var info = new { key.PublicKey, @@ -76,7 +76,7 @@ public void Derive( private static Address GetAddress(string key) { - if (AppPrivateKey.TryParse(key, out var privateKey) == true) + if (PrivateKeyUtility.TryParse(key, out var privateKey) == true) { return privateKey.Address; } diff --git a/src/common/LibplanetConsole.Common/Converters/AppPrivateKeyJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppPrivateKeyJsonConverter.cs index ba8bf6a7..2cb12cfd 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppPrivateKeyJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/AppPrivateKeyJsonConverter.cs @@ -3,19 +3,19 @@ namespace LibplanetConsole.Common.Converters; -public sealed class AppPrivateKeyJsonConverter : JsonConverter +public sealed class PrivateKeyJsonConverter : JsonConverter { - public override AppPrivateKey Read( + public override PrivateKey Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - throw new JsonException($"{nameof(AppPrivateKey)} is not supported for security reasons."); + throw new JsonException($"{nameof(PrivateKey)} is not supported for security reasons."); } public override void Write( - Utf8JsonWriter writer, AppPrivateKey value, JsonSerializerOptions options) + Utf8JsonWriter writer, PrivateKey value, JsonSerializerOptions options) { - throw new JsonException($"{nameof(AppPrivateKey)} is not supported for security reasons."); + throw new JsonException($"{nameof(PrivateKey)} is not supported for security reasons."); } } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs index 4162191c..29808200 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs @@ -1,26 +1,26 @@ -#pragma warning disable SA1402 // File may only contain a single type -using System.ComponentModel.DataAnnotations; -using LibplanetConsole.DataAnnotations; +// #pragma warning disable SA1402 // File may only contain a single type +// using System.ComponentModel.DataAnnotations; +// using LibplanetConsole.DataAnnotations; -namespace LibplanetConsole.Common.DataAnnotations; +// namespace LibplanetConsole.Common.DataAnnotations; -[AttributeUsage(AttributeTargets.Property)] -public sealed class AppPeerAttribute : RegularExpressionAttribute -{ - public const string HostExpression - = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; +// [AttributeUsage(AttributeTargets.Property)] +// public sealed class AppPeerAttribute : RegularExpressionAttribute +// { +// public const string HostExpression +// = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; - public const string PortExpression = @"\d{1,5}"; - public static readonly string RegularExpression - = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; +// public const string PortExpression = @"\d{1,5}"; +// public static readonly string RegularExpression +// = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; - public AppPeerAttribute() - : base($"^{RegularExpression}$") - { - } -} +// public AppPeerAttribute() +// : base($"^{RegularExpression}$") +// { +// } +// } -[AttributeUsage(AttributeTargets.Property)] -public sealed class AppPeerArrayAttribute : ArrayAttribute -{ -} +// [AttributeUsage(AttributeTargets.Property)] +// public sealed class AppPeerArrayAttribute : ArrayAttribute +// { +// } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppEndPointAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/EndPointAttribute.cs similarity index 66% rename from src/common/LibplanetConsole.Common/DataAnnotations/AppEndPointAttribute.cs rename to src/common/LibplanetConsole.Common/DataAnnotations/EndPointAttribute.cs index c3bf07e9..7fe791cb 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppEndPointAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/EndPointAttribute.cs @@ -5,15 +5,15 @@ namespace LibplanetConsole.Common.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] -public sealed class AppEndPointAttribute : RegularExpressionAttribute +public sealed class EndPointAttribute : RegularExpressionAttribute { - public AppEndPointAttribute() + public EndPointAttribute() : base($"^{AppEndPoint.RegularExpression}$") { } } [AttributeUsage(AttributeTargets.Property)] -public sealed class AppEndPointArrayAttribute : ArrayAttribute +public sealed class AppEndPointArrayAttribute : ArrayAttribute { } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppPrivateKeyAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/PrivateKeyAttribute.cs similarity index 52% rename from src/common/LibplanetConsole.Common/DataAnnotations/AppPrivateKeyAttribute.cs rename to src/common/LibplanetConsole.Common/DataAnnotations/PrivateKeyAttribute.cs index 21878a8b..251d8a64 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppPrivateKeyAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/PrivateKeyAttribute.cs @@ -5,15 +5,17 @@ namespace LibplanetConsole.Common.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] -public sealed class AppPrivateKeyAttribute : RegularExpressionAttribute +public sealed class PrivateKeyAttribute : RegularExpressionAttribute { - public AppPrivateKeyAttribute() - : base($"^{AppPrivateKey.RegularExpression}$") + public const string RegularExpression = "[0-9a-fA-F]{64}"; + + public PrivateKeyAttribute() + : base($"^{RegularExpression}$") { } } [AttributeUsage(AttributeTargets.Property)] -public sealed class AppPrivateKeyArrayAttribute : ArrayAttribute +public sealed class PrivateKeyArrayAttribute : ArrayAttribute { } diff --git a/src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs new file mode 100644 index 00000000..e35cb77e --- /dev/null +++ b/src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs @@ -0,0 +1,38 @@ +using System.Security; +using System.Text; +using System.Text.Json; +using Bencodex; +using Bencodex.Types; +using Libplanet.Crypto; + +namespace LibplanetConsole.Common.Extensions; + +public static class PrivateKeyExtensions +{ + private static readonly Codec _codec = new(); + + public static SecureString ToSecureString(this PrivateKey @this) + { + var secureString = new SecureString(); + var text = ByteUtil.Hex(@this.ByteArray); + secureString.AppendString(text); + return secureString; + } + + public static byte[] Sign(this PrivateKey @this, object obj) + { + if (obj is IValue value) + { + return @this.Sign(_codec.Encode(value)); + } + + if (obj is IBencodable bencodable) + { + return @this.Sign(_codec.Encode(bencodable.Bencoded)); + } + + var json = JsonSerializer.Serialize(obj); + var bytes = Encoding.UTF8.GetBytes(json); + return @this.Sign(bytes); + } +} diff --git a/src/common/LibplanetConsole.Common/PrivateKeyUtility.cs b/src/common/LibplanetConsole.Common/PrivateKeyUtility.cs new file mode 100644 index 00000000..e98e5879 --- /dev/null +++ b/src/common/LibplanetConsole.Common/PrivateKeyUtility.cs @@ -0,0 +1,40 @@ +using System.Diagnostics.CodeAnalysis; +using System.Security; +using System.Text; +using System.Text.Json; +using Bencodex; +using Bencodex.Types; +using Libplanet.Crypto; + +namespace LibplanetConsole.Common; + +public static class PrivateKeyUtility +{ + public static PrivateKey FromSecureString(SecureString secureString) + { + using var ptr = new StringPointer(secureString); + var text = ptr.GetString(); + var bytes = ByteUtil.ParseHex(text); + return new(bytes); + } + + public static PrivateKey ParseOrRandom(string text) + => text == string.Empty ? new PrivateKey() : new PrivateKey(text); + + public static bool TryParse(string text, [MaybeNullWhen(false)] out PrivateKey privateKey) + { + try + { + privateKey = new(text); + return true; + } + catch + { + privateKey = default; + return false; + } + } + + public static string ToString(PrivateKey? privateKey) + => privateKey is not null ? ByteUtil.Hex(privateKey.ToByteArray()) : string.Empty; +} diff --git a/src/common/LibplanetConsole.Seed/SeedNode.cs b/src/common/LibplanetConsole.Seed/SeedNode.cs index fb6ecd38..0a88100e 100644 --- a/src/common/LibplanetConsole.Seed/SeedNode.cs +++ b/src/common/LibplanetConsole.Seed/SeedNode.cs @@ -21,8 +21,8 @@ static SeedNode() typeof(BoundPeer), new JsonConverterAttribute(typeof(BoundPeerJsonConverter))); } - public static readonly AppPrivateKey AppProtocolKey - = AppPrivateKey.Parse("2a15e7deaac09ce631e1faa184efadb175b6b90989cf1faed9dfc321ad1db5ac"); + public static readonly PrivateKey AppProtocolKey + = new("2a15e7deaac09ce631e1faa184efadb175b6b90989cf1faed9dfc321ad1db5ac"); public static readonly AppProtocolVersion AppProtocolVersion = AppProtocolVersion.Sign((PrivateKey)AppProtocolKey, 1); diff --git a/src/common/LibplanetConsole.Seed/SeedOptions.cs b/src/common/LibplanetConsole.Seed/SeedOptions.cs index 94861479..caa4ae06 100644 --- a/src/common/LibplanetConsole.Seed/SeedOptions.cs +++ b/src/common/LibplanetConsole.Seed/SeedOptions.cs @@ -4,7 +4,7 @@ namespace LibplanetConsole.Seed; public sealed record class SeedOptions { - public required AppPrivateKey PrivateKey { get; init; } + public required PrivateKey PrivateKey { get; init; } public required AppEndPoint EndPoint { get; init; } diff --git a/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs b/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs index 3b2118bb..af9f299f 100644 --- a/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs +++ b/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs @@ -13,7 +13,7 @@ internal sealed record class ApplicationSettings [CommandProperty] [CommandSummary("The endpoint of the libplanet-console. " + "If omitted, a random endpoint is used.")] - [AppEndPoint] + [EndPoint] public string EndPoint { get; init; } = string.Empty; #if DEBUG @@ -120,7 +120,7 @@ public static ApplicationSettings Parse(string[] args) } private static NodeOptions[] GetNodeOptions( - AppEndPoint endPoint, AppPrivateKey[] nodePrivateKeys) + AppEndPoint endPoint, PrivateKey[] nodePrivateKeys) { return [.. nodePrivateKeys.Select(key => new NodeOptions { @@ -131,7 +131,7 @@ private static NodeOptions[] GetNodeOptions( } private static ClientOptions[] GetClientOptions( - NodeOptions[] nodeOptions, AppPrivateKey[] clientPrivateKeys) + NodeOptions[] nodeOptions, PrivateKey[] clientPrivateKeys) { return [.. clientPrivateKeys.Select(key => new ClientOptions { @@ -144,23 +144,23 @@ static NodeOptions Random(NodeOptions[] nodeOptions) => nodeOptions[System.Random.Shared.Next(nodeOptions.Length)]; } - private AppPrivateKey[] GetNodes() + private PrivateKey[] GetNodes() { if (Nodes.Length > 0) { - return [.. Nodes.Select(AppPrivateKey.Parse)]; + return [.. Nodes.Select(PrivateKey.Parse)]; } - return [.. Enumerable.Range(0, NodeCount).Select(item => new AppPrivateKey())]; + return [.. Enumerable.Range(0, NodeCount).Select(item => new PrivateKey())]; } - private AppPrivateKey[] GetClients() + private PrivateKey[] GetClients() { if (Clients.Length > 0) { - return [.. Clients.Select(AppPrivateKey.Parse)]; + return [.. Clients.Select(PrivateKey.Parse)]; } - return [.. Enumerable.Range(0, ClientCount).Select(item => new AppPrivateKey())]; + return [.. Enumerable.Range(0, ClientCount).Select(item => new PrivateKey())]; } } diff --git a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs index 740cc484..f0049012 100644 --- a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs +++ b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs @@ -25,7 +25,7 @@ public InitializeCommand() [CommandProperty] [CommandSummary("The endpoint of the libplanet-console. " + "If omitted, a random endpoint is used.")] - [AppEndPoint] + [EndPoint] public string EndPoint { get; set; } = string.Empty; [CommandProperty(InitValue = 4)] @@ -38,7 +38,7 @@ public InitializeCommand() [CommandSummary("The private keys of the nodes to create. ex) --nodes \"key1,key2,...\"\n" + "Mutually exclusive with '--node-count' option.")] [CommandPropertyExclusion(nameof(NodeCount))] - [AppPrivateKeyArray] + [PrivateKeyArray] public string[] Nodes { get; init; } = []; [CommandProperty(InitValue = 2)] @@ -51,7 +51,7 @@ public InitializeCommand() [CommandSummary("The private keys of the clients to create. ex) --clients \"key1,key2,...\"\n" + "Mutually exclusive with '--client-count' option.")] [CommandPropertyExclusion(nameof(ClientCount))] - [AppPrivateKeyArray] + [PrivateKeyArray] public string[] Clients { get; init; } = []; [CommandPropertySwitch("quiet", 'q')] @@ -61,7 +61,7 @@ public InitializeCommand() [CommandProperty] [CommandSummary("The private key of the genesis block. " + "if omitted, a random private key is used.")] - [AppPrivateKey] + [PrivateKey] [Category("Genesis")] public string GenesisKey { get; set; } = string.Empty; @@ -84,7 +84,7 @@ public InitializeCommand() protected override void OnExecute() { - var genesisKey = AppPrivateKey.ParseOrRandom(GenesisKey); + var genesisKey = PrivateKeyUtility.ParseOrRandom(GenesisKey); var endPoint = AppEndPoint.ParseOrNext(EndPoint); var prevEndPoint = EndPoint != string.Empty ? endPoint : null; var nodeOptions = GetNodeOptions(ref prevEndPoint); @@ -115,7 +115,7 @@ protected override void OnExecute() dynamic info = repository.Save(outputPath, resolver); info.GenesisArguments = new { - GenesisKey = AppPrivateKey.ToString(genesisKey), + GenesisKey = PrivateKeyUtility.ToString(genesisKey), Validators = nodeOptions.Select( item => item.PrivateKey.PublicKey.ToHex(compress: false)), Timestamp = dateTimeOffset, @@ -176,23 +176,23 @@ private ClientOptions[] GetClientOptions(ref AppEndPoint? prevEndPoint) return [.. clientOptionsList]; } - private AppPrivateKey[] GetNodes() + private PrivateKey[] GetNodes() { if (Nodes.Length > 0) { - return [.. Nodes.Select(item => AppPrivateKey.Parse(item))]; + return [.. Nodes.Select(item => new PrivateKey(item))]; } - return [.. Enumerable.Range(0, NodeCount).Select(item => new AppPrivateKey())]; + return [.. Enumerable.Range(0, NodeCount).Select(item => new PrivateKey())]; } - private AppPrivateKey[] GetClients() + private PrivateKey[] GetClients() { if (Clients.Length > 0) { - return [.. Clients.Select(item => AppPrivateKey.Parse(item))]; + return [.. Clients.Select(item => new PrivateKey(item))]; } - return [.. Enumerable.Range(0, ClientCount).Select(item => new AppPrivateKey())]; + return [.. Enumerable.Range(0, ClientCount).Select(item => new PrivateKey())]; } } diff --git a/src/console/LibplanetConsole.Console/ClientOptions.cs b/src/console/LibplanetConsole.Console/ClientOptions.cs index 9fd22d40..154133f5 100644 --- a/src/console/LibplanetConsole.Console/ClientOptions.cs +++ b/src/console/LibplanetConsole.Console/ClientOptions.cs @@ -8,7 +8,7 @@ public sealed record class ClientOptions { public required AppEndPoint EndPoint { get; init; } - public required AppPrivateKey PrivateKey { get; init; } + public required PrivateKey PrivateKey { get; init; } public AppEndPoint? NodeEndPoint { get; init; } @@ -33,7 +33,7 @@ public static ClientOptions Load(string settingsPath) return new() { EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), - PrivateKey = AppPrivateKey.Parse(applicationSettings.PrivateKey), + PrivateKey = new PrivateKey(applicationSettings.PrivateKey), LogPath = Path.GetFullPath(applicationSettings.LogPath, repositoryPath), NodeEndPoint = AppEndPoint.ParseOrDefault(applicationSettings.NodeEndPoint), RepositoryPath = repositoryPath, diff --git a/src/console/LibplanetConsole.Console/ClientProcess.cs b/src/console/LibplanetConsole.Console/ClientProcess.cs index 9972c134..e9e7280e 100644 --- a/src/console/LibplanetConsole.Console/ClientProcess.cs +++ b/src/console/LibplanetConsole.Console/ClientProcess.cs @@ -24,7 +24,7 @@ public override string[] Arguments argumentList.Add("--end-point"); argumentList.Add(clientOptions.EndPoint.ToString()); argumentList.Add("--private-key"); - argumentList.Add(AppPrivateKey.ToString(clientOptions.PrivateKey)); + argumentList.Add(PrivateKeyUtility.ToString(clientOptions.PrivateKey)); if (clientOptions.LogPath != string.Empty) { diff --git a/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs b/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs index fa48038f..2c37286a 100644 --- a/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs +++ b/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs @@ -4,7 +4,7 @@ namespace LibplanetConsole.Console; internal sealed class ClientRepositoryProcess : ClientProcessBase { - public required AppPrivateKey PrivateKey { get; init; } + public required PrivateKey PrivateKey { get; init; } public required AppEndPoint EndPoint { get; init; } @@ -15,7 +15,7 @@ internal sealed class ClientRepositoryProcess : ClientProcessBase "init", OutputPath, "--private-key", - AppPrivateKey.ToString(PrivateKey), + PrivateKeyUtility.ToString(PrivateKey), "--end-point", AppEndPoint.ToString(EndPoint), ]; diff --git a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs index f096da02..969c1982 100644 --- a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs @@ -57,7 +57,7 @@ public async Task NewAsync( var clientOptions = new ClientOptions { EndPoint = AppEndPoint.Next(), - PrivateKey = AppPrivateKey.ParseOrRandom(privateKey), + PrivateKey = PrivateKeyUtility.ParseOrRandom(privateKey), }; var options = new AddNewClientOptions { diff --git a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs index 2b395304..326e7ac0 100644 --- a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs @@ -66,7 +66,7 @@ public async Task NewAsync( var nodeOptions = new NodeOptions { EndPoint = AppEndPoint.Next(), - PrivateKey = AppPrivateKey.ParseOrRandom(privateKey), + PrivateKey = PrivateKeyUtility.ParseOrRandom(privateKey), }; var options = new AddNewNodeOptions { diff --git a/src/console/LibplanetConsole.Console/Node.cs b/src/console/LibplanetConsole.Console/Node.cs index 2eee2198..7a3811aa 100644 --- a/src/console/LibplanetConsole.Console/Node.cs +++ b/src/console/LibplanetConsole.Console/Node.cs @@ -5,6 +5,7 @@ using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; +using LibplanetConsole.Common.Extensions; using LibplanetConsole.Common.Services; using LibplanetConsole.Console.Services; using LibplanetConsole.Framework; diff --git a/src/console/LibplanetConsole.Console/NodeGenesisProcess.cs b/src/console/LibplanetConsole.Console/NodeGenesisProcess.cs index f680804e..99fd5e2f 100644 --- a/src/console/LibplanetConsole.Console/NodeGenesisProcess.cs +++ b/src/console/LibplanetConsole.Console/NodeGenesisProcess.cs @@ -10,7 +10,7 @@ internal sealed class NodeGenesisProcess : NodeProcessBase [ "genesis", "--genesis-key", - AppPrivateKey.ToString(GenesisOptions.GenesisKey), + PrivateKeyUtility.ToString(GenesisOptions.GenesisKey), "--validators", string.Join(",", GenesisOptions.Validators.Select(item => item.ToString())), "--timestamp", diff --git a/src/console/LibplanetConsole.Console/NodeOptions.cs b/src/console/LibplanetConsole.Console/NodeOptions.cs index 880cc24e..8c9de2fd 100644 --- a/src/console/LibplanetConsole.Console/NodeOptions.cs +++ b/src/console/LibplanetConsole.Console/NodeOptions.cs @@ -8,7 +8,7 @@ public sealed record class NodeOptions { public required AppEndPoint EndPoint { get; init; } - public required AppPrivateKey PrivateKey { get; init; } + public required PrivateKey PrivateKey { get; init; } public AppEndPoint? SeedEndPoint { get; init; } @@ -37,7 +37,7 @@ public static NodeOptions Load(string settingsPath) return new() { EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), - PrivateKey = AppPrivateKey.Parse(applicationSettings.PrivateKey), + PrivateKey = new PrivateKey(applicationSettings.PrivateKey), StorePath = Path.GetFullPath(applicationSettings.StorePath, repositoryPath), LogPath = Path.GetFullPath(applicationSettings.LogPath, repositoryPath), LibraryLogPath = Path.GetFullPath(applicationSettings.LibraryLogPath, repositoryPath), diff --git a/src/console/LibplanetConsole.Console/NodeProcess.cs b/src/console/LibplanetConsole.Console/NodeProcess.cs index 8aea307b..8c88a8c6 100644 --- a/src/console/LibplanetConsole.Console/NodeProcess.cs +++ b/src/console/LibplanetConsole.Console/NodeProcess.cs @@ -23,7 +23,7 @@ public override string[] Arguments argumentList.Add("--end-point"); argumentList.Add(nodeOptions.EndPoint.ToString()); argumentList.Add("--private-key"); - argumentList.Add(AppPrivateKey.ToString(nodeOptions.PrivateKey)); + argumentList.Add(PrivateKeyUtility.ToString(nodeOptions.PrivateKey)); if (nodeOptions.StorePath != string.Empty) { diff --git a/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs b/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs index 50e9874f..41a55995 100644 --- a/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs +++ b/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs @@ -4,7 +4,7 @@ namespace LibplanetConsole.Console; internal sealed class NodeRepositoryProcess : NodeProcessBase { - public required AppPrivateKey PrivateKey { get; init; } + public required PrivateKey PrivateKey { get; init; } public required AppEndPoint EndPoint { get; init; } @@ -17,7 +17,7 @@ internal sealed class NodeRepositoryProcess : NodeProcessBase "init", OutputPath, "--private-key", - AppPrivateKey.ToString(PrivateKey), + PrivateKeyUtility.ToString(PrivateKey), "--end-point", AppEndPoint.ToString(EndPoint), "--genesis-path", diff --git a/src/console/LibplanetConsole.Console/Repository.cs b/src/console/LibplanetConsole.Console/Repository.cs index f0d869cc..ba53e57a 100644 --- a/src/console/LibplanetConsole.Console/Repository.cs +++ b/src/console/LibplanetConsole.Console/Repository.cs @@ -81,14 +81,14 @@ public static Repository Load(string repositoryPath, RepositoryPathResolver reso NodeOptions LoadNodeOptions(string nodePath) { - var privateKey = AppPrivateKey.Parse(Path.GetFileName(nodePath)); + var privateKey = new PrivateKey(Path.GetFileName(nodePath)); var settingsPath = resolver.GetNodeSettingsPath(nodePath, privateKey); return NodeOptions.Load(settingsPath); } ClientOptions LoadClientOptions(string clientPath) { - var privateKey = AppPrivateKey.Parse(Path.GetFileName(clientPath)); + var privateKey = new PrivateKey(Path.GetFileName(clientPath)); var settingsPath = resolver.GetClientSettingsPath(clientPath, privateKey); return ClientOptions.Load(settingsPath); } @@ -174,7 +174,7 @@ private byte[] CreateDefaultGenesis() { var genesisOptions = new GenesisOptions { - GenesisKey = new AppPrivateKey(), + GenesisKey = new PrivateKey(), Validators = Nodes.Select(item => item.PrivateKey.PublicKey).ToArray(), Timestamp = DateTimeOffset.UtcNow, ActionProviderModulePath = string.Empty, diff --git a/src/console/LibplanetConsole.Console/RepositoryPathResolver.cs b/src/console/LibplanetConsole.Console/RepositoryPathResolver.cs index 3279aa0b..42bd6215 100644 --- a/src/console/LibplanetConsole.Console/RepositoryPathResolver.cs +++ b/src/console/LibplanetConsole.Console/RepositoryPathResolver.cs @@ -19,16 +19,16 @@ public virtual string GetNodesPath(string repositoryPath) public virtual string GetNodeSettingsSchemaPath(string nodesPath) => Path.Combine(nodesPath, "node-settings-schema.json"); - public virtual string GetNodeSettingsPath(string nodePath, AppPrivateKey privateKey) + public virtual string GetNodeSettingsPath(string nodePath, PrivateKey privateKey) => Path.Combine(nodePath, "node-settings.json"); - public virtual string GetNodePath(string nodesPath, AppPrivateKey privateKey) - => Path.Combine(nodesPath, AppPrivateKey.ToString(privateKey)); + public virtual string GetNodePath(string nodesPath, PrivateKey privateKey) + => Path.Combine(nodesPath, PrivateKeyUtility.ToString(privateKey)); - public virtual string GetNodeStorePath(string nodePath, AppPrivateKey privateKey) + public virtual string GetNodeStorePath(string nodePath, PrivateKey privateKey) => Path.Combine(nodePath, "store"); - public virtual string GetNodeLogPath(string nodePath, AppPrivateKey privateKey) + public virtual string GetNodeLogPath(string nodePath, PrivateKey privateKey) => Path.Combine(nodePath, "log"); public virtual string GetClientsPath(string repositoryPath) @@ -37,12 +37,12 @@ public virtual string GetClientsPath(string repositoryPath) public virtual string GetClientSettingsSchemaPath(string clientsPath) => Path.Combine(clientsPath, "client-settings-schema.json"); - public virtual string GetClientSettingsPath(string clientPath, AppPrivateKey privateKey) + public virtual string GetClientSettingsPath(string clientPath, PrivateKey privateKey) => Path.Combine(clientPath, "client-settings.json"); - public virtual string GetClientPath(string clientsPath, AppPrivateKey privateKey) - => Path.Combine(clientsPath, AppPrivateKey.ToString(privateKey)); + public virtual string GetClientPath(string clientsPath, PrivateKey privateKey) + => Path.Combine(clientsPath, PrivateKeyUtility.ToString(privateKey)); - public virtual string GetClientLogPath(string clientPath, AppPrivateKey privateKey) + public virtual string GetClientLogPath(string clientPath, PrivateKey privateKey) => Path.Combine(clientPath, "log"); } diff --git a/src/console/LibplanetConsole.Console/Services/SeedService.cs b/src/console/LibplanetConsole.Console/Services/SeedService.cs index 7f217df3..bd1b6b23 100644 --- a/src/console/LibplanetConsole.Console/Services/SeedService.cs +++ b/src/console/LibplanetConsole.Console/Services/SeedService.cs @@ -14,7 +14,7 @@ internal sealed class SeedService : LocalService, ISeedService, IApplicationService, IAsyncDisposable { private readonly ApplicationBase _application; - private readonly AppPrivateKey _seedNodePrivateKey = new(); + private readonly PrivateKey _seedNodePrivateKey = new(); private readonly SeedNode _blocksyncSeedNode; private readonly SeedNode _consensusSeedNode; diff --git a/src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs b/src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs index 6b543e17..d1742c93 100644 --- a/src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs +++ b/src/node/LibplanetConsole.Node.Delegation/ActionProvider.cs @@ -46,7 +46,7 @@ public IActionLoader GetActionLoader() return new AggregateTypedActionLoader(actionLoaders); } - public IAction[] GetGenesisActions(AppPrivateKey genesisKey, PublicKey[] validatorKeys) + public IAction[] GetGenesisActions(PrivateKey genesisKey, PublicKey[] validatorKeys) { var validators = validatorKeys .Select(item => new Validator((PublicKey)item, BigInteger.One)) diff --git a/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs b/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs index 2e7beed1..aaf013aa 100644 --- a/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs +++ b/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs @@ -16,13 +16,13 @@ internal sealed record class ApplicationSettings [CommandProperty] [CommandSummary("Indicates the EndPoint on which the node will run. " + "If omitted, a random endpoint is used.")] - [AppEndPoint] + [EndPoint] public string EndPoint { get; init; } = string.Empty; [CommandProperty] [CommandSummary("Indicates the private key of the node. " + "If omitted, a random private key is used.")] - [AppPrivateKey] + [PrivateKey] public string PrivateKey { get; init; } = string.Empty; [CommandProperty("parent")] @@ -34,7 +34,7 @@ internal sealed record class ApplicationSettings [CommandProperty] [CommandSummary("Indicates the EndPoint of the seed node to connect to.")] [CommandPropertyExclusion(nameof(IsSingleNode))] - [AppEndPoint] + [EndPoint] public string SeedEndPoint { get; init; } = string.Empty; [CommandProperty] @@ -102,7 +102,7 @@ internal sealed record class ApplicationSettings public ApplicationOptions ToOptions(object[] components) { var endPoint = AppEndPoint.ParseOrNext(EndPoint); - var privateKey = AppPrivateKey.ParseOrRandom(PrivateKey); + var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); var genesis = TryGetGenesis(out var g) == true ? g : CreateGenesis(privateKey); var actionProvider = ModuleLoader.LoadActionLoader( ActionProviderModulePath, ActionProviderType); @@ -132,7 +132,7 @@ static string GetFullPath(string path) } } - private static byte[] CreateGenesis(AppPrivateKey privateKey) + private static byte[] CreateGenesis(PrivateKey privateKey) { var genesisOptions = new GenesisOptions { diff --git a/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs b/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs index edd3ab36..b632f1cf 100644 --- a/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs +++ b/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs @@ -16,7 +16,7 @@ public sealed class GenesisCommand : CommandBase [CommandProperty] [CommandSummary("The private key of the genesis block. " + "if omitted, a random private key is used.")] - [AppPrivateKey] + [PrivateKey] public string GenesisKey { get; set; } = string.Empty; [CommandProperty] @@ -53,8 +53,7 @@ public sealed class GenesisCommand : CommandBase protected override void OnExecute() { - var genesisKey = GenesisKey != string.Empty - ? AppPrivateKey.Parse(GenesisKey) : new AppPrivateKey(); + var genesisKey = PrivateKeyUtility.ParseOrRandom(GenesisKey); var validatorKeys = GetValidators(); var dateTimeOffset = DateTimeOffset == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : DateTimeOffset; @@ -80,7 +79,7 @@ protected override void OnExecute() { GenesisArguments = new { - GenesisKey = AppPrivateKey.ToString(genesisKey), + GenesisKey = PrivateKeyUtility.ToString(genesisKey), Validators = validatorKeys, Timestamp = dateTimeOffset, }, @@ -99,7 +98,7 @@ private PublicKey[] GetValidators() else if (ValidatorCount > 0) { return Enumerable.Range(0, ValidatorCount) - .Select(_ => new AppPrivateKey().PublicKey) + .Select(_ => new PrivateKey().PublicKey) .ToArray(); } else diff --git a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs index 2a5cca1f..f6353b95 100644 --- a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs +++ b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs @@ -25,13 +25,13 @@ public InitializeCommand() [CommandProperty] [CommandSummary("Indicates the private key of the node. " + "If omitted, a random private key is used.")] - [AppPrivateKey] + [PrivateKey] public string PrivateKey { get; init; } = string.Empty; [CommandProperty] [CommandSummary("The endpoint of the node. " + "If omitted, a random endpoint is used.")] - [AppEndPoint] + [EndPoint] public string EndPoint { get; set; } = string.Empty; [CommandProperty] @@ -68,7 +68,7 @@ public InitializeCommand() "if omitted, a random private key is used.\n" + "Requires the '--single-node' option to be set.")] [CommandPropertyDependency(nameof(IsSingleNode))] - [AppPrivateKey] + [PrivateKey] [Category("Genesis")] public string GenesisKey { get; set; } = string.Empty; @@ -103,7 +103,7 @@ protected override void OnExecute() { var outputPath = Path.GetFullPath(RepositoryPath); var endPoint = AppEndPoint.ParseOrNext(EndPoint); - var privateKey = AppPrivateKey.ParseOrRandom(PrivateKey); + var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); var storePath = Path.Combine(outputPath, StorePath.Fallback("store")); var logPath = Path.Combine(outputPath, LogPath.Fallback("app.log")); var libraryLogPath = Path.Combine(outputPath, LibraryLogPath.Fallback("library.log")); @@ -130,7 +130,7 @@ protected override void OnExecute() { var genesisOptions = new GenesisOptions { - GenesisKey = AppPrivateKey.ParseOrRandom(GenesisKey), + GenesisKey = PrivateKeyUtility.ParseOrRandom(GenesisKey), Validators = [privateKey.PublicKey], Timestamp = DateTimeOffset != DateTimeOffset.MinValue ? DateTimeOffset : DateTimeOffset.UtcNow, @@ -144,7 +144,7 @@ protected override void OnExecute() File.WriteAllLines(genesisPath, [genesisString]); info.GenesisArguments = new { - GenesisKey = AppPrivateKey.ToString(genesisOptions.GenesisKey), + GenesisKey = PrivateKeyUtility.ToString(genesisOptions.GenesisKey), Validators = genesisOptions.Validators.Select( item => item.ToHex(compress: false)), genesisOptions.Timestamp, diff --git a/src/node/LibplanetConsole.Node.Executable/Repository.cs b/src/node/LibplanetConsole.Node.Executable/Repository.cs index 49e5daed..d4baf488 100644 --- a/src/node/LibplanetConsole.Node.Executable/Repository.cs +++ b/src/node/LibplanetConsole.Node.Executable/Repository.cs @@ -13,7 +13,7 @@ public sealed record class Repository public required AppEndPoint EndPoint { get; init; } - public required AppPrivateKey PrivateKey { get; init; } + public required PrivateKey PrivateKey { get; init; } public AppEndPoint? SeedEndPoint { get; init; } @@ -48,7 +48,7 @@ public static Repository Load(string settingsPath) return new() { EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), - PrivateKey = AppPrivateKey.Parse(applicationSettings.PrivateKey), + PrivateKey = new PrivateKey(applicationSettings.PrivateKey), StorePath = Path.GetFullPath(applicationSettings.StorePath, directoryName), LogPath = Path.GetFullPath(applicationSettings.LogPath, directoryName), LibraryLogPath = Path.GetFullPath(applicationSettings.LibraryLogPath, directoryName), @@ -95,7 +95,7 @@ public dynamic Save(string repositoryPath) Application = new ApplicationSettings { EndPoint = EndPoint.ToString(), - PrivateKey = AppPrivateKey.ToString(privateKey), + PrivateKey = PrivateKeyUtility.ToString(privateKey), GenesisPath = GetRelativePathFromDirectory(repositoryPath, GenesisPath), StorePath = GetRelativePathFromDirectory(repositoryPath, StorePath), LogPath = GetRelativePathFromDirectory(repositoryPath, LogPath), diff --git a/src/node/LibplanetConsole.Node.Explorer/ExplorerSettings.cs b/src/node/LibplanetConsole.Node.Explorer/ExplorerSettings.cs index 369e4ff0..0d356e50 100644 --- a/src/node/LibplanetConsole.Node.Explorer/ExplorerSettings.cs +++ b/src/node/LibplanetConsole.Node.Explorer/ExplorerSettings.cs @@ -21,7 +21,7 @@ internal sealed class ExplorerSettings [CommandSummary("")] [CommandPropertyDependency(nameof(IsExplorerEnabled))] [JsonPropertyName("endPoint")] - [AppEndPoint] + [EndPoint] [Category(Explorer)] public string ExplorerEndPoint { get; init; } = string.Empty; } diff --git a/src/node/LibplanetConsole.Node/ActionProvider.cs b/src/node/LibplanetConsole.Node/ActionProvider.cs index 75fc8df4..d060a667 100644 --- a/src/node/LibplanetConsole.Node/ActionProvider.cs +++ b/src/node/LibplanetConsole.Node/ActionProvider.cs @@ -24,7 +24,7 @@ internal sealed class ActionProvider : IActionProvider public ImmutableArray EndTxActions { get; } = []; - public IAction[] GetGenesisActions(AppPrivateKey genesisKey, PublicKey[] validatorKeys) + public IAction[] GetGenesisActions(PrivateKey genesisKey, PublicKey[] validatorKeys) { var validators = validatorKeys .Select(item => new Validator(item, BigInteger.One)) diff --git a/src/node/LibplanetConsole.Node/ApplicationOptions.cs b/src/node/LibplanetConsole.Node/ApplicationOptions.cs index c475d541..df52d8df 100644 --- a/src/node/LibplanetConsole.Node/ApplicationOptions.cs +++ b/src/node/LibplanetConsole.Node/ApplicationOptions.cs @@ -4,7 +4,7 @@ namespace LibplanetConsole.Node; public sealed record class ApplicationOptions { - public ApplicationOptions(AppEndPoint endPoint, AppPrivateKey privateKey, byte[] genesis) + public ApplicationOptions(AppEndPoint endPoint, PrivateKey privateKey, byte[] genesis) { EndPoint = endPoint; PrivateKey = privateKey; @@ -13,7 +13,7 @@ public ApplicationOptions(AppEndPoint endPoint, AppPrivateKey privateKey, byte[] public AppEndPoint EndPoint { get; } - public AppPrivateKey PrivateKey { get; } + public PrivateKey PrivateKey { get; } public byte[] Genesis { get; } diff --git a/src/node/LibplanetConsole.Node/BlockUtility.cs b/src/node/LibplanetConsole.Node/BlockUtility.cs index 76d36675..99a17948 100644 --- a/src/node/LibplanetConsole.Node/BlockUtility.cs +++ b/src/node/LibplanetConsole.Node/BlockUtility.cs @@ -33,7 +33,7 @@ public static Block CreateGenesisBlock( } private static Block CreateGenesisBlock( - AppPrivateKey genesisKey, + PrivateKey genesisKey, DateTimeOffset dateTimeOffset, IAction[] actions) { diff --git a/src/node/LibplanetConsole.Node/IActionProvider.cs b/src/node/LibplanetConsole.Node/IActionProvider.cs index a16cc61f..c827dcfb 100644 --- a/src/node/LibplanetConsole.Node/IActionProvider.cs +++ b/src/node/LibplanetConsole.Node/IActionProvider.cs @@ -15,7 +15,7 @@ public interface IActionProvider ImmutableArray EndTxActions { get; } - IAction[] GetGenesisActions(AppPrivateKey genesisKey, PublicKey[] validatorKeys); + IAction[] GetGenesisActions(PrivateKey genesisKey, PublicKey[] validatorKeys); IActionLoader GetActionLoader(); } diff --git a/src/node/LibplanetConsole.Node/Node.BlockChain.cs b/src/node/LibplanetConsole.Node/Node.BlockChain.cs index 07b9ff4a..23d7abf9 100644 --- a/src/node/LibplanetConsole.Node/Node.BlockChain.cs +++ b/src/node/LibplanetConsole.Node/Node.BlockChain.cs @@ -24,7 +24,7 @@ public async Task AddTransactionAsync( condition: IsRunning != true, message: "Node is not running."); - var privateKey = AppPrivateKey.FromSecureString(_privateKey); + var privateKey = PrivateKeyUtility.FromSecureString(_privateKey); var blockChain = BlockChain; var genesisBlock = blockChain.Genesis; var nonce = blockChain.GetNextTxNonce(privateKey.Address); diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index 907b6177..809bfde5 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -139,7 +139,7 @@ public AppEndPoint SeedEndPoint public bool Verify(object obj, byte[] signature) => PublicKey.Verify(obj, signature); - public byte[] Sign(object obj) => AppPrivateKey.FromSecureString(_privateKey).Sign(obj); + public byte[] Sign(object obj) => PrivateKeyUtility.FromSecureString(_privateKey).Sign(obj); public async Task StartAsync(CancellationToken cancellationToken) { @@ -152,7 +152,7 @@ public async Task StartAsync(CancellationToken cancellationToken) } var seedInfo = await GetSeedInfoAsync(_seedEndPoint, cancellationToken); - var privateKey = (PrivateKey)AppPrivateKey.FromSecureString(_privateKey); + var privateKey = PrivateKeyUtility.FromSecureString(_privateKey); var appProtocolVersion = _appProtocolVersion; var storePath = _storePath; var blocksyncEndPoint = _blocksyncEndPoint ?? AppEndPoint.Next(); @@ -307,7 +307,7 @@ private static async Task GetSeedInfoAsync( }; var closeToken = await remoteServiceContext.OpenAsync(cancellationToken); var service = remoteService.Service; - var privateKey = new AppPrivateKey(); + var privateKey = new PrivateKey(); var publicKey = privateKey.PublicKey; try { diff --git a/src/node/LibplanetConsole.Node/Services/SeedService.cs b/src/node/LibplanetConsole.Node/Services/SeedService.cs index ac1630ce..c36b6f34 100644 --- a/src/node/LibplanetConsole.Node/Services/SeedService.cs +++ b/src/node/LibplanetConsole.Node/Services/SeedService.cs @@ -12,7 +12,7 @@ namespace LibplanetConsole.Node.Services; internal sealed class SeedService(ApplicationBase application) : LocalService, ISeedService, IApplicationService, IAsyncDisposable { - private readonly AppPrivateKey _seedNodePrivateKey = new(); + private readonly PrivateKey _seedNodePrivateKey = new(); private SeedNode? _blocksyncSeedNode; private SeedNode? _consensusSeedNode; diff --git a/src/shared/LibplanetConsole.Node/GenesisOptions.cs b/src/shared/LibplanetConsole.Node/GenesisOptions.cs index 5b4377af..722f1169 100644 --- a/src/shared/LibplanetConsole.Node/GenesisOptions.cs +++ b/src/shared/LibplanetConsole.Node/GenesisOptions.cs @@ -2,7 +2,7 @@ namespace LibplanetConsole.Common; public sealed record class GenesisOptions { - public AppPrivateKey GenesisKey { get; init; } = new(); + public PrivateKey GenesisKey { get; init; } = new(); public PublicKey[] Validators { get; init; } = []; diff --git a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs b/test/LibplanetConsole.Common.Tests/AppPeerTest.cs index b0d4887a..bf8909f7 100644 --- a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs +++ b/test/LibplanetConsole.Common.Tests/AppPeerTest.cs @@ -5,7 +5,7 @@ // [Fact] // public void Test1() // { -// var publicKey = new AppPrivateKey().PublicKey; +// var publicKey = new PrivateKey().PublicKey; // var endPoint = new AppEndPoint("localhost", 12345); // var peer = new AppPeer(publicKey, endPoint); // Assert.Equal(publicKey, peer.PublicKey); From 85b1f6d4ea4aa6c76c8461eba85a7e38f81491e5 Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 19:02:49 +0900 Subject: [PATCH 7/9] refactor: Remove AppEndPoint --- GlobalUsings.props | 1 + .../ApplicationSettings.cs | 4 +- .../EntryCommands/InitializeCommand.cs | 2 +- .../Repository.cs | 13 +- .../ApplicationBase.cs | 2 +- .../ApplicationInfo.cs | 4 +- .../ApplicationOptions.cs | 6 +- .../Client.BlockChain.cs | 4 +- src/client/LibplanetConsole.Client/Client.cs | 5 +- .../Commands/StartCommand.cs | 2 +- src/client/LibplanetConsole.Client/IClient.cs | 2 +- .../Services/ClientService.cs | 2 +- .../LibplanetConsole.Common/AppEndPoint.cs | 214 +++++++++--------- src/common/LibplanetConsole.Common/AppPeer.cs | 8 +- .../Converters/AppEndPointJsonConverter.cs | 13 +- .../DataAnnotations/AppPeerAttribute.cs | 2 +- .../DataAnnotations/EndPointAttribute.cs | 11 +- .../EndPointUtility.cs | 95 ++++++++ .../Services/LocalServiceContext.cs | 6 +- .../Services/RemoteServiceContext.cs | 6 +- .../LibplanetConsole.Seed/BoundPeerUtility.cs | 2 +- src/common/LibplanetConsole.Seed/SeedNode.cs | 9 +- .../LibplanetConsole.Seed/SeedOptions.cs | 5 +- .../ApplicationSettings.cs | 12 +- .../EntryCommands/InitializeCommand.cs | 13 +- .../Commands/ExplorerCommand.cs | 2 +- .../ExplorerNodeContent.cs | 4 +- .../IExplorerNodeContent.cs | 2 +- .../ApplicationInfo.cs | 2 +- .../ApplicationOptions.cs | 4 +- .../LibplanetConsole.Console/Client.cs | 3 +- .../LibplanetConsole.Console/ClientOptions.cs | 8 +- .../ClientRepositoryProcess.cs | 4 +- .../Commands/ClientCommand.cs | 2 +- .../Commands/NodeCommand.cs | 2 +- .../LibplanetConsole.Console/IClient.cs | 2 +- src/console/LibplanetConsole.Console/INode.cs | 2 +- .../Node.BlockChain.cs | 4 +- src/console/LibplanetConsole.Console/Node.cs | 16 +- .../LibplanetConsole.Console/NodeOptions.cs | 9 +- .../NodeRepositoryProcess.cs | 4 +- .../LibplanetConsole.Console/Repository.cs | 6 +- .../Services/SeedService.cs | 4 +- .../ApplicationSettings.cs | 6 +- .../EntryCommands/InitializeCommand.cs | 2 +- .../Repository.cs | 12 +- .../Commands/ExplorerCommand.cs | 2 +- .../ExplorerNode.cs | 6 +- .../LibplanetConsole.Node/ApplicationBase.cs | 2 +- .../LibplanetConsole.Node/ApplicationInfo.cs | 4 +- .../ApplicationOptions.cs | 6 +- .../LibplanetConsole.Node/BlockUtility.cs | 4 +- .../LibplanetConsole.Node/Node.BlockChain.cs | 2 +- src/node/LibplanetConsole.Node/Node.cs | 29 +-- src/node/LibplanetConsole.Node/PeerUtility.cs | 2 +- .../Services/NodeService.cs | 2 +- .../Services/SeedService.cs | 4 +- .../LibplanetConsole.Explorer/ExplorerInfo.cs | 2 +- .../ExplorerOptions.cs | 2 +- .../AppPeerTest.cs | 2 +- 60 files changed, 360 insertions(+), 252 deletions(-) create mode 100644 src/common/LibplanetConsole.Common/EndPointUtility.cs diff --git a/GlobalUsings.props b/GlobalUsings.props index bbd502e5..a7a288d9 100644 --- a/GlobalUsings.props +++ b/GlobalUsings.props @@ -9,6 +9,7 @@ + diff --git a/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs b/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs index 0717e43e..e2433e79 100644 --- a/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs +++ b/src/client/LibplanetConsole.Client.Executable/ApplicationSettings.cs @@ -47,12 +47,12 @@ internal sealed record class ApplicationSettings public ApplicationOptions ToOptions(object[] components) { - var endPoint = AppEndPoint.ParseOrNext(EndPoint); + var endPoint = EndPointUtility.ParseOrNext(EndPoint); var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); return new ApplicationOptions(endPoint, privateKey) { ParentProcessId = ParentProcessId, - NodeEndPoint = AppEndPoint.ParseOrDefault(NodeEndPoint), + NodeEndPoint = EndPointUtility.ParseOrDefault(NodeEndPoint), LogPath = GetFullPath(LogPath), NoREPL = NoREPL, Components = components, diff --git a/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs b/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs index 7a678cda..469a0f5c 100644 --- a/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs +++ b/src/client/LibplanetConsole.Client.Executable/EntryCommands/InitializeCommand.cs @@ -45,7 +45,7 @@ public InitializeCommand() protected override void OnExecute() { var outputPath = Path.GetFullPath(OutputPath); - var endPoint = AppEndPoint.ParseOrNext(EndPoint); + var endPoint = EndPointUtility.ParseOrNext(EndPoint); var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); var logPath = Path.Combine(outputPath, LogPath.Fallback("app.log")); var repository = new Repository diff --git a/src/client/LibplanetConsole.Client.Executable/Repository.cs b/src/client/LibplanetConsole.Client.Executable/Repository.cs index ca5ad287..623f166b 100644 --- a/src/client/LibplanetConsole.Client.Executable/Repository.cs +++ b/src/client/LibplanetConsole.Client.Executable/Repository.cs @@ -1,4 +1,5 @@ using System.Dynamic; +using System.Net; using System.Text.Json.Serialization; using LibplanetConsole.Common; using LibplanetConsole.Framework; @@ -11,11 +12,11 @@ public sealed record class Repository public const string SettingsFileName = "client-settings.json"; public const string SettingsSchemaFileName = "client-settings-schema.json"; - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public required PrivateKey PrivateKey { get; init; } - public AppEndPoint? NodeEndPoint { get; init; } + public EndPoint? NodeEndPoint { get; init; } public string LogPath { get; init; } = string.Empty; @@ -37,11 +38,11 @@ public static Repository Load(string settingsPath) return new() { - EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), + EndPoint = EndPointUtility.Parse(applicationSettings.EndPoint), PrivateKey = new PrivateKey(applicationSettings.PrivateKey), LogPath = Path.GetFullPath(applicationSettings.LogPath, directoryName), Source = settingsPath, - NodeEndPoint = AppEndPoint.ParseOrDefault(applicationSettings.NodeEndPoint), + NodeEndPoint = EndPointUtility.ParseOrDefault(applicationSettings.NodeEndPoint), }; } @@ -80,10 +81,10 @@ public dynamic Save(string repositoryPath) Schema = SettingsSchemaFileName, Application = new ApplicationSettings { - EndPoint = EndPoint.ToString(), + EndPoint = EndPointUtility.ToString(EndPoint), PrivateKey = PrivateKeyUtility.ToString(privateKey), LogPath = GetRelativePathFromDirectory(repositoryPath, LogPath), - NodeEndPoint = AppEndPoint.ToString(NodeEndPoint), + NodeEndPoint = EndPointUtility.ToString(NodeEndPoint), }, }; diff --git a/src/client/LibplanetConsole.Client/ApplicationBase.cs b/src/client/LibplanetConsole.Client/ApplicationBase.cs index c65e21d9..6b03f461 100644 --- a/src/client/LibplanetConsole.Client/ApplicationBase.cs +++ b/src/client/LibplanetConsole.Client/ApplicationBase.cs @@ -57,7 +57,7 @@ protected ApplicationBase(ApplicationOptions options) public override ApplicationServiceCollection ApplicationServices { get; } - public AppEndPoint EndPoint => _clientServiceContext.EndPoint; + public EndPoint EndPoint => _clientServiceContext.EndPoint; public ApplicationInfo Info => _info; diff --git a/src/client/LibplanetConsole.Client/ApplicationInfo.cs b/src/client/LibplanetConsole.Client/ApplicationInfo.cs index 21870422..d799f968 100644 --- a/src/client/LibplanetConsole.Client/ApplicationInfo.cs +++ b/src/client/LibplanetConsole.Client/ApplicationInfo.cs @@ -4,9 +4,9 @@ namespace LibplanetConsole.Client; public readonly record struct ApplicationInfo { - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } - public AppEndPoint? NodeEndPoint { get; init; } + public EndPoint? NodeEndPoint { get; init; } public required string LogPath { get; init; } } diff --git a/src/client/LibplanetConsole.Client/ApplicationOptions.cs b/src/client/LibplanetConsole.Client/ApplicationOptions.cs index 8feeabbf..817d8060 100644 --- a/src/client/LibplanetConsole.Client/ApplicationOptions.cs +++ b/src/client/LibplanetConsole.Client/ApplicationOptions.cs @@ -4,19 +4,19 @@ namespace LibplanetConsole.Client; public sealed record class ApplicationOptions { - public ApplicationOptions(AppEndPoint endPoint, PrivateKey privateKey) + public ApplicationOptions(EndPoint endPoint, PrivateKey privateKey) { EndPoint = endPoint; PrivateKey = privateKey; } - public AppEndPoint EndPoint { get; } + public EndPoint EndPoint { get; } public PrivateKey PrivateKey { get; } public int ParentProcessId { get; init; } - public AppEndPoint? NodeEndPoint { get; init; } + public EndPoint? NodeEndPoint { get; init; } public string LogPath { get; init; } = string.Empty; diff --git a/src/client/LibplanetConsole.Client/Client.BlockChain.cs b/src/client/LibplanetConsole.Client/Client.BlockChain.cs index 6a296e0c..75a7e9ae 100644 --- a/src/client/LibplanetConsole.Client/Client.BlockChain.cs +++ b/src/client/LibplanetConsole.Client/Client.BlockChain.cs @@ -23,8 +23,8 @@ public async Task SendTransactionAsync( var genesisHash = NodeInfo.GenesisHash; var tx = Transaction.Create( nonce: nonce, - privateKey: (PrivateKey)privateKey, - genesisHash: (BlockHash)genesisHash, + privateKey: privateKey, + genesisHash: genesisHash, actions: [.. actions.Select(item => item.PlainValue)]); var txData = tx.Serialize(); _logger.Debug("Client sends a transaction: {TxId}", tx.Id); diff --git a/src/client/LibplanetConsole.Client/Client.cs b/src/client/LibplanetConsole.Client/Client.cs index ea16da57..a2b40e44 100644 --- a/src/client/LibplanetConsole.Client/Client.cs +++ b/src/client/LibplanetConsole.Client/Client.cs @@ -1,3 +1,4 @@ +using System.Net; using System.Security; using Libplanet.Crypto; using LibplanetConsole.Client.Services; @@ -15,7 +16,7 @@ internal sealed partial class Client : IClient, INodeCallback, IBlockChainCallba private readonly ApplicationBase _application; private readonly SecureString _privateKey; private readonly ILogger _logger; - private AppEndPoint? _nodeEndPoint; + private EndPoint? _nodeEndPoint; private RemoteNodeContext? _remoteNodeContext; private Guid _closeToken; private ClientInfo _info; @@ -48,7 +49,7 @@ public Client(ApplicationBase application, ApplicationOptions options) public NodeInfo NodeInfo { get; private set; } - public AppEndPoint NodeEndPoint + public EndPoint NodeEndPoint { get => _nodeEndPoint ?? throw new InvalidOperationException($"{nameof(NodeEndPoint)} is not initialized."); diff --git a/src/client/LibplanetConsole.Client/Commands/StartCommand.cs b/src/client/LibplanetConsole.Client/Commands/StartCommand.cs index 51efb853..529d1b06 100644 --- a/src/client/LibplanetConsole.Client/Commands/StartCommand.cs +++ b/src/client/LibplanetConsole.Client/Commands/StartCommand.cs @@ -17,7 +17,7 @@ internal sealed class StartCommand(Client client) : CommandAsyncBase protected override async Task OnExecuteAsync(CancellationToken cancellationToken) { - var nodeEndPoint = AppEndPoint.ParseOrFallback(NodeEndPoint, client.NodeEndPoint); + var nodeEndPoint = EndPointUtility.ParseOrFallback(NodeEndPoint, client.NodeEndPoint); client.NodeEndPoint = nodeEndPoint; await client.StartAsync(cancellationToken); } diff --git a/src/client/LibplanetConsole.Client/IClient.cs b/src/client/LibplanetConsole.Client/IClient.cs index b74160a0..0a69e897 100644 --- a/src/client/LibplanetConsole.Client/IClient.cs +++ b/src/client/LibplanetConsole.Client/IClient.cs @@ -21,7 +21,7 @@ public interface IClient : IVerifier Address Address { get; } - AppEndPoint NodeEndPoint { get; set; } + EndPoint NodeEndPoint { get; set; } Task StartAsync(CancellationToken cancellationToken); diff --git a/src/client/LibplanetConsole.Client/Services/ClientService.cs b/src/client/LibplanetConsole.Client/Services/ClientService.cs index 7d521ee7..0c693385 100644 --- a/src/client/LibplanetConsole.Client/Services/ClientService.cs +++ b/src/client/LibplanetConsole.Client/Services/ClientService.cs @@ -28,7 +28,7 @@ public async Task GetInfoAsync(CancellationToken cancellationToken) public async Task StartAsync( string nodeEndPoint, CancellationToken cancellationToken) { - _client.NodeEndPoint = AppEndPoint.Parse(nodeEndPoint); + _client.NodeEndPoint = EndPointUtility.Parse(nodeEndPoint); await _client.StartAsync(cancellationToken); return _client.Info; } diff --git a/src/common/LibplanetConsole.Common/AppEndPoint.cs b/src/common/LibplanetConsole.Common/AppEndPoint.cs index 1979d322..5b43abd9 100644 --- a/src/common/LibplanetConsole.Common/AppEndPoint.cs +++ b/src/common/LibplanetConsole.Common/AppEndPoint.cs @@ -1,107 +1,107 @@ -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Sockets; -using System.Text.Json.Serialization; -using LibplanetConsole.Common.Converters; -using CommunicationUtility = JSSoft.Communication.EndPointUtility; - -namespace LibplanetConsole.Common; - -[JsonConverter(typeof(AppEndPointJsonConverter))] -public sealed record class AppEndPoint -{ - public const string HostExpression - = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; - - public const string PortExpression = @"\d{1,5}"; - public static readonly string RegularExpression - = $"{HostExpression}:{PortExpression}"; - - private static readonly object LockObject = new(); - private static readonly List PortList = []; - - public AppEndPoint(string host, int port) - { - Host = host; - Port = port; - } - - public string Host { get; } - - public int Port { get; } - - public static explicit operator EndPoint(AppEndPoint endPoint) - => new DnsEndPoint(endPoint.Host, endPoint.Port); - - public static explicit operator DnsEndPoint(AppEndPoint endPoint) - => new(endPoint.Host, endPoint.Port); - - public static explicit operator AppEndPoint(EndPoint endPoint) - { - if (endPoint is DnsEndPoint dnsEndPoint) - { - return new(dnsEndPoint.Host, dnsEndPoint.Port); - } - - if (endPoint is IPEndPoint ipEndPoint) - { - return new($"{ipEndPoint.Address}", ipEndPoint.Port); - } - - throw new InvalidCastException(); - } - - public static AppEndPoint Next() => new("localhost", GetPort()); - - public static AppEndPoint Parse(string text) => (AppEndPoint)CommunicationUtility.Parse(text); - - public static AppEndPoint ParseOrNext(string text) - => text == string.Empty ? Next() : Parse(text); - - public static AppEndPoint ParseOrFallback(string text, AppEndPoint fallback) - => text == string.Empty ? fallback : Parse(text); - - public static AppEndPoint? ParseOrDefault(string text) - => text == string.Empty ? null : Parse(text); - - public static bool TryParse(string text, [MaybeNullWhen(false)] out AppEndPoint endPoint) - { - if (CommunicationUtility.TryParse(text, out var value)) - { - endPoint = (AppEndPoint)value; - return true; - } - - endPoint = null; - return false; - } - - public static string ToString(AppEndPoint? endPoint) - => endPoint is not null ? endPoint.ToString() : string.Empty; - - public override string ToString() => $"{Host}:{Port}"; - - private static int GetPort() - { - lock (LockObject) - { - var port = GetRandomPort(); - while (PortList.Contains(port) == true) - { - port = GetRandomPort(); - } - - PortList.Add(port); - return port; - } - } - - private static int GetRandomPort() - { - var listener = new TcpListener(IPAddress.Loopback, 0); - listener.Start(); - var port = ((IPEndPoint)listener.LocalEndpoint).Port; - listener.Stop(); - return port; - } -} +// using System.Diagnostics.CodeAnalysis; +// using System.Net; +// using System.Net.Sockets; +// using System.Text.Json.Serialization; +// using LibplanetConsole.Common.Converters; +// using CommunicationUtility = JSSoft.Communication.EndPointUtility; + +// namespace LibplanetConsole.Common; + +// [JsonConverter(typeof(EndPointJsonConverter))] +// public sealed record class EndPoint +// { +// public const string HostExpression +// = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; + +// public const string PortExpression = @"\d{1,5}"; +// public static readonly string RegularExpression +// = $"{HostExpression}:{PortExpression}"; + +// private static readonly object LockObject = new(); +// private static readonly List PortList = []; + +// public EndPoint(string host, int port) +// { +// Host = host; +// Port = port; +// } + +// public string Host { get; } + +// public int Port { get; } + +// public static explicit operator EndPoint(EndPoint endPoint) +// => new DnsEndPoint(endPoint.Host, endPoint.Port); + +// public static explicit operator DnsEndPoint(EndPoint endPoint) +// => new(endPoint.Host, endPoint.Port); + +// public static explicit operator EndPoint(EndPoint endPoint) +// { +// if (endPoint is DnsEndPoint dnsEndPoint) +// { +// return new(dnsEndPoint.Host, dnsEndPoint.Port); +// } + +// if (endPoint is IPEndPoint ipEndPoint) +// { +// return new($"{ipEndPoint.Address}", ipEndPoint.Port); +// } + +// throw new InvalidCastException(); +// } + +// public static EndPoint Next() => new("localhost", GetPort()); + +// public static EndPoint Parse(string text) => (EndPoint)CommunicationUtility.Parse(text); + +// public static EndPoint ParseOrNext(string text) +// => text == string.Empty ? Next() : Parse(text); + +// public static EndPoint ParseOrFallback(string text, EndPoint fallback) +// => text == string.Empty ? fallback : Parse(text); + +// public static EndPoint? ParseOrDefault(string text) +// => text == string.Empty ? null : Parse(text); + +// public static bool TryParse(string text, [MaybeNullWhen(false)] out EndPoint endPoint) +// { +// if (CommunicationUtility.TryParse(text, out var value)) +// { +// endPoint = (EndPoint)value; +// return true; +// } + +// endPoint = null; +// return false; +// } + +// public static string ToString(EndPoint? endPoint) +// => endPoint is not null ? endPoint.ToString() : string.Empty; + +// public override string ToString() => $"{Host}:{Port}"; + +// private static int GetPort() +// { +// lock (LockObject) +// { +// var port = GetRandomPort(); +// while (PortList.Contains(port) == true) +// { +// port = GetRandomPort(); +// } + +// PortList.Add(port); +// return port; +// } +// } + +// private static int GetRandomPort() +// { +// var listener = new TcpListener(IPAddress.Loopback, 0); +// listener.Start(); +// var port = ((IPEndPoint)listener.LocalEndpoint).Port; +// listener.Stop(); +// return port; +// } +// } diff --git a/src/common/LibplanetConsole.Common/AppPeer.cs b/src/common/LibplanetConsole.Common/AppPeer.cs index 37a93b9f..8695e19c 100644 --- a/src/common/LibplanetConsole.Common/AppPeer.cs +++ b/src/common/LibplanetConsole.Common/AppPeer.cs @@ -6,18 +6,18 @@ // namespace LibplanetConsole.Common; // [JsonConverter(typeof(AppPeerJsonConverter))] -// public readonly struct AppPeer(PublicKey publicKey, AppEndPoint endPoint) +// public readonly struct AppPeer(PublicKey publicKey, EndPoint endPoint) // { // public const string HostExpression // = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; // public const string PortExpression = @"\d{1,5}"; // public static readonly string RegularExpression -// = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; +// = $"^{PublicKeyAttribute.RegularExpression},{EndPoint.RegularExpression}$"; // public PublicKey PublicKey { get; } = publicKey; -// public AppEndPoint EndPoint { get; } = endPoint; +// public EndPoint EndPoint { get; } = endPoint; // public Address Address => PublicKey.Address; @@ -30,7 +30,7 @@ // if (items.Length == 2) // { // var publicKey = PublicKey.FromHex(items[0]); -// var endPoint = AppEndPoint.Parse(items[1].Trim()); +// var endPoint = EndPointUtility.Parse(items[1].Trim()); // return new AppPeer(publicKey, endPoint); // } diff --git a/src/common/LibplanetConsole.Common/Converters/AppEndPointJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppEndPointJsonConverter.cs index 861a0cbd..c2dcca22 100644 --- a/src/common/LibplanetConsole.Common/Converters/AppEndPointJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/AppEndPointJsonConverter.cs @@ -3,24 +3,25 @@ namespace LibplanetConsole.Common.Converters; -public sealed class AppEndPointJsonConverter : JsonConverter +public sealed class EndPointJsonConverter : JsonConverter { - public override AppEndPoint? Read( + public override EndPoint? Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.GetString() is string text) { - return AppEndPoint.Parse(text); + return EndPointUtility.Parse(text); } - throw new JsonException("Cannot read AppEndPoint from JSON."); + throw new JsonException("Cannot read EndPoint from JSON."); } public override void Write( - Utf8JsonWriter writer, AppEndPoint value, JsonSerializerOptions options) + Utf8JsonWriter writer, EndPoint value, JsonSerializerOptions options) { - writer.WriteStringValue(value.ToString()); + var text = EndPointUtility.ToString(value); + writer.WriteStringValue(text); } } diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs index 29808200..bcf0d542 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs @@ -12,7 +12,7 @@ // public const string PortExpression = @"\d{1,5}"; // public static readonly string RegularExpression -// = $"^{PublicKeyAttribute.RegularExpression},{AppEndPoint.RegularExpression}$"; +// = $"^{PublicKeyAttribute.RegularExpression},{EndPoint.RegularExpression}$"; // public AppPeerAttribute() // : base($"^{RegularExpression}$") diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/EndPointAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/EndPointAttribute.cs index 7fe791cb..15a5b58f 100644 --- a/src/common/LibplanetConsole.Common/DataAnnotations/EndPointAttribute.cs +++ b/src/common/LibplanetConsole.Common/DataAnnotations/EndPointAttribute.cs @@ -7,13 +7,20 @@ namespace LibplanetConsole.Common.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] public sealed class EndPointAttribute : RegularExpressionAttribute { + public const string HostExpression + = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; + + public const string PortExpression = @"\d{1,5}"; + public static readonly string RegularExpression + = $"{HostExpression}:{PortExpression}"; + public EndPointAttribute() - : base($"^{AppEndPoint.RegularExpression}$") + : base($"^{RegularExpression}$") { } } [AttributeUsage(AttributeTargets.Property)] -public sealed class AppEndPointArrayAttribute : ArrayAttribute +public sealed class EndPointArrayAttribute : ArrayAttribute { } diff --git a/src/common/LibplanetConsole.Common/EndPointUtility.cs b/src/common/LibplanetConsole.Common/EndPointUtility.cs new file mode 100644 index 00000000..cdc2b5c4 --- /dev/null +++ b/src/common/LibplanetConsole.Common/EndPointUtility.cs @@ -0,0 +1,95 @@ +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Sockets; +using System.Security; +using System.Text; +using System.Text.Json; +using Bencodex; +using Bencodex.Types; +using Libplanet.Crypto; +using Microsoft.AspNetCore.Http; +using CommunicationUtility = JSSoft.Communication.EndPointUtility; + +namespace LibplanetConsole.Common; + +public static class EndPointUtility +{ + private static readonly object LockObject = new(); + private static readonly List PortList = []; + + public static EndPoint Next() => new DnsEndPoint("localhost", GetPort()); + + public static EndPoint Parse(string text) => CommunicationUtility.Parse(text); + + public static EndPoint ParseOrNext(string text) + => text == string.Empty ? Next() : Parse(text); + + public static EndPoint ParseOrFallback(string text, EndPoint fallback) + => text == string.Empty ? fallback : Parse(text); + + public static EndPoint? ParseOrDefault(string text) + => text == string.Empty ? null : Parse(text); + + public static bool TryParse(string text, [MaybeNullWhen(false)] out EndPoint endPoint) + { + if (CommunicationUtility.TryParse(text, out var value)) + { + endPoint = value; + return true; + } + + endPoint = null; + return false; + } + + public static (string Host, int Port) GetHostAndPort(EndPoint endPoint) + { + return endPoint switch + { + DnsEndPoint dnsEndPoint => (dnsEndPoint.Host, dnsEndPoint.Port), + IPEndPoint ipEndPoint => (ipEndPoint.Address.ToString(), ipEndPoint.Port), + _ => throw new NotSupportedException($"Unsupported EndPoint type: {endPoint}."), + }; + } + + // public static string ToString(EndPoint? endPoint) + // => endPoint is not null ? endPoint.ToString() : string.Empty; + + public static string ToString(EndPoint? endPoint) + { + if (endPoint is DnsEndPoint dnsEndPoint) + { + return $"{dnsEndPoint.Host}:{dnsEndPoint.Port}"; + } + else if (endPoint is IPEndPoint ipEndPoint) + { + return $"{ipEndPoint.Address}:{ipEndPoint.Port}"; + } + + return endPoint?.ToString() ?? string.Empty; + } + + private static int GetPort() + { + lock (LockObject) + { + var port = GetRandomPort(); + while (PortList.Contains(port) == true) + { + port = GetRandomPort(); + } + + PortList.Add(port); + return port; + } + } + + private static int GetRandomPort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } +} diff --git a/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs b/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs index 09a65dd3..cabf5226 100644 --- a/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs +++ b/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs @@ -6,7 +6,7 @@ namespace LibplanetConsole.Common.Services; public class LocalServiceContext { private readonly InternalServerContext _serverContext; - private AppEndPoint? _endPoint; + private EndPoint? _endPoint; public LocalServiceContext(IEnumerable localServices) { @@ -24,13 +24,13 @@ public LocalServiceContext(IEnumerable localServices) public event EventHandler? Stopped; - public AppEndPoint EndPoint + public EndPoint EndPoint { get => _endPoint ?? throw new InvalidOperationException("EndPoint is not set."); set { _endPoint = value; - _serverContext.EndPoint = (EndPoint)value; + _serverContext.EndPoint = value; } } diff --git a/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs b/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs index b892e11d..b0f26479 100644 --- a/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs +++ b/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs @@ -6,7 +6,7 @@ namespace LibplanetConsole.Common.Services; public class RemoteServiceContext { private readonly InternalClientContext _clientContext; - private AppEndPoint? _endPoint; + private EndPoint? _endPoint; public RemoteServiceContext(IEnumerable remoteServices) { @@ -19,13 +19,13 @@ public RemoteServiceContext(IEnumerable remoteServices) public event EventHandler? Closed; - public AppEndPoint EndPoint + public EndPoint EndPoint { get => _endPoint ?? throw new InvalidOperationException("EndPoint is not set."); set { _endPoint = value; - _clientContext.EndPoint = (EndPoint)value; + _clientContext.EndPoint = value; } } diff --git a/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs b/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs index 09b322df..14be462b 100644 --- a/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs +++ b/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs @@ -18,7 +18,7 @@ public static BoundPeer Parse(string text) if (items.Length == 2) { var publicKey = PublicKey.FromHex(items[0]); - var endPoint = (DnsEndPoint)AppEndPoint.Parse(items[1].Trim()); + var endPoint = (DnsEndPoint)EndPointUtility.Parse(items[1].Trim()); return new BoundPeer(publicKey, endPoint); } diff --git a/src/common/LibplanetConsole.Seed/SeedNode.cs b/src/common/LibplanetConsole.Seed/SeedNode.cs index 0a88100e..fd457e22 100644 --- a/src/common/LibplanetConsole.Seed/SeedNode.cs +++ b/src/common/LibplanetConsole.Seed/SeedNode.cs @@ -25,7 +25,7 @@ public static readonly PrivateKey AppProtocolKey = new("2a15e7deaac09ce631e1faa184efadb175b6b90989cf1faed9dfc321ad1db5ac"); public static readonly AppProtocolVersion AppProtocolVersion - = AppProtocolVersion.Sign((PrivateKey)AppProtocolKey, 1); + = AppProtocolVersion.Sign(AppProtocolKey, 1); private readonly ILogger _logger = Log.ForContext(); @@ -40,7 +40,7 @@ public static readonly AppProtocolVersion AppProtocolVersion public PeerCollection Peers { get; } = new(seedOptions); - public BoundPeer BoundPeer => new( + public BoundPeer BoundPeer { get; } = new( seedOptions.PrivateKey.PublicKey, (DnsEndPoint)seedOptions.EndPoint); public async Task StartAsync(CancellationToken cancellationToken) @@ -111,15 +111,14 @@ public async ValueTask DisposeAsync() private static async Task CreateTransport(SeedOptions seedOptions) { - var privateKey = (PrivateKey)seedOptions.PrivateKey; + var privateKey = seedOptions.PrivateKey; var appProtocolVersion = AppProtocolVersion; var appProtocolVersionOptions = new AppProtocolVersionOptions { AppProtocolVersion = appProtocolVersion, TrustedAppProtocolVersionSigners = [], }; - var host = seedOptions.EndPoint.Host; - var port = seedOptions.EndPoint.Port; + var (host, port) = EndPointUtility.GetHostAndPort(seedOptions.EndPoint); var hostOptions = new HostOptions(host, [], port); return await NetMQTransport.Create(privateKey, appProtocolVersionOptions, hostOptions); } diff --git a/src/common/LibplanetConsole.Seed/SeedOptions.cs b/src/common/LibplanetConsole.Seed/SeedOptions.cs index caa4ae06..2ebf49d7 100644 --- a/src/common/LibplanetConsole.Seed/SeedOptions.cs +++ b/src/common/LibplanetConsole.Seed/SeedOptions.cs @@ -1,4 +1,5 @@ -using LibplanetConsole.Common; +using System.Net; +using LibplanetConsole.Common; namespace LibplanetConsole.Seed; @@ -6,7 +7,7 @@ public sealed record class SeedOptions { public required PrivateKey PrivateKey { get; init; } - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromSeconds(5); diff --git a/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs b/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs index af9f299f..753fe8a9 100644 --- a/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs +++ b/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs @@ -81,7 +81,7 @@ internal sealed record class ApplicationSettings public ApplicationOptions ToOptions(object[] components) { - var endPoint = AppEndPoint.ParseOrNext(EndPoint); + var endPoint = EndPointUtility.ParseOrNext(EndPoint); var nodeOptions = GetNodeOptions(endPoint, GetNodes()); var clientOptions = GetClientOptions(nodeOptions, GetClients()); var repository = new Repository(endPoint, nodeOptions, clientOptions); @@ -120,11 +120,11 @@ public static ApplicationSettings Parse(string[] args) } private static NodeOptions[] GetNodeOptions( - AppEndPoint endPoint, PrivateKey[] nodePrivateKeys) + EndPoint endPoint, PrivateKey[] nodePrivateKeys) { return [.. nodePrivateKeys.Select(key => new NodeOptions { - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), PrivateKey = key, SeedEndPoint = endPoint, })]; @@ -135,7 +135,7 @@ private static ClientOptions[] GetClientOptions( { return [.. clientPrivateKeys.Select(key => new ClientOptions { - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), NodeEndPoint = Random(nodeOptions).EndPoint, PrivateKey = key, })]; @@ -148,7 +148,7 @@ private PrivateKey[] GetNodes() { if (Nodes.Length > 0) { - return [.. Nodes.Select(PrivateKey.Parse)]; + return [.. Nodes.Select(item => new PrivateKey(item))]; } return [.. Enumerable.Range(0, NodeCount).Select(item => new PrivateKey())]; @@ -158,7 +158,7 @@ private PrivateKey[] GetClients() { if (Clients.Length > 0) { - return [.. Clients.Select(PrivateKey.Parse)]; + return [.. Clients.Select(item => new PrivateKey(item))]; } return [.. Enumerable.Range(0, ClientCount).Select(item => new PrivateKey())]; diff --git a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs index f0049012..8da00a7d 100644 --- a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs +++ b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs @@ -1,4 +1,5 @@ using System.ComponentModel; +using System.Net; using JSSoft.Commands; using LibplanetConsole.Common; using LibplanetConsole.Common.DataAnnotations; @@ -85,7 +86,7 @@ public InitializeCommand() protected override void OnExecute() { var genesisKey = PrivateKeyUtility.ParseOrRandom(GenesisKey); - var endPoint = AppEndPoint.ParseOrNext(EndPoint); + var endPoint = EndPointUtility.ParseOrNext(EndPoint); var prevEndPoint = EndPoint != string.Empty ? endPoint : null; var nodeOptions = GetNodeOptions(ref prevEndPoint); var clientOptions = GetClientOptions(ref prevEndPoint); @@ -126,14 +127,13 @@ protected override void OnExecute() TextWriterExtensions.WriteLineAsJson(writer, info); } - private NodeOptions[] GetNodeOptions(ref AppEndPoint? prevEndPoint) + private NodeOptions[] GetNodeOptions(ref EndPoint? prevEndPoint) { var privateKeys = GetNodes(); var nodeOptionsList = new List(privateKeys.Length); foreach (var privateKey in privateKeys) { - var endPoint = prevEndPoint is not null - ? new AppEndPoint(prevEndPoint.Host, prevEndPoint.Port + 1) : AppEndPoint.Next(); + var endPoint = prevEndPoint ?? EndPointUtility.Next(); var nodeOptions = new NodeOptions { EndPoint = endPoint, @@ -152,14 +152,13 @@ private NodeOptions[] GetNodeOptions(ref AppEndPoint? prevEndPoint) return [.. nodeOptionsList]; } - private ClientOptions[] GetClientOptions(ref AppEndPoint? prevEndPoint) + private ClientOptions[] GetClientOptions(ref EndPoint? prevEndPoint) { var privateKeys = GetClients(); var clientOptionsList = new List(privateKeys.Length); foreach (var privateKey in privateKeys) { - var endPoint = prevEndPoint is not null - ? new AppEndPoint(prevEndPoint.Host, prevEndPoint.Port + 1) : AppEndPoint.Next(); + var endPoint = prevEndPoint ?? EndPointUtility.Next(); var clientOptions = new ClientOptions { EndPoint = endPoint, diff --git a/src/console/LibplanetConsole.Console.Explorer/Commands/ExplorerCommand.cs b/src/console/LibplanetConsole.Console.Explorer/Commands/ExplorerCommand.cs index ce210c86..bcd8e110 100644 --- a/src/console/LibplanetConsole.Console.Explorer/Commands/ExplorerCommand.cs +++ b/src/console/LibplanetConsole.Console.Explorer/Commands/ExplorerCommand.cs @@ -28,7 +28,7 @@ public async Task StartAsync( var explorerNode = node.GetRequiredService(); if (endPoint != string.Empty) { - explorerNode.EndPoint = AppEndPoint.Parse(endPoint); + explorerNode.EndPoint = EndPointUtility.Parse(endPoint); } await explorerNode.StartAsync(cancellationToken); diff --git a/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs b/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs index b9bc59cc..fb9a6ebe 100644 --- a/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs +++ b/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs @@ -17,14 +17,14 @@ internal sealed class ExplorerNodeContent(INode node, ILogger logger, ExplorerSe { private readonly ILogger _logger = logger; private readonly ExecutionScope _executionScope = new(); - private AppEndPoint _endPoint = AppEndPoint.Next(); + private EndPoint _endPoint = EndPointUtility.Next(); private RemoteService? _remoteService; public event EventHandler? Started; public event EventHandler? Stopped; - public AppEndPoint EndPoint + public EndPoint EndPoint { get => _endPoint; set diff --git a/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs b/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs index ac6e22ea..2f402a80 100644 --- a/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs +++ b/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs @@ -9,7 +9,7 @@ public interface IExplorerNodeContent event EventHandler? Stopped; - AppEndPoint EndPoint { get; set; } + EndPoint EndPoint { get; set; } ExplorerInfo Info { get; } diff --git a/src/console/LibplanetConsole.Console/ApplicationInfo.cs b/src/console/LibplanetConsole.Console/ApplicationInfo.cs index ff02d2d7..a9536027 100644 --- a/src/console/LibplanetConsole.Console/ApplicationInfo.cs +++ b/src/console/LibplanetConsole.Console/ApplicationInfo.cs @@ -4,7 +4,7 @@ namespace LibplanetConsole.Console; public readonly record struct ApplicationInfo { - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public required string LogPath { get; init; } diff --git a/src/console/LibplanetConsole.Console/ApplicationOptions.cs b/src/console/LibplanetConsole.Console/ApplicationOptions.cs index 70129aa0..b6565c67 100644 --- a/src/console/LibplanetConsole.Console/ApplicationOptions.cs +++ b/src/console/LibplanetConsole.Console/ApplicationOptions.cs @@ -4,12 +4,12 @@ namespace LibplanetConsole.Console; public sealed record class ApplicationOptions { - public ApplicationOptions(AppEndPoint endPoint) + public ApplicationOptions(EndPoint endPoint) { EndPoint = endPoint; } - public AppEndPoint EndPoint { get; } + public EndPoint EndPoint { get; } public NodeOptions[] Nodes { get; init; } = []; diff --git a/src/console/LibplanetConsole.Console/Client.cs b/src/console/LibplanetConsole.Console/Client.cs index 6b310a28..7a403ac7 100644 --- a/src/console/LibplanetConsole.Console/Client.cs +++ b/src/console/LibplanetConsole.Console/Client.cs @@ -6,6 +6,7 @@ using LibplanetConsole.Client.Services; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; +using LibplanetConsole.Common.Extensions; using LibplanetConsole.Common.Services; using LibplanetConsole.Console.Services; using LibplanetConsole.Framework; @@ -67,7 +68,7 @@ public Client(ApplicationBase application, ClientOptions clientOptions) public bool IsRunning { get; private set; } - public AppEndPoint EndPoint => _remoteServiceContext.EndPoint; + public EndPoint EndPoint => _remoteServiceContext.EndPoint; public ClientInfo Info => _clientInfo; diff --git a/src/console/LibplanetConsole.Console/ClientOptions.cs b/src/console/LibplanetConsole.Console/ClientOptions.cs index 154133f5..bf93a148 100644 --- a/src/console/LibplanetConsole.Console/ClientOptions.cs +++ b/src/console/LibplanetConsole.Console/ClientOptions.cs @@ -6,11 +6,11 @@ namespace LibplanetConsole.Console; public sealed record class ClientOptions { - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public required PrivateKey PrivateKey { get; init; } - public AppEndPoint? NodeEndPoint { get; init; } + public EndPoint? NodeEndPoint { get; init; } public string LogPath { get; init; } = string.Empty; @@ -32,10 +32,10 @@ public static ClientOptions Load(string settingsPath) return new() { - EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), + EndPoint = EndPointUtility.Parse(applicationSettings.EndPoint), PrivateKey = new PrivateKey(applicationSettings.PrivateKey), LogPath = Path.GetFullPath(applicationSettings.LogPath, repositoryPath), - NodeEndPoint = AppEndPoint.ParseOrDefault(applicationSettings.NodeEndPoint), + NodeEndPoint = EndPointUtility.ParseOrDefault(applicationSettings.NodeEndPoint), RepositoryPath = repositoryPath, }; } diff --git a/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs b/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs index 2c37286a..8e906fc7 100644 --- a/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs +++ b/src/console/LibplanetConsole.Console/ClientRepositoryProcess.cs @@ -6,7 +6,7 @@ internal sealed class ClientRepositoryProcess : ClientProcessBase { public required PrivateKey PrivateKey { get; init; } - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public string OutputPath { get; set; } = string.Empty; @@ -17,6 +17,6 @@ internal sealed class ClientRepositoryProcess : ClientProcessBase "--private-key", PrivateKeyUtility.ToString(PrivateKey), "--end-point", - AppEndPoint.ToString(EndPoint), + EndPointUtility.ToString(EndPoint), ]; } diff --git a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs index 969c1982..de369926 100644 --- a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs @@ -56,7 +56,7 @@ public async Task NewAsync( { var clientOptions = new ClientOptions { - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), PrivateKey = PrivateKeyUtility.ParseOrRandom(privateKey), }; var options = new AddNewClientOptions diff --git a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs index 326e7ac0..9569f172 100644 --- a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs @@ -65,7 +65,7 @@ public async Task NewAsync( { var nodeOptions = new NodeOptions { - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), PrivateKey = PrivateKeyUtility.ParseOrRandom(privateKey), }; var options = new AddNewNodeOptions diff --git a/src/console/LibplanetConsole.Console/IClient.cs b/src/console/LibplanetConsole.Console/IClient.cs index a6b6eb0f..48755fe6 100644 --- a/src/console/LibplanetConsole.Console/IClient.cs +++ b/src/console/LibplanetConsole.Console/IClient.cs @@ -19,7 +19,7 @@ public interface IClient : IAddressable, IAsyncDisposable, IServiceProvider, ISi bool IsRunning { get; } - AppEndPoint EndPoint { get; } + EndPoint EndPoint { get; } ClientInfo Info { get; } diff --git a/src/console/LibplanetConsole.Console/INode.cs b/src/console/LibplanetConsole.Console/INode.cs index 0d5d19b2..f99a95f8 100644 --- a/src/console/LibplanetConsole.Console/INode.cs +++ b/src/console/LibplanetConsole.Console/INode.cs @@ -19,7 +19,7 @@ public interface INode : IAddressable, IAsyncDisposable, IServiceProvider, ISign bool IsRunning { get; } - AppEndPoint EndPoint { get; } + EndPoint EndPoint { get; } NodeInfo Info { get; } diff --git a/src/console/LibplanetConsole.Console/Node.BlockChain.cs b/src/console/LibplanetConsole.Console/Node.BlockChain.cs index cd910805..a63fa6d0 100644 --- a/src/console/LibplanetConsole.Console/Node.BlockChain.cs +++ b/src/console/LibplanetConsole.Console/Node.BlockChain.cs @@ -26,8 +26,8 @@ public async Task SendTransactionAsync( var genesisHash = _nodeInfo.GenesisHash; var tx = Transaction.Create( nonce: nonce, - privateKey: (PrivateKey)privateKey, - genesisHash: (BlockHash)genesisHash, + privateKey: privateKey, + genesisHash: genesisHash, actions: [.. actions.Select(item => item.PlainValue)]); var txId = await _blockChainService.Service.SendTransactionAsync( transaction: tx.Serialize(), diff --git a/src/console/LibplanetConsole.Console/Node.cs b/src/console/LibplanetConsole.Console/Node.cs index 7a3811aa..1456a51b 100644 --- a/src/console/LibplanetConsole.Console/Node.cs +++ b/src/console/LibplanetConsole.Console/Node.cs @@ -27,8 +27,8 @@ internal sealed partial class Node : INode, IBlockChain, INodeCallback, IBlockCh private readonly INodeContent[] _contents; private readonly ILogger _logger; private readonly CancellationTokenSource _processCancellationTokenSource = new(); - private AppEndPoint? _blocksyncEndPoint; - private AppEndPoint? _consensusEndPoint; + private EndPoint? _blocksyncEndPoint; + private EndPoint? _consensusEndPoint; private Guid _closeToken; private NodeInfo _nodeInfo; private bool _isDisposed; @@ -66,10 +66,10 @@ public Node(ApplicationBase application, NodeOptions nodeOptions) public event EventHandler? Disposed; - public AppEndPoint SwarmEndPoint + public EndPoint SwarmEndPoint => _blocksyncEndPoint ?? throw new InvalidOperationException("Peer is not set."); - public AppEndPoint ConsensusEndPoint + public EndPoint ConsensusEndPoint => _consensusEndPoint ?? throw new InvalidOperationException("ConsensusPeer is not set."); public PublicKey PublicKey { get; } @@ -80,7 +80,7 @@ public AppEndPoint ConsensusEndPoint public bool IsRunning { get; private set; } - public AppEndPoint EndPoint => _nodeOptions.EndPoint; + public EndPoint EndPoint => _nodeOptions.EndPoint; public NodeInfo Info => _nodeInfo; @@ -170,11 +170,11 @@ public async Task StartAsync(CancellationToken cancellationToken) using var scope = new ProgressScope(this); var application = this.GetRequiredService(); - var seedEndPoint = AppEndPoint.ToString( + var seedEndPoint = EndPointUtility.ToString( _nodeOptions.SeedEndPoint ?? application.Info.EndPoint); _nodeInfo = await _remoteService.Service.StartAsync(seedEndPoint, cancellationToken); - _blocksyncEndPoint = AppEndPoint.Parse(_nodeInfo.SwarmEndPoint); - _consensusEndPoint = AppEndPoint.Parse(_nodeInfo.ConsensusEndPoint); + _blocksyncEndPoint = EndPointUtility.Parse(_nodeInfo.SwarmEndPoint); + _consensusEndPoint = EndPointUtility.Parse(_nodeInfo.ConsensusEndPoint); IsRunning = true; _logger.Debug("Node is started: {Address}", Address); Started?.Invoke(this, EventArgs.Empty); diff --git a/src/console/LibplanetConsole.Console/NodeOptions.cs b/src/console/LibplanetConsole.Console/NodeOptions.cs index 8c9de2fd..5eef5c5c 100644 --- a/src/console/LibplanetConsole.Console/NodeOptions.cs +++ b/src/console/LibplanetConsole.Console/NodeOptions.cs @@ -1,4 +1,5 @@ using System.ComponentModel; +using System.Net; using System.Text.Json.Serialization; using LibplanetConsole.Common; @@ -6,11 +7,11 @@ namespace LibplanetConsole.Console; public sealed record class NodeOptions { - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public required PrivateKey PrivateKey { get; init; } - public AppEndPoint? SeedEndPoint { get; init; } + public EndPoint? SeedEndPoint { get; init; } public string StorePath { get; init; } = string.Empty; @@ -36,12 +37,12 @@ public static NodeOptions Load(string settingsPath) return new() { - EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), + EndPoint = EndPointUtility.Parse(applicationSettings.EndPoint), PrivateKey = new PrivateKey(applicationSettings.PrivateKey), StorePath = Path.GetFullPath(applicationSettings.StorePath, repositoryPath), LogPath = Path.GetFullPath(applicationSettings.LogPath, repositoryPath), LibraryLogPath = Path.GetFullPath(applicationSettings.LibraryLogPath, repositoryPath), - SeedEndPoint = AppEndPoint.ParseOrDefault(applicationSettings.SeedEndPoint), + SeedEndPoint = EndPointUtility.ParseOrDefault(applicationSettings.SeedEndPoint), RepositoryPath = repositoryPath, }; } diff --git a/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs b/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs index 41a55995..3c2f7c14 100644 --- a/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs +++ b/src/console/LibplanetConsole.Console/NodeRepositoryProcess.cs @@ -6,7 +6,7 @@ internal sealed class NodeRepositoryProcess : NodeProcessBase { public required PrivateKey PrivateKey { get; init; } - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public string OutputPath { get; set; } = string.Empty; @@ -19,7 +19,7 @@ internal sealed class NodeRepositoryProcess : NodeProcessBase "--private-key", PrivateKeyUtility.ToString(PrivateKey), "--end-point", - AppEndPoint.ToString(EndPoint), + EndPointUtility.ToString(EndPoint), "--genesis-path", GenesisPath, ]; diff --git a/src/console/LibplanetConsole.Console/Repository.cs b/src/console/LibplanetConsole.Console/Repository.cs index ba53e57a..be4ef35c 100644 --- a/src/console/LibplanetConsole.Console/Repository.cs +++ b/src/console/LibplanetConsole.Console/Repository.cs @@ -15,14 +15,14 @@ public sealed record class Repository private byte[]? _genesis; - public Repository(AppEndPoint endPoint, NodeOptions[] nodes, ClientOptions[] clients) + public Repository(EndPoint endPoint, NodeOptions[] nodes, ClientOptions[] clients) { EndPoint = endPoint; Nodes = nodes; Clients = clients; } - public AppEndPoint EndPoint { get; } + public EndPoint EndPoint { get; } public NodeOptions[] Nodes { get; } = []; @@ -68,7 +68,7 @@ public static Repository Load(string repositoryPath, RepositoryPathResolver reso .Select(LoadClientOptions) .ToArray(); var applicationSettings = LoadSettings(repositoryPath, resolver); - var endPoint = AppEndPoint.Parse(applicationSettings.EndPoint); + var endPoint = EndPointUtility.Parse(applicationSettings.EndPoint); var genesisPath = resolver.GetGenesisPath(repositoryPath); return new(endPoint, nodeOptions, clientOptions) diff --git a/src/console/LibplanetConsole.Console/Services/SeedService.cs b/src/console/LibplanetConsole.Console/Services/SeedService.cs index bd1b6b23..2be64bcf 100644 --- a/src/console/LibplanetConsole.Console/Services/SeedService.cs +++ b/src/console/LibplanetConsole.Console/Services/SeedService.cs @@ -25,12 +25,12 @@ public SeedService(ApplicationBase application) _blocksyncSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), }); _consensusSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), }); } diff --git a/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs b/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs index aaf013aa..f61f3fec 100644 --- a/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs +++ b/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs @@ -101,7 +101,7 @@ internal sealed record class ApplicationSettings public ApplicationOptions ToOptions(object[] components) { - var endPoint = AppEndPoint.ParseOrNext(EndPoint); + var endPoint = EndPointUtility.ParseOrNext(EndPoint); var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); var genesis = TryGetGenesis(out var g) == true ? g : CreateGenesis(privateKey); var actionProvider = ModuleLoader.LoadActionLoader( @@ -121,11 +121,11 @@ public ApplicationOptions ToOptions(object[] components) static string GetFullPath(string path) => path != string.Empty ? Path.GetFullPath(path) : path; - AppEndPoint? GetSeedEndPoint() + EndPoint? GetSeedEndPoint() { if (SeedEndPoint != string.Empty) { - return AppEndPoint.Parse(SeedEndPoint); + return EndPointUtility.Parse(SeedEndPoint); } return IsSingleNode is true ? endPoint : null; diff --git a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs index f6353b95..56a88982 100644 --- a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs +++ b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs @@ -102,7 +102,7 @@ public InitializeCommand() protected override void OnExecute() { var outputPath = Path.GetFullPath(RepositoryPath); - var endPoint = AppEndPoint.ParseOrNext(EndPoint); + var endPoint = EndPointUtility.ParseOrNext(EndPoint); var privateKey = PrivateKeyUtility.ParseOrRandom(PrivateKey); var storePath = Path.Combine(outputPath, StorePath.Fallback("store")); var logPath = Path.Combine(outputPath, LogPath.Fallback("app.log")); diff --git a/src/node/LibplanetConsole.Node.Executable/Repository.cs b/src/node/LibplanetConsole.Node.Executable/Repository.cs index d4baf488..231fd30e 100644 --- a/src/node/LibplanetConsole.Node.Executable/Repository.cs +++ b/src/node/LibplanetConsole.Node.Executable/Repository.cs @@ -11,11 +11,11 @@ public sealed record class Repository public const string SettingsFileName = "node-settings.json"; public const string SettingsSchemaFileName = "node-settings-schema.json"; - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } public required PrivateKey PrivateKey { get; init; } - public AppEndPoint? SeedEndPoint { get; init; } + public EndPoint? SeedEndPoint { get; init; } public string StorePath { get; init; } = string.Empty; @@ -47,13 +47,13 @@ public static Repository Load(string settingsPath) return new() { - EndPoint = AppEndPoint.Parse(applicationSettings.EndPoint), + EndPoint = EndPointUtility.Parse(applicationSettings.EndPoint), PrivateKey = new PrivateKey(applicationSettings.PrivateKey), StorePath = Path.GetFullPath(applicationSettings.StorePath, directoryName), LogPath = Path.GetFullPath(applicationSettings.LogPath, directoryName), LibraryLogPath = Path.GetFullPath(applicationSettings.LibraryLogPath, directoryName), Source = settingsPath, - SeedEndPoint = AppEndPoint.ParseOrDefault(applicationSettings.SeedEndPoint), + SeedEndPoint = EndPointUtility.ParseOrDefault(applicationSettings.SeedEndPoint), ActionProviderModulePath = applicationSettings.ActionProviderModulePath, ActionProviderType = applicationSettings.ActionProviderType, }; @@ -94,13 +94,13 @@ public dynamic Save(string repositoryPath) Schema = SettingsSchemaFileName, Application = new ApplicationSettings { - EndPoint = EndPoint.ToString(), + EndPoint = EndPointUtility.ToString(EndPoint), PrivateKey = PrivateKeyUtility.ToString(privateKey), GenesisPath = GetRelativePathFromDirectory(repositoryPath, GenesisPath), StorePath = GetRelativePathFromDirectory(repositoryPath, StorePath), LogPath = GetRelativePathFromDirectory(repositoryPath, LogPath), LibraryLogPath = GetRelativePathFromDirectory(repositoryPath, LibraryLogPath), - SeedEndPoint = AppEndPoint.ToString(SeedEndPoint), + SeedEndPoint = EndPointUtility.ToString(SeedEndPoint), ActionProviderModulePath = ActionProviderModulePath, ActionProviderType = ActionProviderType, }, diff --git a/src/node/LibplanetConsole.Node.Explorer/Commands/ExplorerCommand.cs b/src/node/LibplanetConsole.Node.Explorer/Commands/ExplorerCommand.cs index 4d60293a..70418922 100644 --- a/src/node/LibplanetConsole.Node.Explorer/Commands/ExplorerCommand.cs +++ b/src/node/LibplanetConsole.Node.Explorer/Commands/ExplorerCommand.cs @@ -18,7 +18,7 @@ public async Task StartAsync( var explorerNode = serviceProvider.GetRequiredService(); var explorerOptions = new ExplorerOptions { - EndPoint = AppEndPoint.ParseOrNext(endPoint), + EndPoint = EndPointUtility.ParseOrNext(endPoint), }; await explorerNode.StartAsync(explorerOptions, cancellationToken); await Console.Out.WriteLineAsync($"http://{explorerOptions.EndPoint}/ui/playground"); diff --git a/src/node/LibplanetConsole.Node.Explorer/ExplorerNode.cs b/src/node/LibplanetConsole.Node.Explorer/ExplorerNode.cs index 030cdd62..8a85c407 100644 --- a/src/node/LibplanetConsole.Node.Explorer/ExplorerNode.cs +++ b/src/node/LibplanetConsole.Node.Explorer/ExplorerNode.cs @@ -35,12 +35,12 @@ public async Task StartAsync( throw new InvalidOperationException("The explorer is already running."); } - var endPoint = options.EndPoint; + var (host, port) = EndPointUtility.GetHostAndPort(options.EndPoint); _webHost = WebHost.CreateDefaultBuilder() .ConfigureServices(services => services.AddSingleton(node)) .UseStartup>() .UseSerilog() - .UseUrls($"http://{endPoint.Host}:{endPoint.Port}/") + .UseUrls($"http://{host}:{port}/") .Build(); await _webHost.StartAsync(cancellationToken); @@ -71,7 +71,7 @@ async Task IApplicationService.InitializeAsync( { var options = new ExplorerOptions { - EndPoint = AppEndPoint.ParseOrNext(settings.ExplorerEndPoint), + EndPoint = EndPointUtility.ParseOrNext(settings.ExplorerEndPoint), }; await StartAsync(options, cancellationToken); } diff --git a/src/node/LibplanetConsole.Node/ApplicationBase.cs b/src/node/LibplanetConsole.Node/ApplicationBase.cs index e37353e4..35849e61 100644 --- a/src/node/LibplanetConsole.Node/ApplicationBase.cs +++ b/src/node/LibplanetConsole.Node/ApplicationBase.cs @@ -61,7 +61,7 @@ protected ApplicationBase(ApplicationOptions options) public override ApplicationServiceCollection ApplicationServices { get; } - public AppEndPoint EndPoint => _nodeContext.EndPoint; + public EndPoint EndPoint => _nodeContext.EndPoint; public ApplicationInfo Info => _info; diff --git a/src/node/LibplanetConsole.Node/ApplicationInfo.cs b/src/node/LibplanetConsole.Node/ApplicationInfo.cs index a2f246ed..71fa9069 100644 --- a/src/node/LibplanetConsole.Node/ApplicationInfo.cs +++ b/src/node/LibplanetConsole.Node/ApplicationInfo.cs @@ -4,9 +4,9 @@ namespace LibplanetConsole.Node; public readonly record struct ApplicationInfo { - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } - public required AppEndPoint? SeedEndPoint { get; init; } + public required EndPoint? SeedEndPoint { get; init; } public required string StorePath { get; init; } diff --git a/src/node/LibplanetConsole.Node/ApplicationOptions.cs b/src/node/LibplanetConsole.Node/ApplicationOptions.cs index df52d8df..d10e5abd 100644 --- a/src/node/LibplanetConsole.Node/ApplicationOptions.cs +++ b/src/node/LibplanetConsole.Node/ApplicationOptions.cs @@ -4,14 +4,14 @@ namespace LibplanetConsole.Node; public sealed record class ApplicationOptions { - public ApplicationOptions(AppEndPoint endPoint, PrivateKey privateKey, byte[] genesis) + public ApplicationOptions(EndPoint endPoint, PrivateKey privateKey, byte[] genesis) { EndPoint = endPoint; PrivateKey = privateKey; Genesis = genesis; } - public AppEndPoint EndPoint { get; } + public EndPoint EndPoint { get; } public PrivateKey PrivateKey { get; } @@ -19,7 +19,7 @@ public ApplicationOptions(AppEndPoint endPoint, PrivateKey privateKey, byte[] ge public int ParentProcessId { get; init; } - public AppEndPoint? SeedEndPoint { get; init; } + public EndPoint? SeedEndPoint { get; init; } public string StorePath { get; init; } = string.Empty; diff --git a/src/node/LibplanetConsole.Node/BlockUtility.cs b/src/node/LibplanetConsole.Node/BlockUtility.cs index 99a17948..b8248f08 100644 --- a/src/node/LibplanetConsole.Node/BlockUtility.cs +++ b/src/node/LibplanetConsole.Node/BlockUtility.cs @@ -40,13 +40,13 @@ private static Block CreateGenesisBlock( var nonce = 0L; var transaction = Transaction.Create( nonce: nonce, - privateKey: (PrivateKey)genesisKey, + privateKey: genesisKey, genesisHash: null, actions: [.. actions.Select(item => item.PlainValue)], timestamp: dateTimeOffset); var transactions = ImmutableList.Create(transaction); return ProposeGenesisBlock( - privateKey: (PrivateKey)genesisKey, + privateKey: genesisKey, transactions: transactions, timestamp: dateTimeOffset); } diff --git a/src/node/LibplanetConsole.Node/Node.BlockChain.cs b/src/node/LibplanetConsole.Node/Node.BlockChain.cs index 23d7abf9..5b66fa27 100644 --- a/src/node/LibplanetConsole.Node/Node.BlockChain.cs +++ b/src/node/LibplanetConsole.Node/Node.BlockChain.cs @@ -31,7 +31,7 @@ public async Task AddTransactionAsync( var values = actions.Select(item => item.PlainValue).ToArray(); var transaction = Transaction.Create( nonce: nonce, - privateKey: (PrivateKey)privateKey, + privateKey: privateKey, genesisHash: genesisBlock.Hash, actions: new TxActionList(values)); await AddTransactionAsync(transaction, cancellationToken); diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index 809bfde5..5d5f5989 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -37,9 +37,9 @@ private readonly SynchronizationContext _synchronizationContext private readonly AppProtocolVersion _appProtocolVersion = SeedNode.AppProtocolVersion; private readonly IActionProvider _actionProvider; - private AppEndPoint? _seedEndPoint; - private AppEndPoint? _blocksyncEndPoint; - private AppEndPoint? _consensusEndPoint; + private EndPoint? _seedEndPoint; + private EndPoint? _blocksyncEndPoint; + private EndPoint? _consensusEndPoint; private Swarm? _swarm; private Task _startTask = Task.CompletedTask; private bool _isDisposed; @@ -64,13 +64,13 @@ public Node(IServiceProvider serviceProvider, ApplicationOptions options, ILogge public event EventHandler? Stopped; - public AppEndPoint SwarmEndPoint + public EndPoint SwarmEndPoint { get => _blocksyncEndPoint ?? throw new InvalidOperationException(); set => _blocksyncEndPoint = value; } - public AppEndPoint ConsensusEndPoint + public EndPoint ConsensusEndPoint { get => _consensusEndPoint ?? throw new InvalidOperationException(); set => _consensusEndPoint = value; @@ -105,7 +105,7 @@ public BoundPeer[] Peers } } - public AppEndPoint SeedEndPoint + public EndPoint SeedEndPoint { get => _seedEndPoint ?? throw new InvalidOperationException($"{nameof(SeedEndPoint)} is not initialized."); @@ -155,8 +155,8 @@ public async Task StartAsync(CancellationToken cancellationToken) var privateKey = PrivateKeyUtility.FromSecureString(_privateKey); var appProtocolVersion = _appProtocolVersion; var storePath = _storePath; - var blocksyncEndPoint = _blocksyncEndPoint ?? AppEndPoint.Next(); - var consensusEndPoint = _consensusEndPoint ?? AppEndPoint.Next(); + var blocksyncEndPoint = _blocksyncEndPoint ?? EndPointUtility.Next(); + var consensusEndPoint = _consensusEndPoint ?? EndPointUtility.Next(); var blocksyncSeedPeer = seedInfo.BlocksyncSeedPeer; var consensusSeedPeer = seedInfo.ConsensusSeedPeer; var swarmTransport @@ -176,7 +176,7 @@ var swarmTransport var consensusReactorOption = new ConsensusReactorOption { SeedPeers = [consensusSeedPeer], - ConsensusPort = consensusEndPoint.Port, + ConsensusPort = EndPointUtility.GetHostAndPort(consensusEndPoint).Port, ConsensusPrivateKey = privateKey, TargetBlockInterval = TimeSpan.FromSeconds(2), ContextTimeoutOptions = new(), @@ -287,18 +287,19 @@ void Action(object? state) } private static async Task CreateTransport( - PrivateKey privateKey, AppEndPoint endPoint, AppProtocolVersion appProtocolVersion) + PrivateKey privateKey, EndPoint endPoint, AppProtocolVersion appProtocolVersion) { var appProtocolVersionOptions = new AppProtocolVersionOptions { AppProtocolVersion = appProtocolVersion, }; - var hostOptions = new HostOptions(endPoint.Host, [], endPoint.Port); + var (host, port) = EndPointUtility.GetHostAndPort(endPoint); + var hostOptions = new HostOptions(host, [], port); return await NetMQTransport.Create(privateKey, appProtocolVersionOptions, hostOptions); } private static async Task GetSeedInfoAsync( - AppEndPoint seedEndPoint, CancellationToken cancellationToken) + EndPoint seedEndPoint, CancellationToken cancellationToken) { var remoteService = new RemoteService(); var remoteServiceContext = new RemoteServiceContext([remoteService]) @@ -344,8 +345,8 @@ private void UpdateNodeInfo() { nodeInfo = nodeInfo with { - SwarmEndPoint = AppEndPoint.ToString(SwarmEndPoint), - ConsensusEndPoint = AppEndPoint.ToString(ConsensusEndPoint), + SwarmEndPoint = EndPointUtility.ToString(SwarmEndPoint), + ConsensusEndPoint = EndPointUtility.ToString(ConsensusEndPoint), GenesisHash = BlockChain.Genesis.Hash, TipHash = BlockChain.Tip.Hash, IsRunning = IsRunning, diff --git a/src/node/LibplanetConsole.Node/PeerUtility.cs b/src/node/LibplanetConsole.Node/PeerUtility.cs index 004d4905..312e60da 100644 --- a/src/node/LibplanetConsole.Node/PeerUtility.cs +++ b/src/node/LibplanetConsole.Node/PeerUtility.cs @@ -11,5 +11,5 @@ // => new((PublicKey)peer.PublicKey, (DnsEndPoint)peer.EndPoint); // public static AppPeer ToAppPeer(BoundPeer boundPeer) -// => new((PublicKey)boundPeer.PublicKey, (AppEndPoint)boundPeer.EndPoint); +// => new((PublicKey)boundPeer.PublicKey, (EndPoint)boundPeer.EndPoint); // } diff --git a/src/node/LibplanetConsole.Node/Services/NodeService.cs b/src/node/LibplanetConsole.Node/Services/NodeService.cs index 92dac108..9974d6f6 100644 --- a/src/node/LibplanetConsole.Node/Services/NodeService.cs +++ b/src/node/LibplanetConsole.Node/Services/NodeService.cs @@ -28,7 +28,7 @@ public async Task GetInfoAsync(CancellationToken cancellationToken) public async Task StartAsync(string seedEndPoint, CancellationToken cancellationToken) { - _node.SeedEndPoint = AppEndPoint.Parse(seedEndPoint); + _node.SeedEndPoint = EndPointUtility.Parse(seedEndPoint); await _node.StartAsync(cancellationToken); _logger.Information("Node started."); return _node.Info; diff --git a/src/node/LibplanetConsole.Node/Services/SeedService.cs b/src/node/LibplanetConsole.Node/Services/SeedService.cs index c36b6f34..4c418765 100644 --- a/src/node/LibplanetConsole.Node/Services/SeedService.cs +++ b/src/node/LibplanetConsole.Node/Services/SeedService.cs @@ -58,12 +58,12 @@ async Task IApplicationService.InitializeAsync( _blocksyncSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), }); _consensusSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = AppEndPoint.Next(), + EndPoint = EndPointUtility.Next(), }); await _blocksyncSeedNode.StartAsync(cancellationToken); await _consensusSeedNode.StartAsync(cancellationToken); diff --git a/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs b/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs index e717fbea..6a281efa 100644 --- a/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs +++ b/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs @@ -4,7 +4,7 @@ namespace LibplanetConsole.Explorer; public readonly record struct ExplorerInfo { - public AppEndPoint? EndPoint { get; init; } + public EndPoint? EndPoint { get; init; } public bool IsRunning { get; init; } } diff --git a/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs b/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs index cc6a4906..480853e1 100644 --- a/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs +++ b/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs @@ -4,5 +4,5 @@ namespace LibplanetConsole.Explorer; public sealed record class ExplorerOptions { - public required AppEndPoint EndPoint { get; init; } + public required EndPoint EndPoint { get; init; } } diff --git a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs b/test/LibplanetConsole.Common.Tests/AppPeerTest.cs index bf8909f7..203a9c86 100644 --- a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs +++ b/test/LibplanetConsole.Common.Tests/AppPeerTest.cs @@ -6,7 +6,7 @@ // public void Test1() // { // var publicKey = new PrivateKey().PublicKey; -// var endPoint = new AppEndPoint("localhost", 12345); +// var endPoint = new EndPoint("localhost", 12345); // var peer = new AppPeer(publicKey, endPoint); // Assert.Equal(publicKey, peer.PublicKey); // Assert.Equal(endPoint, peer.EndPoint); From 25f4458a78b057517250bf56e5da2b9ba7f1f333 Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 19:18:53 +0900 Subject: [PATCH 8/9] refactor: Remove unused codes --- .../ExampleClient.cs | 2 - .../ExampleRemoteNodeService.cs | 1 - .../Repository.cs | 1 - .../ApplicationBase.cs | 1 - .../ApplicationInfo.cs | 2 - .../ApplicationOptions.cs | 2 - .../Client.BlockChain.cs | 6 - src/client/LibplanetConsole.Client/Client.cs | 2 - .../LibplanetConsole.Client/IBlockChain.cs | 4 - src/client/LibplanetConsole.Client/IClient.cs | 2 - .../LibplanetConsole.Common/ActionBase.cs | 2 - .../Actions/AggregateTypedActionLoader.cs | 3 - .../Actions/AssemblyActionLoader.cs | 3 - .../Actions/StringAction.cs | 3 - .../AppAddress.Bencodex.cs | 12 -- .../LibplanetConsole.Common/AppAddress.cs | 84 ------------ .../LibplanetConsole.Common/AppEndPoint.cs | 107 --------------- src/common/LibplanetConsole.Common/AppHash.cs | 64 --------- src/common/LibplanetConsole.Common/AppId.cs | 58 -------- src/common/LibplanetConsole.Common/AppPeer.cs | 43 ------ .../LibplanetConsole.Common/AppPrivateKey.cs | 129 ------------------ .../AppPublicKey.Bencodex.cs | 19 --- .../LibplanetConsole.Common/AppPublicKey.cs | 94 ------------- .../Commands/KeyCommandBase.cs | 1 - .../Converters/AppAddressConverter.cs | 41 ------ .../Converters/AppAddressJsonConverter.cs | 26 ---- .../Converters/AppHashJsonConverter.cs | 26 ---- .../Converters/AppIdJsonConverter.cs | 26 ---- .../Converters/AppPeerJsonConverter.cs | 25 ---- ...nConverter.cs => EndPointJsonConverter.cs} | 0 ...onverter.cs => PrivateKeyJsonConverter.cs} | 0 .../Converters/PublicKeyJsonConverter.cs | 1 - .../DataAnnotations/AppPeerAttribute.cs | 26 ---- .../EndPointUtility.cs | 32 +++-- .../Extensions/AddressExtensions.cs | 1 - .../Extensions/PrivateKeyExtensions.cs | 3 - .../Extensions/PublicKeyExtensions.cs | 3 - .../LibplanetConsole.Common/PortUtility.cs | 1 - .../PrivateKeyUtility.cs | 5 - .../Services/LocalServiceContext.cs | 1 - .../Services/RemoteServiceContext.cs | 2 - .../Services/Serializer.cs | 49 ------- .../LibplanetConsole.Seed/BoundPeerUtility.cs | 9 +- .../LibplanetConsole.Seed/ISeedService.cs | 2 - src/common/LibplanetConsole.Seed/Peer.cs | 2 - .../LibplanetConsole.Seed/PeerCollection.cs | 2 - src/common/LibplanetConsole.Seed/SeedNode.cs | 13 +- .../LibplanetConsole.Seed/SeedOptions.cs | 1 - .../ExampleNodeContent.cs | 1 - .../ApplicationSettings.cs | 4 +- .../EntryCommands/InitializeCommand.cs | 5 +- .../ExplorerNodeContent.cs | 2 +- .../IExplorerNodeContent.cs | 1 - .../ApplicationBase.cs | 1 - .../ApplicationInfo.cs | 2 - .../ApplicationOptions.cs | 2 - .../LibplanetConsole.Console/Client.cs | 3 +- .../ClientCollection.cs | 1 - .../LibplanetConsole.Console/ClientProcess.cs | 4 +- .../Commands/ClientCommand.cs | 2 +- .../Commands/NodeCommand.cs | 2 +- .../LibplanetConsole.Console/IAddressable.cs | 2 - .../LibplanetConsole.Console/IApplication.cs | 3 - .../LibplanetConsole.Console/IBlockChain.cs | 4 - .../IClientCollection.cs | 1 - .../INodeCollection.cs | 2 - .../Node.BlockChain.cs | 6 - src/console/LibplanetConsole.Console/Node.cs | 2 - .../NodeCollection.cs | 2 - .../LibplanetConsole.Console/NodeOptions.cs | 1 - .../LibplanetConsole.Console/NodeProcess.cs | 4 +- .../LibplanetConsole.Console/Repository.cs | 3 +- .../Services/SeedService.cs | 4 +- .../DuplicateVoteViolator.cs | 2 - .../EvidenceNode.cs | 2 - .../Commands/ExampleNodeCommand.cs | 1 - .../ApplicationSettings.cs | 1 - .../EntryCommands/GenesisCommand.cs | 1 - .../EntryCommands/InitializeCommand.cs | 1 - .../LibplanetConsole.Node/ActionProvider.cs | 5 - .../LibplanetConsole.Node/ApplicationBase.cs | 1 - .../LibplanetConsole.Node/ApplicationInfo.cs | 2 - .../ApplicationOptions.cs | 2 - .../BlockChainUtility.cs | 2 - .../LibplanetConsole.Node/BlockUtility.cs | 7 - .../LibplanetConsole.Node/IActionProvider.cs | 3 - src/node/LibplanetConsole.Node/IBlockChain.cs | 4 - src/node/LibplanetConsole.Node/INode.cs | 2 - .../LibplanetConsole.Node/Node.BlockChain.cs | 7 - src/node/LibplanetConsole.Node/Node.cs | 11 +- src/node/LibplanetConsole.Node/PeerUtility.cs | 15 -- .../Services/BlockChainService.cs | 4 - .../Services/SeedService.cs | 8 +- .../LibplanetConsole.Client/ClientInfo.cs | 3 - .../Services/IClientService.cs | 2 - .../LibplanetConsole.Evidence/EvidenceInfo.cs | 1 - .../LibplanetConsole.Evidence/TestEvidence.cs | 2 - .../Services/IExampleNodeCallback.cs | 2 - .../Services/IExampleNodeService.cs | 2 - .../LibplanetConsole.Explorer/ExplorerInfo.cs | 2 - .../ExplorerOptions.cs | 2 - .../LibplanetConsole.Node/ActionInfo.cs | 3 - src/shared/LibplanetConsole.Node/BlockInfo.cs | 3 - .../LibplanetConsole.Node/BlockUtility.cs | 4 - src/shared/LibplanetConsole.Node/NodeInfo.cs | 7 - .../Services/IBlockChainService.cs | 2 - .../LibplanetConsole.Node/TransactionInfo.cs | 3 - .../AppPeerTest.cs | 14 -- .../GlobalUsings.cs | 1 - 109 files changed, 46 insertions(+), 1094 deletions(-) delete mode 100644 src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs delete mode 100644 src/common/LibplanetConsole.Common/AppAddress.cs delete mode 100644 src/common/LibplanetConsole.Common/AppEndPoint.cs delete mode 100644 src/common/LibplanetConsole.Common/AppHash.cs delete mode 100644 src/common/LibplanetConsole.Common/AppId.cs delete mode 100644 src/common/LibplanetConsole.Common/AppPeer.cs delete mode 100644 src/common/LibplanetConsole.Common/AppPrivateKey.cs delete mode 100644 src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs delete mode 100644 src/common/LibplanetConsole.Common/AppPublicKey.cs delete mode 100644 src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs delete mode 100644 src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs delete mode 100644 src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs delete mode 100644 src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs delete mode 100644 src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs rename src/common/LibplanetConsole.Common/Converters/{AppEndPointJsonConverter.cs => EndPointJsonConverter.cs} (100%) rename src/common/LibplanetConsole.Common/Converters/{AppPrivateKeyJsonConverter.cs => PrivateKeyJsonConverter.cs} (100%) delete mode 100644 src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs delete mode 100644 src/common/LibplanetConsole.Common/Services/Serializer.cs delete mode 100644 src/node/LibplanetConsole.Node/PeerUtility.cs delete mode 100644 test/LibplanetConsole.Common.Tests/AppPeerTest.cs delete mode 100644 test/LibplanetConsole.Common.Tests/GlobalUsings.cs diff --git a/src/client/LibplanetConsole.Client.Example/ExampleClient.cs b/src/client/LibplanetConsole.Client.Example/ExampleClient.cs index eb0f94c3..c11c9457 100644 --- a/src/client/LibplanetConsole.Client.Example/ExampleClient.cs +++ b/src/client/LibplanetConsole.Client.Example/ExampleClient.cs @@ -1,6 +1,4 @@ using System.ComponentModel.Composition; -using Libplanet.Crypto; -using LibplanetConsole.Common; using LibplanetConsole.Example.Services; namespace LibplanetConsole.Client.Example; diff --git a/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs b/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs index f6a248b3..86c69a94 100644 --- a/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs +++ b/src/client/LibplanetConsole.Client.Example/ExampleRemoteNodeService.cs @@ -1,5 +1,4 @@ using System.ComponentModel.Composition; -using Libplanet.Crypto; using LibplanetConsole.Common.Services; using LibplanetConsole.Example.Services; diff --git a/src/client/LibplanetConsole.Client.Executable/Repository.cs b/src/client/LibplanetConsole.Client.Executable/Repository.cs index 623f166b..e4e5d576 100644 --- a/src/client/LibplanetConsole.Client.Executable/Repository.cs +++ b/src/client/LibplanetConsole.Client.Executable/Repository.cs @@ -1,5 +1,4 @@ using System.Dynamic; -using System.Net; using System.Text.Json.Serialization; using LibplanetConsole.Common; using LibplanetConsole.Framework; diff --git a/src/client/LibplanetConsole.Client/ApplicationBase.cs b/src/client/LibplanetConsole.Client/ApplicationBase.cs index 6b03f461..f5b0f979 100644 --- a/src/client/LibplanetConsole.Client/ApplicationBase.cs +++ b/src/client/LibplanetConsole.Client/ApplicationBase.cs @@ -2,7 +2,6 @@ using System.ComponentModel.Composition; using System.Diagnostics; using LibplanetConsole.Client.Services; -using LibplanetConsole.Common; using LibplanetConsole.Framework; using LibplanetConsole.Framework.Extensions; using Serilog; diff --git a/src/client/LibplanetConsole.Client/ApplicationInfo.cs b/src/client/LibplanetConsole.Client/ApplicationInfo.cs index d799f968..99e6135b 100644 --- a/src/client/LibplanetConsole.Client/ApplicationInfo.cs +++ b/src/client/LibplanetConsole.Client/ApplicationInfo.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Client; public readonly record struct ApplicationInfo diff --git a/src/client/LibplanetConsole.Client/ApplicationOptions.cs b/src/client/LibplanetConsole.Client/ApplicationOptions.cs index 817d8060..72d6f926 100644 --- a/src/client/LibplanetConsole.Client/ApplicationOptions.cs +++ b/src/client/LibplanetConsole.Client/ApplicationOptions.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Client; public sealed record class ApplicationOptions diff --git a/src/client/LibplanetConsole.Client/Client.BlockChain.cs b/src/client/LibplanetConsole.Client/Client.BlockChain.cs index 75a7e9ae..27669668 100644 --- a/src/client/LibplanetConsole.Client/Client.BlockChain.cs +++ b/src/client/LibplanetConsole.Client/Client.BlockChain.cs @@ -1,10 +1,4 @@ using System.Security.Cryptography; -using Bencodex; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Crypto; -using Libplanet.Types.Blocks; -using Libplanet.Types.Tx; using LibplanetConsole.Common; using LibplanetConsole.Node; diff --git a/src/client/LibplanetConsole.Client/Client.cs b/src/client/LibplanetConsole.Client/Client.cs index a2b40e44..7d4cdc40 100644 --- a/src/client/LibplanetConsole.Client/Client.cs +++ b/src/client/LibplanetConsole.Client/Client.cs @@ -1,6 +1,4 @@ -using System.Net; using System.Security; -using Libplanet.Crypto; using LibplanetConsole.Client.Services; using LibplanetConsole.Common; using LibplanetConsole.Common.Extensions; diff --git a/src/client/LibplanetConsole.Client/IBlockChain.cs b/src/client/LibplanetConsole.Client/IBlockChain.cs index 89be3a54..909d8eb7 100644 --- a/src/client/LibplanetConsole.Client/IBlockChain.cs +++ b/src/client/LibplanetConsole.Client/IBlockChain.cs @@ -1,8 +1,4 @@ using System.Security.Cryptography; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Crypto; -using LibplanetConsole.Common; namespace LibplanetConsole.Client; diff --git a/src/client/LibplanetConsole.Client/IClient.cs b/src/client/LibplanetConsole.Client/IClient.cs index 0a69e897..26cd1d37 100644 --- a/src/client/LibplanetConsole.Client/IClient.cs +++ b/src/client/LibplanetConsole.Client/IClient.cs @@ -1,5 +1,3 @@ -using Libplanet.Action; -using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Node; diff --git a/src/common/LibplanetConsole.Common/ActionBase.cs b/src/common/LibplanetConsole.Common/ActionBase.cs index c5831702..e46c9c21 100644 --- a/src/common/LibplanetConsole.Common/ActionBase.cs +++ b/src/common/LibplanetConsole.Common/ActionBase.cs @@ -1,6 +1,4 @@ using System.Reflection; -using Bencodex.Types; -using Libplanet.Action; using Libplanet.Action.State; namespace LibplanetConsole.Common; diff --git a/src/common/LibplanetConsole.Common/Actions/AggregateTypedActionLoader.cs b/src/common/LibplanetConsole.Common/Actions/AggregateTypedActionLoader.cs index 9b031db4..f8be7955 100644 --- a/src/common/LibplanetConsole.Common/Actions/AggregateTypedActionLoader.cs +++ b/src/common/LibplanetConsole.Common/Actions/AggregateTypedActionLoader.cs @@ -1,7 +1,4 @@ using System.Collections; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Action.Loader; using Libplanet.Action.Sys; namespace LibplanetConsole.Common.Actions; diff --git a/src/common/LibplanetConsole.Common/Actions/AssemblyActionLoader.cs b/src/common/LibplanetConsole.Common/Actions/AssemblyActionLoader.cs index cd268a84..ce32e013 100644 --- a/src/common/LibplanetConsole.Common/Actions/AssemblyActionLoader.cs +++ b/src/common/LibplanetConsole.Common/Actions/AssemblyActionLoader.cs @@ -1,7 +1,4 @@ using System.Reflection; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Action.Loader; using Libplanet.Action.Sys; namespace LibplanetConsole.Common.Actions; diff --git a/src/common/LibplanetConsole.Common/Actions/StringAction.cs b/src/common/LibplanetConsole.Common/Actions/StringAction.cs index 0488edfd..89aa1c8b 100644 --- a/src/common/LibplanetConsole.Common/Actions/StringAction.cs +++ b/src/common/LibplanetConsole.Common/Actions/StringAction.cs @@ -1,7 +1,4 @@ -using Bencodex.Types; -using Libplanet.Action; using Libplanet.Action.State; -using Libplanet.Crypto; namespace LibplanetConsole.Common.Actions; diff --git a/src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs b/src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs deleted file mode 100644 index fd078306..00000000 --- a/src/common/LibplanetConsole.Common/AppAddress.Bencodex.cs +++ /dev/null @@ -1,12 +0,0 @@ -// using Bencodex.Types; -// using Libplanet.Crypto; - -// namespace LibplanetConsole.Common; - -// public readonly partial record struct AppAddress -// { -// public static AppAddress FromBencodex(IValue value) -// => new AppAddress(new Address(value)); - -// public IValue ToBencodex() => _address.Bencoded; -// } diff --git a/src/common/LibplanetConsole.Common/AppAddress.cs b/src/common/LibplanetConsole.Common/AppAddress.cs deleted file mode 100644 index 3fe36147..00000000 --- a/src/common/LibplanetConsole.Common/AppAddress.cs +++ /dev/null @@ -1,84 +0,0 @@ -// using System.ComponentModel; -// using System.Diagnostics.CodeAnalysis; -// using System.Security.Cryptography; -// using System.Text; -// using System.Text.Json.Serialization; -// using Libplanet.Crypto; -// using LibplanetConsole.Common.Converters; - -// namespace LibplanetConsole.Common; - -// [JsonConverter(typeof(AppAddressJsonConverter))] -// [TypeConverter(typeof(AppAddressConverter))] -// public readonly partial record struct AppAddress : IFormattable -// { -// public const string RegularExpression = "0x[0-9a-fA-F]{40}"; -// private readonly Address _address; - -// public AppAddress(Address address) => _address = address; - -// public AppAddress(byte[] bytes) -// : this(new Address(bytes)) -// { -// } - -// public static explicit operator AppAddress(Address address) -// => new(address); - -// public static explicit operator Address(AppAddress address) -// => address._address; - -// public static string ToString(AppAddress? address) -// => address?.ToString() ?? string.Empty; - -// public static AppAddress Parse(string text) => new(new Address(text)); - -// public static AppAddress? ParseOrDefault(string text) -// => text == string.Empty ? null : Parse(text); - -// public static AppAddress ParseOrFallback(string text, AppAddress fallback) -// => text == string.Empty ? fallback : Parse(text); - -// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppAddress address) -// { -// try -// { -// address = Parse(text); -// return true; -// } -// catch -// { -// address = default; -// return false; -// } -// } - -// public override string ToString() => _address.ToString(); - -// public string ToString(string? format, IFormatProvider? formatProvider) -// { -// if (format is "S") -// { -// return $"{_address}"[0..8]; -// } - -// return ToString(); -// } - -// public string ToShortString() => ToString(format: "S", formatProvider: null); - -// public AppAddress Derive(byte[] key) -// { -// var bytes = _address.ToByteArray(); -// var hashed = GetHahsed(key, bytes); -// return new AppAddress(hashed); - -// static byte[] GetHahsed(byte[] key, byte[] bytes) -// { -// using var hmac = new HMACSHA1(key); -// return hmac.ComputeHash(bytes); -// } -// } - -// public AppAddress Derive(string key) => Derive(Encoding.UTF8.GetBytes(key)); -// } diff --git a/src/common/LibplanetConsole.Common/AppEndPoint.cs b/src/common/LibplanetConsole.Common/AppEndPoint.cs deleted file mode 100644 index 5b43abd9..00000000 --- a/src/common/LibplanetConsole.Common/AppEndPoint.cs +++ /dev/null @@ -1,107 +0,0 @@ -// using System.Diagnostics.CodeAnalysis; -// using System.Net; -// using System.Net.Sockets; -// using System.Text.Json.Serialization; -// using LibplanetConsole.Common.Converters; -// using CommunicationUtility = JSSoft.Communication.EndPointUtility; - -// namespace LibplanetConsole.Common; - -// [JsonConverter(typeof(EndPointJsonConverter))] -// public sealed record class EndPoint -// { -// public const string HostExpression -// = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; - -// public const string PortExpression = @"\d{1,5}"; -// public static readonly string RegularExpression -// = $"{HostExpression}:{PortExpression}"; - -// private static readonly object LockObject = new(); -// private static readonly List PortList = []; - -// public EndPoint(string host, int port) -// { -// Host = host; -// Port = port; -// } - -// public string Host { get; } - -// public int Port { get; } - -// public static explicit operator EndPoint(EndPoint endPoint) -// => new DnsEndPoint(endPoint.Host, endPoint.Port); - -// public static explicit operator DnsEndPoint(EndPoint endPoint) -// => new(endPoint.Host, endPoint.Port); - -// public static explicit operator EndPoint(EndPoint endPoint) -// { -// if (endPoint is DnsEndPoint dnsEndPoint) -// { -// return new(dnsEndPoint.Host, dnsEndPoint.Port); -// } - -// if (endPoint is IPEndPoint ipEndPoint) -// { -// return new($"{ipEndPoint.Address}", ipEndPoint.Port); -// } - -// throw new InvalidCastException(); -// } - -// public static EndPoint Next() => new("localhost", GetPort()); - -// public static EndPoint Parse(string text) => (EndPoint)CommunicationUtility.Parse(text); - -// public static EndPoint ParseOrNext(string text) -// => text == string.Empty ? Next() : Parse(text); - -// public static EndPoint ParseOrFallback(string text, EndPoint fallback) -// => text == string.Empty ? fallback : Parse(text); - -// public static EndPoint? ParseOrDefault(string text) -// => text == string.Empty ? null : Parse(text); - -// public static bool TryParse(string text, [MaybeNullWhen(false)] out EndPoint endPoint) -// { -// if (CommunicationUtility.TryParse(text, out var value)) -// { -// endPoint = (EndPoint)value; -// return true; -// } - -// endPoint = null; -// return false; -// } - -// public static string ToString(EndPoint? endPoint) -// => endPoint is not null ? endPoint.ToString() : string.Empty; - -// public override string ToString() => $"{Host}:{Port}"; - -// private static int GetPort() -// { -// lock (LockObject) -// { -// var port = GetRandomPort(); -// while (PortList.Contains(port) == true) -// { -// port = GetRandomPort(); -// } - -// PortList.Add(port); -// return port; -// } -// } - -// private static int GetRandomPort() -// { -// var listener = new TcpListener(IPAddress.Loopback, 0); -// listener.Start(); -// var port = ((IPEndPoint)listener.LocalEndpoint).Port; -// listener.Stop(); -// return port; -// } -// } diff --git a/src/common/LibplanetConsole.Common/AppHash.cs b/src/common/LibplanetConsole.Common/AppHash.cs deleted file mode 100644 index a0eef2e7..00000000 --- a/src/common/LibplanetConsole.Common/AppHash.cs +++ /dev/null @@ -1,64 +0,0 @@ -// using System.Collections.Immutable; -// using System.Diagnostics.CodeAnalysis; -// using System.Security.Cryptography; -// using System.Text.Json.Serialization; -// using Libplanet.Common; -// using Libplanet.Types.Blocks; -// using LibplanetConsole.Common.Converters; - -// namespace LibplanetConsole.Common; - -// [JsonConverter(typeof(AppHashJsonConverter))] -// public readonly record struct AppHash : IFormattable -// { -// private readonly ImmutableArray _bytes; - -// public AppHash(byte[] bytes) => _bytes = [.. bytes]; - -// public AppHash(ImmutableArray bytes) => _bytes = bytes; - -// public AppHash(BlockHash blockHash) => _bytes = blockHash.ByteArray; - -// public static explicit operator AppHash(BlockHash blockHash) => new(blockHash); - -// public static explicit operator AppHash(HashDigest hashDigest) -// => new(hashDigest.ByteArray); - -// public static explicit operator BlockHash(AppHash hash) => new(hash._bytes); - -// public static explicit operator HashDigest(AppHash hash) => new(hash._bytes); - -// public static string ToString(AppHash? blockHash) -// => blockHash?.ToString() ?? string.Empty; - -// public static AppHash Parse(string text) => new(ByteUtil.ParseHexToImmutable(text)); - -// public static AppHash? ParseOrDefault(string text) -// => text == string.Empty ? null : Parse(text); - -// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppHash blockHash) -// { -// try -// { -// blockHash = Parse(text); -// return true; -// } -// catch -// { -// blockHash = default; -// return false; -// } -// } - -// public override string ToString() => ByteUtil.Hex(_bytes); - -// public string ToString(string? format, IFormatProvider? formatProvider) -// { -// if (format is "S") -// { -// return ToString()[..8]; -// } - -// return ToString(); -// } -// } diff --git a/src/common/LibplanetConsole.Common/AppId.cs b/src/common/LibplanetConsole.Common/AppId.cs deleted file mode 100644 index 9d538262..00000000 --- a/src/common/LibplanetConsole.Common/AppId.cs +++ /dev/null @@ -1,58 +0,0 @@ -// using System.Collections.Immutable; -// using System.Diagnostics.CodeAnalysis; -// using System.Text.Json.Serialization; -// using Libplanet.Common; -// using Libplanet.Types.Tx; -// using LibplanetConsole.Common.Converters; - -// namespace LibplanetConsole.Common; - -// [JsonConverter(typeof(AppIdJsonConverter))] -// public readonly record struct AppId : IFormattable -// { -// private readonly ImmutableArray _bytes; - -// public AppId(byte[] bytes) => _bytes = [.. bytes]; - -// public AppId(ImmutableArray bytes) => _bytes = bytes; - -// public AppId(TxId txId) => _bytes = txId.ByteArray; - -// public static explicit operator AppId(TxId txId) => new(txId); - -// public static explicit operator TxId(AppId id) => new(id._bytes); - -// public static string ToString(AppId? blockHash) -// => blockHash?.ToString() ?? string.Empty; - -// public static AppId Parse(string text) => new(ByteUtil.ParseHexToImmutable(text)); - -// public static AppId? ParseOrDefault(string text) -// => text == string.Empty ? null : Parse(text); - -// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppId blockHash) -// { -// try -// { -// blockHash = Parse(text); -// return true; -// } -// catch -// { -// blockHash = default; -// return false; -// } -// } - -// public override string ToString() => ByteUtil.Hex(_bytes); - -// public string ToString(string? format, IFormatProvider? formatProvider) -// { -// if (format is "S") -// { -// return ToString()[..8]; -// } - -// return ToString(); -// } -// } diff --git a/src/common/LibplanetConsole.Common/AppPeer.cs b/src/common/LibplanetConsole.Common/AppPeer.cs deleted file mode 100644 index 8695e19c..00000000 --- a/src/common/LibplanetConsole.Common/AppPeer.cs +++ /dev/null @@ -1,43 +0,0 @@ -// using System.Text.Json.Serialization; -// using Libplanet.Crypto; -// using LibplanetConsole.Common.Converters; -// using LibplanetConsole.Common.DataAnnotations; - -// namespace LibplanetConsole.Common; - -// [JsonConverter(typeof(AppPeerJsonConverter))] -// public readonly struct AppPeer(PublicKey publicKey, EndPoint endPoint) -// { -// public const string HostExpression -// = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; - -// public const string PortExpression = @"\d{1,5}"; -// public static readonly string RegularExpression -// = $"^{PublicKeyAttribute.RegularExpression},{EndPoint.RegularExpression}$"; - -// public PublicKey PublicKey { get; } = publicKey; - -// public EndPoint EndPoint { get; } = endPoint; - -// public Address Address => PublicKey.Address; - -// public static string ToString(AppPeer? peer) -// => peer?.ToString() ?? string.Empty; - -// public static AppPeer Parse(string text) -// { -// var items = text.Split(',', StringSplitOptions.RemoveEmptyEntries); -// if (items.Length == 2) -// { -// var publicKey = PublicKey.FromHex(items[0]); -// var endPoint = EndPointUtility.Parse(items[1].Trim()); -// return new AppPeer(publicKey, endPoint); -// } - -// throw new FormatException($"'{text}' is not supported."); -// } - -// public static AppPeer? ParseOrDefault(string text) => text == string.Empty ? null : Parse(text); - -// public override string ToString() => $"{PublicKey}, {EndPoint}"; -// } diff --git a/src/common/LibplanetConsole.Common/AppPrivateKey.cs b/src/common/LibplanetConsole.Common/AppPrivateKey.cs deleted file mode 100644 index 41562b8a..00000000 --- a/src/common/LibplanetConsole.Common/AppPrivateKey.cs +++ /dev/null @@ -1,129 +0,0 @@ -// using System.Diagnostics.CodeAnalysis; -// using System.Security; -// using System.Text; -// using System.Text.Json; -// using System.Text.Json.Serialization; -// using Bencodex; -// using Bencodex.Types; -// using Libplanet.Common; -// using Libplanet.Crypto; -// using LibplanetConsole.Common.Converters; -// using LibplanetConsole.Common.Extensions; - -// namespace LibplanetConsole.Common; - -// [JsonConverter(typeof(PrivateKeyJsonConverter))] -// public sealed record class PrivateKey -// { -// public const string RegularExpression = "[0-9a-fA-F]{64}"; -// private static readonly Codec _codec = new(); -// private readonly PrivateKey _privateKey; - -// public PrivateKey(PrivateKey privateKey) => _privateKey = privateKey; - -// public PrivateKey(byte[] bytes) -// : this(new PrivateKey(bytes)) -// { -// } - -// public PrivateKey() -// : this(new PrivateKey()) -// { -// } - -// public PublicKey PublicKey => _privateKey.PublicKey; - -// public Address Address => _privateKey.PublicKey.Address; - -// public static explicit operator PrivateKey(PrivateKey privateKey) -// => new(privateKey); - -// public static explicit operator PrivateKey(PrivateKey privateKey) -// => privateKey._privateKey; - -// public static string ToString(PrivateKey? privateKey) -// => privateKey is not null ? ByteUtil.Hex(privateKey.ToByteArray()) : string.Empty; - -// public static PrivateKey Parse(string text) => new(new PrivateKey(text)); - -// public static PrivateKey? ParseOrDefault(string text) -// => text == string.Empty ? null : Parse(text); - -// public static PrivateKey ParseOrRandom(string text) -// => text == string.Empty ? new PrivateKey() : Parse(text); - -// public static bool TryParse(string text, [MaybeNullWhen(false)] out PrivateKey privateKey) -// { -// try -// { -// privateKey = Parse(text); -// return true; -// } -// catch -// { -// privateKey = default; -// return false; -// } -// } - -// public override string? ToString() -// { -// #if DEBUG -// System.Diagnostics.Trace.TraceWarning( -// "PrivateKey.ToString() is called. It may be a security risk."); -// #endif -// return base.ToString(); -// } - -// public byte[] ToByteArray() => [.. _privateKey.ByteArray]; - -// public static PrivateKey FromSecureString(SecureString secureString) -// { -// using var ptr = new StringPointer(secureString); -// var text = ptr.GetString(); -// var bytes = ByteUtil.ParseHex(text); -// return new(bytes); -// } - -// public SecureString ToSecureString() -// { -// var secureString = new SecureString(); -// var text = ByteUtil.Hex(_privateKey.ByteArray); -// secureString.AppendString(text); -// return secureString; -// } - -// public object? Decrypt(string text, Type type) -// { -// var bytes = ByteUtil.ParseHex(text); -// var decrypted = _privateKey.Decrypt(bytes); -// var json = Encoding.UTF8.GetString(decrypted); -// return JsonSerializer.Deserialize(json, type); -// } - -// public byte[] Decrypt(byte[] bytes) => _privateKey.Decrypt(bytes); - -// public T Decrypt(string text) -// where T : notnull => Decrypt(text, typeof(T)) switch -// { -// T result => result, -// _ => throw new InvalidOperationException($"Failed to decrypt {text} as {typeof(T)}."), -// }; - -// public byte[] Sign(object obj) -// { -// if (obj is IValue value) -// { -// return _privateKey.Sign(_codec.Encode(value)); -// } - -// if (obj is IBencodable bencodable) -// { -// return _privateKey.Sign(_codec.Encode(bencodable.Bencoded)); -// } - -// var json = JsonSerializer.Serialize(obj); -// var bytes = Encoding.UTF8.GetBytes(json); -// return _privateKey.Sign(bytes); -// } -// } diff --git a/src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs b/src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs deleted file mode 100644 index 611650c4..00000000 --- a/src/common/LibplanetConsole.Common/AppPublicKey.Bencodex.cs +++ /dev/null @@ -1,19 +0,0 @@ -// using Bencodex.Types; -// using Libplanet.Crypto; - -// namespace LibplanetConsole.Common; - -// public readonly partial record struct AppPublicKey -// { -// public static AppPublicKey FromBencodex(IValue value) -// { -// if (value is not Binary binary) -// { -// throw new InvalidCastException("The given value is not a binary."); -// } - -// return new(new PublicKey(binary.ByteArray)); -// } - -// public IValue ToBencodex() => new Binary(_publicKey.Format(true)); -// } diff --git a/src/common/LibplanetConsole.Common/AppPublicKey.cs b/src/common/LibplanetConsole.Common/AppPublicKey.cs deleted file mode 100644 index cd076b5e..00000000 --- a/src/common/LibplanetConsole.Common/AppPublicKey.cs +++ /dev/null @@ -1,94 +0,0 @@ -// using System.Diagnostics.CodeAnalysis; -// using System.Text; -// using System.Text.Json; -// using System.Text.Json.Serialization; -// using Bencodex; -// using Bencodex.Types; -// using Libplanet.Common; -// using Libplanet.Crypto; -// using LibplanetConsole.Common.Converters; - -// namespace LibplanetConsole.Common; - -// [JsonConverter(typeof(AppPublicKeyJsonConverter))] -// public readonly partial record struct AppPublicKey : IFormattable -// { -// public const string RegularExpression = "(?:[0-9a-fA-F]{130}|[0-9a-fA-F]{66})"; -// private static readonly Codec _codec = new(); -// private readonly PublicKey _publicKey; - -// public AppPublicKey(PublicKey publicKey) => _publicKey = publicKey; - -// public Address Address => _publicKey.Address; - -// public static explicit operator AppPublicKey(PublicKey publicKey) -// => new(publicKey); - -// public static explicit operator PublicKey(AppPublicKey publicKey) -// => publicKey._publicKey; - -// public static string ToString(AppPublicKey? publicKey) -// => publicKey?.ToString() ?? string.Empty; - -// public static AppPublicKey Parse(string text) => new(PublicKey.FromHex(text)); - -// public static AppPublicKey? ParseOrDefault(string text) -// => text == string.Empty ? null : Parse(text); - -// public static bool TryParse(string text, [MaybeNullWhen(false)] out AppPublicKey publicKey) -// { -// try -// { -// publicKey = Parse(text); -// return true; -// } -// catch -// { -// publicKey = default; -// return false; -// } -// } - -// public override string ToString() => _publicKey.ToHex(compress: false); - -// public string ToString(string? format, IFormatProvider? formatProvider) -// { -// if (format is "S" or "C") -// { -// return _publicKey.ToHex(compress: true); -// } - -// return ToString(); -// } - -// public string ToShortString() => ToString(format: "S", formatProvider: null); - -// public byte[] ToByteArray() => [.. _publicKey.ToImmutableArray(compress: false)]; - -// public string Encrypt(object obj) -// { -// var json = JsonSerializer.Serialize(obj); -// var encodings = Encoding.UTF8.GetBytes(json); -// var encrypted = _publicKey.Encrypt(encodings); -// return ByteUtil.Hex(encrypted); -// } - -// public byte[] Encrypt(byte[] bytes) => _publicKey.Encrypt(bytes); - -// public bool Verify(object obj, byte[] signature) -// { -// if (obj is IValue value) -// { -// return _publicKey.Verify(_codec.Encode(value), signature); -// } - -// if (obj is IBencodable bencodable) -// { -// return _publicKey.Verify(_codec.Encode(bencodable.Bencoded), signature); -// } - -// var json = JsonSerializer.Serialize(obj); -// var bytes = Encoding.UTF8.GetBytes(json); -// return _publicKey.Verify(bytes, signature); -// } -// } diff --git a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs index d7412340..b496d52c 100644 --- a/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs +++ b/src/common/LibplanetConsole.Common/Commands/KeyCommandBase.cs @@ -1,5 +1,4 @@ using JSSoft.Commands; -using Libplanet.Crypto; using LibplanetConsole.Common.Extensions; namespace LibplanetConsole.Common.Commands; diff --git a/src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs deleted file mode 100644 index 313d8c44..00000000 --- a/src/common/LibplanetConsole.Common/Converters/AppAddressConverter.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using Libplanet.Crypto; - -namespace LibplanetConsole.Common.Converters; - -internal sealed class AppAddressConverter : TypeConverter -{ - public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) - => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - - public override bool CanConvertTo( - ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType) - => destinationType == typeof(string) || base.CanConvertTo(context, destinationType); - - public override object? ConvertFrom( - ITypeDescriptorContext? context, CultureInfo? culture, object value) - { - if (value is string text) - { - return ParseOrDefault(text); - } - - return base.ConvertFrom(context, culture, value); - } - - public override object? ConvertTo( - ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) - { - if (value is Address address) - { - return address.ToString(); - } - - return base.ConvertTo(context, culture, value, destinationType); - } - - public static Address? ParseOrDefault(string text) - => text == string.Empty ? null : new Address(text); -} diff --git a/src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs deleted file mode 100644 index 0a0da677..00000000 --- a/src/common/LibplanetConsole.Common/Converters/AppAddressJsonConverter.cs +++ /dev/null @@ -1,26 +0,0 @@ -// using System.Text.Json; -// using System.Text.Json.Serialization; - -// namespace LibplanetConsole.Common.Converters; - -// public sealed class AppAddressJsonConverter : JsonConverter -// { -// public override AppAddress Read( -// ref Utf8JsonReader reader, -// Type typeToConvert, -// JsonSerializerOptions options) -// { -// if (reader.GetString() is string text) -// { -// return AppAddress.Parse(text); -// } - -// throw new JsonException("Cannot read AppAddress from JSON."); -// } - -// public override void Write( -// Utf8JsonWriter writer, AppAddress value, JsonSerializerOptions options) -// { -// writer.WriteStringValue(value.ToString()); -// } -// } diff --git a/src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs deleted file mode 100644 index f43e63a3..00000000 --- a/src/common/LibplanetConsole.Common/Converters/AppHashJsonConverter.cs +++ /dev/null @@ -1,26 +0,0 @@ -// using System.Text.Json; -// using System.Text.Json.Serialization; - -// namespace LibplanetConsole.Common.Converters; - -// public sealed class AppHashJsonConverter : JsonConverter -// { -// public override AppHash Read( -// ref Utf8JsonReader reader, -// Type typeToConvert, -// JsonSerializerOptions options) -// { -// if (reader.GetString() is string text) -// { -// return AppHash.Parse(text); -// } - -// throw new JsonException("Cannot read AppHash from JSON."); -// } - -// public override void Write( -// Utf8JsonWriter writer, AppHash value, JsonSerializerOptions options) -// { -// writer.WriteStringValue(value.ToString()); -// } -// } diff --git a/src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs deleted file mode 100644 index 8226c338..00000000 --- a/src/common/LibplanetConsole.Common/Converters/AppIdJsonConverter.cs +++ /dev/null @@ -1,26 +0,0 @@ -// using System.Text.Json; -// using System.Text.Json.Serialization; - -// namespace LibplanetConsole.Common.Converters; - -// public sealed class TxIdJsonConverter : JsonConverter -// { -// public override TxId Read( -// ref Utf8JsonReader reader, -// Type typeToConvert, -// JsonSerializerOptions options) -// { -// if (reader.GetString() is string text) -// { -// return TxId.Parse(text); -// } - -// throw new JsonException("Cannot read TxId from JSON."); -// } - -// public override void Write( -// Utf8JsonWriter writer, TxId value, JsonSerializerOptions options) -// { -// writer.WriteStringValue(value.ToString()); -// } -// } diff --git a/src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs deleted file mode 100644 index 14882764..00000000 --- a/src/common/LibplanetConsole.Common/Converters/AppPeerJsonConverter.cs +++ /dev/null @@ -1,25 +0,0 @@ -// using System.Text.Json; -// using System.Text.Json.Serialization; - -// namespace LibplanetConsole.Common.Converters; - -// public sealed class AppPeerJsonConverter : JsonConverter -// { -// public override AppPeer Read( -// ref Utf8JsonReader reader, -// Type typeToConvert, -// JsonSerializerOptions options) -// { -// if (reader.GetString() is string text) -// { -// return AppPeer.Parse(text); -// } - -// throw new JsonException("Cannot read AppPeer from JSON."); -// } - -// public override void Write(Utf8JsonWriter writer, AppPeer value, JsonSerializerOptions options) -// { -// writer.WriteStringValue(value.ToString()); -// } -// } diff --git a/src/common/LibplanetConsole.Common/Converters/AppEndPointJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/EndPointJsonConverter.cs similarity index 100% rename from src/common/LibplanetConsole.Common/Converters/AppEndPointJsonConverter.cs rename to src/common/LibplanetConsole.Common/Converters/EndPointJsonConverter.cs diff --git a/src/common/LibplanetConsole.Common/Converters/AppPrivateKeyJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/PrivateKeyJsonConverter.cs similarity index 100% rename from src/common/LibplanetConsole.Common/Converters/AppPrivateKeyJsonConverter.cs rename to src/common/LibplanetConsole.Common/Converters/PrivateKeyJsonConverter.cs diff --git a/src/common/LibplanetConsole.Common/Converters/PublicKeyJsonConverter.cs b/src/common/LibplanetConsole.Common/Converters/PublicKeyJsonConverter.cs index 0bb914c1..a3c9d339 100644 --- a/src/common/LibplanetConsole.Common/Converters/PublicKeyJsonConverter.cs +++ b/src/common/LibplanetConsole.Common/Converters/PublicKeyJsonConverter.cs @@ -1,6 +1,5 @@ using System.Text.Json; using System.Text.Json.Serialization; -using Libplanet.Crypto; namespace LibplanetConsole.Common.Converters; diff --git a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs b/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs deleted file mode 100644 index bcf0d542..00000000 --- a/src/common/LibplanetConsole.Common/DataAnnotations/AppPeerAttribute.cs +++ /dev/null @@ -1,26 +0,0 @@ -// #pragma warning disable SA1402 // File may only contain a single type -// using System.ComponentModel.DataAnnotations; -// using LibplanetConsole.DataAnnotations; - -// namespace LibplanetConsole.Common.DataAnnotations; - -// [AttributeUsage(AttributeTargets.Property)] -// public sealed class AppPeerAttribute : RegularExpressionAttribute -// { -// public const string HostExpression -// = @"(?:(?:[a-zA-Z0-9\-\.]+)|(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))"; - -// public const string PortExpression = @"\d{1,5}"; -// public static readonly string RegularExpression -// = $"^{PublicKeyAttribute.RegularExpression},{EndPoint.RegularExpression}$"; - -// public AppPeerAttribute() -// : base($"^{RegularExpression}$") -// { -// } -// } - -// [AttributeUsage(AttributeTargets.Property)] -// public sealed class AppPeerArrayAttribute : ArrayAttribute -// { -// } diff --git a/src/common/LibplanetConsole.Common/EndPointUtility.cs b/src/common/LibplanetConsole.Common/EndPointUtility.cs index cdc2b5c4..cc161f41 100644 --- a/src/common/LibplanetConsole.Common/EndPointUtility.cs +++ b/src/common/LibplanetConsole.Common/EndPointUtility.cs @@ -1,13 +1,5 @@ using System.Diagnostics.CodeAnalysis; -using System.Net; using System.Net.Sockets; -using System.Security; -using System.Text; -using System.Text.Json; -using Bencodex; -using Bencodex.Types; -using Libplanet.Crypto; -using Microsoft.AspNetCore.Http; using CommunicationUtility = JSSoft.Communication.EndPointUtility; namespace LibplanetConsole.Common; @@ -17,12 +9,12 @@ public static class EndPointUtility private static readonly object LockObject = new(); private static readonly List PortList = []; - public static EndPoint Next() => new DnsEndPoint("localhost", GetPort()); + public static EndPoint NextEndPoint() => new DnsEndPoint("localhost", GetPort()); public static EndPoint Parse(string text) => CommunicationUtility.Parse(text); public static EndPoint ParseOrNext(string text) - => text == string.Empty ? Next() : Parse(text); + => text == string.Empty ? NextEndPoint() : Parse(text); public static EndPoint ParseOrFallback(string text, EndPoint fallback) => text == string.Empty ? fallback : Parse(text); @@ -52,9 +44,6 @@ public static (string Host, int Port) GetHostAndPort(EndPoint endPoint) }; } - // public static string ToString(EndPoint? endPoint) - // => endPoint is not null ? endPoint.ToString() : string.Empty; - public static string ToString(EndPoint? endPoint) { if (endPoint is DnsEndPoint dnsEndPoint) @@ -69,6 +58,23 @@ public static string ToString(EndPoint? endPoint) return endPoint?.ToString() ?? string.Empty; } + public static bool CompareEndPoint(EndPoint? endPoint1, EndPoint? endPoint2) + { + if (endPoint1 is null && endPoint2 is null) + { + return true; + } + + if (endPoint1 is null || endPoint2 is null) + { + return false; + } + + var (host1, port1) = GetHostAndPort(endPoint1); + var (host2, port2) = GetHostAndPort(endPoint2); + return host1 == host2 && port1 == port2; + } + private static int GetPort() { lock (LockObject) diff --git a/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs index 5fa4f3c5..586169d3 100644 --- a/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs +++ b/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs @@ -1,6 +1,5 @@ using System.Security.Cryptography; using System.Text; -using Libplanet.Crypto; namespace LibplanetConsole.Common.Extensions; diff --git a/src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs index e35cb77e..2abe5a4a 100644 --- a/src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs +++ b/src/common/LibplanetConsole.Common/Extensions/PrivateKeyExtensions.cs @@ -1,9 +1,6 @@ using System.Security; using System.Text; using System.Text.Json; -using Bencodex; -using Bencodex.Types; -using Libplanet.Crypto; namespace LibplanetConsole.Common.Extensions; diff --git a/src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs index 3e1006ef..aafcabf3 100644 --- a/src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs +++ b/src/common/LibplanetConsole.Common/Extensions/PublicKeyExtensions.cs @@ -1,8 +1,5 @@ using System.Text; using System.Text.Json; -using Bencodex; -using Bencodex.Types; -using Libplanet.Crypto; namespace LibplanetConsole.Common.Extensions; diff --git a/src/common/LibplanetConsole.Common/PortUtility.cs b/src/common/LibplanetConsole.Common/PortUtility.cs index 605a4fd9..874931d5 100644 --- a/src/common/LibplanetConsole.Common/PortUtility.cs +++ b/src/common/LibplanetConsole.Common/PortUtility.cs @@ -1,4 +1,3 @@ -using System.Net; using System.Net.Sockets; namespace LibplanetConsole.Common; diff --git a/src/common/LibplanetConsole.Common/PrivateKeyUtility.cs b/src/common/LibplanetConsole.Common/PrivateKeyUtility.cs index e98e5879..7bdb3785 100644 --- a/src/common/LibplanetConsole.Common/PrivateKeyUtility.cs +++ b/src/common/LibplanetConsole.Common/PrivateKeyUtility.cs @@ -1,10 +1,5 @@ using System.Diagnostics.CodeAnalysis; using System.Security; -using System.Text; -using System.Text.Json; -using Bencodex; -using Bencodex.Types; -using Libplanet.Crypto; namespace LibplanetConsole.Common; diff --git a/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs b/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs index cabf5226..4692b721 100644 --- a/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs +++ b/src/common/LibplanetConsole.Common/Services/LocalServiceContext.cs @@ -1,4 +1,3 @@ -using System.Net; using JSSoft.Communication; namespace LibplanetConsole.Common.Services; diff --git a/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs b/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs index b0f26479..be5af2f8 100644 --- a/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs +++ b/src/common/LibplanetConsole.Common/Services/RemoteServiceContext.cs @@ -1,4 +1,3 @@ -using System.Net; using JSSoft.Communication; namespace LibplanetConsole.Common.Services; @@ -61,6 +60,5 @@ public async Task CloseAsync(Guid token, CancellationToken cancellationToken) private sealed class InternalClientContext(IService[] services) : ClientContext(services) { - // : ISerializer } } diff --git a/src/common/LibplanetConsole.Common/Services/Serializer.cs b/src/common/LibplanetConsole.Common/Services/Serializer.cs deleted file mode 100644 index 5acb962b..00000000 --- a/src/common/LibplanetConsole.Common/Services/Serializer.cs +++ /dev/null @@ -1,49 +0,0 @@ -// using System.Text.Json; -// using System.Text.Json.Serialization; -// using JSSoft.Communication; - -// namespace LibplanetConsole.Common.Services; - -// internal sealed class CommunicationSerializer : ISerializer -// { -// private static readonly Dictionary _converterByType = -// [ -// typeof(BoundPeer) -// ] - -// private static readonly JsonSerializerOptions Options = new() -// { -// IncludeFields = true, -// Converters = -// { -// // new ArgumentExceptionConverter(), -// // new ArgumentNullExceptionConverter(), -// // new ArgumentOutOfRangeExceptionConverter(), -// // new ExceptionConverter(), -// // new IndexOutOfRangeExceptionConverter(), -// // new InvalidOperationExceptionConverter(), -// // new ObjectDisposedExceptionConverter(), -// // new NotSupportedExceptionConverter(), -// // new NullReferenceExceptionConverter(), -// // new SystemExceptionConverter(), -// // new ExceptionConverterFactory(), -// }, -// }; - -// private readonly ISerializer _serializer; - -// public CommunicationSerializer(ISerializer serializer) -// { -// _serializer = serializer; -// } - -// public object? Deserialize(Type type, string text) -// { -// if (Options.Converters.con) -// } - -// public string Serialize(Type type, object? data) -// { -// throw new NotImplementedException(); -// } -// } diff --git a/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs b/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs index 14be462b..ed84722f 100644 --- a/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs +++ b/src/common/LibplanetConsole.Seed/BoundPeerUtility.cs @@ -1,6 +1,4 @@ using System.Net; -using Libplanet.Crypto; -using Libplanet.Net; using LibplanetConsole.Common; namespace LibplanetConsole.Seed; @@ -9,7 +7,7 @@ public static class BoundPeerUtility { public static string ToString(BoundPeer? boundPeer) => boundPeer is not null - ? $"{boundPeer.PublicKey.ToHex(compress: false)}, {boundPeer.EndPoint.Host}:{boundPeer.EndPoint.Port}" + ? $"{boundPeer.PublicKey.ToHex(compress: false)}, {ToString(boundPeer.EndPoint)}" : string.Empty; public static BoundPeer Parse(string text) @@ -25,5 +23,8 @@ public static BoundPeer Parse(string text) throw new FormatException($"'{text}' is not supported."); } - public static BoundPeer? ParseOrDefault(string text) => text == string.Empty ? null : Parse(text); + public static BoundPeer? ParseOrDefault(string text) + => text == string.Empty ? null : Parse(text); + + private static string ToString(DnsEndPoint endPoint) => EndPointUtility.ToString(endPoint); } diff --git a/src/common/LibplanetConsole.Seed/ISeedService.cs b/src/common/LibplanetConsole.Seed/ISeedService.cs index ed760513..6801d2d5 100644 --- a/src/common/LibplanetConsole.Seed/ISeedService.cs +++ b/src/common/LibplanetConsole.Seed/ISeedService.cs @@ -1,5 +1,3 @@ -using Libplanet.Crypto; - namespace LibplanetConsole.Seed; public interface ISeedService diff --git a/src/common/LibplanetConsole.Seed/Peer.cs b/src/common/LibplanetConsole.Seed/Peer.cs index c33dbf83..378add01 100644 --- a/src/common/LibplanetConsole.Seed/Peer.cs +++ b/src/common/LibplanetConsole.Seed/Peer.cs @@ -1,8 +1,6 @@ using System.Diagnostics; -using Libplanet.Crypto; using Libplanet.Net.Messages; using Libplanet.Net.Transports; -using LibplanetConsole.Common; namespace LibplanetConsole.Seed; diff --git a/src/common/LibplanetConsole.Seed/PeerCollection.cs b/src/common/LibplanetConsole.Seed/PeerCollection.cs index 5d0108be..95aed356 100644 --- a/src/common/LibplanetConsole.Seed/PeerCollection.cs +++ b/src/common/LibplanetConsole.Seed/PeerCollection.cs @@ -1,8 +1,6 @@ using System.Collections; using System.Collections.Concurrent; -using Libplanet.Crypto; using Libplanet.Net.Transports; -using LibplanetConsole.Common; using Serilog; namespace LibplanetConsole.Seed; diff --git a/src/common/LibplanetConsole.Seed/SeedNode.cs b/src/common/LibplanetConsole.Seed/SeedNode.cs index fd457e22..d0f1a2f0 100644 --- a/src/common/LibplanetConsole.Seed/SeedNode.cs +++ b/src/common/LibplanetConsole.Seed/SeedNode.cs @@ -1,26 +1,15 @@ -using System.ComponentModel; -using System.Net; -using System.Text.Json.Serialization; +using System.Net; using Dasync.Collections; -using Libplanet.Crypto; -using Libplanet.Net; using Libplanet.Net.Messages; using Libplanet.Net.Options; using Libplanet.Net.Transports; using LibplanetConsole.Common; -using LibplanetConsole.Seed.Converters; using Serilog; namespace LibplanetConsole.Seed; public sealed class SeedNode(SeedOptions seedOptions) { - static SeedNode() - { - TypeDescriptor.AddAttributes( - typeof(BoundPeer), new JsonConverterAttribute(typeof(BoundPeerJsonConverter))); - } - public static readonly PrivateKey AppProtocolKey = new("2a15e7deaac09ce631e1faa184efadb175b6b90989cf1faed9dfc321ad1db5ac"); diff --git a/src/common/LibplanetConsole.Seed/SeedOptions.cs b/src/common/LibplanetConsole.Seed/SeedOptions.cs index 2ebf49d7..c25b0f4b 100644 --- a/src/common/LibplanetConsole.Seed/SeedOptions.cs +++ b/src/common/LibplanetConsole.Seed/SeedOptions.cs @@ -1,5 +1,4 @@ using System.Net; -using LibplanetConsole.Common; namespace LibplanetConsole.Seed; diff --git a/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs b/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs index 68b2179f..95078fcc 100644 --- a/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs +++ b/src/console/LibplanetConsole.Console.Example/ExampleNodeContent.cs @@ -1,6 +1,5 @@ using System.ComponentModel.Composition; using System.Text; -using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Common.Services; using LibplanetConsole.Console.Services; diff --git a/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs b/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs index 753fe8a9..ce825d9c 100644 --- a/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs +++ b/src/console/LibplanetConsole.Console.Executable/ApplicationSettings.cs @@ -124,7 +124,7 @@ private static NodeOptions[] GetNodeOptions( { return [.. nodePrivateKeys.Select(key => new NodeOptions { - EndPoint = EndPointUtility.Next(), + EndPoint = EndPointUtility.NextEndPoint(), PrivateKey = key, SeedEndPoint = endPoint, })]; @@ -135,7 +135,7 @@ private static ClientOptions[] GetClientOptions( { return [.. clientPrivateKeys.Select(key => new ClientOptions { - EndPoint = EndPointUtility.Next(), + EndPoint = EndPointUtility.NextEndPoint(), NodeEndPoint = Random(nodeOptions).EndPoint, PrivateKey = key, })]; diff --git a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs index 8da00a7d..47977408 100644 --- a/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs +++ b/src/console/LibplanetConsole.Console.Executable/EntryCommands/InitializeCommand.cs @@ -1,5 +1,4 @@ using System.ComponentModel; -using System.Net; using JSSoft.Commands; using LibplanetConsole.Common; using LibplanetConsole.Common.DataAnnotations; @@ -133,7 +132,7 @@ private NodeOptions[] GetNodeOptions(ref EndPoint? prevEndPoint) var nodeOptionsList = new List(privateKeys.Length); foreach (var privateKey in privateKeys) { - var endPoint = prevEndPoint ?? EndPointUtility.Next(); + var endPoint = prevEndPoint ?? EndPointUtility.NextEndPoint(); var nodeOptions = new NodeOptions { EndPoint = endPoint, @@ -158,7 +157,7 @@ private ClientOptions[] GetClientOptions(ref EndPoint? prevEndPoint) var clientOptionsList = new List(privateKeys.Length); foreach (var privateKey in privateKeys) { - var endPoint = prevEndPoint ?? EndPointUtility.Next(); + var endPoint = prevEndPoint ?? EndPointUtility.NextEndPoint(); var clientOptions = new ClientOptions { EndPoint = endPoint, diff --git a/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs b/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs index fb9a6ebe..eb5d0ab7 100644 --- a/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs +++ b/src/console/LibplanetConsole.Console.Explorer/ExplorerNodeContent.cs @@ -17,7 +17,7 @@ internal sealed class ExplorerNodeContent(INode node, ILogger logger, ExplorerSe { private readonly ILogger _logger = logger; private readonly ExecutionScope _executionScope = new(); - private EndPoint _endPoint = EndPointUtility.Next(); + private EndPoint _endPoint = EndPointUtility.NextEndPoint(); private RemoteService? _remoteService; public event EventHandler? Started; diff --git a/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs b/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs index 2f402a80..d2bf9e1f 100644 --- a/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs +++ b/src/console/LibplanetConsole.Console.Explorer/IExplorerNodeContent.cs @@ -1,4 +1,3 @@ -using LibplanetConsole.Common; using LibplanetConsole.Explorer; namespace LibplanetConsole.Console.Explorer; diff --git a/src/console/LibplanetConsole.Console/ApplicationBase.cs b/src/console/LibplanetConsole.Console/ApplicationBase.cs index e627796d..9332ee53 100644 --- a/src/console/LibplanetConsole.Console/ApplicationBase.cs +++ b/src/console/LibplanetConsole.Console/ApplicationBase.cs @@ -2,7 +2,6 @@ using System.ComponentModel.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using Libplanet.Types.Blocks; using LibplanetConsole.Framework; using LibplanetConsole.Framework.Extensions; using LibplanetConsole.Node; diff --git a/src/console/LibplanetConsole.Console/ApplicationInfo.cs b/src/console/LibplanetConsole.Console/ApplicationInfo.cs index a9536027..c02781bd 100644 --- a/src/console/LibplanetConsole.Console/ApplicationInfo.cs +++ b/src/console/LibplanetConsole.Console/ApplicationInfo.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Console; public readonly record struct ApplicationInfo diff --git a/src/console/LibplanetConsole.Console/ApplicationOptions.cs b/src/console/LibplanetConsole.Console/ApplicationOptions.cs index b6565c67..8997f0c1 100644 --- a/src/console/LibplanetConsole.Console/ApplicationOptions.cs +++ b/src/console/LibplanetConsole.Console/ApplicationOptions.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Console; public sealed record class ApplicationOptions diff --git a/src/console/LibplanetConsole.Console/Client.cs b/src/console/LibplanetConsole.Console/Client.cs index 7a403ac7..38c1ab82 100644 --- a/src/console/LibplanetConsole.Console/Client.cs +++ b/src/console/LibplanetConsole.Console/Client.cs @@ -1,7 +1,6 @@ using System.Collections; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; -using Libplanet.Crypto; using LibplanetConsole.Client; using LibplanetConsole.Client.Services; using LibplanetConsole.Common; @@ -162,7 +161,7 @@ public async Task StartAsync(INode node, CancellationToken cancellationToken) message: "Client is not attached."); _clientInfo = await _remoteService.Service.StartAsync( - node.EndPoint.ToString(), cancellationToken); + EndPointUtility.ToString(node.EndPoint), cancellationToken); _node = node; IsRunning = true; _logger.Debug("Client is started: {Address}", Address); diff --git a/src/console/LibplanetConsole.Console/ClientCollection.cs b/src/console/LibplanetConsole.Console/ClientCollection.cs index 27c8237d..3808dea7 100644 --- a/src/console/LibplanetConsole.Console/ClientCollection.cs +++ b/src/console/LibplanetConsole.Console/ClientCollection.cs @@ -1,7 +1,6 @@ using System.Collections; using System.Collections.Specialized; using System.ComponentModel.Composition; -using Libplanet.Crypto; using LibplanetConsole.Common.Exceptions; using LibplanetConsole.Framework; using Microsoft.Extensions.DependencyInjection; diff --git a/src/console/LibplanetConsole.Console/ClientProcess.cs b/src/console/LibplanetConsole.Console/ClientProcess.cs index e9e7280e..8b20fe0a 100644 --- a/src/console/LibplanetConsole.Console/ClientProcess.cs +++ b/src/console/LibplanetConsole.Console/ClientProcess.cs @@ -22,7 +22,7 @@ public override string[] Arguments { argumentList.Add("run"); argumentList.Add("--end-point"); - argumentList.Add(clientOptions.EndPoint.ToString()); + argumentList.Add(EndPointUtility.ToString(clientOptions.EndPoint)); argumentList.Add("--private-key"); argumentList.Add(PrivateKeyUtility.ToString(clientOptions.PrivateKey)); @@ -35,7 +35,7 @@ public override string[] Arguments if (clientOptions.NodeEndPoint is { } nodeEndPoint) { argumentList.Add("--node-end-point"); - argumentList.Add(nodeEndPoint.ToString()); + argumentList.Add(EndPointUtility.ToString(nodeEndPoint)); } var extendedArguments = GetArguments(serviceProvider: client, obj: client); diff --git a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs index de369926..20b3efe8 100644 --- a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs @@ -56,7 +56,7 @@ public async Task NewAsync( { var clientOptions = new ClientOptions { - EndPoint = EndPointUtility.Next(), + EndPoint = EndPointUtility.NextEndPoint(), PrivateKey = PrivateKeyUtility.ParseOrRandom(privateKey), }; var options = new AddNewClientOptions diff --git a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs index 9569f172..701d8b1f 100644 --- a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs @@ -65,7 +65,7 @@ public async Task NewAsync( { var nodeOptions = new NodeOptions { - EndPoint = EndPointUtility.Next(), + EndPoint = EndPointUtility.NextEndPoint(), PrivateKey = PrivateKeyUtility.ParseOrRandom(privateKey), }; var options = new AddNewNodeOptions diff --git a/src/console/LibplanetConsole.Console/IAddressable.cs b/src/console/LibplanetConsole.Console/IAddressable.cs index 3b7e8dc9..19d3cb34 100644 --- a/src/console/LibplanetConsole.Console/IAddressable.cs +++ b/src/console/LibplanetConsole.Console/IAddressable.cs @@ -1,5 +1,3 @@ -using Libplanet.Crypto; - namespace LibplanetConsole.Console; public interface IAddressable diff --git a/src/console/LibplanetConsole.Console/IApplication.cs b/src/console/LibplanetConsole.Console/IApplication.cs index 66cf60f1..f11097fd 100644 --- a/src/console/LibplanetConsole.Console/IApplication.cs +++ b/src/console/LibplanetConsole.Console/IApplication.cs @@ -1,6 +1,3 @@ -using Libplanet.Crypto; -using LibplanetConsole.Common; - namespace LibplanetConsole.Console; public interface IApplication : IAsyncDisposable, IServiceProvider diff --git a/src/console/LibplanetConsole.Console/IBlockChain.cs b/src/console/LibplanetConsole.Console/IBlockChain.cs index 536cfce8..44cb09c9 100644 --- a/src/console/LibplanetConsole.Console/IBlockChain.cs +++ b/src/console/LibplanetConsole.Console/IBlockChain.cs @@ -1,8 +1,4 @@ using System.Security.Cryptography; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Crypto; -using LibplanetConsole.Common; namespace LibplanetConsole.Console; diff --git a/src/console/LibplanetConsole.Console/IClientCollection.cs b/src/console/LibplanetConsole.Console/IClientCollection.cs index e5419de3..6ebe597a 100644 --- a/src/console/LibplanetConsole.Console/IClientCollection.cs +++ b/src/console/LibplanetConsole.Console/IClientCollection.cs @@ -1,5 +1,4 @@ using System.Collections.Specialized; -using Libplanet.Crypto; namespace LibplanetConsole.Console; diff --git a/src/console/LibplanetConsole.Console/INodeCollection.cs b/src/console/LibplanetConsole.Console/INodeCollection.cs index 0e041482..18831f7f 100644 --- a/src/console/LibplanetConsole.Console/INodeCollection.cs +++ b/src/console/LibplanetConsole.Console/INodeCollection.cs @@ -1,6 +1,4 @@ using System.Collections.Specialized; -using Libplanet.Crypto; -using LibplanetConsole.Common; namespace LibplanetConsole.Console; diff --git a/src/console/LibplanetConsole.Console/Node.BlockChain.cs b/src/console/LibplanetConsole.Console/Node.BlockChain.cs index a63fa6d0..44610d71 100644 --- a/src/console/LibplanetConsole.Console/Node.BlockChain.cs +++ b/src/console/LibplanetConsole.Console/Node.BlockChain.cs @@ -1,10 +1,4 @@ using System.Security.Cryptography; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Crypto; -using Libplanet.Types.Blocks; -using Libplanet.Types.Tx; -using LibplanetConsole.Common; using LibplanetConsole.Node; using LibplanetConsole.Node.Services; diff --git a/src/console/LibplanetConsole.Console/Node.cs b/src/console/LibplanetConsole.Console/Node.cs index 1456a51b..6d848ab1 100644 --- a/src/console/LibplanetConsole.Console/Node.cs +++ b/src/console/LibplanetConsole.Console/Node.cs @@ -1,8 +1,6 @@ using System.Collections; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; -using Bencodex; -using Libplanet.Crypto; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; using LibplanetConsole.Common.Extensions; diff --git a/src/console/LibplanetConsole.Console/NodeCollection.cs b/src/console/LibplanetConsole.Console/NodeCollection.cs index f0da11a5..d05d06c3 100644 --- a/src/console/LibplanetConsole.Console/NodeCollection.cs +++ b/src/console/LibplanetConsole.Console/NodeCollection.cs @@ -1,8 +1,6 @@ using System.Collections; using System.Collections.Specialized; using System.ComponentModel.Composition; -using Libplanet.Crypto; -using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; using LibplanetConsole.Console.Services; using LibplanetConsole.Framework; diff --git a/src/console/LibplanetConsole.Console/NodeOptions.cs b/src/console/LibplanetConsole.Console/NodeOptions.cs index 5eef5c5c..608a2234 100644 --- a/src/console/LibplanetConsole.Console/NodeOptions.cs +++ b/src/console/LibplanetConsole.Console/NodeOptions.cs @@ -1,5 +1,4 @@ using System.ComponentModel; -using System.Net; using System.Text.Json.Serialization; using LibplanetConsole.Common; diff --git a/src/console/LibplanetConsole.Console/NodeProcess.cs b/src/console/LibplanetConsole.Console/NodeProcess.cs index 8c88a8c6..3ab5b90c 100644 --- a/src/console/LibplanetConsole.Console/NodeProcess.cs +++ b/src/console/LibplanetConsole.Console/NodeProcess.cs @@ -21,7 +21,7 @@ public override string[] Arguments { argumentList.Add("run"); argumentList.Add("--end-point"); - argumentList.Add(nodeOptions.EndPoint.ToString()); + argumentList.Add(EndPointUtility.ToString(nodeOptions.EndPoint)); argumentList.Add("--private-key"); argumentList.Add(PrivateKeyUtility.ToString(nodeOptions.PrivateKey)); @@ -40,7 +40,7 @@ public override string[] Arguments if (nodeOptions.SeedEndPoint is { } seedEndPoint) { argumentList.Add("--seed-end-point"); - argumentList.Add(seedEndPoint.ToString()); + argumentList.Add(EndPointUtility.ToString(seedEndPoint)); } var extendedArguments = GetArguments(serviceProvider: node, obj: node); diff --git a/src/console/LibplanetConsole.Console/Repository.cs b/src/console/LibplanetConsole.Console/Repository.cs index be4ef35c..8c7a5ee5 100644 --- a/src/console/LibplanetConsole.Console/Repository.cs +++ b/src/console/LibplanetConsole.Console/Repository.cs @@ -2,7 +2,6 @@ using System.Dynamic; using System.Text; using System.Text.Json.Serialization; -using Libplanet.Common; using LibplanetConsole.Common; using LibplanetConsole.Console.Extensions; using LibplanetConsole.Framework; @@ -221,7 +220,7 @@ private void SaveSettings(string schemaPath, string settingsPath) Schema = schemaRelativePath, Application = new ApplicationSettings { - EndPoint = EndPoint.ToString(), + EndPoint = EndPointUtility.ToString(EndPoint), LogPath = LogPath, LibraryLogPath = LibraryLogPath, }, diff --git a/src/console/LibplanetConsole.Console/Services/SeedService.cs b/src/console/LibplanetConsole.Console/Services/SeedService.cs index 2be64bcf..0188b16f 100644 --- a/src/console/LibplanetConsole.Console/Services/SeedService.cs +++ b/src/console/LibplanetConsole.Console/Services/SeedService.cs @@ -25,12 +25,12 @@ public SeedService(ApplicationBase application) _blocksyncSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = EndPointUtility.Next(), + EndPoint = EndPointUtility.NextEndPoint(), }); _consensusSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = EndPointUtility.Next(), + EndPoint = EndPointUtility.NextEndPoint(), }); } diff --git a/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs b/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs index 1bd55121..c3fda610 100644 --- a/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs +++ b/src/node/LibplanetConsole.Node.Evidence/DuplicateVoteViolator.cs @@ -1,9 +1,7 @@ using System.Numerics; -using Libplanet.Crypto; using Libplanet.Net; using Libplanet.Net.Consensus; using Libplanet.Net.Messages; -using Libplanet.Types.Blocks; using Libplanet.Types.Consensus; using LibplanetConsole.Node.Evidence.Extensions; using Microsoft.Extensions.DependencyInjection; diff --git a/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs b/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs index f2fb8d94..a591db58 100644 --- a/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs +++ b/src/node/LibplanetConsole.Node.Evidence/EvidenceNode.cs @@ -1,8 +1,6 @@ using System.ComponentModel.Composition; using Libplanet.Blockchain; -using Libplanet.Crypto; using Libplanet.Types.Evidence; -using LibplanetConsole.Common; using LibplanetConsole.Evidence; using Microsoft.Extensions.DependencyInjection; diff --git a/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs b/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs index 8fca3aad..615a2346 100644 --- a/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs +++ b/src/node/LibplanetConsole.Node.Example/Commands/ExampleNodeCommand.cs @@ -1,7 +1,6 @@ using System.ComponentModel.Composition; using System.Text; using JSSoft.Commands; -using LibplanetConsole.Common; namespace LibplanetConsole.Node.Example.Commands; diff --git a/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs b/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs index f61f3fec..88798afd 100644 --- a/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs +++ b/src/node/LibplanetConsole.Node.Executable/ApplicationSettings.cs @@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using JSSoft.Commands; -using Libplanet.Common; using LibplanetConsole.Common; using LibplanetConsole.Common.DataAnnotations; using LibplanetConsole.DataAnnotations; diff --git a/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs b/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs index b632f1cf..fbc8f1d8 100644 --- a/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs +++ b/src/node/LibplanetConsole.Node.Executable/EntryCommands/GenesisCommand.cs @@ -1,6 +1,5 @@ using System.ComponentModel; using JSSoft.Commands; -using Libplanet.Common; using LibplanetConsole.Common; using LibplanetConsole.Common.DataAnnotations; using LibplanetConsole.Common.Extensions; diff --git a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs index 56a88982..242ac6b0 100644 --- a/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs +++ b/src/node/LibplanetConsole.Node.Executable/EntryCommands/InitializeCommand.cs @@ -1,6 +1,5 @@ using System.ComponentModel; using JSSoft.Commands; -using Libplanet.Common; using LibplanetConsole.Common; using LibplanetConsole.Common.DataAnnotations; using LibplanetConsole.Common.Extensions; diff --git a/src/node/LibplanetConsole.Node/ActionProvider.cs b/src/node/LibplanetConsole.Node/ActionProvider.cs index d060a667..533d5d9e 100644 --- a/src/node/LibplanetConsole.Node/ActionProvider.cs +++ b/src/node/LibplanetConsole.Node/ActionProvider.cs @@ -1,12 +1,7 @@ using System.Collections.Immutable; using System.Numerics; using System.Reflection; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Action.Loader; -using Libplanet.Crypto; using Libplanet.Types.Consensus; -using LibplanetConsole.Common; using LibplanetConsole.Common.Actions; using LibplanetConsole.Framework; diff --git a/src/node/LibplanetConsole.Node/ApplicationBase.cs b/src/node/LibplanetConsole.Node/ApplicationBase.cs index 35849e61..c41f6412 100644 --- a/src/node/LibplanetConsole.Node/ApplicationBase.cs +++ b/src/node/LibplanetConsole.Node/ApplicationBase.cs @@ -1,7 +1,6 @@ using System.Collections; using System.ComponentModel.Composition; using System.Diagnostics; -using LibplanetConsole.Common; using LibplanetConsole.Framework; using LibplanetConsole.Framework.Extensions; using LibplanetConsole.Node.Services; diff --git a/src/node/LibplanetConsole.Node/ApplicationInfo.cs b/src/node/LibplanetConsole.Node/ApplicationInfo.cs index 71fa9069..54df3b18 100644 --- a/src/node/LibplanetConsole.Node/ApplicationInfo.cs +++ b/src/node/LibplanetConsole.Node/ApplicationInfo.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Node; public readonly record struct ApplicationInfo diff --git a/src/node/LibplanetConsole.Node/ApplicationOptions.cs b/src/node/LibplanetConsole.Node/ApplicationOptions.cs index d10e5abd..835bfc1a 100644 --- a/src/node/LibplanetConsole.Node/ApplicationOptions.cs +++ b/src/node/LibplanetConsole.Node/ApplicationOptions.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Node; public sealed record class ApplicationOptions diff --git a/src/node/LibplanetConsole.Node/BlockChainUtility.cs b/src/node/LibplanetConsole.Node/BlockChainUtility.cs index 033b4686..4bba5468 100644 --- a/src/node/LibplanetConsole.Node/BlockChainUtility.cs +++ b/src/node/LibplanetConsole.Node/BlockChainUtility.cs @@ -1,11 +1,9 @@ -using Libplanet.Action; using Libplanet.Blockchain; using Libplanet.Blockchain.Policies; using Libplanet.Blockchain.Renderers; using Libplanet.RocksDBStore; using Libplanet.Store; using Libplanet.Store.Trie; -using Libplanet.Types.Blocks; namespace LibplanetConsole.Node; diff --git a/src/node/LibplanetConsole.Node/BlockUtility.cs b/src/node/LibplanetConsole.Node/BlockUtility.cs index b8248f08..ff894645 100644 --- a/src/node/LibplanetConsole.Node/BlockUtility.cs +++ b/src/node/LibplanetConsole.Node/BlockUtility.cs @@ -1,12 +1,5 @@ using System.Collections.Immutable; using System.Security.Cryptography; -using Bencodex; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Common; -using Libplanet.Crypto; -using Libplanet.Types.Blocks; -using Libplanet.Types.Tx; using LibplanetConsole.Common; namespace LibplanetConsole.Node; diff --git a/src/node/LibplanetConsole.Node/IActionProvider.cs b/src/node/LibplanetConsole.Node/IActionProvider.cs index c827dcfb..72d2342c 100644 --- a/src/node/LibplanetConsole.Node/IActionProvider.cs +++ b/src/node/LibplanetConsole.Node/IActionProvider.cs @@ -1,7 +1,4 @@ using System.Collections.Immutable; -using Libplanet.Action; -using Libplanet.Action.Loader; -using LibplanetConsole.Common; namespace LibplanetConsole.Node; diff --git a/src/node/LibplanetConsole.Node/IBlockChain.cs b/src/node/LibplanetConsole.Node/IBlockChain.cs index ee49b537..ed07bb43 100644 --- a/src/node/LibplanetConsole.Node/IBlockChain.cs +++ b/src/node/LibplanetConsole.Node/IBlockChain.cs @@ -1,8 +1,4 @@ using System.Security.Cryptography; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Crypto; -using LibplanetConsole.Common; namespace LibplanetConsole.Node; diff --git a/src/node/LibplanetConsole.Node/INode.cs b/src/node/LibplanetConsole.Node/INode.cs index 0b77bdb7..72aefb88 100644 --- a/src/node/LibplanetConsole.Node/INode.cs +++ b/src/node/LibplanetConsole.Node/INode.cs @@ -1,5 +1,3 @@ -using Libplanet.Action; -using Libplanet.Crypto; using LibplanetConsole.Common; namespace LibplanetConsole.Node; diff --git a/src/node/LibplanetConsole.Node/Node.BlockChain.cs b/src/node/LibplanetConsole.Node/Node.BlockChain.cs index 5b66fa27..8147f98a 100644 --- a/src/node/LibplanetConsole.Node/Node.BlockChain.cs +++ b/src/node/LibplanetConsole.Node/Node.BlockChain.cs @@ -1,12 +1,5 @@ using System.Security.Cryptography; using System.Text; -using Bencodex; -using Bencodex.Types; -using Libplanet.Action; -using Libplanet.Common; -using Libplanet.Crypto; -using Libplanet.Types.Blocks; -using Libplanet.Types.Tx; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index 5d5f5989..69a1f72f 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -1,18 +1,12 @@ using System.Collections.Concurrent; using System.Security; using System.Security.Cryptography; -using Bencodex.Types; -using Libplanet.Action; using Libplanet.Blockchain; using Libplanet.Blockchain.Renderers; -using Libplanet.Common; -using Libplanet.Crypto; using Libplanet.Net; using Libplanet.Net.Consensus; using Libplanet.Net.Options; using Libplanet.Net.Transports; -using Libplanet.Types.Blocks; -using Libplanet.Types.Tx; using LibplanetConsole.Common; using LibplanetConsole.Common.Exceptions; using LibplanetConsole.Common.Extensions; @@ -155,8 +149,8 @@ public async Task StartAsync(CancellationToken cancellationToken) var privateKey = PrivateKeyUtility.FromSecureString(_privateKey); var appProtocolVersion = _appProtocolVersion; var storePath = _storePath; - var blocksyncEndPoint = _blocksyncEndPoint ?? EndPointUtility.Next(); - var consensusEndPoint = _consensusEndPoint ?? EndPointUtility.Next(); + var blocksyncEndPoint = _blocksyncEndPoint ?? EndPointUtility.NextEndPoint(); + var consensusEndPoint = _consensusEndPoint ?? EndPointUtility.NextEndPoint(); var blocksyncSeedPeer = seedInfo.BlocksyncSeedPeer; var consensusSeedPeer = seedInfo.ConsensusSeedPeer; var swarmTransport @@ -350,7 +344,6 @@ private void UpdateNodeInfo() GenesisHash = BlockChain.Genesis.Hash, TipHash = BlockChain.Tip.Hash, IsRunning = IsRunning, - // Peers = [.. Peers], }; } diff --git a/src/node/LibplanetConsole.Node/PeerUtility.cs b/src/node/LibplanetConsole.Node/PeerUtility.cs deleted file mode 100644 index 312e60da..00000000 --- a/src/node/LibplanetConsole.Node/PeerUtility.cs +++ /dev/null @@ -1,15 +0,0 @@ -// using System.Net; -// using Libplanet.Crypto; -// using Libplanet.Net; -// using LibplanetConsole.Common; - -// namespace LibplanetConsole.Node; - -// internal static class PeerUtility -// { -// public static BoundPeer ToBoundPeer(AppPeer peer) -// => new((PublicKey)peer.PublicKey, (DnsEndPoint)peer.EndPoint); - -// public static AppPeer ToAppPeer(BoundPeer boundPeer) -// => new((PublicKey)boundPeer.PublicKey, (EndPoint)boundPeer.EndPoint); -// } diff --git a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs index ebd8f53b..8b926ce9 100644 --- a/src/node/LibplanetConsole.Node/Services/BlockChainService.cs +++ b/src/node/LibplanetConsole.Node/Services/BlockChainService.cs @@ -1,9 +1,5 @@ using System.ComponentModel.Composition; using System.Security.Cryptography; -using Bencodex; -using Libplanet.Crypto; -using Libplanet.Types.Tx; -using LibplanetConsole.Common; using LibplanetConsole.Common.Services; namespace LibplanetConsole.Node.Services; diff --git a/src/node/LibplanetConsole.Node/Services/SeedService.cs b/src/node/LibplanetConsole.Node/Services/SeedService.cs index 4c418765..84e9aac3 100644 --- a/src/node/LibplanetConsole.Node/Services/SeedService.cs +++ b/src/node/LibplanetConsole.Node/Services/SeedService.cs @@ -1,8 +1,8 @@ using System.ComponentModel.Composition; -using LibplanetConsole.Common; using LibplanetConsole.Common.Services; using LibplanetConsole.Framework; using LibplanetConsole.Seed; +using static LibplanetConsole.Common.EndPointUtility; namespace LibplanetConsole.Node.Services; @@ -53,17 +53,17 @@ async ValueTask IAsyncDisposable.DisposeAsync() async Task IApplicationService.InitializeAsync( IServiceProvider serviceProvider, CancellationToken cancellationToken) { - if (application.Info.SeedEndPoint == application.Info.EndPoint) + if (CompareEndPoint(application.Info.SeedEndPoint, application.Info.EndPoint) is true) { _blocksyncSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = EndPointUtility.Next(), + EndPoint = NextEndPoint(), }); _consensusSeedNode = new SeedNode(new() { PrivateKey = _seedNodePrivateKey, - EndPoint = EndPointUtility.Next(), + EndPoint = NextEndPoint(), }); await _blocksyncSeedNode.StartAsync(cancellationToken); await _consensusSeedNode.StartAsync(cancellationToken); diff --git a/src/shared/LibplanetConsole.Client/ClientInfo.cs b/src/shared/LibplanetConsole.Client/ClientInfo.cs index c3f9b292..e60235dc 100644 --- a/src/shared/LibplanetConsole.Client/ClientInfo.cs +++ b/src/shared/LibplanetConsole.Client/ClientInfo.cs @@ -1,6 +1,3 @@ -using Libplanet.Crypto; -using Libplanet.Types.Blocks; - namespace LibplanetConsole.Client; public readonly record struct ClientInfo diff --git a/src/shared/LibplanetConsole.Client/Services/IClientService.cs b/src/shared/LibplanetConsole.Client/Services/IClientService.cs index 9154f825..9530cbd4 100644 --- a/src/shared/LibplanetConsole.Client/Services/IClientService.cs +++ b/src/shared/LibplanetConsole.Client/Services/IClientService.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Client.Services; public interface IClientService diff --git a/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs b/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs index 1dd228a7..2d9a7baf 100644 --- a/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs +++ b/src/shared/LibplanetConsole.Evidence/EvidenceInfo.cs @@ -1,5 +1,4 @@ using Libplanet.Types.Evidence; -using LibplanetConsole.Common; namespace LibplanetConsole.Evidence; diff --git a/src/shared/LibplanetConsole.Evidence/TestEvidence.cs b/src/shared/LibplanetConsole.Evidence/TestEvidence.cs index d7359d9a..2698f878 100644 --- a/src/shared/LibplanetConsole.Evidence/TestEvidence.cs +++ b/src/shared/LibplanetConsole.Evidence/TestEvidence.cs @@ -1,6 +1,4 @@ using System.Globalization; -using Bencodex.Types; -using Libplanet.Crypto; using Libplanet.Types.Evidence; namespace LibplanetConsole.Evidence; diff --git a/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs b/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs index 96ece7c2..d688c09e 100644 --- a/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs +++ b/src/shared/LibplanetConsole.Example/Services/IExampleNodeCallback.cs @@ -1,5 +1,3 @@ -using Libplanet.Crypto; - namespace LibplanetConsole.Example.Services; public interface IExampleNodeCallback diff --git a/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs b/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs index 833c5f3e..6fcfe7ac 100644 --- a/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs +++ b/src/shared/LibplanetConsole.Example/Services/IExampleNodeService.cs @@ -1,5 +1,3 @@ -using Libplanet.Crypto; - namespace LibplanetConsole.Example.Services; public interface IExampleNodeService diff --git a/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs b/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs index 6a281efa..bda107ea 100644 --- a/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs +++ b/src/shared/LibplanetConsole.Explorer/ExplorerInfo.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Explorer; public readonly record struct ExplorerInfo diff --git a/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs b/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs index 480853e1..e29ef02a 100644 --- a/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs +++ b/src/shared/LibplanetConsole.Explorer/ExplorerOptions.cs @@ -1,5 +1,3 @@ -using LibplanetConsole.Common; - namespace LibplanetConsole.Explorer; public sealed record class ExplorerOptions diff --git a/src/shared/LibplanetConsole.Node/ActionInfo.cs b/src/shared/LibplanetConsole.Node/ActionInfo.cs index e5355b66..8c2aea27 100644 --- a/src/shared/LibplanetConsole.Node/ActionInfo.cs +++ b/src/shared/LibplanetConsole.Node/ActionInfo.cs @@ -1,6 +1,3 @@ -using Bencodex.Types; -using LibplanetConsole.Common; - namespace LibplanetConsole.Node; public readonly record struct ActionInfo diff --git a/src/shared/LibplanetConsole.Node/BlockInfo.cs b/src/shared/LibplanetConsole.Node/BlockInfo.cs index 78211573..e5800f3e 100644 --- a/src/shared/LibplanetConsole.Node/BlockInfo.cs +++ b/src/shared/LibplanetConsole.Node/BlockInfo.cs @@ -1,6 +1,3 @@ -using Libplanet.Crypto; -using LibplanetConsole.Common; - namespace LibplanetConsole.Node; public readonly partial record struct BlockInfo diff --git a/src/shared/LibplanetConsole.Node/BlockUtility.cs b/src/shared/LibplanetConsole.Node/BlockUtility.cs index ef98677e..13f07ab2 100644 --- a/src/shared/LibplanetConsole.Node/BlockUtility.cs +++ b/src/shared/LibplanetConsole.Node/BlockUtility.cs @@ -1,7 +1,3 @@ -using Bencodex; -using Bencodex.Types; -using Libplanet.Types.Blocks; - namespace LibplanetConsole.Node; public static partial class BlockUtility diff --git a/src/shared/LibplanetConsole.Node/NodeInfo.cs b/src/shared/LibplanetConsole.Node/NodeInfo.cs index 7f6a420e..0c2337c9 100644 --- a/src/shared/LibplanetConsole.Node/NodeInfo.cs +++ b/src/shared/LibplanetConsole.Node/NodeInfo.cs @@ -1,7 +1,3 @@ -using Libplanet.Crypto; -// using Libplanet.Net; -using LibplanetConsole.Common; - namespace LibplanetConsole.Node; public readonly record struct NodeInfo @@ -22,14 +18,11 @@ public readonly record struct NodeInfo public bool IsRunning { get; init; } - // public BoundPeer[] Peers { get; init; } - public static NodeInfo Empty { get; } = new NodeInfo { ProcessId = -1, AppProtocolVersion = string.Empty, SwarmEndPoint = string.Empty, ConsensusEndPoint = string.Empty, - // Peers = [], }; } diff --git a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs index 5b5ef3c7..3012d2ed 100644 --- a/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs +++ b/src/shared/LibplanetConsole.Node/Services/IBlockChainService.cs @@ -1,6 +1,4 @@ using System.Security.Cryptography; -using Libplanet.Crypto; -using LibplanetConsole.Common; namespace LibplanetConsole.Node.Services; diff --git a/src/shared/LibplanetConsole.Node/TransactionInfo.cs b/src/shared/LibplanetConsole.Node/TransactionInfo.cs index 6ea061f2..f77cc345 100644 --- a/src/shared/LibplanetConsole.Node/TransactionInfo.cs +++ b/src/shared/LibplanetConsole.Node/TransactionInfo.cs @@ -1,6 +1,3 @@ -using Libplanet.Crypto; -using LibplanetConsole.Common; - namespace LibplanetConsole.Node; public readonly partial record struct TransactionInfo diff --git a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs b/test/LibplanetConsole.Common.Tests/AppPeerTest.cs deleted file mode 100644 index 203a9c86..00000000 --- a/test/LibplanetConsole.Common.Tests/AppPeerTest.cs +++ /dev/null @@ -1,14 +0,0 @@ -// namespace LibplanetConsole.Common.Tests; - -// public class AppPeerTest -// { -// [Fact] -// public void Test1() -// { -// var publicKey = new PrivateKey().PublicKey; -// var endPoint = new EndPoint("localhost", 12345); -// var peer = new AppPeer(publicKey, endPoint); -// Assert.Equal(publicKey, peer.PublicKey); -// Assert.Equal(endPoint, peer.EndPoint); -// } -// } diff --git a/test/LibplanetConsole.Common.Tests/GlobalUsings.cs b/test/LibplanetConsole.Common.Tests/GlobalUsings.cs deleted file mode 100644 index c802f448..00000000 --- a/test/LibplanetConsole.Common.Tests/GlobalUsings.cs +++ /dev/null @@ -1 +0,0 @@ -global using Xunit; From 775f527e2bed4bed8def5cff5f6f6d4d11257b02 Mon Sep 17 00:00:00 2001 From: s2quake Date: Mon, 30 Sep 2024 19:48:58 +0900 Subject: [PATCH 9/9] feat: Add ToShortString method for Address and BlockHash --- .../Tracers/BlockChainEventTracer.cs | 3 ++- .../LibplanetConsole.Client/Commands/TxCommand.cs | 3 ++- .../Extensions/AddressExtensions.cs | 3 +++ .../Extensions/BlockHashExtensions.cs | 7 +++++++ .../Tracers/ClientCollectionEventTracer.cs | 12 ++++++------ .../Tracers/NodeCollectionEventTracer.cs | 15 ++++++++------- src/console/LibplanetConsole.Console/Client.cs | 2 +- .../Commands/ClientCommand.cs | 2 +- .../Commands/NodeCommand.cs | 2 +- .../Commands/TxCommand.cs | 5 +++-- src/console/LibplanetConsole.Console/Node.cs | 2 +- .../Tracers/BlockChainEventTracer.cs | 3 ++- .../LibplanetConsole.Node/Commands/TxCommand.cs | 3 ++- src/node/LibplanetConsole.Node/Node.cs | 2 +- 14 files changed, 40 insertions(+), 24 deletions(-) create mode 100644 src/common/LibplanetConsole.Common/Extensions/BlockHashExtensions.cs diff --git a/src/client/LibplanetConsole.Client.Executable/Tracers/BlockChainEventTracer.cs b/src/client/LibplanetConsole.Client.Executable/Tracers/BlockChainEventTracer.cs index 9a3f38b1..bd2f67ef 100644 --- a/src/client/LibplanetConsole.Client.Executable/Tracers/BlockChainEventTracer.cs +++ b/src/client/LibplanetConsole.Client.Executable/Tracers/BlockChainEventTracer.cs @@ -27,7 +27,8 @@ private void BlockChain_BlockAppended(object? sender, BlockEventArgs e) var blockInfo = e.BlockInfo; var hash = blockInfo.Hash; var miner = blockInfo.Miner; - var message = $"Block #{blockInfo.Height} '{hash:S}' Appended by '{miner:S}'"; + var message = $"Block #{blockInfo.Height} '{hash.ToShortString()}' " + + $"Appended by '{miner.ToShortString()}'"; Console.Out.WriteColoredLine(message, TerminalColorType.BrightGreen); } } diff --git a/src/client/LibplanetConsole.Client/Commands/TxCommand.cs b/src/client/LibplanetConsole.Client/Commands/TxCommand.cs index 449789f8..f81bcd02 100644 --- a/src/client/LibplanetConsole.Client/Commands/TxCommand.cs +++ b/src/client/LibplanetConsole.Client/Commands/TxCommand.cs @@ -1,6 +1,7 @@ using System.ComponentModel.Composition; using JSSoft.Commands; using LibplanetConsole.Common.Actions; +using LibplanetConsole.Common.Extensions; namespace LibplanetConsole.Client.Commands; @@ -19,6 +20,6 @@ protected override async Task OnExecuteAsync(CancellationToken cancellationToken Value = Text, }; await blockChain.SendTransactionAsync([action], cancellationToken); - await Out.WriteLineAsync($"{client.Address:S}: {Text}"); + await Out.WriteLineAsync($"{client.Address.ToShortString()}: {Text}"); } } diff --git a/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs index 586169d3..eef750ea 100644 --- a/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs +++ b/src/common/LibplanetConsole.Common/Extensions/AddressExtensions.cs @@ -20,4 +20,7 @@ static byte[] GetHahsed(byte[] key, byte[] bytes) public static Address Derive(this Address @this, string key) => Derive(@this, Encoding.UTF8.GetBytes(key)); + + public static string ToShortString(this Address @this) + => @this.ToString()[..8]; } diff --git a/src/common/LibplanetConsole.Common/Extensions/BlockHashExtensions.cs b/src/common/LibplanetConsole.Common/Extensions/BlockHashExtensions.cs new file mode 100644 index 00000000..63d94fea --- /dev/null +++ b/src/common/LibplanetConsole.Common/Extensions/BlockHashExtensions.cs @@ -0,0 +1,7 @@ +namespace LibplanetConsole.Common.Extensions; + +public static class BlockHashExtensions +{ + public static string ToShortString(this BlockHash @this) + => @this.ToString()[..8]; +} diff --git a/src/console/LibplanetConsole.Console.Executable/Tracers/ClientCollectionEventTracer.cs b/src/console/LibplanetConsole.Console.Executable/Tracers/ClientCollectionEventTracer.cs index a19cf337..f8ebb3e3 100644 --- a/src/console/LibplanetConsole.Console.Executable/Tracers/ClientCollectionEventTracer.cs +++ b/src/console/LibplanetConsole.Console.Executable/Tracers/ClientCollectionEventTracer.cs @@ -57,7 +57,7 @@ private void Clients_CollectionChanged(object? sender, NotifyCollectionChangedEv { foreach (IClient client in e.NewItems!) { - var message = $"Client created: {client.Address:S}"; + var message = $"Client created: {client.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); AttachEvent(client); @@ -67,7 +67,7 @@ private void Clients_CollectionChanged(object? sender, NotifyCollectionChangedEv { foreach (IClient client in e.OldItems!) { - var message = $"Client deleted: {client.Address:S}"; + var message = $"Client deleted: {client.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); DetachEvent(client); @@ -79,7 +79,7 @@ private void Client_Attached(object? sender, EventArgs e) { if (sender is IClient client) { - var message = $"Client attached: {client.Address:S}"; + var message = $"Client attached: {client.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } @@ -89,7 +89,7 @@ private void Client_Detached(object? sender, EventArgs e) { if (sender is IClient client) { - var message = $"Client detached: {client.Address:S}"; + var message = $"Client detached: {client.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } @@ -99,7 +99,7 @@ private void Client_Started(object? sender, EventArgs e) { if (sender is IClient client) { - var message = $"Client started: {client.Address:S}"; + var message = $"Client started: {client.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } @@ -109,7 +109,7 @@ private void Client_Stopped(object? sender, EventArgs e) { if (sender is IClient client) { - var message = $"Client stopped: {client.Address:S}"; + var message = $"Client stopped: {client.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } diff --git a/src/console/LibplanetConsole.Console.Executable/Tracers/NodeCollectionEventTracer.cs b/src/console/LibplanetConsole.Console.Executable/Tracers/NodeCollectionEventTracer.cs index 8b08950f..184e5ddf 100644 --- a/src/console/LibplanetConsole.Console.Executable/Tracers/NodeCollectionEventTracer.cs +++ b/src/console/LibplanetConsole.Console.Executable/Tracers/NodeCollectionEventTracer.cs @@ -82,7 +82,7 @@ private void Nodes_CollectionChanged(object? sender, NotifyCollectionChangedEven { foreach (INode node in e.NewItems!) { - var message = $"Node created: {node.Address:S}"; + var message = $"Node created: {node.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); AttachEvent(node); @@ -92,7 +92,7 @@ private void Nodes_CollectionChanged(object? sender, NotifyCollectionChangedEven { foreach (INode node in e.OldItems!) { - var message = $"Node deleted: {node.Address:S}"; + var message = $"Node deleted: {node.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); DetachEvent(node); @@ -105,7 +105,8 @@ private void BlockChain_BlockAppended(object? sender, BlockEventArgs e) var blockInfo = e.BlockInfo; var hash = blockInfo.Hash; var miner = blockInfo.Miner; - var message = $"Block #{blockInfo.Height} '{hash:S}' Appended by '{miner:S}'"; + var message = $"Block #{blockInfo.Height} '{hash.ToShortString()}' " + + $"Appended by '{miner.ToShortString()}'"; System.Console.Out.WriteColoredLine(message, TerminalColorType.BrightBlue); } @@ -113,7 +114,7 @@ private void Node_Attached(object? sender, EventArgs e) { if (sender is INode node) { - var message = $"Node attached: {node.Address:S}"; + var message = $"Node attached: {node.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } @@ -123,7 +124,7 @@ private void Node_Detached(object? sender, EventArgs e) { if (sender is INode node) { - var message = $"Node detached: {node.Address:S}"; + var message = $"Node detached: {node.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } @@ -133,7 +134,7 @@ private void Node_Started(object? sender, EventArgs e) { if (sender is INode node) { - var message = $"Node started: {node.Address:S}"; + var message = $"Node started: {node.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } @@ -143,7 +144,7 @@ private void Node_Stopped(object? sender, EventArgs e) { if (sender is INode node) { - var message = $"Node stopped: {node.Address:S}"; + var message = $"Node stopped: {node.Address.ToShortString()}"; var colorType = TerminalColorType.BrightBlue; System.Console.Out.WriteColoredLine(message, colorType); } diff --git a/src/console/LibplanetConsole.Console/Client.cs b/src/console/LibplanetConsole.Console/Client.cs index 38c1ab82..4f4fb2d5 100644 --- a/src/console/LibplanetConsole.Console/Client.cs +++ b/src/console/LibplanetConsole.Console/Client.cs @@ -110,7 +110,7 @@ public Client(ApplicationBase application, ClientOptions clientOptions) } } - public override string ToString() => $"{Address:S}: {EndPoint}"; + public override string ToString() => $"{Address.ToShortString()}: {EndPoint}"; public byte[] Sign(object obj) => _clientOptions.PrivateKey.Sign(obj); diff --git a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs index 20b3efe8..654fa352 100644 --- a/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/ClientCommand.cs @@ -165,7 +165,7 @@ public async Task TxAsync( var address = Address; var client = application.GetClient(address); await client.SendTransactionAsync(text, cancellationToken); - await Out.WriteLineAsync($"{client.Address:S}: {text}"); + await Out.WriteLineAsync($"{client.Address.ToShortString()}: {text}"); } private static TerminalColorType? GetForeground(IClient client, bool isCurrent) diff --git a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs index 701d8b1f..2587998b 100644 --- a/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/NodeCommand.cs @@ -153,7 +153,7 @@ public async Task TxAsync( var node = application.GetNode(address); var action = new StringAction { Value = text }; await node.SendTransactionAsync([action], cancellationToken); - await Out.WriteLineAsync($"{node.Address:S}: {text}"); + await Out.WriteLineAsync($"{node.Address.ToShortString()}: {text}"); } private static TerminalColorType? GetForeground(INode node, bool isCurrent) diff --git a/src/console/LibplanetConsole.Console/Commands/TxCommand.cs b/src/console/LibplanetConsole.Console/Commands/TxCommand.cs index c514cf32..9ef326da 100644 --- a/src/console/LibplanetConsole.Console/Commands/TxCommand.cs +++ b/src/console/LibplanetConsole.Console/Commands/TxCommand.cs @@ -1,6 +1,7 @@ using System.ComponentModel.Composition; using JSSoft.Commands; using LibplanetConsole.Common.Actions; +using LibplanetConsole.Common.Extensions; using Microsoft.Extensions.DependencyInjection; namespace LibplanetConsole.Console.Commands; @@ -25,12 +26,12 @@ protected override async Task OnExecuteAsync(CancellationToken cancellationToken var blockChain = node.GetRequiredService(); var action = new StringAction { Value = text }; await blockChain.SendTransactionAsync([action], cancellationToken); - await Out.WriteLineAsync($"{node.Address:S}: {text}"); + await Out.WriteLineAsync($"{node.Address.ToShortString()}: {text}"); } else if (addressable is IClient client) { await client.SendTransactionAsync(text, cancellationToken); - await Out.WriteLineAsync($"{client.Address:S}: {text}"); + await Out.WriteLineAsync($"{client.Address.ToShortString()}: {text}"); } else { diff --git a/src/console/LibplanetConsole.Console/Node.cs b/src/console/LibplanetConsole.Console/Node.cs index 6d848ab1..f5be52eb 100644 --- a/src/console/LibplanetConsole.Console/Node.cs +++ b/src/console/LibplanetConsole.Console/Node.cs @@ -116,7 +116,7 @@ public EndPoint ConsensusEndPoint } } - public override string ToString() => $"{Address:S}: {EndPoint}"; + public override string ToString() => $"{Address.ToShortString()}: {EndPoint}"; public byte[] Sign(object obj) => _nodeOptions.PrivateKey.Sign(obj); diff --git a/src/node/LibplanetConsole.Node.Executable/Tracers/BlockChainEventTracer.cs b/src/node/LibplanetConsole.Node.Executable/Tracers/BlockChainEventTracer.cs index d67e9bef..e878c28f 100644 --- a/src/node/LibplanetConsole.Node.Executable/Tracers/BlockChainEventTracer.cs +++ b/src/node/LibplanetConsole.Node.Executable/Tracers/BlockChainEventTracer.cs @@ -27,7 +27,8 @@ private void Node_BlockAppended(object? sender, BlockEventArgs e) var blockInfo = e.BlockInfo; var hash = blockInfo.Hash; var miner = blockInfo.Miner; - var message = $"Block #{blockInfo.Height} '{hash:S}' Appended by '{miner:S}'"; + var message = $"Block #{blockInfo.Height} '{hash.ToShortString()}' " + + $"Appended by '{miner.ToShortString()}'"; Console.Out.WriteColoredLine(message, TerminalColorType.BrightGreen); } } diff --git a/src/node/LibplanetConsole.Node/Commands/TxCommand.cs b/src/node/LibplanetConsole.Node/Commands/TxCommand.cs index e3b40cfc..668e6e5c 100644 --- a/src/node/LibplanetConsole.Node/Commands/TxCommand.cs +++ b/src/node/LibplanetConsole.Node/Commands/TxCommand.cs @@ -1,6 +1,7 @@ using System.ComponentModel.Composition; using JSSoft.Commands; using LibplanetConsole.Common.Actions; +using LibplanetConsole.Common.Extensions; namespace LibplanetConsole.Node.Commands; @@ -19,6 +20,6 @@ protected override async Task OnExecuteAsync(CancellationToken cancellationToken Value = Text, }; await blockChain.AddTransactionAsync([action], cancellationToken); - await Out.WriteLineAsync($"{node.Address:S}: {Text}"); + await Out.WriteLineAsync($"{node.Address.ToShortString()}: {Text}"); } } diff --git a/src/node/LibplanetConsole.Node/Node.cs b/src/node/LibplanetConsole.Node/Node.cs index 69a1f72f..cee2acdc 100644 --- a/src/node/LibplanetConsole.Node/Node.cs +++ b/src/node/LibplanetConsole.Node/Node.cs @@ -114,7 +114,7 @@ public EndPoint SeedEndPoint } } - public override string ToString() => $"{Address:S}"; + public override string ToString() => $"{Address.ToShortString()}"; public object? GetService(Type serviceType) {