41 Commits

Author SHA1 Message Date
haoeliu@foxmail.com
a1b59cfbfd finish the local version 2022-12-02 16:39:11 +08:00
haoeliu@foxmail.com
76a8e3ca58 fix the conflicts in build.gradle 2022-11-29 15:22:44 +08:00
haoeliu@foxmail.com
14e5fffe1d merge newest origin/master 2022-11-29 15:21:41 +08:00
haoeliu@foxmail.com
9477ff8a31 update test version 2022-11-29 15:17:57 +08:00
CaiHQ
05e301d9e9 add Access 2022-11-29 15:16:31 +08:00
haoeliu@foxmail.com
24c0673b9b finish the draft version 2022-11-27 18:54:50 +08:00
haoeliu@foxmail.com
9686de6ba9 add doipOperationMap in DOOPRequestHandler and merge DOOPRepoHandler 2022-11-16 14:58:26 +08:00
haoeliu@foxmail.com
37ad6c35d7 Merge remote-tracking branch 'origin/master' into lyh_dev to update AnnotationHook 2022-11-15 11:47:28 +08:00
haoeliu@foxmail.com
65aa9fd78d add first version DOOPRequestHandler 2022-11-15 11:47:26 +08:00
CaiHQ
07174bb3b4 upgrade annotation type
upgrade bdledger sdk
2022-11-15 11:37:08 +08:00
haoeliu@foxmail.com
a35ca147e3 resolve merging conflicts 2022-11-09 19:17:35 +08:00
CaiHQ
9317385bd9 add auto type convert in ArgSchema 2022-11-08 17:37:53 +08:00
CaiHQ
64cdfecd67 fix arg schema bugs 2022-09-28 18:15:52 +08:00
CaiHQ
56d140a2c7 connect function node with compiled function 2022-09-06 12:27:27 +08:00
CaiHQ
363a20049a fix rocksdb bugs 2022-09-02 21:21:42 +08:00
Frank.R.Wu
c077d425ab feat: update YJSCompiler
compile getGlobal in all contracts
2022-07-30 16:55:39 +08:00
Frank.R.Wu
ad8de7a92c feat: update YJSCompiler
compile setGlobal in all contracts
2022-07-30 16:55:22 +08:00
CaiHQ
639d8dc6cb upgrade rocksdb
publish cp-1.6.4
publish common-1.5.9
2022-06-29 09:19:57 +08:00
CaiHQ
2770908f2b publish 1.6.4 2022-06-29 02:30:24 +08:00
CaiHQ
14db4a8f6c fix: _mul misuse bugs 2022-06-29 02:29:45 +08:00
CaiHQ
df94bedbae keep sync 2022-06-28 20:40:49 +08:00
CaiHQ
4652d731c4 update version 2022-06-28 18:43:01 +08:00
CaiHQ
e5157df523 update version 2022-06-26 17:50:05 +08:00
CaiHQ
e5e16a5e1d add ClusterUtil
update @Router arguments
add DOIPUtilTest
update log4j2.properties
2022-06-26 17:48:03 +08:00
CaiHQ
5f42ed082c support debug log and normal log 2022-06-11 05:34:40 +08:00
CaiHQ
1229c9ce4c refactor: add bdledger dependencies
feat: IRPUtil
feat: support debug in docker
2022-05-20 22:50:13 +08:00
CaiHQ
c9b5a32e46 fix: yjs.jar corrupted 2022-05-14 01:22:42 +08:00
CaiHQ
30d5ca5ace fix: yjs.jar corrupted 2022-05-14 01:17:54 +08:00
CaiHQ
4318162fa8 prune: update modules for mvn repository 2022-05-13 23:51:26 +08:00
CaiHQ
6064882843 feat: support exception thrown in applyFunction 2022-05-03 15:47:32 +08:00
CaiHQ
cf097ce7fd feat: support onCreateParams 2022-05-02 20:50:47 +08:00
WangXuxin
bac80bbf31 feat: support @RouteInfo byFunc 2022-04-27 10:23:33 +08:00
CaiHQ
fa729d80a0 feat: support onCreateParams 2022-04-07 15:48:39 +08:00
CaiHQ
4b96899653 update ledgerUtil 2022-03-22 23:48:55 +08:00
WangXuxin
8db5c8e2d7 fix: verifyOracleAndContractPermission 2022-03-22 20:35:47 +08:00
62679528e4 fix setGlobal 2022-03-16 14:38:05 +08:00
CaiHQ
ea7eaf5db4 update JSONTool 2022-03-11 17:52:41 +08:00
8095f9735f add ScriptReturnException 2022-02-22 13:46:21 +08:00
CaiHQ
cb13076423 upgrade doipsdk 2022-01-08 23:43:21 +08:00
CaiHQ
b5ec0caccb fix: binarySearch bugs in TimeSerialIndex
feat: support multi tag time index util
2022-01-06 20:33:46 +08:00
CaiHQ
afad80ee2b upgrade doip-sdk 2022-01-04 10:43:53 +08:00
63 changed files with 2439 additions and 932 deletions

View File

