purne codes

This commit is contained in:
CaiHQ 2024-12-24 13:01:42 +08:00
parent b50f891f02
commit 93ccf7410b
3 changed files with 83 additions and 108 deletions

View File

@ -8,7 +8,7 @@ plugins {
apply from: '../spotless.gradle'
group = "org.bdware.sc"
version = "1.10.1"
version = "1.10.2"
tasks.withType(JavaCompile) {
// options.compilerArgs << '-Xlint:none'
// options.compilerArgs << '-Xlint:deprecation' << "-Werror"
@ -45,14 +45,14 @@ dependencies {
implementation 'com.atlassian.commonmark:commonmark:0.17.0'
implementation 'com.idealista:format-preserving-encryption:1.0.0'
implementation 'org.apache.commons:commons-math3:3.6.1'
implementation 'org.codehaus.groovy:groovy-all:3.0.8'
implementation 'io.grpc:grpc-all:1.41.0'
implementation 'org.codehaus.groovy:groovy-all:3.0.8'
implementation 'io.grpc:grpc-all:1.64.0'
implementation 'org.jsoup:jsoup:1.14.2'
implementation 'com.sun.mail:javax.mail:1.6.2'
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'org.bdware.bdcontract:sdk-java:1.0.2'
implementation 'org.bdware.doip:doip-audit-tool:1.5.1'
implementation 'org.bdware.doip:doip-sdk:1.5.5'
implementation 'org.bdware.doip:doip-audit-tool:1.5.4'
implementation 'org.bdware.doip:doip-sdk:1.5.7'
implementation 'org.apache.logging.log4j:log4j-layout-template-json:2.17.2'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.3'
implementation fileTree(dir: 'lib', include: '*.jar')

View File

@ -42,6 +42,8 @@ import org.bdware.sc.util.JsonUtil;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.zz.gmhelper.SM2KeyPair;
import org.zz.gmhelper.SM2Util;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
@ -54,10 +56,9 @@ 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;
@ -109,7 +110,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:")) {
@ -137,8 +138,7 @@ 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,8 +193,7 @@ 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);
@ -214,8 +213,7 @@ 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);
@ -224,8 +222,7 @@ 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();
@ -398,8 +395,7 @@ 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();
@ -421,20 +417,16 @@ 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|")));
}
}
}
@ -443,17 +435,17 @@ 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) {
try {
fixContractIfNecessary(contract);
// long start = System.currentTimeMillis();
// long start0 = start;
this.contract = contract;
JavaScriptEntry.random = new Random();
JavaScriptEntry.invokeID = 0L;
JavaScriptEntry.random.setSeed(Integer.parseInt(contract.getID()));
@ -474,8 +466,7 @@ 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
/*
@ -517,13 +508,21 @@ 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())));
}
}
private void fixContractIfNecessary(Contract contract) {
if (contract.getID() == null)
contract.setID(contract.getScriptStr().hashCode() + "");
if (contract.getPublicKey() == null) {
SM2KeyPair pair = SM2Util.generateSM2KeyPair();
contract.setKey(pair.getPrivateKeyStr());
contract.setPublicKey(pair.getPublicKeyStr());
}
}
@ -560,8 +559,7 @@ 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);
}
@ -588,10 +586,8 @@ 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);
}
}
@ -599,14 +595,11 @@ 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) {
@ -628,9 +621,11 @@ public class ContractProcess {
public String setContract(Contract contract) {
try {
fixContractIfNecessary(contract);
JavaScriptEntry.random = new Random();
JavaScriptEntry.invokeID = 0L;
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();
@ -666,8 +661,7 @@ 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())));
}
}
@ -682,11 +676,9 @@ 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 {
@ -701,20 +693,16 @@ 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");
@ -725,16 +713,13 @@ 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");
@ -769,8 +754,7 @@ 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(";");
@ -808,19 +792,16 @@ 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());
@ -830,17 +811,14 @@ 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);
@ -890,11 +868,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();
@ -905,7 +883,8 @@ 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 {
@ -915,8 +894,7 @@ 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 + "");
@ -959,8 +937,7 @@ 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();
@ -982,8 +959,8 @@ public class ContractProcess {
result = engine.executeContract(request);
result.analysis = bo.toString();
System.out.println("[ContractProcess] result.analysis = " + result.analysis); // 动态分析bug
// null
// pointer
// null
// pointer
// branchResult = JsonUtil.toJson(result);
// branchTrace = result.analysis;
engine.redirectTracePS(previous);
@ -1002,8 +979,7 @@ 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();
@ -1111,8 +1087,7 @@ 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);
}
}
@ -1134,7 +1109,8 @@ public class ContractProcess {
return !JavaScriptEntry.topic_handlers.isEmpty();
}
public void beforeSuicide() {}
public void beforeSuicide() {
}
public String redo(String path) {
return engine.syncUtil.redo(path);
@ -1189,7 +1165,8 @@ public class ContractProcess {
}
@Override
protected void finalize() {}
protected void finalize() {
}
public String getDeclaredEvents() {
return JsonUtil.toJson(cn.events);
@ -1204,8 +1181,7 @@ 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);
}
}
@ -1226,8 +1202,7 @@ 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()) {
@ -1408,8 +1383,7 @@ 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/";

View File

@ -101,7 +101,8 @@ public class DoipLocalSingleton {
ResultChecker checker = new ResultChecker();
server.start(checker);
checker.waitForResult(1000);
if (checker.port > 0) return port;
if (checker.port > 0)
return port;
return -1;
}