Search in sources :

Example 51 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class StructureDescriptorTest method packSmallString.

@Test
public void packSmallString() throws Exception {
    StructureDescriptor d = new StructureDescriptor();
    d.addField("type", 1).addStringField("bb", 19);
    byte[] res = d.pack(Binder.fromKeysValues("type", 32, "bb", "Hello world!"));
    // Bytes.dump(res);
    assertEquals("20 0C 48 65 6C 6C 6F 20 77 6F 72 6C 64 21 00 00 00 00 00 00", Bytes.toHex(res));
    Binder r = d.unpack(res);
    assertEquals(32, r.getIntOrThrow("type"));
    assertEquals("Hello world!", r.getStringOrThrow("bb"));
}
Also used : Binder(net.sergeych.tools.Binder) Test(org.junit.Test)

Example 52 with Binder

use of net.sergeych.tools.Binder 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 53 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class CLIMain method exportFields.

/**
 * Export fields from specified contract.
 *
 * @param contract   - contract to export.
 * @param fieldNames - list of field names to export.
 * @param fileName   - name of file to export to.
 * @param format     - format of file to export to. Can be xml or json.
 */
private static void exportFields(Contract contract, List<String> fieldNames, String fileName, String format, Boolean jsonPretty) throws IOException {
    format = format.toLowerCase();
    report("export format: " + format);
    if (fileName == null) {
        if (testMode && testRootPath != null) {
            fileName = testRootPath + "Universa_fields_" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getCreatedAt());
        } else {
            fileName = "Universa_fields_" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getCreatedAt());
        }
    }
    Binder hm = new Binder();
    try {
        for (String fieldName : fieldNames) {
            report("export field: " + fieldName + " -> " + contract.get(fieldName));
            hm.put(fieldName, contract.get(fieldName));
        }
        Binder binder = DefaultBiMapper.getInstance().newSerializer().serialize(hm);
        byte[] data;
        if ("xml".equals(format)) {
            XStream xstream = new XStream(new DomDriver());
            xstream.registerConverter(new MapEntryConverter());
            xstream.alias("fields", Binder.class);
            data = xstream.toXML(binder).getBytes();
        } else if ("yaml".equals(format) || "yml".equals(format)) {
            Yaml yaml = new Yaml();
            data = yaml.dumpAsMap(binder).getBytes();
        } else {
            Gson gson;
            if (jsonPretty) {
                gson = new GsonBuilder().setPrettyPrinting().create();
            } else {
                gson = new GsonBuilder().create();
            }
            String jsonString = gson.toJson(binder);
            data = jsonString.getBytes();
        }
        try (FileOutputStream fs = new FileOutputStream(fileName)) {
            fs.write(data);
            fs.close();
        }
        report("export fields as " + format + " ok");
    } catch (IllegalArgumentException e) {
        report("export fields error: " + e.getMessage());
    }
}
Also used : Binder(net.sergeych.tools.Binder) DomDriver(com.thoughtworks.xstream.io.xml.DomDriver) GsonBuilder(com.google.gson.GsonBuilder) XStream(com.thoughtworks.xstream.XStream) Gson(com.google.gson.Gson) Yaml(org.yaml.snakeyaml.Yaml)

Example 54 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class CLIMain method importContract.

/**
 * Import contract from specified yaml, xml or json file.
 *
 * @param sourceName
 *
 * @return loaded and from loaded data created Contract.
 */
