Skip to content

Commit

Permalink
Merge branch 'master' into core-calculate-fee
Browse files Browse the repository at this point in the history
  • Loading branch information
shargon authored Sep 16, 2024
2 parents 590e83d + 9946450 commit ea69990
Show file tree
Hide file tree
Showing 19 changed files with 1,343 additions and 258 deletions.
54 changes: 54 additions & 0 deletions src/Neo.CLI/CLI/MainService.Tools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
using Neo.Extensions;
using Neo.IO;
using Neo.SmartContract;
using Neo.VM;
using Neo.Wallets;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
Expand Down Expand Up @@ -441,6 +443,58 @@ private static string Base64Fixed(string str)
}
}

/// <summary>
/// Base64 .nef file Analysis
/// </summary>
[ParseFunction("Base64 .nef file Analysis")]
private string? NefFileAnalyis(string base64)
{
byte[] nefData;
if (File.Exists(base64)) // extension name not considered
nefData = File.ReadAllBytes(base64);
else
{
try
{
nefData = Convert.FromBase64String(base64);
}
catch { return null; }
}
NefFile nef;
Script script;
bool verifyChecksum = false;
bool strictMode = false;
try
{
nef = NefFile.Parse(nefData, true);
verifyChecksum = true;
}
catch (FormatException)
{
nef = NefFile.Parse(nefData, false);
}
catch { return null; }
try
{
script = new Script(nef.Script, true);
strictMode = true;
}
catch (BadScriptException)
{
script = new Script(nef.Script, false);
}
catch { return null; }
string? result = ScriptsToOpCode(Convert.ToBase64String(nef.Script.ToArray()));
if (result == null)
return null;
string prefix = $"\r\n# Compiler: {nef.Compiler}";
if (!verifyChecksum)
prefix += $"\r\n# Warning: Invalid .nef file checksum";
if (!strictMode)
prefix += $"\r\n# Warning: Failed in {nameof(strictMode)}";
return prefix + result;
}

/// <summary>
/// Checks if the string is null or cannot be printed.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Neo.Cryptography.BLS12_381/ConstantTimeUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static bool ConstantTimeEq<T>(in T a, in T b) where T : unmanaged
for (int i = 0; i < a_u64.Length; i++)
f |= a_u64[i] ^ b_u64[i];
for (int i = a_u64.Length * sizeof(ulong); i < a_bytes.Length; i++)
f |= (ulong)a_bytes[i] ^ a_bytes[i];
f |= (ulong)a_bytes[i] ^ b_bytes[i];
return f == 0;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Neo.VM/JumpTable/JumpTable.Compound.cs
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ public virtual void ClearItems(ExecutionEngine engine, Instruction instruction)
/// </summary>
/// <param name="engine">The execution engine.</param>
/// <param name="instruction">The instruction being executed.</param>
/// <remarks>Pop 1, Push 0</remarks>
/// <remarks>Pop 1, Push 1</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual void PopItem(ExecutionEngine engine, Instruction instruction)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Neo.VM/OpCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2028,7 +2028,7 @@ public enum OpCode : byte
/// Using this opcode will need to dup the array before using it.
///
/// <remarks>
/// Push: 0 item(s)
/// Push: 1 item(s)
/// Pop: 1 item(s)
/// </remarks>
/// </summary>
Expand Down
3 changes: 2 additions & 1 deletion src/Neo.VM/ScriptBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ public ScriptBuilder EmitPush(BigInteger value)
<= 4 => Emit(OpCode.PUSHINT32, PadRight(buffer, bytesWritten, 4, value.Sign < 0)),
<= 8 => Emit(OpCode.PUSHINT64, PadRight(buffer, bytesWritten, 8, value.Sign < 0)),
<= 16 => Emit(OpCode.PUSHINT128, PadRight(buffer, bytesWritten, 16, value.Sign < 0)),
_ => Emit(OpCode.PUSHINT256, PadRight(buffer, bytesWritten, 32, value.Sign < 0)),
<= 32 => Emit(OpCode.PUSHINT256, PadRight(buffer, bytesWritten, 32, value.Sign < 0)),
_ => throw new ArgumentOutOfRangeException(nameof(value), "Invalid value: BigInteger is too large"),
};
}

