build: config spotless plugin and reformat code

This commit is contained in:
Frank.R.Wu 2023-06-15 11:31:07 +08:00
parent 698c8cf569
commit 23f367f398
12 changed files with 157 additions and 123 deletions

View File

@ -4,6 +4,9 @@ plugins {
id 'maven-publish' id 'maven-publish'
id 'signing' id 'signing'
} }
apply from: '../spotless.gradle'
group "org.bdware.bdcontract" group "org.bdware.bdcontract"
version "0.7.4" version "0.7.4"
sourceCompatibility = 1.8 sourceCompatibility = 1.8

View File

@ -21,22 +21,26 @@ public class BDRepoTool {
EndpointConfig endpointConfig = storage.loadAsEndpointConfig(); EndpointConfig endpointConfig = storage.loadAsEndpointConfig();
AuditIrpClient irpClient = new AuditIrpClient(endpointConfig); AuditIrpClient irpClient = new AuditIrpClient(endpointConfig);
BDRepoConfig bdosConfig = new Gson().fromJson(storage.load(), BDRepoConfig.class); BDRepoConfig bdosConfig = new Gson().fromJson(storage.load(), BDRepoConfig.class);
BDRepoClient client = new BDRepoClient(bdosConfig.bdRepoId, irpClient, SM2KeyPair.fromJson(bdosConfig.accessKeyPair.toString())); BDRepoClient client = new BDRepoClient(bdosConfig.bdRepoId, irpClient,
SM2KeyPair.fromJson(bdosConfig.accessKeyPair.toString()));
AtomicInteger result = new AtomicInteger(0); AtomicInteger result = new AtomicInteger(0);
if (bcoId == null) if (bcoId == null)
bcoId = bdosConfig.bcoId; bcoId = bdosConfig.bcoId;
LOGGER.info("deploy: " + bcoId + " @" + bdosConfig.bdRepoId); LOGGER.info("deploy: " + bcoId + " @" + bdosConfig.bdRepoId);
client.createBDO(bcoId, bdosConfig.shardingID, bdosConfig.createParam, bdosConfig.doipStartPort, SM2KeyPair.fromJson(bdosConfig.deployKeyPair.toString()), client.createBDO(bcoId, bdosConfig.shardingID, bdosConfig.createParam,
bdosConfig.doipStartPort, SM2KeyPair.fromJson(bdosConfig.deployKeyPair.toString()),
new BDRepoClient.StartBDOResultCallback() { new BDRepoClient.StartBDOResultCallback() {
@Override @Override
public void onResult(BDRepoClient.StartBDOResult ret) { public void onResult(BDRepoClient.StartBDOResult ret) {
LOGGER.info("[BDRepoTool] " + new Gson().toJson(ret)); LOGGER.info("[BDRepoTool] " + new Gson().toJson(ret));
LOGGER.info("[BDRepoTool] " + new Gson().toJson(ret.originalMessage.header)); LOGGER.info(
LOGGER.info("[BDRepoTool] doipMsg:" + ret.originalMessage.body.getDataAsJsonString()); "[BDRepoTool] " + new Gson().toJson(ret.originalMessage.header));
LOGGER.info("[BDRepoTool] doipMsg:"
+ ret.originalMessage.body.getDataAsJsonString());
result.incrementAndGet(); result.incrementAndGet();
} }
}); });
for (; result.get() == 0; ) { for (; result.get() == 0;) {
Thread.yield(); Thread.yield();
} }
} }
@ -54,10 +58,12 @@ public class BDRepoTool {
EndpointConfig endpointConfig = storage.loadAsEndpointConfig(); EndpointConfig endpointConfig = storage.loadAsEndpointConfig();
AuditIrpClient irpClient = new AuditIrpClient(endpointConfig); AuditIrpClient irpClient = new AuditIrpClient(endpointConfig);
BDRepoConfig bdosConfig = new Gson().fromJson(storage.load(), BDRepoConfig.class); BDRepoConfig bdosConfig = new Gson().fromJson(storage.load(), BDRepoConfig.class);
BDRepoClient client = new BDRepoClient(bdosConfig.bdRepoId, irpClient, SM2KeyPair.fromJson(bdosConfig.accessKeyPair.toString())); BDRepoClient client = new BDRepoClient(bdosConfig.bdRepoId, irpClient,
SM2KeyPair.fromJson(bdosConfig.accessKeyPair.toString()));
AtomicInteger result = new AtomicInteger(0); AtomicInteger result = new AtomicInteger(0);
if (bdoId == null) if (bdoId == null)
bdoId = bdosConfig.bdRepoId + "/" + bdosConfig.deployKeyPair.get("publicKey").getAsString().hashCode(); bdoId = bdosConfig.bdRepoId + "/"
+ bdosConfig.deployKeyPair.get("publicKey").getAsString().hashCode();
LOGGER.info("kill:" + bdoId); LOGGER.info("kill:" + bdoId);
client.deleteBDO(bdoId, new DoipMessageCallback() { client.deleteBDO(bdoId, new DoipMessageCallback() {
@Override @Override
@ -67,7 +73,7 @@ public class BDRepoTool {
result.incrementAndGet(); result.incrementAndGet();
} }
}); });
for (; result.get() == 0; ) { for (; result.get() == 0;) {
Thread.yield(); Thread.yield();
} }
} }

