Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
riemannulus authored and s2quake committed Aug 23, 2024
1 parent 91f3f12 commit 1456b4b
Show file tree
Hide file tree
Showing 25 changed files with 291 additions and 123 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.40.0"/>
<PackageReference Include="Grpc.AspNetCore.Server.Reflection" Version="2.64.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
Expand All @@ -21,6 +22,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\Libplanet.Crypto.Secp256k1\Libplanet.Crypto.Secp256k1.csproj" />
<ProjectReference Include="..\Libplanet.Node.Extensions\Libplanet.Node.Extensions.csproj" />
<ProjectReference Include="..\Libplanet.Node\Libplanet.Node.csproj" />
<ProjectReference Include="..\Libplanet.Node.Swagger\Libplanet.Node.Swagger.csproj" />
Expand Down
90 changes: 90 additions & 0 deletions sdk/node/Libplanet.Node.Executable/PluginLoader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System.Reflection;
using Libplanet.Action;
using Libplanet.Action.Loader;
using Libplanet.Blockchain.Policies;

namespace Libplanet.Node.API;

public static class PluginLoader
{
public static IActionLoader LoadActionLoader(string relativePath, string typeName)
{
Assembly assembly = LoadPlugin(relativePath);
IEnumerable<IActionLoader> loaders = Create<IActionLoader>(assembly);
foreach (IActionLoader loader in loaders)
{
if (loader.GetType().FullName == typeName)
{
return loader;
}
}

throw new ApplicationException(
$"Can't find {typeName} in {assembly} from {assembly.Location}. " +
$"Available types: {string
.Join(",", loaders.Select(x => x.GetType().FullName))}");
}

public static IPolicyActionsRegistry LoadPolicyActionRegistry(
string relativePath,
string typeName)
{
Assembly assembly = LoadPlugin(relativePath);
IEnumerable<IPolicyActionsRegistry> policies = Create<IPolicyActionsRegistry>(assembly);
foreach (IPolicyActionsRegistry policy in policies)
{
if (policy.GetType().FullName == typeName)
{
return policy;
}
}

throw new ApplicationException(
$"Can't find {typeName} in {assembly} from {assembly.Location}. " +
$"Available types: {string
.Join(",", policies.Select(x => x.GetType().FullName))}");
}

private static IEnumerable<T> Create<T>(Assembly assembly)
where T : class
{
int count = 0;

foreach (Type type in assembly.GetTypes())
{
if (typeof(T).IsAssignableFrom(type))
{
T result = Activator.CreateInstance(type) as T;
if (result != null)
{
count++;
yield return result;
}
}
}

if (count == 0)
{
string availableTypes = string.Join(",", assembly.GetTypes().Select(t => t.FullName));
throw new ApplicationException(
$"Can't find any type which implements ICommand in {assembly} from {assembly.Location}.\n" +
$"Available types: {availableTypes}");
}
}

private static Assembly LoadPlugin(string relativePath)
{
// Navigate up to the solution root
string root = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(typeof(Program).Assembly.Location)))))));

string pluginLocation = Path.GetFullPath(Path.Combine(root, relativePath.Replace('\\', Path.DirectorySeparatorChar)));
Console.WriteLine($"Loading commands from: {pluginLocation}");
PluginLoadContext loadContext = new PluginLoadContext(pluginLocation);
return loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)));
}
}
25 changes: 25 additions & 0 deletions sdk/node/Libplanet.Node.Executable/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Libplanet.Node.Options.Schema;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Serilog;
using Serilog.Events;

