Search in sources :

Example 36 with PublicKey

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

the class SimpleRoleTest method serializeMany.

@Test
public void serializeMany() throws Exception {
    SimpleRole sr = new SimpleRole("tr1");
    keys.forEach(k -> sr.addKeyRecord(new KeyRecord(k.getPublicKey())));
    Binder serialized = DefaultBiMapper.serialize(sr);
    Role r1 = DefaultBiMapper.deserialize(serialized);
    assertEquals(sr, r1);
    Set<PublicKey> kk = r1.getKeys();
    keys.forEach(k -> assertTrue(kk.contains(k.getPublicKey())));
}
Also used : KeyRecord(com.icodici.universa.contract.KeyRecord) Binder(net.sergeych.tools.Binder) PublicKey(com.icodici.crypto.PublicKey) Test(org.junit.Test)

Example 37 with PublicKey

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

the class InnerContractsService method createFreshTU.

/**
 * Creates fresh contract in the first revision with transaction units.
 *<br><br>
 * This contract should be registered and then should be used as payment for other contract's processing.
 * TU contracts signs with special Universa keys and set as owner public keys from params.
 *<br><br>
 * @param amount is initial number of TU that will be have an owner
 * @param ownerKeys is public keys that will became an owner of TU
 * @param withTestTU if true TU will be created with test transaction units
 * @return sealed TU contract; should be registered in the Universa by simplified procedure.
 * @throws IOException with exceptions while contract preparing
 */
public static synchronized Contract createFreshTU(int amount, Set<PublicKey> ownerKeys, boolean withTestTU) throws IOException {
    PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(Config.tuKeyPath));
    Contract tu;
    if (withTestTU) {
        tu = Contract.fromDslFile(Config.testTUTemplatePath);
    } else {
        tu = Contract.fromDslFile(Config.tuTemplatePath);
    }
    SimpleRole ownerRole = new SimpleRole("owner");
    for (PublicKey k : ownerKeys) {
        KeyRecord kr = new KeyRecord(k);
        ownerRole.addKeyRecord(kr);
    }
    tu.registerRole(ownerRole);
    tu.createRole("owner", ownerRole);
    tu.getStateData().set("transaction_units", amount);
    if (withTestTU) {
        tu.getStateData().set("test_transaction_units", amount * 100);
    }
    tu.addSignerKey(manufacturePrivateKey);
    tu.seal();
    return tu;
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) SimpleRole(com.icodici.universa.contract.roles.SimpleRole) PublicKey(com.icodici.crypto.PublicKey)

Example 38 with PublicKey

use of com.icodici.crypto.PublicKey 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 39 with PublicKey

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

the class CLIMainTest method swapManyContractsViaTransactionAllGood.

