Search in sources :

Example 21 with HashId

use of com.icodici.universa.HashId in project universa by UniversaBlockchain.

the class SqliteLedgerTest method recordExpiration.

@Test
public void recordExpiration() throws Exception {
    // todo: expired can't be get - it should be dropped by the database
    HashId hashId = HashId.createRandom();
    StateRecord r = ledger.findOrCreate(hashId);
    long recordId = r.getRecordId();
    ZonedDateTime inFuture = ZonedDateTime.now().plusHours(2);
    r.setExpiresAt(inFuture);
    StateRecord r1 = ledger.getRecord(hashId);
    assertNotEquals(r1.getExpiresAt(), inFuture);
    r.save();
    r1 = ledger.getRecord(hashId);
    assertAlmostSame(r.getExpiresAt(), r1.getExpiresAt());
    r.setExpiresAt(ZonedDateTime.now().minusHours(1));
    r.save();
    r1 = ledger.getRecord(hashId);
    assertNull(r1);
}
Also used : HashId(com.icodici.universa.HashId) ZonedDateTime(java.time.ZonedDateTime) Test(org.junit.Test)

Example 22 with HashId

use of com.icodici.universa.HashId in project universa by UniversaBlockchain.

the class SqliteLedgerTest method ledgerBenchmark.

