Search in sources :

Example 1 with ErrorRecord

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

the class ContractTest method checkSealingRootContract.

@Test
public void checkSealingRootContract() throws Exception {
    Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml");
    c.addSignerKeyFromFile(rootPath + "_xer0yfe2nn1xthc.private.unikey");
    c.check();
    c.traceErrors();
    assertTrue(c.check());
    byte[] sealed = c.seal();
    // Bytes.dump(sealed);
    // System.out.println(sealed.length);
    Contract c2 = new Contract(sealed);
    assertProperSimpleRootContract(c2);
    boolean ok = c2.check();
    List<ErrorRecord> errors = c2.getErrors();
    if (errors.isEmpty()) {
        assertTrue(ok);
        assertTrue(c.isOk());
    } else {
        for (ErrorRecord e : errors) {
            System.out.println(e);
            fail("errors in contract");
        }
    }
    assertTrue(c.check());
}
Also used : ErrorRecord(com.icodici.universa.ErrorRecord) Test(org.junit.Test)

Example 2 with ErrorRecord

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

the class PermissionsTest method changeOwner.

@Test
public void changeOwner() throws Exception {
    Contract c = Contract.fromDslFile(ROOT_CONTRACT);
    c.addSignerKeyFromFile(PRIVATE_KEY_PATH);
    c.setOwnerKey(ownerKey1);
    assertThat(c.getPermissions().getFirst("change_owner").getRole(), is(instanceOf(RoleLink.class)));
    assertTrue(c.getPermissions().getFirst("change_owner").getRole().isAllowedForKeys(new HashSet(Do.listOf(ownerKey1))));
    // System.out.println("Owner now :" + c.getOwner());
    // System.out.println("change owner permission :" + c.getPermissions().get("change_owner"));
    c.seal();
    c.check();
    c.traceErrors();
    assertTrue(c.check());
    assertEquals(c, ((RoleLink) c.getPermissions().getFirst("change_owner").getRole()).getContract());
    Role cOwner = c.getOwner();
    assertTrue(cOwner.isAllowedForKeys(new HashSet<>(Do.listOf(ownerKey1))));
    assertTrue(!cOwner.isAllowedForKeys(new HashSet<>(Do.listOf(ownerKey2))));
    // Bad contract change: owner has no right to change owner ;)
    Contract c1 = c.createRevision(TestKeys.privateKey(0));
    c1.setOwnerKey(ownerKey2);
    assertNotEquals(c.getOwner(), c1.getOwner());
    c1.seal();
    c1.check();
    c1.traceErrors();
    assertEquals(1, c1.getErrors().size());
    ErrorRecord error = c1.getErrors().get(0);
    assertEquals(Errors.FORBIDDEN, error.getError());
    // good contract change: creator is an owner
    Contract c2 = c.createRevision(TestKeys.privateKey(0), ownerKey1);
    assertEquals(c, ((RoleLink) c.getPermissions().getFirst("change_owner").getRole()).getContract());
    // System.out.println("c owner   : "+c.getRole("owner"));
    // System.out.println("c2 creator: "+c2.getRole("creator"));
    assertEquals(c.getOwner(), ((RoleLink) c.getPermissions().getFirst("change_owner").getRole()).getRole());
    assertEquals(c2, ((RoleLink) c2.getPermissions().getFirst("change_owner").getRole()).getContract());
    assertEquals(c, ((RoleLink) c.getPermissions().getFirst("change_owner").getRole()).getContract());
    c2.setOwnerKey(ownerKey3);
    assertNotEquals(c.getOwner(), c2.getOwner());
    assertEquals(c.getOwner(), ((RoleLink) c.getPermissions().getFirst("change_owner").getRole()).getRole());
    sealCheckTrace(c2, true);
}
Also used : ListRole(com.icodici.universa.contract.roles.ListRole) SimpleRole(com.icodici.universa.contract.roles.SimpleRole) Role(com.icodici.universa.contract.roles.Role) HashSet(java.util.HashSet) ErrorRecord(com.icodici.universa.ErrorRecord) Test(org.junit.Test)

Example 3 with ErrorRecord

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

the class PermissionsTest method revokeWithReference.

