Search in sources :

Example 6 with Client

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();
}
Also used : HashId(com.icodici.universa.HashId) Reference(com.icodici.universa.contract.Reference) AtomicReference(java.util.concurrent.atomic.AtomicReference) ItemResult(com.icodici.universa.node.ItemResult) KeyAddress(com.icodici.crypto.KeyAddress) Client(com.icodici.universa.node2.network.Client) Contract(com.icodici.universa.contract.Contract) Test(org.junit.Test)

Example 7 with Client

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();
}
Also used : RoleLink(com.icodici.universa.contract.roles.RoleLink) Parcel(com.icodici.universa.contract.Parcel) SlotContract(com.icodici.universa.contract.services.SlotContract) Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult) JSApiChangeNumberPermission(com.icodici.universa.contract.jsapi.permissions.JSApiChangeNumberPermission) JSApiPermission(com.icodici.universa.contract.jsapi.permissions.JSApiPermission) JSApiSplitJoinPermission(com.icodici.universa.contract.jsapi.permissions.JSApiSplitJoinPermission) Contract(com.icodici.universa.contract.Contract) NSmartContract(com.icodici.universa.contract.services.NSmartContract) SlotContract(com.icodici.universa.contract.services.SlotContract) ClientError(com.icodici.universa.node2.network.ClientError) Test(org.junit.Test)

Example 8 with Client

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();
}
Also used : NashornScriptEngineFactory(jdk.nashorn.api.scripting.NashornScriptEngineFactory) JSApiRole(com.icodici.universa.contract.jsapi.roles.JSApiRole) java.util(java.util) JSApiChangeNumberPermission(com.icodici.universa.contract.jsapi.permissions.JSApiChangeNumberPermission) Client(com.icodici.universa.node2.network.Client) Binder(net.sergeych.tools.Binder) SimpleRole(com.icodici.universa.contract.roles.SimpleRole) JSApiStorage(com.icodici.universa.contract.jsapi.storage.JSApiStorage) BigDecimal(java.math.BigDecimal) com.icodici.universa.contract.permissions(com.icodici.universa.contract.permissions) PublicKey(com.icodici.crypto.PublicKey) Contract(com.icodici.universa.contract.Contract) com.icodici.universa.contract.jsapi(com.icodici.universa.contract.jsapi) NSmartContract(com.icodici.universa.contract.services.NSmartContract) ClassFilter(jdk.nashorn.api.scripting.ClassFilter) ContractsService(com.icodici.universa.contract.ContractsService) Before(org.junit.Before) ScriptException(javax.script.ScriptException) ItemResult(com.icodici.universa.node.ItemResult) PrivateKey(com.icodici.crypto.PrivateKey) TestKeys(com.icodici.universa.TestKeys) Files(java.nio.file.Files) InnerContractsService(com.icodici.universa.contract.InnerContractsService) JSApiPermission(com.icodici.universa.contract.jsapi.permissions.JSApiPermission) KeyAddress(com.icodici.crypto.KeyAddress) Do(net.sergeych.tools.Do) StandardOpenOption(java.nio.file.StandardOpenOption) Test(org.junit.Test) IOException(java.io.IOException) ClientError(com.icodici.universa.node2.network.ClientError) Bytes(net.sergeych.utils.Bytes) Field(java.lang.reflect.Field) JSApiSplitJoinPermission(com.icodici.universa.contract.jsapi.permissions.JSApiSplitJoinPermission) ItemState(com.icodici.universa.node.ItemState) File(java.io.File) Base64(net.sergeych.utils.Base64) Parcel(com.icodici.universa.contract.Parcel) HashId(com.icodici.universa.HashId) Ignore(org.junit.Ignore) Invocable(javax.script.Invocable) Paths(java.nio.file.Paths) ScriptEngine(javax.script.ScriptEngine) RoleLink(com.icodici.universa.contract.roles.RoleLink) ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) Assert(org.junit.Assert) SlotContract(com.icodici.universa.contract.services.SlotContract) RoleLink(com.icodici.universa.contract.roles.RoleLink) Parcel(com.icodici.universa.contract.Parcel) SlotContract(com.icodici.universa.contract.services.SlotContract) Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult) JSApiChangeNumberPermission(com.icodici.universa.contract.jsapi.permissions.JSApiChangeNumberPermission) JSApiPermission(com.icodici.universa.contract.jsapi.permissions.JSApiPermission) JSApiSplitJoinPermission(com.icodici.universa.contract.jsapi.permissions.JSApiSplitJoinPermission) Contract(com.icodici.universa.contract.Contract) NSmartContract(com.icodici.universa.contract.services.NSmartContract) SlotContract(com.icodici.universa.contract.services.SlotContract) ClientError(com.icodici.universa.node2.network.ClientError) File(java.io.File) Test(org.junit.Test)

Example 9 with Client

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();
}
Also used : HashId(com.icodici.universa.HashId) Binder(net.sergeych.tools.Binder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReference(java.util.concurrent.atomic.AtomicReference) Client(com.icodici.universa.node2.network.Client) AsyncEvent(net.sergeych.tools.AsyncEvent) Contract(com.icodici.universa.contract.Contract) Test(org.junit.Test)

Example 10 with Client

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();
    }
}
Also used : HashId(com.icodici.universa.HashId) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AsyncEvent(net.sergeych.tools.AsyncEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Binder(net.sergeych.tools.Binder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Client(com.icodici.universa.node2.network.Client) Contract(com.icodici.universa.contract.Contract) DeferredResult(net.sergeych.tools.DeferredResult) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

Client (com.icodici.universa.node2.network.Client)44 Test (org.junit.Test)37 PrivateKey (com.icodici.crypto.PrivateKey)30 ItemResult (com.icodici.universa.node.ItemResult)29 Contract (com.icodici.universa.contract.Contract)22 Binder (net.sergeych.tools.Binder)22 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)21 IOException (java.io.IOException)20 HashId (com.icodici.universa.HashId)19 Ignore (org.junit.Ignore)16 KeyAddress (com.icodici.crypto.KeyAddress)15 AsyncEvent (net.sergeych.tools.AsyncEvent)12 PublicKey (com.icodici.crypto.PublicKey)11 AtomicReference (java.util.concurrent.atomic.AtomicReference)11 BigDecimal (java.math.BigDecimal)9 java.util (java.util)9 RoleLink (com.icodici.universa.contract.roles.RoleLink)8 com.icodici.universa.contract (com.icodici.universa.contract)7 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)7 ConnectException (java.net.ConnectException)7