Search in sources :

Example 6 with ItemResult

use of com.icodici.universa.node.ItemResult in project universa by UniversaBlockchain.

the class CLIMain method doProbe.

private static void doProbe() throws IOException {
    List<String> sources = new ArrayList<String>((List) options.valuesOf("probe"));
    List<String> nonOptions = new ArrayList<String>((List) options.nonOptionArguments());
    for (String opt : nonOptions) {
        sources.addAll(asList(opt.split(",")));
    }
    cleanNonOptionalArguments(sources);
    for (int s = 0; s < sources.size(); s++) {
        String source = sources.get(s);
        ItemResult ir = getClientNetwork().check(source);
    // report("Universa network has reported the state:");
    // report(ir.toString());
    }
    finish();
}
Also used : ItemResult(com.icodici.universa.node.ItemResult)

Example 7 with ItemResult

use of com.icodici.universa.node.ItemResult in project universa by UniversaBlockchain.

the class Client method registerParcel.

public boolean registerParcel(byte[] packed, long millisToWait) throws ClientError {
    Object result = protect(() -> httpClient.command("approveParcel", "packedItem", packed).get("result"));
    if (result instanceof String) {
        System.out.println(">> registerParcel " + result);
    } else {
        if (millisToWait > 0) {
            Instant end = Instant.now().plusMillis(millisToWait);
            try {
                Parcel parcel = Parcel.unpack(packed);
                Node.ParcelProcessingState pState = getParcelProcessingState(parcel.getId());
                while (Instant.now().isBefore(end) && pState.isProcessing()) {
                    System.out.println("parcel state is: " + pState);
                    Thread.currentThread().sleep(100);
                    pState = getParcelProcessingState(parcel.getId());
                }
                System.out.println("parcel state is: " + pState);
                ItemResult lastResult = getState(parcel.getPayloadContract().getId());
                while (Instant.now().isBefore(end) && lastResult.state.isPending()) {
                    Thread.currentThread().sleep(100);
                    lastResult = getState(parcel.getPayloadContract().getId());
                    System.out.println("test: " + lastResult);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Quantiser.QuantiserException e) {
                throw new ClientError(e);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return (boolean) result;
    }
    return false;
}
Also used : ItemResult(com.icodici.universa.node.ItemResult) Parcel(com.icodici.universa.contract.Parcel) Instant(java.time.Instant) IOException(java.io.IOException)

Example 8 with ItemResult

use of com.icodici.universa.node.ItemResult in project universa by UniversaBlockchain.

the class Client method getState.

public ItemResult getState(HashId itemId) throws ClientError {
    return protect(() -> {
        // for (int i = 0; i < nodes.size(); i++) {
        // System.out.println("checking node " + i);
        // ItemResult r = getClient(i).command("getState",
        // "itemId", itemId).getOrThrow("itemResult");
        // System.out.println(">> " + r);
        // }
        Binder result = httpClient.command("getState", "itemId", itemId);
        Object ir = result.getOrThrow("itemResult");
        if (ir instanceof ItemResult)
            return (ItemResult) ir;
        if (ir instanceof String)
            System.out.println(">> " + ir);
        return ItemResult.UNDEFINED;
    });
}
Also used : Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult)

Example 9 with ItemResult

use of com.icodici.universa.node.ItemResult 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 10 with ItemResult

use of com.icodici.universa.node.ItemResult in project universa by UniversaBlockchain.

the class ClientHTTPServer method itemResultOfError.

private ItemResult itemResultOfError(Errors error, String object, String message) {
    Binder binder = new Binder();
    binder.put("state", ItemState.UNDEFINED.name());
    binder.put("haveCopy", false);
    binder.put("createdAt", new Date());
    binder.put("expiresAt", new Date());
    ArrayList<ErrorRecord> errorRecords = new ArrayList<>();
    errorRecords.add(new ErrorRecord(error, object, message));
    binder.put("errors", errorRecords);
    return new ItemResult(binder);
}
Also used : Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult) ArrayList(java.util.ArrayList) Date(java.util.Date) ErrorRecord(com.icodici.universa.ErrorRecord)

Aggregations

ItemResult (com.icodici.universa.node.ItemResult)12 IOException (java.io.IOException)5 Contract (com.icodici.universa.contract.Contract)4 PrivateKey (com.icodici.crypto.PrivateKey)3 Parcel (com.icodici.universa.contract.Parcel)3 Instant (java.time.Instant)3 Binder (net.sergeych.tools.Binder)3 Test (org.junit.Test)3 ErrorRecord (com.icodici.universa.ErrorRecord)2 HashId (com.icodici.universa.HashId)2 KeyRecord (com.icodici.universa.contract.KeyRecord)2 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)2 ConnectException (java.net.ConnectException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 EncryptionError (com.icodici.crypto.EncryptionError)1 PublicKey (com.icodici.crypto.PublicKey)1 Approvable (com.icodici.universa.Approvable)1 ItemState (com.icodici.universa.node.ItemState)1 com.icodici.universa.node2 (com.icodici.universa.node2)1 HttpURLConnection (java.net.HttpURLConnection)1