@Test
public void revokeWithReference() throws Exception {
    Set<PrivateKey> stepaPrivateKeys = new HashSet<>();
    stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey")));
    Set<PublicKey> stepaPublicKeys = new HashSet<>();
    for (PrivateKey pk : stepaPrivateKeys) {
        stepaPublicKeys.add(pk.getPublicKey());
    }
    Set<String> references = new HashSet<>();
    references.add("certification_contract");
    Contract c = Contract.fromDslFile(rootPath + "NotaryWithReferenceDSLTemplate.yml");
    c.addSignerKeyFromFile(PRIVATE_KEY_PATH);
    Role r = c.getPermissions().getFirst("revoke").getRole();
    assertThat(r, is(instanceOf(ListRole.class)));
    assertFalse(r.isAllowedFor(stepaPublicKeys, null));
    assertTrue(r.isAllowedFor(stepaPublicKeys, references));
    System.out.println("revoke permission :" + c.getPermissions().get("revoke"));
    c.seal();
    c.check();
    c.traceErrors();
    assertTrue(c.isOk());
    assertEquals(c, (c.getPermissions().getFirst("revoke").getRole()).getContract());
    // Bad contract change: owner has no right to change owner ;)
    Contract c1 = c.createRevision(TestKeys.privateKey(0));
    c1.setOwnerKey(ownerKey2);
    assertNotEquals(c.getOwner(), c1.getOwner());
    c1.seal();
    c1.check();
    c1.traceErrors();
    assertEquals(1, c1.getErrors().size());
    ErrorRecord error = c1.getErrors().get(0);
    assertEquals(Errors.FORBIDDEN, error.getError());
    // bad contract change: good key but bad reference
    Contract c2 = ContractsService.createRevocation(c, stepaPrivateKeys.iterator().next());
    assertEquals(c2.getRevoking().get(0), c2.getRevoking().get(0).getPermissions().getFirst("revoke").getRole().getContract());
    c2.seal();
    c2.check();
    c2.traceErrors();
    assertEquals(1, c2.getErrors().size());
    error = c2.getErrors().get(0);
    assertEquals(Errors.FORBIDDEN, error.getError());
    // good contract change: creator is an owner
    Contract c3 = ContractsService.createRevocation(c, stepaPrivateKeys.iterator().next());
    Reference ref = new Reference();
    ref.name = "certification_contract";
    ref.type = Reference.TYPE_EXISTING;
    ref.addMatchingItem(new Contract());
    c3.getRevoking().get(0).getReferences().put(ref.name, ref);
    // assertEquals(c3.getRevoking().get(0), c3.getPermissions().getFirst("revoke").getRole().getContract());
    System.out.println("-------------");
    sealCheckTrace(c3, true);
}
Also used : ListRole(com.icodici.universa.contract.roles.ListRole) SimpleRole(com.icodici.universa.contract.roles.SimpleRole) Role(com.icodici.universa.contract.roles.Role) PrivateKey(com.icodici.crypto.PrivateKey) PublicKey(com.icodici.crypto.PublicKey) HashSet(java.util.HashSet) ErrorRecord(com.icodici.universa.ErrorRecord) Test(org.junit.Test)

Example 4 with ErrorRecord

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

the class BasicHttpClient method command.

/**
 * Execute a command over the authenticated and encrypted connection. In the case of network errors, restarts the
 * command.
 *
 * @param name   command name
 * @param params command params
 *
 * @return decrypted command answer
 *
 * @throws IOException if the commadn can't be executed after several retries or the remote side reports error.
 */
public Binder command(String name, Binder params) throws IOException {
    synchronized (this) {
        if (session == null || session.getSessionKey() == null)
            throw new IllegalStateException("Session does not created or session key is not got yet.");
        Binder call = Binder.fromKeysValues("command", name, "params", params);
        for (int i = 0; i < DEFAULT_RECONNECT_TIMES; i++) {
            ErrorRecord er = null;
            try {
                Answer a = requestOrThrow("command", "command", "command", "params", session.getSessionKey().encrypt(Boss.pack(call)), "session_id", session.getSessionId());
                Binder data = Boss.unpack(session.getSessionKey().decrypt(a.data.getBinaryOrThrow("result")));
                Binder result = data.getBinder("result", null);
                if (result != null)
                    return result;
                System.out.println("result: " + result);
                er = (ErrorRecord) data.get("error");
                if (er == null)
                    er = new ErrorRecord(Errors.FAILURE, "", "unprocessablereply");
            } catch (EndpointException e) {
                // this is not good = we'd better pass it in the encoded block
                ErrorRecord r = e.getFirstError();
                if (r.getError() == Errors.COMMAND_FAILED)
                    throw e;
                System.err.println(r);
            } catch (SocketTimeoutException e) {
                // e.printStackTrace();
                System.err.println("Socket timeout while executing command " + name);
                log.d("Socket timeout while executing command " + name + ": " + e);
            } catch (ConnectException e) {
                // e.printStackTrace();
                System.err.println("Connection refused while executing command " + name);
                log.d("Connection refused while executing command " + name + ": " + e);
            } catch (IOException e) {
                e.printStackTrace();
                log.d("error executing command " + name + ": " + e);
            }
            // if we get here with error, we need to throw it.
            if (er != null)
                throw new CommandFailedException(er);
            // otherwise it is an recoverable error and we must retry
            log.d("repeating command " + name + ", attempt " + (i + 1));
            try {
                Thread.sleep(i * 3 * 100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            restart();
        }
        throw new IOException("Failed to execute command " + name);
    }
}
Also used : Binder(net.sergeych.tools.Binder) IOException(java.io.IOException) ErrorRecord(com.icodici.universa.ErrorRecord)

Example 5 with ErrorRecord

use of com.icodici.universa.ErrorRecord 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)

Aggregations

ErrorRecord (com.icodici.universa.ErrorRecord)8 Test (org.junit.Test)5 PrivateKey (com.icodici.crypto.PrivateKey)3 PublicKey (com.icodici.crypto.PublicKey)3 ListRole (com.icodici.universa.contract.roles.ListRole)3 Role (com.icodici.universa.contract.roles.Role)3 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)3 HashSet (java.util.HashSet)3 Binder (net.sergeych.tools.Binder)3 ItemResult (com.icodici.universa.node.ItemResult)2 IOException (java.io.IOException)2 EncryptionError (com.icodici.crypto.EncryptionError)1 Approvable (com.icodici.universa.Approvable)1 HashId (com.icodici.universa.HashId)1 Contract (com.icodici.universa.contract.Contract)1 Parcel (com.icodici.universa.contract.Parcel)1 ItemState (com.icodici.universa.node.ItemState)1 com.icodici.universa.node2 (com.icodici.universa.node2)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1