Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions benchmarks/Neo.Benchmarks/SmartContract/Benchmarks.Dispatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
// Copyright (C) 2015-2026 The Neo Project.
//
// Benchmarks.Dispatch.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using Neo.Persistence;
using Neo.SmartContract.Manifest;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.VM.Types;
using System.Numerics;
using System.Reflection;

namespace Neo.SmartContract.Benchmark
{
[Config(typeof(BenchmarkConfig))]
[MemoryDiagnoser]
public class Benchmarks_Dispatch
{
private const int DispatchCount = 1000;
private static readonly ProtocolSettings s_protocol = ProtocolSettings.Load("config.json");
private static readonly NeoSystem s_system = new(s_protocol, (string)null);
private static readonly Script s_dummyScript = new(new byte[] { (byte)OpCode.RET }, true);
private static readonly InteropDescriptor s_syscallNoArgs = CreateInteropDescriptor("InteropNoArgs");
private static readonly InteropDescriptor s_syscallOneArg = CreateInteropDescriptor("InteropOneArg");
private static readonly BenchmarkNativeContract s_nativeContract = new();
private static readonly ContractState s_nativeContractState = s_nativeContract.GetContractState(s_protocol, 0);
private static readonly ContractMethodDescriptor s_nativeNoArgMethod = s_nativeContractState.Manifest.Abi.GetMethod("noArg", 0)!;
private static readonly ContractMethodDescriptor s_nativeOneArgMethod = s_nativeContractState.Manifest.Abi.GetMethod("oneArg", 1)!;
private static readonly StackItem s_integerArg = new Integer(42);

[Benchmark(OperationsPerInvoke = DispatchCount)]
public int Syscall_NoArgs()
{
using var snapshot = s_system.GetSnapshotCache();
using var engine = new BenchmarkEngine(snapshot);
engine.PrepareInteropContext();

int result = 0;
for (int i = 0; i < DispatchCount; i++)
result = engine.InvokeInterop(s_syscallNoArgs);

return result;
}

[Benchmark(OperationsPerInvoke = DispatchCount)]
public int Syscall_OneArg()
{
using var snapshot = s_system.GetSnapshotCache();
using var engine = new BenchmarkEngine(snapshot);
engine.PrepareInteropContext();

int result = 0;
for (int i = 0; i < DispatchCount; i++)
result = engine.InvokeInterop(s_syscallOneArg, s_integerArg);

return result;
}

[Benchmark(OperationsPerInvoke = DispatchCount)]
public int Native_NoArgs()
{
using var snapshot = s_system.GetSnapshotCache();
using var engine = new BenchmarkEngine(snapshot);
engine.PrepareNativeContext(s_nativeContractState, s_nativeNoArgMethod);

int result = 0;
for (int i = 0; i < DispatchCount; i++)
result = engine.InvokeNative();

return result;
}

[Benchmark(OperationsPerInvoke = DispatchCount)]
public int Native_OneArg()
{
using var snapshot = s_system.GetSnapshotCache();
using var engine = new BenchmarkEngine(snapshot);
engine.PrepareNativeContext(s_nativeContractState, s_nativeOneArgMethod);

int result = 0;
for (int i = 0; i < DispatchCount; i++)
result = engine.InvokeNative(s_integerArg);

return result;
}

private static InteropDescriptor CreateInteropDescriptor(string methodName)
{
var flags = BindingFlags.Instance | BindingFlags.NonPublic;
var method = typeof(BenchmarkEngine).GetMethod(methodName, flags)!;

return new InteropDescriptor
{
Name = $"Benchmark.{methodName}",
Handler = method,
FixedPrice = 0,
RequiredCallFlags = CallFlags.None
};
}

private sealed class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
Options |= ConfigOptions.DisableOptimizationsValidator;
}
}

