use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.
the class VotingTest method persistentVotingChangeOwnerReferenced.
@Test
public void persistentVotingChangeOwnerReferenced() throws Exception {
TestSpace ts = prepareTestSpace();
ts.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true));
Client client = new Client("test_node_config_v2", null, TestKeys.privateKey(1));
for (int i = 0; i < client.size(); i++) {
client.getClient(i);
}
Contract referenced = new Contract(TestKeys.privateKey(1));
QuorumVoteRole quorumVoteRole = new QuorumVoteRole("change_owner", referenced, "this.state.data.list", "90%");
referenced.addRole(quorumVoteRole);
List<KeyAddress> addresses = new ArrayList<>();
for (int i = 0; i < 20; i++) {
addresses.add(TestKeys.publicKey(i).getLongAddress());
}
referenced.getStateData().put("list", addresses);
referenced.seal();
assertEquals(client.register(referenced.getPackedTransaction(), 10000).state, ItemState.APPROVED);
Contract updated = new Contract(TestKeys.privateKey(1));
Reference reference = new Reference(updated);
reference.name = "change_owner";
reference.setConditions(Binder.of("all_of", Do.listOf("ref.id==this.state.data.referenced", "this can_play ref.state.roles.change_owner")));
updated.addReference(reference);
updated.getStateData().put("referenced", referenced.getId().toBase64String());
SimpleRole owner = new SimpleRole("owner", updated);
owner.addRequiredReference("change_owner", Role.RequiredMode.ALL_OF);
updated.addRole(owner);
updated.seal();
assertEquals(client.register(updated.getPackedTransaction(), 10000).state, ItemState.APPROVED);
Contract revision1 = updated.createRevision(TestKeys.privateKey(4));
revision1.setOwnerKey(TestKeys.publicKey(2).getLongAddress());
revision1.seal();
revision1.getTransactionPack().addReferencedItem(referenced);
Contract revision2 = updated.createRevision(TestKeys.privateKey(4));
revision2.setOwnerKey(TestKeys.publicKey(3).getLongAddress());
revision2.seal();
revision2.getTransactionPack().addReferencedItem(referenced);
Contract u = Parcel.createPayment(getApprovedUContract(ts), Do.listOf(ts.myKey), 1, false);
HashId opId = client.initiateVote(u.getPackedTransaction(), referenced, "change_owner", Do.listOf(revision1.getId(), revision2.getId()));
while (client.getPaidOperationProcessingState(opId).isProcessing()) {
Thread.sleep(100);
}
if (client.getState(u.getId()).state == ItemState.APPROVED) {
synchronized (ts.uContractLock) {
ts.uContract = u;
}
} else {
throw new IllegalArgumentException("wrong u");
}
ts.shutdown();
ts = prepareTestSpace();
ts.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true));
for (int j = 0; j < 19; j++) {
Client keyClient = new Client("test_node_config_v2", null, TestKeys.privateKey(j));
u = Parcel.createPayment(getApprovedUContract(ts), Do.listOf(ts.myKey), 1, false);
opId = keyClient.voteForContract(u.getPackedTransaction(), referenced.getId(), revision2.getId());
while (keyClient.getPaidOperationProcessingState(opId).isProcessing()) {
Thread.sleep(100);
}
ItemResult ir = client.getState(u.getId());
System.out.println(opId + " " + ir);
if (ir.state == ItemState.APPROVED) {
synchronized (ts.uContractLock) {
ts.uContract = u;
}
} else {
throw new IllegalArgumentException("wrong u");
}
}
assertEquals(client.register(revision1.getPackedTransaction(), 100000).state, ItemState.DECLINED);
assertEquals(client.register(revision2.getPackedTransaction(), 100000).state, ItemState.APPROVED);
ts.shutdown();
}
use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.
the class ScriptEngineTest method latestHttpContractFromSlot1.
@Test
public void latestHttpContractFromSlot1() throws Exception {
System.out.println("============= start nodes...");
TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0));
testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true));
System.out.println("============= start nodes done\n\n\n");
Contract contractServer = new Contract(TestKeys.privateKey(0));
String js = "";
js += "var jsApiEvents = new Object();";
js += "jsApiEvents.httpHandler_getVersion = function(request, response){" + " response.setBodyAsJson({" + " version: 1" + " });" + "};";
contractServer.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters(), true);
RoleLink issuerLink = new RoleLink("issuer_link", "issuer");
contractServer.registerRole(issuerLink);
Permission perm = new ModifyDataPermission(issuerLink, Binder.of("fields", Binder.of("scripts", null)));
contractServer.addPermission(perm);
contractServer.seal();
contractServer = Contract.fromPackedTransaction(contractServer.getPackedTransaction());
ItemResult itemResult = testSpace.client.register(contractServer.getPackedTransaction(), 5000);
assertEquals(ItemState.APPROVED, itemResult.state);
// put contractServer rev1 into slot1
SlotContract slotContract = ContractsService.createSlotContract(new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), new HashSet<>(Arrays.asList(TestKeys.publicKey(0))), nodeInfoProvider);
slotContract.setNodeInfoProvider(nodeInfoProvider);
slotContract.putTrackingContract(contractServer);
Contract stepaU = InnerContractsService.createFreshU(100000000, new HashSet<>(Arrays.asList(TestKeys.publicKey(0))));
itemResult = testSpace.client.register(stepaU.getPackedTransaction(), 5000);
System.out.println("stepaU : " + itemResult);
assertEquals(ItemState.APPROVED, itemResult.state);
Parcel parcel = ContractsService.createPayingParcel(slotContract.getTransactionPack(), stepaU, 1, 100, new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), false);
testSpace.client.registerParcelWithState(parcel.pack(), 5000);
itemResult = testSpace.client.getState(slotContract.getId());
System.out.println("slot : " + itemResult);
assertEquals(ItemState.APPROVED, itemResult.state);
// start http server
JSApiHttpServerRoutes routes = new JSApiHttpServerRoutes();
routes.setPortToListen(8880);
routes.addNewRoute("/contract1/getVersion", "httpHandler_getVersion", contractServer, "client script.js", null, slotContract.getId());
JSApiHttpServer httpServer = new JSApiHttpServer(routes, new JSApiExecOptions(), hashId -> {
try {
return testSpace.client.getState(hashId).state == ItemState.APPROVED;
} catch (ClientError e) {
e.printStackTrace();
return false;
}
}, (slotId, originId) -> {
try {
Binder slotInfo = testSpace.client.querySlotInfo(slotId);
return testSpace.client.queryContract(slotId, originId, null);
} catch (ClientError e) {
e.printStackTrace();
return null;
}
});
// here can be any http client. JSApiHttpClient used just for easiness
JSApiScriptParameters scriptParameters = new JSApiScriptParameters();
scriptParameters.domainMasks.add("localhost:*");
JSApiHttpClient httpClient = new JSApiHttpClient(scriptParameters);
// http access to contractServer rev1
List httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
System.out.println("httpRes: " + httpRes);
assertEquals(1l, ((HashMap) httpRes.get(1)).get("version"));
// create and register contractServer rev2
Contract contractServer2 = contractServer.createRevision();
contractServer2.addSignerKey(TestKeys.privateKey(0));
String js2 = "";
js2 += "var jsApiEvents = new Object();";
js2 += "jsApiEvents.httpHandler_getVersion = function(request, response){" + " response.setBodyAsJson({" + " version: 2" + " });" + "};";
contractServer2.getState().setJS(js2.getBytes(), "client script.js", new JSApiScriptParameters(), true);
contractServer2.seal();
contractServer2 = Contract.fromPackedTransaction(contractServer2.getPackedTransaction());
ItemResult itemResult2 = testSpace.client.register(contractServer2.getPackedTransaction(), 5000);
assertEquals(ItemState.APPROVED, itemResult2.state);
assertEquals(ItemState.REVOKED, testSpace.client.getState(contractServer.getId()).state);
// force update server contracts from slot1
httpServer.checkAllContracts();
// http access to contractServer rev2
httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
System.out.println("httpRes: " + httpRes);
assertEquals(2l, ((HashMap) httpRes.get(1)).get("version"));
System.out.println("\n\n\n============= shutdown...");
testSpace.nodes.forEach(m -> m.shutdown());
httpServer.stop();
}
use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.
the class ScriptEngineTest method initHttpRoutesFromSlot1.
@Test
public void initHttpRoutesFromSlot1() throws Exception {
System.out.println("============= start nodes...");
TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0));
testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true));
System.out.println("============= start nodes done\n\n\n");
Contract contractServer = new Contract(TestKeys.privateKey(0));
String js = "";
js += "var jsApiEvents = new Object();";
js += "jsApiEvents.httpHandler_getVersion = function(request, response){" + " response.setBodyAsJson({" + " version: 1" + " });" + "};";
contractServer.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters(), true);
RoleLink issuerLink = new RoleLink("issuer_link", "issuer");
contractServer.registerRole(issuerLink);
Permission perm = new ModifyDataPermission(issuerLink, Binder.of("fields", Binder.of("scripts", null)));
contractServer.addPermission(perm);
contractServer.seal();
contractServer = Contract.fromPackedTransaction(contractServer.getPackedTransaction());
ItemResult itemResult = testSpace.client.register(contractServer.getPackedTransaction(), 5000);
assertEquals(ItemState.APPROVED, itemResult.state);
// put contractServer rev1 into slot1
SlotContract slotContract = ContractsService.createSlotContract(new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), new HashSet<>(Arrays.asList(TestKeys.publicKey(0))), nodeInfoProvider);
slotContract.setNodeInfoProvider(nodeInfoProvider);
slotContract.putTrackingContract(contractServer);
Contract stepaU = InnerContractsService.createFreshU(100000000, new HashSet<>(Arrays.asList(TestKeys.publicKey(0))));
itemResult = testSpace.client.register(stepaU.getPackedTransaction(), 5000);
System.out.println("stepaU : " + itemResult);
assertEquals(ItemState.APPROVED, itemResult.state);
Parcel parcel = ContractsService.createPayingParcel(slotContract.getTransactionPack(), stepaU, 1, 100, new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), false);
testSpace.client.registerParcelWithState(parcel.pack(), 5000);
itemResult = testSpace.client.getState(slotContract.getId());
System.out.println("slot : " + itemResult);
assertEquals(ItemState.APPROVED, itemResult.state);
JSApiHttpServer.ISlot1Requestor slot1Requestor = (slotId, originId) -> {
try {
Binder slotInfo = testSpace.client.querySlotInfo(slotId);
return testSpace.client.queryContract(slotId, originId, null);
} catch (ClientError e) {
e.printStackTrace();
return null;
}
};
// start http server
String routesJsonString = "{\n" + " \"listenPort\": \"8880\",\n" + " \"routes\": [\n" + " {\"endpoint\": \"/contract1/getVersion\", \"handlerName\": \"httpHandler_getVersion\", \"scriptName\": \"client script.js\", \"slotId\":\"" + slotContract.getId().toBase64String() + "\", \"originId\":\"" + contractServer.getOrigin().toBase64String() + "\"}\n" + " ]\n" + "}\n";
String tmpdir = System.getProperty("java.io.tmpdir");
String strPathRoutes = tmpdir + "/" + "routes.json";
Files.deleteIfExists(Paths.get(strPathRoutes));
new File(strPathRoutes).createNewFile();
Files.write(Paths.get(strPathRoutes), routesJsonString.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
JSApiHttpServerRoutes routes = new JSApiHttpServerRoutes(strPathRoutes, slot1Requestor);
JSApiHttpServer httpServer = new JSApiHttpServer(routes, new JSApiExecOptions(), hashId -> {
try {
return testSpace.client.getState(hashId).state == ItemState.APPROVED;
} catch (ClientError e) {
e.printStackTrace();
return false;
}
}, slot1Requestor);
// here can be any http client. JSApiHttpClient used just for easiness
JSApiScriptParameters scriptParameters = new JSApiScriptParameters();
scriptParameters.domainMasks.add("localhost:*");
JSApiHttpClient httpClient = new JSApiHttpClient(scriptParameters);
// http access to contractServer rev1
List httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
System.out.println("httpRes: " + httpRes);
assertEquals(1l, ((HashMap) httpRes.get(1)).get("version"));
// create and register contractServer rev2
Contract contractServer2 = contractServer.createRevision();
contractServer2.addSignerKey(TestKeys.privateKey(0));
String js2 = "";
js2 += "var jsApiEvents = new Object();";
js2 += "jsApiEvents.httpHandler_getVersion = function(request, response){" + " response.setBodyAsJson({" + " version: 2" + " });" + "};";
contractServer2.getState().setJS(js2.getBytes(), "client script.js", new JSApiScriptParameters(), true);
contractServer2.seal();
contractServer2 = Contract.fromPackedTransaction(contractServer2.getPackedTransaction());
ItemResult itemResult2 = testSpace.client.register(contractServer2.getPackedTransaction(), 5000);
assertEquals(ItemState.APPROVED, itemResult2.state);
assertEquals(ItemState.REVOKED, testSpace.client.getState(contractServer.getId()).state);
// force update server contracts from slot1
httpServer.checkAllContracts();
// http access to contractServer rev2
httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
System.out.println("httpRes: " + httpRes);
assertEquals(2l, ((HashMap) httpRes.get(1)).get("version"));
System.out.println("\n\n\n============= shutdown...");
testSpace.nodes.forEach(m -> m.shutdown());
httpServer.stop();
}
use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.
the class UBotSessionsProTest method createSessionPaid.
@Test
public void createSessionPaid() throws Exception {
Client client = new Client("universa.pro", null, TestKeys.privateKey(0));
int quorumSize = 5;
int poolSize = 8;
Contract executableContract = new Contract(TestKeys.privateKey(1));
executableContract.getStateData().put("cloud_methods", Binder.of("getRandom", Binder.of("pool", Binder.of("size", poolSize), "quorum", Binder.of("size", quorumSize))));
executableContract.getStateData().put("js", "");
executableContract.seal();
assertEquals(client.register(executableContract.getPackedTransaction(), 100000).state, ItemState.APPROVED);
Contract u = InnerContractsService.createFreshU(100000, new HashSet(Do.listOf(TestKeys.privateKey(1).getPublicKey())));
u.setIssuerKeys(TestKeys.privateKey(0).getPublicKey().getLongAddress());
u.seal();
u.addSignatureToSeal(TestKeys.privateKey(0));
assertEquals(client.register(u.getPackedTransaction(), 100000).state, ItemState.APPROVED);
u = u.createRevision(TestKeys.privateKey(1));
u.getStateData().put("transaction_units", u.getStateData().getIntOrThrow("transaction_units") - 3);
u.seal();
Contract requestContract = new Contract(TestKeys.privateKey(2));
requestContract.getStateData().put("executable_contract_id", executableContract.getId());
requestContract.getStateData().put("method_name", "getRandom");
requestContract.getStateData().put("method_args", Do.listOf(1000));
ContractsService.addReferenceToContract(requestContract, executableContract, "executable_contract_constraint", Reference.TYPE_EXISTING_DEFINITION, Do.listOf("ref.id==this.state.data.executable_contract_id"), true);
requestContract.seal();
requestContract.getTransactionPack().addReferencedItem(executableContract);
System.out.println(client.command("ubotCreateSessionPaid", "packedU", u.getPackedTransaction(), "packedRequest", requestContract.getPackedTransaction()));
AtomicInteger readyCounter = new AtomicInteger();
AsyncEvent readyEvent = new AsyncEvent();
AtomicReference<List<Integer>> pool = new AtomicReference<>();
HashId finalRequestId = requestContract.getId();
for (int i = 0; i < client.size(); i++) {
int finalI = i;
Do.inParallel(() -> {
while (true) {
Binder res = client.getClient(finalI).command("ubotGetSession", "requestId", finalRequestId);
System.out.println(client.getClient(finalI).getNodeNumber() + " " + res);
Thread.sleep(500);
if (res.get("session") != null && res.getBinderOrThrow("session").getString("state").equals("OPERATIONAL")) {
pool.set(res.getBinderOrThrow("session").getListOrThrow("sessionPool"));
if (readyCounter.incrementAndGet() == client.size()) {
readyEvent.fire();
}
break;
}
}
});
}
readyEvent.await();
}
use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.
the class UBotSessionsProTest method createSession.
@Ignore
@Test
public void createSession() throws Exception {
Client client = new Client("universa.pro", null, TestKeys.privateKey(0));
int quorumSize = 5;
int poolSize = 8;
Contract executableContract = new Contract(TestKeys.privateKey(1));
executableContract.getStateData().put("cloud_methods", Binder.of("getRandom", Binder.of("pool", Binder.of("size", poolSize), "quorum", Binder.of("size", quorumSize))));
executableContract.getStateData().put("js", "");
executableContract.seal();
assertEquals(client.register(executableContract.getPackedTransaction(), 100000).state, ItemState.APPROVED);
for (int x = 0; x < ATTEMPTS; x++) {
System.out.println("ATTEMPT " + x);
Contract requestContract = new Contract(TestKeys.privateKey(2));
requestContract.getStateData().put("executable_contract_id", executableContract.getId());
requestContract.getStateData().put("method_name", "getRandom");
requestContract.getStateData().put("method_args", Do.listOf(1000));
ContractsService.addReferenceToContract(requestContract, executableContract, "executable_contract_constraint", Reference.TYPE_EXISTING_DEFINITION, Do.listOf("ref.id==this.state.data.executable_contract_id"), true);
requestContract.seal();
requestContract.getTransactionPack().addReferencedItem(executableContract);
System.out.println(client.command("ubotCreateSession", "packedRequest", requestContract.getPackedTransaction()));
AtomicInteger readyCounter = new AtomicInteger();
AsyncEvent readyEvent = new AsyncEvent();
AtomicReference<List<Integer>> pool = new AtomicReference<>();
HashId finalRequestId = requestContract.getId();
for (int i = 0; i < client.size(); i++) {
int finalI = i;
Do.inParallel(() -> {
while (true) {
Binder res = client.getClient(finalI).command("ubotGetSession", "requestId", finalRequestId);
System.out.println(client.getClient(finalI).getNodeNumber() + " " + res);
Thread.sleep(500);
if (res.get("session") != null && res.getBinderOrThrow("session").getString("state").equals("OPERATIONAL")) {
pool.set(res.getBinderOrThrow("session").getListOrThrow("sessionPool"));
if (readyCounter.incrementAndGet() == client.size()) {
readyEvent.fire();
}
break;
}
}
});
}
readyEvent.await();
int votingCount = quorumSize + Do.randomInt(poolSize - quorumSize);
Set<Integer> poolQuorum = new HashSet<>();
while (poolQuorum.size() < votingCount) {
poolQuorum.add(Do.sample(pool.get()));
}
Set<Client> quorumClients = new HashSet<>();
poolQuorum.forEach(n -> {
try {
quorumClients.add(new Client("universa.pro", null, ubotKeys.get(n)));
} catch (IOException e) {
e.printStackTrace();
}
});
assertEquals(quorumClients.size(), poolQuorum.size());
HashId storageValue = HashId.createRandom();
quorumClients.forEach(c -> {
for (int i = 0; i < c.size(); i++) {
int finalI = i;
Do.inParallel(() -> {
try {
// c.getClient(finalI).command("ubotUpdateStorage","executableContractId", executableContract.getId(),"storageName","default","fromValue",null,"toValue", storageValue);
c.getClient(finalI).command("ubotUpdateStorage", "requestId", finalRequestId, "storageName", "default", "toValue", storageValue);
} catch (IOException e) {
e.printStackTrace();
}
});
}
});
while (true) {
Binder res = client.command("ubotGetStorage", "requestId", finalRequestId, "storageNames", Do.listOf("default"));
System.out.println(res);
if (res.getBinderOrThrow("current").get("default") != null && res.getBinderOrThrow("current").get("default").equals(storageValue) && res.getBinderOrThrow("pending").get("default") != null && res.getBinderOrThrow("pending").getBinder("default").size() == 0) {
break;
}
Thread.sleep(10);
}
HashId newStorageValue = HashId.createRandom();
quorumClients.forEach(c -> {
for (int i = 0; i < c.size(); i++) {
int finalI = i;
Do.inParallel(() -> {
try {
// c.getClient(finalI).command("ubotUpdateStorage","executableContractId", executableContract.getId(),"storageName","default","fromValue",oldStorageValue,"toValue", newStorageValue);
c.getClient(finalI).command("ubotUpdateStorage", "requestId", finalRequestId, "storageName", "default", "toValue", newStorageValue);
} catch (IOException e) {
e.printStackTrace();
}
});
}
});
while (true) {
Binder res = client.command("ubotGetStorage", "requestId", finalRequestId, "storageNames", Do.listOf("default"));
System.out.println(res);
if (res.getBinderOrThrow("current").get("default") != null && res.getBinderOrThrow("current").get("default").equals(newStorageValue) && res.getBinderOrThrow("pending").get("default") != null && res.getBinderOrThrow("pending").getBinder("default").size() == 0) {
break;
}
Thread.sleep(10);
}
quorumClients.forEach(c -> {
for (int i = 0; i < c.size(); i++) {
int finalI = i;
Do.inParallel(() -> {
try {
c.getClient(finalI).command("ubotCloseSession", "requestId", finalRequestId, "finished", true);
} catch (IOException e) {
e.printStackTrace();
}
});
}
});
AsyncEvent readyEvent2 = new AsyncEvent();
AtomicInteger readyCounter2 = new AtomicInteger();
for (int i = 0; i < client.size(); i++) {
int finalI = i;
Do.inParallel(() -> {
while (true) {
Binder res = client.getClient(finalI).command("ubotGetSession", "requestId", finalRequestId);
System.out.println(client.getClient(finalI).getNodeNumber() + " " + res);
Thread.sleep(500);
if (res.getBinder("session").isEmpty()) {
if (readyCounter2.incrementAndGet() == client.size()) {
readyEvent2.fire();
}
break;
}
}
}).failure(new DeferredResult.Handler() {
@Override
public void handle(Object data) {
System.out.println("ERR: " + data);
}
});
}
readyEvent2.await();
}
}
Aggregations