Expand Down
22 changes: 11 additions & 11 deletions src/Plugins/OracleService/OracleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class OracleService : Plugin, ICommittingHandler, IServiceAddedHandler, I
private readonly ConcurrentDictionary<ulong, OracleTask> pendingQueue = new ConcurrentDictionary<ulong, OracleTask>();
private readonly ConcurrentDictionary<ulong, DateTime> finishedCache = new ConcurrentDictionary<ulong, DateTime>();
private Timer timer;
private readonly CancellationTokenSource cancelSource = new CancellationTokenSource();
internal readonly CancellationTokenSource cancelSource = new CancellationTokenSource();
private OracleStatus status = OracleStatus.Unstarted;
private IWalletProvider walletProvider;
private int counter;
Expand Down Expand Up @@ -123,25 +123,25 @@ private void OnStart()
Start(walletProvider?.GetWallet());
}

public void Start(Wallet wallet)
public Task Start(Wallet wallet)
{
if (status == OracleStatus.Running) return;
if (status == OracleStatus.Running) return Task.CompletedTask;

if (wallet is null)
{
ConsoleHelper.Warning("Please open wallet first!");
return;
return Task.CompletedTask;
}

if (!CheckOracleAvaiblable(_system.StoreView, out ECPoint[] oracles))
if (!CheckOracleAvailable(_system.StoreView, out ECPoint[] oracles))
{
ConsoleHelper.Warning("The oracle service is unavailable");
return;
return Task.CompletedTask;
}
if (!CheckOracleAccount(wallet, oracles))
{
ConsoleHelper.Warning("There is no oracle account in wallet");
return;
return Task.CompletedTask;
}

this.wallet = wallet;
Expand All @@ -150,7 +150,7 @@ public void Start(Wallet wallet)
status = OracleStatus.Running;
timer = new Timer(OnTimer, null, RefreshIntervalMilliSeconds, Timeout.Infinite);
ConsoleHelper.Info($"Oracle started");
ProcessRequestsAsync();
return ProcessRequestsAsync();
}

[ConsoleCommand("stop oracle", Category = "Oracle", Description = "Stop oracle service")]
Expand Down Expand Up @@ -180,7 +180,7 @@ void ICommittingHandler.Blockchain_Committing_Handler(NeoSystem system, Block bl
OnStart();
}
if (status != OracleStatus.Running) return;
if (!CheckOracleAvaiblable(snapshot, out ECPoint[] oracles) || !CheckOracleAccount(wallet, oracles))
if (!CheckOracleAvailable(snapshot, out ECPoint[] oracles) || !CheckOracleAccount(wallet, oracles))
OnStop();
}

Expand Down Expand Up @@ -325,7 +325,7 @@ private async Task ProcessRequestAsync(DataCache snapshot, OracleRequest req)
}
}