// @Test
public void ledgerBenchmark() throws Exception {
    ExecutorService es = Executors.newCachedThreadPool();
    // ExecutorService es = Executors.newSingleThreadExecutor();
    List<Future<?>> ff = new ArrayList<>();
    long t = StopWatch.measure(true, () -> {
        for (int n = 0; n < 4; n++) {
            final int x = n;
            ff.add(es.submit(() -> {
                HashId[] ids = new HashId[10000];
                for (int i = 0; i < ids.length; i++) ids[i] = HashId.createRandom();
                System.out.println(x);
                StopWatch.measure(true, () -> {
                    for (HashId i : ids) {
                        try {
                            ledger.findOrCreate(i);
                        } catch (Exception e) {
                            e.printStackTrace();
                            fail(e.getMessage());
                        }
                    }
                });
                System.out.println("end-" + x);
                return null;
            }));
        }
        ff.forEach(f -> {
            try {
                f.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
        System.out.println("total");
    });
    System.out.println("TPS: " + (4.0 * 10000 * 1000 / t));
    System.out.println("" + ledger.getDb().queryOne("SELECT count(*) from ledger"));
}
Also used : HashId(com.icodici.universa.HashId) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 23 with HashId

use of com.icodici.universa.HashId in project universa by UniversaBlockchain.

the class SqliteLedgerTest method checkNegatoveBytesInId.

@Test
public void checkNegatoveBytesInId() throws Exception {
    HashId id = HashId.withDigest(Do.randomNegativeBytes(64));
    StateRecord r1 = ledger.findOrCreate(id);
    r1.setState(ItemState.DECLINED);
    r1.save();
    StateRecord r2 = ledger.getRecord(id);
    assertNotNull(r2);
    assertNotSame(r1, r2);
    assertEquals(r1.getState(), r2.getState());
    ledger.enableCache(true);
    StateRecord r3 = ledger.getRecord(id);
    StateRecord r4 = ledger.getRecord(id);
    assertEquals(r3.toString(), r4.toString());
    // why?
    assertSame(r3, r4);
}
Also used : HashId(com.icodici.universa.HashId) Test(org.junit.Test)

Example 24 with HashId

use of com.icodici.universa.HashId in project universa by UniversaBlockchain.

the class Client method getState.

public ItemResult getState(HashId itemId, Reporter reporter) throws ClientError {
    final ExecutorService pool = Executors.newCachedThreadPool();
    final List<ErrorRecord> errors = new ArrayList<>();
    final AsyncEvent<Void> consensusFound = new AsyncEvent<>();
    final int checkConsensus = getNodes().size() / 3;
    final AtomicInteger nodesLeft = new AtomicInteger(nodes.size());
    return protect(() -> {
        final Map<ItemState, List<ItemResult>> states = new HashMap<>();
        for (int i = 0; i < nodes.size(); i++) {
            final int nn = i;
            pool.submit(() -> {
                for (int retry = 0; retry < 5; retry++) {
                    // reporter.verbose("trying "+reporter+" for node "+nn);
                    try {
                        Client c = getClient(nn);
                        ItemResult r = c.command("getState", "itemId", itemId).getOrThrow("itemResult");
                        r.meta.put("url", c.getNodeNumber());
                        synchronized (states) {
                            List<ItemResult> list = states.get(r.state);
                            if (list == null) {
                                list = new ArrayList();
                                states.put(r.state, list);
                            }
                            list.add(r);
                            if (r.errors.size() > 0)
                                reporter.warning("errors from " + c.getNodeNumber() + ": " + r.errors);
                            break;
                        }
                    } catch (IOException e) {
                    // reporter.warning("can't get answer from node " + nn + ", retry #" + retry + ": " + e);
                    }
                }
                // Now we should check the consensus
                states.forEach((itemState, itemResults) -> {
                    if (itemResults.size() >= checkConsensus)
                        if (itemResults.size() >= checkConsensus) {
                            consensusFound.fire();
                            return;
                        }
                });
                if (nodesLeft.decrementAndGet() < 1)
                    consensusFound.fire();
            });
        }
        consensusFound.await(5000);
        pool.shutdownNow();
        final ItemResult[] consensus = new ItemResult[1];
        states.forEach((itemState, itemResults) -> {
            if (itemResults.size() >= checkConsensus)
                consensus[0] = itemResults.get(0);
        });
        if (consensus[0] != null)
            reporter.message("State consensus found:" + consensus[0]);
        else {
            reporter.warning("no consensus found " + states.size());
        }
        if (states.size() > 1) {
            states.entrySet().stream().sorted(Comparator.comparingInt(o -> o.getValue().size())).forEach(kv -> {
                List<ItemResult> itemResults = kv.getValue();
                reporter.message("" + kv.getKey() + ": " + itemResults.size() + ": " + itemResults.stream().map(x -> x.meta.getStringOrThrow("url")).collect(Collectors.toSet()));
            });
        }
        return consensus[0];
    });
}
Also used : BiDeserializer(net.sergeych.biserializer.BiDeserializer) HttpURLConnection(java.net.HttpURLConnection) NonNull(org.checkerframework.checker.nullness.qual.NonNull) java.util(java.util) URL(java.net.URL) Binder(net.sergeych.tools.Binder) ErrorRecord(com.icodici.universa.ErrorRecord) PublicKey(com.icodici.crypto.PublicKey) Contract(com.icodici.universa.contract.Contract) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncEvent(net.sergeych.tools.AsyncEvent) ExecutorService(java.util.concurrent.ExecutorService) ItemResult(com.icodici.universa.node.ItemResult) Reporter(net.sergeych.tools.Reporter) PrivateKey(com.icodici.crypto.PrivateKey) com.icodici.universa.node2(com.icodici.universa.node2) Do(net.sergeych.tools.Do) IOException(java.io.IOException) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ItemState(com.icodici.universa.node.ItemState) Executors(java.util.concurrent.Executors) EncryptionError(com.icodici.crypto.EncryptionError) Approvable(com.icodici.universa.Approvable) Parcel(com.icodici.universa.contract.Parcel) HashId(com.icodici.universa.HashId) DefaultBiMapper(net.sergeych.biserializer.DefaultBiMapper) Boss(net.sergeych.boss.Boss) IOException(java.io.IOException) AsyncEvent(net.sergeych.tools.AsyncEvent) ItemResult(com.icodici.universa.node.ItemResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ItemState(com.icodici.universa.node.ItemState) ExecutorService(java.util.concurrent.ExecutorService) ErrorRecord(com.icodici.universa.ErrorRecord)

Example 25 with HashId

use of com.icodici.universa.HashId in project universa by UniversaBlockchain.

the class ItemResyncNotification method readFrom.

@Override
protected void readFrom(Boss.Reader br) throws IOException {
    super.readFrom(br);
    Map<String, Object> packingMap = br.readMap();
    for (String s : packingMap.keySet()) {
        HashId hid = HashId.withDigest(s);
        ItemState state = ItemState.values()[(int) packingMap.get(s)];
        itemsToResync.put(hid, state);
    }
}
Also used : HashId(com.icodici.universa.HashId) ItemState(com.icodici.universa.node.ItemState)

Aggregations

HashId (com.icodici.universa.HashId)30 Test (org.junit.Test)18 Contract (com.icodici.universa.contract.Contract)6 PrivateKey (com.icodici.crypto.PrivateKey)4 PublicKey (com.icodici.crypto.PublicKey)3 ZonedDateTime (java.time.ZonedDateTime)3 ArrayList (java.util.ArrayList)3 ExecutorService (java.util.concurrent.ExecutorService)3 Binder (net.sergeych.tools.Binder)3 Approvable (com.icodici.universa.Approvable)2 Decimal (com.icodici.universa.Decimal)2 ItemResult (com.icodici.universa.node.ItemResult)2 ItemState (com.icodici.universa.node.ItemState)2 IOException (java.io.IOException)2 ExecutionException (java.util.concurrent.ExecutionException)2 Future (java.util.concurrent.Future)2 EncryptionError (com.icodici.crypto.EncryptionError)1 ErrorRecord (com.icodici.universa.ErrorRecord)1 Parcel (com.icodici.universa.contract.Parcel)1 com.icodici.universa.node2 (com.icodici.universa.node2)1