var builder = WebHost.CreateDefaultBuilder(args);
var assemblies = new string[]
Expand All @@ -14,6 +16,16 @@
builder.ConfigureLogging(logging =>
{
logging.AddConsole();

// Logging setting
var loggerConfig = new LoggerConfiguration();
loggerConfig = loggerConfig.MinimumLevel.Information();
loggerConfig = loggerConfig
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console();

Log.Logger = loggerConfig.CreateLogger();
});
builder.ConfigureKestrel((context, options) =>
{
Expand All @@ -26,6 +38,19 @@
});
builder.ConfigureServices((context, services) =>
{
// string pluginPath = "/Users/bin_bash_shell/Workspaces/planetarium/NineChronicles/" +
// "lib9c/Lib9c.NCActionLoader/bin/Debug/net6.0/Lib9c.NCActionLoader.dll";
// string actionLoaderType = "Lib9c.NCActionLoader.NineChroniclesActionLoader";
// string blockPolicyType = "Lib9c.NCActionLoader.NineChroniclesPolicyActionRegistry";
// IActionLoader actionLoader = PluginLoader.LoadActionLoader(pluginPath, actionLoaderType);
// IPolicyActionsRegistry policyActionRegistry =
// PluginLoader.LoadPolicyActionRegistry(pluginPath, blockPolicyType);

// Libplanet.Crypto.CryptoConfig.CryptoBackend = new Secp256k1CryptoBackend<SHA256>();

// builder.Services.AddSingleton<IActionLoader>(actionLoader);
// builder.Services.AddSingleton<IPolicyActionsRegistry>(policyActionRegistry);

services.AddGrpc();
services.AddGrpcReflection();
services.AddLibplanetNode(context.Configuration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,16 @@
},
"Swarm": {
"IsEnabled": true,
"AppProtocolVersion": "200210/AB2da648b9154F2cCcAFBD85e0Bc3d51f97330Fc/MEUCIQCBr..8VdITFe9nMTobl4akFid.s8G2zy2pBidAyRXSeAIgER77qX+eywjgyth6QYi7rQw5nK3KXO6cQ6ngUh.CyfU=/ZHU5OnRpbWVzdGFtcHUxMDoyMDI0LTA3LTMwZQ=="
"AppProtocolVersion": "200210/AB2da648b9154F2cCcAFBD85e0Bc3d51f97330Fc/MEUCIQCBr..8VdITFe9nMTobl4akFid.s8G2zy2pBidAyRXSeAIgER77qX+eywjgyth6QYi7rQw5nK3KXO6cQ6ngUh.CyfU=/ZHU5OnRpbWVzdGFtcHUxMDoyMDI0LTA3LTMwZQ==",
"BlocksyncSeedPeer": "027bd36895d68681290e570692ad3736750ceaab37be402442ffb203967f98f7b6,9c-main-tcp-seed-1.planetarium.dev:31234"
},
"Validator": {
"IsEnabled": true
},
"Store": {
"Type": 0,
"RootPath": "/Users/jeesu/Projects/Storage/Chain",
"StoreName": "9c-main-snapshot-slim",
"StateStoreName": "9c-main-snapshot-slim/states"
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Libplanet.Action.Loader;
using Libplanet.Blockchain;
using Libplanet.Crypto;
using Libplanet.Node.Options;
Expand Down Expand Up @@ -32,7 +33,7 @@ public void Create_Test()
genesisOptions: genesisOptions,
storeOptions: storeOptions,
policyService: policyService,
actionLoaderProviders: [],
actionLoader: TypedActionLoader.Create(),
logger: logger);
var blockChain = blockChainService.BlockChain;

Expand Down
36 changes: 36 additions & 0 deletions sdk/node/Libplanet.Node/PluginLoadContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.Loader;

namespace Libplanet.Node;

public class PluginLoadContext : AssemblyLoadContext
{
private AssemblyDependencyResolver _resolver;

public PluginLoadContext(string pluginPath)
{
_resolver = new AssemblyDependencyResolver(pluginPath);
}

protected override Assembly Load(AssemblyName assemblyName)
{
string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}

return null;
}

protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
if (libraryPath != null)
{
return LoadUnmanagedDllFromPath(libraryPath);
}

return IntPtr.Zero;
}
}
27 changes: 18 additions & 9 deletions sdk/node/Libplanet.Node/Services/BlockChainService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public BlockChainService(
IOptions<GenesisOptions> genesisOptions,
IOptions<StoreOptions> storeOptions,
PolicyService policyService,
IEnumerable<IActionLoaderProvider> actionLoaderProviders,
IActionLoader actionLoader,
IPolicyActionsRegistry policyActions,
ILogger<BlockChainService> logger)
{
_synchronizationContext = SynchronizationContext.Current ?? new();
Expand All @@ -48,7 +49,8 @@ public BlockChainService(
storeOptions: storeOptions.Value,
stagePolicy: policyService.StagePolicy,
renderers: [this],
actionLoaders: [.. actionLoaderProviders.Select(item => item.GetActionLoader())]);
actionLoader: actionLoader,
policyActions: policyActions);
}

public event EventHandler<BlockEventArgs>? BlockAppended;
Expand Down Expand Up @@ -84,7 +86,7 @@ void Action(object? state)
}
}

_logger.LogInformation("#{Height}: Block appended.", newTip.Index);
_logger.LogInformation("#{Height}: Block appended", newTip.Index);
BlockAppended?.Invoke(this, new(newTip));
}
}
Expand All @@ -94,20 +96,27 @@ private static BlockChain CreateBlockChain(
StoreOptions storeOptions,
IStagePolicy stagePolicy,
IRenderer[] renderers,
IActionLoader[] actionLoaders)
IActionLoader actionLoader,
IPolicyActionsRegistry policyActions)
{
var (store, stateStore) = CreateStore(storeOptions);
var actionLoader = new AggregateTypedActionLoader(actionLoaders);
var actionEvaluator = new ActionEvaluator(
policyActionsRegistry: new(),
policyActionsRegistry: policyActions,
stateStore,
actionLoader);

var genesisBlock = CreateGenesisBlock(genesisOptions);
var policy = new BlockPolicy(
blockInterval: TimeSpan.FromSeconds(10),
getMaxTransactionsPerBlock: _ => int.MaxValue,
getMaxTransactionsBytes: _ => long.MaxValue);
policyActionsRegistry: policyActions,
blockInterval: TimeSpan.FromSeconds(8),
validateNextBlockTx: (chain, transaction) => null,
validateNextBlock: (chain, block) => null,
getMaxTransactionsBytes: l => long.MaxValue,
getMinTransactionsPerBlock: l => 0,
getMaxTransactionsPerBlock: l => int.MaxValue,
getMaxTransactionsPerSignerPerBlock: l => int.MaxValue
);