View File

@ -23,7 +23,8 @@ public class CodeRepoTool {
System.out.println("[CodeRepoTool] error: missing codeRepoId"); System.out.println("[CodeRepoTool] error: missing codeRepoId");
return; return;
} }
CodeRepoClient client = new CodeRepoClient(bdosConfig.codeRepoId, irpClient, SM2KeyPair.fromJson(arg.toString())); CodeRepoClient client = new CodeRepoClient(bdosConfig.codeRepoId, irpClient,
SM2KeyPair.fromJson(arg.toString()));
if (ypkPath == null) if (ypkPath == null)
ypkPath = bdosConfig.ypkPath; ypkPath = bdosConfig.ypkPath;
if (ypkPath == null) { if (ypkPath == null) {
@ -39,7 +40,8 @@ public class CodeRepoTool {
@Override @Override
public void onProgress(String doId, int currentChunk, int totalChunk) { public void onProgress(String doId, int currentChunk, int totalChunk) {
System.out.println("[CodeRepoTool] " + doId + " progress: " + currentChunk + "/" + totalChunk); System.out.println(
"[CodeRepoTool] " + doId + " progress: " + currentChunk + "/" + totalChunk);
} }
@Override @Override
@ -55,7 +57,7 @@ public class CodeRepoTool {
result.incrementAndGet(); result.incrementAndGet();
} }
}); });
for (; result.get() == 0; ) { for (; result.get() == 0;) {
Thread.yield(); Thread.yield();
} }
} }

View File

