Search in sources :

Example 11 with Client

use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.

the class Research2Test method localNetwork2.

@Ignore
@Test
public void localNetwork2() throws Exception {
    List<Main> mm = new ArrayList<>();
    for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false));
    mm.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true));
    Main main = mm.get(0);
    assertEquals("http://localhost:8080", main.myInfo.internalUrlString());
    assertEquals("http://localhost:8080", main.myInfo.publicUrlString());
    PrivateKey myKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey"));
    // Client client = new Client(myKey, main.myInfo, null);
    final long CONTRACTS_PER_THREAD = 60;
    final long THREADS_COUNT = 4;
    class TestRunnable implements Runnable {

        public int threadNum = 0;

        List<Contract> contractList = new ArrayList<>();

        Map<HashId, Contract> contractHashesMap = new ConcurrentHashMap<>();

        Client client = null;

        public void prepareClient() {
            try {
                client = new Client(myKey, main.myInfo, null);
            } catch (Exception e) {
                System.out.println("prepareClient exception: " + e.toString());
            }
        }

        public void prepareContracts() throws Exception {
            contractList = new ArrayList<>();
            for (int iContract = 0; iContract < CONTRACTS_PER_THREAD; ++iContract) {
                Contract testContract = new Contract(myKey);
                for (int i = 0; i < 10; i++) {
                    Contract nc = new Contract(myKey);
                    nc.seal();
                    testContract.addNewItems(nc);
                }
                testContract.seal();
                assertTrue(testContract.isOk());
                contractList.add(testContract);
                contractHashesMap.put(testContract.getId(), testContract);
            }
        }

        private void sendContractsToRegister() throws Exception {
            for (int i = 0; i < contractList.size(); ++i) {
                Contract contract = contractList.get(i);
                client.register(contract.getPackedTransaction());
            }
        }

        private void waitForContracts() throws Exception {
            while (contractHashesMap.size() > 0) {
                Thread.currentThread().sleep(300);
                for (HashId id : contractHashesMap.keySet()) {
                    ItemResult itemResult = client.getState(id);
                    if (itemResult.state == ItemState.APPROVED)
                        contractHashesMap.remove(id);
                    else
                        break;
                }
            }
        }

        @Override
        public void run() {
            try {
                sendContractsToRegister();
                waitForContracts();
            } catch (Exception e) {
                System.out.println("runnable exception: " + e.toString());
            }
        }
    }
    System.out.println("singlethread test prepare...");
    TestRunnable runnableSingle = new TestRunnable();
    Thread threadSingle = new Thread(() -> {
        runnableSingle.threadNum = 0;
        runnableSingle.run();
    });
    runnableSingle.prepareClient();
    runnableSingle.prepareContracts();
    System.out.println("singlethread test start...");
    long t1 = new Date().getTime();
    threadSingle.start();
    threadSingle.join();
    long t2 = new Date().getTime();
    long dt = t2 - t1;
    long singleThreadTime = dt;
    System.out.println("singlethread test done!");
    System.out.println("multithread test prepare...");
    List<Thread> threadsList = new ArrayList<>();
    List<Thread> threadsPrepareList = new ArrayList<>();
    List<TestRunnable> runnableList = new ArrayList<>();
    for (int iThread = 0; iThread < THREADS_COUNT; ++iThread) {
        TestRunnable runnableMultithread = new TestRunnable();
        final int threadNum = iThread + 1;
        Thread threadMultiThread = new Thread(() -> {
            runnableMultithread.threadNum = threadNum;
            runnableMultithread.run();
        });
        Thread threadPrepareMultiThread = new Thread(() -> {
            try {
                runnableMultithread.prepareContracts();
            } catch (Exception e) {
                System.out.println("prepare exception: " + e.toString());
            }
        });
        runnableMultithread.prepareClient();
        threadsList.add(threadMultiThread);
        threadsPrepareList.add(threadPrepareMultiThread);
        runnableList.add(runnableMultithread);
    }
    for (Thread thread : threadsPrepareList) thread.start();
    for (Thread thread : threadsPrepareList) thread.join();
    Thread.sleep(500);
    System.out.println("multithread test start...");
    t1 = new Date().getTime();
    for (Thread thread : threadsList) thread.start();
    for (Thread thread : threadsList) thread.join();
    t2 = new Date().getTime();
    dt = t2 - t1;
    long multiThreadTime = dt;
    System.out.println("multithread test done!");
    Double tpsSingleThread = (double) CONTRACTS_PER_THREAD / (double) singleThreadTime * 1000.0;
    Double tpsMultiThread = (double) CONTRACTS_PER_THREAD * (double) THREADS_COUNT / (double) multiThreadTime * 1000.0;
    Double boostRate = tpsMultiThread / tpsSingleThread;
    System.out.println("\n === total ===");
    System.out.println("singleThread: " + (CONTRACTS_PER_THREAD) + " for " + singleThreadTime + "ms, tps=" + String.format("%.2f", tpsSingleThread));
    System.out.println("multiThread(N=" + THREADS_COUNT + "): " + (CONTRACTS_PER_THREAD * THREADS_COUNT) + " for " + multiThreadTime + "ms, tps=" + String.format("%.2f", tpsMultiThread));
    System.out.println("boostRate: " + String.format("%.2f", boostRate));
    System.out.println("\n");
    mm.forEach(x -> x.shutdown());
}
Also used : HashId(com.icodici.universa.HashId) PrivateKey(com.icodici.crypto.PrivateKey) IOException(java.io.IOException) ItemResult(com.icodici.universa.node.ItemResult) Client(com.icodici.universa.node2.network.Client) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 12 with Client

