Search in sources :

Example 41 with Contract

use of com.icodici.universa.contract.Contract in project universa by UniversaBlockchain.

the class CLIMain method checkContract.

/**
 * Check contract for errors. Print errors if found.
 *
 * @param contract - contract to check.
 */
private static void checkContract(Contract contract) {
    // First, check the sealed state
    if (!contract.isOk()) {
        reporter.message("The capsule is not sealed properly:");
        contract.getErrors().forEach(e -> reporter.error(e.getError().toString(), e.getObjectName(), e.getMessage()));
    }
    Yaml yaml = new Yaml();
    if (reporter.isVerboseMode()) {
        report("api level:   " + contract.getApiLevel());
        report("contract id: " + contract.getId().toBase64String());
        report("issued:      " + contract.getIssuedAt());
        report("revision:    " + contract.getRevision());
        report("created:     " + contract.getCreatedAt());
        report("expires:     " + contract.getExpiresAt());
        System.out.println();
        Set<PublicKey> keys = contract.getSealedByKeys();
        contract.getRevoking().forEach(r -> {
            try {
                ClientNetwork n = getClientNetwork();
                System.out.println();
                report("revoking item exists: " + r.getId().toBase64String());
                report("\tstate: " + n.check(r.getId()));
                HashId origin = r.getOrigin();
                boolean m = origin.equals(contract.getOrigin());
                report("\tOrigin: " + origin);
                report("\t" + (m ? "matches main contract origin" : "does not match main contract origin"));
                if (r.canBeRevoked(keys)) {
                    report("\trevocation is allowed");
                } else
                    reporter.error(Errors.BAD_REVOKE.name(), r.getId().toString(), "revocation not allowed");
            } catch (Exception clientError) {
                clientError.printStackTrace();
            }
        });
        contract.getNewItems().forEach(n -> {
            System.out.println();
            report("New item exists:      " + n.getId().toBase64String());
            Contract nc = (Contract) n;
            boolean m = nc.getOrigin().equals(contract.getOrigin());
            report("\tOrigin: " + ((Contract) n).getOrigin());
            report("\t" + (m ? "matches main contract origin" : "does not match main contract origin"));
        });
        if (keys.size() > 0) {
            report("\nSignature contains " + keys.size() + " valid key(s):\n");
            keys.forEach(k -> {
                KeyInfo i = k.info();
                report("\t✔︎ " + i.getAlgorythm() + ":" + i.getKeyLength() * 8 + ":" + i.getBase64Tag());
            });
            report("\nWhich can play roles:\n");
            contract.getRoles().forEach((name, role) -> {
                String canPlay = role.isAllowedForKeys(keys) ? "✔" : "✘";
                report("\t" + canPlay + " " + role.getName());
            });
            report("\nAnd have permissions:\n");
            contract.getPermissions().values().forEach(perm -> {
                String canPlay = perm.isAllowedForKeys(keys) ? "✔" : "✘";
                report("\t" + canPlay + " " + perm.getName());
                Binder x = DefaultBiMapper.serialize(perm.getParams());
                BufferedReader br = new BufferedReader(new StringReader(yaml.dumpAsMap(x)));
                try {
                    for (String line; (line = br.readLine()) != null; ) {
                        report("\t    " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            reporter.newLine();
        }
    }
    Multimap<String, Permission> permissions = contract.getPermissions();
    Collection<Permission> sjs = permissions.get("split_join");
    if (sjs != null) {
        sjs.forEach(sj -> checkSj(contract, sj));
    }
    try {
        contract.check();
    } catch (Quantiser.QuantiserException e) {
        addError("QUANTIZER_COST_LIMIT", contract.toString(), e.getMessage());
    } catch (Exception e) {
        addError(Errors.FAILURE.name(), contract.toString(), e.getMessage());
    }
    addErrors(contract.getErrors());
    if (contract.getErrors().size() == 0) {
        report("Contract is valid");
    }
}
Also used : PublicKey(com.icodici.crypto.PublicKey) Quantiser(com.icodici.universa.node2.Quantiser) Yaml(org.yaml.snakeyaml.Yaml) BackingStoreException(java.util.prefs.BackingStoreException) OptionException(joptsimple.OptionException) Binder(net.sergeych.tools.Binder) KeyInfo(com.icodici.crypto.KeyInfo) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) Permission(com.icodici.universa.contract.permissions.Permission) Contract(com.icodici.universa.contract.Contract)

Example 42 with Contract

use of com.icodici.universa.contract.Contract in project universa by UniversaBlockchain.

the class CLIMain method doRegister.

private static void doRegister() throws IOException {
    List<String> sources = new ArrayList<String>((List) options.valuesOf("register"));
    String tuSource = (String) options.valueOf("tu");
    int tuAmount = (int) options.valueOf("amount");
    boolean tutest = options.has("tutest");
    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);
        Contract contract = loadContract(source);
        Contract tu = null;
        if (tuSource != null) {
            tu = loadContract(tuSource, true);
            report("load payment revision: " + tu.getState().getRevision() + " id: " + tu.getId());
        }
        Set<PrivateKey> tuKeys = new HashSet<>(keysMap().values());
        if (contract != null) {
            if (tu != null && tuKeys != null && tuKeys.size() > 0) {
                report("registering the paid contract " + contract.getId() + " from " + source + " for " + tuAmount + " TU");
                Parcel parcel = registerContract(contract, tu, tuAmount, tuKeys, tutest, (int) options.valueOf("wait"));
                if (parcel != null) {
                    report("save payment revision: " + parcel.getPaymentContract().getState().getRevision() + " id: " + parcel.getPaymentContract().getId());
                    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES };
                    Files.copy(Paths.get(tuSource), Paths.get(tuSource.replaceAll("(?i)\\.(unicon)$", "_rev" + tu.getRevision() + ".unicon")), copyOptions);
                    saveContract(parcel.getPaymentContract(), tuSource, true, false);
                }
            } else {
                report("registering the contract " + contract.getId().toBase64String() + " from " + source);
                registerContract(contract, (int) options.valueOf("wait"));
            }
        }
    }
    // print cost of processing if asked
    if (options.has("cost")) {
        doCost();
    } else {
        finish();
    }
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) Parcel(com.icodici.universa.contract.Parcel) Contract(com.icodici.universa.contract.Contract)

Example 43 with Contract

use of com.icodici.universa.contract.Contract in project universa by UniversaBlockchain.

the class CLIMain method checkBytesIsValidContract.

/**
 * Check bytes is contract. And if bytes is, check contract for errors. Print errors if found.
 *
 * @param data - data to check.
 *
 * @return true if bytes is Contract and Contract is valid.
 */
private static Boolean checkBytesIsValidContract(byte[] data) {
    try {
        Contract contract = new Contract(data);
        if (!contract.isOk()) {
            reporter.message("The capsule is not sealed");
            contract.getErrors().forEach(e -> reporter.error(e.getError().toString(), e.getObjectName(), e.getMessage()));
        }
        checkContract(contract);
    } catch (RuntimeException e) {
        addError(Errors.BAD_VALUE.name(), "byte[] data", e.getMessage());
        return false;
    } catch (Quantiser.QuantiserException e) {
        addError("QUANTIZER_COST_LIMIT", "", e.toString());
    } catch (IOException e) {
        addError(Errors.BAD_VALUE.name(), "byte[] data", e.getMessage());
        return false;
    }
    return true;
}
Also used : Quantiser(com.icodici.universa.node2.Quantiser) Contract(com.icodici.universa.contract.Contract)

Example 44 with Contract

use of com.icodici.universa.contract.Contract in project universa by UniversaBlockchain.

the class CLIMain method printWallets.

/**
 * Just print wallets info to console.
 *
 * @param wallets
 */
private static void printWallets(List<Wallet> wallets) {
    reporter.message("");
    List<Contract> foundContracts = new ArrayList<>();
    for (Wallet wallet : wallets) {
        foundContracts.addAll(wallet.getContracts());
        reporter.message("found wallet: " + wallet.toString());
        reporter.verbose("");
        HashMap<String, Integer> balance = new HashMap<String, Integer>();
        Integer numcoins;
        String currency;
        for (Contract contract : wallet.getContracts()) {
            try {
                numcoins = contract.getStateData().getIntOrThrow(AMOUNT_FIELD_NAME);
                currency = contract.getDefinition().getData().getOrThrow("currency_code");
                if (balance.containsKey(currency)) {
                    balance.replace(currency, balance.get(currency) + numcoins);
                } else {
                    balance.put(currency, numcoins);
                }
                reporter.verbose("found coins: " + contract.getDefinition().getData().getOrThrow("name") + " -> " + numcoins + " (" + currency + ") ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        reporter.verbose("");
        reporter.message("total in the wallet: ");
        for (String c : balance.keySet()) {
            reporter.message(balance.get(c) + " (" + c + ") ");
        }
    }
}
Also used : Wallet(com.icodici.universa.wallet.Wallet) Contract(com.icodici.universa.contract.Contract) BackingStoreException(java.util.prefs.BackingStoreException) OptionException(joptsimple.OptionException)

Example 45 with Contract

use of com.icodici.universa.contract.Contract in project universa by UniversaBlockchain.

the class CLIMain method doRevoke.

private static void doRevoke() throws IOException {
    List<String> sources = new ArrayList<String>((List) options.valuesOf("revoke"));
    String tuSource = (String) options.valueOf("tu");
    int tuAmount = (int) options.valueOf("amount");
    boolean tutest = options.has("tutest");
    List<String> nonOptions = new ArrayList<String>((List) options.nonOptionArguments());
    for (String opt : nonOptions) {
        sources.addAll(asList(opt.split(",")));
    }
    cleanNonOptionalArguments(sources);
    report("doRevoke");
    for (int s = 0; s < sources.size(); s++) {
        String source = sources.get(s);
        Contract contract = loadContract(source);
        report("doRevoke " + contract);
        Contract tu = null;
        if (tuSource != null) {
            tu = loadContract(tuSource, true);
            report("load payment revision: " + tu.getState().getRevision() + " id: " + tu.getId());
        }
        Set<PrivateKey> tuKeys = new HashSet<>(keysMap().values());
        report("tuKeys num: " + tuKeys.size());
        if (contract != null) {
            if (tu != null && tuKeys != null && tuKeys.size() > 0) {
                report("registering the paid contract " + contract.getId() + " from " + source + " for " + tuAmount + " TU");
                Parcel parcel = null;
                try {
                    if (contract.check()) {
                        report("revoke contract from " + source);
                        parcel = revokeContract(contract, tu, tuAmount, tuKeys, tutest, keysMap().values().toArray(new PrivateKey[0]));
                    } else {
                        addErrors(contract.getErrors());
                    }
                } catch (Quantiser.QuantiserException e) {
                    addError("QUANTIZER_COST_LIMIT", contract.toString(), e.getMessage());
                }
                if (parcel != null) {
                    report("save payment revision: " + parcel.getPaymentContract().getState().getRevision() + " id: " + parcel.getPaymentContract().getId());
                    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES };
                    Files.copy(Paths.get(tuSource), Paths.get(tuSource.replaceAll("(?i)\\.(unicon)$", "_rev" + tu.getRevision() + ".unicon")), copyOptions);
                    saveContract(parcel.getPaymentContract(), tuSource, true, false);
                }
            } else {
                try {
                    if (contract.check()) {
                        report("revoke contract from " + source);
                        revokeContract(contract, keysMap().values().toArray(new PrivateKey[0]));
                    } else {
                        addErrors(contract.getErrors());
                    }
                } catch (Quantiser.QuantiserException e) {
                    addError("QUANTIZER_COST_LIMIT", contract.toString(), e.getMessage());
                }
            }
        }
    }
    finish();
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) Parcel(com.icodici.universa.contract.Parcel) Quantiser(com.icodici.universa.node2.Quantiser) Contract(com.icodici.universa.contract.Contract)

Aggregations

Contract (com.icodici.universa.contract.Contract)131 Test (org.junit.Test)67 Decimal (com.icodici.universa.Decimal)31 PrivateKey (com.icodici.crypto.PrivateKey)24 File (java.io.File)16 AsyncEvent (net.sergeych.tools.AsyncEvent)16 TimeoutException (java.util.concurrent.TimeoutException)14 Binder (net.sergeych.tools.Binder)14 KeyRecord (com.icodici.universa.contract.KeyRecord)13 HashSet (java.util.HashSet)9 Parcel (com.icodici.universa.contract.Parcel)8 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)7 Quantiser (com.icodici.universa.node2.Quantiser)7 PublicKey (com.icodici.crypto.PublicKey)6 TransactionPack (com.icodici.universa.contract.TransactionPack)6 IOException (java.io.IOException)6 BackingStoreException (java.util.prefs.BackingStoreException)6 OptionException (joptsimple.OptionException)6 HashId (com.icodici.universa.HashId)5 Arrays.asList (java.util.Arrays.asList)5