private async void ProcessRequestsAsync()
private async Task ProcessRequestsAsync()
{
while (!cancelSource.IsCancellationRequested)
{
Expand Down Expand Up @@ -553,7 +553,7 @@ private bool CheckTxSign(DataCache snapshot, Transaction tx, ConcurrentDictionar
return false;
}

private static bool CheckOracleAvaiblable(DataCache snapshot, out ECPoint[] oracles)
private static bool CheckOracleAvailable(DataCache snapshot, out ECPoint[] oracles)
{
uint height = NativeContract.Ledger.CurrentIndex(snapshot) + 1;
oracles = NativeContract.RoleManagement.GetDesignatedByRole(snapshot, Role.Oracle, height);
Expand Down
4 changes: 4 additions & 0 deletions src/Plugins/OracleService/OracleService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@
</None>
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Neo.Plugins.OracleService.Tests" />
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions src/Plugins/OracleService/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using Akka.Util.Internal;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
Expand Down Expand Up @@ -59,6 +60,8 @@ private Settings(IConfigurationSection section) : base(section)
MaxOracleTimeout = TimeSpan.FromMilliseconds(section.GetValue("MaxOracleTimeout", 15000));
AllowPrivateHost = section.GetValue("AllowPrivateHost", false);
AllowedContentTypes = section.GetSection("AllowedContentTypes").GetChildren().Select(p => p.Get<string>()).ToArray();
if (AllowedContentTypes.Count() == 0)
AllowedContentTypes = AllowedContentTypes.Concat("application/json").ToArray();
Https = new HttpsSettings(section.GetSection("Https"));
NeoFS = new NeoFSSettings(section.GetSection("NeoFS"));
AutoStart = section.GetValue("AutoStart", false);
Expand Down
60 changes: 47 additions & 13 deletions src/Plugins/RpcServer/RpcServer.Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,23 @@ namespace Neo.Plugins.RpcServer
{
partial class RpcServer
{
[RpcMethod]
protected internal virtual JToken GetConnectionCount(JArray _params)

/// <summary>
/// Gets the current number of connections to the node.
/// </summary>
/// <returns>The number of connections as a JToken.</returns>
[RpcMethodWithParams]
protected internal virtual JToken GetConnectionCount()
{
return localNode.ConnectedCount;
}

[RpcMethod]
protected internal virtual JToken GetPeers(JArray _params)
/// <summary>
/// Gets information about the peers connected to the node.
/// </summary>
/// <returns>A JObject containing information about unconnected, bad, and connected peers.</returns>
[RpcMethodWithParams]
protected internal virtual JToken GetPeers()
{
JObject json = new();
json["unconnected"] = new JArray(localNode.GetUnconnectedPeers().Select(p =>
Expand All @@ -51,9 +60,14 @@ protected internal virtual JToken GetPeers(JArray _params)
return json;
}

/// <summary>
/// Processes the result of a transaction or block relay and returns appropriate response or throws an exception.
/// </summary>
/// <param name="reason">The verification result of the relay.</param>
/// <param name="hash">The hash of the transaction or block.</param>
/// <returns>A JObject containing the hash if successful, otherwise throws an RpcException.</returns>
private static JObject GetRelayResult(VerifyResult reason, UInt256 hash)
{

switch (reason)
{
case VerifyResult.Succeed:
Expand Down Expand Up @@ -109,8 +123,12 @@ private static JObject GetRelayResult(VerifyResult reason, UInt256 hash)
}
}

[RpcMethod]
protected internal virtual JToken GetVersion(JArray _params)
/// <summary>
/// Gets version information about the node, including network, protocol, and RPC settings.
/// </summary>
/// <returns>A JObject containing detailed version and configuration information.</returns>
[RpcMethodWithParams]
protected internal virtual JToken GetVersion()
{
JObject json = new();
json["tcpport"] = localNode.ListenerTcpPort;
Expand Down Expand Up @@ -146,23 +164,39 @@ protected internal virtual JToken GetVersion(JArray _params)
return json;
}

/// <summary>
/// Removes a specified prefix from a string if it exists.
/// </summary>
/// <param name="s">The input string.</param>
/// <param name="prefix">The prefix to remove.</param>
/// <returns>The string with the prefix removed if it existed, otherwise the original string.</returns>
private static string StripPrefix(string s, string prefix)
{
return s.StartsWith(prefix) ? s.Substring(prefix.Length) : s;
}

[RpcMethod]
protected internal virtual JToken SendRawTransaction(JArray _params)
/// <summary>
/// Sends a raw transaction to the network.
/// </summary>
/// <param name="base64Tx">The base64-encoded transaction.</param>
/// <returns>A JToken containing the result of the transaction relay.</returns>
[RpcMethodWithParams]
protected internal virtual JToken SendRawTransaction(string base64Tx)
{
Transaction tx = Result.Ok_Or(() => Convert.FromBase64String(_params[0].AsString()).AsSerializable<Transaction>(), RpcError.InvalidParams.WithData($"Invalid Transaction Format: {_params[0]}"));
Transaction tx = Result.Ok_Or(() => Convert.FromBase64String(base64Tx).AsSerializable<Transaction>(), RpcError.InvalidParams.WithData($"Invalid Transaction Format: {base64Tx}"));
RelayResult reason = system.Blockchain.Ask<RelayResult>(tx).Result;
return GetRelayResult(reason.Result, tx.Hash);
}

[RpcMethod]
protected internal virtual JToken SubmitBlock(JArray _params)
/// <summary>
/// Submits a new block to the network.
/// </summary>
/// <param name="base64Block">The base64-encoded block.</param>
/// <returns>A JToken containing the result of the block submission.</returns>
[RpcMethodWithParams]
protected internal virtual JToken SubmitBlock(string base64Block)
{
Block block = Result.Ok_Or(() => Convert.FromBase64String(_params[0].AsString()).AsSerializable<Block>(), RpcError.InvalidParams.WithData($"Invalid Block Format: {_params[0]}"));
Block block = Result.Ok_Or(() => Convert.FromBase64String(base64Block).AsSerializable<Block>(), RpcError.InvalidParams.WithData($"Invalid Block Format: {base64Block}"));
RelayResult reason = system.Blockchain.Ask<RelayResult>(block).Result;
return GetRelayResult(reason.Result, block.Hash);
}
Expand Down
Loading

0 comments on commit ea69990

Please sign in to comment.