// @Test
public void swapManyContractsViaTransactionAllGood() throws Exception {
    Set<PrivateKey> martyPrivateKeys = new HashSet<>();
    Set<PublicKey> martyPublicKeys = new HashSet<>();
    Set<PrivateKey> stepaPrivateKeys = new HashSet<>();
    Set<PublicKey> stepaPublicKeys = new HashSet<>();
    Contract delorean1 = Contract.fromDslFile(rootPath + "DeLoreanOwnership.yml");
    Contract delorean2 = Contract.fromDslFile(rootPath + "DeLoreanOwnership.yml");
    Contract delorean3 = Contract.fromDslFile(rootPath + "DeLoreanOwnership.yml");
    List<Contract> deloreans = new ArrayList<>();
    deloreans.add(delorean1);
    deloreans.add(delorean2);
    deloreans.add(delorean3);
    Contract lamborghini1 = Contract.fromDslFile(rootPath + "LamborghiniOwnership.yml");
    Contract lamborghini2 = Contract.fromDslFile(rootPath + "LamborghiniOwnership.yml");
    List<Contract> lamborghinis = new ArrayList<>();
    lamborghinis.add(lamborghini1);
    lamborghinis.add(lamborghini2);
    // ----- prepare contracts -----------
    martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_mcfly.private.unikey")));
    for (PrivateKey pk : martyPrivateKeys) {
        martyPublicKeys.add(pk.getPublicKey());
    }
    stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey")));
    for (PrivateKey pk : stepaPrivateKeys) {
        stepaPublicKeys.add(pk.getPublicKey());
    }
    PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey"));
    int i = 0;
    for (Contract d : deloreans) {
        i++;
        d.addSignerKey(manufacturePrivateKey);
        d.seal();
        CLIMain.saveContract(d, rootPath + "delorean" + i + ".unicon");
        callMain("--register", rootPath + "delorean" + i + ".unicon", "-wait", "5000");
    }
    i = 0;
    for (Contract l : lamborghinis) {
        i++;
        l.addSignerKey(manufacturePrivateKey);
        l.seal();
        CLIMain.saveContract(l, rootPath + "lamborghini" + i + ".unicon");
        callMain("--register", rootPath + "lamborghini" + i + ".unicon", "-wait", "5000");
    }
    // register swapped contracts using ContractsService
    System.out.println("--- register swapped contracts using ContractsService ---");
    Contract swapContract;
    // first Marty create transaction, add both contracts and swap owners, sign own new contract
    swapContract = ContractsService.startSwap(deloreans, lamborghinis, martyPrivateKeys, stepaPublicKeys);
    ContractsService.signPresentedSwap(swapContract, stepaPrivateKeys);
    ContractsService.finishSwap(swapContract, martyPrivateKeys);
    swapContract.check();
    swapContract.traceErrors();
    System.out.println("Transaction contract for swapping is valid: " + swapContract.isOk() + " num new contracts: " + swapContract.getNewItems().size());
    CLIMain.saveContract(swapContract, rootPath + "swapContract.unicon", true, true);
    callMain("--register", rootPath + "swapContract.unicon", "-wait", "5000");
    i = 0;
    for (Contract c : swapContract.getNew()) {
        i++;
        CLIMain.saveContract(c, rootPath + "new" + i + ".unicon");
        callMain("-e", rootPath + "new" + i + ".unicon", "-pretty");
    }
// checkSwapResultSuccess(swapContract, delorean, lamborghini, martyPublicKeys, stepaPublicKeys);
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) PublicKey(com.icodici.crypto.PublicKey) Contract(com.icodici.universa.contract.Contract)

Example 40 with PublicKey

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

the class ContractsService method startSwap.

/**
 * First step of swap procedure. Calls from swapper1 part.
 *<br><br>
 * Get lists of contracts.
 *<br><br>
 * Service create new revisions of existing contracts, change owners,
 * added transactional sections with references to each other with asks two signs of swappers
 * and sign contract that was own for calling part.
 *<br><br>
 * Swap procedure consist from three steps:<br>
 * (1) prepare contracts with creating transactional section on the first swapper site, sign only one contract;<br>
 * (2) sign contracts on the second swapper site;<br>
 * (3) sign lost contracts on the first swapper site and finishing swap.
 *<br><br>
 * @param contracts1 is list of own for calling part (swapper1 owned), existing or new revision of contract
 * @param contracts2 is list of foreign for calling part (swapper2 owned), existing or new revision contract
 * @param fromKeys is own for calling part (swapper1 keys) private keys
 * @param toKeys is foreign for calling part (swapper2 keys) public keys
 * @param createNewRevision if true - create new revision of given contracts. If false - use them as new revisions.
 * @return swap contract including new revisions of old contracts swapping between;
 * should be send to partner (swapper2) and he should go to step (2) of the swap procedure.
 */