private sealed class BenchmarkEngine(DataCache snapshot) : ApplicationEngine(TriggerType.Application, null, snapshot, s_system.GenesisBlock, s_protocol, long.MaxValue / FeeFactor)
{
public void PrepareInteropContext()
{
LoadScript(s_dummyScript, configureState: state => state.CallFlags = CallFlags.All);
}

public void PrepareNativeContext(ContractState contract, ContractMethodDescriptor method)
{
LoadScript(contract.Script, initialPosition: method.Offset + 1, configureState: state =>
{
state.CallFlags = CallFlags.All;
state.ScriptHash = contract.Hash;
state.Contract = contract;
});
}

public int InvokeInterop(InteropDescriptor descriptor, params StackItem[] args)
{
PushArguments(args);
OnSysCall(descriptor);
return PopIntegerResult();
}

public int InvokeNative(params StackItem[] args)
{
PushArguments(args);
CallNativeContract(0);
return PopIntegerResult();
}

private void PushArguments(StackItem[] args)
{
for (int i = args.Length - 1; i >= 0; i--)
CurrentContext!.EvaluationStack.Push(args[i]);
}

private int PopIntegerResult()
{
return (int)CurrentContext!.EvaluationStack.Pop().GetInteger();
}

private int InteropNoArgs() => 1;

private int InteropOneArg(int value) => value + 1;
}

private sealed class BenchmarkNativeContract : NativeContract
{
[ContractMethod]
private static int NoArg() => 1;

[ContractMethod]
private static int OneArg(int value) => value + 1;
}
}
}
1 change: 1 addition & 0 deletions src/Neo/Neo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

<ItemGroup>
<InternalsVisibleTo Include="Neo.UnitTests" />
<InternalsVisibleTo Include="Neo.Benchmarks" />
<InternalsVisibleTo Include="Neo.SmartContract.Testing" />
<InternalsVisibleTo Include="Neo.SmartContract.TestEngine" />
<InternalsVisibleTo Include="Neo.Plugins.RpcServer.Tests" />
Expand Down
25 changes: 19 additions & 6 deletions src/Neo/SmartContract/ApplicationEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using Neo.VM;
using Neo.VM.Types;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
Expand Down Expand Up @@ -938,13 +939,25 @@ protected virtual void OnSysCall(InteropDescriptor descriptor)
ValidateCallFlags(descriptor.RequiredCallFlags);
AddFee(descriptor.FixedPrice * _execFeeFactor);

object?[] parameters = new object?[descriptor.Parameters.Count];
for (int i = 0; i < parameters.Length; i++)
parameters[i] = Convert(Pop(), descriptor.Parameters[i]);
int parameterCount = descriptor.Parameters.Count;
object?[] parameters = parameterCount == 0 ? [] : ArrayPool<object?>.Shared.Rent(parameterCount);
try
{
for (int i = 0; i < parameterCount; i++)
parameters[i] = Convert(Pop(), descriptor.Parameters[i]);

object? returnValue = descriptor.Handler.Invoke(this, parameters);
if (descriptor.Handler.ReturnType != typeof(void))
Push(Convert(returnValue));
object? returnValue = descriptor.Invoke(this, parameters);
if (descriptor.Handler.ReturnType != typeof(void))
Push(Convert(returnValue));
}
finally
{
if (parameterCount > 0)
{
Array.Clear(parameters, 0, parameterCount);
ArrayPool<object?>.Shared.Return(parameters);
}
}
}

protected override void PreExecuteInstruction(Instruction instruction)
Expand Down
41 changes: 41 additions & 0 deletions src/Neo/SmartContract/InteropDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@
// modifications are permitted.

