Search in sources :

Example 1 with PrivateKey

use of com.icodici.crypto.PrivateKey in project universa by UniversaBlockchain.

the class MainTest method localNetwork2.

@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));
    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/tu_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.isPending())
                        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) SQLException(java.sql.SQLException) IOException(java.io.IOException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test)

Example 2 with PrivateKey

use of com.icodici.crypto.PrivateKey in project universa by UniversaBlockchain.

the class MainTest method testTransactionUnpack.

@Test
public void testTransactionUnpack() throws Exception {
    testSomeWork(() -> {
        try {
            PrivateKey key = TestKeys.privateKey(3);
            Contract contract = createContract500(key);
            contract.seal();
            byte[] bytes = contract.getPackedTransaction();
            for (int i = 0; i < 20; ++i) TransactionPack.unpack(bytes);
        } catch (Exception e) {
            System.out.println("exception: " + e.toString());
        }
    });
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) SQLException(java.sql.SQLException) IOException(java.io.IOException) Test(org.junit.Test)

Example 3 with PrivateKey

use of com.icodici.crypto.PrivateKey in project universa by UniversaBlockchain.

the class MainTest method networkReconfigurationTestParallel.

@Test
public void networkReconfigurationTestParallel() throws Exception {
    // create 4 nodes from config file. 3 know each other. 4th knows everyone. nobody knows 4th
    List<Main> mm = new ArrayList<>();
    for (int i = 0; i < 4; i++) {
        mm.add(createMain("node" + (i + 1), "_dynamic_test", false));
    }
    // shutdown nodes
    for (Main m : mm) {
        m.shutdown();
    }
    mm.clear();
    // initialize same nodes from db
    List<String> dbUrls = new ArrayList<>();
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t1");
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t2");
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t3");
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t4");
    Random rand = new Random();
    rand.setSeed(new Date().getTime());
    final ArrayList<Integer> clientSleeps = new ArrayList<>();
    final ArrayList<Integer> nodeSleeps = new ArrayList<>();
    for (int i = 0; i < 4; i++) {
        mm.add(createMainFromDb(dbUrls.get(i), false));
        nodeSleeps.add(rand.nextInt(100));
    }
    PrivateKey myKey = TestKeys.privateKey(3);
    final ArrayList<Client> clients = new ArrayList<>();
    final ArrayList<Integer> clientNodes = new ArrayList<>();
    final ArrayList<Contract> contracts = new ArrayList<>();
    final ArrayList<Parcel> parcels = new ArrayList<>();
    final ArrayList<Boolean> contractsApproved = new ArrayList<>();
    for (int i = 0; i < 40; i++) {
        Contract contract = new Contract(myKey);
        contract.seal();
        assertTrue(contract.isOk());
        contracts.add(contract);
        contractsApproved.add(false);
        NodeInfo info = mm.get(rand.nextInt(3)).myInfo;
        clientNodes.add(info.getNumber());
        Client client = new Client(TestKeys.privateKey(i), info, null);
        clients.add(client);
        clientSleeps.add(rand.nextInt(100));
        Parcel parcel = createParcelWithFreshTU(client, contract, Do.listOf(myKey));
        parcels.add(parcel);
    }
    Semaphore semaphore = new Semaphore(-39);
    final AtomicInteger atomicInteger = new AtomicInteger(40);
    for (int i = 0; i < 40; i++) {
        int finalI = i;
        Thread th = new Thread(() -> {
            try {
                // Thread.sleep(clientSleeps.get(finalI));
                Thread.sleep(clientSleeps.get(finalI));
                Contract contract = contracts.get(finalI);
                Client client = clients.get(finalI);
                System.out.println("Register item " + contract.getId().toBase64String() + " @ node #" + clientNodes.get(finalI));
                client.registerParcel(parcels.get(finalI).pack(), 15000);
                ItemResult rr;
                while (true) {
                    rr = client.getState(contract.getId());
                    Thread.currentThread().sleep(50);
                    if (!rr.state.isPending())
                        break;
                }
                assertEquals(rr.state, ItemState.APPROVED);
                semaphore.release();
                atomicInteger.decrementAndGet();
                contractsApproved.set(finalI, true);
            } catch (ClientError clientError) {
                clientError.printStackTrace();
                fail(clientError.getMessage());
            } catch (InterruptedException e) {
                e.printStackTrace();
                fail(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                fail(e.getMessage());
            }
        });
        th.start();
    }
    for (int i = 0; i < 3; i++) {
        int finalI = i;
        Thread th = new Thread(() -> {
            try {
                // Thread.sleep(nodeSleeps.get(finalI));
                Thread.sleep(nodeSleeps.get(finalI));
            } catch (InterruptedException e) {
                e.printStackTrace();
                fail(e.getMessage());
            }
            System.out.println("Adding new node @ node #" + (finalI + 1));
            mm.get(finalI).node.addNode(mm.get(3).myInfo);
            System.out.println("Done new node @ node #" + (finalI + 1));
        });
        th.start();
    }
    if (!semaphore.tryAcquire(15, TimeUnit.SECONDS)) {
        for (int i = 0; i < contractsApproved.size(); i++) {
            if (!contractsApproved.get(i)) {
                System.out.println("Stuck item:" + contracts.get(i).getId().toBase64String());
            }
        }
        System.out.print("Client sleeps: ");
        for (Integer s : clientSleeps) {
            System.out.print(s + ", ");
        }
        System.out.println();
        System.out.print("Node sleeps: ");
        for (Integer s : nodeSleeps) {
            System.out.print(s + ", ");
        }
        System.out.println();
        fail("Items stuck: " + atomicInteger.get());
    }
    for (Main m : mm) {
        m.shutdown();
    }
    System.gc();
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) Semaphore(java.util.concurrent.Semaphore) IOException(java.io.IOException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 4 with PrivateKey

use of com.icodici.crypto.PrivateKey in project universa by UniversaBlockchain.

the class MainTest method checkRealNetwork.

@Test
@Ignore("This test nust be started manually")
public void checkRealNetwork() throws Exception {
    int numThraeds = 8;
    List<PrivateKey> keys = new ArrayList<>();
    for (int j = 0; j < numThraeds; j++) {
        PrivateKey key = new PrivateKey(Do.read("./src/test_contracts/keys/" + j + ".private.unikey"));
        keys.add(key);
    }
    List<Contract> contractsForThreads = new ArrayList<>();
    for (int j = 0; j < numThraeds; j++) {
        PrivateKey key = keys.get(0);
        Contract contract = new Contract(key);
        for (int k = 0; k < 500; k++) {
            Contract nc = new Contract(key);
            nc.seal();
            contract.addNewItems(nc);
        }
        contract.seal();
        contractsForThreads.add(contract);
    }
    List<Thread> threadList = new ArrayList<>();
    long t1 = new Date().getTime();
    for (int i = 0; i < numThraeds; i++) {
        final int ii = i;
        Thread thread = new Thread(() -> {
            PrivateKey clientKey = keys.get(ii);
            Client client = null;
            try {
                client = new Client("http://node-1-sel1.universa.io:8080", clientKey, null);
                Contract c = contractsForThreads.get(ii);
                ItemResult r = client.register(c.getPackedTransaction());
                while (true) {
                    r = client.getState(c.getId());
                    System.out.println("-->? " + r);
                    Thread.currentThread().sleep(50);
                    if (!r.state.isPending())
                        break;
                }
            } catch (ClientError clientError) {
                clientError.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.setName("thread register: " + i);
        threadList.add(thread);
        thread.start();
    }
    for (Thread thread : threadList) thread.join();
    long t2 = new Date().getTime();
    long multiTime = t2 - t1;
    System.out.println("time: " + multiTime + "ms");
// r = client.getState(c.getId());
// assertEquals(ItemState.UNDEFINED, r.state);
// System.out.println(":: " + r);
// 
// LogPrinter.showDebug(true);
// //        r = client.register(c.getLastSealedBinary());
// System.out.println(r);
// 
// Client client = new Client(myKey, );
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) IOException(java.io.IOException) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 5 with PrivateKey

use of com.icodici.crypto.PrivateKey in project universa by UniversaBlockchain.

the class MainTest method localNetwork3.

@Test
public void localNetwork3() 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);
    assertEquals("http://localhost:8080", main.myInfo.internalUrlString());
    assertEquals("http://localhost:8080", main.myInfo.publicUrlString());
    PrivateKey myKey = new PrivateKey(Do.read("./src/test_contracts/keys/tu_key.private.unikey"));
    Set<PrivateKey> fromPrivateKeys = new HashSet<>();
    fromPrivateKeys.add(myKey);
    // Client client = new Client(myKey, main.myInfo, null);
    final long CONTRACTS_PER_THREAD = 10;
    final long THREADS_COUNT = 4;
    LogPrinter.showDebug(true);
    class TestRunnable implements Runnable {

        public int threadNum = 0;

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

        Map<HashId, Parcel> 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());
                Parcel parcel = createParcelWithFreshTU(client, testContract, Do.listOf(myKey));
                contractList.add(parcel);
                contractHashesMap.put(parcel.getId(), parcel);
            }
        }

        private void sendContractsToRegister() throws Exception {
            for (int i = 0; i < contractList.size(); ++i) {
                Parcel parcel = contractList.get(i);
                client.registerParcel(parcel.pack());
            }
        }

        private void waitForContracts() throws Exception {
            while (contractHashesMap.size() > 0) {
                Thread.currentThread().sleep(100);
                for (Parcel p : contractHashesMap.values()) {
                    ItemResult itemResult = client.getState(p.getPayloadContract().getId());
                    if (!itemResult.state.isPending())
                        contractHashesMap.remove(p.getId());
                }
            }
        }

        @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 : PrivateKey(com.icodici.crypto.PrivateKey) SQLException(java.sql.SQLException) IOException(java.io.IOException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test)

Aggregations

PrivateKey (com.icodici.crypto.PrivateKey)168 Test (org.junit.Test)122 PublicKey (com.icodici.crypto.PublicKey)76 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)29 Contract (com.icodici.universa.contract.Contract)24 Binder (net.sergeych.tools.Binder)22 IOException (java.io.IOException)16 HashSet (java.util.HashSet)14 ListRole (com.icodici.universa.contract.roles.ListRole)12 SQLException (java.sql.SQLException)11 Ignore (org.junit.Ignore)9 File (java.io.File)8 KeyAddress (com.icodici.crypto.KeyAddress)7 KeyRecord (com.icodici.universa.contract.KeyRecord)7 Role (com.icodici.universa.contract.roles.Role)7 Semaphore (java.util.concurrent.Semaphore)7 RoleLink (com.icodici.universa.contract.roles.RoleLink)5 TimeoutException (java.util.concurrent.TimeoutException)5 Decimal (com.icodici.universa.Decimal)4 HashId (com.icodici.universa.HashId)4