feat: support onCreateParams

This commit is contained in:
CaiHQ 2022-05-02 20:49:37 +08:00
parent bac80bbf31
commit cf097ce7fd
12 changed files with 250 additions and 59 deletions

View File

@ -6,6 +6,7 @@ plugins {
mainClassName = 'org.bdware.sc.ContractProcess'
repositories {
mavenLocal()
mavenCentral()
}
sourceSets {
@ -39,7 +40,8 @@ dependencies {
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.doip:doip-sdk:1.1.0'
implementation 'org.bdware.bdcontract:sdk-java:1.0.0'
implementation 'org.bdware.doip:doip-audit-tool:0.9.3'
api fileTree(dir: 'lib', include: '*.jar')
testImplementation 'junit:junit:4.13.2'

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.bdware.client.SmartContractClient;
import org.bdware.sc.ContractProcess;
import org.bdware.sc.bean.Contract;
import org.bdware.sc.bean.ContractExecType;
@ -11,6 +13,7 @@ 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;
@ -21,6 +24,21 @@ public class DebugMain {
String content = FileUtil.getFileContent("./debugconf.json");
DebugConfig config = JsonUtil.fromJson(content, DebugConfig.class);
inject(config);
String keyPairStr = "{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}";
SM2KeyPair pair = SM2KeyPair.fromJson(String.format(keyPairStr, config.pubKey, config.privKey));
String uriFormat = "ws://%s/SCIDE/SCExecutor";
if (config.killContract != null && config.killContract.length() > 0) {
SmartContractClient client = new SmartContractClient(String.format(uriFormat, config.agentHttpAddr), pair);
client.waitForConnect();
client.login();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.sendMsg("{\"action\":\"killContractProcess\",\"contractName\":\"" + config.killContract + "\"}");
}
config.contract.setCreateParam(config.createParam);
ContractProcess.main(new String[]{"-port=" + config.port, "-cmi=" + config.cmi, "-disablePID"});
ResultCallback printCallback
= new ResultCallback() {
@ -31,14 +49,16 @@ public class DebugMain {
};
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=reconnectPort&owner=%s&port=%d");
String url = String.format(urlFormat, config.agentHttpAddr,
config.pubKey, ContractProcess.instance.server.mainPort.get());
Map<String, Object> resp = HttpUtil.httpGet(url);
String data = (String) resp.get("response");
LOGGER.info(JsonUtil.toPrettyJson(JsonUtil.parseStringAsJsonObject(data)));
// LOGGER.info(JsonUtil.toPrettyJson(JsonUtil.parseStringAsJsonObject(data)));
LOGGER.info("start done!");
}
@ -77,12 +97,13 @@ public class DebugMain {
}
static class DebugConfig {
String killContract;
public JsonElement createParam;
String script;
String agentHttpAddr;
String pubKey;
String privKey;
//AutoAppend
int port;
String cmi;
String dbPath;

View File

@ -1,10 +1,6 @@
package org.bdware.sc;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
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 org.apache.logging.log4j.Level;
@ -719,10 +715,14 @@ public class ContractProcess {
JavaScriptEntry.isDebug = contract.isDebug();
ContractRequest onCreate = new ContractRequest();
onCreate.setAction("onCreate");
if (arg == null)
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.info("invoke onCreate, param:" + onCreate.getArg().toString());
onCreate.setRequester(contract.getOwner());
if (contract.getDoipFlag() && null != contract.getDOI() && !contract.getDOI().isEmpty()) {
onCreate.setRequesterDOI(contract.getDOI());
@ -760,7 +760,8 @@ public class ContractProcess {
"getFunction:" + (System.currentTimeMillis() - start) + " " + funNode.functionName);
long start1 = System.currentTimeMillis();
funNode.setIsExport(true);
engine.executeContract(onRecover);
ContractResult result = engine.executeContract(onRecover);
LOGGER.info("invoke onCreate, result:" + new Gson().toJson(result));
LOGGER.debug("executeOnCreate:" + (System.currentTimeMillis() - start1));
start1 = System.currentTimeMillis();
funNode.setIsExport(false);

View File

@ -1,11 +1,14 @@
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;
@ -24,13 +27,36 @@ public class SM2Helper {
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;

View File

@ -3,6 +3,8 @@ 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;
@ -11,10 +13,15 @@ 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;
@ -140,4 +147,86 @@ public class DOIPUtil {
.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

@ -3,6 +3,8 @@ 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;
@ -42,7 +44,10 @@ public class LedgerUtil {
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());
@ -52,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

@ -37,12 +37,11 @@ public class RocksDBUtil {
options.setCreateIfMissing(true);
File parent = new File("./ContractDB/" + ContractProcess.getContractDir());
File dir = new File(parent, path);
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 {

View File

@ -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());
}
@ -179,17 +178,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 +196,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

@ -65,6 +65,7 @@ public class DesktopEngine extends JSEngine {
// private String traceDir;
private ContractProcess.Logger tracePS = null;
private Contract contract;
private ContractManifest manifest;
public DesktopEngine() {
startEngine();
@ -248,7 +249,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);
@ -427,7 +427,7 @@ public class DesktopEngine extends JSEngine {
@Override
public synchronized ContractResult executeContract(ContractRequest input) {
public ContractResult executeContract(ContractRequest input) {
Global oldGlobal = Context.getGlobal();
boolean globalChanged = (oldGlobal != global);
if (globalChanged) {
@ -481,34 +481,18 @@ 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();
for (AnnotationHook handler : fun.beforeExecutionAnnotations()) {
ret = handler.handle(input, this, ret);
Object ret;
if (fun.isView()) {
ret = executeWithoutLock(fun, input);
} else {
synchronized (this) {
ret = executeWithoutLock(fun, input);
}
// 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);
@ -558,13 +542,12 @@ public class DesktopEngine extends JSEngine {
new JsonPrimitive("Action " + input.getAction() + " is not exported!"));
}
}catch (ScriptReturnException e){
} catch (ScriptReturnException e) {
e.printStackTrace();
return new ContractResult(
Status.Exception,
e.message);
}
catch (ScriptException e) {
} catch (ScriptException e) {
Throwable cause = e.getCause();
e.printStackTrace();
return new ContractResult(
@ -592,6 +575,33 @@ public class DesktopEngine extends JSEngine {
}
private Object executeWithoutLock(FunctionNode fun, ContractRequest input) throws ScriptException, NoSuchMethodException {
Object ret = null;
// long start = System.currentTimeMillis();
for (AnnotationHook handler : fun.beforeExecutionAnnotations()) {
ret = handler.handle(input, this, ret);
}
// actually invoke!
if (ret == null) {
ret =
engine.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);
}
return ret;
}
private String extractException(String msg, List<String> stack) {
int endIndex = Math.min(msg.indexOf("in"), msg.length());
StringBuilder msb = new StringBuilder(msg.substring(0, endIndex));
@ -872,9 +882,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")) {
@ -911,8 +918,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

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

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

View File

@ -1,12 +1,54 @@
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.202.92";
Client c = new Client(ip, 18021);
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";
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));
}
}