using Neo.Cryptography;
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace Neo.SmartContract
{
internal delegate object? InteropInvoker(ApplicationEngine engine, object?[] args);

/// <summary>
/// Represents a descriptor of an interoperable service.
/// </summary>
Expand Down Expand Up @@ -52,6 +56,8 @@ public uint Hash
/// </summary>
public IReadOnlyList<InteropParameterDescriptor> Parameters => field ??= Handler.GetParameters().Select(p => new InteropParameterDescriptor(p)).ToList().AsReadOnly();

internal InteropInvoker Invoker => field ??= CreateInvoker(Handler);

/// <summary>
/// The fixed price for calling the interoperable service. It can be 0 if the interoperable service has a variable price.
/// </summary>
Expand All @@ -71,5 +77,40 @@ public static implicit operator uint(InteropDescriptor descriptor)
{
return descriptor.Hash;
}

internal object? Invoke(ApplicationEngine engine, object?[] args)
{
try
{
return Invoker(engine, args);
}
catch (Exception ex) when (ex is not TargetInvocationException)
{
throw new TargetInvocationException(ex);
}
}

private static InteropInvoker CreateInvoker(MethodInfo handler)
{
var engine = Expression.Parameter(typeof(ApplicationEngine), "engine");
var args = Expression.Parameter(typeof(object[]), "args");
var handlerParameters = handler.GetParameters();
var callParameters = new Expression[handlerParameters.Length];

for (int i = 0; i < handlerParameters.Length; i++)
{
callParameters[i] = Expression.Convert(
Expression.ArrayIndex(args, Expression.Constant(i)),
handlerParameters[i].ParameterType);
}

Expression? instance = handler.IsStatic ? null : Expression.Convert(engine, handler.DeclaringType!);
Expression call = Expression.Call(instance, handler, callParameters);
Expression body = handler.ReturnType == typeof(void)
? Expression.Block(call, Expression.Constant(null, typeof(object)))
: Expression.Convert(call, typeof(object));

return Expression.Lambda<InteropInvoker>(body, engine, args).Compile();
}
}
}
55 changes: 55 additions & 0 deletions src/Neo/SmartContract/Native/ContractMethodMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using Array = Neo.VM.Types.Array;
Expand All @@ -25,6 +26,8 @@

namespace Neo.SmartContract.Native
{
internal delegate object? NativeMethodInvoker(NativeContract contract, ApplicationEngine engine, object?[] args);

[DebuggerDisplay("{Name}")]
internal class ContractMethodMetadata : IHardforkActivable
{
Expand All @@ -39,6 +42,7 @@ internal class ContractMethodMetadata : IHardforkActivable
public ContractMethodDescriptor Descriptor { get; }
public Hardfork? ActiveIn { get; init; } = null;
public Hardfork? DeprecatedIn { get; init; } = null;
internal NativeMethodInvoker Invoker => field ??= CreateInvoker();

public ContractMethodMetadata(MemberInfo member, ContractMethodAttribute attribute)
{
Expand Down Expand Up @@ -75,6 +79,57 @@ public ContractMethodMetadata(MemberInfo member, ContractMethodAttribute attribu
};
}

internal object? Invoke(NativeContract contract, ApplicationEngine engine, object?[] args)
{
try
{
return Invoker(contract, engine, args);
}
catch (Exception ex) when (ex is not TargetInvocationException)
{
throw new TargetInvocationException(ex);
}
}

private NativeMethodInvoker CreateInvoker()
{
var contract = Expression.Parameter(typeof(NativeContract), "contract");
var engine = Expression.Parameter(typeof(ApplicationEngine), "engine");
var args = Expression.Parameter(typeof(object[]), "args");
var handlerParameters = Handler.GetParameters();
var callParameters = new Expression[handlerParameters.Length];
int publicParameterIndex = 0;

for (int i = 0; i < handlerParameters.Length; i++)
{
if (i == 0 && NeedApplicationEngine)
{
callParameters[i] = Expression.Convert(engine, handlerParameters[i].ParameterType);
continue;
}

if (i == 0 && NeedSnapshot)
Comment on lines +105 to +111
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merge these two if?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree

{
callParameters[i] = Expression.Convert(
Expression.Property(engine, nameof(ApplicationEngine.SnapshotCache)),
handlerParameters[i].ParameterType);
continue;
}

callParameters[i] = Expression.Convert(
Expression.ArrayIndex(args, Expression.Constant(publicParameterIndex++)),
handlerParameters[i].ParameterType);
}

Expression? instance = Handler.IsStatic ? null : Expression.Convert(contract, Handler.DeclaringType!);
Expression call = Expression.Call(instance, Handler, callParameters);
Expression body = Handler.ReturnType == typeof(void)
? Expression.Block(call, Expression.Constant(null, typeof(object)))
: Expression.Convert(call, typeof(object));

return Expression.Lambda<NativeMethodInvoker>(body, contract, engine, args).Compile();
}

private static ContractParameterType ToParameterType(Type type)
{
if (type.BaseType == typeof(ContractTask)) return ToParameterType(type.GenericTypeArguments[0]);
Expand Down
Loading
Loading