Skip to content

Added validator class for NEP-17 contract #311

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
59 changes: 59 additions & 0 deletions src/neoxp/Commands/ContractCommand.Validate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright (C) 2015-2023 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project 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 McMaster.Extensions.CommandLineUtils;
using Neo;
using System.ComponentModel.DataAnnotations;

namespace NeoExpress.Commands;

internal partial class ContractCommand
{
[Command("validate", Description = "Checks a contract for compliance with proposal specification")]
internal class Validate
{
readonly ExpressChainManagerFactory chainManagerFactory;

public Validate(ExpressChainManagerFactory chainManagerFactory)
{
this.chainManagerFactory = chainManagerFactory;
}

[Argument(0, Description = "Path to contract .nef file")]
[Required]
internal string ContractHash { get; init; } = string.Empty;

[Option(Description = "Path to neo-express data file")]
internal string Input { get; init; } = string.Empty;

internal async Task<int> OnExecuteAsync(CommandLineApplication app, IConsole console)
{
try
{
if (UInt160.TryParse(ContractHash, out var scriptHash) == false)
throw new Exception($"{ContractHash} is invalid ScriptHash.");

var (chainManager, _) = chainManagerFactory.LoadChain(Input);
using var expressNode = chainManager.GetExpressNode();
var nep17 = await expressNode.IsNep17CompliantAsync(scriptHash).ConfigureAwait(false);

if (nep17)
await console.Out.WriteLineAsync($"{scriptHash} is NEP-17 compliant.");

return 0;
}
catch (Exception ex)
{
app.WriteException(ex?.InnerException! ?? ex!);
return 1;
}
}
}
}
3 changes: 2 additions & 1 deletion src/neoxp/Commands/ContractCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ namespace NeoExpress.Commands
typeof(List),
typeof(Run),
typeof(Storage),
typeof(Update))]
typeof(Update),
typeof(Validate))]
partial class ContractCommand
{
internal int OnExecute(CommandLineApplication app, IConsole console)
Expand Down
10 changes: 10 additions & 0 deletions src/neoxp/Commands/TransferNFTCommand.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
// Copyright (C) 2015-2023 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project 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 McMaster.Extensions.CommandLineUtils;
using Neo;
using System.ComponentModel.DataAnnotations;
Expand Down
62 changes: 62 additions & 0 deletions src/neoxp/Extensions/ContractManifestExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (C) 2015-2023 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project 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 Neo.SmartContract;
using Neo.SmartContract.Manifest;

namespace NeoExpress;

internal static class ContractManifestExtensions
{
public static bool IsNep17Compliant(this ContractManifest manifest)
{
try
{
var symbolMethod = manifest.Abi.GetMethod("symbol", 0);
var decimalsMethod = manifest.Abi.GetMethod("decimals", 0);
var totalSupplyMethod = manifest.Abi.GetMethod("totalSupply", 0);
var balanceOfMethod = manifest.Abi.GetMethod("balanceOf", 1);
var transferMethod = manifest.Abi.GetMethod("transfer", 4);

var symbolValid = symbolMethod.Safe == true &&
symbolMethod.ReturnType == ContractParameterType.String;
var decimalsValid = decimalsMethod.Safe == true &&
decimalsMethod.ReturnType == ContractParameterType.Integer;
var totalSupplyValid = totalSupplyMethod.Safe == true &&
totalSupplyMethod.ReturnType == ContractParameterType.Integer;
var balanceOfValid = balanceOfMethod.Safe == true &&
balanceOfMethod.ReturnType == ContractParameterType.Integer &&
balanceOfMethod.Parameters[0].Type == ContractParameterType.Hash160;
var transferValid = transferMethod.Safe == false &&
transferMethod.ReturnType == ContractParameterType.Boolean &&
transferMethod.Parameters[0].Type == ContractParameterType.Hash160 &&
transferMethod.Parameters[1].Type == ContractParameterType.Hash160 &&
transferMethod.Parameters[2].Type == ContractParameterType.Integer &&
transferMethod.Parameters[3].Type == ContractParameterType.Any;
var transferEvent = manifest.Abi.Events.SingleOrDefault(s =>
s.Name == "transfer" &&
s.Parameters.Length == 3 &&
s.Parameters[0].Type == ContractParameterType.Hash160 &&
s.Parameters[1].Type == ContractParameterType.Hash160 &&
s.Parameters[2].Type == ContractParameterType.Integer) != null;

return (symbolValid &&
decimalsValid &&
totalSupplyValid &&
balanceOfValid &&
transferValid &&
transferEvent);
}
catch
{
return false;
}
}
}
2 changes: 2 additions & 0 deletions src/neoxp/IExpressNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,7 @@ enum CheckpointMode { Online, Offline }

Task<int> PersistContractAsync(ContractState state, IReadOnlyList<(string key, string value)> storagePairs, ContractCommand.OverwriteForce force);
IAsyncEnumerable<(uint blockIndex, NotificationRecord notification)> EnumerateNotificationsAsync(IReadOnlySet<UInt160>? contractFilter, IReadOnlySet<string>? eventFilter);

Task<bool> IsNep17CompliantAsync(UInt160 contractHash);
}
}
13 changes: 13 additions & 0 deletions src/neoxp/Node/OfflineNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
using Neo.Wallets;
using NeoExpress.Commands;
using NeoExpress.Models;
using NeoExpress.Validators;
using System.Numerics;
using static Neo.Ledger.Blockchain;