@@ -1,10 +1,17 @@
plugins {
id 'java'
id 'application'
id 'java-library'
id 'maven-publish'
id 'signing'
}
mainClassName = 'org.bdware.sc.ContractProcess'
group = "org.bdware.sc"
version = "2.0.0"
repositories {
mavenCentral()
mavenLocal()
}
sourceSets {
main {
java {
@@ -25,51 +32,162 @@ sourceSets {
}
dependencies {
implementation project(":common")
implementation project(":mockjava")
api project(":common")
api project(":mockjava")
implementation 'org.apache.commons:commons-lang3:3.0'
implementation 'com.atlassian.commonmark:commonmark:0.17.0'
implementation 'com.idealista:format-preserving-encryption:1.0.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.sun.mail:javax.mail:1.6.2'
implementation 'org.apache.commons:commons-math3:3.6.1'
implementation 'org.codehaus.groovy:groovy-all:3.0.8'
implementation 'org.jsoup:jsoup:1.14.2'
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
implementation fileTree(dir: 'lib', include: '*.jar')
implementation 'io.grpc:grpc-all:1.41.0'
implementation 'org.jsoup:jsoup:1.14.2'
implementation 'com.sun.mail:javax.mail:1.6.2'
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'org.bdware.bdcontract:sdk-java:1.0.2'
implementation 'org.bdware.doip:doip-audit-tool:1.1.3'
implementation fileTree(dir: 'lib', include: '*.jar')
testImplementation 'junit:junit:4.13.2'
}
tasks.jar.setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
task classJar(type: Jar, dependsOn: classes) {
classifier = "jar"
}
jar {
String libs = ''
configurations.runtimeClasspath.each {
libs = libs + " libs/" + it.name
}
from {
// uncomment this when publish,
//while develop at local use "false"
configurations.runtimeClasspath.filter {
// it.getAbsolutePath().contains("/lib/")
false
}.collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Manifest-Version': project.version
attributes 'Main-Class': mainClassName
attributes 'Main-Class': 'org.bdware.sc.ContractProcess'
attributes 'Class-Path': libs
}
}
tasks.processResources.setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
tasks.processTestResources.setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
tasks.withType(Copy).all {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
}
tasks.withType(Jar).all {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
}
task copyLibs(type: Copy, dependsOn: ":common:jar") {
into "./build/output/libs/"
from configurations.runtimeClasspath
}
task copyJar(type: Copy, dependsOn: ":cp:jar") {
task copyJar(type: Copy, dependsOn: [":cp:jar", ":cp:copyLog4jProp"]) {
into "./build/output/"
from "./build/libs/$project.name-${version}.jar"
rename { String fileName -> "yjs.jar" }
}
task copyLog4jProp(type: Copy) {
into "./build/output/"
from "./src/main/resources/log4j2.debug.properties"
from "./src/main/resources/log4j2.properties"
}
task buildBundle(dependsOn: [":cp:copyLibs", ":cp:copyJar"]) {
doLast {
println "buildBundle in ./build/output/ successfully"
}
}
task sourceJar(type: Jar, dependsOn: classes) {
archiveClassifier = "sources"
classifier = "sources"
from sourceSets.main.allSource
}
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
task javadocJar(type: Jar, dependsOn: javadoc) {
archiveClassifier = 'javadoc'
classifier = "javadoc"
exclude {
details -> details.file.getAbsolutePath().contains("/gm/")
}
from javadoc.destinationDir
}
//shadowJar {
// // classifier = "jar"
// dependencies {
// include(dependency(fileTree(dir: 'lib', include: '*.jar')))
//// exclude(dependency('com.google.code.gson:gson:2.8.6'))
//// relocate 'com.google.code.gson', 'irs.com.google.code.gson'
// }
//}
publishing {
publications {
mavenJava(MavenPublication) {
groupId project.group
artifactId "cp"
version "${version}"
from components.java
artifact sourceJar
artifact javadocJar
artifact classJar
// artifact customFatJar
pom {
name = "bdware-cp"
description = "cp"
url = "https://gitee.com/BDWare/cp"
licenses {
license {
name = "GPL v2"
url = "https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt"
}
}
developers {
developer {
id = "dataware"
email = "caihq@pku.edu.cn"
}
}
scm {
connection = "scm:git:https://gitee.com/BDWare/cp.git"
developerConnection = "scm:git:https://gitee.com/BDWare/cp.git"
url = "https://gitee.com/BDWare/cp"
}
}
}
}
repositories {
maven {
name 'bdwareSnapshotRepository'
url 'https://oss.sonatype.org/content/repositories/snapshots'
// credentials {
// username = "${NEXUS_USERNAME}"
// password = "${NEXUS_PASSWORD}"
// }
}
maven {
name 'bdwareRepository'
url 'https://oss.sonatype.org/service/local/staging/deploy/maven2'
// credentials {
// username = "${NEXUS_USERNAME}"
// password = "${NEXUS_PASSWORD}"
// }
}
}
}
signing {
sign publishing.publications.mavenJava
}

Binary file not shown.

Binary file not shown.

View File

@@ -1,8 +1,10 @@
package org.bdware.sc.debugger;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.client.SmartContractClient;
import org.bdware.sc.ContractProcess;
import org.bdware.sc.bean.Contract;
import org.bdware.sc.bean.ContractExecType;
@@ -11,50 +13,96 @@ import org.bdware.sc.get.GetMessage;
import org.bdware.sc.http.HttpUtil;
import org.bdware.sc.util.FileUtil;
import org.bdware.sc.util.JsonUtil;
import org.zz.gmhelper.SM2KeyPair;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class DebugMain {
static Logger LOGGER = LogManager.getLogger(DebugMain.class);
public static void main(String[] args) {
String content = FileUtil.getFileContent("./debugconf.json");
public static void runWithConf(String configPath) {
String content = FileUtil.getFileContent(configPath);
DebugConfig config = JsonUtil.fromJson(content, DebugConfig.class);
inject(config);
String keyPairStr = "{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}";
SM2KeyPair pair = SM2KeyPair.fromJson(String.format(keyPairStr, config.publicKey, config.privateKey));
String uriFormat = "ws://%s/SCIDE/SCExecutor";
if (config.killBeforeStart != null && config.killBeforeStart.length() > 0) {
AtomicInteger counter = new AtomicInteger(0);
SmartContractClient client = new SmartContractClient(String.format(uriFormat, config.agentAddress), pair) {
public void onLogin(JsonObject obj) {
counter.incrementAndGet();
}
public void onKillContractProcess(JsonObject obj) {
counter.incrementAndGet();
}
};
client.waitForConnect();
client.login();
try {
for (; counter.get() == 0; )
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.sendMsg("{\"action\":\"killContractProcess\",\"name\":\"" + config.killBeforeStart + "\"}");
try {
for (; counter.get() == 1; )
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
config.contract.setCreateParam(config.createParam);
ContractProcess.main(new String[]{"-port=" + config.port, "-cmi=" + config.cmi, "-disablePID"});
ResultCallback printCallback
= new ResultCallback() {
@Override
public void onResult(String str) {
LOGGER.info(str);
LOGGER.info("[PrintCB] " + str);
}
};
ContractProcess.instance.handler.setDBInfo(wrap("", config.dbPath), printCallback);
ContractProcess.instance.handler.registerMangerPort(wrap("", Integer.valueOf(config.cPort)), printCallback);
ContractProcess.instance.handler.setContractBundle(wrap("", config.contract), printCallback);
String urlFormat = ("http://%s/SCIDE/SCManager?action=reconnectAll&owner=%s");
String url = String.format(urlFormat, config.agentHttpAddr, config.pubKey);
ContractProcess.instance.handler.setContractBundle(wrap("", config.contract), printCallback);
String urlFormat = "http://%s/SCIDE/SCManager?action=reconnectPort&owner=%s&port=%d%s";
String cpHost = "";
if (config.cpHost != null && config.cpHost.length() > 0)
cpHost = "&host=" + config.cpHost;
String url = String.format(urlFormat, config.agentAddress,
config.publicKey, ContractProcess.instance.server.mainPort.get(), cpHost);
Map<String, Object> resp = HttpUtil.httpGet(url);
String data = (String) resp.get("response");
LOGGER.info(JsonUtil.toPrettyJson(JsonUtil.parseStringAsJsonObject(data)));
LOGGER.info("start done!");
}
public static void main(String[] args) {
runWithConf("./debugconf.json");
}
private static void inject(DebugConfig config) {
String urlFormat = ("http://%s/SCIDE/SCManager?action=%s&arg=%s");
String url = String.format(urlFormat, config.agentHttpAddr, "getAgentConfig", "");
String url = String.format(urlFormat, config.agentAddress, "getAgentConfig", "");
Map<String, Object> resp = HttpUtil.httpGet(url);
String data = (String
) resp.get("response");
String data = (String) resp.get("response");
assert (int) resp.get("responseCode") == 200;
JsonObject jsonObject = JsonUtil.parseStringAsJsonObject(data);
config.cmi = jsonObject.get("cmi").getAsString();
config.dbPath = jsonObject.get("dbPath").getAsString();
config.cPort = jsonObject.get("cPort").getAsInt();
config.port = jsonObject.get("port").getAsInt();
JsonObject ownerAndScript = new JsonObject();
String arg = "abc&owner=" + config.pubKey + "&script=" + config.script;
url = String.format(urlFormat, config.agentHttpAddr, "allocateKeyPair", arg);
String arg = "abc&owner=" + config.publicKey + "&script=" + config.ypkPath;
url = String.format(urlFormat, config.agentAddress, "allocateKeyPair", arg);
resp = HttpUtil.httpGet(url);
LOGGER.info(url);
String contractStr = (String) resp.get("response");
@@ -76,12 +124,14 @@ public class DebugMain {
}
static class DebugConfig {
String script;
String agentHttpAddr;
String pubKey;
String privKey;
String agentAddress;
public JsonElement createParam;
String publicKey;
String privateKey;
String killBeforeStart;
String ypkPath;
String cpHost;
//AutoAppend
int port;
String cmi;
String dbPath;

View File

@@ -1,10 +1,9 @@
package org.bdware.sc;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.MalformedJsonException;
import groovy.util.logging.Log;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;
import org.bdware.analysis.BasicBlock;
@@ -22,7 +21,6 @@ import org.bdware.sc.ContractResult.Status;
import org.bdware.sc.bean.*;
import org.bdware.sc.boundry.JavaScriptEntry;
import org.bdware.sc.boundry.Resources;
import org.bdware.sc.boundry.utils.FileUtil;
import org.bdware.sc.boundry.utils.RocksDBUtil;
import org.bdware.sc.boundry.utils.UtilRegistry;
import org.bdware.sc.compiler.YJSCompiler;
@@ -30,11 +28,14 @@ import org.bdware.sc.conn.ByteUtil;
import org.bdware.sc.conn.ServiceServer;
import org.bdware.sc.conn.SocketGet;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.engine.hook.*;
import org.bdware.sc.handler.ContractHandler;
import org.bdware.sc.index.TimeSerialIndex;
import org.bdware.sc.node.*;
import org.bdware.sc.server.DoipServerTest;
import org.bdware.sc.trace.ProgramPointCounter;
import org.bdware.sc.util.FileUtil;
import org.bdware.sc.util.HashUtil;
import org.bdware.sc.util.JsonUtil;
import org.objectweb.asm.ClassReader;
@@ -45,6 +46,7 @@ import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
@@ -107,15 +109,15 @@ public class ContractProcess {
Scanner sc = new Scanner(pidInput);
for (String str; sc.hasNextLine(); ) {
str = sc.nextLine();
System.out.println("[CP From STDIN] " + str);
LOGGER.info("[CP From STDIN] " + str);
if (str.contains("CP PID:")) {
int pid = Integer.parseInt(str.replace("CP PID:", ""));
System.setProperty("io.netty.processId", pid + "");
System.out.println("[CP SET PID DONE] " + str);
LOGGER.info("[CP SET PID DONE] " + str);
break;
}
}
System.out.println("[Create CP]");
LOGGER.info("[Create CP]");
instance = new ContractProcess(port, cmi);
}
@@ -425,7 +427,7 @@ public class ContractProcess {
// 判断是否满足Oracle和Contact的执行要求
public String verifyOracleAndContractPermission(Contract contract) {
// 权限校验 如果是Oracle 启动方式只能是Sole 否则报错
if (cn.getYjsType() == YjsType.Oracle && contract.getType() != ContractExecType.Sole) {
if (cn.getYjsType() == YjsType.Oracle && contract.getType() != ContractExecType.Sole && contract.getType() != ContractExecType.Sharding) {
LOGGER.info("Oracle only support Sole ContractType!");
return JsonUtil.toJson(
new ContractResult(
@@ -450,6 +452,13 @@ public class ContractProcess {
return "";
}
public String setMembers(List<String> members) {
JavaScriptEntry.members = members;
if (members != null)
return members.size() + "";
else return "0";
}
public String setContractBundle(Contract contract) {
try {
// long start = System.currentTimeMillis();
@@ -469,18 +478,6 @@ public class ContractProcess {
cn = zipBundle.mergeContractNode();
// check functionNodes
List<FunctionNode> functionNodes = cn.getFunctions();
LOGGER.debug(
"functionNodes jointInfo: "
+ JsonUtil.toPrettyJson(
functionNodes.stream()
.map(
x -> {
JoinInfo joinInfo = x.getJoinInfo();
return null == joinInfo
? "null"
: joinInfo;
})
.toArray()));
injectHandlers();
this.contract.setYjsType(cn.getYjsType());
@@ -515,14 +512,22 @@ public class ContractProcess {
engine = new DesktopEngine(zipBundle.getManifest(), zipPath, contract);
engine.loadJar(zf);
engine.registerResource(new Resources(zf, engine.getClassLoad()));
String retStr =
JsonUtil.toJson(
engine.loadContract(contract, cn, cn.getInstrumentBranch()));
invokeOnCreate();
LOGGER.debug("result: " + retStr);
return retStr;
ContractResult result = engine.loadContract(contract, cn, cn.getInstrumentBranch());
JsonObject jo = new JsonObject();
ContractResult onCreate = invokeOnCreate(contract.getCreateParam());
jo.add("onCreate", JsonUtil.parseObject(onCreate));
jo.add("loadContract", JsonUtil.parseObject(result));
jo.addProperty("status", result.status.merge(onCreate.status).toString());
LOGGER.debug("result: " + jo.toString());
if(cn.getYjsType() == YjsType.DoipModule) {
LOGGER.info("the doipServer has started");
DoipServerTest.main(new String[]{"8080"});
}
return jo.toString();
} else {
contract.setScript(FileUtil.getContent(zipPath));
contract.setScript(FileUtil.getFileContent(zipPath));
return setContract(contract);
}
@@ -556,7 +561,21 @@ public class ContractProcess {
if (fun.isConfidential()) {
fun.appendBeforeInvokeHandler(new ConfidentialHandler(fun));
}
ArgSchemaHandler argSchemaHandler = createHandlerIfExist(fun, fun.annotations, ArgSchemaHandler.class);
if (argSchemaHandler != null) {
fun.appendBeforeInvokeHandler(argSchemaHandler);
}
if (fun.isDoipOperation()) {
fun.appendBeforeInvokeHandler(DOOPHandler.createDOOPHandler());
}
if (fun.isExport()) {
//if(fun.annotations...)
AccessHandler accessHandler = createHandlerIfExist(fun,fun.annotations,AccessHandler.class);
if (accessHandler != null) {
fun.appendBeforeInvokeHandler(accessHandler);
}
fun.appendAfterInvokeHandler(new ObjToJsonHandler());
// fun.appendBeforeInvokeHandler(new ReadMeHandler());
// Mask是用于返回真正结果之后做一些偏移以保护数据隐私。
@@ -576,9 +595,28 @@ public class ContractProcess {
if (fun.isHomomorphicDecrypt()) {
fun.appendAfterInvokeHandler(new HomomorphicDecryptHandler(fun));
}
}
}
<T extends AnnotationHook> T createHandlerIfExist(FunctionNode function, List<AnnotationNode> annotations, Class<T> clz) {
YJSAnnotation annotation = clz.getAnnotation(YJSAnnotation.class);
if (annotation == null) return null;
if (annotations == null) return null;
for (AnnotationNode node : annotations) {
if (annotation.name().equals(node.getType())) {
try {
Method m = clz.getDeclaredMethod("fromAnnotationNode", FunctionNode.class, AnnotationNode.class);
T result = (T) m.invoke(null, function, node);
return result;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
public String changeDumpPeriod(String period) {
System.out.println("[ContractProcess] period" + period);
@@ -610,11 +648,24 @@ public class ContractProcess {
return ver;
}
handleLog();
String ret =
JsonUtil.toJson(engine.loadContract(contract, cn, cn.getInstrumentBranch()));
invokeOnCreate();
LOGGER.info("load script, contract:" + JsonUtil.toJson(contract.getScriptStr()));
LOGGER.info("load cn:" + JsonUtil.toJson(cn));
ContractResult ret =
engine.loadContract(contract, cn, cn.getInstrumentBranch());
ContractResult onCreate = invokeOnCreate(contract.getCreateParam());
JsonObject jo = new JsonObject();
jo.add("onCreate", JsonUtil.parseObject(onCreate));
jo.add("loadContract", JsonUtil.parseObject(ret));
jo.addProperty("status", ret.status.merge(onCreate.status).toString());
LOGGER.debug("result: " + jo.toString());
return ret;
// doipModule的话拉起DoipServer服务端口
if(cn.getYjsType() == YjsType.DoipModule) {
LOGGER.info("the doipServer has started");
DoipServerTest.main(new String[]{"8080"});
}
return jo.toString();
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
@@ -666,7 +717,7 @@ public class ContractProcess {
return r.totalMemory() - r.freeMemory();
}
private void invokeOnCreate() {
private ContractResult invokeOnCreate(JsonElement arg) {
long start = System.currentTimeMillis();
logIndex = new TimeSerialIndex("./ContractDB/" + cn.getContractName() + ".index");
LOGGER.debug("timeSerialIndex: " + (System.currentTimeMillis() - start));
@@ -691,7 +742,14 @@ public class ContractProcess {
JavaScriptEntry.isDebug = contract.isDebug();
ContractRequest onCreate = new ContractRequest();
onCreate.setAction("onCreate");
onCreate.setArg("null");
if (arg == null) {
if (engine != null && engine.getManifest() != null && engine.getManifest().createParam != null)
arg = engine.getManifest().createParam;
else
arg = new JsonPrimitive("");
}
onCreate.setArg(arg);
LOGGER.debug("invoke onCreate, param:" + onCreate.getArg().toString());
onCreate.setRequester(contract.getOwner());
if (contract.getDoipFlag() && null != contract.getDOI() && !contract.getDOI().isEmpty()) {
onCreate.setRequesterDOI(contract.getDOI());
@@ -699,14 +757,21 @@ public class ContractProcess {
onCreate.setRequesterDOI("empty");
}
FunctionNode funNode = cn.getFunction("onCreate");
invoke(start, onCreate, funNode);
return invoke(onCreate, funNode);
}
private void invokeOnRecover() {
long start = System.currentTimeMillis();
public void resetContractName(String name) {
if (name != null)
cn.resetContractName(name);
}
private ContractResult invokeOnRecover(JsonElement arg) {
ContractRequest onRecover = new ContractRequest();
onRecover.setAction("onRecover");
if (arg == null)
onRecover.setArg("null");
else
onRecover.setArg(arg);
onRecover.setRequester(contract.getOwner());
if (contract.getDoipFlag()
&& (contract.getDOI() != null)
@@ -716,25 +781,18 @@ public class ContractProcess {
onRecover.setRequesterDOI("empty");
}
FunctionNode funNode = cn.getFunction("onRecover");
invoke(start, onRecover, funNode);
return invoke(onRecover, funNode);
}
private void invoke(long start, ContractRequest onRecover, FunctionNode funNode) {
// start = System.currentTimeMillis();
private ContractResult invoke(ContractRequest onRecover, FunctionNode funNode) {
if (funNode != null) {
LOGGER.debug(
"getFunction:" + (System.currentTimeMillis() - start) + " " + funNode.functionName);
long start1 = System.currentTimeMillis();
funNode.setIsExport(true);
engine.executeContract(onRecover);
LOGGER.debug("executeOnCreate:" + (System.currentTimeMillis() - start1));
start1 = System.currentTimeMillis();
ContractResult result = engine.executeContract(onRecover);
funNode.setIsExport(false);
engine.getTracePS().clean();
LOGGER.debug("clearTrace:" + (System.currentTimeMillis() - start1));
// start1 = System.currentTimeMillis();
return result;
}
return new ContractResult(Status.Success, new JsonPrimitive("no funNode found"));
}
// public String executeBundle(ContractZipBundle czb, String arg) {
@@ -813,6 +871,25 @@ public class ContractProcess {
return logIndex.size();
}
public String executeFunctionWithoutLimit(String arg) {
try {
JsonObject body = JsonUtil.parseString(arg).getAsJsonObject();
String funcName = body.get("funcName").getAsString();
JsonArray arr = body.getAsJsonArray("funcArgs");
Object[] funcArgs = new Object[arr.size()];
for (int i = 0; i < arr.size(); i++) {
funcArgs[i] = JSONTool.convertJsonElementToMirror(arr.get(i));
}
Object result = engine.invokeFunction(funcName, funcArgs);
result = JSONTool.convertMirrorToJson(result);
return JsonUtil.toJson(result);
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
return bo.toString();
}
}
public String executeContract(String arg) {
// TODO
// eventCenter.pub(new EventMsg("executeContract", arg));
@@ -829,6 +906,7 @@ public class ContractProcess {
}
String reqID = request.getRequestID();
if (cachedRequests.contains(reqID)) {
LOGGER.info("[Hit Cache]:" + reqID);
try {
String cachedResult = edion.get(reqID);
if (cachedResult != null && !cachedResult.isEmpty()) {
@@ -878,10 +956,6 @@ public class ContractProcess {
result = engine.executeContract(request);
result.analysis = bo.toString();
// System.out.println(
// "[withEvaluatesAnalysis ContractProcess] result.analysis =
// "
// + result.analysis);
engine.redirectTracePS(previous);
} else {
@@ -890,15 +964,12 @@ public class ContractProcess {
result = engine.executeContract(request);
engine.redirectTracePS(previous);
}
//
// System.out.println("res" + result.result);
// result.addProperty("result",maskResult.getMaskResult(maskConf,
// ret.get("result")).toString());
String ret = JsonUtil.toJson(result);
if (reqID != null && reqID.endsWith("_mul")) {
cachedRequests.add(reqID);
edion.put(reqID, ret);
}
return ret;
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
@@ -908,7 +979,6 @@ public class ContractProcess {
}
public String evaluatesAnalysis(String getFunction) {
// System.out.println("当前的function:" + getFunction);
Map<String, byte[]> clzs = engine.dumpClass();
Map<String, MethodNode> methods = new HashMap<>();
for (byte[] clz : clzs.values()) {
@@ -1034,7 +1104,7 @@ public class ContractProcess {
public String loadMemoryDump(String path) {
String str = engine.syncUtil.loadMemoryDump(path, contract.getStateful());
invokeOnRecover();
invokeOnRecover(contract.getCreateParam());
return str;
}
@@ -1097,8 +1167,8 @@ public class ContractProcess {
return JsonUtil.toJson(ret);
}
public String getContract() {
return JsonUtil.toJson(contract);
public Contract getContract() {
return contract;
}
public String getPID() {

View File

@@ -0,0 +1,72 @@
package org.bdware.sc;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bdware.sc.util.FileUtil;
import org.zz.gmhelper.SM2KeyPair;
import org.zz.gmhelper.SM2Util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class SM2Helper {
public static void main(String[] args) {
SM2KeyPair pair = SM2Util.generateSM2KeyPair(new SecureRandom());
try {
if (args.length > 0 && args[0].equals("generateKeyToFile")) {
backupFile(new File("./manager.keypair"));
backupFile(new File("./manager.key"));
System.out.println("Generate file: manger.key, manager.keypair");
FileOutputStream fout = new FileOutputStream("./manager.keypair");
fout.write(pair.toJson().getBytes(StandardCharsets.UTF_8));
fout.close();
fout = new FileOutputStream("./manager.key");
fout.write(pair.getPublicKeyStr().getBytes(StandardCharsets.UTF_8));
fout.close();
} else if (args.length > 0 && args[0].equals("generateCMConfig")) {
backupFile(new File("./cmconfig.json"));
System.out.println("Generate file: cmconfig.json");
String content = FileUtil.getFileContent("./cmconfig.json.template");
JsonObject jo = JsonParser.parseReader(new FileReader("cmvar.json")).getAsJsonObject();
for (String key : jo.keySet()) {
content = content.replaceAll(key, jo.get(key).getAsString());
}
JsonObject keypair = JsonParser.parseReader(new FileReader("manager.keypair")).getAsJsonObject();
content = content.replaceAll("_PRIVKEY", keypair.get("privateKey").getAsString());
content = content.replaceAll("_PUBKEY", keypair.get("publicKey").getAsString());
content = content.replaceAll("CMI", System.currentTimeMillis() + "");
FileOutputStream fout = new FileOutputStream("./cmconfig.json");
fout.write(content.getBytes(StandardCharsets.UTF_8));
fout.close();
} else
System.out.println(pair.toJson());
printHelp();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printHelp() {
String usage = "Usage:\n";
usage += "java -cp cp/libs/*:cp/yjs.jar org.bdware.sc.SM2Helper generateCMConfig\n";
usage += "java -cp cp/libs/*:cp/yjs.jar org.bdware.sc.SM2Helper generateKeyToFile";
System.out.println(usage);
}
private static void backupFile(File file) {
if (!file.exists()) return;
File backup = null;
for (int i = 0; i <= 100; i++) {
if (i == 100) throw new IllegalArgumentException("failed to backup:" + file.getAbsolutePath());
backup = new File(file.getParent(), file.getName() + "." + i);
if (!backup.exists())
break;
}
FileUtil.copyFile(file, backup);
System.out.println("Backup: " + file.getAbsolutePath() + " --> " + backup.getAbsolutePath());
}
}

View File

@@ -1,5 +0,0 @@
package org.bdware.sc.blockdb;
public class Constants {
public static final int ELASTIC_DB = 0;
}

View File

@@ -1,13 +0,0 @@
package org.bdware.sc.blockdb;
import org.bdware.sc.commParser.BDLedger.Transaction;
import java.util.Map;
public interface DBRepository {
public String Get(Map<String, Object> condition);//get hash of transaction
public boolean Put(Transaction trans);//put transaction into databases
public boolean Delete(String hash);//delete transaction
public boolean Create_DB();//createDB
public boolean Open_DB(); //OpenDB
}

View File

@@ -1,12 +0,0 @@
package org.bdware.sc.blockdb;
public class DBUtil {
private static DBRepository instance = null;
public static DBRepository getInstance(int type) {
if (null == instance && type == Constants.ELASTIC_DB) {
instance = new ElasticDBUtil();
}
return instance;
}
}

View File

@@ -1,106 +0,0 @@
package org.bdware.sc.blockdb;
import okhttp3.*;
import org.bdware.sc.commParser.BDLedger.Transaction;
import org.bdware.sc.util.JsonUtil;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ElasticDBUtil implements DBRepository {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public OkHttpClient client = new OkHttpClient();
public List<Transaction> transactions = new ArrayList<>();
public int bulk = 10000;
@Override
public String Get(Map<String, Object> condition) {
// TODO Auto-generated method stub
Map<String, Object> map = new HashMap<>();
Map<String, Object> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
map2.put("data", condition.get("data") + "*");
map1.put("wildcard", map2);
map.put("query", map1);
String json = JsonUtil.toJson(map);
RequestBody requestbody = FormBody.create(json, JSON);
Request request = new Request.Builder().url("http://127.0.0.1:9200/transaction/_doc/_search").post(requestbody).build();
try {
Response resp = client.newCall(request).execute();
System.out.print(resp.body().string());
resp.body().close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
@Override
public boolean Put(Transaction trans) {
// TODO Auto-generated method stub
transactions.add(trans);
if (transactions.size() == bulk) {
StringBuilder sb = new StringBuilder();
try {
for (int i = 0; i < bulk; i++) {
sb
.append("{\"index\":{}}\n{\"data\":\"")
.append(new String(transactions.get(i).data, StandardCharsets.UTF_8))
.append("\",")
.append("\"hash\":")
.append("\"")
.append(new String(transactions.get(i).hash, StandardCharsets.UTF_8))
.append("\"")
.append("}")
.append("\n");
}
//System.out.println(sb.toString());
RequestBody requestbody = FormBody.create(sb.toString(), JSON);
Request request = new Request.Builder().url("http://127.0.0.1:9200/transaction/_doc/_bulk").post(requestbody).build();
Response res1 = client.newCall(request).execute();
boolean res = res1.isSuccessful();
res1.body().close();
System.out.println(res);
transactions.clear();
return res;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
@Override
public boolean Delete(String hash) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean Create_DB() {
// TODO Auto-generated method stub
RequestBody body = RequestBody.create("", JSON);
Request request = new Request.Builder().url("http://127.0.0.1:9200/transaction/").put(body).build();
try {
Response response = client.newCall(request).execute();
boolean res = response.isSuccessful();
response.body().close();
return res;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
public boolean Open_DB() {
// TODO Auto-generated method stub
return false;
}
}

View File

@@ -1,36 +0,0 @@
package org.bdware.sc.blockdb;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class MongoDBUtil {
public static Object connect(String url, int port, String dbName, String usrName, String pwd) {
try {
Class serverAddr = Class.forName("com.mongodb.ServerAddress");
Constructor cons = serverAddr.getConstructor(String.class, Integer.TYPE);
Object serverAddress = cons.newInstance(url, port);
List addrs = new ArrayList<>();
addrs.add(serverAddress);
Method createeScramSha1 =
Class.forName("com.mongodb.MongoCredential")
.getDeclaredMethod(
"createScramSha1Credential",
String.class,
String.class,
char[].class);
Object credential = createeScramSha1.invoke(null, usrName, dbName, pwd.toCharArray());
List credentials = new ArrayList<>();
credentials.add(credential);
Constructor mongoClient =
Class.forName("com.mongodb.MongoClient").getConstructor(List.class, List.class);
Object client = mongoClient.newInstance(addrs, credentials);
// 通过连接认证获取MongoDB连接
return client;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

View File

@@ -1,72 +0,0 @@
package org.bdware.sc.blockdb;
import org.bdware.sc.commParser.BDLedger.Transaction;
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import java.io.File;
import java.util.Map;
public class RocksDBUtil implements DBRepository{
private static RocksDB rocksdb;
static {
RocksDB.loadLibrary();
}
public static RocksDB loadDB(String path, String readOnly) {
try {
Options options = new Options();
options.setCreateIfMissing(true);
RocksDB rocksDB;
File lockFile = new File(path,"LOCK");
lockFile.delete();
if (readOnly != null && readOnly.equals("true")) {
rocksDB = RocksDB.openReadOnly(options, path);
} else
rocksDB = RocksDB.open(options, path);
rocksdb = rocksDB;
return rocksDB;
} catch (RocksDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public String Get(Map<String, Object> condition) {
// TODO Auto-generated method stub
if(condition.containsKey("start")&&condition.containsKey("end")) {
int start = (int)condition.get("start");
int end = (int)condition.get("end");
}
return null;
}
@Override
public boolean Put(Transaction trans) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean Delete(String hash) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean Create_DB() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean Open_DB() {
// TODO Auto-generated method stub
return false;
}
}

View File

@@ -1,117 +0,0 @@
package org.bdware.sc.blockdb;
import org.bdware.sc.commParser.BDLedger.Block;
import org.bdware.sc.commParser.BDLedger.BlockBody;
import org.bdware.sc.commParser.BDLedger.BlockHeader;
import org.bdware.sc.util.HashUtil;
import java.io.File;
import java.sql.*;
public class SqliteDBUtil {
private Connection conn;
public static SqliteDBUtil connect(String url) {
try {
String name = "org.sqlite.JDBC";
SqliteDBUtil util = new SqliteDBUtil();
String path = "jdbc:sqlite:";
File file = new File(url);
path = path + file.getAbsolutePath();
System.out.println("[SqliteDBUtil] connect:" + path);
Class.forName(name);
util.conn = DriverManager.getConnection(path);
return util;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public BlockBody getBlockBody(String headerHash, String bodyHash) {
try {
Statement stmt = conn.createStatement();
// ResultSet result = stmt.executeQuery("select * from BlockHeader where hash =
// " + headerHash);
String sql = "select * from BlockBody where ID = ?";
PreparedStatement pre = conn.prepareStatement(sql);
pre.setBytes(1, HashUtil.str16ToBytes(bodyHash));
ResultSet result = pre.executeQuery();
// Assert we get only one!!!!
while (result.next()) {
System.out.println(result.getBytes("ID"));
return BlockBody.fromBytes(result.getBytes("Data"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Block getBlock(String headerHash, String bodyHash) {
try {
BlockHeader header = new BlockHeader();
BlockBody body = new BlockBody();
Statement stmt = conn.createStatement();
String sql = "select * from BlockBody where ID = ?";
PreparedStatement pre = conn.prepareStatement(sql);
pre.setBytes(1, HashUtil.str16ToBytes(bodyHash));
ResultSet result = pre.executeQuery();
while (result.next()) {
body = BlockBody.fromBytes(result.getBytes("Data"));
}
String sql1 = "select * from BlockHeader where Hash = ?";
pre = conn.prepareStatement(sql1);
pre.setBytes(1, HashUtil.str16ToBytes(headerHash));
result = pre.executeQuery();
while (result.next()) {
header.index = result.getInt(1);
header.hash = result.getBytes(2);
header.version = result.getInt(3);
header.timestamp = result.getInt(4);
header.prevblockID = result.getBytes(5);
header.merkleroot = result.getBytes(6);
header.creatorID = result.getBytes(7);
Block block = new Block(header,body);
return block;
//return Block.fromBytes(result.getBytes("Data"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public byte[] bodyselectall() {
try {
Statement stmt = conn.createStatement();
// ResultSet result = stmt.executeQuery("select * from BlockHeader where hash =
// " + headerHash);
String sql = "select * from BlockBody limit 1,1";
PreparedStatement pre = conn.prepareStatement(sql);
ResultSet result = pre.executeQuery();
// Assert we get only one!!!!
while (result.next()) {
return result.getBytes(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public byte[] headerselectall() {
try {
Statement stmt = conn.createStatement();
// ResultSet result = stmt.executeQuery("select * from BlockHeader where hash =
// " + headerHash);
String sql = "select * from BlockHeader limit 1,1";
PreparedStatement pre = conn.prepareStatement(sql);
ResultSet result = pre.executeQuery();
// Assert we get only one!!!!
while (result.next()) {
return result.getBytes(2);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -1,39 +0,0 @@
package org.bdware.sc.blockdb;
import org.bdware.sc.commParser.BDLedger.Transaction;
import java.util.Map;
public class TimeDBUtil implements DBRepository{
@Override
public String Get(Map<String, Object> condition) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean Put(Transaction trans) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean Delete(String hash) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean Create_DB() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean Open_DB() {
// TODO Auto-generated method stub
return false;
}
}

View File

@@ -1,12 +1,11 @@
package org.bdware.sc.boundry;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.ContractProcess;
import org.bdware.sc.bean.ContractExecType;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.boundry.utils.SQLUtil;
import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.conn.SocketGet;
import org.bdware.sc.engine.DesktopEngine;
@@ -25,9 +24,6 @@ import wrp.jdk.nashorn.internal.runtime.ScriptFunction;
import wrp.jdk.nashorn.internal.runtime.ScriptObject;
import wrp.jdk.nashorn.internal.scripts.JO;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -35,11 +31,13 @@ import java.io.PrintStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.Security;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -61,11 +59,25 @@ public class JavaScriptEntry {
public static boolean isDebug;
public static List<REvent> msgList;
public static int shardingID;
public static List<String> members;
// private static SM2KeyPair keyPair = new SM2().generateKeyPair(); // TODO 本地服务器的,39上运行39的
// public static String privKey;
// public static String pubKey;
private static SM2KeyPair keyPair;
public static boolean resetContractName(String name) {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
String method = null;
if (stacktrace.length > 2) {
method = stacktrace[2].getMethodName();
}
if (method != null && method.equals("onCreate")) {
ContractProcess.instance.resetContractName(name);
return true;
}
return false;
}
public static void setSM2KeyPair(String pubKey, String privKey) {
keyPair =
new SM2KeyPair(
@@ -84,25 +96,6 @@ public class JavaScriptEntry {
return HashUtil.hashByteArray(hash);
}
public static Connection getMysqlConnection(String url, String usrName, String pwd) {
return SQLUtil.getConnection("jdbc:mysql://" + url, usrName, pwd);
}
public static String example(String arg) {
LOGGER.debug("called: " + arg);
return arg + 1;
}
// public static MongoClient connectMongoDb(String url, int port, String dbName, String usrName,
// String pwd) {
// return getMongoDBConnection(url, port, dbName, usrName, pwd);
// }
//
// public static MongoClient getMongoDBConnection(String url, int port, String dbName, String
// usrName, String pwd) {
// return MongoDBUtil.connect(url, port, dbName, usrName, pwd);
// }
public static String bytes2Str(byte[] bytes) {
return new String(bytes);
}
@@ -153,44 +146,6 @@ public class JavaScriptEntry {
return bo.toByteArray();
}
// private static String list2Str(List<String> reservedList) {
// return JsonUtil.toJson(reservedList);
// }
//
// private static String map2Str(Map<String, Object> map) {
// return JsonUtil.toJson(map);
// }
// private static CloseableHttpClient getHttpClient(String url) {
// try {
// SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
//
// @Override
// public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
// throws java.security.cert.CertificateException {
// return true;
// }
// }).build();
//
// SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null, null,
// new NoopHostnameVerifier());
// int tle = 10;
// if (url.contains("data.tj.gov.cn"))
// tle = 3;
// return HttpClients.custom().setSSLSocketFactory(sslSf)
// .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
// @Override
// public long getKeepAliveDuration(HttpResponse arg0, HttpContext arg1) {
// return 0;
// }
// }).setConnectionTimeToLive(tle, TimeUnit.SECONDS).build();
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// return null;
// }
public static InputStream httpAsInputStream(String url) {
try {
URL realUrl = new URL(url);
@@ -202,53 +157,8 @@ public class JavaScriptEntry {
}
}
// public static String httpPost(String str) {
// System.out.println("JavaSScriptEntry httpPost:" + str);
// PostRequest req = new PostRequest();
// req = JsonUtil.fromJson(str, PostRequest.class);
// // System.out.println("url========>" + req.url);
// // System.out.println("data=======>" + req.data);
//
// Result r = new Result();
// try {
// URL url = new URL(req.url);//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setUseCaches(false);
// connection.setInstanceFollowRedirects(true);
// connection.setRequestMethod("POST"); // 璁剧疆璇锋眰鏂瑰紡
// connection.setRequestProperty("Accept", "application/json"); // 璁剧疆鎺ユ敹鏁版嵁鐨勬牸寮<E789B8>
// connection.setRequestProperty("Content-Type", "application/json"); // 璁剧疆鍙戦<E98D99>佹暟鎹殑鏍煎紡
// connection.connect();
// OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); //
// utf-8缂栫爜
// out.append(req.data);
// out.flush();
// out.close();
//
// r.resposeCode = connection.getResponseCode();
// InputStream input = connection.getInputStream();
//
// Scanner sc = new Scanner(input);
// StringBuilder sb = new StringBuilder();
// for (; sc.hasNextLine();) {
// sb.append(sc.nextLine()).append("\n");
// }
// sc.close();
// r.response = sb.toString();
// return JsonUtil.toJson(r);
// } catch (Throwable e) {
// r.resposeCode = 505;
// // ByteArrayOutputStream bo = new ByteArrayOutputStream();
// // e.printStackTrace(new PrintStream(bo));
// r.response = e.getMessage();
// return JsonUtil.toJson(r);
// }
// }
public static void executeFunction(ScriptFunction callback, Object arg) {
DesktopEngine.applyWithGlobal(callback, currentEngine.getNashornGlobal(), arg);
public static Object executeFunction(ScriptFunction callback, Object arg) {
return DesktopEngine.applyWithGlobal(callback, currentEngine.getNashornGlobal(), arg);
}
public static ApiGate createAPIGate(String ip) {
@@ -329,7 +239,8 @@ public class JavaScriptEntry {
app.doSignature(keyPair);
app.setRequesterDOI(doi);
app.setFromDebug(isDebug);
if (numOfCopies > 1) {
ContractExecType type = ContractProcess.instance.getContract().getType();
if (type.needSeq()) {
app.setRequestID(
String.format(
"%d_%d_%d_%d_mul",
@@ -404,123 +315,6 @@ public class JavaScriptEntry {
}
}
/*public static String executeContract(String contractID, String action, String arg) {
//redo,use record data
if(currentSyncUtil.transRecoverUtil != null && currentSyncUtil.transRecoverUtil.recovering){
String k = TransRecordUtil.produceExecuteIdentifier(contractID,action,arg);
return currentSyncUtil.transRecoverUtil.curRecoverRecord.getExecuteResult(k);
}
try {
ContractRequest app = new ContractRequest();
app.setContractID(contractID).setAction(action).setArg(arg);
//app.doSignature(keyPair.getPrivateKey().toString(16));
app.doSignature(keyPair);
String result = get.syncGet("dd", "executeContract", JsonUtil.toJson(app));
if(currentSyncUtil.startFlag && currentSyncUtil.currType == SyncType.Trans){
String k = currentSyncUtil.transRecordUtil.produceExecuteIdentifier(contractID,action,arg);
currentSyncUtil.transRecordUtil.recordExecutes(k,result);
}
return result;
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
String result = bo.toString();
if(currentSyncUtil.startFlag && currentSyncUtil.currType == SyncType.Trans){
String k = TransRecordUtil.produceExecuteIdentifier(contractID,action,arg);
currentSyncUtil.transRecordUtil.recordExecutes(k,result);
}
return result;
}
}*/
// public static String queryContractIdByDOI(String contractDOI) throws Exception {
// DigitalObject contractDO;
// DoipClient doipClient =
// DoipClient.createByRepoUrlAndMsgFmt(
// DOIPMainServer.repoUrl, DoipMessageFormat.PACKET.getName());
// DoMessage response = doipClient.retrieve(contractDOI, null, null);
// if (response.parameters.response == DoResponse.Success) {
// contractDO = DigitalObject.parse(response.body);
// } else {
// response = DOAClient.getGlobalInstance().retrieve(contractDOI, null, null);
// contractDO = DigitalObject.parse(response.body);
// }
// ContractInstanceDO contractInstanceDO =
// (ContractInstanceDO)
// ContractManager.toObject(contractDO.elements.get(0).getData());
// return contractInstanceDO.id;
// }
// public static String executeContractByDOI(String contractDOI, String action, String arg) {
// try {
// String contractID = queryContractIdByDOI(contractDOI);
// return executeContract(contractID, action, arg);
// } catch (Exception e) {
// ByteArrayOutputStream bo = new ByteArrayOutputStream();
// e.printStackTrace(new PrintStream(bo));
// return bo.toString();
// }
// }
//
// public static String getAuthInfo() {
// try {
// DigitalObject contractDO;
// DoipClient doipClient =
// DoipClient.createByRepoUrlAndMsgFmt(
// DOIPMainServer.repoUrl, DoipMessageFormat.PACKET.getName());
// DoMessage response = doipClient.retrieve(authInfoPersistDOI, null, null);
// if (response.parameters.response != DoResponse.Success) {
// response = DOAClient.getGlobalInstance().retrieve(authInfoPersistDOI, null,
// null);
// }
// contractDO = DigitalObject.parse(response.body);
// return new String(contractDO.elements.get(0).getData());
// } catch (Exception e) {
// ByteArrayOutputStream bo = new ByteArrayOutputStream();
// e.printStackTrace(new PrintStream(bo));
// return "Failed: " + bo.toString();
// }
// }
//
// public static String setAuthInfo(String authInfo) {
// try {
//
// DigitalObject contractDO = new DigitalObject(authInfoPersistDOI, DoType.Json);
// Element e = new Element("authInfo", "JsonString");
// e.setData(authInfo.getBytes());
// contractDO.addElements(e);
//
// DoipClient doipClient =
// DoipClient.createByRepoUrlAndMsgFmt(
// DOIPMainServer.repoUrl, DoipMessageFormat.PACKET.getName());
// DoMessage response = doipClient.update(contractDO);
// if (response.parameters.response != DoResponse.Success) {
// DoHandleRecord dohr =
// DOAClient.getGlobalInstance().resolveDO(authInfoPersistDOI);
// if (dohr == null) {
// return "Failed: Can not resolve authInfoPersistDOI: " +
// authInfoPersistDOI;
// }
// ServiceHandleRecord repoHandleRecord =
// DOAClient.getGlobalInstance().resolveDOIPService(dohr.repository);
// doipClient =
// DoipClient.createByRepoUrlAndMsgFmt(
// repoHandleRecord.getListenerInfos().get(0).url,
// DoipMessageFormat.PACKET.getName());
// response = doipClient.update(contractDO);
// if (response.parameters.response != DoResponse.Success) {
// return "Failed: Can not update authInfoPersistDOI: " + authInfoPersistDOI;
// }
// }
// return "Succeeded";
// } catch (Exception e) {
// ByteArrayOutputStream bo = new ByteArrayOutputStream();
// e.printStackTrace(new PrintStream(bo));
// return "Failed: " + bo.toString();
// }
// }
public static String executeContractAsync(
String contractID, String action, String arg, final ScriptFunction cb) {
try {
@@ -551,6 +345,11 @@ public class JavaScriptEntry {
}
}
//YancloudUtil.exceptionReturn({"msg":"missing arguments repoId ","code":1});
public static void exceptionReturn(Object obj) throws ScriptReturnException {
throw new ScriptReturnException(JSONTool.convertMirrorToJson(obj));
}
/**
* publish an event with semantic AT_LEAST_ONCE
*
@@ -590,10 +389,10 @@ public class JavaScriptEntry {
* @author Kaidong Wu
*/
public static String subscribe(String topic, ScriptFunction fun) {
subscribe(topic, fun, false);
if (topic_handlers.containsKey(topic)) {
ContractProcess.instance.unSubscribe(topic_handlers.get(topic).getName());
}
subscribe(topic, fun, false);
topic_handlers.put(topic, fun);
return topic;
}
@@ -696,46 +495,6 @@ public class JavaScriptEntry {
// TODO
}
public static String sendEmail(String json) {
try {
final JsonObject jo = JsonParser.parseString(json).getAsJsonObject();
Properties props = new Properties();
props.setProperty("mail.debug", "false");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host", jo.get("host").getAsString());
props.setProperty("mail.smtp.port", jo.get("port").getAsString());
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", jo.get("port").getAsString());
Session session =
Session.getDefaultInstance(
props,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
jo.get("from").getAsString(),
jo.get("pwd").getAsString()); // 发件人邮件用户名、密码
}
});
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject(jo.get("subject").getAsString());
msg.setText(jo.get("content").getAsString());
msg.setFrom(new InternetAddress(jo.get("from").getAsString()));
msg.addRecipient(
Message.RecipientType.TO, new InternetAddress(jo.get("to").getAsString()));
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
return "success";
}
public static ScriptObject getCaller(int i) {
JO ret = new JO(PropertyMap.newMap());
@@ -752,8 +511,4 @@ public class JavaScriptEntry {
public String response;
}
static class PostRequest {
String url;
String data;
}
}

View File

@@ -0,0 +1,12 @@
package org.bdware.sc.boundry;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class ScriptReturnException extends IllegalStateException {
public JsonObject message;
public ScriptReturnException(JsonElement jsonElement) {
message = jsonElement.getAsJsonObject();
}
}

View File

@@ -0,0 +1,58 @@
package org.bdware.sc.boundry.utils;
import com.google.gson.JsonArray;
import org.bdware.sc.boundry.JavaScriptEntry;
import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.Permission;
import org.bdware.sc.util.JsonUtil;
import wrp.jdk.nashorn.internal.objects.NativeArray;
import wrp.jdk.nashorn.internal.runtime.PropertyMap;
import wrp.jdk.nashorn.internal.runtime.ScriptObject;
import wrp.jdk.nashorn.internal.scripts.JO;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@PermissionStub(permission = Permission.Cluster)
public class ClusterUtil {
public static int getShardingID() {
return JavaScriptEntry.shardingID;
}
public static Object getMembers() {
if (JavaScriptEntry.members == null) {
return new NativeArray();
}
NativeArray narray = new NativeArray();
for (int i = 0; i < JavaScriptEntry.members.size(); i++)
NativeArray.push(narray, JavaScriptEntry.members.get(i));
return narray;
}
public static String getMember(int i) {
return JavaScriptEntry.members.get(i);
}
public static int getMembersSize() {
if (JavaScriptEntry.members != null)
return JavaScriptEntry.members.size();
return 1;
}
public static Object getCurrentNodeID() {
if (isCluster()) {
return JavaScriptEntry.members.get(JavaScriptEntry.shardingID);
}
return null;
}
public static boolean isCluster() {
return (JavaScriptEntry.members != null);
}
}

View File

@@ -0,0 +1,234 @@
package org.bdware.sc.boundry.utils;
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.audit.EndpointConfig;
import org.bdware.doip.audit.client.AuditIrpClient;
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.stateinfo.StateInfoBase;
import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.Permission;
import org.bdware.sc.util.JsonUtil;
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.DOIP)
public class DOIPUtil {
private static final Logger LOGGER = LogManager.getLogger(DOIPUtil.class);
private final String url;
private final DoipClientImpl doipClient;
private DOIPUtil(String url) {
this.url = url;
this.doipClient = new DoipClientImpl();
doipClient.connect(ClientConfig.fromUrl(url));
}
public static DOIPUtil createClient(String url) {
return new DOIPUtil(url);
}
public String test(String doi) {
return "create DOClient And hello " + doi + " World";
}
public boolean reconnect() {
try {
if (doipClient != null)
doipClient.reconnect();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private DoipMessage syncGetMessage(DoipMessage message) {
List<DoipMessage> ret = new ArrayList<>();
DoipMessage msg = null;
try {
doipClient.sendMessage(message, new DoipMessageCallback() {
@Override
public void onResult(DoipMessage doipMessage) {
ret.add(doipMessage);
synchronized (ret) {
ret.notify();
}
}
});
synchronized (ret) {
ret.wait(5000);
}
if (ret.size() > 0)
msg = ret.get(0);
if (msg != null) {
return msg;
} else return DoipMessageFactory.createTimeoutResponse(message.requestID);
} catch (Exception ie) {
ie.printStackTrace();
return DoipMessageFactory.createConnectFailedResponse(message.requestID);
}
}
private static String convertDoipMsgToString(DoipMessage ret) {
try {
LOGGER.info(new String(ret.body.encodedData));
DigitalObject respDO = ret.body.getDataAsDigitalObject();
return respDO.toString();
} catch (Exception ie) {
ie.printStackTrace();
return ret.body.getDataAsJsonString();
}
}
public String hello(String repoID) {
DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder()).createRequest(repoID, BasicOperations.Hello.getName()).create();
return convertDoipMsgToString(syncGetMessage(msg));
}
public String retrieve(String doi, String args) {
DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder()).createRequest(doi, BasicOperations.Retrieve.getName())
.create();
msg.header.parameters.addAttribute("element", "");
return convertDoipMsgToString(syncGetMessage(msg));
}
public String call(String doi, String action, String args) {
JsonObject jo = new JsonObject();
jo.addProperty("action", action);
jo.addProperty("args", args);
DoipMessage msg = (new DoipMessageFactory.DoipMessageBuilder())
.createRequest(doi, BasicOperations.Retrieve.getName())
.setBody(jo.toString().getBytes(StandardCharsets.UTF_8)).create();
return convertDoipMsgToString(syncGetMessage(msg));
}
public String create(String repoID, String doString) {
DigitalObject digitalObject = JsonUtil.fromJson(doString, DigitalObject.class);
for (Element e : digitalObject.elements) {
if (null != e.dataString) {
e.setData(e.dataString.getBytes());
}
e.dataString = null;
}
DoipMessage msg =
new DoipMessageFactory.DoipMessageBuilder()
.createRequest(repoID, BasicOperations.Create.getName())
.setBody(digitalObject)
.create();
return convertDoipMsgToString(syncGetMessage(msg));
}
public String delete(String doID) {
DoipMessage msg =
new DoipMessageFactory.DoipMessageBuilder()
.createRequest(doID, BasicOperations.Delete.getName())
.create();
return convertDoipMsgToString(syncGetMessage(msg));
}
public String listOperation(String doID) {
DoipMessage msg =
new DoipMessageFactory.DoipMessageBuilder()
.createRequest(doID, BasicOperations.ListOps.getName())
.create();
return convertDoipMsgToString(syncGetMessage(msg));
}
public static class IRPClientWrapper {
public AuditIrpClient impl;
public IRPClientWrapper(EndpointConfig config) {
impl = new AuditIrpClient(config);
}
public Object reconnect() {
JsonObject jo2 = new JsonObject();
try {
impl.reconnect();
jo2.addProperty("code", 1);
jo2.addProperty("msg", "success");
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
jo2.addProperty("code", 0);
jo2.addProperty("msg", bo.toString());
}
return JSONTool.convertJsonElementToMirror(jo2);
}
public Object resolve(String doId) {
StateInfoBase jo = null;
try {
jo = impl.resolve(doId);
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
JsonObject jo2 = new JsonObject();
jo2.addProperty("code", 0);
jo2.addProperty("msg", bo.toString());
return JSONTool.convertJsonElementToMirror(jo2);
}
return JSONTool.convertJsonElementToMirror(jo.getHandleValues());
}
public Object register(ScriptObjectMirror obj) {
JsonObject jo = JSONTool.convertMirrorToJson(obj).getAsJsonObject();
StateInfoBase base = new StateInfoBase();
jo.addProperty("repoId", impl.getEndpointInfo().getDoId());
base.setHandleValues(jo);
String ret = null;
JsonObject jo2 = new JsonObject();
try {
ret = impl.register(base);
if (ret != null) {
jo2.addProperty("code", 1);
jo2.addProperty("doId", ret.toString());
} else {
jo2.addProperty("code", 0);
jo2.addProperty("msg", "connection failed!");
}
} catch (Exception e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bo));
jo2.addProperty("code", 0);
jo2.addProperty("msg", bo.toString());
return JSONTool.convertJsonElementToMirror(jo2);
}
return JSONTool.convertJsonElementToMirror(jo2);
}
}
public static IRPClientWrapper createIrpClient(String uri) {
return createIrpClient(uri, null, null, null);
}
public static IRPClientWrapper createIrpClient(String uri, String pubkey, String privateKey, String repoName) {
EndpointConfig config = new EndpointConfig();
config.routerURI = uri;
config.repoName = repoName;
config.privateKey = privateKey;
config.publicKey = pubkey;
return new IRPClientWrapper(config);
}
}

View File

@@ -0,0 +1,53 @@
package org.bdware.sc.boundry.utils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Properties;
public class EmailUtil {
public static String sendEmail(String json) {
try {
final JsonObject jo = JsonParser.parseString(json).getAsJsonObject();
Properties props = new Properties();
props.setProperty("mail.debug", "false");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host", jo.get("host").getAsString());
props.setProperty("mail.smtp.port", jo.get("port").getAsString());
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", jo.get("port").getAsString());
Session session =
Session.getDefaultInstance(
props,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
jo.get("from").getAsString(),
jo.get("pwd").getAsString()); // 发件人邮件用户名、密码
}
});
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject(jo.get("subject").getAsString());
msg.setText(jo.get("content").getAsString());
msg.setFrom(new InternetAddress(jo.get("from").getAsString()));
msg.addRecipient(
Message.RecipientType.TO, new InternetAddress(jo.get("to").getAsString()));
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
return "success";
}
}

View File

@@ -12,7 +12,7 @@ import java.io.PrintStream;
public class FileUtil extends org.bdware.sc.util.FileUtil {
private static String getInternalFile(String path) {
File parent = new File("./ContractDB/" + ContractProcess.instance.getContractName());
if (path.contains("..")) {
if (path.contains("")) {
return null;
}
File f = new File(parent, path);

View File

@@ -0,0 +1,94 @@
package org.bdware.sc.boundry.utils;
import com.google.api.client.json.Json;
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.audit.EndpointConfig;
import org.bdware.doip.audit.client.AuditIrpClient;
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.sc.compiler.PermissionStub;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.Permission;
import org.bdware.sc.util.JsonUtil;
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)
public class IRPUtil {
private static final Logger LOGGER = LogManager.getLogger(IRPUtil.class);
private final AuditIrpClient auditIrpClient;
private IRPUtil(String config) {
TempConfigStorage configStorage = new TempConfigStorage(config);
JsonObject jo = configStorage.load();
EndpointConfig endpointConfig = configStorage.loadAsEndpointConfig();
if (jo.has("clientDoId")) {
this.auditIrpClient = new AuditIrpClient(jo.get("clientDoId").getAsString(), endpointConfig);
} else {
this.auditIrpClient = new AuditIrpClient(endpointConfig);
}
}
public static IRPUtil createClient(String jsonObject) {
return new IRPUtil(jsonObject);
}
public String test(String doi) {
return "create DOClient And hello " + doi + " World";
}
public Object resolve(String doId) {
try {
StateInfoBase result = auditIrpClient.resolve(doId);
JsonObject r = new JsonObject();
r.addProperty("code", 0);
r.add("handleValues", result.handleValues);
return JSONTool.convertJsonElementToMirror(result.handleValues);
} catch (Exception e) {
JsonObject r = new JsonObject();
r.addProperty("code", 1);
r.addProperty("msg", e.getMessage());
return JSONTool.convertJsonElementToMirror(r);
}
}
public Object register(ScriptObjectMirror mirror) {
JsonObject jo = JSONTool.convertMirrorToJson(mirror).getAsJsonObject();
StateInfoBase base = new StateInfoBase();
JsonObject result = new JsonObject();
if (jo.has("identifier"))
base.identifier = jo.get("identifier").getAsString();
base.handleValues = jo.get("handleValues").getAsJsonObject();
try {
String val = auditIrpClient.register(base);
result.addProperty("code", 0);
result.addProperty("doId", val);
if (val == null || val.length() == 0) {
result.addProperty("code", 1);
result.addProperty("msg", auditIrpClient.getLastResponse().getResponseMessage());
}
return JSONTool.convertJsonElementToMirror(result);
} catch (Exception e) {
result.addProperty("code", 1);
result.addProperty("msg", e.getMessage());
return JSONTool.convertJsonElementToMirror(result);
}
}
}

View File

@@ -1,11 +1,18 @@
package org.bdware.sc.boundry.utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.bdledger.api.grpc.Client;
import org.bdware.bdledger.api.grpc.pb.CommonProto.Transaction;
import org.bdware.bdledger.api.grpc.pb.CommonProto.TransactionType;
import org.bdware.bdledger.api.grpc.pb.LedgerProto.SendTransactionResponse;
import org.bdware.bdledger.api.grpc.pb.QueryProto.GetTransactionByHashResponse;
import org.bdware.sc.boundry.JavaScriptEntry;
import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.Permission;
import org.bdware.sc.util.HashUtil;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
@@ -19,11 +26,28 @@ import java.security.SecureRandom;
public class LedgerUtil {
static SecureRandom random = new SecureRandom((System.currentTimeMillis() + "").getBytes());
public static Object getLedgerParams() {
//format:{nodes:[{ip:ip,port:port}]}
String ledgerParam = JavaScriptEntry.get.syncGet("", "getLedgerParams", "");
JsonElement jo = JsonParser.parseString(ledgerParam);
return JSONTool.convertJsonElementToMirror(jo);
}
public static Client getDefaultClient() {
String ledgerParam = JavaScriptEntry.get.syncGet("", "getLedgerParams", "");
JsonElement jo = JsonParser.parseString(ledgerParam);
JsonObject param = jo.getAsJsonObject().get("nodes").getAsJsonArray().get(0).getAsJsonObject();
return new Client(param.get("ip").getAsString(), param.get("port").getAsInt());
}
public static Client getClient(ScriptObjectMirror str) {
return new Client((String) str.get("ip"), Integer.parseInt(str.get("port").toString()));
}
static Logger LOGGER = LogManager.getLogger(LedgerUtil.class);
public static ScriptObject queryByHash(Client c, ScriptObjectMirror str) {
LOGGER.info("TID:" + Thread.currentThread().getId());
String ledger = str.get("ledger").toString();
String hash = str.get("hash").toString();
JO ret = new JO(PropertyMap.newMap());
@@ -33,6 +57,7 @@ public class LedgerUtil {
ret.put("to", HashUtil.byteArray2Str(transaction.getTo().toByteArray(), 0), false);
ret.put("type", transaction.getType().toString(), false);
ret.put("data", new String(transaction.getData().toByteArray()), false);
ret.put("blockHsah", HashUtil.byteArray2Str(transaction.getBlockHash().toByteArray(), 0), false);
return ret;
}

View File

@@ -3,6 +3,38 @@ package org.bdware.sc.boundry.utils;
import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.node.Permission;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@PermissionStub(permission = Permission.MongoDB)
public class MongoDBUtil extends org.bdware.sc.blockdb.MongoDBUtil {
public class MongoDBUtil {
public static Object connect(String url, int port, String dbName, String usrName, String pwd) {
try {
Class serverAddr = Class.forName("com.mongodb.ServerAddress");
Constructor cons = serverAddr.getConstructor(String.class, Integer.TYPE);
Object serverAddress = cons.newInstance(url, port);
List addrs = new ArrayList<>();
addrs.add(serverAddress);
Method createeScramSha1 =
Class.forName("com.mongodb.MongoCredential")
.getDeclaredMethod(
"createScramSha1Credential",
String.class,
String.class,
char[].class);
Object credential = createeScramSha1.invoke(null, usrName, dbName, pwd.toCharArray());
List credentials = new ArrayList<>();
credentials.add(credential);
Constructor mongoClient =
Class.forName("com.mongodb.MongoClient").getConstructor(List.class, List.class);
Object client = mongoClient.newInstance(addrs, credentials);
// 通过连接认证获取MongoDB连接
return client;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

View File

@@ -0,0 +1,136 @@
package org.bdware.sc.boundry.utils;
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.ContractProcess;
import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.db.MultiIndexTimeRocksDBUtil;
import org.bdware.sc.node.Permission;
import org.rocksdb.RocksDB;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@PermissionStub(permission = Permission.MultiTagIndexDB)
public class MultiTagIndexDBUtil {
private static final Logger LOGGER = LogManager.getLogger(MultiIndexTimeRocksDBUtil.class);
static Map<String, MultiTagIndexDBUtil> cacheDB = new HashMap<>();
static {
RocksDB.loadLibrary();
}
MultiIndexTimeRocksDBUtil rocksDB;
String path;
public MultiTagIndexDBUtil(String path, String tableName) {
try {
this.path = path;
File parent = new File("./ContractDB/" + ContractProcess.getContractDir());
File dir = new File(parent, path);
LOGGER.info("init RocksDB in " + dir.getAbsolutePath());
if (!dir.exists()) {
LOGGER.trace("create directory " + dir.getAbsolutePath() + ": " + dir.mkdirs());
}
File lockFile = new File(dir, "LOCK");
LOGGER.trace("delete file" + lockFile.getAbsolutePath() + ": " + lockFile.delete());
rocksDB = new MultiIndexTimeRocksDBUtil(dir.getAbsolutePath(), tableName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static MultiTagIndexDBUtil loadDB(String path, String tableName) {
if (cacheDB.containsKey(path)) {
return cacheDB.get(path);
}
MultiTagIndexDBUtil ret = new MultiTagIndexDBUtil(path, tableName);
cacheDB.put(path, ret);
return ret;
}
public void close() {
rocksDB.close();
cacheDB.remove(path);
}
public String get(String key) {
try {
return new String(rocksDB.get(key));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public long size() {
try {
return rocksDB.size();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public void put(String label, String value) {
try {
rocksDB.put(label, value);
} catch (Exception e) {
e.printStackTrace();
}
}
public List<String> getTags(String prefix) {
return rocksDB.getIndexStartWith(prefix);
}
public List<String> getAllTags() {
List<String> list = rocksDB.getAllIndexKey();
return list;
}
public long getSize(String tag) {
try {
return rocksDB.size(tag);
} catch (Exception e) {
e.printStackTrace();
}
return 0L;
}
public long queryOffset(String tag, long startTimestamp) {
return rocksDB.queryOffset(tag, startTimestamp);
}
public List<JsonObject> queryByOffset(String tag, long offset, int count) {
return rocksDB.queryByOffset(tag, offset, count);
}
public List<Long> countInInterval(String tag, long startTime, long endTime, long interval) {
List<Long> ret = new ArrayList<>();
if (interval <= 0) return ret;
long start = rocksDB.queryOffset(tag, startTime);
long delta;
startTime += interval;
for (; startTime < endTime; startTime += interval) {
delta = rocksDB.queryOffset(tag, startTime);
ret.add(delta - start);
start = delta;
}
delta = rocksDB.queryOffset(tag, endTime);
ret.add(delta - start);
return ret;
}
public List<String> queryInInterval(String tag, long startTime, long endTime) {
return rocksDB.queryByDateAsString(tag, startTime, endTime);
}
}

View File

@@ -7,7 +7,6 @@ import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.node.Permission;
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import wrp.jdk.nashorn.internal.runtime.PropertyMap;
import wrp.jdk.nashorn.internal.runtime.ScriptObject;
@@ -30,32 +29,43 @@ public class RocksDBUtil {
RocksDB rocksDB;
String path;
public RocksDBUtil(String path, boolean readOnly) {
try {
public void tryLoad(String path, boolean readOnly) throws Exception {
this.path = path;
Options options = new Options();
options.setCreateIfMissing(true);
File parent = new File("./ContractDB/" + ContractProcess.getContractDir());
File dir = new File(parent, path);
System.out.println("[EEEEEEEEEERO]");
LOGGER.info("init RocksDB in " + dir.getAbsolutePath());
//LOGGER.info("init RocksDB in " + dir.getAbsolutePath());
if (!dir.exists()) {
LOGGER.trace("create directory " + dir.getAbsolutePath() + ": " + dir.mkdirs());
LOGGER.info("create directory " + dir.getAbsolutePath() + ": " + dir.mkdirs());
}
File lockFile = new File(dir, "LOCK");
LOGGER.trace("delete file" + lockFile.getAbsolutePath() + ": " + lockFile.delete());
if (readOnly) {
rocksDB = RocksDB.openReadOnly(options, dir.getAbsolutePath());
} else {
rocksDB = RocksDB.open(options, dir.getAbsolutePath());
}
} catch (RocksDBException e) {
}
public RocksDBUtil(String path, boolean readOnly) {
try {
tryLoad(path, readOnly);
} catch (Exception e) {
LOGGER.info("======TRY Load Again 2s later====");
try {
Thread.sleep(2000L);
} catch (InterruptedException ex) {
}
try {
tryLoad(path, readOnly);
} catch (Exception ex) {
LOGGER.info("======LOAD FAILED!====");
e.printStackTrace();
}
}
}
public static RocksDBUtil loadDB(String path, boolean readOnly) {
public static synchronized RocksDBUtil loadDB(String path, boolean readOnly) {
if (cacheDB.containsKey(path)) {
return cacheDB.get(path);
}
@@ -77,7 +87,6 @@ public class RocksDBUtil {
try {
return new String(rocksDB.get(key.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@@ -120,7 +129,6 @@ public class RocksDBUtil {
}
public ScriptObject getNext(RocksIterator iter) {
if (iter.isValid()) {
JO ret = new JO(PropertyMap.newMap());
ret.put("key", new String(iter.key()), false);
@@ -130,4 +138,8 @@ public class RocksDBUtil {
}
return null;
}
public String clean() {
return "todo";
}
}

View File

@@ -17,7 +17,6 @@ public class UtilRegistry {
public static Map<String, String> stubClzNameMap = new HashMap<>();
public static List<Class<?>> getUtilClasses() {
List<String> allName = Permission.allName();
List<Class<?>> ret = new ArrayList<>();
try {
@@ -57,7 +56,6 @@ public class UtilRegistry {
String.format(
"%sUtil = %s.%sUtil%s;\n",
s, UtilRegistry.class.getPackage().getName(), s, open ? "" : "Stub");
LOGGER.debug(ret);
return ret;
}
return "";

View File

@@ -0,0 +1,15 @@
package org.bdware.sc.compiler;
import org.bdware.sc.node.Permission;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PermissionStub {
Permission permission();
}

View File

@@ -0,0 +1,81 @@
package org.bdware.sc.compiler;
import org.objectweb.asm.*;
import java.io.IOException;
import java.io.InputStream;
public class PermissionStubGenerator extends ClassVisitor implements Opcodes {
private final String p;
public PermissionStubGenerator(int api, ClassVisitor cn, String permission) {
super(api, cn);
this.p = permission;
}
public static byte[] generateStub(Class<?> clz, String permission) {
PermissionStub stub = clz.getAnnotation(PermissionStub.class);
if (stub == null)
return null;
try {
String resource = clz.getCanonicalName().replaceAll("\\.", "/") + ".class";
InputStream input = clz.getClassLoader().getResourceAsStream(resource);
ClassReader cr;
cr = new ClassReader(input);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
PermissionStubGenerator generator = new PermissionStubGenerator(ASM4, cw, permission);
cr.accept(generator, 0);
return cw.toByteArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
if (cv != null) {
cv.visit(version, access, name + "Stub", null, "java/lang/Object", null);
}
MethodVisitor mv = cv.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
mv.visitInsn(RETURN);
Label l1 = new Label();
mv.visitLabel(l1);
// mv.visitLocalVariable("this", "Lcom/yancloud/sc/boundry/utils/FileUtilStub;",
// null, l0, l1, 0);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
if (cv != null) {
if (name.equals("<clinit>"))
return null;
if (name.equals("<init>")) {
return null;
}
MethodVisitor mv = cv.visitMethod(access, name, desc, signature,
new String[]{"javax/script/ScriptException"});
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitTypeInsn(NEW, "javax/script/ScriptException");
mv.visitInsn(DUP);
mv.visitLdcInsn("Do not have " + p + " Permission");
mv.visitMethodInsn(INVOKESPECIAL, "javax/script/ScriptException", "<init>", "(Ljava/lang/String;)V");
mv.visitInsn(ATHROW);
mv.visitMaxs(5, 20);
mv.visitEnd();
return null;
}
return null;
}
}

View File

@@ -120,7 +120,7 @@ public class YJSCompiler {
// 如果没有就不限制根据gas进行插装
if (0L != cm.getInsnLimit()) {
System.out.println("++++++++++++++++++++++true");
LOGGER.info("++++++++++++++++++++++true");
}
czb.setManifest(cm);
Set<String> toParse = new HashSet<>();
@@ -137,7 +137,6 @@ public class YJSCompiler {
}
ContractNode cn = compile(zf.getInputStream(entry), str);
czb.put(str, cn);
System.out.println("----" + str);
for (ImportNode in : cn.getImports()) {
todo.add(in.getPath());
}
@@ -163,6 +162,16 @@ public class YJSCompiler {
preSubConName + ".yjs");
czb.put(preSubConName + ".yjs", preSubNode);
LOGGER.info("--compile-- " + preSubConName);
String globalBeanName = cm.main.substring(0, cm.main.length() - 4) + "GlobalBean";
String globalBeanContract =
"contract " + globalBeanName + "{ function setGlobal (_global) { Global = _global; }\n" +
" function getGlobal () { return Global; }}";
czb.put(globalBeanName + ".yjs",
compile(new ByteArrayInputStream(globalBeanContract.getBytes(StandardCharsets.UTF_8)),
globalBeanName + ".yjs"));
LOGGER.info("--compile-- " + globalBeanName);
return czb;
}
@@ -179,17 +188,14 @@ public class YJSCompiler {
ProgramContext tree = parser.program();
// 应该是antlr4访问器进行遍历语法树
ContractReader reader = new ContractReader(fileName);
System.out.println("遍历语法树");
contract = reader.visitProgram(tree);
// 遍历完 获取 contract 里的 yjs type
System.out.println(contract.getYjsType());
contract.initPlainText(cts);
handleAnnotation(contract);//处理注解
return contract;
}
private void handleAnnotation(ContractNode contractNode) {
System.out.println("handleAnnotation");
for (AnnotationNode node : contract.annotations) {
AnnotationProcessor processor = findProcessor(node);
if (processor != null) {
@@ -200,8 +206,6 @@ public class YJSCompiler {
List<AnnotationNode> annos = functionNode.annotations;//函数里的annotation
if (annos != null)
for (AnnotationNode anno : annos) {
System.out.println(anno.getType());//打印类型和参数
System.out.println(anno.getArgs());
AnnotationProcessor processor = findProcessor(anno);
if (processor != null)
processor.processFunction(anno, contractNode, functionNode);

View File

@@ -3,13 +3,14 @@ package org.bdware.sc.compiler.ap;
import org.bdware.sc.compiler.AnnotationProcessor;
import org.bdware.sc.node.AnnotationNode;
import org.bdware.sc.node.ContractNode;
import org.bdware.sc.node.FunctionNode;
public class Access extends AnnotationProcessor {
@Override
public void processContract(AnnotationNode anno, ContractNode contractNode) {
contractNode.sigRequired = false;
if (anno != null) {
contractNode.sigRequired = "\"verified\"".equals(anno.getArgs().get(0));
for (FunctionNode fn : contractNode.getFunctions()) {
fn.addAnnotation(anno);
}
}
}

View File

@@ -0,0 +1,37 @@
package org.bdware.sc.compiler.ap;
import org.bdware.doip.codec.operations.BasicOperations;
import org.bdware.sc.bean.DoipOperationInfo;
import org.bdware.sc.compiler.AnnotationProcessor;
import org.bdware.sc.engine.hook.DOOPHandler;
import org.bdware.sc.handler.DOOPRequestHandler;
import org.bdware.sc.node.AnnotationNode;
import org.bdware.sc.node.ContractNode;
import org.bdware.sc.node.FunctionNode;
import java.util.List;
// DOOP is designed for DoipModule which contains specific functions for RepositoryHandler
public class DOOP extends AnnotationProcessor {
@Override
public void processFunction(AnnotationNode anno, ContractNode contractNode, FunctionNode functionNode) {
// 通过DOOP注解解析对应的值并放进对应的FunctionNode中
// 注解必须暴露出来昂!!!
functionNode.setIsExport(true);
functionNode.setIsDoipOperation(true);
functionNode.setDoipOperationInfo(DoipOperationInfo.create(anno, contractNode));
// functionNode.setFunctionName(functionNode.getDoipOperationInfo().operationName);
// 维护DOOPRequestHandler
DOOPRequestHandler.createHandler();
DOOPRequestHandler.instance.addDoipOperation(functionNode);
// 维护DOOPHandler
DOOPHandler.createDOOPHandler();
DOOPHandler.instance.putFuncNameAndDoipOperationsMapping(functionNode);
// 维护ContractNodefunctionName is useless, use BasicOperation to map the corresponding functionNode
// contractNode.updateFunctionMap(functionNode.functionName, functionNode.getDoipOperationInfo().operationName);
}
}

View File

@@ -18,6 +18,7 @@ import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.bean.ProjectConfig;
import org.bdware.sc.boundry.JavaScriptEntry;
import org.bdware.sc.boundry.Resources;
import org.bdware.sc.boundry.ScriptReturnException;
import org.bdware.sc.boundry.utils.UtilRegistry;
import org.bdware.sc.encrypt.HardwareInfo;
import org.bdware.sc.encrypt.HardwareInfo.OSType;
@@ -31,6 +32,7 @@ import org.bdware.sc.util.HashUtil;
import org.bdware.sc.util.JsonUtil;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.MethodNode;
import wrp.jdk.nashorn.api.scripting.NashornException;
import wrp.jdk.nashorn.api.scripting.NashornScriptEngine;
import wrp.jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
@@ -39,6 +41,7 @@ import wrp.jdk.nashorn.internal.runtime.*;
import javax.script.*;
import java.io.*;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
@@ -64,6 +67,7 @@ public class DesktopEngine extends JSEngine {
// private String traceDir;
private ContractProcess.Logger tracePS = null;
private Contract contract;
private ContractManifest manifest;
public DesktopEngine() {
startEngine();
@@ -82,7 +86,7 @@ public class DesktopEngine extends JSEngine {
startEngine();
}
public static void applyWithGlobal(ScriptFunction script, Global global, Object... obj) {
public static Object applyWithGlobal(ScriptFunction script, Global global, Object... obj) {
Global oldGlobal = Context.getGlobal();
boolean globalChanged = (oldGlobal != global);
try {
@@ -91,8 +95,10 @@ public class DesktopEngine extends JSEngine {
}
// System.out.println("[DesktopEngine]" + script.getName() + " -->\n" +
// script.safeToString());
ScriptRuntime.apply(script, global, obj);
Object ret = ScriptRuntime.apply(script, global, obj);
return ret;
} catch (NashornException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
} finally {
@@ -100,6 +106,7 @@ public class DesktopEngine extends JSEngine {
Context.setGlobal(oldGlobal);
}
}
return null;
}
public void setRecovering(boolean b) {
@@ -247,7 +254,6 @@ public class DesktopEngine extends JSEngine {
@Override
public ContractResult loadContract(
Contract contract, ContractNode contractNode, boolean isInsnLimit) {
LOGGER.info("loadContract isInsnLimit:" + isInsnLimit);
cn = contractNode;
engine.getContext()
.setAttribute(ScriptEngine.FILENAME, ScriptFileName, ScriptContext.ENGINE_SCOPE);
@@ -265,7 +271,7 @@ public class DesktopEngine extends JSEngine {
ScriptEngine.FILENAME,
fun.getFileName(),
ScriptContext.ENGINE_SCOPE);
compileFunction(str, isInsnLimit);
compileFunction(fun, str, isInsnLimit);
} catch (ScriptException e) {
return wrapperException(e, fun);
} catch (Exception e) {
@@ -293,6 +299,8 @@ public class DesktopEngine extends JSEngine {
}
ScriptObjectMirror globalVars = (ScriptObjectMirror) engine.get("Global");
ConfidentialContractUtil.generateConfidentialContract(cn, globalVars, global);
Context.setGlobal(global);
ContractResult cResult =
new ContractResult(Status.Success, new JsonPrimitive(contract.getPublicKey()));
cResult.isInsnLimit = isInsnLimit;
@@ -313,13 +321,13 @@ public class DesktopEngine extends JSEngine {
"function %s(arg) { YancloudUtil.pubEventConstraint(\"%s\", arg, \"%s\"); }",
name, topic, semantics.name());
}
compileFunction(str, false);
compileFunction(null, str, false);
LOGGER.debug("compile function " + name + " success!");
str =
String.format(
"function %ss(arg0, arg1) { YancloudUtil.pubEventConstraint(\"%s\", arg0, arg1); }",
name, topic);
compileFunction(str, false);
compileFunction(null, str, false);
LOGGER.debug("compile function " + name + "s success!");
} catch (ScriptException e) {
e.printStackTrace();
@@ -398,7 +406,7 @@ public class DesktopEngine extends JSEngine {
//
// return new ContractResult(Status.Success, new JsonPrimitive(""));
// }
private void compileFunction(ScriptObjectMirror sf, boolean instrumentBranch) {
private void compileFunction(FunctionNode functionNode, ScriptObjectMirror sf, boolean instrumentBranch) {
Global oldGlobal = Context.getGlobal();
boolean globalChanged = (oldGlobal != global);
try {
@@ -410,7 +418,32 @@ public class DesktopEngine extends JSEngine {
Context.TRACEMETHOD = true;
}
sf.compileScriptFunction();
ScriptFunction scriptFunction = (ScriptFunction) sf.getScriptObject();
Field f = ScriptFunction.class.getDeclaredField("data");
f.setAccessible(true);
ScriptFunctionData scriptFunctioNData = (ScriptFunctionData) f.get(scriptFunction);
Object scope = scriptFunction.getScope();
Method getGeneric = ScriptFunctionData.class.getDeclaredMethod("getGenericInvoker", ScriptObject.class);
getGeneric.setAccessible(true);
MethodHandle methodHandle = (MethodHandle) getGeneric.invoke(scriptFunctioNData, scope);
if (methodHandle.getClass() != Class.forName("java.lang.invoke.DirectMethodHandle")) {
Field argL0 = methodHandle.getClass().getDeclaredField("argL0");
argL0.setAccessible(true);
methodHandle = (MethodHandle) argL0.get(methodHandle);
}
Field memberNameField = methodHandle.getClass().getDeclaredField("member");
memberNameField.setAccessible(true);
Object memberName = memberNameField.get(methodHandle);
Field clazz = memberName.getClass().getDeclaredField("clazz");
clazz.setAccessible(true);
Class clazz2 = (Class) clazz.get(memberName);
if (functionNode != null)
functionNode.compiledClazz = clazz2;
//functionNode==null --> event functions
} catch (Exception e) {
e.printStackTrace();
} finally {
if (globalChanged) Context.setGlobal(oldGlobal);
@@ -418,13 +451,18 @@ public class DesktopEngine extends JSEngine {
}
}
public void compileFunction(String snippet, boolean instrumentBranch) throws ScriptException {
compileFunction((ScriptObjectMirror) engine.eval(snippet), instrumentBranch);
public void compileFunction(FunctionNode functionNode, String snippet, boolean instrumentBranch) throws ScriptException {
compileFunction(functionNode, (ScriptObjectMirror) engine.eval(snippet), instrumentBranch);
}
@Override
public synchronized ContractResult executeContract(ContractRequest input) {
public ContractResult executeContract(ContractRequest input) {
Global oldGlobal = Context.getGlobal();
boolean globalChanged = (oldGlobal != global);
if (globalChanged) {
Context.setGlobal(global);
}
ContractProcess.Logger previous = this.getTracePS();
ByteArrayOutputStream bo = null;
if (syncUtil.startFlag && syncUtil.currType == SyncType.Trace && !recovering) {
@@ -473,34 +511,19 @@ public class DesktopEngine extends JSEngine {
ppCountMap);
this.redirectTracePS(ppc);
}
Invocable cal = engine;
if (fun.isExport() ||
// if the function has been registered as event handler
(fun.isHandler() &&
null != input.getRequester() &&
input.getRequester().startsWith("event"))) {
Object ret = null;
// long start = System.currentTimeMillis();
Object ret;
if (fun.isView()) {
ret = executeWithoutLock(fun, input, null);
} else {
synchronized (this) {
ret = executeWithoutLock(fun, input, null);
for (AnnotationHook handler : fun.beforeExecutionAnnotations()) {
ret = handler.handle(input, this, ret);
}
// actually invoke!
if (ret == null) {
ret =
cal.invokeFunction(
input.getAction(),
(fun.isHandler()
? JsonUtil.fromJson(input.getArg(), Event.class)
: JSONTool.convertJsonElementToMirror(input.getArg())),
input.getRequester(),
input.getRequesterDOI());
}
for (AnnotationHook handler : fun.afterExecutionAnnotations()) {
//Mask在after裏面
//System.out.println("afterHook"+contract.Mask);
ret = handler.handle(input, this, ret);
}
//System.out.println("[DesktopEngine MaskConfig]"+ContractProcess.instance.getProjectConfig().getMaskConfig().config.toString());
ContractResult contractRes = new ContractResult(Status.Success, (JsonElement) ret);
@@ -519,7 +542,7 @@ public class DesktopEngine extends JSEngine {
List<REvent> msgList = JavaScriptEntry.msgList;
JavaScriptEntry.msgList = null;
if (!msgList.isEmpty()) {
if (msgList != null && !msgList.isEmpty()) {
contractRes.events = msgList;
contractRes.eventRelated = true;
}
@@ -530,10 +553,10 @@ public class DesktopEngine extends JSEngine {
if (syncUtil.startFlag && !recovering) {
switch (syncUtil.currType) {
case Trace:
syncUtil.traceRecordUtil.eachFinish();
// syncUtil.traceRecordUtil.eachFinish();
break;
case Trans:
syncUtil.transRecordUtil.eachFinish();
// syncUtil.transRecordUtil.eachFinish();
break;
case Memory:
default:
@@ -550,6 +573,11 @@ public class DesktopEngine extends JSEngine {
new JsonPrimitive("Action " + input.getAction() + " is not exported!"));
}
} catch (ScriptReturnException e) {
e.printStackTrace();
return new ContractResult(
Status.Exception,
e.message);
} catch (ScriptException e) {
Throwable cause = e.getCause();
e.printStackTrace();
@@ -573,7 +601,39 @@ public class DesktopEngine extends JSEngine {
}
} finally {
this.redirectTracePS(previous);
if (globalChanged) Context.setGlobal(oldGlobal);
}
}
public Object executeWithoutLock(FunctionNode fun, ContractRequest input, Object injectedArg) throws ScriptException, NoSuchMethodException {
// long start = System.currentTimeMillis();
ArgPacks argPacks = new ArgPacks(input, input.getArg(), null);
if(injectedArg != null) {
argPacks.arg = injectedArg;
}
for (AnnotationHook handler : fun.beforeExecutionAnnotations()) {
argPacks = handler.handle(this, argPacks);
}
// actually invoke!
if (argPacks.ret == null) {
argPacks.ret =
engine.invokeFunction(
input.getAction(),
(fun.isHandler()
? JsonUtil.fromJson(input.getArg(), Event.class)
: JSONTool.convertJsonElementToMirror(argPacks.arg)),
input.getRequester(),
input.getRequesterDOI());
}
for (AnnotationHook handler : fun.afterExecutionAnnotations()) {
//Mask在after裏面
//System.out.println("afterHook"+contract.Mask);
argPacks = handler.handle(this, argPacks);
}
return argPacks.ret;
}
private String extractException(String msg, List<String> stack) {
@@ -856,9 +916,6 @@ public class DesktopEngine extends JSEngine {
try {
assert null != loader;
if (entry.getName().endsWith(".jar")) {
System.out.println("[DesktopEngine] loadJar:" + entry.getName());
System.out.println("[DesktopEngine] classLoader:" + getClassLoad());
loader.loadJar(zf.getInputStream(entry), entry.getName().replaceAll(".*/", ""));
}
if (entry.getName().endsWith(".so") || entry.getName().endsWith(".so.1")) {
@@ -895,8 +952,12 @@ public class DesktopEngine extends JSEngine {
return null;
}
public void initManifest(ContractManifest manifest) {
// TODO Auto-generated method stub
public void setManifest(ContractManifest manifest) {
this.manifest = manifest;
}
public ContractManifest getManifest() {
return this.manifest;
}
public ContractProcess.Logger getTracePS() {

View File

@@ -1,12 +1,14 @@
package org.bdware.sc.engine;
import com.google.gson.*;
import jdk.nashorn.internal.runtime.Context;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
import wrp.jdk.nashorn.internal.objects.NativeArray;
import wrp.jdk.nashorn.internal.runtime.PropertyMap;
import wrp.jdk.nashorn.internal.runtime.ScriptObject;
import wrp.jdk.nashorn.internal.scripts.JO;
import java.util.HashSet;
import java.util.Set;
import java.util.*;
public class JSONTool {
public static JsonElement convertMirrorToJson(Object ret2) {
@@ -29,22 +31,62 @@ public class JSONTool {
}
return jo;
} else if (jsonElement.isJsonArray()) {
JO jo = new JO(PropertyMap.newMap());
jo.setIsArray();
NativeArray narray = new NativeArray();
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++)
jo.put(i, convertJsonElementToMirror(jsonArray.get(i)), false);
return jo;
NativeArray.push(narray, convertJsonElementToMirror(jsonArray.get(i)));
return narray;
}
return null;
}
public static Object convertJsonElementToMirror(Object input) {
if(input instanceof JsonElement) {
return convertJsonElementToMirror((JsonElement) input);
} else {
return input;
}
}
private static JsonElement convertMirrorToJsonInternal(Object obj, Set<Object> recorded) {
if (recorded.contains(obj)) return JsonNull.INSTANCE;
if (obj == null) return JsonNull.INSTANCE;
if (obj.getClass() == wrp.jdk.nashorn.internal.runtime.Undefined.class)
return JsonNull.INSTANCE;
if (obj.getClass() == ScriptObjectMirror.class) {
if (obj instanceof JsonElement) return (JsonElement) obj;
if (obj.getClass().isArray()) {
Object[] arr = (Object[]) obj;
recorded.add(obj);
JsonArray jsonArray = new JsonArray();
for (int i = 0; i < arr.length; i++) {
jsonArray.add(convertMirrorToJsonInternal(arr[i], recorded));
}
return jsonArray;
} else if (List.class.isAssignableFrom(obj.getClass())) {
List arr = (List) obj;
recorded.add(arr);
JsonArray jsonArray = new JsonArray();
for (int i = 0; i < arr.size(); i++) {
jsonArray.add(convertMirrorToJsonInternal(arr.get(i), recorded));
}
return jsonArray;
} else if (List.class.isAssignableFrom(obj.getClass())) {
List arr = (List) obj;
recorded.add(arr);
JsonArray jsonArray = new JsonArray();
for (int i = 0; i < arr.size(); i++) {
jsonArray.add(convertMirrorToJsonInternal(arr.get(i), recorded));
}
return jsonArray;
} else if (Set.class.isAssignableFrom(obj.getClass())) {
Set arr = (Set) obj;
recorded.add(arr);
JsonArray jsonArray = new JsonArray();
for (Object k : arr) {
jsonArray.add(convertMirrorToJsonInternal(k, recorded));
}
return jsonArray;
} else if (obj.getClass() == ScriptObjectMirror.class) {
recorded.add(obj);
ScriptObjectMirror som = (ScriptObjectMirror) obj;
if (som.isFunction()) {
@@ -52,7 +94,6 @@ public class JSONTool {
}
if (som.isArray()) {
JsonArray jarray = new JsonArray();
for (String str : som.getOwnKeys(true)) {
try {
if (Integer.parseInt(str) >= 0)
@@ -95,6 +136,14 @@ public class JSONTool {
}
return jo;
}
} else if (Map.class.isAssignableFrom(obj.getClass())) {
Map arr = (Map) obj;
recorded.add(arr);
JsonObject jsonObject = new JsonObject();
for (Object k : arr.keySet()) {
jsonObject.add(k.toString(), convertMirrorToJsonInternal(arr.get(k), recorded));
}
return jsonObject;
} else if (obj.getClass() == jdk.internal.dynalink.beans.StaticClass.class) {
return JsonNull.INSTANCE;
} else if (obj instanceof Number) {

View File

@@ -84,7 +84,7 @@ public class YJSClassLoader extends URLClassLoader {
private void addDirToPath(String s) {
try {
System.out.println("[YJSClassloader] addtopath:" + s);
// System.out.println("[YJSClassloader] addtopath:" + s);
Field field = ClassLoader.class.getDeclaredField("sys_paths");
field.setAccessible(true);
String[] path = (String[]) field.get(null);

View File

@@ -0,0 +1,78 @@
package org.bdware.sc.engine.hook;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.boundry.ScriptReturnException;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.AnnotationNode;
import org.bdware.sc.node.ArgPacks;
import org.bdware.sc.node.FunctionNode;
import wrp.jdk.nashorn.internal.objects.Global;
import wrp.jdk.nashorn.internal.runtime.Context;
import wrp.jdk.nashorn.internal.runtime.PropertyMap;
import wrp.jdk.nashorn.internal.scripts.JO;
@YJSAnnotation(name = "Access")
public class AccessHandler implements AnnotationHook {
public String acFunction;
public boolean requireSign;
public AccessHandler(AnnotationNode annoNode) {
requireSign = false;
String content = annoNode.getArgs().get(0);
JsonElement je = JsonParser.parseString(content);
if (je.isJsonPrimitive() && je.getAsJsonPrimitive().getAsString().equals("verified")) {
requireSign = true;
}
if (je.isJsonObject()) {
acFunction = je.getAsJsonObject().get("ACFunction").getAsString();
}
}
public static AccessHandler fromAnnotationNode(FunctionNode funNode, AnnotationNode annoNode) {
return new AccessHandler(annoNode);
}
@Override
public ArgPacks handle(JSEngine desktopEngine, ArgPacks argPacks) {
if (requireSign) {
if (!argPacks.request.verifySignature()) {
throw new ScriptReturnException(JsonParser.parseString("{\"code\":400,\"msg\":\"permission denied\"}"));
}
return argPacks;
}
if (acFunction == null) return argPacks;
DesktopEngine de = (DesktopEngine) desktopEngine;
Global oldGlobal = Context.getGlobal();
Global newGlobal = de.getDesktopGlobal();
boolean globalChanged = (oldGlobal != newGlobal);
try {
if (globalChanged) {
Context.setGlobal(newGlobal);
}
ContractRequest input = argPacks.request;
JO jo = new JO(PropertyMap.newMap());
jo.put("requester", input.getRequester(), false);
jo.put("action", input.getAction(), false);
jo.put("arg", JSONTool.convertJsonElementToMirror(input.getArg()), false);
de.engine.invokeFunction(acFunction, jo);
return argPacks;
} catch (ScriptReturnException e) {
throw e;
} catch (Exception e) {
JsonObject jo = new JsonObject();
jo.addProperty("code", "401");
jo.addProperty("msg", "access check meets exception! " + e);
throw new ScriptReturnException(jo);
} finally {
if (globalChanged) Context.setGlobal(oldGlobal);
}
}
}

View File

@@ -0,0 +1,72 @@
package org.bdware.sc.engine.hook;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.boundry.ScriptReturnException;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.AnnotationNode;
import org.bdware.sc.node.ArgPacks;
import org.bdware.sc.node.FunctionNode;
@YJSAnnotation(name = "ArgSchema")
public class ArgSchemaHandler implements AnnotationHook {
private AnnotationNode a;
private static final Logger LOGGER = LogManager.getLogger(ArgSchemaHandler.class);
public ArgSchemaHandler(AnnotationNode annoNode) {
a = annoNode;
String arg = a.getArgs().get(0);
// if (arg.startsWith("/")){
// ;//ContractProcess.instance.engine.getResources().loadAsString(arg);
// }else {
// ;
// }
}
public static ArgSchemaHandler fromAnnotationNode(FunctionNode funNode, AnnotationNode annoNode) {
return new ArgSchemaHandler(annoNode);
}
@Override
public ArgPacks handle(JSEngine Engine, ArgPacks argPacks) throws ScriptReturnException {
ContractRequest input = argPacks.request;
JsonElement je = input.getArg();
ArgSchemaVisitor visitor;
if (je.isJsonObject())
visitor = new ArgSchemaVisitor(input.getArg().getAsJsonObject());
else {
try {
JsonElement obj = JsonParser.parseString(input.getArg().getAsString());
visitor = new ArgSchemaVisitor(obj);
//IMPORTANT automatically convert arg type here
input.setArg(obj);
argPacks.arg = obj;
} catch (Exception e) {
e.printStackTrace();
JsonObject jo = new JsonObject();
jo.addProperty("msg", "[Illegal Type] argument should be JSON");
jo.addProperty("code", 1004);
throw new ScriptReturnException(jo);
}
}
if (je.toString().isEmpty() && !a.getArgs().get(0).equals("")) {
JsonObject jo = new JsonObject();
jo.addProperty("msg", "[Empty argument] argument should not be empty");
jo.addProperty("code", 1003);
throw new ScriptReturnException(jo);
}
visitor.visit(JsonParser.parseString(a.getArgs().get(0)));
if (!visitor.getStatus()) {
JsonObject jo = new JsonObject();
jo.addProperty("msg", visitor.getException());
jo.addProperty("code", visitor.errorCode);
throw new ScriptReturnException(jo);
}
return argPacks;
}
}

View File

@@ -0,0 +1,152 @@
package org.bdware.sc.engine.hook;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.bdware.mockjava.JsonVisitor;
public class ArgSchemaVisitor extends JsonVisitor {
JsonElement root;
public boolean status = true;
public int errorCode = 0;
//{"msg":"xxx","code":1000}
//
// JsonElement message = new JsonPrimitive("");
public String message = "";
public ArgSchemaVisitor(JsonElement ret) {
root = ret;
}
@Override
public JsonVisitor visitObject(JsonObject schema) {
//message = new JsonObject();
if (root.isJsonObject()) {
JsonObject jo = root.getAsJsonObject();
for (String key : schema.keySet()) {
if (key.startsWith("!")) {
//TODO
//if(必選)
if (jo.has(key.substring(1))) {
ArgSchemaVisitor visitor = new ArgSchemaVisitor(jo.get(key.substring(1)));
visitor.visit(schema.get(key));
if (!visitor.status) {
errorCode += visitor.errorCode;
message += visitor.message;
}
status &= visitor.status;
} else {
message += "[Missing argument] " + key.substring(1) + " should be supplied ";
status = false;
errorCode = 1002;
}
} else {
if (jo.has(key)) {
ArgSchemaVisitor visitor = new ArgSchemaVisitor(jo.get(key));
visitor.visit(schema.get(key));
if (!visitor.status) {
message += visitor.message;
errorCode += visitor.errorCode;
}
status &= visitor.status;
}
}
}
} else {
message += "[Incorrect type] should be object";
status = false;
errorCode = 1003;
}
return this;
}
@Override
public JsonVisitor visitJsonArray(JsonArray ele) {
if (root.isJsonArray()) {
JsonArray array = root.getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
ArgSchemaVisitor visitor = new ArgSchemaVisitor(array.get(i));
visitor.visit(ele.get(0));
message += visitor.message;
status &= visitor.status;
}
}
return this;
}
public JsonElement get() {
return root;
}
@Override
public JsonVisitor visitPrimitive(JsonPrimitive primitive) {
//
if (primitive.isString()) {
String type = primitive.getAsString();
try {
String result = "";
//md5不需要参数
if (type.equals("string")) {
if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isString()) {
return this;
} else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be string";
status = false;
errorCode = 1001;
return this;
}
} else if (type.equals("number")) {
if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isNumber()) {
return this;
} else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be number";
status = false;
errorCode = 1001;
return this;
}
} else if (type.equals("boolean")) {
if (root.isJsonPrimitive() && root.getAsJsonPrimitive().isBoolean()) {
return this;
} else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be boolean";
status = false;
errorCode = 1001;
return this;
}
} else if (type.equals("[]")) {
if (root.isJsonArray()) {
return this;
} else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be array";
status = false;
errorCode = 1001;
return this;
}
} else if (type.equals("{}")) {
if (root.isJsonObject()) {
return this;
} else {
message = "[Type error] The value (" + root.getAsJsonPrimitive().getAsString() + ") should be object";
status = false;
errorCode = 1001;
return this;
}
}
} catch (Exception e) {
System.out.println(e);
}
}
return this;
}
public boolean getStatus() {
return status;
}
public String getException() {
return message;
}
}

View File

@@ -5,6 +5,7 @@ import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.engine.ConfidentialContractUtil;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
import org.bdware.sc.node.FunctionNode;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
@@ -16,19 +17,20 @@ public class ConfidentialHandler implements AnnotationHook {
}
@Override
public Object handle(ContractRequest input, JSEngine engine, Object ret) {
public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
try {
ContractRequest input = argPacks.request;
DesktopEngine desktopEngine = (DesktopEngine) engine;
ConfidentialContractUtil.copyTemplateToDestination(input);
ScriptObjectMirror globalVars = (ScriptObjectMirror) desktopEngine.get("Global");
ConfidentialContractUtil.dumpScriptAndStates(
desktopEngine.engine, fun, input, globalVars);
// run in SGX instead of Nashorn if function has @Confidential annotation
ret = ConfidentialContractUtil.executeConfidentialContract(input);
return ret;
argPacks.ret = ConfidentialContractUtil.executeConfidentialContract(input);
return argPacks;
} catch (Exception e) {
e.printStackTrace();
}
return ret;
return argPacks;
}
}

View File

@@ -0,0 +1,129 @@
package org.bdware.sc.engine.hook;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.codec.doipMessage.DoipMessageFactory;
import org.bdware.doip.codec.doipMessage.DoipResponseCode;
import org.bdware.doip.codec.operations.BasicOperations;
import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.boundry.ScriptReturnException;
import org.bdware.sc.entity.DoipMessagePacker;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
import org.bdware.sc.node.FunctionNode;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class DOOPHandler implements AnnotationHook {
public static Map<String, BasicOperations> funcNameToDoipOperations;
public static DOOPHandler instance;
public DOOPHandler() {
funcNameToDoipOperations = new HashMap<>();
}
public static DOOPHandler createDOOPHandler() {
if(instance == null) {
instance = new DOOPHandler();
}
return instance;
}
public void putFuncNameAndDoipOperationsMapping(FunctionNode fn) {
String basicOperationsString = fn.getDoipOperationInfo().operationType;
BasicOperations operation = BasicOperations.Unknown;
for(BasicOperations basicOperation : BasicOperations.values()) {
if(basicOperation.toString().equals(basicOperationsString)) {
operation = basicOperation;
}
}
funcNameToDoipOperations.put(fn.getFunctionName(), operation);
}
@Override
public ArgPacks handle(JSEngine desktopEngine, ArgPacks argPacks) {
Object arg = argPacks.arg;
DoipMessagePacker doipMsgPackerArg = new DoipMessagePacker();
if (arg instanceof DoipMessagePacker){
doipMsgPackerArg = (DoipMessagePacker)arg;
} else {
// validate http request's params
ContractRequest httpReq = argPacks.request;
validateHTTPRequestArgs(httpReq);
// set doipMsgPackerArg struct's params
doipMsgPackerArg.setSource("http");
doipMsgPackerArg.rawDoipMsg = convertContractRequestToDoipMessage(httpReq);
}
argPacks.arg = doipMsgPackerArg;
return argPacks;
}
public static void validateHTTPRequestArgs(ContractRequest httpReq) {
JsonElement originArgs = httpReq.getArg();
JsonElement httpArgs = JsonParser.parseString(originArgs.getAsString());
BasicOperations curOp = funcNameToDoipOperations.get(httpReq.getAction());
// get args rules and validate http args
JsonElement httpArgsRules = getRulesForBasicOperation(curOp);
ArgSchemaVisitor visitor = new ArgSchemaVisitor(httpArgs);
visitor.visit(httpArgsRules);
if (!visitor.getStatus()) {
JsonObject jo = new JsonObject();
jo.addProperty("msg", visitor.getException());
jo.addProperty("code", visitor.errorCode);
throw new ScriptReturnException(jo);
}
}
public static JsonElement getRulesForBasicOperation(BasicOperations basicOperation) {
switch(basicOperation) {
case Hello:
return JsonParser.parseString("{\"!doid\":\"string\"}");
case Retrieve:
return JsonParser.parseString("{\"!doid\":\"string\", \"!element\":\"boolean\"}");
default:
return null;
}
}
public static DoipMessage convertContractRequestToDoipMessage(ContractRequest httpReq) {
BasicOperations httpOperation = funcNameToDoipOperations.get(httpReq.getAction());
JsonObject jsonParams = JsonParser.parseString(httpReq.getArg().getAsString()).getAsJsonObject();
DoipMessage doipMessage = new DoipMessageFactory.DoipMessageBuilder().createRequest("", httpReq.getAction()).create();
switch(httpOperation) {
case Hello:
doipMessage = new DoipMessageFactory.DoipMessageBuilder().createRequest(jsonParams.get("doid").getAsString(), httpReq.getAction()).create();
break;
case Retrieve:
DoipMessageFactory.DoipMessageBuilder msgBuilder = new DoipMessageFactory.DoipMessageBuilder().createRequest(jsonParams.get("doid").getAsString(), httpReq.getAction());
msgBuilder = msgBuilder.addAttributes("element", jsonParams.get("element").getAsString());
doipMessage = msgBuilder.create();
break;
}
return doipMessage;
}
public static DoipMessage convertJsonElementToDoipMessage(JsonElement jsonElementRet, DoipMessage msg) {
DoipMessageFactory.DoipMessageBuilder builder = new DoipMessageFactory.DoipMessageBuilder();
String responseCodeStr = jsonElementRet.getAsJsonObject().get("doipResponseCode").getAsString();
DoipResponseCode responseCode = DoipResponseCode.UnKnownError;
for (DoipResponseCode resp : DoipResponseCode.values()) {
if (resp.toString().equals(responseCodeStr)) responseCode = resp;
}
DoipMessage doipRet = builder.createResponse(responseCode, msg).create();;
doipRet.body.encodedData = jsonElementRet.getAsJsonObject().get("body").getAsJsonObject().get("encodedData").getAsString().getBytes(StandardCharsets.UTF_8);
return doipRet;
}
}

View File

@@ -6,9 +6,9 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.ContractResult;
import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.boundry.JavaScriptEntry;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
import org.bdware.sc.node.FunctionNode;
import org.bdware.sc.util.JsonUtil;
import org.paillier.PaillierKeyPair;
@@ -25,7 +25,7 @@ public class HomomorphicDecryptHandler implements AnnotationHook {
}
@Override
public Object handle(ContractRequest input, JSEngine engine, Object ret) {
public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
try {
// GetHomArgs args =
// new GetHomArgs(
@@ -45,18 +45,18 @@ public class HomomorphicDecryptHandler implements AnnotationHook {
RSAPrivateKey privkey = (RSAPrivateKey) PaillierKeyPair.pemToPrivateKey(privKeyStr);
LOGGER.info("HomomorphicEncryptHandler--------------------------------3: " + privkey);
HomoVisitor.privateKey = privkey;
ret = getDecryptResult(homoDecryptConf, JsonUtil.parseObject(ret));
if (null != ret) {
return ret;
argPacks.ret = getDecryptResult(homoDecryptConf, JsonUtil.parseObject(argPacks.ret));
if (null != argPacks.ret) {
return argPacks;
}
ret = new JsonObject();
argPacks.ret = new JsonObject();
}
return ret;
return argPacks;
// return ret;
} catch (Exception e) {
e.printStackTrace();
}
return ret;
return argPacks;
}
private Object getDecryptResult(JsonElement homoDecryptConf, JsonElement data) {

View File

@@ -9,6 +9,7 @@ import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.boundry.JavaScriptEntry;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
import org.bdware.sc.node.FunctionNode;
import org.bdware.sc.util.JsonUtil;
import org.paillier.PaillierKeyPair;
@@ -25,15 +26,16 @@ public class HomomorphicEncryptHandler implements AnnotationHook {
}
@Override
public Object handle(ContractRequest input, JSEngine engine, Object ret) {
public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
try {
ContractRequest input = argPacks.request;
LOGGER.info(
"HomomorphicEncryptHandler--------------------------------1: "
+ input.getRequester());
LOGGER.info(
"HomomorphicEncryptHandler--------------------------------2: "
+ this.fun.getSecretID());
JsonElement response = (JsonElement) ret;
JsonElement response = (JsonElement) argPacks.ret;
JsonElement homoEncryptConf = this.fun.getHomoEncryptConf();
if (homoEncryptConf != null && !homoEncryptConf.isJsonNull()) {
String res =
@@ -54,20 +56,20 @@ public class HomomorphicEncryptHandler implements AnnotationHook {
// if (homoEncryptConf.getAsJsonPrimitive().isString())
// homoEncryptConf = JsonParser.parseString(homoEncryptConf.getAsString());
LOGGER.info("HomomorphicEncryptHandler--------------------------------6: " + homoEncryptConf);
LOGGER.info("HomomorphicEncryptHandler--------------------------------7: " + ret);
LOGGER.info("HomomorphicEncryptHandler--------------------------------8: " + ret.toString());
LOGGER.info("HomomorphicEncryptHandler--------------------------------7: " + argPacks.ret);
LOGGER.info("HomomorphicEncryptHandler--------------------------------8: " + argPacks.ret.toString());
// LOGGER.info("HomomorphicEncryptHandler--------------------------------9: " + JsonUtil.toJson(ret));
ret = getEncryptResult(homoEncryptConf, response);
if (ret != null) {
return ret;
argPacks.ret = getEncryptResult(homoEncryptConf, response);
if (argPacks.ret != null) {
return argPacks;
}
ret = new JsonObject();
argPacks.ret = new JsonObject();
}
return ret;
return argPacks;
} catch (Exception e) {
e.printStackTrace();
}
return ret;
return argPacks;
}
private Object getEncryptResult(JsonElement homoEncryptConf, JsonElement data) {

View File

@@ -9,13 +9,16 @@ import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.bean.ProjectConfig;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
public class MaskHandler implements AnnotationHook {
private static final Logger LOGGER = LogManager.getLogger(MaskHandler.class);
@Override
public Object handle(ContractRequest input, JSEngine Engine, Object ret) {
public ArgPacks handle(JSEngine Engine, ArgPacks argPacks) {
try {
ContractRequest input = argPacks.request;
Object ret = argPacks.ret;
DesktopEngine desktopEngine = (DesktopEngine) Engine;
ProjectConfig projectConfig = desktopEngine.getProjectConfig();
JsonElement maskConf = projectConfig.getMask(input.getAction());
@@ -35,14 +38,17 @@ public class MaskHandler implements AnnotationHook {
ret = visitor.get();
LOGGER.debug(maskConf);
if (null != ret) {
return ret;
argPacks.ret = ret;
return argPacks;
}
ret = JsonParser.parseString("");
}
return ret;
argPacks.ret = ret;
return argPacks;
} catch (Exception e) {
// e.printStackTrace();
return ret;
return argPacks;
}
}

View File

@@ -6,11 +6,13 @@ import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.bean.ProjectConfig;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
public class MockTemplateHandler implements AnnotationHook {
@Override
public Object handle(ContractRequest request, JSEngine engine, Object ret) {
public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
try {
ContractRequest request = argPacks.request;
if (request.fromDebug()) {
System.out.println(request.getAction());
DesktopEngine desktopEngine = (DesktopEngine) engine;
@@ -19,13 +21,14 @@ public class MockTemplateHandler implements AnnotationHook {
if (template != null && template.length() > 0) {
System.out.println(template);
MockUtil Mock = new MockUtil();
return Mock.mock(template).toString();
} else return ret; //When mock config is null defined just ignore.
argPacks.ret = Mock.mock(template).toString();
return argPacks;
} else return argPacks; //When mock config is null defined just ignore.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return ret;
return argPacks;
}
}
}

View File

@@ -1,17 +1,14 @@
package org.bdware.sc.engine.hook;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonPrimitive;
import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.engine.JSONTool;
import org.bdware.sc.node.AnnotationHook;
import wrp.jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.bdware.sc.node.ArgPacks;
public class ObjToJsonHandler implements AnnotationHook {
@Override
public Object handle(ContractRequest input, JSEngine desktopEngine, Object ret) {
return JSONTool.convertMirrorToJson(ret);
public ArgPacks handle(JSEngine desktopEngine, ArgPacks argPacks) {
argPacks.ret = JSONTool.convertMirrorToJson(argPacks.ret);
return argPacks;
}
}

View File

@@ -4,6 +4,7 @@ import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
import org.commonmark.node.FencedCodeBlock;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
@@ -56,12 +57,14 @@ public class ReadMeHandler implements AnnotationHook {
}
@Override
public Object handle(ContractRequest input, JSEngine engine, Object ret) {
public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
DesktopEngine desktopEngine = (DesktopEngine) engine;
if (input.fromDebug() && (ret == null || ret.equals("emptyMock"))) {
ret = getReadMeData(desktopEngine, input);
System.out.println(ret);
ContractRequest input = argPacks.request;
if (input.fromDebug() && (argPacks.ret == null || argPacks.ret.equals("emptyMock"))) {
argPacks.ret = getReadMeData(desktopEngine, input);
System.out.println(argPacks.ret);
}
return ret;
return argPacks;
}
}

View File

@@ -0,0 +1,9 @@
package org.bdware.sc.engine.hook;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface YJSAnnotation {
String name() default "";
}

View File

@@ -0,0 +1,25 @@
package org.bdware.sc.entity;
import org.bdware.doip.codec.doipMessage.DoipMessage;
public class DoipMessagePacker {
// the DoipMessagePacker is raised by http/doip
public String source;
// the well-composed DoipMessage
public DoipMessage rawDoipMsg;
public DoipMessagePacker() {}
public DoipMessagePacker(String source, DoipMessage rawMsg) {
this.source = source;
this.rawDoipMsg = rawMsg;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
}

View File

@@ -1,5 +1,6 @@
package org.bdware.sc.handler;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.ContractProcess;
@@ -12,6 +13,7 @@ import org.bdware.sc.get.GetMessage;
import org.bdware.sc.util.JsonUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ContractHandler extends MsgHandler implements Runnable {
@@ -100,6 +102,12 @@ public class ContractHandler extends MsgHandler implements Runnable {
cb.onResult(cs.setContractBundle(JsonUtil.fromJson(msg.arg, Contract.class)));
}
@Description("set members")
public void setMembers(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.setMembers(JsonUtil.fromJson(msg.arg, new TypeToken<List<String>>() {
}.getType())));
}
@Description("get current contract name")
public void getContractName(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.getContractName());
@@ -110,11 +118,16 @@ public class ContractHandler extends MsgHandler implements Runnable {
cb.onResult(cs.setContract(JsonUtil.fromJson(msg.arg, Contract.class)));
}
@Description(value = "execute contract")
@Description(value = "execute contract", isAsync = true)
public void executeContract(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.executeContract(msg.arg));
}
@Description(value = "invoke function without limit")
public void invokeFunctionWithoutLimit(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.executeFunctionWithoutLimit(msg.arg));
}
@Description("set DesktopPermission")
public void setDesktopPermission(GetMessage msg, ResultCallback cb) {
String result = cs.setDesktopPermission(msg.arg);
@@ -221,7 +234,7 @@ public class ContractHandler extends MsgHandler implements Runnable {
@Description("get contract")
public void getContract(GetMessage msg, ResultCallback cb) {
cb.onResult(cs.getContract());
cb.onResult(JsonUtil.toJson(cs.getContract()));
}
@Description("setPID")

View File

@@ -0,0 +1,146 @@
package org.bdware.sc.handler;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.codec.operations.BasicOperations;
import org.bdware.doip.endpoint.server.DoipRequestHandler;
import org.bdware.doip.endpoint.server.NettyServerHandler;
import org.bdware.doip.endpoint.server.RepositoryHandler;
import org.bdware.sc.ContractProcess;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.engine.hook.DOOPHandler;
import org.bdware.sc.entity.DoipMessagePacker;
import org.bdware.sc.node.FunctionNode;
import java.util.HashMap;
import java.util.Map;
public class DOOPRequestHandler implements DoipRequestHandler, RepositoryHandler {
public Map<String, FunctionNode> doipOperationsMap;
static Logger logger = LogManager.getLogger(NettyServerHandler.class);
static Gson gson;
public static DOOPRequestHandler instance;
public DOOPRequestHandler() {
doipOperationsMap = new HashMap<>();
gson = new Gson();
}
public static DOOPRequestHandler createHandler() {
if(instance == null) {
instance = new DOOPRequestHandler();
}
return instance;
}
public void addDoipOperation(FunctionNode function) {
doipOperationsMap.put(function.getDoipOperationInfo().operationName, function);
}
@Override
public DoipMessage onRequest(ChannelHandlerContext ctx, DoipMessage msg) {
String str = msg.header.parameters.operation;
logger.debug("[Call operation] name: " + str);
if (str != null) {
FunctionNode fn;
fn = doipOperationsMap.get(str);
if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
if (fn != null) {
return buildRequestAndInvokeEngine(fn, msg);
}
}
return null;
}
@Override
public DoipMessage handleHello(DoipMessage request) {
FunctionNode fn = doipOperationsMap.get(BasicOperations.Hello.getName());
if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
if (fn != null) {
return buildRequestAndInvokeEngine(fn, request);
}
return null;
}
@Override
public DoipMessage handleListOps(DoipMessage request) {
FunctionNode fn = doipOperationsMap.get(BasicOperations.ListOps.getName());
if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
if (fn != null) {
return buildRequestAndInvokeEngine(fn, request);
}
return null;
}
@Override
public DoipMessage handleCreate(DoipMessage request) {
FunctionNode fn = doipOperationsMap.get(BasicOperations.Create.getName());
if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
if (fn != null) {
return buildRequestAndInvokeEngine(fn, request);
}
return null;
}
@Override
public DoipMessage handleUpdate(DoipMessage request) {
FunctionNode fn = doipOperationsMap.get(BasicOperations.Update.getName());
if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
if (fn != null) {
return buildRequestAndInvokeEngine(fn, request);
}
return null;
}
@Override
public DoipMessage handleDelete(DoipMessage request) {
FunctionNode fn = doipOperationsMap.get(BasicOperations.Delete.getName());
if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
if (fn != null) {
return buildRequestAndInvokeEngine(fn, request);
}
return null;
}
@Override
public DoipMessage handleRetrieve(DoipMessage request) {
FunctionNode fn = doipOperationsMap.get(BasicOperations.Retrieve.getName());
if (fn == null) fn = doipOperationsMap.get(BasicOperations.Unknown.getName());
if (fn != null) {
return buildRequestAndInvokeEngine(fn, request);
}
return null;
}
public DoipMessage buildRequestAndInvokeEngine(FunctionNode fn, DoipMessage msg) {
ContractRequest contractRequest = constructContractRequest(fn, msg);
DoipMessagePacker arg = new DoipMessagePacker("doip", msg);
try {
// 改变调用的函数 + 构造DoipMessagePacker
Object ret = ContractProcess.instance.engine.executeWithoutLock(fn, contractRequest, arg);
return DOOPHandler.convertJsonElementToDoipMessage((JsonElement) ret, msg);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public ContractRequest constructContractRequest(FunctionNode fn, DoipMessage request) {
ContractRequest cr = new ContractRequest();
cr.setContractID("");
if(request.credential == null) {
cr.setRequester(null);
} else {
cr.setRequester(request.credential.getSigner());
}
cr.setAction(fn.functionName);
return cr;
}
}

View File

@@ -0,0 +1,52 @@
package org.bdware.sc.server;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.endpoint.server.DoipListenerConfig;
import org.bdware.doip.endpoint.server.DoipServerImpl;
import org.bdware.doip.endpoint.server.DoipServiceInfo;
import org.bdware.sc.handler.DOOPRequestHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class DoipServerTest {
static Logger LOGGER = LogManager.getLogger(DoipServerTest.class);
public static void main(String[] arg) throws InterruptedException {
final int port = (arg.length == 0 ? 21042 : Integer.parseInt(arg[0]));
Thread doipServerThread = new Thread(){
@Override
public void run() {
try {
DoipServerTest.run(port);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
doipServerThread.start();
}
public static void run(int port) throws InterruptedException {
List<DoipListenerConfig> infos = new ArrayList<>();
try {
infos.add(new DoipListenerConfig("tcp://127.0.0.1:" + port, "2.1"));
} catch (Exception e) {
e.printStackTrace();
}
DoipServiceInfo info = new DoipServiceInfo("aibd.govdata.tj/do.3f9c41e6-9f8e-48a0-9220-53f438d40e43", "ownerDEF", "gateRepo", infos);
DoipServerImpl server = new DoipServerImpl(info);
final AtomicInteger count = new AtomicInteger(0);
DOOPRequestHandler handler = DOOPRequestHandler.createHandler();
server.setRepositoryHandler(handler);
server.start();
for (; ; ) {
LOGGER.info("Count:" + count.get());
Thread.sleep(10000);
}
}
}

View File

@@ -2,18 +2,14 @@ package org.bdware.sc.trace;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sun.mail.iap.ByteArray;
import org.bdware.analysis.CFGraph;
import org.bdware.sc.ContractProcess;
import wrp.jdk.nashorn.internal.runtime.ScriptObject;
import wrp.jdk.nashorn.internal.runtime.ScriptRuntime;
import wrp.jdk.nashorn.internal.runtime.TraceMethod;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class ProgramPointCounter extends ContractProcess.Logger implements TraceMethod {

View File

@@ -1,8 +0,0 @@
### 设置###
log4j.rootLogger = debug,stdout
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M]%n

View File

@@ -0,0 +1,9 @@
filter.threshold.type=ThresholdFilter
filter.threshold.level=all
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=%highlight{[%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M]%n}{FATAL=Bright Red,ERROR=Red,WARN=Yellow,INFO=Green,DEBUG=Blue,TRACE=White}
rootLogger.level=all
rootLogger.appenderRef.stdout.ref=STDOUT

View File

@@ -1,15 +1,10 @@
filter.threshold.type=ThresholdFilter
filter.threshold.level=debug
filter.threshold.level=all
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=%highlight{[%-5p] %d{HH:mm:ss.SSS} %m (%F:%L)[%M]%n}{FATAL=Bright Red,ERROR=Red,WARN=Yellow,INFO=Green,DEBUG=Blue,TRACE=White}
appender.rolling.type=File
appender.rolling.name=log
appender.rolling.append=true
appender.rolling.fileName=./log/ct.log
appender.rolling.layout.type=PatternLayout
appender.rolling.layout.pattern=%d-%m%n
rootLogger.level=info
rootLogger.appenderRef.stdout.ref=STDOUT
rootLogger.appenderRef.log.ref=log
rootLogger.appenderRef.stdout.level=info

View File

@@ -0,0 +1,52 @@
package org.bdware.doip;
import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.endpoint.client.ClientConfig;
import org.bdware.doip.endpoint.client.DoipClientImpl;
import org.bdware.doip.endpoint.client.DoipMessageCallback;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
public class DoipClientTest {
long start = System.currentTimeMillis();
final AtomicInteger total = new AtomicInteger(0);
final AtomicInteger correct = new AtomicInteger(0);
int totalCount = 10000;
@Test
public void doipClientTest(){
long start = System.currentTimeMillis();
final AtomicInteger total = new AtomicInteger(0);
final AtomicInteger correct = new AtomicInteger(0);
int totalCount = 1;
for (int i = 0; i < totalCount; i++) {
final DoipClientImpl doipClient = new DoipClientImpl();
doipClient.connect(ClientConfig.fromUrl("tcp://127.0.0.1:8080"));
doipClient.retrieve("aibd/do.e626924a-3b1c-492f-9a41-59179bfe0361", null, true, new DoipMessageCallback() {
@Override
public void onResult(DoipMessage msg) {
String str = new String(msg.body.encodedData);
System.out.println("Result is " + str);
//LOGGER.info("Retrieved:" + str
//+ " respCode:" + msg.header.parameters.response);
total.incrementAndGet();
if (str.contains("aaa"))
correct.incrementAndGet();
if (doipClient != null) doipClient.close();
}
});
}
int circle = 0;
for (; total.get() < totalCount; ) {
if (++circle % 100 == 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

View File

@@ -0,0 +1,32 @@
package org.bdware.sc;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class ByteArrayTest {
@Test
public void abc() {
String str = "abc6787689dd";
byte[] data = str.getBytes(StandardCharsets.UTF_8);
String hexStr = ByteUtils.toHexString(data);
System.out.println("hashCode:" + Arrays.hashCode(data));
System.out.println("hexStr:" + hexStr);
//hashCode:-606029994
//hexStr:616263363738373638396464
}
@Test
public void abc2() {
String str = "abc678768229dd";
byte[] data = str.getBytes(StandardCharsets.UTF_8);
String hexStr = ByteUtils.toHexString(data);
System.out.println("hashCode:" + Arrays.hashCode(data));
System.out.println("hexStr:" + hexStr);
//hashCode:1712735702
//hexStr:6162633637383736383232396464
//
}
}

View File

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

View File

@@ -0,0 +1,21 @@
package org.bdware.sc;
import org.junit.Test;
import org.zz.gmhelper.SM2KeyPair;
import java.math.BigInteger;
public class SM2Test {
@Test
public void run(){
String str = "{publicKey:\"04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7c0a5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15\",privateKey:\"82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc\"}";
String pubKey = "04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7c0a5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15";
// 04398dfde44290595cd098cd2f904b36367c69f9011719d43fb0955f823cf1386764769bc7cOa5649dcb316d552998a5c106afd268d9db8b6482ce527544a7bd15
String privKey = "82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc";
// 82a119ee46db52778182682f11e21980b6de3070b070a2f58e614af66775d6fc
SM2KeyPair key = new SM2KeyPair(
SM2KeyPair.publicKeyStr2ECPoint(pubKey), new BigInteger(privKey, 16));
System.out.println("hello");
}
}

View File

@@ -0,0 +1,17 @@
package org.bdware.sc.boundry.utils.test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.boundry.utils.DOIPUtil;
import org.junit.Test;
public class DOIPUtilTest {
static Logger LOGGER = LogManager.getLogger(DOIPUtilTest.class);
@Test
public void testRetrieve() {
DOIPUtil util = DOIPUtil.createClient("tcp://127.0.0.1:21032");
LOGGER.info(util.retrieve("AnnotationExample", "{\"operation\":\"main\",\"arg\":\"\"}"));
}
}

View File

@@ -1,12 +1,56 @@
package org.bdware.sc.boundry.utils.test;
import org.bdware.bdledger.api.grpc.Client;
import org.bdware.bdledger.api.grpc.pb.CommonProto;
import org.bdware.bdledger.api.grpc.pb.LedgerProto;
import org.bdware.sc.conn.ByteUtil;
import org.bdware.sc.util.HashUtil;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.junit.Test;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class LedgerUtilTest {
public static void main(String[] arg) {
Client c = new Client("39.108.56.240", 18091);
// c.sendTransactionSync("test", TransactionType.RECORD, arg2, arg3, arg4)
String ip = "39.104.202.92";
ip = "39.104.205.122";
ip = "39.104.201.40";
Client c = new Client(ip, 21121);
System.out.println(c.clientVersionSync().getVersion());
System.out.println(c.getLedgersSync().toString());
String from = "0xb60e8dd61c5d32be8058bb8eb970870f07233155";
LedgerProto.SendTransactionResponse ret = c.sendTransactionSync("bdcontract", CommonProto.TransactionType.MESSAGE,
from, System.currentTimeMillis(), from, "hello".getBytes(StandardCharsets.UTF_8));
System.out.println("=====" + HashUtil.byteArray2Str(ret.getHash().toByteArray()));
}
@Test
public void transToB64() {
String str = "1dc589951b10840e097c793764f8ad63ff577ef7";
str = "3c011ab510c5756db9aab1f2ac1a14742b85200f";
str ="867020d3463126c0f5ea41967100865770ca1873";
str = "3f40a6afcd4e7c7db1ee8a3cf54074be270c6847";
str = "ab7d541b4f320f77fe424082d79d1f4ca2a40f84";
str = "246f5527c3182d162ea8f1c3f5e0be05d9269517";
str = "d148e40be1078c707891ba12ed270978d81dad30";
str = "dbda443da8a6da3b4703b06250f07f7df3e04d72";
str = "d16da370021447c1c1136f97f9975069b1f22ddb";
str = "448b314de358384a55b9c5d2eae7596cff4e3587";
str ="a114aa22365c2d61ee1c242c755d82c035783e41";
str = "d9be17b4287ed9a548901ef0e738f65f25dc7041";
str="e90dbc995add64b26fa483b1b0ad7747b19ad579";
byte[] bytes = ByteUtils.fromHexString(str);
String hash = ByteUtil.encodeBASE64(bytes);
System.out.println(URLEncoder.encode(hash));
}
@Test
public void readData(){
String hash = "kNkTGrOLKlMiVHiCx/Ik3Tx3DDI=";
hash = "mEoVJx4k2L5nhKY6exjtJWmU7RA=";
hash = "OTg0YTE1MjcxZTI0ZDhiZTY3ODRhNjNhN2IxOGVkMjU2OTk0ZWQxMA==";
byte[] data = ByteUtil.decodeBASE64(hash);
//<ByteString@67aaeb8d size=20 contents="<D\206P!\241\005\017\366\321\312\336\323cWiS>\226\207">
// System.out.println(new String(data));
}
}

View File

@@ -0,0 +1,57 @@
package org.bdware.sc.engine.hook.test;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bdware.sc.engine.hook.ArgSchemaVisitor;
import org.junit.Test;
public class ArgSchemaTest {
@Test
public void test1(){
JsonObject realData=JsonParser.parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}],\"doId\":1}").getAsJsonObject();
JsonObject schema=JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"doId\":\"number\"}").getAsJsonObject();
ArgSchemaVisitor visitor=new ArgSchemaVisitor(realData);
visitor.visit(schema);
System.out.println(visitor.getStatus());
System.out.println(visitor.getException().toString());
}
@Test
public void test2(){
JsonObject realData=JsonParser.parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}],\"doId\":\"string\"}").getAsJsonObject();
JsonObject schema=JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"doId\":\"number\"}").getAsJsonObject();
ArgSchemaVisitor visitor=new ArgSchemaVisitor(realData);
visitor.visit(schema);
System.out.println(visitor.getStatus());
System.out.println(visitor.getException().toString());
System.out.println(visitor.errorCode);
}
@Test
public void test3(){
JsonElement realData=JsonParser.parseString("data.json");
JsonElement schema=JsonParser.parseString("\"string\"");
ArgSchemaVisitor visitor=new ArgSchemaVisitor(realData);
visitor.visit(schema);
System.out.println(visitor.getStatus());
System.out.println(visitor.getException().toString());
System.out.println(visitor.errorCode);
}
//缺少必选项
@Test
public void test4(){
JsonObject realData=JsonParser.parseString("{\"data\":[{\"name\":\"zzz\"},{\"name\":\"aaa\"}]}").getAsJsonObject();
JsonObject schema=JsonParser.parseString("{\"data\":[{\"name\":\"string\"}],\"!doId\":\"string\"}").getAsJsonObject();
ArgSchemaVisitor visitor=new ArgSchemaVisitor(realData);
visitor.visit(schema);
System.out.println(visitor.getStatus());
System.out.println(visitor.getException());
System.out.println(visitor.errorCode);
}
}

View File

@@ -1,16 +1,13 @@
package org.bdware.sc.test.synctest;
import org.bdware.sc.conn.ByteUtil;
import com.google.gson.JsonPrimitive;
import org.bdware.sc.redo.TransRecord;
import java.io.*;
import java.util.zip.GZIPInputStream;
public class TransRecordTest {
static TransRecord currentTransRecord = new TransRecord("myFun","myArg");
static TransRecord currentTransRecord = new TransRecord("myFun", new JsonPrimitive("myArg"));
public static void main(String[] args){
public static void main(String[] args) {
// currentTransRecord.executes.put("k1","v1");
// currentTransRecord.executes.put("k2","v2");
// currentTransRecord.executes.put("k3","v3");