public static synchronized Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision) {
    Set<PublicKey> fromPublicKeys = new HashSet<>();
    for (PrivateKey pk : fromKeys) {
        fromPublicKeys.add(pk.getPublicKey());
    }
    // first of all we creating main swap contract which will include new revisions of contract for swap
    // you can think about this contract as about transaction
    Contract swapContract = new Contract();
    Contract.Definition cd = swapContract.getDefinition();
    // by default, transactions expire in 30 days
    cd.setExpiresAt(swapContract.getCreatedAt().plusDays(30));
    SimpleRole issuerRole = new SimpleRole("issuer");
    for (PrivateKey k : fromKeys) {
        KeyRecord kr = new KeyRecord(k.getPublicKey());
        issuerRole.addKeyRecord(kr);
    }
    swapContract.registerRole(issuerRole);
    swapContract.createRole("owner", issuerRole);
    swapContract.createRole("creator", issuerRole);
    // now we will prepare new revisions of contracts
    // create new revisions of contracts and create transactional sections in it
    List<Contract> newContracts1 = new ArrayList<>();
    for (Contract c : contracts1) {
        Contract nc;
        if (createNewRevision) {
            nc = c.createRevision(fromKeys);
        } else {
            nc = c;
        }
        nc.createTransactionalSection();
        nc.getTransactional().setId(HashId.createRandom().toBase64String());
        newContracts1.add(nc);
    }
    List<Contract> newContracts2 = new ArrayList<>();
    for (Contract c : contracts2) {
        Contract nc;
        if (createNewRevision) {
            nc = c.createRevision();
        } else {
            nc = c;
        }
        nc.createTransactionalSection();
        nc.getTransactional().setId(HashId.createRandom().toBase64String());
        newContracts2.add(nc);
    }
    // prepare roles for references
    // it should new owners and old creators in new revisions of contracts
    SimpleRole ownerFrom = new SimpleRole("owner");
    SimpleRole creatorFrom = new SimpleRole("creator");
    for (PrivateKey k : fromKeys) {
        KeyRecord kr = new KeyRecord(k.getPublicKey());
        ownerFrom.addKeyRecord(kr);
        creatorFrom.addKeyRecord(kr);
    }
    SimpleRole ownerTo = new SimpleRole("owner");
    SimpleRole creatorTo = new SimpleRole("creator");
    for (PublicKey k : toKeys) {
        KeyRecord kr = new KeyRecord(k);
        ownerTo.addKeyRecord(kr);
        creatorTo.addKeyRecord(kr);
    }
    for (Contract nc1 : newContracts1) {
        for (Contract nc2 : newContracts2) {
            Reference reference = new Reference(nc1);
            reference.transactional_id = nc2.getTransactional().getId();
            reference.type = Reference.TYPE_TRANSACTIONAL;
            reference.required = true;
            reference.signed_by = new ArrayList<>();
            reference.signed_by.add(ownerFrom);
            reference.signed_by.add(creatorTo);
            nc1.getTransactional().addReference(reference);
        }
    }
    for (Contract nc2 : newContracts2) {
        for (Contract nc1 : newContracts1) {
            Reference reference = new Reference(nc2);
            reference.transactional_id = nc1.getTransactional().getId();
            reference.type = Reference.TYPE_TRANSACTIONAL;
            reference.required = true;
            reference.signed_by = new ArrayList<>();
            reference.signed_by.add(ownerTo);
            reference.signed_by.add(creatorFrom);
            nc2.getTransactional().addReference(reference);
        }
    }
    // swap owners in this contracts
    for (Contract nc : newContracts1) {
        nc.setOwnerKeys(toKeys);
        nc.seal();
    }
    for (Contract nc : newContracts2) {
        nc.setOwnerKeys(fromPublicKeys);
        nc.seal();
    }
    // finally on this step add created new revisions to main swap contract
    for (Contract nc : newContracts1) {
        swapContract.addNewItems(nc);
    }
    for (Contract nc : newContracts2) {
        swapContract.addNewItems(nc);
    }
    swapContract.seal();
    return swapContract;
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) SimpleRole(com.icodici.universa.contract.roles.SimpleRole) PublicKey(com.icodici.crypto.PublicKey)

Aggregations

PublicKey (com.icodici.crypto.PublicKey)84 PrivateKey (com.icodici.crypto.PrivateKey)75 Test (org.junit.Test)57 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)17 HashSet (java.util.HashSet)14 Binder (net.sergeych.tools.Binder)13 ListRole (com.icodici.universa.contract.roles.ListRole)11 Role (com.icodici.universa.contract.roles.Role)7 Contract (com.icodici.universa.contract.Contract)6 KeyAddress (com.icodici.crypto.KeyAddress)4 RoleLink (com.icodici.universa.contract.roles.RoleLink)4 KeyRecord (com.icodici.universa.contract.KeyRecord)3 ChangeOwnerPermission (com.icodici.universa.contract.permissions.ChangeOwnerPermission)3 Permission (com.icodici.universa.contract.permissions.Permission)3 TimeoutException (java.util.concurrent.TimeoutException)3 Decimal (com.icodici.universa.Decimal)2 ErrorRecord (com.icodici.universa.ErrorRecord)2 HashId (com.icodici.universa.HashId)2 Quantiser (com.icodici.universa.node2.Quantiser)2 List (java.util.List)2