Expand Down Expand Up @@ -393,5 +394,17 @@ public Task<int> PersistContractAsync(ContractState state, IReadOnlyList<(string
}
}
#pragma warning restore 1998

public Task<bool> IsNep17CompliantAsync(UInt160 contractHash)
{
var snapshot = neoSystem.GetSnapshot();
var validator = new Nep17Token(ProtocolSettings, snapshot, contractHash);

return Task.FromResult(
validator.HasValidMethods() &&
validator.IsSymbolValid() &&
validator.IsDecimalsValid() &&
validator.IsBalanceOfValid());
}
}
}
5 changes: 5 additions & 0 deletions src/neoxp/Node/OnlineNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,5 +305,10 @@ public async Task<int> PersistContractAsync(ContractState state, IReadOnlyList<(
count += values.Count;
}
}

public async Task<bool> IsNep17CompliantAsync(UInt160 contractHash)
{
return false;
}
}
}
4 changes: 4 additions & 0 deletions src/neoxp/TransactionExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ public async Task ContractDeployAsync(string contract, string accountName, strin
{
throw new Exception($"{manifest.Name} Contract declares support for both NEP-11 and NEP-17 standards. Use --force to deploy contract with invalid supported standards declarations.");
}
if (nep17 && manifest.IsNep17Compliant() == false)
{
throw new Exception($"{manifest.Name} Contract declares support for NEP-17 standards. However is not NEP-17 compliant. Invalid methods/events.");
}
}

ContractParameter dataParam;
Expand Down
24 changes: 24 additions & 0 deletions src/neoxp/Validators/Nep17Token.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (C) 2015-2023 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project 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 Neo;
using Neo.Persistence;

namespace NeoExpress.Validators;

internal class Nep17Token : TokenBase
{
public Nep17Token(
ProtocolSettings protocolSettings,
DataCache snapshot,
UInt160 scriptHash) : base(protocolSettings, snapshot, scriptHash)
{
}
}
163 changes: 163 additions & 0 deletions src/neoxp/Validators/TokenBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright (C) 2015-2023 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project 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 Neo;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.VM;
using System.Numerics;

namespace NeoExpress.Validators;

