purne codes

This commit is contained in:
CaiHQ 2024-12-24 13:01:51 +08:00
parent 93ccf7410b
commit 533c92f843

View File

@ -56,9 +56,10 @@ import java.util.*;
import java.util.zip.ZipFile;
public class ContractProcess {
private static final byte[] ZIP_HEADER_1 = new byte[]{80, 75, 3, 4};
private static final byte[] ZIP_HEADER_2 = new byte[]{80, 75, 5, 6};
private static final org.apache.logging.log4j.Logger LOGGER = org.apache.logging.log4j.LogManager.getLogger(ContractProcess.class);
private static final byte[] ZIP_HEADER_1 = new byte[] {80, 75, 3, 4};
private static final byte[] ZIP_HEADER_2 = new byte[] {80, 75, 5, 6};
private static final org.apache.logging.log4j.Logger LOGGER =
org.apache.logging.log4j.LogManager.getLogger(ContractProcess.class);
public static ContractProcess instance;
public final String cmi;
@ -110,7 +111,7 @@ public class ContractProcess {
}
}
Scanner sc = new Scanner(pidInput);
for (String str; sc.hasNextLine(); ) {
for (String str; sc.hasNextLine();) {
str = sc.nextLine();
LOGGER.info("[CP From STDIN] " + str);
if (str.contains("CP PID:")) {
@ -138,7 +139,8 @@ public class ContractProcess {
byte[] buffer = new byte[4];
int length = input.read(buffer, 0, 4);
if (length == 4) {
isArchive = (Arrays.equals(ZIP_HEADER_1, buffer)) || (Arrays.equals(ZIP_HEADER_2, buffer));
isArchive = (Arrays.equals(ZIP_HEADER_1, buffer))
|| (Arrays.equals(ZIP_HEADER_2, buffer));
}
} catch (IOException e) {
e.printStackTrace();
@ -193,7 +195,8 @@ public class ContractProcess {
cn = czb.mergeContractNode();
} else {
cn = compiler.compile(new ByteArrayInputStream(script.getBytes()), "contract_main.yjs");
cn = compiler.compile(new ByteArrayInputStream(script.getBytes()),
"contract_main.yjs");
}
DesktopEngine engine = new DesktopEngine(); // engine.loadJar(zf);
engine.loadContract(c, cn, ret.isInsnLimit);
@ -213,7 +216,8 @@ public class ContractProcess {
MethodNode mn = methods.get(fn.functionName);
if (mn != null) {
System.out.println("[ContractManager] getMethodNode, verify:" + fn.functionName);
System.out
.println("[ContractManager] getMethodNode, verify:" + fn.functionName);
TaintResult.nLocals = mn.maxLocals;
TaintResult.nStack = mn.maxStack;
TaintCFG cfg = new TaintCFG(mn);
@ -222,7 +226,8 @@ public class ContractProcess {
MultiSourceTaintAnalysis analysis = new MultiSourceTaintAnalysis(cfg);
analysis.analysis();
TaintBB bb = cfg.getLastBlock();
if (bb != null) result.addProperty(fn.functionName, bb.getResultWithTaintBit());
if (bb != null)
result.addProperty(fn.functionName, bb.getResultWithTaintBit());
System.out.println("[ContractManager] verifyDone:" + fn.functionName);
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
@ -395,7 +400,8 @@ public class ContractProcess {
String yancloud_desktop = "";
isOpen.put(pmList[0], pmList[1]);
yancloud_desktop += UtilRegistry.getInitStr(pmList[0], pmList[1].equals("open"));
engine.getNashornEngine().getContext().setAttribute(ScriptEngine.FILENAME, yancloud_desktop, ScriptContext.ENGINE_SCOPE);
engine.getNashornEngine().getContext().setAttribute(ScriptEngine.FILENAME,
yancloud_desktop, ScriptContext.ENGINE_SCOPE);
engine.getNashornEngine().eval(yancloud_desktop);
} catch (ScriptException e) {
e.printStackTrace();
@ -417,16 +423,20 @@ public class ContractProcess {
// 判断是否满足Oracle和Contact的执行要求
public String verifyOracleAndContractPermission(Contract contract) {
// 权限校验 如果是Oracle 启动方式只能是Sole 否则报错
if (cn.getYjsType() == YjsType.Oracle && contract.getType() != ContractExecType.Sole && contract.getType() != ContractExecType.Sharding) {
if (cn.getYjsType() == YjsType.Oracle && contract.getType() != ContractExecType.Sole
&& contract.getType() != ContractExecType.Sharding) {
LOGGER.info("Oracle only support Sole ContractType!");
return JsonUtil.toJson(new ContractResult(Status.Error, new JsonPrimitive("Oracle only support Sole ContractType!")));
return JsonUtil.toJson(new ContractResult(Status.Error,
new JsonPrimitive("Oracle only support Sole ContractType!")));
}
// 权限校验 如果是contract 申请了MySQL等权限 报错
if (cn.getYjsType() == YjsType.Contract) {
for (Permission per : cn.getPermission()) {
if (per == Permission.SQL || per == Permission.Http || per == Permission.RocksDB || per == Permission.MongoDB) {
if (per == Permission.SQL || per == Permission.Http || per == Permission.RocksDB
|| per == Permission.MongoDB) {
LOGGER.debug("Contract can not have permissions of IO!");
return JsonUtil.toJson(new ContractResult(Status.Error, new JsonPrimitive("Contract can not have permissions of IO|")));
return JsonUtil.toJson(new ContractResult(Status.Error,
new JsonPrimitive("Contract can not have permissions of IO|")));
}
}
}
@ -435,8 +445,10 @@ public class ContractProcess {
public String setMembers(List<String> members) {
JavaScriptEntry.members = members;
if (members != null) return members.size() + "";
else return "0";
if (members != null)
return members.size() + "";
else
return "0";
}
public String setContractBundle(Contract contract) {
@ -466,7 +478,8 @@ public class ContractProcess {
memorySet = cn.memorySet;
this.contract.sourcePath = zipBundle.getManifest().sourcePath;
LOGGER.debug("check sourcePath\n\tin-contract=" + this.contract.sourcePath + "\n\tin-manifest=" + zipBundle.getManifest().sourcePath);
LOGGER.debug("check sourcePath\n\tin-contract=" + this.contract.sourcePath
+ "\n\tin-manifest=" + zipBundle.getManifest().sourcePath);
// zhanghongwei
/*
@ -508,11 +521,13 @@ public class ContractProcess {
}
} catch (MalformedJsonException | JsonSyntaxException e) {
return JsonUtil.toJson(new ContractResult(Status.Error, new JsonPrimitive("parse manifest.json error, not json format!")));
return JsonUtil.toJson(new ContractResult(Status.Error,
new JsonPrimitive("parse manifest.json error, not json format!")));
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
return JsonUtil.toJson(new ContractResult(Status.Error, new JsonPrimitive(bo.toString())));
return JsonUtil
.toJson(new ContractResult(Status.Error, new JsonPrimitive(bo.toString())));
}
}
@ -559,7 +574,8 @@ public class ContractProcess {
fun.appendBeforeInvokeHandler(accessHandler);
}
fun.appendAfterInvokeHandler(new ObjToJsonHandler());
ResultSchemaHandler resultSchemaHandler = createHandlerIfExist(fun, ResultSchemaHandler.class);
ResultSchemaHandler resultSchemaHandler =
createHandlerIfExist(fun, ResultSchemaHandler.class);
if (resultSchemaHandler != null) {
fun.appendAfterInvokeHandler(resultSchemaHandler);
}
@ -586,8 +602,10 @@ public class ContractProcess {
if (doopRequestHandler == null) {
doopRequestHandler = new DOOPRequestHandler();
}
fun.appendBeforeInvokeHandler(new DOOPBeforeExecHandler(fun.getDoipOperationInfo().operation));
fun.appendAfterInvokeHandler(new DOOPAfterExecHandler(fun.getDoipOperationInfo().operation));
fun.appendBeforeInvokeHandler(
new DOOPBeforeExecHandler(fun.getDoipOperationInfo().operation));
fun.appendAfterInvokeHandler(
new DOOPAfterExecHandler(fun.getDoipOperationInfo().operation));
doopRequestHandler.addDoipOperation(fun);
}
}
@ -595,11 +613,14 @@ public class ContractProcess {
<T extends AnnotationHook> T createHandlerIfExist(FunctionNode function, Class<T> clz) {
YJSAnnotation annotation = clz.getAnnotation(YJSAnnotation.class);
if (annotation == null) return null;
if (annotation == null)
return null;
try {
AnnotationNode node = function.getAnnotation(annotation.name());
if (node == null) return null;
Method m = clz.getDeclaredMethod("fromAnnotationNode", FunctionNode.class, AnnotationNode.class);
if (node == null)
return null;
Method m = clz.getDeclaredMethod("fromAnnotationNode", FunctionNode.class,
AnnotationNode.class);
T result = (T) m.invoke(null, function, node);
return result;
} catch (Exception e) {
@ -624,8 +645,10 @@ public class ContractProcess {
fixContractIfNecessary(contract);
JavaScriptEntry.random = new Random();
JavaScriptEntry.invokeID = 0L;
if (contract.getID() == null) JavaScriptEntry.random.setSeed(contract.getScriptStr().hashCode());
else JavaScriptEntry.random.setSeed(Integer.parseInt(contract.getID()));
if (contract.getID() == null)
JavaScriptEntry.random.setSeed(contract.getScriptStr().hashCode());
else
JavaScriptEntry.random.setSeed(Integer.parseInt(contract.getID()));
JavaScriptEntry.numOfCopies = contract.getNumOfCopies();
// TODO Optimize, 4 seconds takes to create an Engine.
engine = new DesktopEngine();
@ -661,7 +684,8 @@ public class ContractProcess {
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
return JsonUtil.toJson(new ContractResult(Status.Error, new JsonPrimitive(bo.toString())));
return JsonUtil
.toJson(new ContractResult(Status.Error, new JsonPrimitive(bo.toString())));
}
}
@ -676,9 +700,11 @@ public class ContractProcess {
if (createParams.has("router")) {
JsonElement routerInfo = createParams.get("router");
if (!routerInfo.isJsonObject())
throw new Exception("Provide wrong router info in create params to DoipModule");
throw new Exception(
"Provide wrong router info in create params to DoipModule");
else {
EndpointConfig endpointConfig = JsonUtil.GSON.fromJson(routerInfo.getAsJsonObject(), EndpointConfig.class);
EndpointConfig endpointConfig = JsonUtil.GSON
.fromJson(routerInfo.getAsJsonObject(), EndpointConfig.class);
DoipClusterServer.createDOOPServerInstance(endpointConfig);
}
} else {
@ -693,16 +719,20 @@ public class ContractProcess {
}
}
public void invokeOnStartingDoipServer(ContractNode cn, JsonElement arg, JsonObject returnValue) {
public void invokeOnStartingDoipServer(ContractNode cn, JsonElement arg,
JsonObject returnValue) {
ContractRequest onStartingDoipServer = new ContractRequest();
onStartingDoipServer.setAction("onServerStart");
if (arg == null) {
if (engine != null && engine.getManifest() != null && engine.getManifest().createParam != null)
if (engine != null && engine.getManifest() != null
&& engine.getManifest().createParam != null)
arg = engine.getManifest().createParam;
else arg = new JsonPrimitive("");
else
arg = new JsonPrimitive("");
}
onStartingDoipServer.setArg(arg);
LOGGER.debug("invoke onStartingDoipServer, param:" + onStartingDoipServer.getArg().toString());
LOGGER.debug(
"invoke onStartingDoipServer, param:" + onStartingDoipServer.getArg().toString());
onStartingDoipServer.setRequester(contract.getOwner());
FunctionNode funNode = cn.getFunction("onServerStart");
@ -713,13 +743,16 @@ public class ContractProcess {
if (arg.isJsonObject() && arg.getAsJsonObject().has("doipStartPort")) {
startPort = arg.getAsJsonObject().get("doipStartPort").getAsInt();
}
LOGGER.info("Fetch the onStartingDoipServerRes from router successfully, the result is " + onStartingDoipServerRes);
int doipListenPort = DoipClusterServer.startDoipServer(startPort, onStartingDoipServerRes);
LOGGER.info("Fetch the onStartingDoipServerRes from router successfully, the result is "
+ onStartingDoipServerRes);
int doipListenPort =
DoipClusterServer.startDoipServer(startPort, onStartingDoipServerRes);
returnValue.addProperty("doipListenPort", doipListenPort);
this.contract.setDoipPort(doipListenPort);
returnValue.addProperty("doipStartPort", startPort);
} catch (Exception e) {
LOGGER.error("DoipLocalSingleton cannot starts properly, plz check the onServerStart function");
LOGGER.error(
"DoipLocalSingleton cannot starts properly, plz check the onServerStart function");
e.printStackTrace();
}
funNode = cn.getFunction("onInitSharableVars");
@ -754,7 +787,8 @@ public class ContractProcess {
}
}
if (fun.getLogToBDContract()) detail.append("bdcontract;");
if (fun.getLogToBDContract())
detail.append("bdcontract;");
if (fun.getLogToNamedLedger()) {
for (String str : fun.getLedgerNames()) {
detail.append("bdledger:").append(str).append(";");
@ -792,16 +826,19 @@ public class ContractProcess {
}
JavaScriptEntry.setSM2KeyPair(contract.getPublicKey(), contract.getKey());
if (null != contract.getAuthInfoPersistDOI() && !contract.getAuthInfoPersistDOI().isEmpty()) {
if (null != contract.getAuthInfoPersistDOI()
&& !contract.getAuthInfoPersistDOI().isEmpty()) {
JavaScriptEntry.authInfoPersistDOI = contract.getAuthInfoPersistDOI();
}
JavaScriptEntry.isDebug = contract.isDebug();
ContractRequest onCreate = new ContractRequest();
onCreate.setAction("onCreate");
if (arg == null) {
if (engine != null && engine.getManifest() != null && engine.getManifest().createParam != null)
if (engine != null && engine.getManifest() != null
&& engine.getManifest().createParam != null)
arg = engine.getManifest().createParam;
else arg = new JsonPrimitive("");
else
arg = new JsonPrimitive("");
}
onCreate.setArg(arg);
LOGGER.debug("invoke onCreate, param:" + onCreate.getArg().toString());
@ -811,14 +848,17 @@ public class ContractProcess {
}
public void resetContractName(String name) {
if (name != null) cn.resetContractName(name);
if (name != null)
cn.resetContractName(name);
}
private ContractResult invokeOnRecover(JsonElement arg) {
ContractRequest onRecover = new ContractRequest();
onRecover.setAction("onRecover");
if (arg == null) onRecover.setArg("null");
else onRecover.setArg(arg);
if (arg == null)
onRecover.setArg("null");
else
onRecover.setArg(arg);
onRecover.setRequester(contract.getOwner());
FunctionNode funNode = cn.getFunction("onRecover");
return invoke(onRecover, funNode);
@ -868,11 +908,11 @@ public class ContractProcess {
List<Long> hashes = logIndex.request(offset, size);
List<Map<String, String>> jo = new ArrayList<>();
TypeToken<Map<String, String>> token = new TypeToken<Map<String, String>>() {
};
TypeToken<Map<String, String>> token = new TypeToken<Map<String, String>>() {};
for (Long hash : hashes)
try {
Map<String, String> obj = JsonUtil.fromJson(edion.get(hash.toString()), token.getType());
Map<String, String> obj =
JsonUtil.fromJson(edion.get(hash.toString()), token.getType());
jo.add(obj);
} catch (JsonSyntaxException e) {
e.printStackTrace();
@ -883,8 +923,7 @@ public class ContractProcess {
public String requestLast(int count) {
List<Long> hashes = logIndex.requestLast(count);
List<Map<String, String>> jo = new ArrayList<>();
TypeToken<Map<String, String>> token = new TypeToken<Map<String, String>>() {
};
TypeToken<Map<String, String>> token = new TypeToken<Map<String, String>>() {};
String log;
for (Long hash : hashes)
try {
@ -894,7 +933,8 @@ public class ContractProcess {
}
Map<String, String> obj = JsonUtil.fromJson(log, token.getType());
if (obj == null) {
System.out.println("[ContractProcess] requestLast, parseJsonError:" + log + "==");
System.out
.println("[ContractProcess] requestLast, parseJsonError:" + log + "==");
continue;
}
obj.put("hash", hash + "");
@ -937,7 +977,8 @@ public class ContractProcess {
try {
request = JsonUtil.fromJson(arg, ContractRequest.class);
} catch (Exception ignored) {
result = new ContractResult(ContractResult.Status.Error, new JsonPrimitive("Illegal Arguments!"));
result = new ContractResult(ContractResult.Status.Error,
new JsonPrimitive("Illegal Arguments!"));
return JsonUtil.toJson(result);
}
String reqID = request.getRequestID();
@ -979,7 +1020,8 @@ public class ContractProcess {
evaluatesAnalysis(request.getAction());
}
engine.redirectTracePS(new ProgramPointCounter(bo, this, gasLimit, functionIndex, request.getValue(), 0L, request.getAction(), ppCountMap));
engine.redirectTracePS(new ProgramPointCounter(bo, this, gasLimit, functionIndex,
request.getValue(), 0L, request.getAction(), ppCountMap));
result = engine.executeContract(request);
result.analysis = bo.toString();
@ -1087,7 +1129,8 @@ public class ContractProcess {
TaintBB bb = cfg.getLastBlock();
result.analysis = bb.getResultWithTaintBit();
System.out.println("[ContractProcess] dynamically verify: " + ac.getAction() + "-->" + result.analysis);
System.out.println("[ContractProcess] dynamically verify: " + ac.getAction() + "-->"
+ result.analysis);
}
}
@ -1109,8 +1152,7 @@ public class ContractProcess {
return !JavaScriptEntry.topic_handlers.isEmpty();
}
public void beforeSuicide() {
}
public void beforeSuicide() {}
public String redo(String path) {
return engine.syncUtil.redo(path);
@ -1165,8 +1207,7 @@ public class ContractProcess {
}
@Override
protected void finalize() {
}
protected void finalize() {}
public String getDeclaredEvents() {
return JsonUtil.toJson(cn.events);
@ -1181,7 +1222,8 @@ public class ContractProcess {
for (FunctionNode fn : cn.getFunctions()) {
if (fn.isExport() && !fn.functionName.equals("onCreate")) {
function.add(fn.functionName);
FunctionDesp desp = new FunctionDesp(fn.functionName, fn.annotations, fn.getRouteInfo(), fn.getJoinInfo(), fn.isView());
FunctionDesp desp = new FunctionDesp(fn.functionName, fn.annotations,
fn.getRouteInfo(), fn.getJoinInfo(), fn.isView());
ret.add(desp);
}
}
@ -1202,7 +1244,8 @@ public class ContractProcess {
public String startAutoDump() {
String dumpPeriod = projectConfig.getDumpPeriod();
System.out.println("[ContractProcess] startAutoDump : " + cn.getContractName() + " period = " + dumpPeriod);
System.out.println("[ContractProcess] startAutoDump : " + cn.getContractName()
+ " period = " + dumpPeriod);
String status = "startAutoDump status 0";
if (null != dt) {
if (null == dumpPeriod || dumpPeriod.isEmpty()) {
@ -1383,7 +1426,8 @@ public class ContractProcess {
private class DumpTask extends TimerTask {
@Override
public void run() {
System.out.println("[ContractProcess DumpTask] auto dump period : " + projectConfig.getDumpPeriod());
System.out.println("[ContractProcess DumpTask] auto dump period : "
+ projectConfig.getDumpPeriod());
File file1 = new File(dir);
File file2 = new File(file1.getParent());
String dir2 = file2.getParent() + "/memory/";