feat: support jsontype in executeContract

This commit is contained in:
CaiHQ 2021-12-03 11:17:58 +08:00
parent f72e05679c
commit 372a8bd869
12 changed files with 80 additions and 78 deletions

View File

@ -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<String, CFGraph> CFGmap = new HashMap<>();
HashMap<String, Long> ppCountMap = new HashMap<>();
List<String> function = new ArrayList<>();
private Global global;
private TimeSerialIndex logIndex;
private RocksDBUtil edion;
private String pid;

View File

@ -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 + "<seperate>" + flag + "<seperate>" + 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 + "<seperate>" + flag + "<seperate>" + 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);

View File

@ -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());

View File

@ -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,

View File

@ -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());
}

View File

@ -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<Object> 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<Object> 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;
}
}

View File

@ -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",

View File

@ -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("\"", ""));

View File

@ -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;
}
}
}

View File

@ -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);
}
}

View File

@ -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);
}

View File

@ -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();