internal abstract class TokenBase
{
public UInt160 ScriptHash { get; private init; }
public string Symbol { get; private set; }
public byte Decimals { get; private set; }

protected readonly DataCache _snapshot;
protected readonly ProtocolSettings _protocolSettings;

public TokenBase(
ProtocolSettings protocolSettings,
DataCache snapshot,
UInt160 scriptHash)
{
_protocolSettings = protocolSettings;
_snapshot = snapshot;
ScriptHash = scriptHash;

using var builder = new ScriptBuilder();
builder.EmitDynamicCall(ScriptHash, "decimals");
builder.EmitDynamicCall(ScriptHash, "symbol");

using var engine = builder.Invoke(_protocolSettings, _snapshot);
if (engine.State != VMState.HALT)
throw new NotSupportedException($"{ScriptHash} is not NEP-17 compliant.");

var results = engine.ResultStack;
Symbol = results.Pop().GetString()!;
Decimals = checked((byte)results.Pop().GetInteger());
}

public bool HasValidMethods()
{
using var builder = new ScriptBuilder();
builder.EmitDynamicCall(ScriptHash, "decimals");
builder.EmitDynamicCall(ScriptHash, "symbol");
builder.EmitDynamicCall(ScriptHash, "totalSupply");
builder.EmitDynamicCall(ScriptHash, "balanceOf", UInt160.Zero);
builder.EmitDynamicCall(ScriptHash, "transfer", UInt160.Zero, UInt160.Zero, 0, null);

// You need to add this line for transaction
// for ApplicationEngine not to crash
// see https://github.com/neo-project/neo/issues/2952
var tx = new Transaction() { Signers = new[] { new Signer() { Account = UInt160.Zero } }, Attributes = Array.Empty<TransactionAttribute>() };

using var engine = builder.Invoke(_protocolSettings, _snapshot, tx);
if (engine.State == VMState.FAULT)
throw engine.FaultException;

return engine.State == VMState.HALT;
}

public bool IsBalanceOfValid()
{
return BalanceOf(UInt160.Zero) == 0;
}

public bool IsDecimalsValid()
{
using var builder = new ScriptBuilder();
builder.EmitDynamicCall(ScriptHash, "decimals");

byte? dec = null;
int x = 0;

// This loop checks for constant byte of decimals
while (x <= 5)
{
using var appEng = builder.Invoke(_protocolSettings, _snapshot);
if (appEng.State != VMState.HALT)
throw appEng.FaultException;
try
{
if (dec.HasValue == false)
dec = (byte)appEng.ResultStack.Pop().GetInteger();
else
{
if (dec == (byte)appEng.ResultStack.Pop().GetInteger())
x++;
else
return false;
}
}
catch (OverflowException)
{
return false;
}
}

return true;
}

public bool IsSymbolValid()
{
using var builder = new ScriptBuilder();
builder.EmitDynamicCall(ScriptHash, "symbol");

var symbol = string.Empty;
int x = 0;

// This loop checks for constant string of symbol
while (x <= 5)
{
using var appEng = builder.Invoke(_protocolSettings, _snapshot);
if (appEng.State != VMState.HALT)
throw appEng.FaultException;

if (string.IsNullOrEmpty(symbol))
symbol = appEng.ResultStack.Pop().GetString()!;
else
{
if (symbol == appEng.ResultStack.Pop().GetString()!)
x++;
else
return false;
}
}

if (symbol.Any(a => char.IsWhiteSpace(a) || char.IsControl(a) || char.IsAscii(a) == false))
return false;

return true;
}

public BigInteger TotalSupply()
{
using var builder = new ScriptBuilder();
builder.EmitDynamicCall(ScriptHash, "totalSupply");

using var appEng = builder.Invoke(_protocolSettings, _snapshot);
if (appEng.State == VMState.HALT)
return appEng.ResultStack.Pop().GetInteger();
throw new InvalidOperationException();
}

public BigInteger BalanceOf(UInt160 owner)
{
using var builder = new ScriptBuilder();
builder.EmitDynamicCall(ScriptHash, "balanceOf", owner);

using var appEng = builder.Invoke(_protocolSettings, _snapshot);
if (appEng.State == VMState.HALT)
return appEng.ResultStack.Pop().GetInteger();
throw new InvalidOperationException();
}
}