From 372a8bd8697a97a3d827123d030bb6439e6b6773 Mon Sep 17 00:00:00 2001 From: CaiHQ Date: Fri, 3 Dec 2021 11:17:58 +0800 Subject: [PATCH] feat: support jsontype in executeContract --- .../java/org/bdware/sc/ContractProcess.java | 2 - .../bdware/sc/boundry/JavaScriptEntry.java | 18 +++--- .../bdware/sc/boundry/utils/RocksDBUtil.java | 1 + .../org/bdware/sc/boundry/utils/SM2Util.java | 3 - .../org/bdware/sc/engine/DesktopEngine.java | 7 ++- .../java/org/bdware/sc/engine/JSONTool.java | 56 ++++++++++++------- .../hook/HomomorphicDecryptHandler.java | 2 +- .../hook/HomomorphicEncryptHandler.java | 2 +- .../sc/engine/hook/MockTemplateHandler.java | 27 +++++---- .../sc/engine/hook/ObjToJsonHandler.java | 27 +-------- .../org/bdware/sc/redo/TransRecordUtil.java | 5 +- .../org/bdware/sc/redo/TransRecoverUtil.java | 8 ++- 12 files changed, 80 insertions(+), 78 deletions(-) diff --git a/src/main/java/org/bdware/sc/ContractProcess.java b/src/main/java/org/bdware/sc/ContractProcess.java index 641ea24..caa3df4 100644 --- a/src/main/java/org/bdware/sc/ContractProcess.java +++ b/src/main/java/org/bdware/sc/ContractProcess.java @@ -5,7 +5,6 @@ import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.MalformedJsonException; -import jdk.nashorn.internal.objects.Global; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; @@ -77,7 +76,6 @@ public class ContractProcess { HashMap CFGmap = new HashMap<>(); HashMap ppCountMap = new HashMap<>(); List function = new ArrayList<>(); - private Global global; private TimeSerialIndex logIndex; private RocksDBUtil edion; private String pid; diff --git a/src/main/java/org/bdware/sc/boundry/JavaScriptEntry.java b/src/main/java/org/bdware/sc/boundry/JavaScriptEntry.java index 5a52252..953be3d 100644 --- a/src/main/java/org/bdware/sc/boundry/JavaScriptEntry.java +++ b/src/main/java/org/bdware/sc/boundry/JavaScriptEntry.java @@ -10,6 +10,7 @@ import org.bdware.sc.boundry.utils.SQLUtil; import org.bdware.sc.conn.ResultCallback; import org.bdware.sc.conn.SocketGet; import org.bdware.sc.engine.DesktopEngine; +import org.bdware.sc.engine.JSONTool; import org.bdware.sc.engine.SyncMechUtil; import org.bdware.sc.event.REvent; import org.bdware.sc.http.ApiGate; @@ -299,7 +300,7 @@ public class JavaScriptEntry { } } - public static String executeContract(String contractID, String action, String arg) { + public static Object executeContract(String contractID, String action, Object arg) { if (currentSyncUtil.engine.recovering) { String str = currentSyncUtil.transRecoverUtil.curRecoverRecord.getExecuteResult( @@ -314,7 +315,8 @@ public class JavaScriptEntry { if (flag.equals("1")) { random.nextInt(); } - return res; + JsonObject jo = JsonUtil.parseStringAsJsonObject(res); + return JSONTool.convertJsonElementToMirror(jo); } long formerInvokeID = invokeID; @@ -323,7 +325,7 @@ public class JavaScriptEntry { try { ContractRequest app = new ContractRequest(); - app.setContractID(contractID).setAction(action).setArg(arg); + app.setContractID(contractID).setAction(action).setArg(JSONTool.convertMirrorToJson(arg)); app.doSignature(keyPair); app.setRequesterDOI(doi); app.setFromDebug(isDebug); @@ -360,11 +362,12 @@ public class JavaScriptEntry { currentSyncUtil.transRecordUtil.recordExecutes( formerInvokeID + "", flag1 + "" + flag + "" + result); } - return result; + JsonObject jo = JsonUtil.parseStringAsJsonObject(result); + return JSONTool.convertJsonElementToMirror(jo); } } - private static String executeContract(long formerInvokeID, int flag1, int flag, ContractRequest app) { + private static Object executeContract(long formerInvokeID, int flag1, int flag, ContractRequest app) { String result = get.syncGet("dd", "executeContract", JsonUtil.toJson(app)); if (currentSyncUtil.startFlag && currentSyncUtil.currType == SyncType.Trans @@ -373,7 +376,8 @@ public class JavaScriptEntry { formerInvokeID + "", flag1 + "" + flag + "" + result); } - return result; + JsonObject jo = JsonUtil.parseStringAsJsonObject(result); + return JSONTool.convertJsonElementToMirror(jo); } public static void executeContractAsyncWithoutSig( @@ -401,7 +405,7 @@ public class JavaScriptEntry { } } - /* public static String executeContract(String contractID, String action, String arg) { + /*public static String executeContract(String contractID, String action, String arg) { //redo,use record data if(currentSyncUtil.transRecoverUtil != null && currentSyncUtil.transRecoverUtil.recovering){ String k = TransRecordUtil.produceExecuteIdentifier(contractID,action,arg); diff --git a/src/main/java/org/bdware/sc/boundry/utils/RocksDBUtil.java b/src/main/java/org/bdware/sc/boundry/utils/RocksDBUtil.java index a46306b..843e403 100644 --- a/src/main/java/org/bdware/sc/boundry/utils/RocksDBUtil.java +++ b/src/main/java/org/bdware/sc/boundry/utils/RocksDBUtil.java @@ -38,6 +38,7 @@ public class RocksDBUtil { File parent = new File("./ContractDB/" + ContractProcess.getContractDir()); File dir = new File(parent, path); + System.out.println("[EEEEEEEEEERO]"); LOGGER.info("init RocksDB in " + dir.getAbsolutePath()); if (!dir.exists()) { LOGGER.trace("create directory " + dir.getAbsolutePath() + ": " + dir.mkdirs()); diff --git a/src/main/java/org/bdware/sc/boundry/utils/SM2Util.java b/src/main/java/org/bdware/sc/boundry/utils/SM2Util.java index cdf9bc8..0976f2b 100644 --- a/src/main/java/org/bdware/sc/boundry/utils/SM2Util.java +++ b/src/main/java/org/bdware/sc/boundry/utils/SM2Util.java @@ -8,7 +8,6 @@ import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.pqc.math.linearalgebra.ByteUtils; import org.zz.gmhelper.BCECUtil; import org.zz.gmhelper.SM2KeyPair; -import org.zz.gmhelper.SM3Util; import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror; import wrp.jdk.nashorn.internal.runtime.PropertyMap; import wrp.jdk.nashorn.internal.runtime.ScriptObject; @@ -34,7 +33,6 @@ public class SM2Util { ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(privateKey, org.zz.gmhelper.SM2Util.DOMAIN_PARAMS); byte[] sign = org.zz.gmhelper.SM2Util.sign(priKey, content.getBytes()); - sign = org.zz.gmhelper.SM2Util.decodeDERSM2Sign(sign); ret.put("status", "success", false); ret.put("signature", ByteUtils.toHexString(sign), false); } catch (Exception e) { @@ -48,7 +46,6 @@ public class SM2Util { JO ret = new JO(PropertyMap.newMap()); try { byte[] sig = ByteUtils.fromHexString(signature); - sig = org.zz.gmhelper.SM2Util.encodeSM2SignToDER(sig); ECPublicKeyParameters pubKey = BCECUtil.createECPublicKeyFromStrParameters( pubKeyStr, diff --git a/src/main/java/org/bdware/sc/engine/DesktopEngine.java b/src/main/java/org/bdware/sc/engine/DesktopEngine.java index 0d9fb3b..ab9d859 100644 --- a/src/main/java/org/bdware/sc/engine/DesktopEngine.java +++ b/src/main/java/org/bdware/sc/engine/DesktopEngine.java @@ -427,6 +427,11 @@ public class DesktopEngine extends JSEngine { } JavaScriptEntry.msgList = new ArrayList<>(); FunctionNode fun = cn.getFunction(input.getAction()); + if (fun == null) { + return new ContractResult( + Status.Exception, + new JsonPrimitive("Action " + input.getAction() + " is not exists")); + } ProgramPointCounter ppc = null; try { if (fun.getCost() != null && fun.getCost().isCountGas()) { @@ -473,7 +478,7 @@ public class DesktopEngine extends JSEngine { input.getAction(), (fun.isHandler() ? JsonUtil.fromJson(input.getArg(), Event.class) - : input.getArg()), + : JSONTool.convertJsonElementToMirror(input.getArg())), input.getRequester(), input.getRequesterDOI()); } diff --git a/src/main/java/org/bdware/sc/engine/JSONTool.java b/src/main/java/org/bdware/sc/engine/JSONTool.java index 3b9e2de..50f67b1 100644 --- a/src/main/java/org/bdware/sc/engine/JSONTool.java +++ b/src/main/java/org/bdware/sc/engine/JSONTool.java @@ -1,24 +1,46 @@ package org.bdware.sc.engine; import com.google.gson.*; - import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror; +import wrp.jdk.nashorn.internal.runtime.PropertyMap; +import wrp.jdk.nashorn.internal.scripts.JO; import java.util.HashSet; import java.util.Set; public class JSONTool { - private static Set recorded = null; - - public static JsonElement copy(ScriptObjectMirror ret2) { - recorded = new HashSet<>(); - JsonElement jsonElement = copyInternal(ret2); - recorded.clear(); - ; + public static JsonElement convertMirrorToJson(Object ret2) { + JsonElement jsonElement = convertMirrorToJsonInternal(ret2, new HashSet<>()); return jsonElement; } - private static JsonElement copyInternal(Object obj) { + public static Object convertJsonElementToMirror(JsonElement jsonElement) { + if (jsonElement.isJsonPrimitive()) { + JsonPrimitive primitive = jsonElement.getAsJsonPrimitive(); + if (primitive.isString()) + return primitive.getAsString(); + else if (primitive.isBoolean()) + return primitive.getAsBoolean(); + return primitive.getAsNumber(); + } else if (jsonElement.isJsonObject()) { + JO jo = new JO(PropertyMap.newMap()); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + for (String key : jsonObject.keySet()) { + jo.put(key, convertJsonElementToMirror(jsonObject.get(key)), false); + } + return jo; + } else if (jsonElement.isJsonArray()) { + JO jo = new JO(PropertyMap.newMap()); + jo.setIsArray(); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + for (int i = 0; i < jsonArray.size(); i++) + jo.put(i, convertJsonElementToMirror(jsonArray.get(i)), false); + return jo; + } + return null; + } + + private static JsonElement convertMirrorToJsonInternal(Object obj, Set recorded) { if (recorded.contains(obj)) return JsonNull.INSTANCE; if (obj == null) return JsonNull.INSTANCE; if (obj.getClass() == wrp.jdk.nashorn.internal.runtime.Undefined.class) @@ -35,7 +57,7 @@ public class JSONTool { for (String str : som.getOwnKeys(true)) { try { if (Integer.parseInt(str) >= 0) - jarray.add(copyInternal(som.getMember(str))); + jarray.add(convertMirrorToJsonInternal(som.getMember(str),recorded)); } catch (Exception e) { // System.out.println("[JSONTool] ignore key:"+str); } @@ -44,7 +66,7 @@ public class JSONTool { } else { JsonObject jo = new JsonObject(); for (String str : som.getOwnKeys(true)) { - jo.add(str, copyInternal(som.getMember(str))); + jo.add(str, convertMirrorToJsonInternal(som.getMember(str),recorded)); } return jo; } @@ -61,7 +83,7 @@ public class JSONTool { for (String str : som.getOwnKeys(true)) { try { if (Integer.parseInt(str) >= 0) - jarray.add(copyInternal(som.getMember(str))); + jarray.add(convertMirrorToJsonInternal(som.getMember(str),recorded)); } catch (Exception e) { // System.out.println("[JSONTool] ignore key:"+str); } @@ -70,7 +92,7 @@ public class JSONTool { } else { JsonObject jo = new JsonObject(); for (String str : som.getOwnKeys(true)) { - jo.add(str, copyInternal(som.getMember(str))); + jo.add(str, convertMirrorToJsonInternal(som.getMember(str),recorded)); } return jo; } @@ -90,12 +112,4 @@ public class JSONTool { } return JsonNull.INSTANCE; } - - public static JsonElement copy(jdk.nashorn.api.scripting.ScriptObjectMirror res) { - recorded = new HashSet<>(); - JsonElement jsonElement = copyInternal(res); - recorded.clear(); - ; - return jsonElement; - } } diff --git a/src/main/java/org/bdware/sc/engine/hook/HomomorphicDecryptHandler.java b/src/main/java/org/bdware/sc/engine/hook/HomomorphicDecryptHandler.java index ddb99a0..761f14d 100644 --- a/src/main/java/org/bdware/sc/engine/hook/HomomorphicDecryptHandler.java +++ b/src/main/java/org/bdware/sc/engine/hook/HomomorphicDecryptHandler.java @@ -33,7 +33,7 @@ public class HomomorphicDecryptHandler implements AnnotationHook { // String arg = JsonUtil.toJson(args); JsonElement homoDecryptConf = this.fun.getHomoDecryptConf(); if (null != homoDecryptConf && !homoDecryptConf.isJsonNull()) { - String res = + String res = (String) JavaScriptEntry.executeContract( "keyManager_1", "getPrivKey", diff --git a/src/main/java/org/bdware/sc/engine/hook/HomomorphicEncryptHandler.java b/src/main/java/org/bdware/sc/engine/hook/HomomorphicEncryptHandler.java index c0937cd..e269188 100644 --- a/src/main/java/org/bdware/sc/engine/hook/HomomorphicEncryptHandler.java +++ b/src/main/java/org/bdware/sc/engine/hook/HomomorphicEncryptHandler.java @@ -37,7 +37,7 @@ public class HomomorphicEncryptHandler implements AnnotationHook { JsonElement homoEncryptConf = this.fun.getHomoEncryptConf(); if (homoEncryptConf != null && !homoEncryptConf.isJsonNull()) { String res = - JavaScriptEntry.executeContract( + (String) JavaScriptEntry.executeContract( "keyManager_1", "getPubKey", this.fun.getSecretID().replaceAll("\"", "")); diff --git a/src/main/java/org/bdware/sc/engine/hook/MockTemplateHandler.java b/src/main/java/org/bdware/sc/engine/hook/MockTemplateHandler.java index bcbc083..8b9a29b 100644 --- a/src/main/java/org/bdware/sc/engine/hook/MockTemplateHandler.java +++ b/src/main/java/org/bdware/sc/engine/hook/MockTemplateHandler.java @@ -10,17 +10,22 @@ import org.bdware.sc.node.AnnotationHook; public class MockTemplateHandler implements AnnotationHook { @Override public Object handle(ContractRequest request, JSEngine engine, Object ret) { - if (request.fromDebug()) { - System.out.println(request.getAction()); - DesktopEngine desktopEngine = (DesktopEngine) engine; - ProjectConfig projectConfig = desktopEngine.getProjectConfig(); - String template = projectConfig.getMock(request.getAction()); - if (template != null && template.length() > 0) { - System.out.println(template); - MockUtil Mock = new MockUtil(); - return Mock.mock(template).toString(); + try { + if (request.fromDebug()) { + System.out.println(request.getAction()); + DesktopEngine desktopEngine = (DesktopEngine) engine; + ProjectConfig projectConfig = desktopEngine.getProjectConfig(); + String template = projectConfig.getMock(request.getAction()); + if (template != null && template.length() > 0) { + System.out.println(template); + MockUtil Mock = new MockUtil(); + return Mock.mock(template).toString(); + } else return ret; //When mock config is null defined just ignore. } - else return ret; //When mock config is null defined just ignore. - } else return ret; + } catch (Exception e) { + e.printStackTrace(); + } finally { + return ret; + } } } diff --git a/src/main/java/org/bdware/sc/engine/hook/ObjToJsonHandler.java b/src/main/java/org/bdware/sc/engine/hook/ObjToJsonHandler.java index d1cff64..c1af666 100644 --- a/src/main/java/org/bdware/sc/engine/hook/ObjToJsonHandler.java +++ b/src/main/java/org/bdware/sc/engine/hook/ObjToJsonHandler.java @@ -10,33 +10,8 @@ import org.bdware.sc.node.AnnotationHook; import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror; public class ObjToJsonHandler implements AnnotationHook { -// private static final Logger LOGGER = LogManager.getLogger(ObjToJsonHandler.class); - @Override public Object handle(ContractRequest input, JSEngine desktopEngine, Object ret) { - JsonElement je; - if (ret == null) { - je = JsonNull.INSTANCE; - } else if (ret instanceof ScriptObjectMirror) { - ScriptObjectMirror ret2 = (ScriptObjectMirror) ret; - // LOGGER.debug("[before parse to json]" + ret2); - je = JSONTool.copy(ret2); - } else if (ret instanceof jdk.nashorn.api.scripting.ScriptObjectMirror) { - jdk.nashorn.api.scripting.ScriptObjectMirror ret2 = - (jdk.nashorn.api.scripting.ScriptObjectMirror) ret; - // LOGGER.debug("[before parse to json]" + ret2); - je = JSONTool.copy(ret2); - } else if (ret instanceof Number) { - je = new JsonPrimitive((Number) ret); - } else if (ret instanceof Character) { - je = new JsonPrimitive((Character) ret); - } else if (ret instanceof Boolean) { - je = new JsonPrimitive((Boolean) ret); - } else if (ret instanceof String) { - je = new JsonPrimitive((String) ret); - } else { - je = new JsonPrimitive(ret.toString()); - } - return je; + return JSONTool.convertMirrorToJson(ret); } } diff --git a/src/main/java/org/bdware/sc/redo/TransRecordUtil.java b/src/main/java/org/bdware/sc/redo/TransRecordUtil.java index 4762b3b..530872b 100644 --- a/src/main/java/org/bdware/sc/redo/TransRecordUtil.java +++ b/src/main/java/org/bdware/sc/redo/TransRecordUtil.java @@ -1,5 +1,6 @@ package org.bdware.sc.redo; +import com.google.gson.JsonElement; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bdware.sc.engine.DesktopEngine; @@ -30,12 +31,12 @@ public class TransRecordUtil { } //每次事务开始时初始化 - public void startNext(String fun, String arg, int sequence) { + public void startNext(String fun, JsonElement arg, int sequence) { //logger.debug("TransRecordUtil 开始记录事务"); currentTransRecord = new TransRecord(fun, arg, sequence); } - public void startNext(String fun, String arg) { + public void startNext(String fun, JsonElement arg) { //logger.debug("TransRecordUtil 开始记录事务"); currentTransRecord = new TransRecord(fun, arg); } diff --git a/src/main/java/org/bdware/sc/redo/TransRecoverUtil.java b/src/main/java/org/bdware/sc/redo/TransRecoverUtil.java index 70ed12e..5b5f4bf 100644 --- a/src/main/java/org/bdware/sc/redo/TransRecoverUtil.java +++ b/src/main/java/org/bdware/sc/redo/TransRecoverUtil.java @@ -1,10 +1,12 @@ package org.bdware.sc.redo; +import com.google.gson.JsonElement; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bdware.sc.ContractResult; import org.bdware.sc.bean.ContractRequest; import org.bdware.sc.engine.DesktopEngine; +import org.bdware.sc.util.JsonUtil; import java.io.*; import java.util.ArrayList; @@ -44,9 +46,9 @@ public class TransRecoverUtil { System.out.println("恢复时加入 " + cur_read.toString()); } if (strs[1].equals("true")) - cur_read = new TransRecord(strs[3], arg, Integer.parseInt(strs[2])); + cur_read = new TransRecord(strs[3], JsonUtil.parseString(arg), Integer.parseInt(strs[2])); else - cur_read = new TransRecord(strs[3], arg); + cur_read = new TransRecord(strs[3], JsonUtil.parseString(arg)); } else { cur_read.addExecutes(strs[0], strs[1]); } @@ -70,7 +72,7 @@ public class TransRecoverUtil { for (int i = 0; i < transRecords.size(); i++) { curRecoverRecord = transRecords.get(i); String funName = curRecoverRecord.getFuncName(); - String arg = curRecoverRecord.getArg(); + JsonElement arg = curRecoverRecord.getArg(); ContractRequest ac = null; ac = new ContractRequest();