Search in sources :

Example 81 with Yaml

use of org.yaml.snakeyaml.Yaml in project universa by UniversaBlockchain.

the class Node2LocalNetworkTest method initTestSet.

private static void initTestSet(int posCons, int negCons) throws Exception {
    System.out.println("init test set... ");
    nodesMap_s = new HashMap<>();
    networks_s = new ArrayList<>();
    config_s = new Config();
    config_s.setPositiveConsensus(posCons);
    config_s.setNegativeConsensus(negCons);
    config_s.setResyncBreakConsensus(2);
    config_s.setTransactionUnitsIssuerKeyData(Bytes.fromHex("1E 08 1C 01 00 01 C4 00 01 B9 C7 CB 1B BA 3C 30 80 D0 8B 29 54 95 61 41 39 9E C6 BB 15 56 78 B8 72 DC 97 58 9F 83 8E A0 B7 98 9E BB A9 1D 45 A1 6F 27 2F 61 E0 26 78 D4 9D A9 C2 2F 29 CB B6 F7 9F 97 60 F3 03 ED 5C 58 27 27 63 3B D3 32 B5 82 6A FB 54 EA 26 14 E9 17 B6 4C 5D 60 F7 49 FB E3 2F 26 52 16 04 A6 5E 6E 78 D1 78 85 4D CD 7B 71 EB 2B FE 31 39 E9 E0 24 4F 58 3A 1D AE 1B DA 41 CA 8C 42 2B 19 35 4B 11 2E 45 02 AD AA A2 55 45 33 39 A9 FD D1 F3 1F FA FE 54 4C 2E EE F1 75 C9 B4 1A 27 5C E9 C0 42 4D 08 AD 3E A2 88 99 A3 A2 9F 70 9E 93 A3 DF 1C 75 E0 19 AB 1F E0 82 4D FF 24 DA 5D B4 22 A0 3C A7 79 61 41 FD B7 02 5C F9 74 6F 2C FE 9A DD 36 44 98 A2 37 67 15 28 E9 81 AC 40 CE EF 05 AA 9E 36 8F 56 DA 97 10 E4 10 6A 32 46 16 D0 3B 6F EF 80 41 F3 CC DA 14 74 D1 BF 63 AC 28 E0 F1 04 69 63 F7"));
    config_s.getKeysWhiteList().add(config_s.getTransactionUnitsIssuerKey());
    // config_s.setPollTime(Duration.ofMillis(2500));
    // config_s.setConsensusReceivedCheckTime(Duration.ofMillis(2500));
    // config_s.setResyncTime(Duration.ofMillis(2500));
    Properties properties = new Properties();
    File file = new File(CONFIG_2_PATH + "config/config.yaml");
    Yaml yaml = new Yaml();
    Binder settings = new Binder();
    if (file.exists())
        settings = Binder.from(yaml.load(new FileReader(file)));
    // properties.setProperty("database", settings.getStringOrThrow("database"));
    /* test loading onfig should be in other place
        NetConfig ncNet = new NetConfig(CONFIG_2_PATH+"config/nodes");
        List<NodeConsumer> netNodes = ncNet.toList();
        */
    nc_s = new NetConfig();
    for (int i = 0; i < NODES; i++) {
        int offset = 7100 + 10 * i;
        NodeInfo info = new NodeInfo(getNodeKey(i).getPublicKey(), i, "testnode_" + i, "localhost", offset + 3, offset, offset + 2);
        nc_s.addNode(info);
    }
    for (int i = 0; i < NODES; i++) {
        NodeInfo info = nc_s.getInfo(i);
        System.out.println("set up node " + info);
        TestLocalNetwork ln = new TestLocalNetwork(nc_s, info, getNodeKey(i));
        ln.setNodes(nodesMap_s);
        // ledger = new SqliteLedger("jdbc:sqlite:testledger" + "_t" + i);
        Ledger ledger = new PostgresLedger(PostgresLedgerTest.CONNECTION_STRING + "_t" + i, properties);
        Node n = new Node(config_s, info, ledger, ln);
        nodesMap_s.put(info, n);
        networks_s.add(ln);
        if (i == 0) {
            ledger_s = ledger;
            network_s = ln;
        }
    }
    node_s = nodesMap_s.values().iterator().next();
    nodes_s = new ArrayList<>();
    for (int i = 0; i < NODES; i++) {
        nodes_s.add(nodesMap_s.get(nc_s.getInfo(i)));
    }
// System.out.println("waiting for sanitation... ");
// for(Node n : nodes_s) {
// if(n.isSanitating())
// n.sanitationFinished.await();
// }
// System.out.println("sanitation finished!");
}
Also used : Yaml(org.yaml.snakeyaml.Yaml) Binder(net.sergeych.tools.Binder) FileReader(java.io.FileReader) File(java.io.File)

Example 82 with Yaml

use of org.yaml.snakeyaml.Yaml 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 83 with Yaml

use of org.yaml.snakeyaml.Yaml 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 84 with Yaml

use of org.yaml.snakeyaml.Yaml 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 85 with Yaml

use of org.yaml.snakeyaml.Yaml in project universa by UniversaBlockchain.

the class Main method loadNodeConfig.

private void loadNodeConfig() throws IOException, SQLException {
    Yaml yaml = new Yaml();
    configRoot = (String) options.valueOf("config");
    nodeKey = null;
    Binder settings = Binder.of(yaml.load(new FileInputStream(configRoot + "/config/config.yaml")));
    log("node settings: " + settings);
    String nodeKeyFileName = configRoot + "/tmp/" + settings.getStringOrThrow("node_name") + ".private.unikey";
    log(nodeKeyFileName);
    nodeKey = new PrivateKey(Do.read(nodeKeyFileName));
    myInfo = new NodeInfo(nodeKey.getPublicKey(), settings.getIntOrThrow("node_number"), settings.getStringOrThrow("node_name"), (String) settings.getListOrThrow("ip").get(0), settings.getStringOrThrow("public_host"), settings.getIntOrThrow("udp_server_port"), settings.getIntOrThrow("http_client_port"), settings.getIntOrThrow("http_server_port"));
    ledger = new PostgresLedger(settings.getStringOrThrow("database"));
    log("ledger constructed");
    log("key loaded: " + nodeKey.info());
    log("node local URL: " + myInfo.publicUrlString());
    log("node info: " + myInfo.toBinder());
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) PostgresLedger(com.icodici.universa.node.PostgresLedger) Yaml(org.yaml.snakeyaml.Yaml) FileInputStream(java.io.FileInputStream)

Aggregations

Yaml (org.yaml.snakeyaml.Yaml)276 Map (java.util.Map)104 HashMap (java.util.HashMap)85 IOException (java.io.IOException)58 FileInputStream (java.io.FileInputStream)49 InputStream (java.io.InputStream)49 File (java.io.File)43 DumperOptions (org.yaml.snakeyaml.DumperOptions)42 Constructor (org.yaml.snakeyaml.constructor.Constructor)30 Test (org.junit.Test)26 ArrayList (java.util.ArrayList)25 FileNotFoundException (java.io.FileNotFoundException)22 SafeConstructor (org.yaml.snakeyaml.constructor.SafeConstructor)22 List (java.util.List)21 Writer (java.io.Writer)18 Path (java.nio.file.Path)17 LinkedHashMap (java.util.LinkedHashMap)17 Reader (java.io.Reader)16 Properties (java.util.Properties)14 InputStreamReader (java.io.InputStreamReader)13