use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.

the class Research2Test method researchPaidOperation.

@Ignore
@Test
public void researchPaidOperation() throws Exception {
    List<Main> mm = new ArrayList<>();
    for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false));
    Main main = mm.get(0);
    PrivateKey myKey = TestKeys.privateKey(0);
    // System.out.println("wait for sanitation...");
    // Thread.sleep(9000);
    Client client = new Client(myKey, main.myInfo, null);
    System.out.println("\n\n\n\n\n\n\n\n === start ===\n");
    // create and register U contract
    mm.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true));
    Contract uContract = InnerContractsService.createFreshU(9000, new HashSet<>(Arrays.asList(myKey.getPublicKey())));
    uContract.seal();
    ItemResult itemResult = client.register(uContract.getPackedTransaction(), 5000);
    System.out.println("register uContract: " + itemResult);
    assertEquals(ItemState.APPROVED, itemResult.state);
    mm.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(false));
    Contract payment = uContract.createRevision(myKey);
    payment.getStateData().set("transaction_units", 8900);
    payment.seal();
    Contract testPayload = new Contract(myKey);
    testPayload.seal();
    Parcel testParcel = new Parcel(testPayload.getTransactionPack(), payment.getTransactionPack());
    PaidOperation paidOperation = new PaidOperation(payment.getTransactionPack(), "test_operation", new Binder("field1", "value1"));
    // mm.forEach(m -> {m.node.verboseLevel = DatagramAdapter.VerboseLevel.BASE;});
    // mm.get(3).node.verboseLevel = DatagramAdapter.VerboseLevel.BASE;
    System.out.println("\nregister... paymentId=" + paidOperation.getPaymentContract().getId() + ", operationId=" + paidOperation.getId());
    ItemResult operationResult = client.registerPaidOperationWithState(paidOperation.pack(), 10000);
    System.out.println("operationResult: " + operationResult);
    // client.registerParcel(testParcel.pack());
    System.out.println("payment state: " + client.getState(payment.getId()));
    System.out.println("uContract state: " + client.getState(uContract.getId()));
    System.out.println("\n === done ===\n\n\n\n\n\n\n\n\n");
    mm.forEach(x -> x.shutdown());
}
Also used : Binder(net.sergeych.tools.Binder) PrivateKey(com.icodici.crypto.PrivateKey) ItemResult(com.icodici.universa.node.ItemResult) Client(com.icodici.universa.node2.network.Client) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 13 with Client

use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.

the class ResearchTest method createNodeClient.

private static void createNodeClient() throws Exception {
    // List<Main> mm = new ArrayList<>();
    // for (int i = 0; i < 4; i++)
    // mm.add(createMain("node" + (i + 1), false));
    // 
    // Thread.sleep(2000);
    clients = new ArrayList<>();
    for (int i = 0; i < 10; ++i) {
        int n = i + 1;
        String nodeUrl = "http://node-" + n + "-pro.utoken.io:8080";
        PrivateKey clientKey = TestKeys.privateKey(i);
        Client client = new Client(nodeUrl, clientKey, null, false);
        clients.add(client);
    }
    nodeClient = clients.get(0);
    Thread.sleep(100);
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) Client(com.icodici.universa.node2.network.Client)

Example 14 with Client

use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.

the class UBotExecutionTest method connectToUbot.

@Test
public void connectToUbot() throws Exception {
    Client client = new Client("universa.pro", null, TestKeys.privateKey(0));
    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);
    Contract executableContract = new Contract(TestKeys.privateKey(1));
    executableContract.getStateData().put("cloud_methods", Binder.of("getRandom", Binder.of("pool", Binder.of("size", 31), "quorum", Binder.of("size", 31)), "readRandom", Binder.of("pool", Binder.of("size", 31), "quorum", Binder.of("size", 31))));
    executableContract.getStateData().put("js", new String(Do.read("./src/ubot_scripts/random.js")));
    executableContract.seal();
    assertEquals(client.register(executableContract.getPackedTransaction(), 10000).state, ItemState.APPROVED);
    final int ATTEMPTS = 3;
    for (int i = 0; i < ATTEMPTS; i++) {
        u = u.createRevision(TestKeys.privateKey(1));
        u.getStateData().put("transaction_units", u.getStateData().getIntOrThrow("transaction_units") - 100);
        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.executeCloudMethod(requestContract.getPackedTransaction(), u.getPackedTransaction(), true, 0.3f));
        requestContract = new Contract(TestKeys.privateKey(2));
        requestContract.getStateData().put("executable_contract_id", executableContract.getId());
        requestContract.getStateData().put("method_name", "readRandom");
        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);
        u = u.createRevision(TestKeys.privateKey(1));
        u.getStateData().put("transaction_units", u.getStateData().getIntOrThrow("transaction_units") - 100);
        u.seal();
        System.out.println(client.executeCloudMethod(requestContract.getPackedTransaction(), u.getPackedTransaction(), true, 0.3f));
    }
}
Also used : Client(com.icodici.universa.node2.network.Client) BasicHttpClient(com.icodici.universa.node2.network.BasicHttpClient) Contract(com.icodici.universa.contract.Contract) Test(org.junit.Test)