var blockChainStates = new BlockChainStates(store, stateStore);
if (store.GetCanonicalChainId() is null)
{
Expand Down
11 changes: 10 additions & 1 deletion sdk/node/Libplanet.Node/Services/SwarmService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using System.Net;
using Libplanet.Common;
using Libplanet.Crypto;
Expand Down Expand Up @@ -184,9 +185,17 @@ private static async Task<NetMQTransport> CreateTransport(
var appProtocolVersionOptions = new Net.Options.AppProtocolVersionOptions
{
AppProtocolVersion = appProtocolVersion,
TrustedAppProtocolVersionSigners = new HashSet<PublicKey>()
{
PublicKey.FromHex("030ffa9bd579ee1503ce008394f687c182279da913bfaec12baca34e79698a7cd1"),
}.ToImmutableHashSet(),
};
var hostOptions = new Net.Options.HostOptions(endPoint.Host, [], endPoint.Port);
return await NetMQTransport.Create(privateKey, appProtocolVersionOptions, hostOptions);
return await NetMQTransport.Create(
privateKey,
appProtocolVersionOptions,
hostOptions,
TimeSpan.FromSeconds(60));
}

private static ConsensusReactorOption CreateConsensusReactorOption(
Expand Down
4 changes: 2 additions & 2 deletions src/Libplanet.Action/ActionEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Libplanet.Action
public class ActionEvaluator : IActionEvaluator
{
private readonly ILogger _logger;
private readonly PolicyActionsRegistry _policyActionsRegistry;
private readonly IPolicyActionsRegistry _policyActionsRegistry;
private readonly IStateStore _stateStore;
private readonly IActionLoader _actionLoader;

Expand All @@ -40,7 +40,7 @@ public class ActionEvaluator : IActionEvaluator
/// <param name="actionTypeLoader"> A <see cref="IActionLoader"/> implementation using
/// action type lookup.</param>
public ActionEvaluator(
PolicyActionsRegistry policyActionsRegistry,
IPolicyActionsRegistry policyActionsRegistry,
IStateStore stateStore,
IActionLoader actionTypeLoader)
{
Expand Down
36 changes: 36 additions & 0 deletions src/Libplanet.Action/IPolicyActionsRegistry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Collections.Immutable;

namespace Libplanet.Action
{
public interface IPolicyActionsRegistry
{
/// <summary>
/// An array of <see cref="IAction"/> to execute and be rendered at the beginning
/// for every block, if any.</summary>
ImmutableArray<IAction> BeginBlockActions
{
get;
}

Check warning on line 13 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 13 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 13 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

/// <summary>

Check warning on line 14 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 14 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 14 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 14 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 14 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

Check warning on line 14 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

/// An array of <see cref="IAction"/> to execute and be rendered at the end
/// for every block, if any.</summary>
ImmutableArray<IAction> EndBlockActions
{
get;
}

Check warning on line 20 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 20 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 20 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

/// <summary>

Check warning on line 21 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 21 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 21 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 21 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 21 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

Check warning on line 21 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

/// An array of <see cref="IAction"/> to execute and be rendered at the beginning
/// for every transaction, if any.</summary>
ImmutableArray<IAction> BeginTxActions
{
get;
}

Check warning on line 27 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 27 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 27 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

/// <summary>

Check warning on line 28 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 28 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (linux-8cores)

Check warning on line 28 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 28 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / docs

Check warning on line 28 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

Check warning on line 28 in src/Libplanet.Action/IPolicyActionsRegistry.cs

View workflow job for this annotation

GitHub Actions / Run Benchmark.Net benchmarks (windows-8cores)

/// An array of <see cref="IAction"/> to execute and be rendered at the end
/// for every transaction, if any.</summary>
ImmutableArray<IAction> EndTxActions
{
get;
}
}
}
2 changes: 1 addition & 1 deletion src/Libplanet.Action/PolicyActionsRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace Libplanet.Action
{
public class PolicyActionsRegistry
public class PolicyActionsRegistry : IPolicyActionsRegistry
{
/// <summary>
/// A class containing policy actions to evaluate at each situation.
Expand Down
Loading

0 comments on commit 1456b4b

Please sign in to comment.