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"));
}
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");
}
}
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());
}
}
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;
}
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);
}
Aggregations