Example 15 with Client

use of com.icodici.universa.node2.network.Client in project universa by UniversaBlockchain.

the class UBotSessionsTest method unloadSessionFromMem.

@Ignore
@Test
public void unloadSessionFromMem() throws Exception {
    TestSpace ts = prepareTestSpace();
    // ts.nodes.forEach(m->m.node.setVerboseLevel(BASE));
    int quorumSize = 1;
    int poolSize = 1;
    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.seal();
    ts.node.node.registerItem(executableContract);
    ItemResult ir = ts.node.node.waitItem(executableContract.getId(), 10000);
    assertEquals(ir.state, ItemState.APPROVED);
    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));
    requestContract.seal();
    requestContract.getTransactionPack().addReferencedItem(executableContract);
    System.out.println(ts.client.command("ubotCreateSession", "packedRequest", requestContract.getPackedTransaction()));
    Client ubotClient = null;
    while (true) {
        Thread.sleep(100);
        Binder res = ts.client.command("ubotGetSession", "requestId", requestContract.getId());
        if (res.get("session") != null && res.getBinderOrThrow("session").get("state") == null)
            continue;
        if (res.get("session") != null && res.getBinderOrThrow("session").getString("state").equals("OPERATIONAL")) {
            List<Integer> sessionPool = res.getBinderOrThrow("session").getListOrThrow("sessionPool");
            System.out.println("sessionPool: " + sessionPool);
            ubotClient = new Client("./src/test_node_config_v2/test_node_config_v2.json", null, ubotKeys.get(sessionPool.get(0)));
            break;
        }
    }
    HashId storageValue = HashId.createRandom();
    System.out.println("storageValue: " + storageValue);
    for (int c = 0; c < ubotClient.size(); ++c) ubotClient.getClient(c).command("ubotUpdateStorage", "executableContractId", executableContract.getId(), "storageName", "default", "toValue", storageValue);
    while (true) {
        Thread.sleep(100);
        Binder res = ubotClient.command("ubotGetStorage", "executableContractId", executableContract.getId(), "storageNames", Do.listOf("default"));
        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;
        }
    }
    Field privateField = Node.class.getDeclaredField("ubotSessionProcessors");
    privateField.setAccessible(true);
    ConcurrentHashMap<HashId, Node.UBotSessionProcessor> ubotSessionProcessors = (ConcurrentHashMap<HashId, Node.UBotSessionProcessor>) privateField.get(ts.node.node);
    System.out.println("ubotSessionProcessors count: " + ubotSessionProcessors.size());
    assertEquals(1, ubotSessionProcessors.size());
    while (true) {
        Thread.sleep(2000);
        System.out.println("wait for unload ubot processors... ubotSessionProcessors.size = " + ubotSessionProcessors.size());
        if (ubotSessionProcessors.size() == 0)
            break;
    }
    while (true) {
        Thread.sleep(1000);
        Binder res = ubotClient.command("ubotGetStorage", "executableContractId", executableContract.getId(), "storageNames", Do.listOf("default"));
        System.out.println("res: " + 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;
        }
    }
    HashId newStorageValue = HashId.createRandom();
    System.out.println("newStorageValue: " + newStorageValue);
    for (int c = 0; c < ubotClient.size(); ++c) ubotClient.getClient(c).command("ubotUpdateStorage", "executableContractId", executableContract.getId(), "storageName", "default", "toValue", newStorageValue);
    while (true) {
        Thread.sleep(100);
        Binder res = ubotClient.command("ubotGetStorage", "executableContractId", executableContract.getId(), "storageNames", Do.listOf("default"));
        if (res.getBinderOrThrow("current").get("default") != null && res.getBinderOrThrow("current").get("default").equals(newStorageValue) && res.getBinderOrThrow("pending").getBinder("default").size() == 0) {
            break;
        }
    }
    assertEquals(1, ubotSessionProcessors.size());
    ts.shutdown();
}
Also used : HashId(com.icodici.universa.HashId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Binder(net.sergeych.tools.Binder) Field(java.lang.reflect.Field) ItemResult(com.icodici.universa.node.ItemResult) Client(com.icodici.universa.node2.network.Client) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) 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