Skip to content
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

Generate manifest with static calls #478

Merged
merged 12 commits into from
Mar 17, 2021
52 changes: 24 additions & 28 deletions src/Neo.Compiler.MSIL/FuncExport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using Mono.Cecil;
using Neo.IO.Json;
using Neo.SmartContract;
using System;
using System.Collections.Generic;
using System.Linq;
Expand Down Expand Up @@ -69,13 +70,13 @@ internal static string ConvType(TypeReference t)

public static JObject GenerateAbi(NeoModule module, Dictionary<int, int> addrConvTable)
{
var outjson = new JObject();
JObject outjson = new();

//functions
var methods = new JArray();
JArray methods = new();
outjson["methods"] = methods;

HashSet<string> names = new HashSet<string>();
HashSet<string> names = new();
foreach (var function in module.mapMethods.OrderBy(u => u.Value.funcaddr))
{
var mm = function.Value;
Expand All @@ -88,18 +89,18 @@ public static JObject GenerateAbi(NeoModule module, Dictionary<int, int> addrCon
{
throw new Exception("abi not allow same name functions");
}
var funcsign = new JObject();
JObject funcsign = new();
methods.Add(funcsign);
funcsign["name"] = function.Value.displayName;
funcsign["offset"] = addrConvTable?[function.Value.funcaddr] ?? function.Value.funcaddr;
funcsign["safe"] = function.Value.method?.method.CustomAttributes.Any(u => u.AttributeType.FullName == "Neo.SmartContract.Framework.SafeAttribute") == true;
JArray funcparams = new JArray();
JArray funcparams = new();
funcsign["parameters"] = funcparams;
if (mm.paramtypes != null)
{
foreach (var v in mm.paramtypes)
{
var item = new JObject();
JObject item = new();
funcparams.Add(item);

item["name"] = v.name;
Expand All @@ -117,22 +118,22 @@ public static JObject GenerateAbi(NeoModule module, Dictionary<int, int> addrCon
}

//events
var eventsigns = new JArray();
JArray eventsigns = new();
outjson["events"] = eventsigns;
foreach (var events in module.mapEvents)
{
var mm = events.Value;
var funcsign = new JObject();
JObject funcsign = new();
eventsigns.Add(funcsign);

funcsign["name"] = events.Value.displayName;
JArray funcparams = new JArray();
JArray funcparams = new();
funcsign["parameters"] = funcparams;
if (mm.paramtypes != null)
{
foreach (var v in mm.paramtypes)
{
var item = new JObject();
JObject item = new();
funcparams.Add(item);

item["name"] = v.name;
Expand Down Expand Up @@ -191,7 +192,7 @@ private static string ScapeJson(string value)
return value.Replace("\"", "");
}

public static string GenerateManifest(JObject abi, NeoModule module)
public static string GenerateManifest(JObject abi, NeoModule module, MethodToken[] tokens)
{
var sbABI = abi.ToString(false);
var extraAttributes = module == null ? Array.Empty<Mono.Collections.Generic.Collection<CustomAttributeArgument>>() : module.attributes.Where(u => u.AttributeType.FullName == "Neo.SmartContract.Framework.ManifestExtraAttribute").Select(attribute => attribute.ConstructorArguments).ToArray();
Expand All @@ -202,27 +203,22 @@ public static string GenerateManifest(JObject abi, NeoModule module)
.Where(u => u.AttributeType.FullName == "System.ComponentModel.DisplayNameAttribute")
.Select(u => ScapeJson((string)u.ConstructorArguments.FirstOrDefault().Value))
.FirstOrDefault() ?? module.Name;
var permissions =
string.Join(',',
module.attributes

PermissionBuilder permissions = new();
module.attributes
.Where(u => u.AttributeType.FullName == "Neo.SmartContract.Framework.ContractPermissionAttribute")
.Select(u => ContractPermissionToManifest(u))
.ToList());
if (string.IsNullOrEmpty(permissions)) permissions = @"{""contract"":""*"",""methods"":""*""}";
.ToList().ForEach(u =>
{
var methods = (CustomAttributeArgument[])u.ConstructorArguments[1].Value;
var hash = ScapeJson((string)u.ConstructorArguments[0].Value);
permissions.Add(hash, (methods?.Length ?? 0) == 0 ? new string[] { "*" } : methods.Select(u => (string)u.Value).ToArray());
});
tokens.ToList().ForEach(u => permissions.Add(u.Hash.ToString(), new string[] { u.Method }));

return
@"{""groups"":[],""abi"":" + sbABI +
@",""permissions"":[" + permissions + @"],""trusts"":[],""name"":""" + name + @""",""supportedstandards"":" + supportedStandards + @",""extra"":" + extra + "}";
}

private static string ContractPermissionToManifest(CustomAttribute u)
{
var methods = (CustomAttributeArgument[])u.ConstructorArguments[1].Value;
var jsonMethods = ((methods?.Length ?? 0) == 0 || (string)methods[0].Value == "*") ?
"\"*\"" : $"[{string.Join(',', methods.Select(u => "\"" + ScapeJson((string)u.Value) + "\""))}]";

var value = ScapeJson((string)u.ConstructorArguments[0].Value);
return $"{{\"contract\":\"{value}\",\"methods\":{jsonMethods}}}";
@",""permissions"":[" + permissions.ToString() +
@"],""trusts"":[],""name"":""" + name + @""",""supportedstandards"":" + supportedStandards + @",""extra"":" + extra + "}";
}
}
}
34 changes: 17 additions & 17 deletions src/Neo.Compiler.MSIL/NeoModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ public class NeoModule
public string Name;

public ConvOption option;
public List<CustomAttribute> attributes = new List<CustomAttribute>();
public Dictionary<string, NeoMethod> mapMethods = new Dictionary<string, NeoMethod>();
public Dictionary<string, NeoEvent> mapEvents = new Dictionary<string, NeoEvent>();
public Dictionary<string, NeoField> mapFields = new Dictionary<string, NeoField>();
public Dictionary<string, object> staticfieldsWithConstValue = new Dictionary<string, object>();
public List<ILMethod> staticfieldsCctor = new List<ILMethod>();
public SortedDictionary<int, NeoCode> totalCodes = new SortedDictionary<int, NeoCode>();
public List<CustomAttribute> attributes = new();
public Dictionary<string, NeoMethod> mapMethods = new();
public Dictionary<string, NeoEvent> mapEvents = new();
public Dictionary<string, NeoField> mapFields = new();
public Dictionary<string, object> staticfieldsWithConstValue = new();
public List<ILMethod> staticfieldsCctor = new();
public SortedDictionary<int, NeoCode> totalCodes = new();

public byte[] Build()
{
List<byte> bytes = new List<byte>();
List<byte> bytes = new();
foreach (var c in this.totalCodes.Values)
{
bytes.Add((byte)c.code);
Expand All @@ -37,11 +37,11 @@ public byte[] Build()

public string GenJson()
{
JObject json = new JObject();
JObject json = new();
json["__name__"] = "neomodule.";

//code
var jsoncode = new JArray();
JArray jsoncode = new();
json["code"] = jsoncode;
foreach (var c in this.totalCodes.Values)
{
Expand All @@ -57,7 +57,7 @@ public string GenJson()
json["codebin"] = codestr;

//calls
JObject methodinfo = new JObject();
JObject methodinfo = new();
json["call"] = methodinfo;
foreach (var m in this.mapMethods)
{
Expand All @@ -78,28 +78,28 @@ public class NeoMethod
public string _namespace;
public string name;
public string displayName;
public List<NeoParam> paramtypes = new List<NeoParam>();
public List<NeoParam> paramtypes = new();
public TypeReference returntype;
public bool isPublic = true;
public bool inSmartContract;
public ILMethod method;
public ILType type;

public List<NeoParam> body_Variables = new List<NeoParam>(); // Temporary variable
public SortedDictionary<int, NeoCode> body_Codes = new SortedDictionary<int, NeoCode>(); // Temporary records and will be merged later
public List<NeoParam> body_Variables = new(); // Temporary variable
public SortedDictionary<int, NeoCode> body_Codes = new(); // Temporary records and will be merged later
public int funcaddr;

public JObject GenJson()
{
JObject json = new JObject();
JObject json = new();
json["name"] = this.name;
json["returntype"] = FuncExport.ConvType(this.returntype);
json["paramcount"] = this.paramtypes.Count;
JArray jsonparams = new JArray();
JArray jsonparams = new();
json["params"] = jsonparams;
for (var i = 0; i < this.paramtypes.Count; i++)
{
JObject item = new JObject();
JObject item = new();
item["name"] = this.paramtypes[i].name;
item["type"] = FuncExport.ConvType(this.paramtypes[i].type);
jsonparams.Add(item);
Expand Down
89 changes: 89 additions & 0 deletions src/Neo.Compiler.MSIL/PermissionBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using Neo.IO.Json;
using System.Collections.Generic;
using System.Linq;

namespace Neo.Compiler
{
class PermissionBuilder
{
private readonly HashSet<(string Hash, string Method)> normalItems = new();
private readonly HashSet<string> wildcardHashes = new();
private readonly HashSet<string> wildcardMethods = new();
private bool isWildcard;

public void Add(string hash, params string[] methods)
{
foreach (var method in methods) Add(hash, method);
}

public void Add(string hash, string method)
{
if (isWildcard) return;
if (hash == "*")
{
if (method == "*")
{
isWildcard = true;
}
else
{
if (wildcardMethods.Add(method))
normalItems.RemoveWhere(p => p.Method == method);
}
}
else
{
if (method == "*")
{
if (wildcardHashes.Add(hash))
normalItems.RemoveWhere(p => p.Hash == hash);
}
else
{
if (!wildcardHashes.Contains(hash) && !wildcardMethods.Contains(method))
normalItems.Add((hash, method));
}
}
}

public JArray ToJson()
{
JArray permissions = new();
if (isWildcard || normalItems.Count == 0)
{
permissions.Add(new JObject
{
["contract"] = "*",
["methods"] = "*"
});
}
else
{
foreach (var group in normalItems.GroupBy(p => p.Hash, p => p.Method).OrderBy(p => p.Key))
permissions.Add(new JObject
{
["contract"] = group.Key,
["methods"] = new JArray(group.OrderBy(p => p).Select(p => (JString)p))
});
foreach (string hash in wildcardHashes.OrderBy(p => p))
permissions.Add(new JObject
{
["contract"] = hash,
["methods"] = "*"
});
if (wildcardMethods.Count > 0)
permissions.Add(new JObject
{
["contract"] = "*",
["methods"] = new JArray(wildcardMethods.OrderBy(p => p).Select(p => (JString)p))
});
}
return permissions;
}

public override string ToString()
{
return ToJson().ToString(false);
}
}
}
7 changes: 4 additions & 3 deletions src/Neo.Compiler.MSIL/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,14 +207,15 @@ public static int Compile(Options options, ILogger log = null)
}

// Write bytes
NefFile nef;

try
{
string bytesname = onlyname + ".nef";
var nef = new NefFile
nef = new NefFile
{
Compiler = "neon-" + Version.Parse(((AssemblyFileVersionAttribute)Assembly.GetAssembly(typeof(Program))
.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version).ToString(),
.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version).ToString(),
Tokens = conv.methodTokens.ToArray(),
Script = bytes
};
Expand Down Expand Up @@ -277,7 +278,7 @@ public static int Compile(Options options, ILogger log = null)
try
{
string manifest = onlyname + ".manifest.json";
var defManifest = FuncExport.GenerateManifest(abi, module);
var defManifest = FuncExport.GenerateManifest(abi, module, nef.Tokens);

File.Delete(manifest);
File.WriteAllText(manifest, defManifest);
Expand Down
2 changes: 1 addition & 1 deletion tests/Neo.Compiler.MSIL.UnitTests/Utils/BuildScript.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public void Build(Stream fs, Stream fspdb, bool optimizer)

try
{
finalManifest = FuncExport.GenerateManifest(finalABI, converterIL.outModule);
finalManifest = FuncExport.GenerateManifest(finalABI, converterIL.outModule, converterIL.methodTokens.ToArray());
}
catch (Exception err)
{
Expand Down