build: config spotless plugin and reformat code

This commit is contained in:
Frank.R.Wu 2023-06-15 11:17:31 +08:00
parent 587310c899
commit 0e5f92e51e
135 changed files with 2847 additions and 2989 deletions

View File

@ -5,6 +5,8 @@ plugins {
id 'signing' id 'signing'
} }
apply from: '../spotless.gradle'
group = "org.bdware.sc" group = "org.bdware.sc"
version = "1.9.0" version = "1.9.0"
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {

View File

@ -16,8 +16,6 @@ import com.alibaba.datax.plugin.rdbms.util.DBUtil;
import com.alibaba.datax.plugin.rdbms.util.DBUtilErrorCode; import com.alibaba.datax.plugin.rdbms.util.DBUtilErrorCode;
import com.alibaba.datax.plugin.rdbms.util.DataBaseType; import com.alibaba.datax.plugin.rdbms.util.DataBaseType;
import com.alibaba.datax.plugin.rdbms.util.RdbmsException; import com.alibaba.datax.plugin.rdbms.util.RdbmsException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
@ -56,8 +54,10 @@ public class MaskingJob {
jdbcUrl = readerPara.getString(Key.JDBC_URL); jdbcUrl = readerPara.getString(Key.JDBC_URL);
table = readerPara.getString(Key.TABLE); table = readerPara.getString(Key.TABLE);
buffer = new ArrayList<>(); buffer = new ArrayList<>();
System.out.println("maskConf11"+maskConf.getConfiguration(CoreConstant.DATAX_JOB_CONTENT + "[0]")); System.out.println(
transformerExecs = TransformerUtil.buildTransformerInfo(maskConf.getConfiguration(CoreConstant.DATAX_JOB_CONTENT + "[0]")); "maskConf11" + maskConf.getConfiguration(CoreConstant.DATAX_JOB_CONTENT + "[0]"));
transformerExecs = TransformerUtil.buildTransformerInfo(
maskConf.getConfiguration(CoreConstant.DATAX_JOB_CONTENT + "[0]"));
} }
public String buildQuerySql() { public String buildQuerySql() {
@ -65,7 +65,8 @@ public class MaskingJob {
// String column = readerPara.getString(Key.COLUMN); // String column = readerPara.getString(Key.COLUMN);
String table = readerPara.getString(Key.TABLE); String table = readerPara.getString(Key.TABLE);
String where = readerPara.getString(Key.WHERE, null); String where = readerPara.getString(Key.WHERE, null);
//String querySql = SingleTableSplitUtil.buildQuerySql(column, table, where) + " limit 100"; // String querySql = SingleTableSplitUtil.buildQuerySql(column, table, where) + " limit
// 100";
String querySql = SingleTableSplitUtil.buildQuerySql(column, table, where) + " limit 100"; String querySql = SingleTableSplitUtil.buildQuerySql(column, table, where) + " limit 100";
return querySql; return querySql;
@ -113,8 +114,7 @@ public class MaskingJob {
return new JsonPrimitive(res); return new JsonPrimitive(res);
} }
private Record transportOneRecord(ResultSet rs, ResultSetMetaData metaData, private Record transportOneRecord(ResultSet rs, ResultSetMetaData metaData, int columnNumber) {
int columnNumber) {
Record record = buildRecord(rs, metaData, columnNumber); Record record = buildRecord(rs, metaData, columnNumber);
sendToWriter(record); sendToWriter(record);
return record; return record;
@ -138,8 +138,8 @@ public class MaskingJob {
return record; return record;
} }
ClassLoaderSwapper classLoaderSwapper = ClassLoaderSwapper ClassLoaderSwapper classLoaderSwapper =
.newCurrentThreadClassLoaderSwapper(); ClassLoaderSwapper.newCurrentThreadClassLoaderSwapper();
Record result = record; Record result = record;
@ -148,17 +148,19 @@ public class MaskingJob {
for (TransformerExecution transformerInfoExec : transformerExecs) { for (TransformerExecution transformerInfoExec : transformerExecs) {
System.out.println("transformerExecs" + transformerInfoExec.getTransformerName()); System.out.println("transformerExecs" + transformerInfoExec.getTransformerName());
if (transformerInfoExec.getClassLoader() != null) { if (transformerInfoExec.getClassLoader() != null) {
classLoaderSwapper.setCurrentThreadClassLoader(transformerInfoExec.getClassLoader()); classLoaderSwapper
.setCurrentThreadClassLoader(transformerInfoExec.getClassLoader());
} }
/** /**
* 延迟检查transformer参数的有效性直接抛出异常不作为脏数据 * 延迟检查transformer参数的有效性直接抛出异常不作为脏数据 不需要在插件中检查参数的有效性但参数的个数等和插件相关的参数在插件内部检查
* 不需要在插件中检查参数的有效性但参数的个数等和插件相关的参数在插件内部检查
*/ */
if (!transformerInfoExec.isChecked()) { if (!transformerInfoExec.isChecked()) {
if (transformerInfoExec.getColumnIndex() != null && transformerInfoExec.getColumnIndex() >= record.getColumnNumber()) { if (transformerInfoExec.getColumnIndex() != null
throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_ILLEGAL_PARAMETER, && transformerInfoExec.getColumnIndex() >= record.getColumnNumber()) {
throw DataXException.asDataXException(
TransformerErrorCode.TRANSFORMER_ILLEGAL_PARAMETER,
String.format("columnIndex[%s] out of bound[%s]. name=%s", String.format("columnIndex[%s] out of bound[%s]. name=%s",
transformerInfoExec.getColumnIndex(), record.getColumnNumber(), transformerInfoExec.getColumnIndex(), record.getColumnNumber(),
transformerInfoExec.getTransformerName())); transformerInfoExec.getTransformerName()));
@ -167,10 +169,11 @@ public class MaskingJob {
} }
try { try {
result = transformerInfoExec.getTransformer().evaluate(result, transformerInfoExec.gettContext(), transformerInfoExec.getFinalParas()); result = transformerInfoExec.getTransformer().evaluate(result,
transformerInfoExec.gettContext(), transformerInfoExec.getFinalParas());
} catch (Exception e) { } catch (Exception e) {
errorMsg = String.format("transformer(%s) has Exception(%s)", transformerInfoExec.getTransformerName(), errorMsg = String.format("transformer(%s) has Exception(%s)",
e.getMessage()); transformerInfoExec.getTransformerName(), e.getMessage());
failed = true; failed = true;
// LOG.error(errorMsg, e); // LOG.error(errorMsg, e);
// transformerInfoExec.addFailedRecords(1); // transformerInfoExec.addFailedRecords(1);
@ -199,8 +202,7 @@ public class MaskingJob {
} }
protected Record buildRecord(ResultSet rs, ResultSetMetaData metaData, protected Record buildRecord(ResultSet rs, ResultSetMetaData metaData, int columnNumber) {
int columnNumber) {
final byte[] EMPTY_CHAR_ARRAY = new byte[0]; final byte[] EMPTY_CHAR_ARRAY = new byte[0];
Record record = new DefaultRecord(); Record record = new DefaultRecord();
try { try {
@ -276,13 +278,10 @@ public class MaskingJob {
break; break;
default: default:
throw DataXException throw DataXException.asDataXException(DBUtilErrorCode.UNSUPPORTED_TYPE,
.asDataXException(
DBUtilErrorCode.UNSUPPORTED_TYPE,
String.format( String.format(
"您的配置文件中的列配置信息有误. 因为DataX 不支持数据库读取这种字段类型. 字段名:[%s], 字段名称:[%s], 字段Java类型:[%s]. 请尝试使用数据库函数将其转换datax支持的类型 或者不同步该字段 .", "您的配置文件中的列配置信息有误. 因为DataX 不支持数据库读取这种字段类型. 字段名:[%s], 字段名称:[%s], 字段Java类型:[%s]. 请尝试使用数据库函数将其转换datax支持的类型 或者不同步该字段 .",
metaData.getColumnName(i), metaData.getColumnName(i), metaData.getColumnType(i),
metaData.getColumnType(i),
metaData.getColumnClassName(i))); metaData.getColumnClassName(i)));
} }
} }

View File

@ -26,12 +26,14 @@ public class DebugMain {
DebugConfig config = JsonUtil.fromJson(content, DebugConfig.class); DebugConfig config = JsonUtil.fromJson(content, DebugConfig.class);
inject(config); inject(config);
String keyPairStr = "{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}"; String keyPairStr = "{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}";
SM2KeyPair pair = SM2KeyPair.fromJson(String.format(keyPairStr, config.publicKey, config.privateKey)); SM2KeyPair pair =
SM2KeyPair.fromJson(String.format(keyPairStr, config.publicKey, config.privateKey));
String uriFormat = "ws://%s/SCIDE/SCExecutor"; String uriFormat = "ws://%s/SCIDE/SCExecutor";
if (config.killBeforeStart != null && config.killBeforeStart.length() > 0) { if (config.killBeforeStart != null && config.killBeforeStart.length() > 0) {
AtomicInteger counter = new AtomicInteger(0); AtomicInteger counter = new AtomicInteger(0);
SmartContractClient client = new SmartContractClient(String.format(uriFormat, config.agentAddress), pair) { SmartContractClient client =
new SmartContractClient(String.format(uriFormat, config.agentAddress), pair) {
public void onLogin(JsonObject obj) { public void onLogin(JsonObject obj) {
counter.incrementAndGet(); counter.incrementAndGet();
} }
@ -49,7 +51,8 @@ public class DebugMain {
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
client.sendMsg("{\"action\":\"killContractProcess\",\"name\":\"" + config.killBeforeStart + "\"}"); client.sendMsg("{\"action\":\"killContractProcess\",\"name\":\""
+ config.killBeforeStart + "\"}");
try { try {
for (; counter.get() == 1;) for (; counter.get() == 1;)
Thread.sleep(100); Thread.sleep(100);
@ -58,9 +61,9 @@ public class DebugMain {
} }
} }
config.contract.setCreateParam(config.createParam); config.contract.setCreateParam(config.createParam);
ContractProcess.main(new String[]{"-port=" + config.port, "-cmi=" + config.cmi, "-disablePID"}); ContractProcess
ResultCallback printCallback .main(new String[] {"-port=" + config.port, "-cmi=" + config.cmi, "-disablePID"});
= new ResultCallback() { ResultCallback printCallback = new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
if (str.contains("Error")) { if (str.contains("Error")) {
@ -70,16 +73,18 @@ public class DebugMain {
} }
}; };
ContractProcess.instance.handler.setDBInfo(wrap("", config.dbPath), printCallback); ContractProcess.instance.handler.setDBInfo(wrap("", config.dbPath), printCallback);
ContractProcess.instance.handler.registerMangerPort(wrap("", Integer.valueOf(config.cPort)), printCallback); ContractProcess.instance.handler.registerMangerPort(wrap("", Integer.valueOf(config.cPort)),
printCallback);
ContractProcess.instance.handler.setContractBundle(wrap("", config.contract), printCallback); ContractProcess.instance.handler.setContractBundle(wrap("", config.contract),
printCallback);
String urlFormat = "http://%s/SCIDE/SCManager?action=reconnectPort&owner=%s&port=%d%s"; String urlFormat = "http://%s/SCIDE/SCManager?action=reconnectPort&owner=%s&port=%d%s";
String cpHost = ""; String cpHost = "";
if (config.cpHost != null && config.cpHost.length() > 0) if (config.cpHost != null && config.cpHost.length() > 0)
cpHost = "&host=" + config.cpHost; cpHost = "&host=" + config.cpHost;
String url = String.format(urlFormat, config.agentAddress, String url = String.format(urlFormat, config.agentAddress, config.publicKey,
config.publicKey, ContractProcess.instance.server.mainPort.get(), cpHost); ContractProcess.instance.server.mainPort.get(), cpHost);
Map<String, Object> resp = HttpUtil.httpGet(url); Map<String, Object> resp = HttpUtil.httpGet(url);
String data = (String) resp.get("response"); String data = (String) resp.get("response");
@ -103,7 +108,8 @@ public class DebugMain {
config.cPort = jsonObject.get("cPort").getAsInt(); config.cPort = jsonObject.get("cPort").getAsInt();
config.port = jsonObject.get("port").getAsInt(); config.port = jsonObject.get("port").getAsInt();
JsonObject ownerAndScript = new JsonObject(); JsonObject ownerAndScript = new JsonObject();
String arg = "abc&owner=" + config.publicKey + "&script=" + config.ypkPath + "&doipStartPort=" + config.doipStartPort; String arg = "abc&owner=" + config.publicKey + "&script=" + config.ypkPath
+ "&doipStartPort=" + config.doipStartPort;
url = String.format(urlFormat, config.agentAddress, "allocateKeyPair", arg); url = String.format(urlFormat, config.agentAddress, "allocateKeyPair", arg);
resp = HttpUtil.httpGet(url); resp = HttpUtil.httpGet(url);
LOGGER.info(url); LOGGER.info(url);

View File

@ -137,8 +137,7 @@ public class ContractProcess {
byte[] buffer = new byte[4]; byte[] buffer = new byte[4];
int length = input.read(buffer, 0, 4); int length = input.read(buffer, 0, 4);
if (length == 4) { if (length == 4) {
isArchive = isArchive = (Arrays.equals(ZIP_HEADER_1, buffer))
(Arrays.equals(ZIP_HEADER_1, buffer))
|| (Arrays.equals(ZIP_HEADER_2, buffer)); || (Arrays.equals(ZIP_HEADER_2, buffer));
} }
} catch (IOException e) { } catch (IOException e) {
@ -194,9 +193,8 @@ public class ContractProcess {
cn = czb.mergeContractNode(); cn = czb.mergeContractNode();
} else { } else {
cn = cn = compiler.compile(new ByteArrayInputStream(script.getBytes()),
compiler.compile( "contract_main.yjs");
new ByteArrayInputStream(script.getBytes()), "contract_main.yjs");
} }
DesktopEngine engine = new DesktopEngine(); // engine.loadJar(zf); DesktopEngine engine = new DesktopEngine(); // engine.loadJar(zf);
engine.loadContract(c, cn, ret.isInsnLimit); engine.loadContract(c, cn, ret.isInsnLimit);
@ -216,8 +214,8 @@ public class ContractProcess {
MethodNode mn = methods.get(fn.functionName); MethodNode mn = methods.get(fn.functionName);
if (mn != null) { if (mn != null) {
System.out.println( System.out
"[ContractManager] getMethodNode, verify:" + fn.functionName); .println("[ContractManager] getMethodNode, verify:" + fn.functionName);
TaintResult.nLocals = mn.maxLocals; TaintResult.nLocals = mn.maxLocals;
TaintResult.nStack = mn.maxStack; TaintResult.nStack = mn.maxStack;
TaintCFG cfg = new TaintCFG(mn); TaintCFG cfg = new TaintCFG(mn);
@ -278,17 +276,12 @@ public class ContractProcess {
* CFGraph cfg = new CFGraph(mn) { * CFGraph cfg = new CFGraph(mn) {
* *
* @Override public BasicBlock getBasicBlock(int id) { return new * @Override public BasicBlock getBasicBlock(int id) { return new
* BasicBlock(id); } }; FrontCF frontCF = new FrontCF(graph); String[] * BasicBlock(id); } }; FrontCF frontCF = new FrontCF(graph); String[] data =
data = * fn.plainText().split("\n"); for (int i = 0; i < graph.getBasicBlockSize();
* fn.plainText().split("\n"); for (int i = 0; i < * i++) { BasicBlock bb = graph.getBasicBlockAt(i); String decompiled = ""; if
graph.getBasicBlockSize();
* i++) { BasicBlock bb = graph.getBasicBlockAt(i); String decompiled =
""; if
* (bb.lineNum - 1 < data.length && bb.lineNum > 0) { decompiled = * (bb.lineNum - 1 < data.length && bb.lineNum > 0) { decompiled =
* data[bb.lineNum - 1]; } frontCF.addBB(bb, decompiled); Set<BasicBlock> * data[bb.lineNum - 1]; } frontCF.addBB(bb, decompiled); Set<BasicBlock> suc =
suc = * graph.getSucBlocks(bb); for (BasicBlock sucBB : suc) frontCF.addEdge(bb,
* graph.getSucBlocks(bb); for (BasicBlock sucBB : suc)
frontCF.addEdge(bb,
* sucBB); } * sucBB); }
*/ */
TaintResult.nLocals = mn.maxLocals; TaintResult.nLocals = mn.maxLocals;
@ -311,7 +304,8 @@ public class ContractProcess {
List<Integer> ids = map.get(i); List<Integer> ids = map.get(i);
frontCF.addBB(bb, decompiled, ids, cfg); frontCF.addBB(bb, decompiled, ids, cfg);
Set<BasicBlock> suc = cfg.getSucBlocks(bb); Set<BasicBlock> suc = cfg.getSucBlocks(bb);
for (BasicBlock sucBB : suc) frontCF.addEdge(bb, sucBB); for (BasicBlock sucBB : suc)
frontCF.addEdge(bb, sucBB);
} }
// get result // get result
// TaintBB lastBlock = cfg.getLastBlock(); // TaintBB lastBlock = cfg.getLastBlock();
@ -404,10 +398,8 @@ public class ContractProcess {
String yancloud_desktop = ""; String yancloud_desktop = "";
isOpen.put(pmList[0], pmList[1]); isOpen.put(pmList[0], pmList[1]);
yancloud_desktop += UtilRegistry.getInitStr(pmList[0], pmList[1].equals("open")); yancloud_desktop += UtilRegistry.getInitStr(pmList[0], pmList[1].equals("open"));
engine.getNashornEngine() engine.getNashornEngine().getContext().setAttribute(ScriptEngine.FILENAME,
.getContext() yancloud_desktop, ScriptContext.ENGINE_SCOPE);
.setAttribute(
ScriptEngine.FILENAME, yancloud_desktop, ScriptContext.ENGINE_SCOPE);
engine.getNashornEngine().eval(yancloud_desktop); engine.getNashornEngine().eval(yancloud_desktop);
} catch (ScriptException e) { } catch (ScriptException e) {
e.printStackTrace(); e.printStackTrace();
@ -429,24 +421,19 @@ public class ContractProcess {
// 判断是否满足Oracle和Contact的执行要求 // 判断是否满足Oracle和Contact的执行要求
public String verifyOracleAndContractPermission(Contract contract) { public String verifyOracleAndContractPermission(Contract contract) {
// 权限校验 如果是Oracle 启动方式只能是Sole 否则报错 // 权限校验 如果是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!"); LOGGER.info("Oracle only support Sole ContractType!");
return JsonUtil.toJson( return JsonUtil.toJson(new ContractResult(Status.Error,
new ContractResult(
Status.Error,
new JsonPrimitive("Oracle only support Sole ContractType!"))); new JsonPrimitive("Oracle only support Sole ContractType!")));
} }
// 权限校验 如果是contract 申请了MySQL等权限 报错 // 权限校验 如果是contract 申请了MySQL等权限 报错
if (cn.getYjsType() == YjsType.Contract) { if (cn.getYjsType() == YjsType.Contract) {
for (Permission per : cn.getPermission()) { for (Permission per : cn.getPermission()) {
if (per == Permission.SQL if (per == Permission.SQL || per == Permission.Http || per == Permission.RocksDB
|| per == Permission.Http
|| per == Permission.RocksDB
|| per == Permission.MongoDB) { || per == Permission.MongoDB) {
LOGGER.debug("Contract can not have permissions of IO!"); LOGGER.debug("Contract can not have permissions of IO!");
return JsonUtil.toJson( return JsonUtil.toJson(new ContractResult(Status.Error,
new ContractResult(
Status.Error,
new JsonPrimitive("Contract can not have permissions of IO|"))); new JsonPrimitive("Contract can not have permissions of IO|")));
} }
} }
@ -458,7 +445,8 @@ public class ContractProcess {
JavaScriptEntry.members = members; JavaScriptEntry.members = members;
if (members != null) if (members != null)
return members.size() + ""; return members.size() + "";
else return "0"; else
return "0";
} }
public String setContractBundle(Contract contract) { public String setContractBundle(Contract contract) {
@ -470,8 +458,7 @@ public class ContractProcess {
JavaScriptEntry.invokeID = 0L; JavaScriptEntry.invokeID = 0L;
JavaScriptEntry.random.setSeed(Integer.parseInt(contract.getID())); JavaScriptEntry.random.setSeed(Integer.parseInt(contract.getID()));
JavaScriptEntry.numOfCopies = this.contract.getNumOfCopies(); JavaScriptEntry.numOfCopies = this.contract.getNumOfCopies();
JavaScriptEntry.shardingID = JavaScriptEntry.shardingID = this.contract.getShardingId(); // 设置javaScriptEntry中的shardingID
this.contract.getShardingId(); // 设置javaScriptEntry中的shardingID
// JavaScriptEntry // JavaScriptEntry
// contract.getCreateParam().get("repoId").getAsString()-->去获取repoId // contract.getCreateParam().get("repoId").getAsString()-->去获取repoId
// 知道自己的BDOID --> repo的id+contract.getID() // 知道自己的BDOID --> repo的id+contract.getID()
@ -487,17 +474,14 @@ public class ContractProcess {
memorySet = cn.memorySet; memorySet = cn.memorySet;
this.contract.sourcePath = zipBundle.getManifest().sourcePath; this.contract.sourcePath = zipBundle.getManifest().sourcePath;
LOGGER.debug( LOGGER.debug("check sourcePath\n\tin-contract=" + this.contract.sourcePath
"check sourcePath\n\tin-contract=" + "\n\tin-manifest=" + zipBundle.getManifest().sourcePath);
+ this.contract.sourcePath
+ "\n\tin-manifest="
+ zipBundle.getManifest().sourcePath);
// zhanghongwei // zhanghongwei
/* if (ret.getManifest().getInsnLimit() != 0) { /*
gasLimit=ret.getManifest().getInsnLimit(); * if (ret.getManifest().getInsnLimit() != 0) {
isInsnLimit = true; * gasLimit=ret.getManifest().getInsnLimit(); isInsnLimit = true; }
}*/ */
String ver = verifyOracleAndContractPermission(contract); String ver = verifyOracleAndContractPermission(contract);
if (!ver.isEmpty()) { if (!ver.isEmpty()) {
return ver; return ver;
@ -533,15 +517,13 @@ public class ContractProcess {
} }
} catch (MalformedJsonException | JsonSyntaxException e) { } catch (MalformedJsonException | JsonSyntaxException e) {
return JsonUtil.toJson( return JsonUtil.toJson(new ContractResult(Status.Error,
new ContractResult(
Status.Error,
new JsonPrimitive("parse manifest.json error, not json format!"))); new JsonPrimitive("parse manifest.json error, not json format!")));
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
return JsonUtil.toJson( return JsonUtil
new ContractResult(Status.Error, new JsonPrimitive(bo.toString()))); .toJson(new ContractResult(Status.Error, new JsonPrimitive(bo.toString())));
} }
} }
@ -578,7 +560,8 @@ public class ContractProcess {
fun.appendBeforeInvokeHandler(accessHandler); fun.appendBeforeInvokeHandler(accessHandler);
} }
fun.appendAfterInvokeHandler(new ObjToJsonHandler()); fun.appendAfterInvokeHandler(new ObjToJsonHandler());
ResultSchemaHandler resultSchemaHandler = createHandlerIfExist(fun, ResultSchemaHandler.class); ResultSchemaHandler resultSchemaHandler =
createHandlerIfExist(fun, ResultSchemaHandler.class);
if (resultSchemaHandler != null) { if (resultSchemaHandler != null) {
fun.appendAfterInvokeHandler(resultSchemaHandler); fun.appendAfterInvokeHandler(resultSchemaHandler);
} }
@ -605,8 +588,10 @@ public class ContractProcess {
if (doopRequestHandler == null) { if (doopRequestHandler == null) {
doopRequestHandler = new DOOPRequestHandler(); doopRequestHandler = new DOOPRequestHandler();
} }
fun.appendBeforeInvokeHandler(new DOOPBeforeExecHandler(fun.getDoipOperationInfo().operation)); fun.appendBeforeInvokeHandler(
fun.appendAfterInvokeHandler(new DOOPAfterExecHandler(fun.getDoipOperationInfo().operation)); new DOOPBeforeExecHandler(fun.getDoipOperationInfo().operation));
fun.appendAfterInvokeHandler(
new DOOPAfterExecHandler(fun.getDoipOperationInfo().operation));
doopRequestHandler.addDoipOperation(fun); doopRequestHandler.addDoipOperation(fun);
} }
} }
@ -614,11 +599,14 @@ public class ContractProcess {
<T extends AnnotationHook> T createHandlerIfExist(FunctionNode function, Class<T> clz) { <T extends AnnotationHook> T createHandlerIfExist(FunctionNode function, Class<T> clz) {
YJSAnnotation annotation = clz.getAnnotation(YJSAnnotation.class); YJSAnnotation annotation = clz.getAnnotation(YJSAnnotation.class);
if (annotation == null) return null; if (annotation == null)
return null;
try { try {
AnnotationNode node = function.getAnnotation(annotation.name()); AnnotationNode node = function.getAnnotation(annotation.name());
if (node == null) return null; if (node == null)
Method m = clz.getDeclaredMethod("fromAnnotationNode", FunctionNode.class, AnnotationNode.class); return null;
Method m = clz.getDeclaredMethod("fromAnnotationNode", FunctionNode.class,
AnnotationNode.class);
T result = (T) m.invoke(null, function, node); T result = (T) m.invoke(null, function, node);
return result; return result;
} catch (Exception e) { } catch (Exception e) {
@ -660,8 +648,7 @@ public class ContractProcess {
handleLog(); handleLog();
LOGGER.info("load script, contract:" + JsonUtil.toJson(contract.getScriptStr())); LOGGER.info("load script, contract:" + JsonUtil.toJson(contract.getScriptStr()));
LOGGER.info("load cn:" + JsonUtil.toJson(cn)); LOGGER.info("load cn:" + JsonUtil.toJson(cn));
ContractResult ret = ContractResult ret = engine.loadContract(contract, cn, cn.getInstrumentBranch());
engine.loadContract(contract, cn, cn.getInstrumentBranch());
ContractResult onCreate = invokeOnCreate(contract.getCreateParam()); ContractResult onCreate = invokeOnCreate(contract.getCreateParam());
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();
jo.add("onCreate", JsonUtil.parseObject(onCreate)); jo.add("onCreate", JsonUtil.parseObject(onCreate));
@ -679,8 +666,8 @@ public class ContractProcess {
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
return JsonUtil.toJson( return JsonUtil
new ContractResult(Status.Error, new JsonPrimitive(bo.toString()))); .toJson(new ContractResult(Status.Error, new JsonPrimitive(bo.toString())));
} }
} }
@ -695,9 +682,11 @@ public class ContractProcess {
if (createParams.has("router")) { if (createParams.has("router")) {
JsonElement routerInfo = createParams.get("router"); JsonElement routerInfo = createParams.get("router");
if (!routerInfo.isJsonObject()) 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 { else {
EndpointConfig endpointConfig = JsonUtil.GSON.fromJson(routerInfo.getAsJsonObject(), EndpointConfig.class); EndpointConfig endpointConfig = JsonUtil.GSON
.fromJson(routerInfo.getAsJsonObject(), EndpointConfig.class);
DoipClusterServer.createDOOPServerInstance(endpointConfig); DoipClusterServer.createDOOPServerInstance(endpointConfig);
} }
} else { } else {
@ -712,17 +701,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(); ContractRequest onStartingDoipServer = new ContractRequest();
onStartingDoipServer.setAction("onServerStart"); onStartingDoipServer.setAction("onServerStart");
if (arg == null) { 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; arg = engine.getManifest().createParam;
else else
arg = new JsonPrimitive(""); arg = new JsonPrimitive("");
} }
onStartingDoipServer.setArg(arg); onStartingDoipServer.setArg(arg);
LOGGER.debug("invoke onStartingDoipServer, param:" + onStartingDoipServer.getArg().toString()); LOGGER.debug(
"invoke onStartingDoipServer, param:" + onStartingDoipServer.getArg().toString());
onStartingDoipServer.setRequester(contract.getOwner()); onStartingDoipServer.setRequester(contract.getOwner());
FunctionNode funNode = cn.getFunction("onServerStart"); FunctionNode funNode = cn.getFunction("onServerStart");
@ -733,13 +725,16 @@ public class ContractProcess {
if (arg.isJsonObject() && arg.getAsJsonObject().has("doipStartPort")) { if (arg.isJsonObject() && arg.getAsJsonObject().has("doipStartPort")) {
startPort = arg.getAsJsonObject().get("doipStartPort").getAsInt(); startPort = arg.getAsJsonObject().get("doipStartPort").getAsInt();
} }
LOGGER.info("Fetch the onStartingDoipServerRes from router successfully, the result is " + onStartingDoipServerRes); LOGGER.info("Fetch the onStartingDoipServerRes from router successfully, the result is "
int doipListenPort = DoipClusterServer.startDoipServer(startPort, onStartingDoipServerRes); + onStartingDoipServerRes);
int doipListenPort =
DoipClusterServer.startDoipServer(startPort, onStartingDoipServerRes);
returnValue.addProperty("doipListenPort", doipListenPort); returnValue.addProperty("doipListenPort", doipListenPort);
this.contract.setDoipPort(doipListenPort); this.contract.setDoipPort(doipListenPort);
returnValue.addProperty("doipStartPort", startPort); returnValue.addProperty("doipStartPort", startPort);
} catch (Exception e) { } 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(); e.printStackTrace();
} }
funNode = cn.getFunction("onInitSharableVars"); funNode = cn.getFunction("onInitSharableVars");
@ -774,7 +769,8 @@ public class ContractProcess {
} }
} }
if (fun.getLogToBDContract()) detail.append("bdcontract;"); if (fun.getLogToBDContract())
detail.append("bdcontract;");
if (fun.getLogToNamedLedger()) { if (fun.getLogToNamedLedger()) {
for (String str : fun.getLedgerNames()) { for (String str : fun.getLedgerNames()) {
detail.append("bdledger:").append(str).append(";"); detail.append("bdledger:").append(str).append(";");
@ -820,7 +816,8 @@ public class ContractProcess {
ContractRequest onCreate = new ContractRequest(); ContractRequest onCreate = new ContractRequest();
onCreate.setAction("onCreate"); onCreate.setAction("onCreate");
if (arg == null) { 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; arg = engine.getManifest().createParam;
else else
arg = new JsonPrimitive(""); arg = new JsonPrimitive("");
@ -893,8 +890,7 @@ public class ContractProcess {
List<Long> hashes = logIndex.request(offset, size); List<Long> hashes = logIndex.request(offset, size);
List<Map<String, String>> jo = new ArrayList<>(); 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) for (Long hash : hashes)
try { try {
Map<String, String> obj = Map<String, String> obj =
@ -909,8 +905,7 @@ public class ContractProcess {
public String requestLast(int count) { public String requestLast(int count) {
List<Long> hashes = logIndex.requestLast(count); List<Long> hashes = logIndex.requestLast(count);
List<Map<String, String>> jo = new ArrayList<>(); 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; String log;
for (Long hash : hashes) for (Long hash : hashes)
try { try {
@ -920,8 +915,8 @@ public class ContractProcess {
} }
Map<String, String> obj = JsonUtil.fromJson(log, token.getType()); Map<String, String> obj = JsonUtil.fromJson(log, token.getType());
if (obj == null) { if (obj == null) {
System.out.println( System.out
"[ContractProcess] requestLast, parseJsonError:" + log + "=="); .println("[ContractProcess] requestLast, parseJsonError:" + log + "==");
continue; continue;
} }
obj.put("hash", hash + ""); obj.put("hash", hash + "");
@ -964,9 +959,8 @@ public class ContractProcess {
try { try {
request = JsonUtil.fromJson(arg, ContractRequest.class); request = JsonUtil.fromJson(arg, ContractRequest.class);
} catch (Exception ignored) { } catch (Exception ignored) {
result = result = new ContractResult(ContractResult.Status.Error,
new ContractResult( new JsonPrimitive("Illegal Arguments!"));
ContractResult.Status.Error, new JsonPrimitive("Illegal Arguments!"));
return JsonUtil.toJson(result); return JsonUtil.toJson(result);
} }
String reqID = request.getRequestID(); String reqID = request.getRequestID();
@ -987,9 +981,9 @@ public class ContractProcess {
engine.redirectTracePS(new Logger(bo, this)); engine.redirectTracePS(new Logger(bo, this));
result = engine.executeContract(request); result = engine.executeContract(request);
result.analysis = bo.toString(); result.analysis = bo.toString();
System.out.println( System.out.println("[ContractProcess] result.analysis = " + result.analysis); // 动态分析bug
"[ContractProcess] result.analysis = " // null
+ result.analysis); // 动态分析bug null pointer // pointer
// branchResult = JsonUtil.toJson(result); // branchResult = JsonUtil.toJson(result);
// branchTrace = result.analysis; // branchTrace = result.analysis;
engine.redirectTracePS(previous); engine.redirectTracePS(previous);
@ -1008,16 +1002,8 @@ public class ContractProcess {
evaluatesAnalysis(request.getAction()); evaluatesAnalysis(request.getAction());
} }
engine.redirectTracePS( engine.redirectTracePS(new ProgramPointCounter(bo, this, gasLimit, functionIndex,
new ProgramPointCounter( request.getValue(), 0L, request.getAction(), ppCountMap));
bo,
this,
gasLimit,
functionIndex,
request.getValue(),
0L,
request.getAction(),
ppCountMap));
result = engine.executeContract(request); result = engine.executeContract(request);
result.analysis = bo.toString(); result.analysis = bo.toString();
@ -1058,8 +1044,7 @@ public class ContractProcess {
for (String s : function) { for (String s : function) {
MethodNode mn = methods.get(s); MethodNode mn = methods.get(s);
if (mn != null) { if (mn != null) {
CFGraph cfg = CFGraph cfg = new CFGraph(mn) {
new CFGraph(mn) {
@Override @Override
public BasicBlock getBasicBlock(int id) { public BasicBlock getBasicBlock(int id) {
return new BasicBlock(id); return new BasicBlock(id);
@ -1126,10 +1111,7 @@ public class ContractProcess {
TaintBB bb = cfg.getLastBlock(); TaintBB bb = cfg.getLastBlock();
result.analysis = bb.getResultWithTaintBit(); result.analysis = bb.getResultWithTaintBit();
System.out.println( System.out.println("[ContractProcess] dynamically verify: " + ac.getAction() + "-->"
"[ContractProcess] dynamically verify: "
+ ac.getAction()
+ "-->"
+ result.analysis); + result.analysis);
} }
} }
@ -1152,8 +1134,7 @@ public class ContractProcess {
return !JavaScriptEntry.topic_handlers.isEmpty(); return !JavaScriptEntry.topic_handlers.isEmpty();
} }
public void beforeSuicide() { public void beforeSuicide() {}
}
public String redo(String path) { public String redo(String path) {
return engine.syncUtil.redo(path); return engine.syncUtil.redo(path);
@ -1208,8 +1189,7 @@ public class ContractProcess {
} }
@Override @Override
protected void finalize() { protected void finalize() {}
}
public String getDeclaredEvents() { public String getDeclaredEvents() {
return JsonUtil.toJson(cn.events); return JsonUtil.toJson(cn.events);
@ -1224,8 +1204,8 @@ public class ContractProcess {
for (FunctionNode fn : cn.getFunctions()) { for (FunctionNode fn : cn.getFunctions()) {
if (fn.isExport() && !fn.functionName.equals("onCreate")) { if (fn.isExport() && !fn.functionName.equals("onCreate")) {
function.add(fn.functionName); function.add(fn.functionName);
FunctionDesp desp = FunctionDesp desp = new FunctionDesp(fn.functionName, fn.annotations,
new FunctionDesp(fn.functionName, fn.annotations, fn.getRouteInfo(), fn.getJoinInfo(), fn.isView()); fn.getRouteInfo(), fn.getJoinInfo(), fn.isView());
ret.add(desp); ret.add(desp);
} }
} }
@ -1246,11 +1226,8 @@ public class ContractProcess {
public String startAutoDump() { public String startAutoDump() {
String dumpPeriod = projectConfig.getDumpPeriod(); String dumpPeriod = projectConfig.getDumpPeriod();
System.out.println( System.out.println("[ContractProcess] startAutoDump : " + cn.getContractName()
"[ContractProcess] startAutoDump : " + " period = " + dumpPeriod);
+ cn.getContractName()
+ " period = "
+ dumpPeriod);
String status = "startAutoDump status 0"; String status = "startAutoDump status 0";
if (null != dt) { if (null != dt) {
if (null == dumpPeriod || dumpPeriod.isEmpty()) { if (null == dumpPeriod || dumpPeriod.isEmpty()) {
@ -1431,8 +1408,7 @@ public class ContractProcess {
private class DumpTask extends TimerTask { private class DumpTask extends TimerTask {
@Override @Override
public void run() { public void run() {
System.out.println( System.out.println("[ContractProcess DumpTask] auto dump period : "
"[ContractProcess DumpTask] auto dump period : "
+ projectConfig.getDumpPeriod()); + projectConfig.getDumpPeriod());
File file1 = new File(dir); File file1 = new File(dir);
File file2 = new File(file1.getParent()); File file2 = new File(file1.getParent());

View File

@ -31,11 +31,13 @@ public class SM2Helper {
backupFile(new File("./cmconfig.json")); backupFile(new File("./cmconfig.json"));
System.out.println("Generate file: cmconfig.json"); System.out.println("Generate file: cmconfig.json");
String content = FileUtil.getFileContent("./cmconfig.json.template"); String content = FileUtil.getFileContent("./cmconfig.json.template");
JsonObject jo = JsonParser.parseReader(new FileReader("cmvar.json")).getAsJsonObject(); JsonObject jo =
JsonParser.parseReader(new FileReader("cmvar.json")).getAsJsonObject();
for (String key : jo.keySet()) { for (String key : jo.keySet()) {
content = content.replaceAll(key, jo.get(key).getAsString()); content = content.replaceAll(key, jo.get(key).getAsString());
} }
JsonObject keypair = JsonParser.parseReader(new FileReader("manager.keypair")).getAsJsonObject(); JsonObject keypair =
JsonParser.parseReader(new FileReader("manager.keypair")).getAsJsonObject();
content = content.replaceAll("_PRIVKEY", keypair.get("privateKey").getAsString()); content = content.replaceAll("_PRIVKEY", keypair.get("privateKey").getAsString());
content = content.replaceAll("_PUBKEY", keypair.get("publicKey").getAsString()); content = content.replaceAll("_PUBKEY", keypair.get("publicKey").getAsString());
content = content.replaceAll("CMI", System.currentTimeMillis() + ""); content = content.replaceAll("CMI", System.currentTimeMillis() + "");
@ -58,15 +60,18 @@ public class SM2Helper {
} }
private static void backupFile(File file) { private static void backupFile(File file) {
if (!file.exists()) return; if (!file.exists())
return;
File backup = null; File backup = null;
for (int i = 0; i <= 100; i++) { for (int i = 0; i <= 100; i++) {
if (i == 100) throw new IllegalArgumentException("failed to backup:" + file.getAbsolutePath()); if (i == 100)
throw new IllegalArgumentException("failed to backup:" + file.getAbsolutePath());
backup = new File(file.getParent(), file.getName() + "." + i); backup = new File(file.getParent(), file.getName() + "." + i);
if (!backup.exists()) if (!backup.exists())
break; break;
} }
FileUtil.copyFile(file, backup); FileUtil.copyFile(file, backup);
System.out.println("Backup: " + file.getAbsolutePath() + " --> " + backup.getAbsolutePath()); System.out
.println("Backup: " + file.getAbsolutePath() + " --> " + backup.getAbsolutePath());
} }
} }

View File

@ -14,7 +14,6 @@ import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.MethodNode;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.util.*; import java.util.*;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
@ -44,10 +43,7 @@ public class FSAnalysis extends BreadthFirstSearch<TaintResult, TaintBB> {
setToAnalysis(toAnalysis); setToAnalysis(toAnalysis);
if (isDebug) { if (isDebug) {
System.out.println("===Method:" + cfg.getMethodNode().name + cfg.getMethodNode().desc); System.out.println("===Method:" + cfg.getMethodNode().name + cfg.getMethodNode().desc);
System.out.println( System.out.println("===Local:" + cfg.getMethodNode().maxLocals + " "
"===Local:"
+ cfg.getMethodNode().maxLocals
+ " "
+ cfg.getMethodNode().maxStack); + cfg.getMethodNode().maxStack);
} }
} }
@ -81,9 +77,8 @@ public class FSAnalysis extends BreadthFirstSearch<TaintResult, TaintBB> {
ContractZipBundle czb = compiler.compile(zf); ContractZipBundle czb = compiler.compile(zf);
cn = czb.mergeContractNode(); cn = czb.mergeContractNode();
} else { } else {
cn = cn = compiler.compile(new ByteArrayInputStream(script.getBytes()),
compiler.compile( "contract_main.yjs");
new ByteArrayInputStream(script.getBytes()), "contract_main.yjs");
} }
DesktopEngine engine = new DesktopEngine(); // engine.loadJar(zf); DesktopEngine engine = new DesktopEngine(); // engine.loadJar(zf);
engine.loadContract(c, cn, false); engine.loadContract(c, cn, false);
@ -109,7 +104,8 @@ public class FSAnalysis extends BreadthFirstSearch<TaintResult, TaintBB> {
FSAnalysis analysis = new FSAnalysis(cfg); FSAnalysis analysis = new FSAnalysis(cfg);
analysis.analysis(); analysis.analysis();
TaintBB bb = cfg.getLastBlock(); TaintBB bb = cfg.getLastBlock();
if (bb != null) result.put(fn.functionName, bb.getResult()); if (bb != null)
result.put(fn.functionName, bb.getResult());
cfg.printSelf(); cfg.printSelf();
} }
} }

View File

@ -126,7 +126,8 @@ public class AccountIndex {
} }
try { try {
LenVarTimeSerialIndex2 index = getIndexFile(getString(args, "account") + getString(args, "file")); LenVarTimeSerialIndex2 index =
getIndexFile(getString(args, "account") + getString(args, "file"));
long startTime = getLong(args, "startTime"); long startTime = getLong(args, "startTime");
long endTime = getLong(args, "endTime"); long endTime = getLong(args, "endTime");
List<byte[]> result = index.requestByTime(startTime, endTime); List<byte[]> result = index.requestByTime(startTime, endTime);
@ -183,7 +184,8 @@ public class AccountIndex {
} }
try { try {
LenVarTimeSerialIndex2 index = getIndexFile(getString(args, "account") + getString(args, "file")); LenVarTimeSerialIndex2 index =
getIndexFile(getString(args, "account") + getString(args, "file"));
long date = getLong(args, "date"); long date = getLong(args, "date");
String content = getString(args, "content"); String content = getString(args, "content");
index.manullyIndex(date, HashUtil.str16ToBytes(content)); index.manullyIndex(date, HashUtil.str16ToBytes(content));

View File

@ -78,9 +78,8 @@ public class JavaScriptEntry {
} }
public static void setSM2KeyPair(String pubKey, String privKey) { public static void setSM2KeyPair(String pubKey, String privKey) {
keyPair = keyPair = new SM2KeyPair(SM2KeyPair.publicKeyStr2ECPoint(pubKey),
new SM2KeyPair( new BigInteger(privKey, 16));
SM2KeyPair.publicKeyStr2ECPoint(pubKey), new BigInteger(privKey, 16));
} }
public static SM2KeyPair getKeyPair() { public static SM2KeyPair getKeyPair() {
@ -168,8 +167,8 @@ public class JavaScriptEntry {
return new ApiGate(ip, Integer.parseInt(port)); return new ApiGate(ip, Integer.parseInt(port));
} }
public static String executeContractWithSig( public static String executeContractWithSig(String contractID, String action, String arg,
String contractID, String action, String arg, String pubkey, String sig) { String pubkey, String sig) {
try { try {
ContractRequest app = new ContractRequest(); ContractRequest app = new ContractRequest();
app.setContractID(contractID).setAction(action).setArg(arg); app.setContractID(contractID).setAction(action).setArg(arg);
@ -182,21 +181,10 @@ public class JavaScriptEntry {
app.setFromDebug(isDebug); app.setFromDebug(isDebug);
if (numOfCopies > 1) { if (numOfCopies > 1) {
// The caller is special. // The caller is special.
app.setRequestID( app.setRequestID(app.getPublicKey().hashCode() + "_" + numOfCopies + "_"
app.getPublicKey().hashCode() + (invokeID++) + "_" + random.nextInt() + "_mul");
+ "_"
+ numOfCopies
+ "_"
+ (invokeID++)
+ "_"
+ random.nextInt()
+ "_mul");
} else { } else {
app.setRequestID( app.setRequestID(app.getPublicKey().hashCode() + "_" + (invokeID++) + "_"
app.getPublicKey().hashCode()
+ "_"
+ (invokeID++)
+ "_"
+ random.nextInt()); + random.nextInt());
} }
return get.syncGet("dd", "executeContract", JsonUtil.toJson(app)); return get.syncGet("dd", "executeContract", JsonUtil.toJson(app));
@ -210,9 +198,8 @@ public class JavaScriptEntry {
public static Object executeContract(String contractID, String action, Object arg) { public static Object executeContract(String contractID, String action, Object arg) {
if (currentSyncUtil.engine.recovering) { if (currentSyncUtil.engine.recovering) {
String str = String str = currentSyncUtil.transRecoverUtil.curRecoverRecord
currentSyncUtil.transRecoverUtil.curRecoverRecord.getExecuteResult( .getExecuteResult(invokeID + "");
invokeID + "");
String[] strs = str.split("<seperate>"); String[] strs = str.split("<seperate>");
String flag1 = strs[0]; String flag1 = strs[0];
String flag = strs[1]; String flag = strs[1];
@ -233,29 +220,22 @@ public class JavaScriptEntry {
try { try {
ContractRequest app = new ContractRequest(); ContractRequest app = new ContractRequest();
app.setContractID(contractID).setAction(action).setArg(JSONTool.convertMirrorToJson(arg)); app.setContractID(contractID).setAction(action)
.setArg(JSONTool.convertMirrorToJson(arg));
app.doSignature(keyPair); app.doSignature(keyPair);
app.setFromDebug(isDebug); app.setFromDebug(isDebug);
ContractExecType type = ContractProcess.instance.getContract().getType(); ContractExecType type = ContractProcess.instance.getContract().getType();
if (type.needSeq()) { if (type.needSeq()) {
app.setRequestID( app.setRequestID(
String.format( String.format("%d_%d_%d_%d_mul", keyPair.getPublicKeyStr().hashCode(),
"%d_%d_%d_%d_mul", numOfCopies, (invokeID++), random.nextInt()));
keyPair.getPublicKeyStr().hashCode(),
numOfCopies,
(invokeID++),
random.nextInt()));
// The caller is special. // The caller is special.
flag = 1; flag = 1;
flag1 = 1; flag1 = 1;
LOGGER.warn("invoke contractExecution! " + JsonUtil.toJson(app)); LOGGER.warn("invoke contractExecution! " + JsonUtil.toJson(app));
} else { } else {
app.setRequestID( app.setRequestID(String.format("%d_%d_%d", keyPair.getPublicKeyStr().hashCode(),
String.format( (invokeID++), random.nextInt()));
"%d_%d_%d",
keyPair.getPublicKeyStr().hashCode(),
(invokeID++),
random.nextInt()));
flag = 1; flag = 1;
flag1 = 1; flag1 = 1;
} }
@ -264,45 +244,38 @@ public class JavaScriptEntry {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
String result = bo.toString(); String result = bo.toString();
if (currentSyncUtil.startFlag if (currentSyncUtil.startFlag && currentSyncUtil.currType == SyncType.Trans
&& currentSyncUtil.currType == SyncType.Trans
&& !currentSyncUtil.engine.recovering) { && !currentSyncUtil.engine.recovering) {
currentSyncUtil.transRecordUtil.recordExecutes( currentSyncUtil.transRecordUtil.recordExecutes(formerInvokeID + "",
formerInvokeID + "", flag1 + "<seperate>" + flag + "<seperate>" + result); flag1 + "<seperate>" + flag + "<seperate>" + result);
} }
return result; return result;
} }
} }
private static Object 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)); String result = get.syncGet("dd", "executeContract", JsonUtil.toJson(app));
if (currentSyncUtil.startFlag if (currentSyncUtil.startFlag && currentSyncUtil.currType == SyncType.Trans
&& currentSyncUtil.currType == SyncType.Trans
&& !currentSyncUtil.engine.recovering) { && !currentSyncUtil.engine.recovering) {
currentSyncUtil.transRecordUtil.recordExecutes( currentSyncUtil.transRecordUtil.recordExecutes(formerInvokeID + "",
formerInvokeID + "",
flag1 + "<seperate>" + flag + "<seperate>" + result); flag1 + "<seperate>" + flag + "<seperate>" + result);
} }
JsonObject jo = JsonUtil.parseStringAsJsonObject(result); JsonObject jo = JsonUtil.parseStringAsJsonObject(result);
return JSONTool.convertJsonElementToMirror(jo); return JSONTool.convertJsonElementToMirror(jo);
} }
public static void executeContractAsyncWithoutSig( public static void executeContractAsyncWithoutSig(String contractID, String action, String arg,
String contractID, String action, String arg, final ScriptFunction cb) { final ScriptFunction cb) {
try { try {
ContractRequest app = new ContractRequest(); ContractRequest app = new ContractRequest();
app.setContractID(contractID).setAction(action).setArg(arg); app.setContractID(contractID).setAction(action).setArg(arg);
app.setRequestID((invokeID++) + "_" + random.nextInt()); app.setRequestID((invokeID++) + "_" + random.nextInt());
get.asyncGet( get.asyncGet("dd", "executeContract", JsonUtil.toJson(app), new ResultCallback() {
"dd",
"executeContract",
JsonUtil.toJson(app),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
if (null != cb) { if (null != cb) {
DesktopEngine.applyWithGlobal( DesktopEngine.applyWithGlobal(cb, currentEngine.getNashornGlobal(), str);
cb, currentEngine.getNashornGlobal(), str);
} }
} }
}); });
@ -312,24 +285,20 @@ public class JavaScriptEntry {
} }
} }
public static String executeContractAsync( public static String executeContractAsync(String contractID, String action, String arg,
String contractID, String action, String arg, final ScriptFunction cb) { final ScriptFunction cb) {
try { try {
ContractRequest app = new ContractRequest(); ContractRequest app = new ContractRequest();
app.setContractID(contractID).setAction(action).setArg(arg); app.setContractID(contractID).setAction(action).setArg(arg);
app.doSignature(keyPair); app.doSignature(keyPair);
app.setRequestID((invokeID++) + "_" + random()); app.setRequestID((invokeID++) + "_" + random());
get.asyncGet( get.asyncGet("dd", "executeContract", JsonUtil.toJson(app), new ResultCallback() {
"dd",
"executeContract",
JsonUtil.toJson(app),
new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
if (cb != null) { if (cb != null) {
DesktopEngine.applyWithGlobal( DesktopEngine.applyWithGlobal(cb, currentEngine.getNashornGlobal(), str,
cb, currentEngine.getNashornGlobal(), str, arg); arg);
} }
} }
}); });
@ -366,10 +335,8 @@ public class JavaScriptEntry {
* @author Kaidong Wu * @author Kaidong Wu
*/ */
public static void pubEventConstraint(String topic, String content, String constraint) { public static void pubEventConstraint(String topic, String content, String constraint) {
String reqID = String reqID = String.format("%d_%d_%d_%s_pe", keyPair.getPublicKeyStr().hashCode(),
String.format( numOfCopies, invokeID, random());
"%d_%d_%d_%s_pe",
keyPair.getPublicKeyStr().hashCode(), numOfCopies, invokeID, random());
REvent msg = new REvent(topic, PUBLISH, content, reqID); REvent msg = new REvent(topic, PUBLISH, content, reqID);
if (null != constraint) { if (null != constraint) {
msg.setSemantics(REvent.REventSemantics.valueOf(constraint)); msg.setSemantics(REvent.REventSemantics.valueOf(constraint));
@ -412,17 +379,11 @@ public class JavaScriptEntry {
} }
private static void subscribe(String topic, ScriptFunction fun, boolean fromPreSub) { private static void subscribe(String topic, ScriptFunction fun, boolean fromPreSub) {
String reqID = String reqID = String.format("%d_%d_%d_%s_se", keyPair.getPublicKeyStr().hashCode(),
String.format( numOfCopies, invokeID, random());
"%d_%d_%d_%s_se",
keyPair.getPublicKeyStr().hashCode(), numOfCopies, invokeID, random());
REvent msg = REvent msg = new REvent(topic, SUBSCRIBE,
new REvent( String.format("{\"subscriber\":\"%s\",\"handler\":\"%s\"}",
topic,
SUBSCRIBE,
String.format(
"{\"subscriber\":\"%s\",\"handler\":\"%s\"}",
ContractProcess.instance.getContractName(), fun.getName()), ContractProcess.instance.getContractName(), fun.getName()),
reqID); reqID);
if (fromPreSub) { if (fromPreSub) {
@ -434,10 +395,8 @@ public class JavaScriptEntry {
} }
public static void unsubscribe(String topic) { public static void unsubscribe(String topic) {
String reqID = String reqID = String.format("%d_%d_%d_%s_us", keyPair.getPublicKeyStr().hashCode(),
String.format( numOfCopies, invokeID, random());
"%d_%d_%d_%s_us",
keyPair.getPublicKeyStr().hashCode(), numOfCopies, invokeID, random());
String content; String content;
if (null == topic) { if (null == topic) {
content = "{\"subscriber\":\"" + ContractProcess.instance.getContractName() + "\"}"; content = "{\"subscriber\":\"" + ContractProcess.instance.getContractName() + "\"}";
@ -447,9 +406,7 @@ public class JavaScriptEntry {
}); });
} else { } else {
String handler = topic_handlers.get(topic).getName(); String handler = topic_handlers.get(topic).getName();
content = content = String.format("{\"subscriber\":\"%s\",\"handler\":\"%s\"}",
String.format(
"{\"subscriber\":\"%s\",\"handler\":\"%s\"}",
ContractProcess.instance.getContractName(), handler); ContractProcess.instance.getContractName(), handler);
topic_handlers.remove(topic); topic_handlers.remove(topic);
ContractProcess.instance.unSubscribe(handler); ContractProcess.instance.unSubscribe(handler);
@ -468,10 +425,8 @@ public class JavaScriptEntry {
public static void preSub(String topic, String content) { public static void preSub(String topic, String content) {
String newTopic = topic + "|" + content + "|" + ContractProcess.instance.getContractName(); String newTopic = topic + "|" + content + "|" + ContractProcess.instance.getContractName();
subscribe(newTopic, topic_handlers.get(topic), true); subscribe(newTopic, topic_handlers.get(topic), true);
String reqID = String reqID = String.format("%d_%d_%d_%s_pse", keyPair.getPublicKeyStr().hashCode(),
String.format( numOfCopies, (invokeID++), random());
"%d_%d_%d_%s_pse",
keyPair.getPublicKeyStr().hashCode(), numOfCopies, (invokeID++), random());
REvent msg = new REvent(topic, REvent.REventType.PRESUB, newTopic, reqID); REvent msg = new REvent(topic, REvent.REventType.PRESUB, newTopic, reqID);
msg.setSemantics(REvent.REventSemantics.ONLY_ONCE); msg.setSemantics(REvent.REventSemantics.ONLY_ONCE);
msgList.add(msg); msgList.add(msg);
@ -482,7 +437,8 @@ public class JavaScriptEntry {
* @author Kaidong Wu * @author Kaidong Wu
*/ */
public static String random() { public static String random() {
String seed = String.valueOf(null == random ? System.currentTimeMillis() : random.nextInt()); String seed =
String.valueOf(null == random ? System.currentTimeMillis() : random.nextInt());
return HashUtil.sha3(seed); return HashUtil.sha3(seed);
} }

View File

@ -10,7 +10,6 @@ import java.util.Scanner;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class Resources { public class Resources {
private final ZipFile zf; private final ZipFile zf;
YJSClassLoader loader; YJSClassLoader loader;
@ -67,7 +66,8 @@ public class Resources {
ZipEntry entry = zf.getEntry(path); ZipEntry entry = zf.getEntry(path);
if (entry == null) if (entry == null)
return null; return null;
reader = new BufferedReader(new InputStreamReader(zf.getInputStream(entry), StandardCharsets.UTF_8)); reader = new BufferedReader(
new InputStreamReader(zf.getInputStream(entry), StandardCharsets.UTF_8));
String line = null; String line = null;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
fileList.add(line); fileList.add(line);
@ -84,7 +84,8 @@ public class Resources {
public String unzipToDir(String path) { public String unzipToDir(String path) {
ZipEntry entry = zf.getEntry(path); ZipEntry entry = zf.getEntry(path);
try { try {
return loader.unzipLibrary(zf.getInputStream(entry), entry.getName().replaceAll(".*/", "")); return loader.unzipLibrary(zf.getInputStream(entry),
entry.getName().replaceAll(".*/", ""));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -16,13 +16,16 @@ import java.security.NoSuchAlgorithmException;
@PermissionStub(permission = Permission.AES) @PermissionStub(permission = Permission.AES)
public class AESUtil { public class AESUtil {
public static ScriptObject encrypt(String key, String plaintext) throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { public static ScriptObject encrypt(String key, String plaintext)
throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException {
JO ret = new JO(PropertyMap.newMap()); JO ret = new JO(PropertyMap.newMap());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
String iv = generateKey(128); String iv = generateKey(128);
IvParameterSpec ivSpec = new IvParameterSpec(DatatypeConverter.parseHexBinary(iv)); IvParameterSpec ivSpec = new IvParameterSpec(DatatypeConverter.parseHexBinary(iv));
byte[] byteContent = plaintext.getBytes(); byte[] byteContent = plaintext.getBytes();
SecretKeySpec secretKeySpecSpec = new SecretKeySpec(DatatypeConverter.parseHexBinary(key), "AES"); SecretKeySpec secretKeySpecSpec =
new SecretKeySpec(DatatypeConverter.parseHexBinary(key), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpecSpec, ivSpec); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpecSpec, ivSpec);
byte[] result = cipher.doFinal(byteContent); byte[] result = cipher.doFinal(byteContent);
ret.put("iv", iv, false); ret.put("iv", iv, false);
@ -30,12 +33,16 @@ public class AESUtil {
return ret; return ret;
} }
public static String decrypt(String key, String ciphertext, String iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { public static String decrypt(String key, String ciphertext, String iv)
throws NoSuchPaddingException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException,
IllegalBlockSizeException {
// JO ret = new JO(PropertyMap.newMap()); // JO ret = new JO(PropertyMap.newMap());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(DatatypeConverter.parseHexBinary(iv)); IvParameterSpec ivSpec = new IvParameterSpec(DatatypeConverter.parseHexBinary(iv));
byte[] byteContent = DatatypeConverter.parseHexBinary(ciphertext); byte[] byteContent = DatatypeConverter.parseHexBinary(ciphertext);
SecretKeySpec secretKeySpecSpec = new SecretKeySpec(DatatypeConverter.parseHexBinary(key), "AES"); SecretKeySpec secretKeySpecSpec =
new SecretKeySpec(DatatypeConverter.parseHexBinary(key), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpecSpec, ivSpec); cipher.init(Cipher.DECRYPT_MODE, secretKeySpecSpec, ivSpec);
byte[] result = cipher.doFinal(byteContent); byte[] result = cipher.doFinal(byteContent);
return new String(result); return new String(result);

View File

@ -30,15 +30,13 @@ public class AsyncUtil {
} }
public static String postFunction(final ScriptFunction callback, Object wrapper) { public static String postFunction(final ScriptFunction callback, Object wrapper) {
ServiceServer.executor.execute( ServiceServer.executor.execute(() -> JavaScriptEntry.executeFunction(callback, wrapper));
() -> JavaScriptEntry.executeFunction(callback, wrapper));
return "success"; return "success";
} }
public static TimerTask setTimeOut( public static TimerTask setTimeOut(final ScriptFunction callback, long delay,
final ScriptFunction callback, long delay, final Object arg) { final Object arg) {
TimerTask task = TimerTask task = new TimerTask() {
new TimerTask() {
@Override @Override
public void run() { public void run() {
JavaScriptEntry.executeFunction(callback, arg); JavaScriptEntry.executeFunction(callback, arg);
@ -48,10 +46,9 @@ public class AsyncUtil {
return task; return task;
} }
public static TimerTask setInterval( public static TimerTask setInterval(final ScriptFunction callback, long delay, long interval,
final ScriptFunction callback, long delay, long interval, final Object arg) { final Object arg) {
TimerTask task = TimerTask task = new TimerTask() {
new TimerTask() {
@Override @Override
public void run() { public void run() {
JavaScriptEntry.executeFunction(callback, arg); JavaScriptEntry.executeFunction(callback, arg);
@ -61,22 +58,19 @@ public class AsyncUtil {
return task; return task;
} }
public static void executeContractAsyncWithoutSig( public static void executeContractAsyncWithoutSig(String contractID, String action, String arg,
String contractID, String action, String arg, final ScriptFunction cb) { final ScriptFunction cb) {
try { try {
ContractRequest app = new ContractRequest(); ContractRequest app = new ContractRequest();
app.setContractID(contractID).setAction(action).setArg(arg); app.setContractID(contractID).setAction(action).setArg(arg);
app.setRequestID((JavaScriptEntry.invokeID++) + "_" + JavaScriptEntry.random.nextInt()); app.setRequestID((JavaScriptEntry.invokeID++) + "_" + JavaScriptEntry.random.nextInt());
JavaScriptEntry.get.asyncGet( JavaScriptEntry.get.asyncGet("dd", "executeContract", JsonUtil.toJson(app),
"dd",
"executeContract",
JsonUtil.toJson(app),
new ResultCallback() { new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
if (null != cb) { if (null != cb) {
DesktopEngine.applyWithGlobal( DesktopEngine.applyWithGlobal(cb,
cb, JavaScriptEntry.currentEngine.getNashornGlobal(), str); JavaScriptEntry.currentEngine.getNashornGlobal(), str);
} }
} }
}); });
@ -85,24 +79,22 @@ public class AsyncUtil {
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
} }
} }
public static String executeContractAsync(
String contractID, String action, String arg, final ScriptFunction cb) { public static String executeContractAsync(String contractID, String action, String arg,
final ScriptFunction cb) {
try { try {
ContractRequest app = new ContractRequest(); ContractRequest app = new ContractRequest();
app.setContractID(contractID).setAction(action).setArg(arg); app.setContractID(contractID).setAction(action).setArg(arg);
app.doSignature(JavaScriptEntry.getKeyPair()); app.doSignature(JavaScriptEntry.getKeyPair());
app.setRequestID((JavaScriptEntry.invokeID++) + "_" + JavaScriptEntry.random()); app.setRequestID((JavaScriptEntry.invokeID++) + "_" + JavaScriptEntry.random());
JavaScriptEntry.get.asyncGet( JavaScriptEntry.get.asyncGet("dd", "executeContract", JsonUtil.toJson(app),
"dd",
"executeContract",
JsonUtil.toJson(app),
new ResultCallback() { new ResultCallback() {
@Override @Override
public void onResult(String str) { public void onResult(String str) {
if (cb != null) { if (cb != null) {
DesktopEngine.applyWithGlobal( DesktopEngine.applyWithGlobal(cb,
cb, JavaScriptEntry.currentEngine.getNashornGlobal(), str, arg); JavaScriptEntry.currentEngine.getNashornGlobal(), str, arg);
} }
} }
}); });

View File

@ -2,7 +2,6 @@ package org.bdware.sc.boundry.utils;
import org.bdware.sc.ContractProcess; import org.bdware.sc.ContractProcess;
import org.bdware.sc.compiler.PermissionStub; import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.db.TimeDBUtil;
import org.bdware.sc.db.TimeRocksDBUtil; import org.bdware.sc.db.TimeRocksDBUtil;
import org.bdware.sc.node.Permission; import org.bdware.sc.node.Permission;

View File

@ -77,7 +77,8 @@ public class DOIPUtil {
msg = ret.get(0); msg = ret.get(0);
if (msg != null) { if (msg != null) {
return msg; return msg;
} else return DoipMessageFactory.createTimeoutResponse(message.requestID); } else
return DoipMessageFactory.createTimeoutResponse(message.requestID);
} catch (Exception ie) { } catch (Exception ie) {
ie.printStackTrace(); ie.printStackTrace();
return DoipMessageFactory.createConnectFailedResponse(message.requestID); return DoipMessageFactory.createConnectFailedResponse(message.requestID);
@ -97,13 +98,14 @@ public class DOIPUtil {
} }
public String hello(String repoID) { public String hello(String repoID) {
DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder()).createRequest(repoID, BasicOperations.Hello.getName()).create(); DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder())
.createRequest(repoID, BasicOperations.Hello.getName()).create();
return convertDoipMsgToString(syncGetMessage(msg)); return convertDoipMsgToString(syncGetMessage(msg));
} }
public String retrieve(String doi, String args) { public String retrieve(String doi, String args) {
DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder()).createRequest(doi, BasicOperations.Retrieve.getName()) DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder())
.create(); .createRequest(doi, BasicOperations.Retrieve.getName()).create();
msg.header.parameters.addAttribute("element", ""); msg.header.parameters.addAttribute("element", "");
return convertDoipMsgToString(syncGetMessage(msg)); return convertDoipMsgToString(syncGetMessage(msg));
} }
@ -126,27 +128,21 @@ public class DOIPUtil {
} }
e.dataString = null; e.dataString = null;
} }
DoipMessage msg = DoipMessage msg = new DoipMessageFactory.DoipMessageBuilder()
new DoipMessageFactory.DoipMessageBuilder() .createRequest(repoID, BasicOperations.Create.getName()).setBody(digitalObject)
.createRequest(repoID, BasicOperations.Create.getName())
.setBody(digitalObject)
.create(); .create();
return convertDoipMsgToString(syncGetMessage(msg)); return convertDoipMsgToString(syncGetMessage(msg));
} }
public String delete(String doID) { public String delete(String doID) {
DoipMessage msg = DoipMessage msg = new DoipMessageFactory.DoipMessageBuilder()
new DoipMessageFactory.DoipMessageBuilder() .createRequest(doID, BasicOperations.Delete.getName()).create();
.createRequest(doID, BasicOperations.Delete.getName())
.create();
return convertDoipMsgToString(syncGetMessage(msg)); return convertDoipMsgToString(syncGetMessage(msg));
} }
public String listOperation(String doID) { public String listOperation(String doID) {
DoipMessage msg = DoipMessage msg = new DoipMessageFactory.DoipMessageBuilder()
new DoipMessageFactory.DoipMessageBuilder() .createRequest(doID, BasicOperations.ListOps.getName()).create();
.createRequest(doID, BasicOperations.ListOps.getName())
.create();
return convertDoipMsgToString(syncGetMessage(msg)); return convertDoipMsgToString(syncGetMessage(msg));
} }
@ -222,7 +218,8 @@ public class DOIPUtil {
return createIrpClient(uri, null, null, null); return createIrpClient(uri, null, null, null);
} }
public static IRPClientWrapper createIrpClient(String uri, String pubkey, String privateKey, String repoName) { public static IRPClientWrapper createIrpClient(String uri, String pubkey, String privateKey,
String repoName) {
EndpointConfig config = new EndpointConfig(); EndpointConfig config = new EndpointConfig();
config.routerURI = uri; config.routerURI = uri;
config.repoName = repoName; config.repoName = repoName;

View File

@ -25,13 +25,9 @@ public class EmailUtil {
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", jo.get("port").getAsString()); props.setProperty("mail.smtp.socketFactory.port", jo.get("port").getAsString());
Session session = Session session = Session.getDefaultInstance(props, new Authenticator() {
Session.getDefaultInstance(
props,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() { public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( return new PasswordAuthentication(jo.get("from").getAsString(),
jo.get("from").getAsString(),
jo.get("pwd").getAsString()); // 发件人邮件用户名密码 jo.get("pwd").getAsString()); // 发件人邮件用户名密码
} }
}); });
@ -41,8 +37,8 @@ public class EmailUtil {
msg.setSubject(jo.get("subject").getAsString()); msg.setSubject(jo.get("subject").getAsString());
msg.setText(jo.get("content").getAsString()); msg.setText(jo.get("content").getAsString());
msg.setFrom(new InternetAddress(jo.get("from").getAsString())); msg.setFrom(new InternetAddress(jo.get("from").getAsString()));
msg.addRecipient( msg.addRecipient(Message.RecipientType.TO,
Message.RecipientType.TO, new InternetAddress(jo.get("to").getAsString())); new InternetAddress(jo.get("to").getAsString()));
Transport.send(msg); Transport.send(msg);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -48,7 +48,8 @@ public class HttpUtil {
ScriptObjectMirror som = (ScriptObjectMirror) headers; ScriptObjectMirror som = (ScriptObjectMirror) headers;
for (String key : som.getOwnKeys(true)) { for (String key : som.getOwnKeys(true)) {
Object val = som.get(key); Object val = som.get(key);
if (val instanceof String) connection.setRequestProperty(key, (String) val); if (val instanceof String)
connection.setRequestProperty(key, (String) val);
} }
} else { } else {
connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept", "application/json");
@ -77,9 +78,11 @@ public class HttpUtil {
} }
return ret; return ret;
} }
public static String encodeURI(String str) { public static String encodeURI(String str) {
return URLEncoder.encode(str); return URLEncoder.encode(str);
} }
public static String decodeURI(String str) { public static String decodeURI(String str) {
return URLDecoder.decode(str); return URLDecoder.decode(str);
} }
@ -131,7 +134,8 @@ public class HttpUtil {
connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Type", "application/json");
} }
connection.connect(); connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); OutputStreamWriter out =
new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
out.append((String) str.get("data")); out.append((String) str.get("data"));
out.flush(); out.flush();
out.close(); out.close();
@ -156,24 +160,17 @@ public class HttpUtil {
private static CloseableHttpClient getHttpClient(String url) { private static CloseableHttpClient getHttpClient(String url) {
try { try {
SSLContext sslcontext = SSLContext sslcontext =
SSLContexts.custom() SSLContexts.custom().loadTrustMaterial(null, (arg0, arg1) -> true).build();
.loadTrustMaterial(
null,
(arg0, arg1) -> true)
.build();
SSLConnectionSocketFactory sslSf = SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null,
new SSLConnectionSocketFactory( null, new NoopHostnameVerifier());
sslcontext, null, null, new NoopHostnameVerifier());
int tle = 10; int tle = 10;
if (url.contains("data.tj.gov.cn")) { if (url.contains("data.tj.gov.cn")) {
tle = 3; tle = 3;
} }
return HttpClients.custom() return HttpClients.custom().setSSLSocketFactory(sslSf)
.setSSLSocketFactory(sslSf)
.setKeepAliveStrategy((arg0, arg1) -> 0) .setKeepAliveStrategy((arg0, arg1) -> 0)
.setConnectionTimeToLive(tle, TimeUnit.SECONDS) .setConnectionTimeToLive(tle, TimeUnit.SECONDS).build();
.build();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -235,18 +232,15 @@ public class HttpUtil {
RequestBody.create(MediaType.parse("application/json; charset=utf-8"), req.data); RequestBody.create(MediaType.parse("application/json; charset=utf-8"), req.data);
Request request = new Request.Builder().url(req.url).post(body).build(); // 2.瀹氫箟涓<EFBFBD>涓猺equest Request request = new Request.Builder().url(req.url).post(body).build(); // 2.瀹氫箟涓<EFBFBD>涓猺equest
Call call = okHttpClient.newCall(request); // Call call = okHttpClient.newCall(request); //
call.enqueue( call.enqueue(new Callback() { //
new Callback() { //
@Override @Override
public void onFailure(Call call, IOException e) { public void onFailure(Call call, IOException e) {}
}
@Override @Override
public void onResponse(Call call, Response response) throws IOException { public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string(); // String result = response.body().string(); //
System.out.println("currentEngine:"); System.out.println("currentEngine:");
DesktopEngine.applyWithGlobal( DesktopEngine.applyWithGlobal(callback, currentEngine.getNashornGlobal(), result);
callback, currentEngine.getNashornGlobal(), result);
} }
}); });
return "success"; return "success";

View File

@ -1,33 +1,17 @@
package org.bdware.sc.boundry.utils; package org.bdware.sc.boundry.utils;
import com.google.api.client.json.Json;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bdware.doip.audit.EndpointConfig; import org.bdware.doip.audit.EndpointConfig;
import org.bdware.doip.audit.client.AuditIrpClient; import org.bdware.doip.audit.client.AuditIrpClient;
import org.bdware.doip.audit.config.TempConfigStorage; import org.bdware.doip.audit.config.TempConfigStorage;
import org.bdware.doip.codec.digitalObject.DigitalObject;
import org.bdware.doip.codec.digitalObject.Element;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.codec.doipMessage.DoipMessageFactory;
import org.bdware.doip.codec.operations.BasicOperations;
import org.bdware.doip.endpoint.client.ClientConfig;
import org.bdware.doip.endpoint.client.DoipClientImpl;
import org.bdware.doip.endpoint.client.DoipMessageCallback;
import org.bdware.irp.exception.IrpClientException;
import org.bdware.irp.stateinfo.StateInfoBase; import org.bdware.irp.stateinfo.StateInfoBase;
import org.bdware.sc.compiler.PermissionStub; import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.engine.JSONTool; import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.Permission; import org.bdware.sc.node.Permission;
import org.bdware.sc.util.JsonUtil;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror; import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@PermissionStub(permission = Permission.IRP) @PermissionStub(permission = Permission.IRP)
public class IRPUtil { public class IRPUtil {
@ -40,7 +24,8 @@ public class IRPUtil {
EndpointConfig endpointConfig = configStorage.loadAsEndpointConfig(); EndpointConfig endpointConfig = configStorage.loadAsEndpointConfig();
if (jo.has("clientDoId")) { if (jo.has("clientDoId")) {
this.auditIrpClient = new AuditIrpClient(jo.get("clientDoId").getAsString(), endpointConfig); this.auditIrpClient =
new AuditIrpClient(jo.get("clientDoId").getAsString(), endpointConfig);
} else { } else {
this.auditIrpClient = new AuditIrpClient(endpointConfig); this.auditIrpClient = new AuditIrpClient(endpointConfig);
} }

View File

@ -36,7 +36,8 @@ public class LedgerUtil {
public static Client getDefaultClient() { public static Client getDefaultClient() {
String ledgerParam = JavaScriptEntry.get.syncGet("", "getLedgerParams", ""); String ledgerParam = JavaScriptEntry.get.syncGet("", "getLedgerParams", "");
JsonElement jo = JsonParser.parseString(ledgerParam); JsonElement jo = JsonParser.parseString(ledgerParam);
JsonObject param = jo.getAsJsonObject().get("nodes").getAsJsonArray().get(0).getAsJsonObject(); JsonObject param =
jo.getAsJsonObject().get("nodes").getAsJsonArray().get(0).getAsJsonObject();
return new Client(param.get("ip").getAsString(), param.get("port").getAsInt()); return new Client(param.get("ip").getAsString(), param.get("port").getAsInt());
} }
@ -57,7 +58,8 @@ public class LedgerUtil {
ret.put("to", HashUtil.byteArray2Str(transaction.getTo().toByteArray(), 0), false); ret.put("to", HashUtil.byteArray2Str(transaction.getTo().toByteArray(), 0), false);
ret.put("type", transaction.getType().toString(), false); ret.put("type", transaction.getType().toString(), false);
ret.put("data", new String(transaction.getData().toByteArray()), false); ret.put("data", new String(transaction.getData().toByteArray()), false);
ret.put("blockHsah", HashUtil.byteArray2Str(transaction.getBlockHash().toByteArray(), 0), false); ret.put("blockHsah", HashUtil.byteArray2Str(transaction.getBlockHash().toByteArray(), 0),
false);
return ret; return ret;
} }
@ -66,14 +68,8 @@ public class LedgerUtil {
String from = str.get("from").toString(); String from = str.get("from").toString();
String to = str.get("to").toString(); String to = str.get("to").toString();
String data = str.get("data").toString(); String data = str.get("data").toString();
SendTransactionResponse result = SendTransactionResponse result = c.sendTransactionSync(ledger, TransactionType.MESSAGE,
c.sendTransactionSync( from, random.nextLong(), to, data.getBytes());
ledger,
TransactionType.MESSAGE,
from,
random.nextLong(),
to,
data.getBytes());
return HashUtil.byteArray2Str(result.getHash().toByteArray(), 0); return HashUtil.byteArray2Str(result.getHash().toByteArray(), 0);
} }
} }

View File

@ -18,12 +18,8 @@ public class MongoDBUtil {
List addrs = new ArrayList<>(); List addrs = new ArrayList<>();
addrs.add(serverAddress); addrs.add(serverAddress);
Method createeScramSha1 = Method createeScramSha1 =
Class.forName("com.mongodb.MongoCredential") Class.forName("com.mongodb.MongoCredential").getDeclaredMethod(
.getDeclaredMethod( "createScramSha1Credential", String.class, String.class, char[].class);
"createScramSha1Credential",
String.class,
String.class,
char[].class);
Object credential = createeScramSha1.invoke(null, usrName, dbName, pwd.toCharArray()); Object credential = createeScramSha1.invoke(null, usrName, dbName, pwd.toCharArray());
List credentials = new ArrayList<>(); List credentials = new ArrayList<>();
credentials.add(credential); credentials.add(credential);

View File

@ -116,7 +116,8 @@ public class MultiTagIndexDBUtil {
public List<Long> countInInterval(String tag, long startTime, long endTime, long interval) { public List<Long> countInInterval(String tag, long startTime, long endTime, long interval) {
List<Long> ret = new ArrayList<>(); List<Long> ret = new ArrayList<>();
if (interval <= 0) return ret; if (interval <= 0)
return ret;
long start = rocksDB.queryOffset(tag, startTime); long start = rocksDB.queryOffset(tag, startTime);
long delta; long delta;
startTime += interval; startTime += interval;

View File

@ -46,14 +46,13 @@ public class SM2Util {
JO ret = new JO(PropertyMap.newMap()); JO ret = new JO(PropertyMap.newMap());
try { try {
byte[] sig = ByteUtils.fromHexString(signature); byte[] sig = ByteUtils.fromHexString(signature);
ECPublicKeyParameters pubKey = ECPublicKeyParameters pubKey = BCECUtil.createECPublicKeyFromStrParameters(pubKeyStr,
BCECUtil.createECPublicKeyFromStrParameters( org.zz.gmhelper.SM2Util.CURVE, org.zz.gmhelper.SM2Util.DOMAIN_PARAMS);
pubKeyStr,
org.zz.gmhelper.SM2Util.CURVE,
org.zz.gmhelper.SM2Util.DOMAIN_PARAMS);
boolean value = org.zz.gmhelper.SM2Util.verify(pubKey, content.getBytes(), sig); boolean value = org.zz.gmhelper.SM2Util.verify(pubKey, content.getBytes(), sig);
if (value) ret.put("status", "success", false); if (value)
else ret.put("status", "failed", false); ret.put("status", "success", false);
else
ret.put("status", "failed", false);
ret.put("result", value, false); ret.put("result", value, false);
} catch (Exception e) { } catch (Exception e) {
ret.put("status", "failed", false); ret.put("status", "failed", false);
@ -65,9 +64,8 @@ public class SM2Util {
public static String encrypt(String content, String pubkey) { public static String encrypt(String content, String pubkey) {
try { try {
return ByteUtils.toHexString( return ByteUtils.toHexString(org.zz.gmhelper.SM2Util
org.zz.gmhelper.SM2Util.encrypt( .encrypt(SM2KeyPair.publicKeyStr2ECPoint(pubkey), content.getBytes()));
SM2KeyPair.publicKeyStr2ECPoint(pubkey), content.getBytes()));
} catch (InvalidCipherTextException e) { } catch (InvalidCipherTextException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -76,12 +74,10 @@ public class SM2Util {
public static String decrypt(String content, String privateKey) { public static String decrypt(String content, String privateKey) {
try { try {
ECPrivateKeyParameters privateKeyParam = ECPrivateKeyParameters privateKeyParam = new ECPrivateKeyParameters(
new ECPrivateKeyParameters(
new BigInteger(privateKey, 16), org.zz.gmhelper.SM2Util.DOMAIN_PARAMS); new BigInteger(privateKey, 16), org.zz.gmhelper.SM2Util.DOMAIN_PARAMS);
return new String( return new String(org.zz.gmhelper.SM2Util.decrypt(privateKeyParam,
org.zz.gmhelper.SM2Util.decrypt( ByteUtils.fromHexString(content)));
privateKeyParam, ByteUtils.fromHexString(content)));
} catch (InvalidCipherTextException e) { } catch (InvalidCipherTextException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -16,8 +16,7 @@ public class SQLUtil {
.setContextClassLoader(ContractProcess.instance.engine.getClassLoad()); .setContextClassLoader(ContractProcess.instance.engine.getClassLoad());
Class.forName(driver, true, ContractProcess.instance.engine.getClassLoad()); Class.forName(driver, true, ContractProcess.instance.engine.getClassLoad());
} catch (Exception e) { } catch (Exception e) {
System.out.println( System.out.println("Still can't find class! Cl of SQLUtil:\n\t\t"
"Still can't find class! Cl of SQLUtil:\n\t\t"
+ SQLUtil.class.getClassLoader()); + SQLUtil.class.getClassLoader());
System.out.println( System.out.println(
"Cl of DEgine:\n\t\t" + ContractProcess.instance.engine.getClassLoad()); "Cl of DEgine:\n\t\t" + ContractProcess.instance.engine.getClassLoad());
@ -40,18 +39,15 @@ public class SQLUtil {
if (password != null && !"undefined".equals(password)) { if (password != null && !"undefined".equals(password)) {
info.put("password", password); info.put("password", password);
} }
if (url.startsWith("jdbc:postgresql")) info.put("sslmode", "allow"); if (url.startsWith("jdbc:postgresql"))
info.put("sslmode", "allow");
Class<?> clz = Class<?> clz = Class.forName("java.sql.DriverManager", true,
Class.forName(
"java.sql.DriverManager",
true,
ContractProcess.instance.engine.getClassLoad()); ContractProcess.instance.engine.getClassLoad());
// set caller class into null, thus use YJSClassLoader in // set caller class into null, thus use YJSClassLoader in
// DriverManager.isDriverAllowed(driver,classloader); // DriverManager.isDriverAllowed(driver,classloader);
Method m = Method m = clz.getDeclaredMethod("getConnection", String.class, Properties.class,
clz.getDeclaredMethod( Class.class);
"getConnection", String.class, Properties.class, Class.class);
m.setAccessible(true); m.setAccessible(true);
return (Connection) m.invoke(null, url, info, null); return (Connection) m.invoke(null, url, info, null);
} catch (Exception e) { } catch (Exception e) {

View File

@ -23,7 +23,8 @@ public class UtilRegistry {
for (String name : allName) { for (String name : allName) {
Class<?> clz; Class<?> clz;
try { try {
clz = Class.forName(String.format("%s.%sUtil", UtilRegistry.class.getPackage().getName(), name)); clz = Class.forName(String.format("%s.%sUtil",
UtilRegistry.class.getPackage().getName(), name));
ret.add(clz); ret.add(clz);
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
@ -52,10 +53,8 @@ public class UtilRegistry {
public static String getInitStr(String s, boolean open) { public static String getInitStr(String s, boolean open) {
if (stubClzNameMap.containsKey(s)) { if (stubClzNameMap.containsKey(s)) {
String ret = String ret = String.format("%sUtil = %s.%sUtil%s;\n", s,
String.format( UtilRegistry.class.getPackage().getName(), s, open ? "" : "Stub");
"%sUtil = %s.%sUtil%s;\n",
s, UtilRegistry.class.getPackage().getName(), s, open ? "" : "Stub");
return ret; return ret;
} }
return ""; return "";

View File

@ -9,8 +9,8 @@ public abstract class AnnotationProcessor {
return; return;
} }
public void processFunction( public void processFunction(AnnotationNode anno, ContractNode contractNode,
AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) throws Exception { FunctionNode functionNode) throws Exception {
return; return;
} }
} }

View File

@ -34,7 +34,8 @@ public class PermissionStubGenerator extends ClassVisitor implements Opcodes {
return null; return null;
} }
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { public void visit(int version, int access, String name, String signature, String superName,
String[] interfaces) {
if (cv != null) { if (cv != null) {
cv.visit(version, access, name + "Stub", null, "java/lang/Object", null); cv.visit(version, access, name + "Stub", null, "java/lang/Object", null);
} }
@ -53,7 +54,8 @@ public class PermissionStubGenerator extends ClassVisitor implements Opcodes {
mv.visitEnd(); mv.visitEnd();
} }
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { public MethodVisitor visitMethod(int access, String name, String desc, String signature,
String[] exceptions) {
if (cv != null) { if (cv != null) {
if (name.equals("<clinit>")) if (name.equals("<clinit>"))
return null; return null;
@ -69,7 +71,8 @@ public class PermissionStubGenerator extends ClassVisitor implements Opcodes {
mv.visitTypeInsn(NEW, "javax/script/ScriptException"); mv.visitTypeInsn(NEW, "javax/script/ScriptException");
mv.visitInsn(DUP); mv.visitInsn(DUP);
mv.visitLdcInsn("Do not have " + p + " Permission"); mv.visitLdcInsn("Do not have " + p + " Permission");
mv.visitMethodInsn(INVOKESPECIAL, "javax/script/ScriptException", "<init>", "(Ljava/lang/String;)V"); mv.visitMethodInsn(INVOKESPECIAL, "javax/script/ScriptException", "<init>",
"(Ljava/lang/String;)V");
mv.visitInsn(ATHROW); mv.visitInsn(ATHROW);
mv.visitMaxs(5, 20); mv.visitMaxs(5, 20);
mv.visitEnd(); mv.visitEnd();

View File

@ -34,8 +34,7 @@ public class YJSCompiler {
ContractNode contract; ContractNode contract;
private static final Logger LOGGER = LogManager.getLogger(YJSCompiler.class); private static final Logger LOGGER = LogManager.getLogger(YJSCompiler.class);
public YJSCompiler() { public YJSCompiler() {}
}
public static ScriptFunction compileWithGlobal(Source source, Global global, Context context) { public static ScriptFunction compileWithGlobal(Source source, Global global, Context context) {
Global oldGlobal = Context.getGlobal(); Global oldGlobal = Context.getGlobal();
@ -55,8 +54,8 @@ public class YJSCompiler {
} }
} }
private static Context makeContext( private static Context makeContext(final InputStream in, final OutputStream out,
final InputStream in, final OutputStream out, final OutputStream err) { final OutputStream err) {
final PrintStream pout = final PrintStream pout =
out instanceof PrintStream ? (PrintStream) out : new PrintStream(out); out instanceof PrintStream ? (PrintStream) out : new PrintStream(out);
final PrintStream perr = final PrintStream perr =
@ -92,14 +91,8 @@ public class YJSCompiler {
} }
} }
} }
return new Context( return new Context(options, errors, wout, werr,
options, Thread.currentThread().getContextClassLoader(), new YJSFilter(), null);
errors,
wout,
werr,
Thread.currentThread().getContextClassLoader(),
new YJSFilter(),
null);
} }
public ContractZipBundle compile(ZipFile zf) throws Exception { public ContractZipBundle compile(ZipFile zf) throws Exception {
@ -115,9 +108,8 @@ public class YJSCompiler {
// Gson gson = new GsonBuilder().registerTypeAdapter(Contract.Type.class, // Gson gson = new GsonBuilder().registerTypeAdapter(Contract.Type.class,
// typeAdapter) // typeAdapter)
ContractManifest cm = ContractManifest cm = JsonUtil.GSON.fromJson(new InputStreamReader(manifestInput),
JsonUtil.GSON.fromJson( ContractManifest.class);
new InputStreamReader(manifestInput), ContractManifest.class);
// 如果没有就不限制根据gas进行插装 // 如果没有就不限制根据gas进行插装
if (0L != cm.getInsnLimit()) { if (0L != cm.getInsnLimit()) {
LOGGER.info("++++++++++++++++++++++true"); LOGGER.info("++++++++++++++++++++++true");
@ -161,23 +153,21 @@ public class YJSCompiler {
// add function _preSub // add function _preSub
// Kaidong Wu // Kaidong Wu
String preSubConName = cm.main.substring(0, cm.main.length() - 4) + "PreSub"; String preSubConName = cm.main.substring(0, cm.main.length() - 4) + "PreSub";
String preSubContract = String preSubContract = "contract " + preSubConName
"contract "
+ preSubConName
+ " { function _preSub (e) { YancloudUtil.preSub(e.topic, e.content); }}"; + " { function _preSub (e) { YancloudUtil.preSub(e.topic, e.content); }}";
ContractNode preSubNode = ContractNode preSubNode =
compile( compile(new ByteArrayInputStream(preSubContract.getBytes(StandardCharsets.UTF_8)),
new ByteArrayInputStream(preSubContract.getBytes(StandardCharsets.UTF_8)),
preSubConName + ".yjs"); preSubConName + ".yjs");
czb.put(preSubConName + ".yjs", preSubNode); czb.put(preSubConName + ".yjs", preSubNode);
LOGGER.info("--compile-- " + preSubConName); LOGGER.info("--compile-- " + preSubConName);
String globalBeanName = cm.main.substring(0, cm.main.length() - 4) + "GlobalBean"; String globalBeanName = cm.main.substring(0, cm.main.length() - 4) + "GlobalBean";
String globalBeanContract = String globalBeanContract = "contract " + globalBeanName
"contract " + globalBeanName + "{ function setGlobal (_global) { Global = _global; }\n" + + "{ function setGlobal (_global) { Global = _global; }\n"
" function getGlobal () { return Global; }}"; + " function getGlobal () { return Global; }}";
czb.put(globalBeanName + ".yjs", czb.put(globalBeanName + ".yjs",
compile(new ByteArrayInputStream(globalBeanContract.getBytes(StandardCharsets.UTF_8)), compile(new ByteArrayInputStream(
globalBeanContract.getBytes(StandardCharsets.UTF_8)),
globalBeanName + ".yjs")); globalBeanName + ".yjs"));
LOGGER.info("--compile-- " + globalBeanName); LOGGER.info("--compile-- " + globalBeanName);
czb.setMergedContractNode(); czb.setMergedContractNode();

View File

@ -7,6 +7,8 @@ import org.bdware.sc.node.FunctionNode;
public class Confidential extends AnnotationProcessor { public class Confidential extends AnnotationProcessor {
@Override @Override
public void processFunction(AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { public void processFunction(AnnotationNode anno, ContractNode contractNode,
functionNode.setConfidential(true); } FunctionNode functionNode) {
functionNode.setConfidential(true);
}
} }

View File

@ -9,8 +9,8 @@ import org.bdware.sc.util.JsonUtil;
public class Cost extends AnnotationProcessor { public class Cost extends AnnotationProcessor {
@Override @Override
public void processFunction( public void processFunction(AnnotationNode anno, ContractNode contractNode,
AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { FunctionNode functionNode) {
CostDetail detail = JsonUtil.fromJson(anno.getArgs().get(0), CostDetail.class); CostDetail detail = JsonUtil.fromJson(anno.getArgs().get(0), CostDetail.class);
functionNode.setCost(detail); functionNode.setCost(detail);
if (detail.isCountGas()) if (detail.isCountGas())

View File

@ -10,7 +10,8 @@ import org.bdware.sc.node.FunctionNode;
// DOOP is designed for DoipModule which contains specific functions for RepositoryHandler // DOOP is designed for DoipModule which contains specific functions for RepositoryHandler
public class DOOP extends AnnotationProcessor { public class DOOP extends AnnotationProcessor {
@Override @Override
public void processFunction(AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) throws Exception { public void processFunction(AnnotationNode anno, ContractNode contractNode,
FunctionNode functionNode) throws Exception {
// 通过DOOP注解解析对应的值并放进对应的FunctionNode中 // 通过DOOP注解解析对应的值并放进对应的FunctionNode中
functionNode.setIsExport(true); functionNode.setIsExport(true);
functionNode.setIsDoipOperation(true); functionNode.setIsDoipOperation(true);

View File

@ -8,7 +8,8 @@ import org.bdware.sc.node.FunctionNode;
public class HomomorphicDecrypt extends AnnotationProcessor { public class HomomorphicDecrypt extends AnnotationProcessor {
@Override @Override
public void processFunction(AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { public void processFunction(AnnotationNode anno, ContractNode contractNode,
FunctionNode functionNode) {
functionNode.setHomomorphicDecrypt(true); functionNode.setHomomorphicDecrypt(true);
functionNode.setKeyManagerID(anno.getArgs().get(0)); functionNode.setKeyManagerID(anno.getArgs().get(0));
functionNode.setSecretID(anno.getArgs().get(1)); functionNode.setSecretID(anno.getArgs().get(1));

View File

@ -8,7 +8,8 @@ import org.bdware.sc.node.FunctionNode;
public class HomomorphicEncrypt extends AnnotationProcessor { public class HomomorphicEncrypt extends AnnotationProcessor {
@Override @Override
public void processFunction(AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { public void processFunction(AnnotationNode anno, ContractNode contractNode,
FunctionNode functionNode) {
functionNode.setHomomorphicEncrypt(true); functionNode.setHomomorphicEncrypt(true);
functionNode.setKeyManagerID(anno.getArgs().get(0)); functionNode.setKeyManagerID(anno.getArgs().get(0));
functionNode.setSecretID(anno.getArgs().get(1)); functionNode.setSecretID(anno.getArgs().get(1));

View File

@ -8,8 +8,8 @@ import org.bdware.sc.node.FunctionNode;
public class Join extends AnnotationProcessor { public class Join extends AnnotationProcessor {
@Override @Override
public void processFunction( public void processFunction(AnnotationNode anno, ContractNode contractNode,
AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { FunctionNode functionNode) {
// functionNode.setRouteInfo(RouteInfo.create(anno,contractNode)); // functionNode.setRouteInfo(RouteInfo.create(anno,contractNode));
// 增加标记在ContractNode中记录Join相关的函数和Join规则 // 增加标记在ContractNode中记录Join相关的函数和Join规则
functionNode.setJoinInfo(JoinInfo.create(anno, contractNode)); functionNode.setJoinInfo(JoinInfo.create(anno, contractNode));

View File

@ -14,12 +14,11 @@ public class LogLocation extends AnnotationProcessor {
} }
@Override @Override
public void processFunction( public void processFunction(AnnotationNode anno, ContractNode contractNode,
AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { FunctionNode functionNode) {
if (anno != null && anno.getArgs() != null) if (anno != null && anno.getArgs() != null)
for (String s : anno.getArgs()) { for (String s : anno.getArgs()) {
if (s.equals("\"dataware\"") if (s.equals("\"dataware\"") || s.equals("\"bdledger\"")
|| s.equals("\"bdledger\"")
|| s.equals("\"bdledger:\"")) { || s.equals("\"bdledger:\"")) {
functionNode.setLogToBDContract(true); functionNode.setLogToBDContract(true);
} else if (s.startsWith("\"bdledger:") && s.length() > 11) { } else if (s.startsWith("\"bdledger:") && s.length() > 11) {

View File

@ -15,12 +15,13 @@ public class LogType extends AnnotationProcessor {
} }
@Override @Override
public void processFunction( public void processFunction(AnnotationNode anno, ContractNode contractNode,
AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { FunctionNode functionNode) {
for (String str : anno.getArgs()) { for (String str : anno.getArgs()) {
org.bdware.sc.node.LogType type = org.bdware.sc.node.LogType.parse(str); org.bdware.sc.node.LogType type = org.bdware.sc.node.LogType.parse(str);
functionNode.addLogType(type); functionNode.addLogType(type);
if (type == org.bdware.sc.node.LogType.Branch) contractNode.setInstrumentBranch(true); if (type == org.bdware.sc.node.LogType.Branch)
contractNode.setInstrumentBranch(true);
} }
} }
} }

View File

@ -1,17 +1,15 @@
package org.bdware.sc.compiler.ap; package org.bdware.sc.compiler.ap;
import com.google.gson.Gson;
import org.bdware.sc.bean.RouteInfo; import org.bdware.sc.bean.RouteInfo;
import org.bdware.sc.compiler.AnnotationProcessor; import org.bdware.sc.compiler.AnnotationProcessor;
import org.bdware.sc.node.AnnotationNode; import org.bdware.sc.node.AnnotationNode;
import org.bdware.sc.node.ContractNode; import org.bdware.sc.node.ContractNode;
import org.bdware.sc.node.CostDetail;
import org.bdware.sc.node.FunctionNode; import org.bdware.sc.node.FunctionNode;
public class Route extends AnnotationProcessor { public class Route extends AnnotationProcessor {
@Override @Override
public void processFunction( public void processFunction(AnnotationNode anno, ContractNode contractNode,
AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { FunctionNode functionNode) {
functionNode.setRouteInfo(RouteInfo.create(anno, contractNode)); functionNode.setRouteInfo(RouteInfo.create(anno, contractNode));
} }
} }

View File

@ -9,8 +9,8 @@ import org.bdware.sc.node.FunctionNode;
public class Split extends AnnotationProcessor { public class Split extends AnnotationProcessor {
@Override @Override
public void processFunction( public void processFunction(AnnotationNode anno, ContractNode contractNode,
AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) { FunctionNode functionNode) {
functionNode.setRouteInfo(RouteInfo.create(anno, contractNode)); functionNode.setRouteInfo(RouteInfo.create(anno, contractNode));
} }
} }

View File

@ -13,7 +13,8 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class SharableVar { public class SharableVar {
public final static HashedWheelTimer HASHED_WHEEL_TIMER = new HashedWheelTimer(new ThreadFactory() { public final static HashedWheelTimer HASHED_WHEEL_TIMER =
new HashedWheelTimer(new ThreadFactory() {
@Override @Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable r) {
Thread t = Executors.defaultThreadFactory().newThread(r); Thread t = Executors.defaultThreadFactory().newThread(r);
@ -31,7 +32,8 @@ public class SharableVar {
private SyncTimeout nextTimeOut; private SyncTimeout nextTimeOut;
public SharableVar(String cpId, String identifier, SharableVarManager.VarResolveResult resolveResult) { public SharableVar(String cpId, String identifier,
SharableVarManager.VarResolveResult resolveResult) {
counter = new GCounter(cpId, identifier); counter = new GCounter(cpId, identifier);
myId = cpId; myId = cpId;
varId = identifier; varId = identifier;

View File

@ -49,7 +49,8 @@ public class SharableVarManager {
String content = message.header.parameters.attributes.get("content").getAsString(); String content = message.header.parameters.attributes.get("content").getAsString();
SharableVar var = getVar(varId); SharableVar var = getVar(varId);
var.join(content); var.join(content);
DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder(); DoipMessageFactory.DoipMessageBuilder builder =
new DoipMessageFactory.DoipMessageBuilder();
builder.createResponse(DoipResponseCode.Success, message); builder.createResponse(DoipResponseCode.Success, message);
builder.addAttributes("msg", "success"); builder.addAttributes("msg", "success");
return builder.create(); return builder.create();
@ -57,7 +58,8 @@ public class SharableVarManager {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(); e.printStackTrace();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder(); DoipMessageFactory.DoipMessageBuilder builder =
new DoipMessageFactory.DoipMessageBuilder();
builder.createResponse(DoipResponseCode.UnKnownError, message); builder.createResponse(DoipResponseCode.UnKnownError, message);
builder.addAttributes("exception", bo.toString()); builder.addAttributes("exception", bo.toString());
return builder.create(); return builder.create();
@ -83,7 +85,8 @@ public class SharableVarManager {
client.sendMessage(doipMessage, new DoipMessageCallback() { client.sendMessage(doipMessage, new DoipMessageCallback() {
@Override @Override
public void onResult(DoipMessage doipMessage) { public void onResult(DoipMessage doipMessage) {
LOGGER.info("RECV Sync:" + JsonUtil.toJson(JsonDoipMessage.fromDoipMessage(doipMessage))); LOGGER.info("RECV Sync:"
+ JsonUtil.toJson(JsonDoipMessage.fromDoipMessage(doipMessage)));
} }
}); });
} }
@ -104,14 +107,18 @@ public class SharableVarManager {
public synchronized SharableVar createVar(String identifier, String type) { public synchronized SharableVar createVar(String identifier, String type) {
try { try {
if (allVars.containsKey(identifier)) return allVars.get(identifier); if (allVars.containsKey(identifier))
return allVars.get(identifier);
StateInfoBase stateInfoBase = client.resolve(identifier); StateInfoBase stateInfoBase = client.resolve(identifier);
if (stateInfoBase.handleValues.has("bdwType") && stateInfoBase.handleValues.get("bdwType").getAsString().equals("SharableVar")) { if (stateInfoBase.handleValues.has("bdwType") && stateInfoBase.handleValues
VarResolveResult resolveResult = JsonUtil.fromJson(stateInfoBase.handleValues, VarResolveResult.class); .get("bdwType").getAsString().equals("SharableVar")) {
VarResolveResult resolveResult =
JsonUtil.fromJson(stateInfoBase.handleValues, VarResolveResult.class);
SharableVar sharableVar = new SharableVar(cpId, identifier, resolveResult); SharableVar sharableVar = new SharableVar(cpId, identifier, resolveResult);
allVars.put(identifier, sharableVar); allVars.put(identifier, sharableVar);
return sharableVar; return sharableVar;
} else return null; } else
return null;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;

View File

@ -23,23 +23,26 @@ public class ConfidentialContractUtil {
public static final String CONFIDENTIAL_TEMPLATE_PATH = System.getenv("GRAPHENE_DIR") public static final String CONFIDENTIAL_TEMPLATE_PATH = System.getenv("GRAPHENE_DIR")
+ File.separator + "Examples" + File.separator + "nodejs-secret"; + File.separator + "Examples" + File.separator + "nodejs-secret";
public static final String CONFIDENTIAL_SCRIPT_PATH = System.getenv("GRAPHENE_DIR") public static final String CONFIDENTIAL_SCRIPT_PATH =
+ File.separator + "App"; System.getenv("GRAPHENE_DIR") + File.separator + "App";
public static final String[] COMMAND = {"bash", "executeContract.sh"}; public static final String[] COMMAND = {"bash", "executeContract.sh"};
private static final Type MapType = TypeToken.getParameterized(HashMap.class, String.class, String.class).getType(); private static final Type MapType =
TypeToken.getParameterized(HashMap.class, String.class, String.class).getType();
public static String executeConfidentialContract(ContractRequest input) throws IOException, InterruptedException { public static String executeConfidentialContract(ContractRequest input)
throws IOException, InterruptedException {
File runDir = new File(CONFIDENTIAL_SCRIPT_PATH + File.separator + input.getRequestID()); File runDir = new File(CONFIDENTIAL_SCRIPT_PATH + File.separator + input.getRequestID());
ProcessBuilder pb = new ProcessBuilder(COMMAND); ProcessBuilder pb = new ProcessBuilder(COMMAND);
pb.directory(runDir); pb.directory(runDir);
Process p = pb.start(); Process p = pb.start();
p.waitFor(); p.waitFor();
File resultFile = new File(CONFIDENTIAL_SCRIPT_PATH + File.separator + input.getRequestID() + File resultFile = new File(CONFIDENTIAL_SCRIPT_PATH + File.separator + input.getRequestID()
File.separator + "result.json"); + File.separator + "result.json");
return FileUtils.readFileToString(resultFile, StandardCharsets.UTF_8); return FileUtils.readFileToString(resultFile, StandardCharsets.UTF_8);
} }
public static void generateConfidentialContract(ContractNode cn, ScriptObjectMirror globalVars, Global global) { public static void generateConfidentialContract(ContractNode cn, ScriptObjectMirror globalVars,
Global global) {
List<FunctionNode> functionNodes = cn.getFunctions(); List<FunctionNode> functionNodes = cn.getFunctions();
for (FunctionNode fn : functionNodes) { for (FunctionNode fn : functionNodes) {
// assuming only one confidential function for now // assuming only one confidential function for now
@ -54,18 +57,46 @@ public class ConfidentialContractUtil {
} }
} }
// load necessary Node.js libraries // load necessary Node.js libraries
jsStr.append("var fs = require('fs');\n" + "var crypto = require('crypto');\n" + "var sm2 = require('sm-crypto').sm2;\n"); jsStr.append("var fs = require('fs');\n" + "var crypto = require('crypto');\n"
+ "var sm2 = require('sm-crypto').sm2;\n");
// load Global variables and arguments from files // load Global variables and arguments from files
jsStr.append("let rawGlobal = fs.readFileSync('global.json').toString();\n" + "let Global = JSON.parse(rawGlobal);\n"); jsStr.append("let rawGlobal = fs.readFileSync('global.json').toString();\n"
jsStr.append("let rawArg = fs.readFileSync('arg.json').toString();\n" + "let jsonArg = JSON.parse(rawArg);\n" + "let requester = jsonArg.requester;\n" + "let arg = jsonArg.arg;\n"); + "let Global = JSON.parse(rawGlobal);\n");
jsStr.append("let rawArg = fs.readFileSync('arg.json').toString();\n"
+ "let jsonArg = JSON.parse(rawArg);\n"
+ "let requester = jsonArg.requester;\n" + "let arg = jsonArg.arg;\n");
jsStr.append("let srcStr = fs.readFileSync('contract.js').toString();\n"); jsStr.append("let srcStr = fs.readFileSync('contract.js').toString();\n");
// verify signatures and decrypt all confidential variables Important!!!!! // verify signatures and decrypt all confidential variables Important!!!!!
jsStr.append("for (var k in Global) {\n" + " if (Global.hasOwnProperty(k)) {\n" + " if (k.startsWith('conf_')) {\n" + " let sig = Global[k].signature;\n" + " let pubKey = Global[k].owner;\n" + " let verifyResult = sm2.doVerifySignature(srcStr, sig, pubKey);\n" + " if (verifyResult) {\n" + " let newKey = k.substring(5);\n" + " let decKey = Buffer.from(process.env['KEY_'+pubKey.substring(0,10).toUpperCase()], 'hex');\n" + " let decIv = Buffer.from(Global[k].iv, 'hex');\n" + " let cipherText = Buffer.from(Global[k].cipherText, 'hex');\n" + " let decipher = crypto.createDecipheriv('aes-256-cbc', decKey, decIv);\n" + " let decrypted = decipher.update(cipherText);\n" + " decrypted = Buffer.concat([decrypted, decipher.final()]);\n" + " let plaintext = decrypted.toString();\n" + " Global[newKey] = plaintext;\n" + " }\n" + " }\n" + " }\n" + "}\n"); jsStr.append("for (var k in Global) {\n" + " if (Global.hasOwnProperty(k)) {\n"
+ " if (k.startsWith('conf_')) {\n"
+ " let sig = Global[k].signature;\n"
+ " let pubKey = Global[k].owner;\n"
+ " let verifyResult = sm2.doVerifySignature(srcStr, sig, pubKey);\n"
+ " if (verifyResult) {\n" + " let newKey = k.substring(5);\n"
+ " let decKey = Buffer.from(process.env['KEY_'+pubKey.substring(0,10).toUpperCase()], 'hex');\n"
+ " let decIv = Buffer.from(Global[k].iv, 'hex');\n"
+ " let cipherText = Buffer.from(Global[k].cipherText, 'hex');\n"
+ " let decipher = crypto.createDecipheriv('aes-256-cbc', decKey, decIv);\n"
+ " let decrypted = decipher.update(cipherText);\n"
+ " decrypted = Buffer.concat([decrypted, decipher.final()]);\n"
+ " let plaintext = decrypted.toString();\n"
+ " Global[newKey] = plaintext;\n" + " }\n" + " }\n"
+ " }\n" + "}\n");
// call function // call function
jsStr.append("var ret = ").append(fn.functionName).append("(arg, requester, null);\n"); jsStr.append("var ret = ").append(fn.functionName)
// TODO: encrypt all confidential variables so state can be updated in confidential function @shujunyi .append("(arg, requester, null);\n");
// TODO: encrypt all confidential variables so state can be updated in confidential
// function @shujunyi
// encrypt return value and write to a file // encrypt return value and write to a file
jsStr.append("var retStr = JSON.stringify(ret);\n" + "var key = Buffer.from(process.env['KEY_'+requester.substring(0,10).toUpperCase()], 'hex');\n" + "var iv = crypto.randomBytes(16);\n" + "let cipher = crypto.createCipheriv('aes-256-cbc', key, iv); \n" + "let encRet = cipher.update(retStr);\n" + "encRet = Buffer.concat([encRet, cipher.final()]);\n" + "let result = {iv: iv.toString('hex'), encryptedData: encRet.toString('hex')};\n" + "let resultStr = JSON.stringify(result);\n" + "fs.writeFileSync('result.json', resultStr);\n"); jsStr.append("var retStr = JSON.stringify(ret);\n"
+ "var key = Buffer.from(process.env['KEY_'+requester.substring(0,10).toUpperCase()], 'hex');\n"
+ "var iv = crypto.randomBytes(16);\n"
+ "let cipher = crypto.createCipheriv('aes-256-cbc', key, iv); \n"
+ "let encRet = cipher.update(retStr);\n"
+ "encRet = Buffer.concat([encRet, cipher.final()]);\n"
+ "let result = {iv: iv.toString('hex'), encryptedData: encRet.toString('hex')};\n"
+ "let resultStr = JSON.stringify(result);\n"
+ "fs.writeFileSync('result.json', resultStr);\n");
// put script into Global so owner can send it and collect signatures // put script into Global so owner can send it and collect signatures
Object som = ScriptObjectMirror.wrap(jsStr.toString(), global); Object som = ScriptObjectMirror.wrap(jsStr.toString(), global);
globalVars.put("src_" + fn.functionName, som); globalVars.put("src_" + fn.functionName, som);
@ -85,11 +116,8 @@ public class ConfidentialContractUtil {
} }
} }
public static void dumpScriptAndStates( public static void dumpScriptAndStates(Invocable engine, FunctionNode functionNode,
Invocable engine, ContractRequest input, ScriptObjectMirror globalVars)
FunctionNode functionNode,
ContractRequest input,
ScriptObjectMirror globalVars)
throws IOException, ScriptException, NoSuchMethodException { throws IOException, ScriptException, NoSuchMethodException {
Map<String, Object> globalMap = (Map<String, Object>) convertIntoJavaObject(globalVars); Map<String, Object> globalMap = (Map<String, Object>) convertIntoJavaObject(globalVars);
String dest = CONFIDENTIAL_SCRIPT_PATH + File.separator + input.getRequestID(); String dest = CONFIDENTIAL_SCRIPT_PATH + File.separator + input.getRequestID();
@ -136,156 +164,116 @@ public class ConfidentialContractUtil {
return dependentFunctions; return dependentFunctions;
} }
private static String generateGrapheneManifestStr(Invocable engine, ContractRequest input) throws ScriptException, NoSuchMethodException { private static String generateGrapheneManifestStr(Invocable engine, ContractRequest input)
String manifestStr = "# Nodejs manifest file example\n" + throws ScriptException, NoSuchMethodException {
"#\n" + String manifestStr = "# Nodejs manifest file example\n" + "#\n"
"# This manifest was prepared and tested on Ubuntu 18.04.\n" + + "# This manifest was prepared and tested on Ubuntu 18.04.\n" + "\n"
"\n" + + "loader.argv0_override = \"nodejs\"\n" + "\n"
"loader.argv0_override = \"nodejs\"\n" + + "# LibOS layer library of Graphene. There is currently only one implementation,\n"
"\n" + + "# so it is always set to libsysdb.so.\n"
"# LibOS layer library of Graphene. There is currently only one implementation,\n" + + "loader.preload = \"file:$(GRAPHENEDIR)/Runtime/libsysdb.so\"\n" + "\n"
"# so it is always set to libsysdb.so.\n" + + "# Show/hide debug log of Graphene ('inline' or 'none' respectively).\n"
"loader.preload = \"file:$(GRAPHENEDIR)/Runtime/libsysdb.so\"\n" + + "loader.debug_type = \"$(GRAPHENEDEBUG)\"\n" + "\n"
"\n" + + "# Read application arguments directly from the command line. Don't use this on production!\n"
"# Show/hide debug log of Graphene ('inline' or 'none' respectively).\n" + + "loader.insecure__use_cmdline_argv = 1\n" + "\n"
"loader.debug_type = \"$(GRAPHENEDEBUG)\"\n" + + "# Specify paths to search for libraries. The usual LD_LIBRARY_PATH syntax\n"
"\n" + + "# applies. Paths must be in-Graphene visible paths, not host-OS paths (i.e.,\n"
"# Read application arguments directly from the command line. Don't use this on production!\n" + + "# paths must be taken from fs.mount.xxx.path, not fs.mount.xxx.uri).\n"
"loader.insecure__use_cmdline_argv = 1\n" + + "loader.env.LD_LIBRARY_PATH = \"/lib:/usr/lib:$(ARCH_LIBDIR):/usr/$(ARCH_LIBDIR):./\"\n"
"\n" + + "\n"
"# Specify paths to search for libraries. The usual LD_LIBRARY_PATH syntax\n" + + "# Mount host-OS directory to required libraries (in 'uri') into in-Graphene\n"
"# applies. Paths must be in-Graphene visible paths, not host-OS paths (i.e.,\n" + + "# visible directory /lib (in 'path').\n" + "fs.mount.lib.type = \"chroot\"\n"
"# paths must be taken from fs.mount.xxx.path, not fs.mount.xxx.uri).\n" + + "fs.mount.lib.path = \"/lib\"\n"
"loader.env.LD_LIBRARY_PATH = \"/lib:/usr/lib:$(ARCH_LIBDIR):/usr/$(ARCH_LIBDIR):./\"\n" + + "fs.mount.lib.uri = \"file:$(GRAPHENEDIR)/Runtime\"\n" + "\n"
"\n" + + "fs.mount.lib2.type = \"chroot\"\n" + "fs.mount.lib2.path = \"$(ARCH_LIBDIR)\"\n"
"# Mount host-OS directory to required libraries (in 'uri') into in-Graphene\n" + + "fs.mount.lib2.uri = \"file:$(ARCH_LIBDIR)\"\n" + "\n"
"# visible directory /lib (in 'path').\n" + + "#fs.mount.lib3.type = \"chroot\"\n"
"fs.mount.lib.type = \"chroot\"\n" + + "#fs.mount.lib3.path = \"/usr/$(ARCH_LIBDIR)\"\n"
"fs.mount.lib.path = \"/lib\"\n" + + "#fs.mount.lib3.uri = \"file:/usr/$(ARCH_LIBDIR)\"\n" + "\n"
"fs.mount.lib.uri = \"file:$(GRAPHENEDIR)/Runtime\"\n" + + "fs.mount.usr.type = \"chroot\"\n" + "fs.mount.usr.path = \"/usr\"\n"
"\n" + + "fs.mount.usr.uri = \"file:/usr\"\n" + "\n"
"fs.mount.lib2.type = \"chroot\"\n" + + "# Host-level directory to NSS files required by Glibc + NSS libs\n"
"fs.mount.lib2.path = \"$(ARCH_LIBDIR)\"\n" + + "fs.mount.etc.type = \"chroot\"\n" + "fs.mount.etc.path = \"/etc\"\n"
"fs.mount.lib2.uri = \"file:$(ARCH_LIBDIR)\"\n" + + "fs.mount.etc.uri = \"file:/etc\"\n" + "\n"
"\n" + + "# Workload needs to create temporary files\n"
"#fs.mount.lib3.type = \"chroot\"\n" + + "fs.mount.tmp.type = \"chroot\"\n" + "fs.mount.tmp.path = \"/tmp\"\n"
"#fs.mount.lib3.path = \"/usr/$(ARCH_LIBDIR)\"\n" + + "fs.mount.tmp.uri = \"file:/tmp\"\n" + "\n"
"#fs.mount.lib3.uri = \"file:/usr/$(ARCH_LIBDIR)\"\n" + + "# Set enclave size to 2GB; NodeJS expects around 1.7GB of heap on startup,\n"
"\n" + + "# see e.g. https://github.com/nodejs/node/issues/13018.\n"
"fs.mount.usr.type = \"chroot\"\n" + + "# Recall that SGX v1 requires to specify enclave size at enclave creation time.\n"
"fs.mount.usr.path = \"/usr\"\n" + + "sgx.enclave_size = \"2G\"\n" + "\n"
"fs.mount.usr.uri = \"file:/usr\"\n" + + "# Set maximum number of in-enclave threads (somewhat arbitrarily) to 8. Recall\n"
"\n" + + "# that SGX v1 requires to specify the maximum number of simultaneous threads at\n"
"# Host-level directory to NSS files required by Glibc + NSS libs\n" + + "# enclave creation time.\n" + "sgx.thread_num = 16\n" + "\n"
"fs.mount.etc.type = \"chroot\"\n" + + "# Specify all libraries used by Node.js and its dependencies (including all libs\n"
"fs.mount.etc.path = \"/etc\"\n" + + "# which can be loaded at runtime via dlopen).\n"
"fs.mount.etc.uri = \"file:/etc\"\n" + + "sgx.trusted_files.ld = \"file:$(GRAPHENEDIR)/Runtime/ld-linux-x86-64.so.2\"\n"
"\n" + + "sgx.trusted_files.libc = \"file:$(GRAPHENEDIR)/Runtime/libc.so.6\"\n"
"# Workload needs to create temporary files\n" + + "sgx.trusted_files.libm = \"file:$(GRAPHENEDIR)/Runtime/libm.so.6\"\n"
"fs.mount.tmp.type = \"chroot\"\n" + + "sgx.trusted_files.libdl = \"file:$(GRAPHENEDIR)/Runtime/libdl.so.2\"\n"
"fs.mount.tmp.path = \"/tmp\"\n" + + "sgx.trusted_files.librt = \"file:$(GRAPHENEDIR)/Runtime/librt.so.1\"\n"
"fs.mount.tmp.uri = \"file:/tmp\"\n" + + "sgx.trusted_files.libutil = \"file:$(GRAPHENEDIR)/Runtime/libutil.so.1\"\n"
"\n" + + "sgx.trusted_files.libpthread = \"file:$(GRAPHENEDIR)/Runtime/libpthread.so.0\"\n"
"# Set enclave size to 2GB; NodeJS expects around 1.7GB of heap on startup,\n" + + "sgx.trusted_files.libnssdns = \"file:$(GRAPHENEDIR)/Runtime/libnss_dns.so.2\"\n"
"# see e.g. https://github.com/nodejs/node/issues/13018.\n" + + "sgx.trusted_files.libresolv = \"file:$(GRAPHENEDIR)/Runtime/libresolv.so.2\"\n"
"# Recall that SGX v1 requires to specify enclave size at enclave creation time.\n" + + "\n" + "sgx.trusted_files.libstdc = \"file:/usr/$(ARCH_LIBDIR)/libstdc++.so.6\"\n"
"sgx.enclave_size = \"2G\"\n" + + "sgx.trusted_files.libgccs = \"file:$(ARCH_LIBDIR)/libgcc_s.so.1\"\n"
"\n" + + "sgx.trusted_files.libaptpkg = \"file:/usr/$(ARCH_LIBDIR)/libapt-pkg.so.5.0\"\n"
"# Set maximum number of in-enclave threads (somewhat arbitrarily) to 8. Recall\n" + + "sgx.trusted_files.liblz4 = \"file:/usr/$(ARCH_LIBDIR)/liblz4.so.1\"\n"
"# that SGX v1 requires to specify the maximum number of simultaneous threads at\n" + + "sgx.trusted_files.libsystemd = \"file:$(ARCH_LIBDIR)/libsystemd.so.0\"\n"
"# enclave creation time.\n" + + "sgx.trusted_files.libselinux = \"file:$(ARCH_LIBDIR)/libselinux.so.1\"\n"
"sgx.thread_num = 16\n" + + "sgx.trusted_files.libgcrypt = \"file:$(ARCH_LIBDIR)/libgcrypt.so.20\"\n"
"\n" + + "sgx.trusted_files.libpcre = \"file:$(ARCH_LIBDIR)/libpcre.so.3\"\n"
"# Specify all libraries used by Node.js and its dependencies (including all libs\n" + + "sgx.trusted_files.libgpgerror = \"file:$(ARCH_LIBDIR)/libgpg-error.so.0\"\n"
"# which can be loaded at runtime via dlopen).\n" + + "sgx.trusted_files.libexpat = \"file:$(ARCH_LIBDIR)/libexpat.so.1\"\n"
"sgx.trusted_files.ld = \"file:$(GRAPHENEDIR)/Runtime/ld-linux-x86-64.so.2\"\n" + + "sgx.trusted_files.libz = \"file:$(ARCH_LIBDIR)/libz.so.1\"\n"
"sgx.trusted_files.libc = \"file:$(GRAPHENEDIR)/Runtime/libc.so.6\"\n" + + "sgx.trusted_files.libz2 = \"file:$(ARCH_LIBDIR)/libbz2.so.1.0\"\n"
"sgx.trusted_files.libm = \"file:$(GRAPHENEDIR)/Runtime/libm.so.6\"\n" + + "sgx.trusted_files.liblzma = \"file:$(ARCH_LIBDIR)/liblzma.so.5\"\n"
"sgx.trusted_files.libdl = \"file:$(GRAPHENEDIR)/Runtime/libdl.so.2\"\n" + + "sgx.trusted_files.libmpdec = \"file:/usr/$(ARCH_LIBDIR)/libmpdec.so.2\"\n" + "\n"
"sgx.trusted_files.librt = \"file:$(GRAPHENEDIR)/Runtime/librt.so.1\"\n" + + "# Name Service Switch (NSS) libraries (Glibc dependencies)\n"
"sgx.trusted_files.libutil = \"file:$(GRAPHENEDIR)/Runtime/libutil.so.1\"\n" + + "sgx.trusted_files.libnssfiles = \"file:$(ARCH_LIBDIR)/libnss_files.so.2\"\n"
"sgx.trusted_files.libpthread = \"file:$(GRAPHENEDIR)/Runtime/libpthread.so.0\"\n" + + "sgx.trusted_files.libnsscompat = \"file:$(ARCH_LIBDIR)/libnss_compat.so.2\"\n"
"sgx.trusted_files.libnssdns = \"file:$(GRAPHENEDIR)/Runtime/libnss_dns.so.2\"\n" + + "sgx.trusted_files.libnssnis = \"file:$(ARCH_LIBDIR)/libnss_nis.so.2\"\n"
"sgx.trusted_files.libresolv = \"file:$(GRAPHENEDIR)/Runtime/libresolv.so.2\"\n" + + "sgx.trusted_files.libnsl = \"file:$(ARCH_LIBDIR)/libnsl.so.1\"\n"
"\n" + + "sgx.trusted_files.libnssmyhostname = \"file:$(ARCH_LIBDIR)/libnss_myhostname.so.2\"\n"
"sgx.trusted_files.libstdc = \"file:/usr/$(ARCH_LIBDIR)/libstdc++.so.6\"\n" + + "sgx.trusted_files.libnssmdns = \"file:$(ARCH_LIBDIR)/libnss_mdns4_minimal.so.2\"\n"
"sgx.trusted_files.libgccs = \"file:$(ARCH_LIBDIR)/libgcc_s.so.1\"\n" + + "\n" + "# Scratch space\n" + "sgx.allowed_files.tmp = \"file:/tmp\"\n" + "\n"
"sgx.trusted_files.libaptpkg = \"file:/usr/$(ARCH_LIBDIR)/libapt-pkg.so.5.0\"\n" + + "# APT config files\n"
"sgx.trusted_files.liblz4 = \"file:/usr/$(ARCH_LIBDIR)/liblz4.so.1\"\n" + + "sgx.allowed_files.aptconfd = \"file:/etc/apt/apt.conf.d\"\n"
"sgx.trusted_files.libsystemd = \"file:$(ARCH_LIBDIR)/libsystemd.so.0\"\n" + + "sgx.allowed_files.aptconf = \"file:/etc/apt/apt.conf\"\n"
"sgx.trusted_files.libselinux = \"file:$(ARCH_LIBDIR)/libselinux.so.1\"\n" + + "sgx.allowed_files.apport = \"file:/etc/default/apport\"\n" + "\n"
"sgx.trusted_files.libgcrypt = \"file:$(ARCH_LIBDIR)/libgcrypt.so.20\"\n" + + "# Name Service Switch (NSS) files (Glibc reads these files)\n"
"sgx.trusted_files.libpcre = \"file:$(ARCH_LIBDIR)/libpcre.so.3\"\n" + + "sgx.allowed_files.nsswitch = \"file:/etc/nsswitch.conf\"\n"
"sgx.trusted_files.libgpgerror = \"file:$(ARCH_LIBDIR)/libgpg-error.so.0\"\n" + + "sgx.allowed_files.group = \"file:/etc/group\"\n"
"sgx.trusted_files.libexpat = \"file:$(ARCH_LIBDIR)/libexpat.so.1\"\n" + + "sgx.allowed_files.passwd = \"file:/etc/passwd\"\n" + "\n"
"sgx.trusted_files.libz = \"file:$(ARCH_LIBDIR)/libz.so.1\"\n" + + "# DNS hostname resolution files (Glibc reads these files)\n"
"sgx.trusted_files.libz2 = \"file:$(ARCH_LIBDIR)/libbz2.so.1.0\"\n" + + "sgx.allowed_files.hostconf = \"file:/etc/host.conf\"\n"
"sgx.trusted_files.liblzma = \"file:$(ARCH_LIBDIR)/liblzma.so.5\"\n" + + "sgx.allowed_files.hosts = \"file:/etc/hosts\"\n"
"sgx.trusted_files.libmpdec = \"file:/usr/$(ARCH_LIBDIR)/libmpdec.so.2\"\n" + + "sgx.allowed_files.gaiconf = \"file:/etc/gai.conf\"\n"
"\n" + + "sgx.allowed_files.resolv = \"file:/etc/resolv.conf\"\n" + "\n"
"# Name Service Switch (NSS) libraries (Glibc dependencies)\n" + + "sgx.allowed_files.openssl = \"file:/etc/ssl/openssl.cnf\"\n" + "\n"
"sgx.trusted_files.libnssfiles = \"file:$(ARCH_LIBDIR)/libnss_files.so.2\"\n" + + "# System's file system table\n"
"sgx.trusted_files.libnsscompat = \"file:$(ARCH_LIBDIR)/libnss_compat.so.2\"\n" + + "sgx.allowed_files.fstab = \"file:/etc/fstab\"\n" + "\n"
"sgx.trusted_files.libnssnis = \"file:$(ARCH_LIBDIR)/libnss_nis.so.2\"\n" + + "$(NODEJS_TRUSTED_LIBS)\n" + "\n" + "# JavaScript (trusted)\n"
"sgx.trusted_files.libnsl = \"file:$(ARCH_LIBDIR)/libnsl.so.1\"\n" + + "sgx.allowed_files.smlib = \"file:node_modules\"\n"
"sgx.trusted_files.libnssmyhostname = \"file:$(ARCH_LIBDIR)/libnss_myhostname.so.2\"\n" + + "sgx.trusted_files.npminfo = \"file:package.json\"\n"
"sgx.trusted_files.libnssmdns = \"file:$(ARCH_LIBDIR)/libnss_mdns4_minimal.so.2\"\n" + + "sgx.trusted_files.contract = \"file:contract.js\"\n"
"\n" + + "sgx.trusted_files.globaljson = \"file:global.json\"\n"
"# Scratch space\n" + + "sgx.trusted_files.argjson = \"file:arg.json\"\n" + "\n"
"sgx.allowed_files.tmp = \"file:/tmp\"\n" + + "sys.insecure__allow_eventfd = 1\n" + "\n" + "sgx.remote_attestation = 1\n" + "\n"
"\n" + + "loader.env.LD_PRELOAD = \"libsecret_prov_attest.so\"\n"
"# APT config files\n" + + "loader.env.SECRET_PROVISION_CONSTRUCTOR = \"1\"\n"
"sgx.allowed_files.aptconfd = \"file:/etc/apt/apt.conf.d\"\n" + + "loader.env.SECRET_PROVISION_SET_PF_KEY = \"1\"\n"
"sgx.allowed_files.aptconf = \"file:/etc/apt/apt.conf\"\n" + + "loader.env.SECRET_PROVISION_CA_CHAIN_PATH = \"certs/test-ca-sha256.crt\"\n"
"sgx.allowed_files.apport = \"file:/etc/default/apport\"\n" + + "loader.env.SECRET_PROVISION_SERVERS = \"localhost:4433\"\n" + "\n"
"\n" + + "sgx.trusted_files.libsecretprovattest = \"file:libsecret_prov_attest.so\"\n"
"# Name Service Switch (NSS) files (Glibc reads these files)\n" + + "sgx.trusted_files.cachain = \"file:certs/test-ca-sha256.crt\"\n" + "\n"
"sgx.allowed_files.nsswitch = \"file:/etc/nsswitch.conf\"\n" + + "# Specify your SPID and linkable/unlinkable attestation policy\n"
"sgx.allowed_files.group = \"file:/etc/group\"\n" + + "sgx.ra_client_spid = \"DF3A8BA098E93F66CC64E8A215E98333\"\n"
"sgx.allowed_files.passwd = \"file:/etc/passwd\"\n" + + "sgx.ra_client_linkable = 0\n";
"\n" +
"# DNS hostname resolution files (Glibc reads these files)\n" +
"sgx.allowed_files.hostconf = \"file:/etc/host.conf\"\n" +
"sgx.allowed_files.hosts = \"file:/etc/hosts\"\n" +
"sgx.allowed_files.gaiconf = \"file:/etc/gai.conf\"\n" +
"sgx.allowed_files.resolv = \"file:/etc/resolv.conf\"\n" +
"\n" +
"sgx.allowed_files.openssl = \"file:/etc/ssl/openssl.cnf\"\n" +
"\n" +
"# System's file system table\n" +
"sgx.allowed_files.fstab = \"file:/etc/fstab\"\n" +
"\n" +
"$(NODEJS_TRUSTED_LIBS)\n" +
"\n" +
"# JavaScript (trusted)\n" +
"sgx.allowed_files.smlib = \"file:node_modules\"\n" +
"sgx.trusted_files.npminfo = \"file:package.json\"\n" +
"sgx.trusted_files.contract = \"file:contract.js\"\n" +
"sgx.trusted_files.globaljson = \"file:global.json\"\n" +
"sgx.trusted_files.argjson = \"file:arg.json\"\n" +
"\n" +
"sys.insecure__allow_eventfd = 1\n" +
"\n" +
"sgx.remote_attestation = 1\n" +
"\n" +
"loader.env.LD_PRELOAD = \"libsecret_prov_attest.so\"\n" +
"loader.env.SECRET_PROVISION_CONSTRUCTOR = \"1\"\n" +
"loader.env.SECRET_PROVISION_SET_PF_KEY = \"1\"\n" +
"loader.env.SECRET_PROVISION_CA_CHAIN_PATH = \"certs/test-ca-sha256.crt\"\n" +
"loader.env.SECRET_PROVISION_SERVERS = \"localhost:4433\"\n" +
"\n" +
"sgx.trusted_files.libsecretprovattest = \"file:libsecret_prov_attest.so\"\n" +
"sgx.trusted_files.cachain = \"file:certs/test-ca-sha256.crt\"\n" +
"\n" +
"# Specify your SPID and linkable/unlinkable attestation policy\n" +
"sgx.ra_client_spid = \"DF3A8BA098E93F66CC64E8A215E98333\"\n" +
"sgx.ra_client_linkable = 0\n";
// add secret servers // add secret servers
manifestStr += "loader.env.SECRET_PROVISION_CC_SERVERS = "; manifestStr += "loader.env.SECRET_PROVISION_CC_SERVERS = ";
Object resultStr = engine.invokeFunction( Object resultStr = engine.invokeFunction("getAllSecret", "", input.getRequester(),
"getAllSecret",
"",
input.getRequester(),
input.getRequesterDOI()); input.getRequesterDOI());
Map<String, String> resultMap = JsonUtil.fromJson(resultStr.toString(), MapType); Map<String, String> resultMap = JsonUtil.fromJson(resultStr.toString(), MapType);
Map<String, String> serverMap = JsonUtil.fromJson(resultMap.get("result"), MapType); Map<String, String> serverMap = JsonUtil.fromJson(resultMap.get("result"), MapType);

View File

@ -1,6 +1,5 @@
package org.bdware.sc.engine; package org.bdware.sc.engine;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -139,11 +138,7 @@ public class DesktopEngine extends JSEngine {
ccl = (ccl == null) ? NashornScriptEngineFactory.class.getClassLoader() : ccl; ccl = (ccl == null) ? NashornScriptEngineFactory.class.getClassLoader() : ccl;
String[] args = new String[] {"--loader-per-compile=false", "-strict=false"}; String[] args = new String[] {"--loader-per-compile=false", "-strict=false"};
classLoader = new YJSClassLoader(ccl, new YJSFilter()); classLoader = new YJSClassLoader(ccl, new YJSFilter());
engine = engine = (NashornScriptEngine) new NashornScriptEngineFactory().getScriptEngine(args, // "--print-ast",
(NashornScriptEngine)
new NashornScriptEngineFactory()
.getScriptEngine(
args, // "--print-ast",
// "true", // "true",
// "-d=/Users/huaqiancai/Downloads/dumpedClz", // "-d=/Users/huaqiancai/Downloads/dumpedClz",
// "--trace-callsites=enterexit" // "--trace-callsites=enterexit"
@ -157,17 +152,12 @@ public class DesktopEngine extends JSEngine {
// engine = (NashornScriptEngine) new // engine = (NashornScriptEngine) new
// NashornScriptEngineFactory().getScriptEngine(new YJSFilter()); // NashornScriptEngineFactory().getScriptEngine(new YJSFilter());
if (_with_init_script) { if (_with_init_script) {
InputStream in = InputStream in = DesktopEngine.class.getClassLoader()
DesktopEngine.class
.getClassLoader()
.getResourceAsStream("org/bdware/sc/engine/yancloud_desktop.js"); .getResourceAsStream("org/bdware/sc/engine/yancloud_desktop.js");
assert in != null; assert in != null;
InputStreamReader streamReader = new InputStreamReader(in); InputStreamReader streamReader = new InputStreamReader(in);
engine.getContext() engine.getContext().setAttribute(ScriptEngine.FILENAME,
.setAttribute( "org/bdware/sc/engine/yancloud_desktop.js", ScriptContext.ENGINE_SCOPE);
ScriptEngine.FILENAME,
"org/bdware/sc/engine/yancloud_desktop.js",
ScriptContext.ENGINE_SCOPE);
engine.eval(streamReader); engine.eval(streamReader);
} }
global = engine.getNashornGlobal(); global = engine.getNashornGlobal();
@ -195,10 +185,7 @@ public class DesktopEngine extends JSEngine {
yancloud_desktop.append(UtilRegistry.getInitStr(str, false)); yancloud_desktop.append(UtilRegistry.getInitStr(str, false));
} }
// LOGGER.debug("[initScript] " + yancloud_desktop); // LOGGER.debug("[initScript] " + yancloud_desktop);
engine.getContext() engine.getContext().setAttribute(ScriptEngine.FILENAME, yancloud_desktop.toString(),
.setAttribute(
ScriptEngine.FILENAME,
yancloud_desktop.toString(),
ScriptContext.ENGINE_SCOPE); ScriptContext.ENGINE_SCOPE);
engine.eval(yancloud_desktop.toString()); engine.eval(yancloud_desktop.toString());
} catch (ScriptException e) { } catch (ScriptException e) {
@ -252,11 +239,11 @@ public class DesktopEngine extends JSEngine {
} }
@Override @Override
public ContractResult loadContract( public ContractResult loadContract(Contract contract, ContractNode contractNode,
Contract contract, ContractNode contractNode, boolean isInsnLimit) { boolean isInsnLimit) {
cn = contractNode; cn = contractNode;
engine.getContext() engine.getContext().setAttribute(ScriptEngine.FILENAME, ScriptFileName,
.setAttribute(ScriptEngine.FILENAME, ScriptFileName, ScriptContext.ENGINE_SCOPE); ScriptContext.ENGINE_SCOPE);
try { try {
setPermission(cn.getPermission()); setPermission(cn.getPermission());
} catch (Exception e) { } catch (Exception e) {
@ -266,10 +253,7 @@ public class DesktopEngine extends JSEngine {
for (FunctionNode fun : contractNode.getFunctions()) for (FunctionNode fun : contractNode.getFunctions())
try { try {
String str = fun.plainText(); String str = fun.plainText();
engine.getContext() engine.getContext().setAttribute(ScriptEngine.FILENAME, fun.getFileName(),
.setAttribute(
ScriptEngine.FILENAME,
fun.getFileName(),
ScriptContext.ENGINE_SCOPE); ScriptContext.ENGINE_SCOPE);
compileFunction(fun, str, isInsnLimit); compileFunction(fun, str, isInsnLimit);
} catch (ScriptException e) { } catch (ScriptException e) {
@ -280,7 +264,8 @@ public class DesktopEngine extends JSEngine {
e.printStackTrace(); e.printStackTrace();
return new ContractResult(Status.Error, new JsonPrimitive(bo.toString())); return new ContractResult(Status.Error, new JsonPrimitive(bo.toString()));
} }
LOGGER.debug(JsonUtil.toJson(contractNode.events) + "\n\t" + JsonUtil.toJson(contractNode.logs)); LOGGER.debug(
JsonUtil.toJson(contractNode.events) + "\n\t" + JsonUtil.toJson(contractNode.logs));
for (String topic : contractNode.events.keySet()) { for (String topic : contractNode.events.keySet()) {
compileEventFunction(topic, topic, contractNode.events.get(topic)); compileEventFunction(topic, topic, contractNode.events.get(topic));
} }
@ -311,20 +296,16 @@ public class DesktopEngine extends JSEngine {
try { try {
String str; String str;
if (REventSemantics.AT_LEAST_ONCE.equals(semantics)) { if (REventSemantics.AT_LEAST_ONCE.equals(semantics)) {
str = str = String.format("function %s(arg) { YancloudUtil.pubEvent(\"%s\", arg); }",
String.format(
"function %s(arg) { YancloudUtil.pubEvent(\"%s\", arg); }",
name, topic); name, topic);
} else { } else {
str = str = String.format(
String.format(
"function %s(arg) { YancloudUtil.pubEventConstraint(\"%s\", arg, \"%s\"); }", "function %s(arg) { YancloudUtil.pubEventConstraint(\"%s\", arg, \"%s\"); }",
name, topic, semantics.name()); name, topic, semantics.name());
} }
compileFunction(null, str, false); compileFunction(null, str, false);
LOGGER.debug("compile function " + name + " success!"); LOGGER.debug("compile function " + name + " success!");
str = str = String.format(
String.format(
"function %ss(arg0, arg1) { YancloudUtil.pubEventConstraint(\"%s\", arg0, arg1); }", "function %ss(arg0, arg1) { YancloudUtil.pubEventConstraint(\"%s\", arg0, arg1); }",
name, topic); name, topic);
compileFunction(null, str, false); compileFunction(null, str, false);
@ -406,7 +387,8 @@ public class DesktopEngine extends JSEngine {
// //
// return new ContractResult(Status.Success, new JsonPrimitive("")); // return new ContractResult(Status.Success, new JsonPrimitive(""));
// } // }
private void compileFunction(FunctionNode functionNode, ScriptObjectMirror sf, boolean instrumentBranch) { private void compileFunction(FunctionNode functionNode, ScriptObjectMirror sf,
boolean instrumentBranch) {
Global oldGlobal = Context.getGlobal(); Global oldGlobal = Context.getGlobal();
boolean globalChanged = (oldGlobal != global); boolean globalChanged = (oldGlobal != global);
try { try {
@ -423,7 +405,8 @@ public class DesktopEngine extends JSEngine {
f.setAccessible(true); f.setAccessible(true);
ScriptFunctionData scriptFunctioNData = (ScriptFunctionData) f.get(scriptFunction); ScriptFunctionData scriptFunctioNData = (ScriptFunctionData) f.get(scriptFunction);
Object scope = scriptFunction.getScope(); Object scope = scriptFunction.getScope();
Method getGeneric = ScriptFunctionData.class.getDeclaredMethod("getGenericInvoker", ScriptObject.class); Method getGeneric = ScriptFunctionData.class.getDeclaredMethod("getGenericInvoker",
ScriptObject.class);
getGeneric.setAccessible(true); getGeneric.setAccessible(true);
MethodHandle methodHandle = (MethodHandle) getGeneric.invoke(scriptFunctioNData, scope); MethodHandle methodHandle = (MethodHandle) getGeneric.invoke(scriptFunctioNData, scope);
if (methodHandle.getClass() != Class.forName("java.lang.invoke.DirectMethodHandle")) { if (methodHandle.getClass() != Class.forName("java.lang.invoke.DirectMethodHandle")) {
@ -446,12 +429,14 @@ public class DesktopEngine extends JSEngine {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (globalChanged) Context.setGlobal(oldGlobal); if (globalChanged)
Context.setGlobal(oldGlobal);
Context.TRACEIF = false; Context.TRACEIF = false;
} }
} }
public void compileFunction(FunctionNode functionNode, String snippet, boolean instrumentBranch) throws ScriptException { public void compileFunction(FunctionNode functionNode, String snippet, boolean instrumentBranch)
throws ScriptException {
compileFunction(functionNode, (ScriptObjectMirror) engine.eval(snippet), instrumentBranch); compileFunction(functionNode, (ScriptObjectMirror) engine.eval(snippet), instrumentBranch);
} }
@ -481,8 +466,7 @@ public class DesktopEngine extends JSEngine {
JavaScriptEntry.msgList = new ArrayList<>(); JavaScriptEntry.msgList = new ArrayList<>();
FunctionNode fun = cn.getFunction(input.getAction()); FunctionNode fun = cn.getFunction(input.getAction());
if (fun == null) { if (fun == null) {
return new ContractResult( return new ContractResult(Status.Exception,
Status.Exception,
new JsonPrimitive("Action " + input.getAction() + " is not exists")); new JsonPrimitive("Action " + input.getAction() + " is not exists"));
} }
ProgramPointCounter ppc = null; ProgramPointCounter ppc = null;
@ -499,23 +483,14 @@ public class DesktopEngine extends JSEngine {
HashMap<String, Long> ppCountMap = evaluatesAnalysis(input.getAction(), functions); HashMap<String, Long> ppCountMap = evaluatesAnalysis(input.getAction(), functions);
Long extraGas = getExtraGas(fun.getCost().getExtraGas(), input); Long extraGas = getExtraGas(fun.getCost().getExtraGas(), input);
bo = new ByteArrayOutputStream(); bo = new ByteArrayOutputStream();
ppc = ppc = new ProgramPointCounter(bo, previous.getCp(), Long.MAX_VALUE, functionIndex,
new ProgramPointCounter( input.getGasLimit(), extraGas, input.getAction(), ppCountMap);
bo,
previous.getCp(),
Long.MAX_VALUE,
functionIndex,
input.getGasLimit(),
extraGas,
input.getAction(),
ppCountMap);
this.redirectTracePS(ppc); this.redirectTracePS(ppc);
} }
if (fun.isExport() || if (fun.isExport() ||
// if the function has been registered as event handler // if the function has been registered as event handler
(fun.isHandler() && (fun.isHandler() && null != input.getRequester()
null != input.getRequester() && && input.getRequester().startsWith("event"))) {
input.getRequester().startsWith("event"))) {
Object ret; Object ret;
if (fun.isView()) { if (fun.isView()) {
ret = executeWithoutLock(fun, input, null); ret = executeWithoutLock(fun, input, null);
@ -525,8 +500,10 @@ public class DesktopEngine extends JSEngine {
} }
} }
//System.out.println("[DesktopEngine MaskConfig]"+ContractProcess.instance.getProjectConfig().getMaskConfig().config.toString()); // System.out.println("[DesktopEngine
ContractResult contractRes = new ContractResult(Status.Success, JSONTool.convertMirrorToJson(ret)); // MaskConfig]"+ContractProcess.instance.getProjectConfig().getMaskConfig().config.toString());
ContractResult contractRes =
new ContractResult(Status.Success, JSONTool.convertMirrorToJson(ret));
if (ppc != null) { if (ppc != null) {
contractRes.extraGas = ppc.extraGas; contractRes.extraGas = ppc.extraGas;
contractRes.executionGas = ppc.cost; contractRes.executionGas = ppc.cost;
@ -568,16 +545,13 @@ public class DesktopEngine extends JSEngine {
} else { } else {
// return new ContractResult(Status.Exception, "Action " + input.getAction() + " // return new ContractResult(Status.Exception, "Action " + input.getAction() + "
// is not exported!"); // is not exported!");
return new ContractResult( return new ContractResult(Status.Exception,
Status.Exception,
new JsonPrimitive("Action " + input.getAction() + " is not exported!")); new JsonPrimitive("Action " + input.getAction() + " is not exported!"));
} }
} catch (ScriptReturnException e) { } catch (ScriptReturnException e) {
e.printStackTrace(); e.printStackTrace();
return new ContractResult( return new ContractResult(Status.Exception, e.message);
Status.Exception,
e.message);
} catch (ScriptException e) { } catch (ScriptException e) {
Throwable cause = e.getCause(); Throwable cause = e.getCause();
e.printStackTrace(); e.printStackTrace();
@ -588,23 +562,22 @@ public class DesktopEngine extends JSEngine {
e.printStackTrace(ps); e.printStackTrace(ps);
e.printStackTrace(); e.printStackTrace();
if (e.getCause() != null && e.getCause() instanceof ScriptException) { if (e.getCause() != null && e.getCause() instanceof ScriptException) {
return new ContractResult( return new ContractResult(Status.Exception, new JsonPrimitive(
Status.Exception,
new JsonPrimitive(
extractException(bo1.toString(), extract(cn, e.getCause())))); extractException(bo1.toString(), extract(cn, e.getCause()))));
} else { } else {
return new ContractResult( return new ContractResult(Status.Exception,
Status.Exception,
new JsonPrimitive(extractException(bo1.toString(), extract(cn, e)))); new JsonPrimitive(extractException(bo1.toString(), extract(cn, e))));
} }
} finally { } finally {
this.redirectTracePS(previous); this.redirectTracePS(previous);
if (globalChanged) Context.setGlobal(oldGlobal); if (globalChanged)
Context.setGlobal(oldGlobal);
} }
} }
public Object executeWithoutLock(FunctionNode fun, ContractRequest input, Object injectedArg) throws ScriptException, NoSuchMethodException { public Object executeWithoutLock(FunctionNode fun, ContractRequest input, Object injectedArg)
throws ScriptException, NoSuchMethodException {
// long start = System.currentTimeMillis(); // long start = System.currentTimeMillis();
ArgPacks argPacks = new ArgPacks(input, input.getArg(), null); ArgPacks argPacks = new ArgPacks(input, input.getArg(), null);
if (injectedArg != null) { if (injectedArg != null) {
@ -616,14 +589,10 @@ public class DesktopEngine extends JSEngine {
// actually invoke! // actually invoke!
if (argPacks.ret == null) { if (argPacks.ret == null) {
argPacks.ret = argPacks.ret = engine.invokeFunction(input.getAction(),
engine.invokeFunction( (fun.isHandler() ? JsonUtil.fromJson(input.getArg(), Event.class)
input.getAction(),
(fun.isHandler()
? JsonUtil.fromJson(input.getArg(), Event.class)
: JSONTool.convertJsonElementToMirror(argPacks.arg)), : JSONTool.convertJsonElementToMirror(argPacks.arg)),
input.getRequester(), input.getRequester(), input.getRequesterDOI());
input.getRequesterDOI());
} }
for (AnnotationHook handler : fun.afterExecutionAnnotations()) { for (AnnotationHook handler : fun.afterExecutionAnnotations()) {
@ -661,8 +630,7 @@ public class DesktopEngine extends JSEngine {
for (String function : functions) { for (String function : functions) {
MethodNode mn = methods.get(function); MethodNode mn = methods.get(function);
if (mn != null) { if (mn != null) {
CFGraph cfg = CFGraph cfg = new CFGraph(mn) {
new CFGraph(mn) {
@Override @Override
public BasicBlock getBasicBlock(int id) { public BasicBlock getBasicBlock(int id) {
return new BasicBlock(id); return new BasicBlock(id);
@ -686,15 +654,15 @@ public class DesktopEngine extends JSEngine {
flag++; flag++;
} }
} }
/* for (Map.Entry<String, Long> map : PPCount.functionSumGas.entrySet()) { /*
if (map.getKey().contains(getFunction) && map.getKey().contains("true")) { * for (Map.Entry<String, Long> map : PPCount.functionSumGas.entrySet()) { if
System.out.println("[合约方法pub中条件循环为true时]" + map.getValue()); * (map.getKey().contains(getFunction) && map.getKey().contains("true")) {
} else if (map.getKey().contains(getFunction) && map.getKey().contains("false")) { * System.out.println("[合约方法pub中条件循环为true时]" + map.getValue()); } else if
System.out.println("[合约方法pub中条件循环为false时]" + map.getValue()); * (map.getKey().contains(getFunction) && map.getKey().contains("false")) {
} else if (map.getKey().contains(getFunction)) { * System.out.println("[合约方法pub中条件循环为false时]" + map.getValue()); } else if
System.out.println("[合约方法pub中其他语句消耗]" + map.getValue()); * (map.getKey().contains(getFunction)) { System.out.println("[合约方法pub中其他语句消耗]" +
} * map.getValue()); } }
}*/ */
return ppCountMap; return ppCountMap;
} }
@ -704,11 +672,7 @@ public class DesktopEngine extends JSEngine {
return 0L; return 0L;
} }
Invocable cal = engine; Invocable cal = engine;
Object ret = Object ret = cal.invokeFunction(costFunction, input.getArg(), input.getRequester(),
cal.invokeFunction(
costFunction,
input.getArg(),
input.getRequester(),
input.getRequesterDOI()); input.getRequesterDOI());
if (ret != null && StringUtils.isNumeric(ret.toString())) { if (ret != null && StringUtils.isNumeric(ret.toString())) {
return Long.parseLong(ret.toString()); return Long.parseLong(ret.toString());
@ -765,15 +729,16 @@ public class DesktopEngine extends JSEngine {
if (actLine != -1) { if (actLine != -1) {
actLine += line - 1; actLine += line - 1;
} }
message = message = message.replaceAll("at line number " + e.getLineNumber(),
message.replaceAll( "at line number " + (actLine));
"at line number " + e.getLineNumber(), "at line number " + (actLine));
if (fun.getFileName() != null) if (fun.getFileName() != null)
message = message.replace("in contract_main.yjs", "in " + fun.getFileName()); message = message.replace("in contract_main.yjs", "in " + fun.getFileName());
content.append(message); content.append(message);
content.append("("); content.append("(");
if (fun.functionName != null) content.append(fun.functionName); if (fun.functionName != null)
else content.append("contract_main.yjs"); content.append(fun.functionName);
else
content.append("contract_main.yjs");
content.append(":"); content.append(":");
content.append(actLine); content.append(actLine);
@ -792,16 +757,14 @@ public class DesktopEngine extends JSEngine {
String methodName = element.getMethodName(); String methodName = element.getMethodName();
String fileName = element.getFileName(); String fileName = element.getFileName();
if (fileName.endsWith(".java")) continue; if (fileName.endsWith(".java"))
continue;
if (c.isBundle()) { if (c.isBundle()) {
fileName = fixFile(c, methodName); fileName = fixFile(c, methodName);
} }
if (fileName.equals("--")) continue; if (fileName.equals("--"))
ret.add( continue;
String.format( ret.add(String.format("at %s(%s:%d)", methodName, fileName,
"at %s(%s:%d)",
methodName,
fileName,
(fixLine(c, methodName) + element.getLineNumber()))); (fixLine(c, methodName) + element.getLineNumber())));
} }
return ret; return ret;
@ -918,13 +881,13 @@ public class DesktopEngine extends JSEngine {
} }
if (entry.getName().endsWith(".so") || entry.getName().endsWith(".so.1")) { if (entry.getName().endsWith(".so") || entry.getName().endsWith(".so.1")) {
System.out.println("unzip library:" + entry.getName().replaceAll(".*/", "")); System.out.println("unzip library:" + entry.getName().replaceAll(".*/", ""));
loader.unzipLibrary( loader.unzipLibrary(zf.getInputStream(entry),
zf.getInputStream(entry), entry.getName().replaceAll(".*/", "")); entry.getName().replaceAll(".*/", ""));
} }
if (HardwareInfo.type == OSType.mac && entry.getName().endsWith(".dylib")) { if (HardwareInfo.type == OSType.mac && entry.getName().endsWith(".dylib")) {
System.out.println("unzip library:" + entry.getName().replaceAll(".*/", "")); System.out.println("unzip library:" + entry.getName().replaceAll(".*/", ""));
loader.unzipLibrary( loader.unzipLibrary(zf.getInputStream(entry),
zf.getInputStream(entry), entry.getName().replaceAll(".*/", "")); entry.getName().replaceAll(".*/", ""));
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -50,11 +50,14 @@ public class JSONTool {
} }
private static JsonElement convertMirrorToJsonInternal(Object obj, Set<Object> recorded) { private static JsonElement convertMirrorToJsonInternal(Object obj, Set<Object> recorded) {
if (recorded.contains(obj)) return JsonNull.INSTANCE; if (recorded.contains(obj))
if (obj == null) return JsonNull.INSTANCE; return JsonNull.INSTANCE;
if (obj == null)
return JsonNull.INSTANCE;
if (obj.getClass() == wrp.jdk.nashorn.internal.runtime.Undefined.class) if (obj.getClass() == wrp.jdk.nashorn.internal.runtime.Undefined.class)
return JsonNull.INSTANCE; return JsonNull.INSTANCE;
if (obj instanceof JsonElement) return (JsonElement) obj; if (obj instanceof JsonElement)
return (JsonElement) obj;
if (obj.getClass().isArray()) { if (obj.getClass().isArray()) {
Object[] arr = (Object[]) obj; Object[] arr = (Object[]) obj;
recorded.add(obj); recorded.add(obj);

View File

@ -128,17 +128,18 @@ public class SyncMechUtil {
} }
/* /*
* memory的操作 * memory的操作 无需startFlag就可以使用memory的操作
* 无需startFlag就可以使用memory的操作
*/ */
public synchronized String dumpMemory(String path) { public synchronized String dumpMemory(String path) {
if (memoryDumpUtil == null) memoryDumpUtil = new MemoryDumpUtil(engine.engine); if (memoryDumpUtil == null)
memoryDumpUtil = new MemoryDumpUtil(engine.engine);
return memoryDumpUtil.dumpMemory(path, true); return memoryDumpUtil.dumpMemory(path, true);
} }
public synchronized String dumpMemory(String path, boolean stateful) { public synchronized String dumpMemory(String path, boolean stateful) {
LOGGER.info("dumpMemroy : stateful=" + stateful); LOGGER.info("dumpMemroy : stateful=" + stateful);
if (memoryDumpUtil == null) memoryDumpUtil = new MemoryDumpUtil(engine.engine); if (memoryDumpUtil == null)
memoryDumpUtil = new MemoryDumpUtil(engine.engine);
return memoryDumpUtil.dumpMemory(path, stateful); return memoryDumpUtil.dumpMemory(path, stateful);
} }
@ -210,7 +211,8 @@ public class SyncMechUtil {
} }
public void changeCurrType(SyncType t) { public void changeCurrType(SyncType t) {
if (t == currType) return; if (t == currType)
return;
// finASyncRecord(); // finASyncRecord();
currType = t; currType = t;
@ -226,7 +228,8 @@ public class SyncMechUtil {
} }
break; break;
case Memory: case Memory:
if (memoryDumpUtil == null) memoryDumpUtil = new MemoryDumpUtil(engine.engine); if (memoryDumpUtil == null)
memoryDumpUtil = new MemoryDumpUtil(engine.engine);
break; break;
default: default:
break; break;
@ -256,7 +259,8 @@ public class SyncMechUtil {
* Trans操作 * Trans操作
*/ */
public synchronized String redo(String path) { public synchronized String redo(String path) {
if (transRecoverUtil == null) transRecoverUtil = new TransRecoverUtil(engine); if (transRecoverUtil == null)
transRecoverUtil = new TransRecoverUtil(engine);
// 先清空否则会重复执行一些trans // 先清空否则会重复执行一些trans
if (transRecoverUtil.transRecords != null && !transRecoverUtil.transRecords.isEmpty()) if (transRecoverUtil.transRecords != null && !transRecoverUtil.transRecords.isEmpty())
@ -264,7 +268,8 @@ public class SyncMechUtil {
// 某一次检查点之后没有transRecords // 某一次检查点之后没有transRecords
File file = new File(path); File file = new File(path);
if (!file.exists()) return "success"; if (!file.exists())
return "success";
transRecoverUtil.setTraceRecords(path); transRecoverUtil.setTraceRecords(path);
transRecoverUtil.recoverFromTransRecord(); transRecoverUtil.recoverFromTransRecord();

View File

@ -6,9 +6,8 @@ import javax.script.ScriptEngine;
public class TestClassFilter { public class TestClassFilter {
public TestClassFilter() { public TestClassFilter() {
final String script = "print(java.lang.System.getProperty(\"java.home\"));" + final String script = "print(java.lang.System.getProperty(\"java.home\"));"
"print(\"Create file variable\");" + + "print(\"Create file variable\");" + "var File = Java.type(\"java.io.File\");";
"var File = Java.type(\"java.io.File\");";
NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new YJSFilter()); ScriptEngine engine = factory.getScriptEngine(new YJSFilter());
try { try {

View File

@ -63,7 +63,8 @@ public class YJSClassLoader extends URLClassLoader {
public String unzipLibrary(InputStream inputStream, String name) { public String unzipLibrary(InputStream inputStream, String name) {
try { try {
if (libDir == null) { if (libDir == null) {
libDir = new File(System.getProperty("java.io.tmpdir"), "yjscontract_" + System.currentTimeMillis()); libDir = new File(System.getProperty("java.io.tmpdir"),
"yjscontract_" + System.currentTimeMillis());
libDir.mkdirs(); libDir.mkdirs();
} }
File f = new File(libDir, name); File f = new File(libDir, name);

View File

@ -43,19 +43,22 @@ public class AccessHandler implements AnnotationHook {
public ArgPacks handle(JSEngine desktopEngine, ArgPacks argPacks) { public ArgPacks handle(JSEngine desktopEngine, ArgPacks argPacks) {
if (requireSign) { if (requireSign) {
if (!argPacks.request.verifySignature()) { if (!argPacks.request.verifySignature()) {
throw new ScriptReturnException(JsonParser.parseString("{\"code\":400,\"msg\":\"permission denied\"}")); throw new ScriptReturnException(
JsonParser.parseString("{\"code\":400,\"msg\":\"permission denied\"}"));
} }
return argPacks; return argPacks;
} }
if (!argPacks.request.verifySignature()) { if (!argPacks.request.verifySignature()) {
LOGGER.info("verify failed! clear requester," + argPacks.request.getContentStr() + LOGGER.info("verify failed! clear requester," + argPacks.request.getContentStr()
" -> " + argPacks.request.getPublicKey() + "sign:" + argPacks.request.getSignature()); + " -> " + argPacks.request.getPublicKey() + "sign:"
+ argPacks.request.getSignature());
// TODO // TODO
// FIXME here! // FIXME here!
// argPacks.request.setRequester(null); // argPacks.request.setRequester(null);
} else } else
LOGGER.info("verify success!" + argPacks.request.getRequester()); LOGGER.info("verify success!" + argPacks.request.getRequester());
if (acFunction == null) return argPacks; if (acFunction == null)
return argPacks;
DesktopEngine de = (DesktopEngine) desktopEngine; DesktopEngine de = (DesktopEngine) desktopEngine;
try { try {
ContractRequest input = argPacks.request; ContractRequest input = argPacks.request;

View File

@ -28,7 +28,8 @@ public class ArgSchemaHandler implements AnnotationHook {
// } // }
} }
public static ArgSchemaHandler fromAnnotationNode(FunctionNode funNode, AnnotationNode annoNode) { public static ArgSchemaHandler fromAnnotationNode(FunctionNode funNode,
AnnotationNode annoNode) {
return new ArgSchemaHandler(annoNode); return new ArgSchemaHandler(annoNode);
} }

View File

@ -89,7 +89,8 @@ public class ArgSchemaVisitor extends JsonVisitor {
if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isString()) { if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isString()) {
return this; return this;
} else { } else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be string"; message = "[Type error] The value ("
+ root.getAsJsonPrimitive().getAsString() + ") should be string";
status = false; status = false;
errorCode = 1001; errorCode = 1001;
return this; return this;
@ -98,7 +99,8 @@ public class ArgSchemaVisitor extends JsonVisitor {
if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isNumber()) { if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isNumber()) {
return this; return this;
} else { } else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be number"; message = "[Type error] The value ("
+ root.getAsJsonPrimitive().getAsString() + ") should be number";
status = false; status = false;
errorCode = 1001; errorCode = 1001;
return this; return this;
@ -107,7 +109,8 @@ public class ArgSchemaVisitor extends JsonVisitor {
if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isBoolean()) { if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isBoolean()) {
return this; return this;
} else { } else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be boolean"; message = "[Type error] The value ("
+ root.getAsJsonPrimitive().getAsString() + ") should be boolean";
status = false; status = false;
errorCode = 1001; errorCode = 1001;
return this; return this;
@ -116,7 +119,8 @@ public class ArgSchemaVisitor extends JsonVisitor {
if (root.isJsonArray()) { if (root.isJsonArray()) {
return this; return this;
} else { } else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be array"; message = "[Type error] The value ("
+ root.getAsJsonPrimitive().getAsString() + ") should be array";
status = false; status = false;
errorCode = 1001; errorCode = 1001;
return this; return this;
@ -125,7 +129,8 @@ public class ArgSchemaVisitor extends JsonVisitor {
if (root.isJsonObject()) { if (root.isJsonObject()) {
return this; return this;
} else { } else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be object"; message = "[Type error] The value ("
+ root.getAsJsonPrimitive().getAsString() + ") should be object";
status = false; status = false;
errorCode = 1001; errorCode = 1001;
return this; return this;

View File

@ -23,8 +23,8 @@ public class ConfidentialHandler implements AnnotationHook {
DesktopEngine desktopEngine = (DesktopEngine) engine; DesktopEngine desktopEngine = (DesktopEngine) engine;
ConfidentialContractUtil.copyTemplateToDestination(input); ConfidentialContractUtil.copyTemplateToDestination(input);
ScriptObjectMirror globalVars = (ScriptObjectMirror) desktopEngine.get("Global"); ScriptObjectMirror globalVars = (ScriptObjectMirror) desktopEngine.get("Global");
ConfidentialContractUtil.dumpScriptAndStates( ConfidentialContractUtil.dumpScriptAndStates(desktopEngine.engine, fun, input,
desktopEngine.engine, fun, input, globalVars); globalVars);
// run in SGX instead of Nashorn if function has @Confidential annotation // run in SGX instead of Nashorn if function has @Confidential annotation
argPacks.ret = ConfidentialContractUtil.executeConfidentialContract(input); argPacks.ret = ConfidentialContractUtil.executeConfidentialContract(input);
return argPacks; return argPacks;

View File

@ -35,23 +35,27 @@ public class DOOPAfterExecHandler implements AnnotationHook {
// if http, directly return // if http, directly return
if (doipMessagePacker.source.equals("http")) { if (doipMessagePacker.source.equals("http")) {
if (argPacks.ret != null && argPacks.ret instanceof DoipMessage) { if (argPacks.ret != null && argPacks.ret instanceof DoipMessage) {
argPacks.ret = JsonUtil.parseObject(JsonDoipMessage.fromDoipMessage((DoipMessage) argPacks.ret)); argPacks.ret = JsonUtil.parseObject(
JsonDoipMessage.fromDoipMessage((DoipMessage) argPacks.ret));
} }
return argPacks; return argPacks;
} else { } else {
// pack // pack
if (!(argPacks.ret instanceof DoipMessage)) { if (!(argPacks.ret instanceof DoipMessage)) {
JsonObject jsonObjectRes = ((JsonElement) argPacks.ret).getAsJsonObject(); JsonObject jsonObjectRes = ((JsonElement) argPacks.ret).getAsJsonObject();
if (!jsonObjectRes.has("bodyBase64Encoded") || jsonObjectRes.get("bodyBase64Encoded").getAsBoolean() == false) { if (!jsonObjectRes.has("bodyBase64Encoded")
|| jsonObjectRes.get("bodyBase64Encoded").getAsBoolean() == false) {
if (jsonObjectRes.has("body")) { if (jsonObjectRes.has("body")) {
String body = jsonObjectRes.get("body").getAsString(); String body = jsonObjectRes.get("body").getAsString();
jsonObjectRes.addProperty("body", ByteUtil.encodeBASE64(body.getBytes(StandardCharsets.UTF_8))); jsonObjectRes.addProperty("body",
ByteUtil.encodeBASE64(body.getBytes(StandardCharsets.UTF_8)));
} }
} }
// validate json response // validate json response
ArgSchemaVisitor visitor = new ArgSchemaVisitor(jsonObjectRes); ArgSchemaVisitor visitor = new ArgSchemaVisitor(jsonObjectRes);
validateJsonElementRulesByArgSchemaVisitor(jsonResponseRules, visitor); validateJsonElementRulesByArgSchemaVisitor(jsonResponseRules, visitor);
JsonDoipMessage returnedMessage = JsonUtil.fromJson(jsonObjectRes, JsonDoipMessage.class); JsonDoipMessage returnedMessage =
JsonUtil.fromJson(jsonObjectRes, JsonDoipMessage.class);
argPacks.ret = returnedMessage.toResponseDoipMessage(originDoipMsg); argPacks.ret = returnedMessage.toResponseDoipMessage(originDoipMsg);
} }
return argPacks; return argPacks;
@ -71,7 +75,8 @@ public class DOOPAfterExecHandler implements AnnotationHook {
case Search: case Search:
case ListOps: case ListOps:
case Delete: case Delete:
return JsonParser.parseString("{\"header\":{\"response\":\"string\",\"attributes\":{}},\"body\":\"string\"}"); return JsonParser.parseString(
"{\"header\":{\"response\":\"string\",\"attributes\":{}},\"body\":\"string\"}");
case Extension: case Extension:
case Unknown: case Unknown:
default: default:
@ -80,17 +85,21 @@ public class DOOPAfterExecHandler implements AnnotationHook {
} }
// old convert jsonResponse from argPack's ret to Doip response in doip chain logic // old convert jsonResponse from argPack's ret to Doip response in doip chain logic
public DoipMessage convertJsonResponseToDoipMessage(FunctionNode fn, JsonElement jsonResponse, DoipMessage msg) { public DoipMessage convertJsonResponseToDoipMessage(FunctionNode fn, JsonElement jsonResponse,
DoipMessage msg) {
JsonObject jsonParams = jsonResponse.getAsJsonObject(); JsonObject jsonParams = jsonResponse.getAsJsonObject();
// validate json response // validate json response
ArgSchemaVisitor visitor = new ArgSchemaVisitor(jsonResponse); ArgSchemaVisitor visitor = new ArgSchemaVisitor(jsonResponse);
validateJsonElementRulesByArgSchemaVisitor(jsonResponseRules, visitor); validateJsonElementRulesByArgSchemaVisitor(jsonResponseRules, visitor);
JsonObject header = jsonParams.get("header") != null ? jsonParams.get("header").getAsJsonObject() : null; JsonObject header =
jsonParams.get("header") != null ? jsonParams.get("header").getAsJsonObject()
: null;
String body = jsonParams.get("body") != null ? jsonParams.get("body").getAsString() : null; String body = jsonParams.get("body") != null ? jsonParams.get("body").getAsString() : null;
if (header != null) { if (header != null) {
String headerRespCode = header.get("response") != null ? header.get("response").getAsString() : null; String headerRespCode =
header.get("response") != null ? header.get("response").getAsString() : null;
if (headerRespCode != null) { if (headerRespCode != null) {
for (DoipResponseCode responseCode : DoipResponseCode.values()) { for (DoipResponseCode responseCode : DoipResponseCode.values()) {
if (responseCode.toString().equals(headerRespCode)) { if (responseCode.toString().equals(headerRespCode)) {
@ -107,7 +116,8 @@ public class DOOPAfterExecHandler implements AnnotationHook {
return msg; return msg;
} }
public static void validateJsonElementRulesByArgSchemaVisitor(JsonElement jsonElement, ArgSchemaVisitor visitor) { public static void validateJsonElementRulesByArgSchemaVisitor(JsonElement jsonElement,
ArgSchemaVisitor visitor) {
visitor.visit(jsonElement); visitor.visit(jsonElement);
if (!visitor.getStatus()) { if (!visitor.getStatus()) {
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();

View File

@ -40,7 +40,8 @@ public class DOOPBeforeExecHandler implements AnnotationHook {
doipMsgPackerArg.rawDoipMsg = convertHttpRequestToDoipMessage(httpReq); doipMsgPackerArg.rawDoipMsg = convertHttpRequestToDoipMessage(httpReq);
if (httpReq.verifySignature()) { if (httpReq.verifySignature()) {
doipMsgPackerArg.rawDoipMsg.credential = new MessageCredential(httpReq.getRequester(), new byte[0]); doipMsgPackerArg.rawDoipMsg.credential =
new MessageCredential(httpReq.getRequester(), new byte[0]);
} else { } else {
doipMsgPackerArg.rawDoipMsg.credential = null; doipMsgPackerArg.rawDoipMsg.credential = null;
} }
@ -70,11 +71,14 @@ public class DOOPBeforeExecHandler implements AnnotationHook {
return JsonParser.parseString("{\"!header\":{\"!identifier\":\"string\"}}"); return JsonParser.parseString("{\"!header\":{\"!identifier\":\"string\"}}");
case Create: case Create:
case Update: case Update:
return JsonParser.parseString("{\"!header\":{\"!identifier\":\"string\"}, \"!body\":\"string\"}"); return JsonParser.parseString(
"{\"!header\":{\"!identifier\":\"string\"}, \"!body\":\"string\"}");
case Search: case Search:
return JsonParser.parseString("{\"!header\":{\"!identifier\":\"string\", \"!attributes\":{\"!query\":\"string\", \"!pageNum\":\"int\", \"!pageSize\":\"int\", \"!type\":\"string\"}}}"); return JsonParser.parseString(
"{\"!header\":{\"!identifier\":\"string\", \"!attributes\":{\"!query\":\"string\", \"!pageNum\":\"int\", \"!pageSize\":\"int\", \"!type\":\"string\"}}}");
case Retrieve: case Retrieve:
return JsonParser.parseString("{\"!header\":{\"!identifier\":\"string\", \"attributes\":{\"element\":\"string\", \"includeElementData\":\"boolean\"}}}"); return JsonParser.parseString(
"{\"!header\":{\"!identifier\":\"string\", \"attributes\":{\"element\":\"string\", \"includeElementData\":\"boolean\"}}}");
case Extension: case Extension:
case Unknown: case Unknown:
default: default:
@ -92,7 +96,8 @@ public class DOOPBeforeExecHandler implements AnnotationHook {
} }
public static void validateJsonElementRulesByArgSchemaVisitor(JsonElement jsonElement, ArgSchemaVisitor visitor) { public static void validateJsonElementRulesByArgSchemaVisitor(JsonElement jsonElement,
ArgSchemaVisitor visitor) {
visitor.visit(jsonElement); visitor.visit(jsonElement);
if (!visitor.getStatus()) { if (!visitor.getStatus()) {
JsonObject jo = new JsonObject(); JsonObject jo = new JsonObject();

View File

@ -33,19 +33,19 @@ public class HomomorphicDecryptHandler implements AnnotationHook {
// String arg = JsonUtil.toJson(args); // String arg = JsonUtil.toJson(args);
JsonElement homoDecryptConf = this.fun.getHomoDecryptConf(); JsonElement homoDecryptConf = this.fun.getHomoDecryptConf();
if (null != homoDecryptConf && !homoDecryptConf.isJsonNull()) { if (null != homoDecryptConf && !homoDecryptConf.isJsonNull()) {
String res = (String) String res = (String) JavaScriptEntry.executeContract("keyManager_1", "getPrivKey",
JavaScriptEntry.executeContract(
"keyManager_1",
"getPrivKey",
this.fun.getSecretID().replaceAll("\"", "")); this.fun.getSecretID().replaceAll("\"", ""));
LOGGER.info("HomomorphicDecryptHandler--------------------------------1: " + res); LOGGER.info("HomomorphicDecryptHandler--------------------------------1: " + res);
ContractResult results = JsonUtil.fromJson(res, ContractResult.class); ContractResult results = JsonUtil.fromJson(res, ContractResult.class);
String privKeyStr = results.result.getAsString(); String privKeyStr = results.result.getAsString();
LOGGER.info("HomomorphicEncryptHandler--------------------------------2: " + privKeyStr); LOGGER.info("HomomorphicEncryptHandler--------------------------------2: "
+ privKeyStr);
RSAPrivateKey privkey = (RSAPrivateKey) PaillierKeyPair.pemToPrivateKey(privKeyStr); RSAPrivateKey privkey = (RSAPrivateKey) PaillierKeyPair.pemToPrivateKey(privKeyStr);
LOGGER.info("HomomorphicEncryptHandler--------------------------------3: " + privkey); LOGGER.info(
"HomomorphicEncryptHandler--------------------------------3: " + privkey);
HomoVisitor.privateKey = privkey; HomoVisitor.privateKey = privkey;
argPacks.ret = getDecryptResult(homoDecryptConf, JsonUtil.parseObject(argPacks.ret)); argPacks.ret =
getDecryptResult(homoDecryptConf, JsonUtil.parseObject(argPacks.ret));
if (null != argPacks.ret) { if (null != argPacks.ret) {
return argPacks; return argPacks;
} }

View File

@ -29,19 +29,14 @@ public class HomomorphicEncryptHandler implements AnnotationHook {
public ArgPacks handle(JSEngine engine, ArgPacks argPacks) { public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
try { try {
ContractRequest input = argPacks.request; ContractRequest input = argPacks.request;
LOGGER.info( LOGGER.info("HomomorphicEncryptHandler--------------------------------1: "
"HomomorphicEncryptHandler--------------------------------1: "
+ input.getRequester()); + input.getRequester());
LOGGER.info( LOGGER.info("HomomorphicEncryptHandler--------------------------------2: "
"HomomorphicEncryptHandler--------------------------------2: "
+ this.fun.getSecretID()); + this.fun.getSecretID());
JsonElement response = (JsonElement) argPacks.ret; JsonElement response = (JsonElement) argPacks.ret;
JsonElement homoEncryptConf = this.fun.getHomoEncryptConf(); JsonElement homoEncryptConf = this.fun.getHomoEncryptConf();
if (homoEncryptConf != null && !homoEncryptConf.isJsonNull()) { if (homoEncryptConf != null && !homoEncryptConf.isJsonNull()) {
String res = String res = (String) JavaScriptEntry.executeContract("keyManager_1", "getPubKey",
(String) JavaScriptEntry.executeContract(
"keyManager_1",
"getPubKey",
this.fun.getSecretID().replaceAll("\"", "")); this.fun.getSecretID().replaceAll("\"", ""));
// String res = // String res =
// JavaScriptEntry.executeContract( // JavaScriptEntry.executeContract(
@ -51,14 +46,19 @@ public class HomomorphicEncryptHandler implements AnnotationHook {
LOGGER.info("HomomorphicEncryptHandler--------------------------------4: " + res); LOGGER.info("HomomorphicEncryptHandler--------------------------------4: " + res);
ContractResult results = JsonUtil.fromJson(res, ContractResult.class); ContractResult results = JsonUtil.fromJson(res, ContractResult.class);
String pubKeyStr = results.result.getAsString(); String pubKeyStr = results.result.getAsString();
LOGGER.info("HomomorphicEncryptHandler--------------------------------5: " + pubKeyStr); LOGGER.info(
"HomomorphicEncryptHandler--------------------------------5: " + pubKeyStr);
HomoVisitor.publicKey = (RSAPublicKey) PaillierKeyPair.pemToPublicKey(pubKeyStr); HomoVisitor.publicKey = (RSAPublicKey) PaillierKeyPair.pemToPublicKey(pubKeyStr);
// if (homoEncryptConf.getAsJsonPrimitive().isString()) // if (homoEncryptConf.getAsJsonPrimitive().isString())
// homoEncryptConf = JsonParser.parseString(homoEncryptConf.getAsString()); // homoEncryptConf = JsonParser.parseString(homoEncryptConf.getAsString());
LOGGER.info("HomomorphicEncryptHandler--------------------------------6: " + homoEncryptConf); LOGGER.info("HomomorphicEncryptHandler--------------------------------6: "
LOGGER.info("HomomorphicEncryptHandler--------------------------------7: " + argPacks.ret); + homoEncryptConf);
LOGGER.info("HomomorphicEncryptHandler--------------------------------8: " + argPacks.ret.toString()); LOGGER.info("HomomorphicEncryptHandler--------------------------------7: "
// LOGGER.info("HomomorphicEncryptHandler--------------------------------9: " + JsonUtil.toJson(ret)); + argPacks.ret);
LOGGER.info("HomomorphicEncryptHandler--------------------------------8: "
+ argPacks.ret.toString());
// LOGGER.info("HomomorphicEncryptHandler--------------------------------9: " +
// JsonUtil.toJson(ret));
argPacks.ret = getEncryptResult(homoEncryptConf, response); argPacks.ret = getEncryptResult(homoEncryptConf, response);
if (argPacks.ret != null) { if (argPacks.ret != null) {
return argPacks; return argPacks;

View File

@ -23,7 +23,8 @@ public class MockTemplateHandler implements AnnotationHook {
MockUtil Mock = new MockUtil(); MockUtil Mock = new MockUtil();
argPacks.ret = Mock.mock(template).toString(); argPacks.ret = Mock.mock(template).toString();
return argPacks; return argPacks;
} else return argPacks; //When mock config is null defined just ignore. } else
return argPacks; // When mock config is null defined just ignore.
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -13,10 +13,9 @@ import org.commonmark.parser.Parser;
public class ReadMeHandler implements AnnotationHook { public class ReadMeHandler implements AnnotationHook {
String getReadMeData(DesktopEngine desktopEngine, ContractRequest c) { String getReadMeData(DesktopEngine desktopEngine, ContractRequest c) {
String fileReadme = String fileReadme = desktopEngine.getResources().loadAsString("/assets/README.md"); // is
desktopEngine // "/README.md"
.getResources() // not"./README.md"!!!!
.loadAsString("/assets/README.md"); // is "/README.md" not"./README.md"!!!!
// System.out.println("fileReadme:" + fileReadme); // System.out.println("fileReadme:" + fileReadme);
if (null == fileReadme) { if (null == fileReadme) {
return "项目目录下无预览文档"; return "项目目录下无预览文档";
@ -30,18 +29,11 @@ public class ReadMeHandler implements AnnotationHook {
while (visitor != null) { while (visitor != null) {
if (visitor instanceof Heading) { if (visitor instanceof Heading) {
if (((Heading) visitor).getLevel() == 2) { if (((Heading) visitor).getLevel() == 2) {
if (((Text) (visitor.getFirstChild())) if (((Text) (visitor.getFirstChild())).getLiteral()
.getLiteral()
.equals(targetFunction)) { .equals(targetFunction)) {
FencedCodeBlock blockResult = FencedCodeBlock blockResult =
(FencedCodeBlock) (FencedCodeBlock) (visitor.getNext().getNext().getNext()
(visitor.getNext() .getNext().getNext().getNext().getNext());
.getNext()
.getNext()
.getNext()
.getNext()
.getNext()
.getNext());
result = blockResult.getLiteral(); result = blockResult.getLiteral();
break; break;
} }

View File

@ -78,7 +78,8 @@ public class ResultSchemaHandler implements AnnotationHook {
return argPacks; return argPacks;
} }
public static ResultSchemaHandler fromAnnotationNode(FunctionNode funNode, AnnotationNode annoNode) { public static ResultSchemaHandler fromAnnotationNode(FunctionNode funNode,
AnnotationNode annoNode) {
return new ResultSchemaHandler(annoNode); return new ResultSchemaHandler(annoNode);
} }
} }

View File

@ -3,8 +3,7 @@ package org.bdware.sc.engine.setArgs;
public class GetHomArgs { public class GetHomArgs {
public String secretID; public String secretID;
public GetHomArgs() { public GetHomArgs() {}
}
public GetHomArgs(String secretID) { public GetHomArgs(String secretID) {
this.secretID = secretID; this.secretID = secretID;

View File

@ -11,8 +11,7 @@ public class DoipMessagePacker {
// the well-composed DoipMessage // the well-composed DoipMessage
public DoipMessage rawDoipMsg; public DoipMessage rawDoipMsg;
public DoipMessagePacker() { public DoipMessagePacker() {}
}
public DoipMessagePacker(String source, DoipMessage rawMsg) { public DoipMessagePacker(String source, DoipMessage rawMsg) {
this.source = source; this.source = source;
@ -28,6 +27,7 @@ public class DoipMessagePacker {
} }
public Object toJSObject() { public Object toJSObject() {
return JSONTool.convertJsonElementToMirror(JsonUtil.parseObject(JsonDoipMessage.fromDoipMessage(rawDoipMsg))); return JSONTool.convertJsonElementToMirror(
JsonUtil.parseObject(JsonDoipMessage.fromDoipMessage(rawDoipMsg)));
} }
} }

View File

@ -104,8 +104,8 @@ public class ContractHandler extends MsgHandler implements Runnable {
@Description("set members") @Description("set members")
public void setMembers(GetMessage msg, ResultCallback cb) { public void setMembers(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.setMembers(JsonUtil.fromJson(msg.arg, new TypeToken<List<String>>() { cb.onResult(cs.setMembers(
}.getType()))); JsonUtil.fromJson(msg.arg, new TypeToken<List<String>>() {}.getType())));
} }
@Description("get current contract name") @Description("get current contract name")

View File

@ -42,14 +42,16 @@ public class DOOPRequestHandler implements DoipRequestHandler {
@Override @Override
public DoipMessage onRequest(ChannelHandlerContext ctx, DoipMessage msg) { public DoipMessage onRequest(ChannelHandlerContext ctx, DoipMessage msg) {
String str = msg.header.parameters.operation; String str = msg.header.parameters.operation;
if (msg.header != null && msg.header.parameters.operation.equals(SharableVarManager.SHARABLEOP)) { if (msg.header != null
&& msg.header.parameters.operation.equals(SharableVarManager.SHARABLEOP)) {
return SharableVarManager.instance.handleSyncMessage(msg); return SharableVarManager.instance.handleSyncMessage(msg);
} }
logger.debug("[Call operation] name: " + str); logger.debug("[Call operation] name: " + str);
if (str != null) { if (str != null) {
FunctionNode fn; FunctionNode fn;
fn = doipFunctionNodeMap.get(str); fn = doipFunctionNodeMap.get(str);
if (fn == null) fn = doipFunctionNodeMap.get(BasicOperations.Unknown.getName()); if (fn == null)
fn = doipFunctionNodeMap.get(BasicOperations.Unknown.getName());
if (fn != null) { if (fn != null) {
return buildRequestAndInvokeEngine(fn, msg); return buildRequestAndInvokeEngine(fn, msg);
} }
@ -62,7 +64,8 @@ public class DOOPRequestHandler implements DoipRequestHandler {
DoipMessagePacker arg = new DoipMessagePacker("doip", msg); DoipMessagePacker arg = new DoipMessagePacker("doip", msg);
try { try {
// 改变调用的函数 + 构造DoipMessagePacker // 改变调用的函数 + 构造DoipMessagePacker
Object ret = ContractProcess.instance.engine.executeWithoutLock(fn, contractRequest, arg); Object ret =
ContractProcess.instance.engine.executeWithoutLock(fn, contractRequest, arg);
DoipMessage finalDoipMsg = (DoipMessage) ret; DoipMessage finalDoipMsg = (DoipMessage) ret;
finalDoipMsg.requestID = msg.requestID; finalDoipMsg.requestID = msg.requestID;
if (finalDoipMsg.header.parameters == null) { if (finalDoipMsg.header.parameters == null) {
@ -71,16 +74,19 @@ public class DOOPRequestHandler implements DoipRequestHandler {
if (finalDoipMsg.header.parameters.attributes == null) { if (finalDoipMsg.header.parameters.attributes == null) {
finalDoipMsg.header.parameters.attributes = new JsonObject(); finalDoipMsg.header.parameters.attributes = new JsonObject();
} }
finalDoipMsg.header.parameters.attributes.addProperty("nodeID", String.valueOf(JavaScriptEntry.shardingID)); finalDoipMsg.header.parameters.attributes.addProperty("nodeID",
String.valueOf(JavaScriptEntry.shardingID));
return finalDoipMsg; return finalDoipMsg;
} catch (Exception e) { } catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo)); e.printStackTrace(new PrintStream(bo));
DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder(); DoipMessageFactory.DoipMessageBuilder builder =
new DoipMessageFactory.DoipMessageBuilder();
builder.createResponse(DoipResponseCode.Declined, msg); builder.createResponse(DoipResponseCode.Declined, msg);
builder.setBody(bo.toByteArray()); builder.setBody(bo.toByteArray());
builder.addAttributes("nodeID", String.valueOf(JavaScriptEntry.shardingID)); builder.addAttributes("nodeID", String.valueOf(JavaScriptEntry.shardingID));
logger.error("buildRequestAndInvokeEngine has something wrong, executeWithoutLock err or validateJsonElementRulesByArgSchemaVisitor err"); logger.error(
"buildRequestAndInvokeEngine has something wrong, executeWithoutLock err or validateJsonElementRulesByArgSchemaVisitor err");
return builder.create(); return builder.create();
} }
} }

View File

@ -4,8 +4,9 @@ import jdk.internal.dynalink.beans.StaticClass;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror; import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
public enum MOType { public enum MOType {
String(true), Int(true), Double(true), Boolean(true),JSObject(false), JSArray(false), JavaObject(false), Method(false), String(true), Int(true), Double(true), Boolean(true), JSObject(false), JSArray(
Undefined(true), JSFunction(false),JSStatic(false); false), JavaObject(
false), Method(false), Undefined(true), JSFunction(false), JSStatic(false);
private boolean isPrimitive; private boolean isPrimitive;

View File

@ -100,10 +100,9 @@ public class MemoryDump implements Serializable {
currID = id; currID = id;
if (obj.getClass() == jdk.internal.dynalink.beans.StaticClass.class) { if (obj.getClass() == jdk.internal.dynalink.beans.StaticClass.class) {
/* /*
String obj2 = "jdk.internal.dynalink.beans.StaticClass.class"; * String obj2 = "jdk.internal.dynalink.beans.StaticClass.class"; if
if (allocated.containsKey(obj2)) * (allocated.containsKey(obj2)) return allocated.get(obj2); allocated.put(obj2,
return allocated.get(obj2); * currID);
allocated.put(obj2, currID);
*/ */
} else { } else {
if (allocated.containsKey(obj)) if (allocated.containsKey(obj))
@ -151,7 +150,8 @@ public class MemoryDump implements Serializable {
mo.data = obj; mo.data = obj;
objects.put(currID, mo); objects.put(currID, mo);
} else } else
System.out.println("[MemoryDump] Allocat MetType:" + obj.getClass() + " now id=" + currID); System.out.println(
"[MemoryDump] Allocat MetType:" + obj.getClass() + " now id=" + currID);
} }
return currID; return currID;
@ -203,10 +203,12 @@ public class MemoryDump implements Serializable {
} }
switch (mo.type) { switch (mo.type) {
case JSArray: case JSArray:
obj = ScriptObjectMirror.wrap(Global.allocate(new int[0]), JavaScriptEntry.getEngineGlobal()); obj = ScriptObjectMirror.wrap(Global.allocate(new int[0]),
JavaScriptEntry.getEngineGlobal());
break; break;
case JSObject: case JSObject:
obj = ScriptObjectMirror.wrap(new JO(PropertyMap.newMap()), JavaScriptEntry.getEngineGlobal()); obj = ScriptObjectMirror.wrap(new JO(PropertyMap.newMap()),
JavaScriptEntry.getEngineGlobal());
break; break;
case JSFunction: case JSFunction:
break; break;

View File

@ -34,7 +34,8 @@ public class MemoryDumpUtil {
memoryDump = (MemoryDump) reader.readObject(); memoryDump = (MemoryDump) reader.readObject();
reader.close(); reader.close();
String ret = JsonUtil.toPrettyJson(memoryDump.objects); String ret = JsonUtil.toPrettyJson(memoryDump.objects);
ret += ("<seperate>" + memoryDump.jseDump.invokeID + ";" + memoryDump.jseDump.ranSeed + ";" + memoryDump.jseDump.numsOfCopies + ""); ret += ("<seperate>" + memoryDump.jseDump.invokeID + ";" + memoryDump.jseDump.ranSeed
+ ";" + memoryDump.jseDump.numsOfCopies + "");
return ret; return ret;
} catch (IOException | ClassNotFoundException e) { } catch (IOException | ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
@ -43,20 +44,11 @@ public class MemoryDumpUtil {
} }
/* /*
public static String getContentFromFile2(String path) { * public static String getContentFromFile2(String path) { File file = new File(path);
File file = new File(path); * ObjectInputStream reader; try { FileInputStream fileout = new FileInputStream(file); reader =
ObjectInputStream reader; * new ObjectInputStream(fileout); String ret = (String)reader.readObject(); reader.close();
try { * return ret; } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return
FileInputStream fileout = new FileInputStream(file); * null; }
reader = new ObjectInputStream(fileout);
String ret = (String)reader.readObject();
reader.close();
return ret;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
*/ */
// stateful 表示合约是有/无状态合约 // stateful 表示合约是有/无状态合约
@ -73,16 +65,21 @@ public class MemoryDumpUtil {
long id = memoryDump.allocate(obj); long id = memoryDump.allocate(obj);
root.addField(key, id); root.addField(key, id);
} }
memoryDump.jseDump = new JSEDump(JavaScriptEntry.invokeID, Long.parseLong(JavaScriptEntry.currentSyncUtil.contractID), JavaScriptEntry.numOfCopies); memoryDump.jseDump = new JSEDump(JavaScriptEntry.invokeID,
Long.parseLong(JavaScriptEntry.currentSyncUtil.contractID),
JavaScriptEntry.numOfCopies);
ret = JsonUtil.toPrettyJson(memoryDump.objects); ret = JsonUtil.toPrettyJson(memoryDump.objects);
} else { // 无状态合约 } else { // 无状态合约
memoryDump.jseDump = new JSEDump(JavaScriptEntry.invokeID, Long.parseLong(JavaScriptEntry.currentSyncUtil.contractID), JavaScriptEntry.numOfCopies); memoryDump.jseDump = new JSEDump(JavaScriptEntry.invokeID,
Long.parseLong(JavaScriptEntry.currentSyncUtil.contractID),
JavaScriptEntry.numOfCopies);
memoryDump.objects.clear(); memoryDump.objects.clear();
ret = JsonUtil.toPrettyJson(memoryDump.objects); ret = JsonUtil.toPrettyJson(memoryDump.objects);
} }
ret += "--seperate--"; ret += "--seperate--";
ret += (memoryDump.jseDump.invokeID + ";" + memoryDump.jseDump.ranSeed + ";" + memoryDump.jseDump.numsOfCopies); ret += (memoryDump.jseDump.invokeID + ";" + memoryDump.jseDump.ranSeed + ";"
+ memoryDump.jseDump.numsOfCopies);
if (path == null || path.equals("")) { if (path == null || path.equals("")) {
return ret; return ret;
@ -90,7 +87,8 @@ public class MemoryDumpUtil {
File mem = new File(path); File mem = new File(path);
File parent = mem.getParentFile(); File parent = mem.getParentFile();
if (!parent.exists()) parent.mkdirs(); if (!parent.exists())
parent.mkdirs();
ObjectOutputStream writer; ObjectOutputStream writer;
try { try {
FileOutputStream fileout = new FileOutputStream(mem); FileOutputStream fileout = new FileOutputStream(mem);
@ -112,44 +110,25 @@ public class MemoryDumpUtil {
/* /*
public String dumpMemory(String path) { * public String dumpMemory(String path) { memoryDump = new MemoryDump(); Bindings bindings =
memoryDump = new MemoryDump(); * engine.getBindings(ScriptContext.ENGINE_SCOPE);
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); * System.out.println("[MemoryDumpUtil] bindings size=" + bindings.size()); MemoryJSObject root
System.out.println("[MemoryDumpUtil] bindings size=" + bindings.size()); * = memoryDump.getRoot(); for (String key : bindings.keySet()) {
MemoryJSObject root = memoryDump.getRoot(); * System.out.println("[MemoryDumpUtil] dumpMemory " + key); Object obj = bindings.get(key);
for (String key : bindings.keySet()) { * long id = memoryDump.allocate(obj); root.addField(key, id);
System.out.println("[MemoryDumpUtil] dumpMemory " + key); *
Object obj = bindings.get(key); * System.out.println("[root addFiled] key=" + key + " id=" + id); } String ret =
long id = memoryDump.allocate(obj); * JsonUtil.toPrettyJson(memoryDump); dumpContent = ret;
root.addField(key, id); *
* if(path == null || path.equals("")) { return ret; }
System.out.println("[root addFiled] key=" + key + " id=" + id); *
} * File mem = new File(path); File parent = mem.getParentFile(); if (!parent.exists())
String ret = JsonUtil.toPrettyJson(memoryDump); * parent.mkdirs(); ObjectOutputStream writer; try { FileOutputStream fileout = new
dumpContent = ret; * FileOutputStream(mem); writer = new ObjectOutputStream(fileout);
* writer.writeObject(dumpContent);
if(path == null || path.equals("")) { *
return ret; * writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); }
} *
* memoryDump = null; return ret; }
File mem = new File(path);
File parent = mem.getParentFile();
if (!parent.exists())
parent.mkdirs();
ObjectOutputStream writer;
try {
FileOutputStream fileout = new FileOutputStream(mem);
writer = new ObjectOutputStream(fileout);
writer.writeObject(dumpContent);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
memoryDump = null;
return ret;
}
*/ */
} }

View File

@ -1,7 +1,6 @@
package org.bdware.sc.memory; package org.bdware.sc.memory;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map;
public class MemoryJSObject extends MemoryObject { public class MemoryJSObject extends MemoryObject {
private static final long serialVersionUID = -2290414347562477503L; private static final long serialVersionUID = -2290414347562477503L;

View File

@ -114,7 +114,8 @@ public class MemoryRecoverUtil {
ScriptObjectMirror global = (ScriptObjectMirror) objects.get(0L); ScriptObjectMirror global = (ScriptObjectMirror) objects.get(0L);
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
for (Object key : global.keySet()) { for (Object key : global.keySet()) {
if (global.get(key) != null) bindings.put((String) key, global.get(key)); if (global.get(key) != null)
bindings.put((String) key, global.get(key));
} }
} }
this.memoryDump = null; this.memoryDump = null;
@ -127,34 +128,20 @@ public class MemoryRecoverUtil {
} }
/* /*
public void loadMemory(String path) { * public void loadMemory(String path) { try { String memory; File mem = new File(path);
try { * FileInputStream fileout = new FileInputStream(mem); ObjectInputStream reader = new
String memory; * ObjectInputStream(fileout); loadContent = (String) reader.readObject(); //
File mem = new File(path); * System.out.println("[MemoryRecoverUtil] loadContent : \n" + loadContent); reader.close();
FileInputStream fileout = new FileInputStream(mem); * memoryDump = MemoryDump.loadFromStr(loadContent);
ObjectInputStream reader = new ObjectInputStream(fileout); *
loadContent = (String) reader.readObject(); *
// System.out.println("[MemoryRecoverUtil] loadContent : \n" + loadContent); * String ret = JsonUtil.toPrettyJson(memoryDump); MemoryJSObject root = memoryDump.getRoot();
reader.close(); * Map<Long, Object> objects = memoryDump.recreateObject(); ScriptObjectMirror global =
memoryDump = MemoryDump.loadFromStr(loadContent); * (ScriptObjectMirror) objects.get(0L); Bindings bindings =
* engine.getBindings(ScriptContext.ENGINE_SCOPE); for (Object key : global.keySet()) { if
* (global.get(key) != null) bindings.put((String) key, global.get(key)); } this.memoryDump =
String ret = JsonUtil.toPrettyJson(memoryDump); * null; if (resource != null) ((Invocable) engine).invokeFunction("defineProp", "Resources",
MemoryJSObject root = memoryDump.getRoot(); * resource); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
Map<Long, Object> objects = memoryDump.recreateObject(); * }
ScriptObjectMirror global = (ScriptObjectMirror) objects.get(0L);
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
for (Object key : global.keySet()) {
if (global.get(key) != null)
bindings.put((String) key, global.get(key));
}
this.memoryDump = null;
if (resource != null)
((Invocable) engine).invokeFunction("defineProp", "Resources", resource);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/ */
} }

View File

@ -14,7 +14,8 @@ public class TransRecordUtil {
public static final int RESERVED = 20; // 最近的多少次records内存也保存如果一个节点距离集群当前的seq相差超过这个值就不从本地恢复让别的节点现场dump public static final int RESERVED = 20; // 最近的多少次records内存也保存如果一个节点距离集群当前的seq相差超过这个值就不从本地恢复让别的节点现场dump
public static final int DUMP_PERIOD = 50; // 每满50次记录就记录一次全量状态清一次trans记录 public static final int DUMP_PERIOD = 50; // 每满50次记录就记录一次全量状态清一次trans记录
private static final Logger LOGGER = LogManager.getLogger(TransRecordUtil.class); private static final Logger LOGGER = LogManager.getLogger(TransRecordUtil.class);
public Map<Integer, TransRecord> cacheTransRecords = new TreeMap<Integer, TransRecord>(); //TODO 认为其中records一定是seq连续的否则可能有问题? public Map<Integer, TransRecord> cacheTransRecords = new TreeMap<Integer, TransRecord>(); // TODO
// 认为其中records一定是seq连续的否则可能有问题?
// public PriorityQueue<TransRecord> transRecords = new PriorityQueue<TransRecord>(); // public PriorityQueue<TransRecord> transRecords = new PriorityQueue<TransRecord>();
public TransRecord currentTransRecord; public TransRecord currentTransRecord;
SyncMechUtil syncUtil; SyncMechUtil syncUtil;

View File

@ -46,7 +46,8 @@ public class TransRecoverUtil {
System.out.println("恢复时加入 " + cur_read.toString()); System.out.println("恢复时加入 " + cur_read.toString());
} }
if (strs[1].equals("true")) if (strs[1].equals("true"))
cur_read = new TransRecord(strs[3], JsonUtil.parseString(arg), Integer.parseInt(strs[2])); cur_read = new TransRecord(strs[3], JsonUtil.parseString(arg),
Integer.parseInt(strs[2]));
else else
cur_read = new TransRecord(strs[3], JsonUtil.parseString(arg)); cur_read = new TransRecord(strs[3], JsonUtil.parseString(arg));
} else { } else {
@ -83,7 +84,8 @@ public class TransRecoverUtil {
ac.seq = curRecoverRecord.seq; ac.seq = curRecoverRecord.seq;
LOGGER.info("[TransRecordUtil] redo 重新执行事务 " + ac.seq); LOGGER.info("[TransRecordUtil] redo 重新执行事务 " + ac.seq);
} }
System.out.println("[TransRecoverUtil] recover " + ac.needSeq + " " + ac.seq + " " + ac.getAction() + " " + ac.getArg()); System.out.println("[TransRecoverUtil] recover " + ac.needSeq + " " + ac.seq + " "
+ ac.getAction() + " " + ac.getArg());
ContractResult result = engine.executeContract(ac); ContractResult result = engine.executeContract(ac);

View File

@ -42,7 +42,8 @@ public class DoipClusterServer extends DoipServerImpl {
return instance; return instance;
} }
public static int startDoipServer(int startPort, JsonElement otherConfigs) throws InterruptedException { public static int startDoipServer(int startPort, JsonElement otherConfigs)
throws InterruptedException {
try { try {
int ret = DoipLocalSingleton.run(startPort, otherConfigs); int ret = DoipLocalSingleton.run(startPort, otherConfigs);
return ret; return ret;
@ -56,7 +57,10 @@ public class DoipClusterServer extends DoipServerImpl {
repoIrpClient = new AuditIrpClient(config); repoIrpClient = new AuditIrpClient(config);
EndpointInfo info = repoIrpClient.getEndpointInfo(); EndpointInfo info = repoIrpClient.getEndpointInfo();
if (info == null) { if (info == null) {
String content = "{\"date\":\"2022-1-13\",\"name\":\"testrepoforaibd\",\"doId\":\"bdware.test.local/Repo\",\"address\":\"tcp://127.0.0.1:" + defaultDOIPServerPort + "\",\"status\":\"已审核\",\"protocol\":\"DOIP\",\"pubKey\":\"empty\",\"version\":\"2.1\"}"; String content =
"{\"date\":\"2022-1-13\",\"name\":\"testrepoforaibd\",\"doId\":\"bdware.test.local/Repo\",\"address\":\"tcp://127.0.0.1:"
+ defaultDOIPServerPort
+ "\",\"status\":\"已审核\",\"protocol\":\"DOIP\",\"pubKey\":\"empty\",\"version\":\"2.1\"}";
info = EndpointInfo.fromJson(content); info = EndpointInfo.fromJson(content);
} }
List<DoipListenerConfig> infos = new ArrayList<>(); List<DoipListenerConfig> infos = new ArrayList<>();
@ -65,7 +69,8 @@ public class DoipClusterServer extends DoipServerImpl {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
DoipServiceInfo ret = new DoipServiceInfo(info.getDoId(), info.getPubKey(), defaultRepoType, infos); DoipServiceInfo ret =
new DoipServiceInfo(info.getDoId(), info.getPubKey(), defaultRepoType, infos);
return ret; return ret;
} }
@ -93,10 +98,14 @@ public class DoipClusterServer extends DoipServerImpl {
// 维护RouteInfo将RouteInfo和doipOperationName的映射关系以及所有Router中用得到的函数都维护好 // 维护RouteInfo将RouteInfo和doipOperationName的映射关系以及所有Router中用得到的函数都维护好
// TODO 移除这部分逻辑 // TODO 移除这部分逻辑
cn.maintainRouteJoinInfo(methodRouteInfoMap, methodJoinInfoMap, functions); cn.maintainRouteJoinInfo(methodRouteInfoMap, methodJoinInfoMap, functions);
if (clusterInfo != null) repoHandleValues.add("clusterInfo", clusterInfo); if (clusterInfo != null)
if (functions.size() > 0) repoHandleValues.add("functions", functions); repoHandleValues.add("clusterInfo", clusterInfo);
if (methodRouteInfoMap.size() > 0) repoHandleValues.add("routeInfo", methodRouteInfoMap); if (functions.size() > 0)
if (methodJoinInfoMap.size() > 0) repoHandleValues.add("joinInfo", methodJoinInfoMap); repoHandleValues.add("functions", functions);
if (methodRouteInfoMap.size() > 0)
repoHandleValues.add("routeInfo", methodRouteInfoMap);
if (methodJoinInfoMap.size() > 0)
repoHandleValues.add("joinInfo", methodJoinInfoMap);
repoInfo.handleValues.addProperty("cluster", repoHandleValues.toString()); repoInfo.handleValues.addProperty("cluster", repoHandleValues.toString());
String updateRepoInfoRes = repoIrpClient.reRegister(repoInfo); String updateRepoInfoRes = repoIrpClient.reRegister(repoInfo);
if (updateRepoInfoRes.equals("success")) { if (updateRepoInfoRes.equals("success")) {
@ -104,7 +113,8 @@ public class DoipClusterServer extends DoipServerImpl {
} else if (updateRepoInfoRes.equals("failed")) { } else if (updateRepoInfoRes.equals("failed")) {
LOGGER.error("Failed to update cluster info to router"); LOGGER.error("Failed to update cluster info to router");
} else { } else {
LOGGER.warn("Oops...The result of updating clusterInfo to the router is " + updateRepoInfoRes); LOGGER.warn("Oops...The result of updating clusterInfo to the router is "
+ updateRepoInfoRes);
} }
} }

View File

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

View File

@ -3,8 +3,7 @@ package org.bdware.sc.trace;
import java.io.Serializable; import java.io.Serializable;
/* /*
* js中对象 * js中对象 ScriptObject JO
* ScriptObject JO
*/ */
public class JSObject extends JSScript implements Serializable { public class JSObject extends JSScript implements Serializable {

View File

@ -49,7 +49,8 @@ public class MethodInvokePrinter implements TraceMethod {
} }
} }
public void tracePrint(final String tag, int pc, String methodName, final Object[] args, final Object result) { public void tracePrint(final String tag, int pc, String methodName, final Object[] args,
final Object result) {
// boolean isVoid = type().returnType() == void.class; // boolean isVoid = type().returnType() == void.class;
out.print(tag); out.print(tag);
out.print(methodName + "_" + pc + "("); out.print(methodName + "_" + pc + "(");

View File

@ -24,14 +24,8 @@ public class ProgramPointCounter extends ContractProcess.Logger implements Trace
int functionIndex = 0; int functionIndex = 0;
public long gasValue = 0; public long gasValue = 0;
public ProgramPointCounter( public ProgramPointCounter(ByteArrayOutputStream bo, ContractProcess cp, long gasLimit,
ByteArrayOutputStream bo, int functionIndex, long gasValue, long extraGas, String action,
ContractProcess cp,
long gasLimit,
int functionIndex,
long gasValue,
long extraGas,
String action,
HashMap<String, Long> countMap) { HashMap<String, Long> countMap) {
super(new PrintStream(bo), cp); super(new PrintStream(bo), cp);
// out = System.out; // out = System.out;
@ -50,52 +44,33 @@ public class ProgramPointCounter extends ContractProcess.Logger implements Trace
public String getOutputStr() { public String getOutputStr() {
return bo.toString(); return bo.toString();
} }
/* /*
private void printObject(final Object arg) { * private void printObject(final Object arg) { if (simple) return; if (arg instanceof
if (simple) return; * ScriptObject) { final ScriptObject object = (ScriptObject) arg;
if (arg instanceof ScriptObject) { *
final ScriptObject object = (ScriptObject) arg; * boolean isFirst = true; final Set<Object> keySet = object.keySet(); //
* System.out.println("[keySet:]"); if (keySet.isEmpty()) {
boolean isFirst = true; * out.print(ScriptRuntime.safeToString(arg)); } else { out.print("{ ");
final Set<Object> keySet = object.keySet(); *
// System.out.println("[keySet:]"); * for (final Object key : keySet) { if (!isFirst) { out.print(", "); }
if (keySet.isEmpty()) { *
out.print(ScriptRuntime.safeToString(arg)); * out.print(key); out.print(":");
} else { *
out.print("{ "); * final Object value = object.get(key);
*
for (final Object key : keySet) { * if (value instanceof ScriptObject) { out.print("..."); } else { printObject(value); }
if (!isFirst) { *
out.print(", "); * isFirst = false; }
} *
* out.print(" }"); } } else { out.print(ScriptRuntime.safeToString(arg)); } }
out.print(key);
out.print(":");
final Object value = object.get(key);
if (value instanceof ScriptObject) {
out.print("...");
} else {
printObject(value);
}
isFirst = false;
}
out.print(" }");
}
} else {
out.print(ScriptRuntime.safeToString(arg));
}
}
*/ */
boolean initEnter = false; boolean initEnter = false;
Stack<Integer> pcStack = new Stack<>(); Stack<Integer> pcStack = new Stack<>();
@Override @Override
public void tracePrint( public void tracePrint(final String tag, int pc, String methodName, final Object[] args,
final String tag, int pc, String methodName, final Object[] args, final Object result) { final Object result) {
// System.out.println("!@#$%^&*" + tag + pc + methodName + args + result); // System.out.println("!@#$%^&*" + tag + pc + methodName + args + result);
if (!initEnter) { if (!initEnter) {
// System.out.println("[functionIndex]:" + countMap.get(String.valueOf(functionIndex))); // System.out.println("[functionIndex]:" + countMap.get(String.valueOf(functionIndex)));

View File

@ -2,7 +2,6 @@ package org.bdware.sc.trace;
import java.io.*; import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
@ -93,7 +92,8 @@ public class TraceRecordUtil {
public void saveTraceRecords(String fileName) { public void saveTraceRecords(String fileName) {
if (traceRecords == null) { if (traceRecords == null) {
System.out.println("[saveTraceRecords] traceRecords is null,can't save traceRecords to fill!"); System.out.println(
"[saveTraceRecords] traceRecords is null,can't save traceRecords to fill!");
} }
File traceFile = new File(fileName + ".trace"); // trace文件名中不带时间 File traceFile = new File(fileName + ".trace"); // trace文件名中不带时间
@ -159,11 +159,10 @@ public class TraceRecordUtil {
TraceSetup tracesetup = new TraceSetup((JSScript) produceJS(arg)); TraceSetup tracesetup = new TraceSetup((JSScript) produceJS(arg));
/* /*
* System.out.println("[startRecord] setupScriptObject argID=" + * System.out.println("[startRecord] setupScriptObject argID=" + arg.getObjectID() +
* arg.getObjectID() + " map=" + map.size()); Iterator<String> keys = * " map=" + map.size()); Iterator<String> keys = arg.propertyIterator();
* arg.propertyIterator(); while(keys.hasNext()) { String key = keys.next(); * while(keys.hasNext()) { String key = keys.next(); System.out.println(key + " ; "
* System.out.println(key + " ; " + * + map.findProperty(key).getClass().getCanonicalName());
* map.findProperty(key).getClass().getCanonicalName());
* tracesetup.add(map.findProperty(key)); } * tracesetup.add(map.findProperty(key)); }
*/ */
@ -195,15 +194,15 @@ public class TraceRecordUtil {
/* /*
* Context.TRACESETGLOBALOBJECTPROTO = new TraceSetGlobalObjectProto() { * Context.TRACESETGLOBALOBJECTPROTO = new TraceSetGlobalObjectProto() {
* *
* @Override public void trace(int id, int id2,List<Object> keys,List<Object> * @Override public void trace(int id, int id2,List<Object> keys,List<Object> values) {
* values) { System.out.println("[startRecord] set global object proto id=" + id * System.out.println("[startRecord] set global object proto id=" + id + " id2=" + id2 +
* + " id2=" + id2 + " size=" + keys.size()); * " size=" + keys.size());
* *
* *
* *
* TraceInitObject traceinitobject = new TraceInitObject(id,id2); for(int i = * TraceInitObject traceinitobject = new TraceInitObject(id,id2); for(int i = 0;i <
* 0;i < keys.size();i++) { System.out.println("i=" + i + " key=" + keys.get(i) * keys.size();i++) { System.out.println("i=" + i + " key=" + keys.get(i) + " value=" +
* + " value=" + values.get(i)); } currentTraceRecord.record(traceinitobject); } * values.get(i)); } currentTraceRecord.record(traceinitobject); }
* *
* }; * };
*/ */
@ -228,7 +227,8 @@ public class TraceRecordUtil {
} else if (arg instanceof wrp.jdk.nashorn.internal.runtime.Undefined) { } else if (arg instanceof wrp.jdk.nashorn.internal.runtime.Undefined) {
return new JSUndifined(); return new JSUndifined();
} else { } else {
System.out.println("[produceJS] arg encounter new type!" + arg.toString() + " " + arg.getClass()); System.out.println(
"[produceJS] arg encounter new type!" + arg.toString() + " " + arg.getClass());
return new JS(); return new JS();
} }
} }

View File

@ -50,9 +50,12 @@ public class TraceRecoverUtil {
} }
public TraceRecord getTraceRecord(int c) { public TraceRecord getTraceRecord(int c) {
if (traceRecords == null) return null; if (traceRecords == null)
else if (traceRecords.size() <= c) return null; return null;
else return traceRecords.get(c); else if (traceRecords.size() <= c)
return null;
else
return traceRecords.get(c);
} }
public String getTraceRecordsContent() { public String getTraceRecordsContent() {
@ -86,7 +89,8 @@ public class TraceRecoverUtil {
for (String key : bindings.keySet()) { for (String key : bindings.keySet()) {
Object obj = bindings.get(key); Object obj = bindings.get(key);
if (obj instanceof ScriptObjectMirror) initRecoverMap((ScriptObjectMirror) obj); if (obj instanceof ScriptObjectMirror)
initRecoverMap((ScriptObjectMirror) obj);
} }
Context.setGlobal(JavaScriptEntry.getEngineGlobal()); Context.setGlobal(JavaScriptEntry.getEngineGlobal());
} }
@ -137,31 +141,25 @@ public class TraceRecoverUtil {
return "[recoverFromTraceRecord] recover all"; return "[recoverFromTraceRecord] recover all";
} }
/* /*
* 通过traceRecord进行恢复 从当前状态恢复到第c次执行之后的状态 * 通过traceRecord进行恢复 从当前状态恢复到第c次执行之后的状态
*/ */
public String recoverFromTraceRecord(int c) { public String recoverFromTraceRecord(int c) {
int oldflag = recoverFlag; int oldflag = recoverFlag;
if (recoverFlag < 0) recoverInit(); if (recoverFlag < 0)
recoverInit();
if (recoverFlag > c) { if (recoverFlag > c) {
System.out.println( System.out.println("[recoverFromTraceRecord] recoverFlag now is " + recoverFlag
"[recoverFromTraceRecord] recoverFlag now is " + " ,can't recover to " + c + " !");
+ recoverFlag
+ " ,can't recover to "
+ c
+ " !");
return "recover from trace failed!"; return "recover from trace failed!";
} }
if (c >= traceRecords.size()) { if (c >= traceRecords.size()) {
System.out.println( System.out.println("[recoverFromTraceRecord] traceRecords' size now is "
"[recoverFromTraceRecord] traceRecords' size now is " + traceRecords.size() + " ,can't recover to " + c + " !");
+ traceRecords.size()
+ " ,can't recover to "
+ c
+ " !");
return "recover from trace failed!"; return "recover from trace failed!";
} }
@ -217,10 +215,8 @@ public class TraceRecoverUtil {
if (trace.getObj() instanceof JSArray) { if (trace.getObj() instanceof JSArray) {
id = ((JSArray) trace.getObj()).getObjID(); id = ((JSArray) trace.getObj()).getObjID();
obj = obj = (ScriptObjectMirror) ScriptObjectMirror.wrap(Global.allocate(new int[0]),
(ScriptObjectMirror) engine.getDesktopGlobal());
ScriptObjectMirror.wrap(
Global.allocate(new int[0]), engine.getDesktopGlobal());
obj.setObjectID(id); obj.setObjectID(id);
} else if (trace.getObj() instanceof JSObject) { } else if (trace.getObj() instanceof JSObject) {
@ -233,9 +229,8 @@ public class TraceRecoverUtil {
* System.out.println("[recover setup JSObject] : "); id = ((JSObject) * System.out.println("[recover setup JSObject] : "); id = ((JSObject)
* trace.getObj()).getObjID(); * trace.getObj()).getObjID();
* *
* PropertyMap map = PropertyMap.newMap(); for(int i = 0;i < * PropertyMap map = PropertyMap.newMap(); for(int i = 0;i < trace.proLength();i++) {
* trace.proLength();i++) { map.addProperty(trace.get(i)); } ScriptObject so = * map.addProperty(trace.get(i)); } ScriptObject so = new JO(map);
* new JO(map);
* *
* *
* *
@ -279,12 +274,14 @@ public class TraceRecoverUtil {
// 目前JSArray和JSObject一样可能可以简化 // 目前JSArray和JSObject一样可能可以简化
else if (value instanceof JSArray) else if (value instanceof JSArray)
value = getScriptObjectMirrorById(((JSArray) value).getObjID()); value = getScriptObjectMirrorById(((JSArray) value).getObjID());
else if (value instanceof String || value instanceof Integer || value instanceof Double) ; else if (value instanceof String || value instanceof Integer || value instanceof Double)
;
else if (value instanceof JSNull) // 数组trace中可能存在null和Undifined类型赋值时跳过 else if (value instanceof JSNull) // 数组trace中可能存在null和Undifined类型赋值时跳过
return; return;
else if (value instanceof JSUndifined) { else if (value instanceof JSUndifined) {
return; return;
} else System.out.println("[recoverSet] encounter new value type!" + value.toString()); } else
System.out.println("[recoverSet] encounter new value type!" + value.toString());
// 修改ScriptObjectMirror中的setMemeber使它支持所有类型 // 修改ScriptObjectMirror中的setMemeber使它支持所有类型
owner.setMember2(key, value); owner.setMember2(key, value);
@ -294,8 +291,10 @@ public class TraceRecoverUtil {
* 将bindings中的变量放入recoverMap 对于函数的scope中的对象以及对象中的对象的情况可以通过递归将所有需要的都放入recoverMap中 * 将bindings中的变量放入recoverMap 对于函数的scope中的对象以及对象中的对象的情况可以通过递归将所有需要的都放入recoverMap中
*/ */
private void initRecoverMap(ScriptObjectMirror obj) { private void initRecoverMap(ScriptObjectMirror obj) {
if (obj == null) return; if (obj == null)
if (recoverMap.containsKey(obj.getObjectID())) return; return;
if (recoverMap.containsKey(obj.getObjectID()))
return;
recoverMap.put(obj.getObjectID(), obj); recoverMap.put(obj.getObjectID(), obj);
// 全局变量从bindings中获得 // 全局变量从bindings中获得
@ -309,10 +308,8 @@ public class TraceRecoverUtil {
if (svalue.isFunction()) { if (svalue.isFunction()) {
ScriptFunction sf = (ScriptFunction) svalue.getScriptObject(); ScriptFunction sf = (ScriptFunction) svalue.getScriptObject();
ScriptObject s = sf.getScope(); ScriptObject s = sf.getScope();
ScriptObjectMirror obj2 = ScriptObjectMirror obj2 = (ScriptObjectMirror) ScriptObjectMirror.wrap(s,
(ScriptObjectMirror) JavaScriptEntry.getEngineGlobal());
ScriptObjectMirror.wrap(
s, JavaScriptEntry.getEngineGlobal());
initRecoverMap(obj2); initRecoverMap(obj2);
} }
} }
@ -326,7 +323,8 @@ public class TraceRecoverUtil {
ScriptObjectMirror so = null; ScriptObjectMirror so = null;
// 从recoverMap中获得 // 从recoverMap中获得
if (recoverMap.containsKey(id)) return recoverMap.get(id); if (recoverMap.containsKey(id))
return recoverMap.get(id);
System.out.println("[getScriptObjectMirrorById] can't find the ScriptObjectMirror by id!"); System.out.println("[getScriptObjectMirrorById] can't find the ScriptObjectMirror by id!");
return so; return so;

View File

@ -3,8 +3,7 @@ package org.bdware.sc.trace;
import java.io.Serializable; import java.io.Serializable;
/* /*
* 记录nashorn中setElem和setProp的trace * 记录nashorn中setElem和setProp的trace 自定义对象和数组的set不同
* 自定义对象和数组的set不同
*/ */
public class TraceSet extends Trace implements Serializable { public class TraceSet extends Trace implements Serializable {
int owner; // 该对象的id int owner; // 该对象的id

View File

@ -28,10 +28,12 @@ public class TraceSetIdentifier {
if (this.key instanceof String && obj2.key instanceof String && obj2.key.equals(this.key)) if (this.key instanceof String && obj2.key instanceof String && obj2.key.equals(this.key))
return true; return true;
else if(this.key instanceof Double && obj2.key instanceof Double && obj2.key.equals(this.key)) else if (this.key instanceof Double && obj2.key instanceof Double
&& obj2.key.equals(this.key))
return true; return true;
else else
System.out.println("[TraceSetIdentifier] error : encounter new key type : " + this.key.getClass().getName()); System.out.println("[TraceSetIdentifier] error : encounter new key type : "
+ this.key.getClass().getName());
return false; return false;
} }
@ -50,7 +52,8 @@ public class TraceSetIdentifier {
temp = (int) t; temp = (int) t;
result = result * 31 + temp; result = result * 31 + temp;
} else { } else {
System.out.println("[TraceSetIdentifier] error : encounter new key type : " + this.key.getClass().getName()); System.out.println("[TraceSetIdentifier] error : encounter new key type : "
+ this.key.getClass().getName());
} }
if (result < 0) if (result < 0)

View File

@ -39,9 +39,11 @@ public class TraceSetup extends Trace implements Serializable{
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
str.append("[TraceSetup]\n"); str.append("[TraceSetup]\n");
if (obj instanceof JSObject) if (obj instanceof JSObject)
str.append(((JSObject)obj).getObjID() + "," + ((JSObject)obj).getClass()+ " " + /*map.toString() +*/ "\n"); str.append(((JSObject) obj).getObjID() + "," + ((JSObject) obj).getClass() + " "
+ /* map.toString() + */ "\n");
else if (obj instanceof JSArray) else if (obj instanceof JSArray)
str.append(((JSArray)obj).getObjID() + "," + ((JSArray)obj).getClass() + " " +/* map.toString() + */"\n"); str.append(((JSArray) obj).getObjID() + "," + ((JSArray) obj).getClass() + " "
+ /* map.toString() + */"\n");
if (properties.size() > 0) { if (properties.size() > 0) {
str.append("properties : " + "\n"); str.append("properties : " + "\n");

View File

@ -13,12 +13,14 @@ public class DataXTest {
File directory = new File(""); File directory = new File("");
String path = directory.getCanonicalPath(); String path = directory.getCanonicalPath();
try { try {
BufferedReader bf = new BufferedReader(new FileReader("./src/test/data-mask/maskingJobs/config.json")); BufferedReader bf = new BufferedReader(
new FileReader("./src/test/data-mask/maskingJobs/config.json"));
while ((s = bf.readLine()) != null) { while ((s = bf.readLine()) != null) {
content.append(s.trim()); content.append(s.trim());
} }
s = content.toString(); s = content.toString();
} catch (Exception e) {} } catch (Exception e) {
}
String ans = mj.getMaskedData(s).getAsString(); String ans = mj.getMaskedData(s).getAsString();
System.out.println(ans); System.out.println(ans);
} }

View File

@ -7,7 +7,8 @@ public class DataBaseProcess {
// // start a process before // // start a process before
// long startJava = System.currentTimeMillis(); // long startJava = System.currentTimeMillis();
// // authentication: user, dbname, pwd // // authentication: user, dbname, pwd
// MongoCredential credential = MongoCredential.createCredential("yancloud-dbuser", "yancloud", // MongoCredential credential = MongoCredential.createCredential("yancloud-dbuser",
// "yancloud",
// "yancloud-112".toCharArray()); // "yancloud-112".toCharArray());
// // connect to mongodb server // // connect to mongodb server
// ServerAddress addr = new ServerAddress("39.106.118.0", 27017); // ServerAddress addr = new ServerAddress("39.106.118.0", 27017);

View File

@ -8,8 +8,8 @@ public class FSAnalysisTest {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Contract contract = new Contract(); Contract contract = new Contract();
FSAnalysis.isDebug = true; FSAnalysis.isDebug = true;
String content = String content = FileUtil.getFileContent(
FileUtil.getFileContent("/Users/hulingxuan/git/SmartContract/contractExamples/fsanlysis.yjs"); "/Users/hulingxuan/git/SmartContract/contractExamples/fsanlysis.yjs");
contract.setScript(null == content ? "" : content); contract.setScript(null == content ? "" : content);
FSAnalysis.staticVerify(contract); FSAnalysis.staticVerify(contract);
} }

View File

@ -42,9 +42,7 @@ public class MultiSourceTaintAyalysisTest extends MultiSourceTaintAnalysis {
// contractNode = compiler.compile(new FileInputStream(path), "contract_main.yjs"); // contractNode = compiler.compile(new FileInputStream(path), "contract_main.yjs");
// contractNode = compiler.compile(new FileInputStream(path), "DORepo.yjs"); // contractNode = compiler.compile(new FileInputStream(path), "DORepo.yjs");
contractNode = contractNode = compiler.compile(new ZipFile(
compiler.compile(
new ZipFile(
"/Users/huaqiancai/BDWare/BDContract/front-agent/./BDWareProjectDir/publicCompiled/StaticAnalysisExample_2020-07-09-00.ypk")) "/Users/huaqiancai/BDWare/BDContract/front-agent/./BDWareProjectDir/publicCompiled/StaticAnalysisExample_2020-07-09-00.ypk"))
.mergeContractNode(); .mergeContractNode();
DesktopEngine engine = new DesktopEngine(); // engine.loadJar(zf); DesktopEngine engine = new DesktopEngine(); // engine.loadJar(zf);
@ -78,8 +76,6 @@ public class MultiSourceTaintAyalysisTest extends MultiSourceTaintAnalysis {
TaintResult.printer.setLabelOrder(cfg.getLabelOrder()); TaintResult.printer.setLabelOrder(cfg.getLabelOrder());
MultiSourceTaintAnalysis analysis = new MultiSourceTaintAnalysis(cfg); MultiSourceTaintAnalysis analysis = new MultiSourceTaintAnalysis(cfg);
analysis.analysis(); analysis.analysis();
@ -95,7 +91,8 @@ public class MultiSourceTaintAyalysisTest extends MultiSourceTaintAnalysis {
List<Integer> ids = map.get(i); List<Integer> ids = map.get(i);
frontCF.addBB(bb, decompiled, ids, cfg); frontCF.addBB(bb, decompiled, ids, cfg);
Set<BasicBlock> suc = cfg.getSucBlocks(bb); Set<BasicBlock> suc = cfg.getSucBlocks(bb);
for (BasicBlock sucBB : suc) frontCF.addEdge(bb, sucBB); for (BasicBlock sucBB : suc)
frontCF.addEdge(bb, sucBB);
} }
TaintBB bb = cfg.getLastBlock(); TaintBB bb = cfg.getLastBlock();
cfg.printSelf(); cfg.printSelf();
@ -103,7 +100,8 @@ public class MultiSourceTaintAyalysisTest extends MultiSourceTaintAnalysis {
// if(fn.functionName.equals("setDBInfo")) // if(fn.functionName.equals("setDBInfo"))
// cfg.printSelf(); // cfg.printSelf();
if (bb != null) result.put(fn.functionName, bb.getResultWithTaintBit()); if (bb != null)
result.put(fn.functionName, bb.getResultWithTaintBit());
System.out.println("[ContractManager] verifyDone:" + fn.functionName); System.out.println("[ContractManager] verifyDone:" + fn.functionName);
} }
} }

View File

@ -44,8 +44,7 @@ public class PPCountTest extends PPCount {
// flag++; // flag++;
MethodNode mn = methods.get("log"); MethodNode mn = methods.get("log");
if (mn != null) { if (mn != null) {
CFGraph cfg = CFGraph cfg = new CFGraph(mn) {
new CFGraph(mn) {
@Override @Override
public BasicBlock getBasicBlock(int id) { public BasicBlock getBasicBlock(int id) {
return new BasicBlock(id); return new BasicBlock(id);

View File

@ -2,7 +2,6 @@ package org.bdware.sc;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import jdk.nashorn.internal.objects.Global;
import org.bdware.sc.bean.Contract; import org.bdware.sc.bean.Contract;
import org.bdware.sc.engine.JSONTool; import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.util.JsonUtil; import org.bdware.sc.util.JsonUtil;
@ -11,7 +10,8 @@ import org.junit.Test;
public class ExecuteFunctionWithoutLimitTest { public class ExecuteFunctionWithoutLimitTest {
@Test @Test
public void go() { public void go() {
String arg = "{\"funcName\":\"getWriteCandidates\",\"funcArgs\":[\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",[\"04a68e0f34cd28484f67cf4e108eb64b8d565d18ecd916e9049151f97d1553872bf8706b3be9e418b7e6136e627d8e81c82a7ce3fd7045ed5382ae3196aa3ac418\",\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",\"04cd228cc3eeec97d912a5158eb25edfcb37947f9934a7645a3311eeeb06f1af05f155f2019ff1edc716d3d10a79a67714284a06ef16d61ccea80aa6816110d157\"],3,{\"doId\":\"abc\",\"body\":\"abcdefg\"}]}"; String arg =
"{\"funcName\":\"getWriteCandidates\",\"funcArgs\":[\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",[\"04a68e0f34cd28484f67cf4e108eb64b8d565d18ecd916e9049151f97d1553872bf8706b3be9e418b7e6136e627d8e81c82a7ce3fd7045ed5382ae3196aa3ac418\",\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",\"04cd228cc3eeec97d912a5158eb25edfcb37947f9934a7645a3311eeeb06f1af05f155f2019ff1edc716d3d10a79a67714284a06ef16d61ccea80aa6816110d157\"],3,{\"doId\":\"abc\",\"body\":\"abcdefg\"}]}";
JsonObject body = JsonUtil.parseString(arg).getAsJsonObject(); JsonObject body = JsonUtil.parseString(arg).getAsJsonObject();
String funcName = body.get("funcName").getAsString(); String funcName = body.get("funcName").getAsString();
@ -19,13 +19,15 @@ public class ExecuteFunctionWithoutLimitTest {
Object[] funcArgs = JsonUtil.fromJson(arr, Object[].class); Object[] funcArgs = JsonUtil.fromJson(arr, Object[].class);
System.out.println(funcArgs); System.out.println(funcArgs);
} }
@Test @Test
public void go2() { public void go2() {
ContractProcess instance = new ContractProcess(124, "bac"); ContractProcess instance = new ContractProcess(124, "bac");
Contract c = new Contract(); Contract c = new Contract();
c.setScript("contract abc{}"); c.setScript("contract abc{}");
instance.setContract(c); instance.setContract(c);
String arg = "{\"funcName\":\"getWriteCandidates\",\"funcArgs\":[\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",[\"04a68e0f34cd28484f67cf4e108eb64b8d565d18ecd916e9049151f97d1553872bf8706b3be9e418b7e6136e627d8e81c82a7ce3fd7045ed5382ae3196aa3ac418\",\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",\"04cd228cc3eeec97d912a5158eb25edfcb37947f9934a7645a3311eeeb06f1af05f155f2019ff1edc716d3d10a79a67714284a06ef16d61ccea80aa6816110d157\"],3,{\"doId\":\"abc\",\"body\":\"abcdefg\"}]}"; String arg =
"{\"funcName\":\"getWriteCandidates\",\"funcArgs\":[\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",[\"04a68e0f34cd28484f67cf4e108eb64b8d565d18ecd916e9049151f97d1553872bf8706b3be9e418b7e6136e627d8e81c82a7ce3fd7045ed5382ae3196aa3ac418\",\"041016acfbc8f4068a24d38a99a1355449ba958f7e905d66617cec9eda311e3001f8d15a4440b6eb61d7b7bd94bb434b30a518623c1593540e7d32eb72fe8088e1\",\"04cd228cc3eeec97d912a5158eb25edfcb37947f9934a7645a3311eeeb06f1af05f155f2019ff1edc716d3d10a79a67714284a06ef16d61ccea80aa6816110d157\"],3,{\"doId\":\"abc\",\"body\":\"abcdefg\"}]}";
JsonObject body = JsonUtil.parseString(arg).getAsJsonObject(); JsonObject body = JsonUtil.parseString(arg).getAsJsonObject();
String funcName = body.get("funcName").getAsString(); String funcName = body.get("funcName").getAsString();
JsonArray arr = body.getAsJsonArray("funcArgs"); JsonArray arr = body.getAsJsonArray("funcArgs");

View File

@ -8,14 +8,16 @@ import java.math.BigInteger;
public class SM2Test { public class SM2Test {
@Test @Test
public void run() { public void run() {
String str = "{publicKey:\"04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7c0a5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15\",privateKey:\"82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc\"}"; String str =
String pubKey = "04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7c0a5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15"; "{publicKey:\"04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7c0a5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15\",privateKey:\"82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc\"}";
String pubKey =
"04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7c0a5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15";
// 04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7cOa5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15 // 04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7cOa5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15
String privKey = "82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc"; String privKey = "82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc";
// 82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc // 82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc
SM2KeyPair key = new SM2KeyPair( SM2KeyPair key = new SM2KeyPair(SM2KeyPair.publicKeyStr2ECPoint(pubKey),
SM2KeyPair.publicKeyStr2ECPoint(pubKey), new BigInteger(privKey, 16)); new BigInteger(privKey, 16));
System.out.println("hello"); System.out.println("hello");
} }
} }

View File

@ -3,8 +3,10 @@ package org.bdware.sc.blockdb.test;
public class SQLiteTest { public class SQLiteTest {
public static void main(String[] args) { public static void main(String[] args) {
// SqliteDBUtil db = SqliteDBUtil.connect("testdb"); // SqliteDBUtil db = SqliteDBUtil.connect("testdb");
// Block block = db.getBlock("bb68c4a00b251ea350bbb28052eb44b565749586", "480af5c0c74eb471b671edb49bc9db93dc3456e4"); // Block block = db.getBlock("bb68c4a00b251ea350bbb28052eb44b565749586",
// DataInputStream in = new DataInputStream(new ByteArrayInputStream(block.blockheader.prevblockID)); // "480af5c0c74eb471b671edb49bc9db93dc3456e4");
// DataInputStream in = new DataInputStream(new
// ByteArrayInputStream(block.blockheader.prevblockID));
// byte[] b1 = new byte[20]; // byte[] b1 = new byte[20];
// byte[] b2 = new byte[20]; // byte[] b2 = new byte[20];
// byte[] b3 = new byte[20]; // byte[] b3 = new byte[20];

View File

@ -19,7 +19,8 @@ public class ACIndexTest {
DesktopEngine engine = new DesktopEngine(); DesktopEngine engine = new DesktopEngine();
engine.getDesktopGlobal(); engine.getDesktopGlobal();
Context.setGlobal(JavaScriptEntry.getEngineGlobal()); Context.setGlobal(JavaScriptEntry.getEngineGlobal());
ScriptObjectMirror mir = (ScriptObjectMirror) ScriptObjectMirror.wrap(Global.allocate(new int[0]), engine.getDesktopGlobal()); ScriptObjectMirror mir = (ScriptObjectMirror) ScriptObjectMirror
.wrap(Global.allocate(new int[0]), engine.getDesktopGlobal());
mir.setMember("account", "ac1"); mir.setMember("account", "ac1");
mir.setMember("file", "time"); mir.setMember("file", "time");
mir.setMember("dataLength", "32"); mir.setMember("dataLength", "32");
@ -29,7 +30,8 @@ public class ACIndexTest {
for (int i = 0; i < 10000000; i++) { for (int i = 0; i < 10000000; i++) {
mir.setMember("account", "ac1"); mir.setMember("account", "ac1");
mir.setMember("file", "time"); mir.setMember("file", "time");
mir.setMember("content", "61c1dc1d49ccd251b2f73567c776b4607dd36b12fa64e49e7ca53630102d0389"); mir.setMember("content",
"61c1dc1d49ccd251b2f73567c776b4607dd36b12fa64e49e7ca53630102d0389");
mir.setMember("date", 1578042000 + i); mir.setMember("date", 1578042000 + i);
obj = index.manullyIndex(mir); obj = index.manullyIndex(mir);
} }

View File

@ -35,14 +35,15 @@ public class HttpPostTest {
} }
public static String get24Html(String url) { public static String get24Html(String url) {
ProcessBuilder builder = new ProcessBuilder("curl", url, "-H", "Connection: keep-alive", "-H", ProcessBuilder builder = new ProcessBuilder("curl", url, "-H", "Connection: keep-alive",
"Cache-Control: max-age=0", "-H", "Origin: http://162.105.138.123", "-H", "-H", "Cache-Control: max-age=0", "-H", "Origin: http://162.105.138.123", "-H",
"Upgrade-Insecure-Requests: 1", "-H", "Content-Type: application/x-www-form-urlencoded", "-H", "Upgrade-Insecure-Requests: 1", "-H",
"Content-Type: application/x-www-form-urlencoded", "-H",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36",
"-H", "-H",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"-H", "Referer: http://162.105.138.123/net25/query.asp", "-H", "Accept-Encoding: gzip, deflate", "-H", "-H", "Referer: http://162.105.138.123/net25/query.asp", "-H",
"Accept-Language: zh-CN,zh;q=0.9", "-H", "Accept-Encoding: gzip, deflate", "-H", "Accept-Language: zh-CN,zh;q=0.9", "-H",
"Cookie: setstring=%CB%CE%CC%E5%2FBLACK%2F4%2F%C1%A5%CA%E9%2FBLUE%2F2%2F%CB%CE%CC%E5%2Fgreen%2F3%2F%C1%A5%CA%E9%2FBLUE%2F2; clientadd=10%2E1%2E12%2E68; serveradd=162%2E105%2E138%2E123; ASPSESSIONIDAQQTRBDT=HHKDBDKBHGLMACLALGIFGKPO", "Cookie: setstring=%CB%CE%CC%E5%2FBLACK%2F4%2F%C1%A5%CA%E9%2FBLUE%2F2%2F%CB%CE%CC%E5%2Fgreen%2F3%2F%C1%A5%CA%E9%2FBLUE%2F2; clientadd=10%2E1%2E12%2E68; serveradd=162%2E105%2E138%2E123; ASPSESSIONIDAQQTRBDT=HHKDBDKBHGLMACLALGIFGKPO",
"--compressed"); "--compressed");
try { try {
@ -54,14 +55,16 @@ public class HttpPostTest {
} }
public static String getCatalogHtml(String key) { public static String getCatalogHtml(String key) {
ProcessBuilder builder = new ProcessBuilder("curl", "http://162.105.138.123/net25/readns-25.htm", "-H", ProcessBuilder builder = new ProcessBuilder("curl",
"Connection: keep-alive", "-H", "Cache-Control: max-age=0", "-H", "Origin: http://162.105.138.123", "http://162.105.138.123/net25/readns-25.htm", "-H", "Connection: keep-alive", "-H",
"-H", "Upgrade-Insecure-Requests: 1", "-H", "Content-Type: application/x-www-form-urlencoded", "-H", "Cache-Control: max-age=0", "-H", "Origin: http://162.105.138.123", "-H",
"Upgrade-Insecure-Requests: 1", "-H",
"Content-Type: application/x-www-form-urlencoded", "-H",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36",
"-H", "-H",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"-H", "Referer: http://162.105.138.123/net25/query.asp", "-H", "Accept-Encoding: gzip, deflate", "-H", "-H", "Referer: http://162.105.138.123/net25/query.asp", "-H",
"Accept-Language: zh-CN,zh;q=0.9", "-H", "Accept-Encoding: gzip, deflate", "-H", "Accept-Language: zh-CN,zh;q=0.9", "-H",
"Cookie: setstring=%CB%CE%CC%E5%2FBLACK%2F4%2F%C1%A5%CA%E9%2FBLUE%2F2%2F%CB%CE%CC%E5%2Fgreen%2F3%2F%C1%A5%CA%E9%2FBLUE%2F2; clientadd=10%2E1%2E12%2E68; serveradd=162%2E105%2E138%2E123; ASPSESSIONIDAQQTRBDT=HHKDBDKBHGLMACLALGIFGKPO", "Cookie: setstring=%CB%CE%CC%E5%2FBLACK%2F4%2F%C1%A5%CA%E9%2FBLUE%2F2%2F%CB%CE%CC%E5%2Fgreen%2F3%2F%C1%A5%CA%E9%2FBLUE%2F2; clientadd=10%2E1%2E12%2E68; serveradd=162%2E105%2E138%2E123; ASPSESSIONIDAQQTRBDT=HHKDBDKBHGLMACLALGIFGKPO",
"--compressed"); "--compressed");
try { try {
@ -73,14 +76,16 @@ public class HttpPostTest {
} }
public static String query24(String keyword) { public static String query24(String keyword) {
ProcessBuilder builder = new ProcessBuilder("curl", "http://162.105.138.123/net25/readwhole.asp", "-H", ProcessBuilder builder = new ProcessBuilder("curl",
"Connection: keep-alive", "-H", "Cache-Control: max-age=0", "-H", "Origin: http://162.105.138.123", "http://162.105.138.123/net25/readwhole.asp", "-H", "Connection: keep-alive", "-H",
"-H", "Upgrade-Insecure-Requests: 1", "-H", "Content-Type: application/x-www-form-urlencoded", "-H", "Cache-Control: max-age=0", "-H", "Origin: http://162.105.138.123", "-H",
"Upgrade-Insecure-Requests: 1", "-H",
"Content-Type: application/x-www-form-urlencoded", "-H",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36",
"-H", "-H",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"-H", "Referer: http://162.105.138.123/net25/query.asp", "-H", "Accept-Encoding: gzip, deflate", "-H", "-H", "Referer: http://162.105.138.123/net25/query.asp", "-H",
"Accept-Language: zh-CN,zh;q=0.9", "-H", "Accept-Encoding: gzip, deflate", "-H", "Accept-Language: zh-CN,zh;q=0.9", "-H",
"Cookie: setstring=%CB%CE%CC%E5%2FBLACK%2F4%2F%C1%A5%CA%E9%2FBLUE%2F2%2F%CB%CE%CC%E5%2Fgreen%2F3%2F%C1%A5%CA%E9%2FBLUE%2F2; clientadd=10%2E1%2E12%2E68; serveradd=162%2E105%2E138%2E123; ASPSESSIONIDAQQTRBDT=HHKDBDKBHGLMACLALGIFGKPO", "Cookie: setstring=%CB%CE%CC%E5%2FBLACK%2F4%2F%C1%A5%CA%E9%2FBLUE%2F2%2F%CB%CE%CC%E5%2Fgreen%2F3%2F%C1%A5%CA%E9%2FBLUE%2F2; clientadd=10%2E1%2E12%2E68; serveradd=162%2E105%2E138%2E123; ASPSESSIONIDAQQTRBDT=HHKDBDKBHGLMACLALGIFGKPO",
"--data", "--data",
"query=_keyword&B1=%BC%EC+%CB%F7&colid=2.0&colid=2.1&colid=2.14&colid=2.25&colid=2.34&colid=2.65&colid=2.136&colid=2.138" "query=_keyword&B1=%BC%EC+%CB%F7&colid=2.0&colid=2.1&colid=2.14&colid=2.25&colid=2.34&colid=2.65&colid=2.136&colid=2.138"

View File

@ -20,8 +20,9 @@ public class LedgerUtilTest {
System.out.println(c.clientVersionSync().getVersion()); System.out.println(c.clientVersionSync().getVersion());
System.out.println(c.getLedgersSync().toString()); System.out.println(c.getLedgersSync().toString());
String from = "0xb60e8dd61c5d32be8058bb8eb970870f07233155"; String from = "0xb60e8dd61c5d32be8058bb8eb970870f07233155";
LedgerProto.SendTransactionResponse ret = c.sendTransactionSync("bdcontract", CommonProto.TransactionType.MESSAGE, LedgerProto.SendTransactionResponse ret =
from, System.currentTimeMillis(), from, "hello".getBytes(StandardCharsets.UTF_8)); c.sendTransactionSync("bdcontract", CommonProto.TransactionType.MESSAGE, from,
System.currentTimeMillis(), from, "hello".getBytes(StandardCharsets.UTF_8));
System.out.println("=====" + HashUtil.byteArray2Str(ret.getHash().toByteArray())); System.out.println("=====" + HashUtil.byteArray2Str(ret.getHash().toByteArray()));
} }
@ -44,13 +45,15 @@ public class LedgerUtilTest {
String hash = ByteUtil.encodeBASE64(bytes); String hash = ByteUtil.encodeBASE64(bytes);
System.out.println(URLEncoder.encode(hash)); System.out.println(URLEncoder.encode(hash));
} }
@Test @Test
public void readData() { public void readData() {
String hash = "kNkTGrOLKlMiVHiCx/Ik3Tx3DDI="; String hash = "kNkTGrOLKlMiVHiCx/Ik3Tx3DDI=";
hash = "mEoVJx4k2L5nhKY6exjtJWmU7RA="; hash = "mEoVJx4k2L5nhKY6exjtJWmU7RA=";
hash = "OTg0YTE1MjcxZTI0ZDhiZTY3ODRhNjNhN2IxOGVkMjU2OTk0ZWQxMA=="; hash = "OTg0YTE1MjcxZTI0ZDhiZTY3ODRhNjNhN2IxOGVkMjU2OTk0ZWQxMA==";
byte[] data = ByteUtil.decodeBASE64(hash); byte[] data = ByteUtil.decodeBASE64(hash);
//<ByteString@67aaeb8d size=20 contents="<D\206P!\241\005\017\366\321\312\336\323cWiS>\226\207"> // <ByteString@67aaeb8d size=20
// contents="<D\206P!\241\005\017\366\321\312\336\323cWiS>\226\207">
// System.out.println(new String(data)); // System.out.println(new String(data));
} }
} }

View File

@ -18,7 +18,8 @@ public class SQLUtilTest {
// 1.getConnection()方法连接MySQL数据库 // 1.getConnection()方法连接MySQL数据库
con = DriverManager.getConnection(url, user, password); con = DriverManager.getConnection(url, user, password);
if (!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); if (!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
// 2.创建statement类对象用来执行SQL语句 // 2.创建statement类对象用来执行SQL语句
Statement statement = con.createStatement(); Statement statement = con.createStatement();

View File

@ -9,8 +9,12 @@ import org.junit.Test;
public class ArgSchemaTest { public class ArgSchemaTest {
@Test @Test
public void test1() { public void test1() {
JsonObject realData=JsonParser.parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}],\"doId\":1}").getAsJsonObject(); JsonObject realData = JsonParser
JsonObject schema=JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"doId\":\"number\"}").getAsJsonObject(); .parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}],\"doId\":1}")
.getAsJsonObject();
JsonObject schema =
JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"doId\":\"number\"}")
.getAsJsonObject();
ArgSchemaVisitor visitor = new ArgSchemaVisitor(realData); ArgSchemaVisitor visitor = new ArgSchemaVisitor(realData);
@ -18,10 +22,16 @@ public class ArgSchemaTest {
System.out.println(visitor.getStatus()); System.out.println(visitor.getStatus());
System.out.println(visitor.getException().toString()); System.out.println(visitor.getException().toString());
} }
@Test @Test
public void test2() { public void test2() {
JsonObject realData=JsonParser.parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}],\"doId\":\"string\"}").getAsJsonObject(); JsonObject realData = JsonParser
JsonObject schema=JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"doId\":\"number\"}").getAsJsonObject(); .parseString(
"{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}],\"doId\":\"string\"}")
.getAsJsonObject();
JsonObject schema =
JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"doId\":\"number\"}")
.getAsJsonObject();
ArgSchemaVisitor visitor = new ArgSchemaVisitor(realData); ArgSchemaVisitor visitor = new ArgSchemaVisitor(realData);
@ -30,6 +40,7 @@ public class ArgSchemaTest {
System.out.println(visitor.getException().toString()); System.out.println(visitor.getException().toString());
System.out.println(visitor.errorCode); System.out.println(visitor.errorCode);
} }
@Test @Test
public void test3() { public void test3() {
JsonElement realData = JsonParser.parseString("data.json"); JsonElement realData = JsonParser.parseString("data.json");
@ -46,8 +57,12 @@ public class ArgSchemaTest {
// 缺少必选项 // 缺少必选项
@Test @Test
public void test4() { public void test4() {
JsonObject realData=JsonParser.parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}]}").getAsJsonObject(); JsonObject realData =
JsonObject schema=JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"!doId\":\"string\"}").getAsJsonObject(); JsonParser.parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}]}")
.getAsJsonObject();
JsonObject schema =
JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"!doId\":\"string\"}")
.getAsJsonObject();
ArgSchemaVisitor visitor = new ArgSchemaVisitor(realData); ArgSchemaVisitor visitor = new ArgSchemaVisitor(realData);
visitor.visit(schema); visitor.visit(schema);
System.out.println(visitor.getStatus()); System.out.println(visitor.getStatus());

View File

@ -6,8 +6,10 @@ import org.bdware.sc.engine.hook.MaskVisitor;
public class MaskVisitorTest { public class MaskVisitorTest {
public static void main(String[] args) { public static void main(String[] args) {
String mask = "[{\"score\":\"md5\",\"name\":\"fpe\",\"grade\":\"edp\",\"number\":\"aes\",\"info\":{\"age\":\"edp\",\"sex\":\"md5\"}}]"; String mask =
String data = "[{\"score\":11,\"name\":\"ccq\",\"grade\":98.5,\"number\":2001210533,\"info\":{\"age\":\"18\",\"sex\":\"m\"}},{\"score\":11,\"name\":\"ccq\",\"grade\":98.5,\"number\":2001210533}]"; "[{\"score\":\"md5\",\"name\":\"fpe\",\"grade\":\"edp\",\"number\":\"aes\",\"info\":{\"age\":\"edp\",\"sex\":\"md5\"}}]";
String data =
"[{\"score\":11,\"name\":\"ccq\",\"grade\":98.5,\"number\":2001210533,\"info\":{\"age\":\"18\",\"sex\":\"m\"}},{\"score\":11,\"name\":\"ccq\",\"grade\":98.5,\"number\":2001210533}]";
String m1 = "{\"score\":\"edp\",\"name\":\"md5\"}"; String m1 = "{\"score\":\"edp\",\"name\":\"md5\"}";
String d1 = "{\"score\":\"95\",\"name\":\"zzz\"}"; String d1 = "{\"score\":\"95\",\"name\":\"zzz\"}";

View File

@ -35,7 +35,8 @@ public class MockUtilTest {
Object ret = MockUtil.mock(ele2.toString()); Object ret = MockUtil.mock(ele2.toString());
// System.out.println( // System.out.println(
// (JSONTool.copy((jdk.nashorn.api.scripting.ScriptObjectMirror) mock(ele2.toString()))).toString()); // (JSONTool.copy((jdk.nashorn.api.scripting.ScriptObjectMirror)
// mock(ele2.toString()))).toString());
System.out.println(MockUtil.mock("'@string'")); System.out.println(MockUtil.mock("'@string'"));
} }

View File

@ -24,45 +24,32 @@ public class MemoryDumpRecoverTest {
return sb.toString(); return sb.toString();
} }
/* //仅支持public路径下测试 /*
public static void memoryRecover(String contractName) { * //仅支持public路径下测试 public static void memoryRecover(String contractName) { String name =
String name = contractName + "/" + contractName; * contractName + "/" + contractName;
*
//启动合约 * //启动合约 ContractManager cm2 = new ContractManager(); cm2.yjsPath = JudgeStatus.yjsPath;
ContractManager cm2 = new ContractManager(); * Contract c = new Contract(); c.setType(ContractType.Sole); String id = "169412582";
cm2.yjsPath = JudgeStatus.yjsPath; * c.setID(id); c.setScript(RedoRecoverTest.file2Str(
Contract c = new Contract(); * "/Users/zhangyixuan/Lab/newProject/BDContract/front-agent/BDWareProjectDir/public/" + name +
c.setType(ContractType.Sole); * ".yjs")); String key =
String id = "169412582"; * "{\"publicKey\":\"041d7b4818817736b3d64305675f04e9a00a12ce23c72e6740f83785edcffec6bae2c178fbc934f66d72e26f89a2e7a2c966dc3f0a8e415663c9b933af7a2e9ff8\",\"privateKey\":\"18505919022281880113072981827955639221458448578012075254857346196103069175443\"}";
c.setID(id); * SM2KeyPair pair = SM2KeyPair.fromJson(key); c.doSignature(pair);
c.setScript(RedoRecoverTest.file2Str("/Users/zhangyixuan/Lab/newProject/BDContract/front-agent/BDWareProjectDir/public/" + name + ".yjs")); * System.out.println("<<<Start a contract>>> : " + cm2.startContractAndRedirect(c, null));
String key = "{\"publicKey\":\"041d7b4818817736b3d64305675f04e9a00a12ce23c72e6740f83785edcffec6bae2c178fbc934f66d72e26f89a2e7a2c966dc3f0a8e415663c9b933af7a2e9ff8\",\"privateKey\":\"18505919022281880113072981827955639221458448578012075254857346196103069175443\"}"; *
SM2KeyPair pair = SM2KeyPair.fromJson(key); *
c.doSignature(pair); *
System.out.println("<<<Start a contract>>> : " + cm2.startContractAndRedirect(c, null)); *
* //loadMemory long time1 = System.currentTimeMillis(); File mem = new
* File("./cp/recoverTestFiles/memory/" + contractName + ".txt"); String res =
* cm2.loadMemory(contractName, mem.getAbsolutePath()); long time2 = System.currentTimeMillis();
* try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch
//loadMemory * block e.printStackTrace(); } System.out.println("<<<Load memory>>> : " + res); double cost =
long time1 = System.currentTimeMillis(); * ((double)time2 - (double)time1)/1000; System.out.println("load memory 用时" + cost + "s");
File mem = new File("./cp/recoverTestFiles/memory/" + contractName + ".txt"); *
String res = cm2.loadMemory(contractName, mem.getAbsolutePath()); *
long time2 = System.currentTimeMillis(); * String content1 = MemoryDumpUtil.getContentFromFile(mem.getAbsolutePath()); String content2 =
try { * cm2.dumpContract(contractName, ""); System.out.println("load之后dump : \n" + content2 +
Thread.sleep(3000); * "\n\n"); System.out.println(content1.equals(content2)); }
} catch (InterruptedException e) { */
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("<<<Load memory>>> : " + res);
double cost = ((double)time2 - (double)time1)/1000;
System.out.println("load memory 用时" + cost + "s");
String content1 = MemoryDumpUtil.getContentFromFile(mem.getAbsolutePath());
String content2 = cm2.dumpContract(contractName, "");
System.out.println("load之后dump : \n" + content2 + "\n\n");
System.out.println(content1.equals(content2));
}*/
} }

View File

@ -8,55 +8,36 @@ public class MemoryDumpTest {
// memoryRecord("Test","Test1"); // memoryRecord("Test","Test1");
} }
/* //仅支持public路径下测试 /*
public static void memoryRecord(String contractName,String argsFileName) { * //仅支持public路径下测试 public static void memoryRecord(String contractName,String argsFileName) {
String name = contractName + "/" + contractName; * String name = contractName + "/" + contractName;
*
//启动合约 * //启动合约 ContractManager cm1 = new ContractManager(); cm1.yjsPath = JudgeStatus.yjsPath;
ContractManager cm1 = new ContractManager(); * Contract c = new Contract(); c.setType(ContractType.Sole); String id = "169412582";
cm1.yjsPath = JudgeStatus.yjsPath; * c.setID(id); c.setScript(RedoRecoverTest.file2Str(
Contract c = new Contract(); * "/Users/zhangyixuan/Lab/newProject/BDContract/front-agent/BDWareProjectDir/public/" + name +
c.setType(ContractType.Sole); * ".yjs")); String key =
String id = "169412582"; * "{\"publicKey\":\"041d7b4818817736b3d64305675f04e9a00a12ce23c72e6740f83785edcffec6bae2c178fbc934f66d72e26f89a2e7a2c966dc3f0a8e415663c9b933af7a2e9ff8\",\"privateKey\":\"18505919022281880113072981827955639221458448578012075254857346196103069175443\"}";
c.setID(id); * SM2KeyPair pair = SM2KeyPair.fromJson(key); c.doSignature(pair);
c.setScript(RedoRecoverTest.file2Str("/Users/zhangyixuan/Lab/newProject/BDContract/front-agent/BDWareProjectDir/public/" + name + ".yjs")); * System.out.println("<<<Start a contract>>> : " + cm1.startContractAndRedirect(c, null));
String key = "{\"publicKey\":\"041d7b4818817736b3d64305675f04e9a00a12ce23c72e6740f83785edcffec6bae2c178fbc934f66d72e26f89a2e7a2c966dc3f0a8e415663c9b933af7a2e9ff8\",\"privateKey\":\"18505919022281880113072981827955639221458448578012075254857346196103069175443\"}"; *
SM2KeyPair pair = SM2KeyPair.fromJson(key); *
c.doSignature(pair); *
System.out.println("<<<Start a contract>>> : " + cm1.startContractAndRedirect(c, null)); * //执行事务 int count = 0; ContractRequest cor = new ContractRequest();
* cor.setContractID(contractName); cor.doSignature(pair); File file = new
* File("./cp/recoverTestFiles/affairs/" + contractName + "/" + argsFileName); try { FileReader
* fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String s = null;
//执行事务 * while((s=br.readLine()) != null) { String[] strs = s.split(" "); cor.setAction(strs[0]);
int count = 0; * cor.setArg(strs[1]); System.out.println("<<<execute the contract>> NO." + (++count) +
ContractRequest cor = new ContractRequest(); * " [Result]" + cm1.execute(cor,null)); } } catch (IOException e1) { // TODO Auto-generated
cor.setContractID(contractName); * catch block e1.printStackTrace(); }
cor.doSignature(pair); *
File file = new File("./cp/recoverTestFiles/affairs/" + contractName + "/" + argsFileName); *
try { * //memoryDump long time1 = System.currentTimeMillis(); File mem = new
FileReader fr = new FileReader(file); * File("./cp/recoverTestFiles/memory/" + contractName + ".txt"); String memory =
BufferedReader br = new BufferedReader(fr); * cm1.dumpContract(contractName,mem.getAbsolutePath()); System.out.println("memory\n" +
String s = null; * memory); long time2 = System.currentTimeMillis(); double cost = ((double)time2 -
while((s=br.readLine()) != null) { * (double)time1)/1000; System.out.println("" + count + "项事务dump memory 用时" + cost + "s"); }
String[] strs = s.split(" "); */
cor.setAction(strs[0]);
cor.setArg(strs[1]);
System.out.println("<<<execute the contract>> NO." + (++count) + " [Result]" + cm1.execute(cor,null));
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//memoryDump
long time1 = System.currentTimeMillis();
File mem = new File("./cp/recoverTestFiles/memory/" + contractName + ".txt");
String memory = cm1.dumpContract(contractName,mem.getAbsolutePath());
System.out.println("memory\n" + memory);
long time2 = System.currentTimeMillis();
double cost = ((double)time2 - (double)time1)/1000;
System.out.println("" + count + "项事务dump memory 用时" + cost + "s");
}*/
} }

View File

@ -18,7 +18,8 @@ import java.io.InputStream;
public class YJSParserTest { public class YJSParserTest {
@Test @Test
public void elseTest() throws IOException { public void elseTest() throws IOException {
InputStream resource = YJSParserTest.class.getClassLoader().getResourceAsStream("module1.yjs"); InputStream resource =
YJSParserTest.class.getClassLoader().getResourceAsStream("module1.yjs");
JavaScriptLexer lexer; JavaScriptLexer lexer;
assert resource != null; assert resource != null;
lexer = new JavaScriptLexer(CharStreams.fromStream(resource)); lexer = new JavaScriptLexer(CharStreams.fromStream(resource));
@ -37,7 +38,8 @@ public class YJSParserTest {
@Test @Test
public void functionTest() throws IOException { public void functionTest() throws IOException {
InputStream resource = YJSParserTest.class.getClassLoader().getResourceAsStream("function.yjs"); InputStream resource =
YJSParserTest.class.getClassLoader().getResourceAsStream("function.yjs");
JavaScriptLexer lexer; JavaScriptLexer lexer;
assert resource != null; assert resource != null;
lexer = new JavaScriptLexer(CharStreams.fromStream(resource)); lexer = new JavaScriptLexer(CharStreams.fromStream(resource));
@ -50,7 +52,8 @@ public class YJSParserTest {
parser.addErrorListener(errorListener); parser.addErrorListener(errorListener);
parser.addErrorListener(new DiagnosticErrorListener()); parser.addErrorListener(new DiagnosticErrorListener());
YJSParser.ProgramContext tree = parser.program(); YJSParser.ProgramContext tree = parser.program();
for (YJSParser.ClzOrFunctionDeclarationContext clzOrFunc : tree.contractDeclar().clzOrFunctionDeclaration()) { for (YJSParser.ClzOrFunctionDeclarationContext clzOrFunc : tree.contractDeclar()
.clzOrFunctionDeclaration()) {
System.out.println(clzOrFunc.functionDeclaration().View()); System.out.println(clzOrFunc.functionDeclaration().View());
} }
for (String str : errorListener.getResultList()) { for (String str : errorListener.getResultList()) {

View File

@ -21,26 +21,18 @@ public class ExecuteContractTest {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
String testDir = "./scripts/test/"; String testDir = "./scripts/test/";
File f = new File(testDir); File f = new File(testDir);
if (!f.exists()) f.mkdirs(); if (!f.exists())
String[] confs = f.mkdirs();
new String[]{ String[] confs = new String[] {"HelloAtMac", "AnalysisAtMac", "TFAtMac", "HelloAtAli",
"HelloAtMac", "AnalysisAtAli", "TFAtAli"};
"AnalysisAtMac",
"TFAtMac",
"HelloAtAli",
"AnalysisAtAli",
"TFAtAli"
};
// http://59.110.5.194:8080/ // http://59.110.5.194:8080/
String[] urls = String[] urls = new String[] {
new String[]{
"http://127.0.0.1:18000/SCIDE/CMManager?action=executeContract&&contractID=HelloAtMac&operation=get&arg=world", "http://127.0.0.1:18000/SCIDE/CMManager?action=executeContract&&contractID=HelloAtMac&operation=get&arg=world",
"http://127.0.0.1:18000/SCIDE/CMManager?action=executeContract&&contractID=AppDataContractAtMac&operation=connectDBAndQuery&arg=%7B%22type%22%3A%22takeout%22%2C%22detail%22%3A%22overall%22%2C%22district%22%3A%22%E5%AF%86%E4%BA%91%22%7D&requestID=1576408475257_93", "http://127.0.0.1:18000/SCIDE/CMManager?action=executeContract&&contractID=AppDataContractAtMac&operation=connectDBAndQuery&arg=%7B%22type%22%3A%22takeout%22%2C%22detail%22%3A%22overall%22%2C%22district%22%3A%22%E5%AF%86%E4%BA%91%22%7D&requestID=1576408475257_93",
"http://127.0.0.1:18000/SCIDE/CMManager?action=executeContract&&contractID=ImageMatcherAtMac&operation=testLocal&arg=%2Fimgs%2Fcup.jpg", "http://127.0.0.1:18000/SCIDE/CMManager?action=executeContract&&contractID=ImageMatcherAtMac&operation=testLocal&arg=%2Fimgs%2Fcup.jpg",
"http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=HelloAt59&operation=get&arg=world", "http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=HelloAt59&operation=get&arg=world",
"http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=AppDataContractAt59&operation=connectDBAndQuery&arg=%7B%22type%22%3A%22takeout%22%2C%22detail%22%3A%22overall%22%2C%22district%22%3A%22%E5%AF%86%E4%BA%91%22%7D&requestID=1576408475257_93", "http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=AppDataContractAt59&operation=connectDBAndQuery&arg=%7B%22type%22%3A%22takeout%22%2C%22detail%22%3A%22overall%22%2C%22district%22%3A%22%E5%AF%86%E4%BA%91%22%7D&requestID=1576408475257_93",
"http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=ImageMatcherAt59&operation=testLocal&arg=%2Fimgs%2Fcup.jpg" "http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=ImageMatcherAt59&operation=testLocal&arg=%2Fimgs%2Fcup.jpg"};
};
// String[] urls = new String[] { // String[] urls = new String[] {
// //
@ -54,7 +46,8 @@ public class ExecuteContractTest {
// //
// "http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=AppDataContractAtMac&operation=connectDBAndQuery&arg=%7B%22type%22%3A%22takeout%22%2C%22detail%22%3A%22overall%22%2C%22district%22%3A%22%E5%AF%86%E4%BA%91%22%7D&requestID=1576408475257_93", // "http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=AppDataContractAtMac&operation=connectDBAndQuery&arg=%7B%22type%22%3A%22takeout%22%2C%22detail%22%3A%22overall%22%2C%22district%22%3A%22%E5%AF%86%E4%BA%91%22%7D&requestID=1576408475257_93",
// //
// "http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=ImageMatcherAtMac&operation=testLocal&arg=%2Fimgs%2Fcup.jpg" }; // "http://59.110.5.194:8080/SCIDE/CMManager?action=executeContract&&contractID=ImageMatcherAtMac&operation=testLocal&arg=%2Fimgs%2Fcup.jpg"
// };
String output = "./scripts/test/executeContract_cross.txt"; String output = "./scripts/test/executeContract_cross.txt";
FileOutputStream fout = new FileOutputStream(output, true); FileOutputStream fout = new FileOutputStream(output, true);
@ -82,10 +75,10 @@ public class ExecuteContractTest {
// System.out.println("http result:" + r.response); // System.out.println("http result:" + r.response);
if (r.get("response").toString().contains("busy")) if (r.get("response").toString().contains("busy"))
c.busy.incrementAndGet(); c.busy.incrementAndGet();
else c.success.incrementAndGet(); else
c.success.incrementAndGet();
JsonObject jo = JsonObject jo =
JsonParser.parseString(r.get("response").toString()) JsonParser.parseString(r.get("response").toString()).getAsJsonObject();
.getAsJsonObject();
int exeTime = jo.get("executeTime").getAsInt(); int exeTime = jo.get("executeTime").getAsInt();
out.println(conf + "\t" + exeTime); out.println(conf + "\t" + exeTime);
}); });

View File

@ -36,11 +36,9 @@ public class PermissionStubDocGenerator {
List<Method> methodList = Arrays.asList(methods); List<Method> methodList = Arrays.asList(methods);
methodList.sort(Comparator.comparing(Method::getName)); methodList.sort(Comparator.comparing(Method::getName));
System.out.println("## " + stub.permission() + "util\n"); System.out.println("## " + stub.permission() + "util\n");
System.out.printf( System.out.printf("可以使用@Permission(\"%s\")来引入%s对象。%n", stub.permission(),
"可以使用@Permission(\"%s\")来引入%s对象。%n", stub.permission() + "util");
stub.permission(), stub.permission() + "util"); System.out.printf("```\n@Permission(\"%s\")\ncontract %sExample{\n ...\n}\n```\n%n",
System.out.printf(
"```\n@Permission(\"%s\")\ncontract %sExample{\n ...\n}\n```\n%n",
stub.permission(), stub.permission()); stub.permission(), stub.permission());
for (Method m : methods) { for (Method m : methods) {
@ -52,15 +50,14 @@ public class PermissionStubDocGenerator {
System.out.println("|---|---|---|"); System.out.println("|---|---|---|");
int i = 1; int i = 1;
for (Parameter p : parameters) { for (Parameter p : parameters) {
System.out.printf( System.out.printf("| %d | %s | %s |%n", i, p.getName(),
"| %d | %s | %s |%n", p.getType().getCanonicalName());
i, p.getName(), p.getType().getCanonicalName());
i++; i++;
} }
System.out.println("\n#### 使用示例\n"); System.out.println("\n#### 使用示例\n");
System.out.println("```javascript"); System.out.println("```javascript");
System.out.println( System.out
"var ret = " + stub.permission() + "Util." + m.getName() + "();"); .println("var ret = " + stub.permission() + "Util." + m.getName() + "();");
System.out.println("```"); System.out.println("```");
} }
} }

View File

@ -13,26 +13,18 @@ public class StartContractTest {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
String testDir = "./scripts/test/"; String testDir = "./scripts/test/";
File f = new File(testDir); File f = new File(testDir);
if (!f.exists()) f.mkdirs(); if (!f.exists())
String[] confs = f.mkdirs();
new String[] { String[] confs = new String[] {"HelloAtMac", "AnalysisAtMac", "TFAtMac", "HelloAtAli",
"HelloAtMac", "AnalysisAtAli", "TFAtAli"};
"AnalysisAtMac",
"TFAtMac",
"HelloAtAli",
"AnalysisAtAli",
"TFAtAli"
};
// http://59.110.5.194:8080/ // http://59.110.5.194:8080/
String[] urls = String[] urls = new String[] {
new String[] {
"http://127.0.0.1:18000/SCIDE/CMManager?action=startContractBatched&fileList=[A2.yjs]", "http://127.0.0.1:18000/SCIDE/CMManager?action=startContractBatched&fileList=[A2.yjs]",
"http://127.0.0.1:18000/SCIDE/CMManager?action=startContractBatched&fileList=[EleAnalysis.yjs]", "http://127.0.0.1:18000/SCIDE/CMManager?action=startContractBatched&fileList=[EleAnalysis.yjs]",
"http://127.0.0.1:18000/SCIDE/CMManager?action=startContract&owner=04266aa345154d8e224990e33dd47a3203dd927d8c4f6420f63fbab063d9ecb8c4d58751e81940f2092dc4609de22a1980f4d8df39730ba0ddd453e3fa3b7b2a6b&requestID=1576403183009&contractid=Hello&script=empty&path=/Tensorflow/imagematch.yjs&signature=815490e34a3c85bcfe54a740f91e8739cfd6e5daa6c73084de758705e754a43bb245c5c23ff9f46c2a99cc0d627d4cf1da583e20073e85455f6cb10c63bef86b", "http://127.0.0.1:18000/SCIDE/CMManager?action=startContract&owner=04266aa345154d8e224990e33dd47a3203dd927d8c4f6420f63fbab063d9ecb8c4d58751e81940f2092dc4609de22a1980f4d8df39730ba0ddd453e3fa3b7b2a6b&requestID=1576403183009&contractid=Hello&script=empty&path=/Tensorflow/imagematch.yjs&signature=815490e34a3c85bcfe54a740f91e8739cfd6e5daa6c73084de758705e754a43bb245c5c23ff9f46c2a99cc0d627d4cf1da583e20073e85455f6cb10c63bef86b",
"http://59.110.5.194:8080/SCIDE/CMManager?action=startContractBatched&fileList=[A2.yjs]", "http://59.110.5.194:8080/SCIDE/CMManager?action=startContractBatched&fileList=[A2.yjs]",
"http://59.110.5.194:8080/SCIDE/CMManager?action=startContractBatched&fileList=[EleAnalysis.yjs]", "http://59.110.5.194:8080/SCIDE/CMManager?action=startContractBatched&fileList=[EleAnalysis.yjs]",
"http://59.110.5.194:8080/SCIDE/CMManager?action=startContract&owner=04266aa345154d8e224990e33dd47a3203dd927d8c4f6420f63fbab063d9ecb8c4d58751e81940f2092dc4609de22a1980f4d8df39730ba0ddd453e3fa3b7b2a6b&requestID=1576403183009&contractid=Hello&script=empty&path=/Tensorflow/imagematch.yjs&signature=815490e34a3c85bcfe54a740f91e8739cfd6e5daa6c73084de758705e754a43bb245c5c23ff9f46c2a99cc0d627d4cf1da583e20073e85455f6cb10c63bef86b" "http://59.110.5.194:8080/SCIDE/CMManager?action=startContract&owner=04266aa345154d8e224990e33dd47a3203dd927d8c4f6420f63fbab063d9ecb8c4d58751e81940f2092dc4609de22a1980f4d8df39730ba0ddd453e3fa3b7b2a6b&requestID=1576403183009&contractid=Hello&script=empty&path=/Tensorflow/imagematch.yjs&signature=815490e34a3c85bcfe54a740f91e8739cfd6e5daa6c73084de758705e754a43bb245c5c23ff9f46c2a99cc0d627d4cf1da583e20073e85455f6cb10c63bef86b"};
};
String output = "./scripts/test/startContract.txt"; String output = "./scripts/test/startContract.txt";
FileOutputStream fout = new FileOutputStream(output, true); FileOutputStream fout = new FileOutputStream(output, true);

View File

@ -5,19 +5,8 @@ import com.google.gson.JsonParser;
import org.bdware.sc.http.HttpUtil; import org.bdware.sc.http.HttpUtil;
import org.junit.Test; import org.junit.Test;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.sql.*; import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class setMaskTest { public class setMaskTest {
@Test @Test
public void test1() { public void test1() {
@ -27,9 +16,11 @@ public class setMaskTest {
String operation = "hello1"; String operation = "hello1";
String maskInfo = "\"md5\""; String maskInfo = "\"md5\"";
maskInfo = ""; maskInfo = "";
String pubkey="04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7"; String pubkey =
"04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7";
System.out.println(url); System.out.println(url);
String sign="30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79"; String sign =
"30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79";
// url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign; // url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign;
url += "&contractID=" + contractID + "&operation=" + operation + "&maskInfo=" + maskInfo; url += "&contractID=" + contractID + "&operation=" + operation + "&maskInfo=" + maskInfo;
// url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9"; // url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9";
@ -41,6 +32,7 @@ public class setMaskTest {
String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); String resp = HttpUtil.httpGet(url.toString()).get("response").toString();
System.out.println(resp); System.out.println(resp);
} }
@Test @Test
public void testSetMock() { public void testSetMock() {
@ -49,9 +41,11 @@ public class setMaskTest {
String operation = "hello1"; String operation = "hello1";
String mockInfo = "\"@string\""; String mockInfo = "\"@string\"";
// String mockInfo=""; // String mockInfo="";
String pubkey="04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7"; String pubkey =
"04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7";
System.out.println(url); System.out.println(url);
String sign="30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79"; String sign =
"30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79";
// url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign; // url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign;
url += "&contractID=" + contractID + "&operation=" + operation + "&mockInfo=" + mockInfo; url += "&contractID=" + contractID + "&operation=" + operation + "&mockInfo=" + mockInfo;
// url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9"; // url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9";
@ -63,6 +57,7 @@ public class setMaskTest {
String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); String resp = HttpUtil.httpGet(url.toString()).get("response").toString();
System.out.println(resp); System.out.println(resp);
} }
@Test @Test
public void testGetMock() { public void testGetMock() {
@ -70,9 +65,11 @@ public class setMaskTest {
String contractID = "Hello1"; String contractID = "Hello1";
String operation = "hello1"; String operation = "hello1";
String mockInfo = "@string"; String mockInfo = "@string";
String pubkey="04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7"; String pubkey =
"04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7";
System.out.println(url); System.out.println(url);
String sign="30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79"; String sign =
"30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79";
// url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign; // url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign;
url += "&contractID=" + contractID + "&operation=" + operation; url += "&contractID=" + contractID + "&operation=" + operation;
// url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9"; // url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9";
@ -84,6 +81,7 @@ public class setMaskTest {
String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); String resp = HttpUtil.httpGet(url.toString()).get("response").toString();
System.out.println(resp); System.out.println(resp);
} }
@Test @Test
public void test3() { public void test3() {
@ -91,9 +89,11 @@ public class setMaskTest {
String contractID = "Hello"; String contractID = "Hello";
String operation = "hello3"; String operation = "hello3";
String maskInfo = ""; String maskInfo = "";
String pubkey="04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7"; String pubkey =
"04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7";
System.out.println(url); System.out.println(url);
String sign="30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79"; String sign =
"30440220138c8ae1956f6af19ddb24b9a0fe5cf9cc4f8ecd25537a8b5c4dcd5f30a4f985022026475279687ccdfb112cbcc307e573333d80f45386281def4df54b8b7532ed79";
// url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign; // url+="&contractID="+contractID+"&operation="+operation+"&maskInfo="+maskInfo+"&pubkey="+pubkey+"&signature="+sign;
url += "&contractID=" + contractID + "&operation=" + operation + "&maskInfo=" + maskInfo; url += "&contractID=" + contractID + "&operation=" + operation + "&maskInfo=" + maskInfo;
// url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9"; // url="http://127.0.0.1:21030/SCIDE/CMManager?action=setMask&&pubkey=04c111cde30c257eb9d891653e2a25eb15df5239dd9882389e8daeffd4b16f65f30b30688b58d3e2eaf25ce5a529a601e4924581b55cedf78d94d17864b73c51a7&signature=304602210082f33a4cdbf483428c701753eb08ca430f855d52df18547a367fe14ee638761f022100cab7fa189b03248b54f3cb679d7df6c2548f6743256cad6ee772c532bb34bdf9";
@ -105,12 +105,14 @@ public class setMaskTest {
String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); String resp = HttpUtil.httpGet(url.toString()).get("response").toString();
System.out.println(resp); System.out.println(resp);
} }
@Test @Test
public void test2() { public void test2() {
String s1 = "{\"score\":\"md5\",\"name\":\"aes\"}"; String s1 = "{\"score\":\"md5\",\"name\":\"aes\"}";
JsonElement je1 = JsonParser.parseString("{\"score\":\"md5\",\"name\":\"aes\"}"); JsonElement je1 = JsonParser.parseString("{\"score\":\"md5\",\"name\":\"aes\"}");
System.out.println(je1); System.out.println(je1);
} }
@Test @Test
public void testHangUp() { public void testHangUp() {
String url = "http://127.0.0.1:21030/SCIDE/CMManager?action="; String url = "http://127.0.0.1:21030/SCIDE/CMManager?action=";
@ -123,6 +125,7 @@ public class setMaskTest {
// String operation="hello3"; // String operation="hello3";
} }
@Test @Test
public void testResume() { public void testResume() {
String url = "http://127.0.0.1:21030/SCIDE/CMManager?action="; String url = "http://127.0.0.1:21030/SCIDE/CMManager?action=";
@ -135,10 +138,12 @@ public class setMaskTest {
// String operation="hello3"; // String operation="hello3";
} }
@Test @Test
public void testMysql() { public void testMysql() {
String contractID = "AAA12BMySQL"; String contractID = "AAA12BMySQL";
String url="http://127.0.0.1:21030/SCIDE/CMManager?action=getMask"+"&contractID="+contractID+"&requestID=1"; String url = "http://127.0.0.1:21030/SCIDE/CMManager?action=getMask" + "&contractID="
+ contractID + "&requestID=1";
System.out.println(url); System.out.println(url);
String resp = HttpUtil.httpGet(url.toString()).get("response").toString(); String resp = HttpUtil.httpGet(url.toString()).get("response").toString();

View File

@ -1,11 +1,11 @@
package org.bdware.sc.test.synctest; package org.bdware.sc.test.synctest;
import org.bdware.sc.trace.TraceRecordUtil;
public class PrintTraceRecords { public class PrintTraceRecords {
public static void main(String[] args) { public static void main(String[] args) {
// String path = "/Users/zhangyixuan/Lab/new/BDContract/front-agent/BDWareProjectDir/trace/"; // String path =
// "/Users/zhangyixuan/Lab/new/BDContract/front-agent/BDWareProjectDir/trace/";
// String contractName = "Test"; // String contractName = "Test";
// path += (contractName + "/"); // path += (contractName + "/");
// //

View File

@ -1,11 +1,10 @@
package org.bdware.sc.test.synctest; package org.bdware.sc.test.synctest;
import org.bdware.sc.redo.TransRecordUtil;
import org.bdware.sc.trace.TraceRecordUtil;
public class PrintTransRecords { public class PrintTransRecords {
public static void main(String[] args) { public static void main(String[] args) {
// String path = "/Users/zhangyixuan/Lab/new/BDContract/front-agent/BDWareProjectDir/trans/"; // String path =
// "/Users/zhangyixuan/Lab/new/BDContract/front-agent/BDWareProjectDir/trans/";
// String contractName = "Test"; // String contractName = "Test";
// path += (contractName + "/"); // path += (contractName + "/");
// //

View File

@ -17,8 +17,10 @@ public class RedoRecordTest {
// c.setType(ContractType.Sole); // c.setType(ContractType.Sole);
// String id = "169412582"; // String id = "169412582";
// c.setID(id); // c.setID(id);
// c.setScript(RedoRecoverTest.file2Str("/Users/zhangyixuan/Lab/BDWareHttp/BDWareProjectDir/public/" + name + ".yjs")); // c.setScript(RedoRecoverTest.file2Str("/Users/zhangyixuan/Lab/BDWareHttp/BDWareProjectDir/public/"
// String key = "{\"publicKey\":\"041d7b4818817736b3d64305675f04e9a00a12ce23c72e6740f83785edcffec6bae2c178fbc934f66d72e26f89a2e7a2c966dc3f0a8e415663c9b933af7a2e9ff8\",\"privateKey\":\"18505919022281880113072981827955639221458448578012075254857346196103069175443\"}"; // + name + ".yjs"));
// String key =
// "{\"publicKey\":\"041d7b4818817736b3d64305675f04e9a00a12ce23c72e6740f83785edcffec6bae2c178fbc934f66d72e26f89a2e7a2c966dc3f0a8e415663c9b933af7a2e9ff8\",\"privateKey\":\"18505919022281880113072981827955639221458448578012075254857346196103069175443\"}";
// SM2KeyPair pair = SM2KeyPair.fromJson(key); // SM2KeyPair pair = SM2KeyPair.fromJson(key);
// c.doSignature(pair); // c.doSignature(pair);
// System.out.println("<<<Start a contract>>> : " + cm1.startContractAndRedirect(c, null)); // System.out.println("<<<Start a contract>>> : " + cm1.startContractAndRedirect(c, null));
@ -30,7 +32,8 @@ public class RedoRecordTest {
// ContractRequest cor = new ContractRequest(); // ContractRequest cor = new ContractRequest();
// cor.setContractID(contractName); // cor.setContractID(contractName);
// cor.doSignature(pair); // cor.doSignature(pair);
// File file = new File("./cp/recoverTestFiles/affairs/" + contractName + "/" + argsFileName); // File file = new File("./cp/recoverTestFiles/affairs/" + contractName + "/" +
// argsFileName);
// try { // try {
// FileReader fr = new FileReader(file); // FileReader fr = new FileReader(file);
// BufferedReader br = new BufferedReader(fr); // BufferedReader br = new BufferedReader(fr);
@ -39,7 +42,8 @@ public class RedoRecordTest {
// String[] strs = s.split(" "); // String[] strs = s.split(" ");
// cor.setAction(strs[0]); // cor.setAction(strs[0]);
// cor.setArg(strs[1]); // cor.setArg(strs[1]);
// System.out.println("<<<execute the contract>> NO." + (++count) + " [Result]" + cm1.execute(cor)); // System.out.println("<<<execute the contract>> NO." + (++count) + " [Result]" +
// cm1.execute(cor));
// } // }
// } catch (IOException e1) { // } catch (IOException e1) {
// // TODO Auto-generated catch block // // TODO Auto-generated catch block
@ -51,7 +55,8 @@ public class RedoRecordTest {
// //
// //记录最终状态 // //记录最终状态
// cm1.saveTransRecords(contractName,"./cp/recoverTestFiles/trans/" + contractName); // cm1.saveTransRecords(contractName,"./cp/recoverTestFiles/trans/" + contractName);
// System.out.println("<<<transRecords>>> : \n" + cm1.engineTransRecords2String(contractName)); // System.out.println("<<<transRecords>>> : \n" +
// cm1.engineTransRecords2String(contractName));
// //
// //
// File mem = new File("./cp/recoverTestFiles/memory/" + contractName + ".txt"); // File mem = new File("./cp/recoverTestFiles/memory/" + contractName + ".txt");

Some files were not shown because too many files have changed in this diff Show More