@ -25,10 +25,12 @@ public class DeployConfGenerator {
return null; return null;
} }
public static void generateDeployConf(String dir, String template, String commonvar, String fileName) { public static void generateDeployConf(String dir, String template, String commonvar,
String fileName) {
String templateStr = getFileContent(dir + template); String templateStr = getFileContent(dir + template);
try { try {
JsonObject commVar = JsonParser.parseReader(new FileReader(new File(dir, commonvar))).getAsJsonObject(); JsonObject commVar = JsonParser.parseReader(new FileReader(new File(dir, commonvar)))
.getAsJsonObject();
String content = templateStr; String content = templateStr;
File output = new File(dir, fileName); File output = new File(dir, fileName);
if (!output.getParentFile().exists()) if (!output.getParentFile().exists())
@ -44,11 +46,14 @@ public class DeployConfGenerator {
} }
} }
public static void batchGenerateDeployConf(String dir, String template, String commonvar, String filesStr) { public static void batchGenerateDeployConf(String dir, String template, String commonvar,
String filesStr) {
String templateStr = getFileContent(new File(dir, template).getAbsolutePath()); String templateStr = getFileContent(new File(dir, template).getAbsolutePath());
try { try {
JsonObject commVar = JsonParser.parseReader(new FileReader(new File(dir, commonvar))).getAsJsonObject(); JsonObject commVar = JsonParser.parseReader(new FileReader(new File(dir, commonvar)))
JsonArray files = JsonParser.parseReader(new FileReader(new File(dir, filesStr))).getAsJsonArray(); .getAsJsonObject();
JsonArray files = JsonParser.parseReader(new FileReader(new File(dir, filesStr)))
.getAsJsonArray();
for (JsonElement je : files) { for (JsonElement je : files) {
JsonObject file = je.getAsJsonObject(); JsonObject file = je.getAsJsonObject();
File output = new File(dir, file.get("fileName").getAsString()); File output = new File(dir, file.get("fileName").getAsString());
@ -57,11 +62,13 @@ public class DeployConfGenerator {
FileOutputStream fout = new FileOutputStream(output); FileOutputStream fout = new FileOutputStream(output);
String content = templateStr; String content = templateStr;
for (String key : file.keySet()) { for (String key : file.keySet()) {
if (!key.startsWith("_")) continue; if (!key.startsWith("_"))
continue;
content = content.replaceAll(key, file.get(key).getAsString()); content = content.replaceAll(key, file.get(key).getAsString());
} }
for (String key : commVar.keySet()) { for (String key : commVar.keySet()) {
if (file.has(key)) continue; if (file.has(key))
continue;
content = content.replaceAll(key, commVar.get(key).getAsString()); content = content.replaceAll(key, commVar.get(key).getAsString());
} }
fout.write(content.getBytes(StandardCharsets.UTF_8)); fout.write(content.getBytes(StandardCharsets.UTF_8));

View File

@ -25,19 +25,23 @@ public class Entry {
} }
private static void deployYpk(List<String> deployTasks) { private static void deployYpk(List<String> deployTasks) {
if (deployTasks == null) return; if (deployTasks == null)
return;
for (String deployTask : deployTasks) { for (String deployTask : deployTasks) {
HTTPTool.deploy(deployTask); HTTPTool.deploy(deployTask);
} }
} }
private static void generateJson(List<GenerateTask> generateTaskList) { private static void generateJson(List<GenerateTask> generateTaskList) {
if (generateTaskList == null) return; if (generateTaskList == null)
return;
for (GenerateTask task : generateTaskList) { for (GenerateTask task : generateTaskList) {
if (task.isBatch) { if (task.isBatch) {
DeployConfGenerator.batchGenerateDeployConf(task.dir, task.template, task.commvar, task.files); DeployConfGenerator.batchGenerateDeployConf(task.dir, task.template, task.commvar,
task.files);
} else } else
DeployConfGenerator.generateDeployConf(task.dir, task.template, task.commvar, task.files); DeployConfGenerator.generateDeployConf(task.dir, task.template, task.commvar,
task.files);
} }
} }

View File

@ -28,7 +28,7 @@ public class HTTPTool {
static class DeployConfig { static class DeployConfig {
public boolean asDebug; public boolean asDebug;
String agentAddress; String agentAddress;
//common config // common config
JsonElement createParam; JsonElement createParam;
String killBeforeStart; String killBeforeStart;
String privateKey; String privateKey;
@ -74,23 +74,24 @@ public class HTTPTool {
private static void restart(DeployConfig config) { private static void restart(DeployConfig config) {
SM2KeyPair keyPair = SM2KeyPair.fromJson(new Gson().toJson(config)); SM2KeyPair keyPair = SM2KeyPair.fromJson(new Gson().toJson(config));
SmartContractClientExt ext = new SmartContractClientExt(String.format("ws://%s/SCIDE/SCExecutor", config.agentAddress), keyPair); SmartContractClientExt ext = new SmartContractClientExt(
String.format("ws://%s/SCIDE/SCExecutor", config.agentAddress), keyPair);
ext.waitForConnect(); ext.waitForConnect();
ext.login(); ext.login();
for (; !ext.isLoggedIn; ) for (; !ext.isLoggedIn;)
Thread.yield(); Thread.yield();
AtomicInteger counter = new AtomicInteger(0); AtomicInteger counter = new AtomicInteger(0);
try { try {
if (config.killBeforeStart != null) ext.kill(config.killBeforeStart, new ResultCallback() { if (config.killBeforeStart != null)
@Override ext.kill(config.killBeforeStart, new ResultCallback() {
public void onResult(JsonObject r) { @Override
System.out.println(TAG + r); public void onResult(JsonObject r) {
counter.incrementAndGet(); System.out.println(TAG + r);
} counter.incrementAndGet();
}); }
for (; counter.get() == 0; ) });
Thread.yield(); for (; counter.get() == 0;)
; Thread.yield();;
Thread.sleep(200); Thread.sleep(200);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -101,15 +102,17 @@ public class HTTPTool {
ext.listProjects(true, new ResultCallback() { ext.listProjects(true, new ResultCallback() {
@Override @Override
public void onResult(JsonObject r) { public void onResult(JsonObject r) {
JsonArray array = JsonParser.parseString(r.get("data").getAsString()).getAsJsonArray(); JsonArray array =
JsonParser.parseString(r.get("data").getAsString()).getAsJsonArray();
for (JsonElement je : array) { for (JsonElement je : array) {
String fileName = je.getAsString(); String fileName = je.getAsString();
if (fileName.startsWith(contractName)) fileNames.add(fileName); if (fileName.startsWith(contractName))
fileNames.add(fileName);
} }
counter.incrementAndGet(); counter.incrementAndGet();
} }
}); });
for (; counter.get() == 1; ) for (; counter.get() == 1;)
Thread.yield(); Thread.yield();
Collections.sort(fileNames, new Comparator<String>() { Collections.sort(fileNames, new Comparator<String>() {
@Override @Override
@ -120,24 +123,26 @@ public class HTTPTool {
System.out.println(TAG + "startContract:" + fileNames.get(0)); System.out.println(TAG + "startContract:" + fileNames.get(0));
if (config.asDebug) { if (config.asDebug) {
ext.startContractAsDebug(fileNames.get(0), config.createParam,config.remoteDebugPort, new ResultCallback() { ext.startContractAsDebug(fileNames.get(0), config.createParam, config.remoteDebugPort,
@Override new ResultCallback() {
public void onResult(JsonObject r) { @Override
System.out.println(TAG + r); public void onResult(JsonObject r) {
counter.incrementAndGet(); System.out.println(TAG + r);
} counter.incrementAndGet();
}); }
});
} else { } else {
ext.startContract(fileNames.get(0), config.createParam,config.remoteDebugPort, new ResultCallback() { ext.startContract(fileNames.get(0), config.createParam, config.remoteDebugPort,
@Override new ResultCallback() {
public void onResult(JsonObject r) { @Override
System.out.println(TAG + r); public void onResult(JsonObject r) {
counter.incrementAndGet(); System.out.println(TAG + r);
} counter.incrementAndGet();
}); }
});
} }
for (; counter.get() == 2; ) for (; counter.get() == 2;)
Thread.yield(); Thread.yield();
} }
@ -145,7 +150,8 @@ public class HTTPTool {
String sub = dirName.substring(contractName.length()); String sub = dirName.substring(contractName.length());
if (sub.startsWith("_")) { if (sub.startsWith("_")) {
return Integer.valueOf(sub.substring(1)); return Integer.valueOf(sub.substring(1));
} else return -1; } else
return -1;
} }
public static void deployUseHttp(DeployConfig config) { public static void deployUseHttp(DeployConfig config) {
@ -154,9 +160,13 @@ public class HTTPTool {
String argWithoutSig = "path=%s&fileName=%s&isPrivate=true&order=%d&count=%d&pubKey=%s"; String argWithoutSig = "path=%s&fileName=%s&isPrivate=true&order=%d&count=%d&pubKey=%s";
SM2KeyPair keyPair; SM2KeyPair keyPair;
try { try {
keyPair = SM2KeyPair.fromJson(String.format("{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}", config.publicKey, config.privateKey)); keyPair = SM2KeyPair
.fromJson(String.format("{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}",
config.publicKey, config.privateKey));
} catch (Exception e) { } catch (Exception e) {
System.out.println("[HttpTool] parse key error:\n" + String.format("{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}", config.publicKey, config.privateKey)); System.out.println("[HttpTool] parse key error:\n"
+ String.format("{\"publicKey\":\"%s\",\"privateKey\":\"%s\"}",
config.publicKey, config.privateKey));
e.printStackTrace(); e.printStackTrace();
return; return;
} }
@ -169,17 +179,21 @@ public class HTTPTool {
FileInputStream fin = new FileInputStream(file); FileInputStream fin = new FileInputStream(file);
for (int len = 0; (len = fin.read(buff)) > 0; order++) { for (int len = 0; (len = fin.read(buff)) > 0; order++) {
CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpClient client = HttpClients.createDefault();
String arg = String.format(argWithoutSig, "./", file.getName(), order, count, pubKey); String arg =
String sign = ByteUtils.toHexString(SM2Util.sign(keyPair.getPrivateKeyParameter(), arg.getBytes(StandardCharsets.UTF_8))); String.format(argWithoutSig, "./", file.getName(), order, count, pubKey);
String sign = ByteUtils.toHexString(SM2Util.sign(keyPair.getPrivateKeyParameter(),
arg.getBytes(StandardCharsets.UTF_8)));
String urlStr = String.format(url, config.agentAddress, arg, sign); String urlStr = String.format(url, config.agentAddress, arg, sign);
HttpPost httpPost = new HttpPost(urlStr); HttpPost httpPost = new HttpPost(urlStr);
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (len == trunc) if (len == trunc)
builder.addBinaryBody("file", buff, ContentType.APPLICATION_OCTET_STREAM, file.getName()); builder.addBinaryBody("file", buff, ContentType.APPLICATION_OCTET_STREAM,
file.getName());
else { else {
byte[] bu = new byte[len]; byte[] bu = new byte[len];
System.arraycopy(buff, 0, bu, 0, len); System.arraycopy(buff, 0, bu, 0, len);
builder.addBinaryBody("file", bu, ContentType.APPLICATION_OCTET_STREAM, file.getName()); builder.addBinaryBody("file", bu, ContentType.APPLICATION_OCTET_STREAM,
file.getName());
} }
HttpEntity multipart = builder.build(); HttpEntity multipart = builder.build();

View File

@ -42,7 +42,7 @@ public class RouterSetter {
count.incrementAndGet(); count.incrementAndGet();
} }
}); });
for (; count.get() < entry.tasks.size(); ) { for (; count.get() < entry.tasks.size();) {
try { try {
Thread.sleep(10000); Thread.sleep(10000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -55,8 +55,8 @@ public class RouterSetter {
private static void executeTask(SetUpperTask task) throws Exception { private static void executeTask(SetUpperTask task) throws Exception {
SM2KeyPair keyPair = SM2KeyPair.fromJson(new Gson().toJson(task)); SM2KeyPair keyPair = SM2KeyPair.fromJson(new Gson().toJson(task));
SmartContractClientExt ext = new SmartContractClientExt(String.format("ws://%s/SCIDE/SCExecutor", task.ipAndPort), SmartContractClientExt ext = new SmartContractClientExt(
keyPair); String.format("ws://%s/SCIDE/SCExecutor", task.ipAndPort), keyPair);
System.out.println("[RouterSetter] try connect " + task.nodeName + " " + task.ipAndPort); System.out.println("[RouterSetter] try connect " + task.nodeName + " " + task.ipAndPort);
ext.waitForConnect(); ext.waitForConnect();
@ -99,10 +99,8 @@ public class RouterSetter {
cr.setAction("setSignature"); cr.setAction("setSignature");
cr.setContractID("Router"); cr.setContractID("Router");
String toSign = task.nodeName + "|" + task.publicKey; String toSign = task.nodeName + "|" + task.publicKey;
String signature = String signature = ByteUtils
ByteUtils.toHexString( .toHexString(SM2Util.sign(keyPair.getPrivateKeyParameter(), toSign.getBytes()));
SM2Util.sign(
keyPair.getPrivateKeyParameter(), toSign.getBytes()));
cr.setArg(String.format("{\"signature\":\"%s\"}", signature)); cr.setArg(String.format("{\"signature\":\"%s\"}", signature));
cr.doSignature(keyPair); cr.doSignature(keyPair);
result = ext.executeContractSync(cr); result = ext.executeContractSync(cr);

View File

@ -37,7 +37,8 @@ public class SmartContractClientExt extends SmartContractClient {
startContract(project, createParam, 0, null); startContract(project, createParam, 0, null);
} }
public void startContractByYpk(String path, boolean isPrivate, JsonElement createParam, ResultCallback rc) { public void startContractByYpk(String path, boolean isPrivate, JsonElement createParam,
ResultCallback rc) {
String reqID = System.currentTimeMillis() + ""; String reqID = System.currentTimeMillis() + "";
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "startContractByYPK"); ret.put("action", "startContractByYPK");
@ -50,10 +51,8 @@ public class SmartContractClientExt extends SmartContractClient {
String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr()); String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr());
String sig; String sig;
try { try {
sig = sig = ByteUtils.toHexString(
ByteUtils.toHexString( SM2Util.sign(getKeyPair().getPrivateKeyParameter(), content.getBytes()));
SM2Util.sign(
getKeyPair().getPrivateKeyParameter(), content.getBytes()));
ret.put("signature", sig); ret.put("signature", sig);
} catch (CryptoException e) { } catch (CryptoException e) {
e.printStackTrace(); e.printStackTrace();
@ -77,10 +76,8 @@ public class SmartContractClientExt extends SmartContractClient {
String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr()); String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr());
String sig; String sig;
try { try {
sig = sig = ByteUtils.toHexString(
ByteUtils.toHexString( SM2Util.sign(getKeyPair().getPrivateKeyParameter(), content.getBytes()));
SM2Util.sign(
getKeyPair().getPrivateKeyParameter(), content.getBytes()));
ret.put("signature", sig); ret.put("signature", sig);
} catch (CryptoException e) { } catch (CryptoException e) {
e.printStackTrace(); e.printStackTrace();
@ -93,7 +90,8 @@ public class SmartContractClientExt extends SmartContractClient {
this.sendMsg(new Gson().toJson(ret)); this.sendMsg(new Gson().toJson(ret));
} }
public void startContractAsDebug(String project, JsonElement createParam, int remoteDebugPort, ResultCallback rc) { public void startContractAsDebug(String project, JsonElement createParam, int remoteDebugPort,
ResultCallback rc) {
String reqID = System.currentTimeMillis() + ""; String reqID = System.currentTimeMillis() + "";
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "startContractAsDebug"); ret.put("action", "startContractAsDebug");
@ -108,10 +106,8 @@ public class SmartContractClientExt extends SmartContractClient {
String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr()); String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr());
String sig; String sig;
try { try {
sig = sig = ByteUtils.toHexString(
ByteUtils.toHexString( SM2Util.sign(getKeyPair().getPrivateKeyParameter(), content.getBytes()));
SM2Util.sign(
getKeyPair().getPrivateKeyParameter(), content.getBytes()));
ret.put("signature", sig); ret.put("signature", sig);
} catch (CryptoException e) { } catch (CryptoException e) {
e.printStackTrace(); e.printStackTrace();
@ -124,7 +120,8 @@ public class SmartContractClientExt extends SmartContractClient {
this.sendMsg(new Gson().toJson(ret)); this.sendMsg(new Gson().toJson(ret));
} }
public void startContract(String project, JsonElement createParam, int remoteDebugPort, ResultCallback rc) { public void startContract(String project, JsonElement createParam, int remoteDebugPort,
ResultCallback rc) {
String reqID = System.currentTimeMillis() + ""; String reqID = System.currentTimeMillis() + "";
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "startContract"); ret.put("action", "startContract");
@ -139,10 +136,8 @@ public class SmartContractClientExt extends SmartContractClient {
String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr()); String.format("Sole|%s|%s", ret.get("path"), getKeyPair().getPublicKeyStr());
String sig; String sig;
try { try {
sig = sig = ByteUtils.toHexString(
ByteUtils.toHexString( SM2Util.sign(getKeyPair().getPrivateKeyParameter(), content.getBytes()));
SM2Util.sign(
getKeyPair().getPrivateKeyParameter(), content.getBytes()));
ret.put("signature", sig); ret.put("signature", sig);
} catch (CryptoException e) { } catch (CryptoException e) {
e.printStackTrace(); e.printStackTrace();
@ -157,11 +152,12 @@ public class SmartContractClientExt extends SmartContractClient {
@Override @Override
public void onLogin(JsonObject obj) { public void onLogin(JsonObject obj) {
// LOGGER.info(obj.toString()); // LOGGER.info(obj.toString());
isLoggedIn = true; isLoggedIn = true;
} }
public void startMultiContractByScript(String script, String peersID, JsonElement createParam, ResultCallback rc) { public void startMultiContractByScript(String script, String peersID, JsonElement createParam,
ResultCallback rc) {
String reqID = System.currentTimeMillis() + "" + secureRandom.nextInt(); String reqID = System.currentTimeMillis() + "" + secureRandom.nextInt();
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "startContractMultiPoint"); ret.put("action", "startContractMultiPoint");
@ -172,7 +168,8 @@ public class SmartContractClientExt extends SmartContractClient {
ret.put("requestID", reqID); ret.put("requestID", reqID);
ret.put("createParam", createParam); ret.put("createParam", createParam);
// "Algorithm|" + request.script + "|" + global.sm2Key.publicKey // "Algorithm|" + request.script + "|" + global.sm2Key.publicKey
ret.put("signature", doSignature(getKeyPair().getPrivateKeyParameter(), "Sole|" + script + "|" + ret.get("owner"))); ret.put("signature", doSignature(getKeyPair().getPrivateKeyParameter(),
"Sole|" + script + "|" + ret.get("owner")));
if (rc != null) { if (rc != null) {
cbs.put(reqID, rc); cbs.put(reqID, rc);
} }
@ -183,10 +180,7 @@ public class SmartContractClientExt extends SmartContractClient {
public String doSignature(ECPrivateKeyParameters privateKey, String content) { public String doSignature(ECPrivateKeyParameters privateKey, String content) {
try { try {
return return ByteUtils.toHexString(SM2Util.sign(privateKey, content.getBytes()));
ByteUtils.toHexString(
SM2Util.sign(
privateKey, content.getBytes()));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -208,13 +202,8 @@ public class SmartContractClientExt extends SmartContractClient {
} }
public void startMultiContract( public void startMultiContract(boolean isPrivate, String ypkName, String peersID,
boolean isPrivate, int contractExecType, JsonElement createParam, ResultCallback rc) {
String ypkName,
String peersID,
int contractExecType,
JsonElement createParam,
ResultCallback rc) {
String reqID = System.currentTimeMillis() + "" + secureRandom.nextInt(); String reqID = System.currentTimeMillis() + "" + secureRandom.nextInt();
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
ret.put("action", "startContractMultiPoint"); ret.put("action", "startContractMultiPoint");
@ -242,9 +231,8 @@ public class SmartContractClientExt extends SmartContractClient {
ret.put("owner", getKeyPair().getPublicKeyStr()); ret.put("owner", getKeyPair().getPublicKeyStr());
ret.put("requestID", reqID); ret.put("requestID", reqID);
// "Algorithm|" + request.script + "|" + global.sm2Key.publicKey // "Algorithm|" + request.script + "|" + global.sm2Key.publicKey
ret.put( ret.put("signature", doSignature(getKeyPair().getPrivateKeyParameter(),
"signature", "Algorithm|" + script + "|" + ret.get("owner")));
doSignature(getKeyPair().getPrivateKeyParameter(), "Algorithm|" + script + "|" + ret.get("owner")));
if (rc != null) { if (rc != null) {
cbs.put(reqID, rc); cbs.put(reqID, rc);
} }
@ -272,8 +260,8 @@ public class SmartContractClientExt extends SmartContractClient {
this.sendMsg(new Gson().toJson(ret)); this.sendMsg(new Gson().toJson(ret));
} }
// public void onExecuteResult(JsonObject obj) { // public void onExecuteResult(JsonObject obj) {
// } // }
public void genBDCoin(String name) { public void genBDCoin(String name) {
Map<String, Object> ret = new HashMap<>(); Map<String, Object> ret = new HashMap<>();
@ -295,7 +283,8 @@ public class SmartContractClientExt extends SmartContractClient {
public void onStartContractTrustfullyResult(JsonObject jo) { public void onStartContractTrustfullyResult(JsonObject jo) {
String responseID = jo.get("responseID").getAsString(); String responseID = jo.get("responseID").getAsString();
ResultCallback cb = cbs.get(responseID); ResultCallback cb = cbs.get(responseID);
if (cb != null) cb.onResult(jo); if (cb != null)
cb.onResult(jo);
} }
@Action @Action
@ -317,7 +306,8 @@ public class SmartContractClientExt extends SmartContractClient {
public void onListProjects(JsonObject jo) { public void onListProjects(JsonObject jo) {
String responseID = jo.get("responseID").getAsString(); String responseID = jo.get("responseID").getAsString();
ResultCallback cb = cbs.get(responseID); ResultCallback cb = cbs.get(responseID);
if (cb != null) cb.onResult(jo); if (cb != null)
cb.onResult(jo);
} }
@ -329,7 +319,8 @@ public class SmartContractClientExt extends SmartContractClient {
} }
String responseID = jo.get("responseID").getAsString(); String responseID = jo.get("responseID").getAsString();
ResultCallback cb = cbs.get(responseID); ResultCallback cb = cbs.get(responseID);
if (cb != null) cb.onResult(jo); if (cb != null)
cb.onResult(jo);
} }
public void requestNodeInfo() { public void requestNodeInfo() {
@ -344,7 +335,7 @@ public class SmartContractClientExt extends SmartContractClient {
public void loginSync() { public void loginSync() {
login(); login();
for (; !isLoggedIn; ) for (; !isLoggedIn;)
Thread.yield(); Thread.yield();
} }

View File

@ -5,32 +5,34 @@ import org.junit.Test;
public class EntryTest { public class EntryTest {
@Test @Test
public void generateAllConf() { public void generateAllConf() {
Entry.main(new String[]{"./testinput/generateAllConf.json"}); Entry.main(new String[] {"./testinput/generateAllConf.json"});
} }
@Test @Test
public void deployrouter() { public void deployrouter() {
Entry.main(new String[]{"./testinput/deployrouter.json"}); Entry.main(new String[] {"./testinput/deployrouter.json"});
} }
@Test @Test
public void deployap() { public void deployap() {
Entry.main(new String[]{"./testinput/deployrouter.json"}); Entry.main(new String[] {"./testinput/deployrouter.json"});
} }
@Test @Test
public void deploycp() { public void deploycp() {
Entry.main(new String[]{"./testinput/deployrouter.json"}); Entry.main(new String[] {"./testinput/deployrouter.json"});
} }
@Test @Test
public void deployBDTest() { public void deployBDTest() {
HTTPTool.deploy("./testinput/deploy/router/GlobalRouter-023.json"); HTTPTool.deploy("./testinput/deploy/router/GlobalRouter-023.json");
} }
@Test @Test
public void deployShanxiProxy() { public void deployShanxiProxy() {
HTTPTool.deploy("./testinput/debugconf-shanxiproxy.json"); HTTPTool.deploy("./testinput/debugconf-shanxiproxy.json");
} }
@Test @Test
public void deployRemoteDebug() { public void deployRemoteDebug() {
HTTPTool.deploy("./testinput/debugconf-remotedebug.json"); HTTPTool.deploy("./testinput/debugconf-remotedebug.json");

View File

@ -21,12 +21,15 @@ public class HttpUploadTest {
@Test @Test
public void run() { public void run() {
String url = "http://%s/Upload?%s&sign=%s"; String url = "http://%s/Upload?%s&sign=%s";
File file = new File("/Users/huaqiancai/BDWare/bdcontract-bundle/agent-backend/BDWareProjectDir/publicCompiled/DoipDist-0.3.3.ypk"); File file = new File(
String argWithoutSig = "path=%s&fileName=%s&isPrivate=true&contractID=%s&order=%d&count=%d&pubKey=%s"; "/Users/huaqiancai/BDWare/bdcontract-bundle/agent-backend/BDWareProjectDir/publicCompiled/DoipDist-0.3.3.ypk");
String argWithoutSig =
"path=%s&fileName=%s&isPrivate=true&contractID=%s&order=%d&count=%d&pubKey=%s";
SM2KeyPair keyPair; SM2KeyPair keyPair;
try { try {
keyPair = SM2KeyPair.fromJson("{\"privateKey\":\"589d94ee5688358a1c5c18430dd9c75097ddddebf769f139da36a807911d20f8\",\"publicKey\":\"04d1924329f72ced148f6f333fb985ccbaa31b1e3aacf10be5f43d4a4ff5ad88899a005e79e37fc06993e1d66ada8cf8b711cb36f59538bb7d3e39e70fa9360ddd\"}"); keyPair = SM2KeyPair.fromJson(
"{\"privateKey\":\"589d94ee5688358a1c5c18430dd9c75097ddddebf769f139da36a807911d20f8\",\"publicKey\":\"04d1924329f72ced148f6f333fb985ccbaa31b1e3aacf10be5f43d4a4ff5ad88899a005e79e37fc06993e1d66ada8cf8b711cb36f59538bb7d3e39e70fa9360ddd\"}");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return; return;
@ -40,18 +43,22 @@ public class HttpUploadTest {
FileInputStream fin = new FileInputStream(file); FileInputStream fin = new FileInputStream(file);
for (int len = 0; (len = fin.read(buff)) > 0; order++) { for (int len = 0; (len = fin.read(buff)) > 0; order++) {
CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpClient client = HttpClients.createDefault();
String arg = String.format(argWithoutSig, "/ypks", file.getName(), "CodeRepo", order, count, pubKey); String arg = String.format(argWithoutSig, "/ypks", file.getName(), "CodeRepo",
String sign = ByteUtils.toHexString(SM2Util.sign(keyPair.getPrivateKeyParameter(), arg.getBytes(StandardCharsets.UTF_8))); order, count, pubKey);
String sign = ByteUtils.toHexString(SM2Util.sign(keyPair.getPrivateKeyParameter(),
arg.getBytes(StandardCharsets.UTF_8)));
String urlStr = String.format(url, "127.0.0.1:18000", arg, sign); String urlStr = String.format(url, "127.0.0.1:18000", arg, sign);
System.out.println("urlStr:" + urlStr); System.out.println("urlStr:" + urlStr);
HttpPost httpPost = new HttpPost(urlStr); HttpPost httpPost = new HttpPost(urlStr);
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (len == trunc) if (len == trunc)
builder.addBinaryBody("file", buff, ContentType.APPLICATION_OCTET_STREAM, file.getName()); builder.addBinaryBody("file", buff, ContentType.APPLICATION_OCTET_STREAM,
file.getName());
else { else {
byte[] bu = new byte[len]; byte[] bu = new byte[len];
System.arraycopy(buff, 0, bu, 0, len); System.arraycopy(buff, 0, bu, 0, len);
builder.addBinaryBody("file", bu, ContentType.APPLICATION_OCTET_STREAM, file.getName()); builder.addBinaryBody("file", bu, ContentType.APPLICATION_OCTET_STREAM,
file.getName());
} }
HttpEntity multipart = builder.build(); HttpEntity multipart = builder.build();