private static Contract importContract(String sourceName) throws IOException {
    ContractFileTypes fileType = getFileType(sourceName);
    Contract contract = null;
    File pathFile = new File(sourceName);
    if (pathFile.exists()) {
        try {
            Binder binder;
            FileReader reader = new FileReader(sourceName);
            if (fileType == ContractFileTypes.YAML) {
                Yaml yaml = new Yaml();
                binder = Binder.convertAllMapsToBinders(yaml.load(reader));
            } else if (fileType == ContractFileTypes.JSON) {
                Gson gson = new GsonBuilder().create();
                binder = Binder.convertAllMapsToBinders(gson.fromJson(reader, Binder.class));
            } else {
                XStream xstream = new XStream(new DomDriver());
                xstream.registerConverter(new MapEntryConverter());
                xstream.alias("contract", Binder.class);
                binder = Binder.convertAllMapsToBinders(xstream.fromXML(reader));
            }
            BiDeserializer bm = DefaultBiMapper.getInstance().newDeserializer();
            contract = new Contract();
            contract.deserialize(binder, bm);
            report(">>> imported contract: " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getCreatedAt()));
            report("import from " + fileType.toString().toLowerCase() + " ok");
        } catch (Exception e) {
            addError(Errors.FAILURE.name(), sourceName, e.getMessage());
        }
    } else {
        addError(Errors.NOT_FOUND.name(), sourceName, "Path " + sourceName + " does not exist");
    // usage("Path " + sourceName + " does not exist");
    }
    return contract;
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) XStream(com.thoughtworks.xstream.XStream) Gson(com.google.gson.Gson) BiDeserializer(net.sergeych.biserializer.BiDeserializer) Yaml(org.yaml.snakeyaml.Yaml) BackingStoreException(java.util.prefs.BackingStoreException) OptionException(joptsimple.OptionException) Binder(net.sergeych.tools.Binder) DomDriver(com.thoughtworks.xstream.io.xml.DomDriver) Contract(com.icodici.universa.contract.Contract)

Example 55 with Binder

use of net.sergeych.tools.Binder in project universa by UniversaBlockchain.

the class Contract method addSignatureToSeal.

/**
 * Add signature to sealed (before) contract. Do not deserializing or changing contract bytes,
 * but will change sealed and hashId.
 *
 * Useful if you got contracts from third-party (another computer) and need to sign it.
 * F.e. contracts that shoul be sign with two persons.
 *
 * @param privateKeys - key to sign contract will with
 */
public void addSignatureToSeal(Set<PrivateKey> privateKeys) {
    if (sealedBinary == null)
        throw new IllegalStateException("failed to add signature: sealed binary does not exist");
    Binder data = Boss.unpack(sealedBinary);
    byte[] contractBytes = data.getBinaryOrThrow("data");
    List<byte[]> signatures = data.getListOrThrow("signatures");
    for (PrivateKey key : privateKeys) {
        byte[] signature = ExtendedSignature.sign(key, contractBytes);
        signatures.add(signature);
        data.put("signatures", signatures);
        ExtendedSignature es = ExtendedSignature.verify(key.getPublicKey(), signature, contractBytes);
        if (es != null) {
            sealedByKeys.put(key.getPublicKey(), es);
        }
    }
    setOwnBinary(data);
}
Also used : Binder(net.sergeych.tools.Binder)

Aggregations

Binder (net.sergeych.tools.Binder)136 Test (org.junit.Test)67 PrivateKey (com.icodici.crypto.PrivateKey)21 Contract (com.icodici.universa.contract.Contract)14 PublicKey (com.icodici.crypto.PublicKey)13 IOException (java.io.IOException)11 KeyRecord (com.icodici.universa.contract.KeyRecord)10 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)10 Yaml (org.yaml.snakeyaml.Yaml)9 Bytes (net.sergeych.utils.Bytes)8 Decimal (com.icodici.universa.Decimal)7 ListRole (com.icodici.universa.contract.roles.ListRole)6 NonNull (org.checkerframework.checker.nullness.qual.NonNull)5 Gson (com.google.gson.Gson)4 GsonBuilder (com.google.gson.GsonBuilder)4 XStream (com.thoughtworks.xstream.XStream)4 DomDriver (com.thoughtworks.xstream.io.xml.DomDriver)4 List (java.util.List)4 RoleLink (com.icodici.universa.contract.roles.RoleLink)3 ItemResult (com.icodici.universa.node.ItemResult)3